mozjs_sys 0.67.1

System crate for the Mozilla SpiderMonkey JavaScript engine.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
/* -*- 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 "jit/BaselineIC.h"

#include "mozilla/Casting.h"
#include "mozilla/DebugOnly.h"
#include "mozilla/IntegerPrintfMacros.h"
#include "mozilla/Sprintf.h"
#include "mozilla/TemplateLib.h"

#include "jsfriendapi.h"
#include "jslibmath.h"
#include "jstypes.h"

#include "builtin/Eval.h"
#include "gc/Policy.h"
#include "jit/BaselineCacheIRCompiler.h"
#include "jit/BaselineDebugModeOSR.h"
#include "jit/BaselineJIT.h"
#include "jit/InlinableNatives.h"
#include "jit/JitSpewer.h"
#include "jit/Linker.h"
#include "jit/Lowering.h"
#ifdef JS_ION_PERF
#  include "jit/PerfSpewer.h"
#endif
#include "jit/SharedICHelpers.h"
#include "jit/VMFunctions.h"
#include "js/Conversions.h"
#include "js/GCVector.h"
#include "vm/JSFunction.h"
#include "vm/Opcodes.h"
#include "vm/SelfHosting.h"
#include "vm/TypedArrayObject.h"

#include "builtin/Boolean-inl.h"

#include "jit/JitFrames-inl.h"
#include "jit/MacroAssembler-inl.h"
#include "jit/shared/Lowering-shared-inl.h"
#include "jit/SharedICHelpers-inl.h"
#include "jit/VMFunctionList-inl.h"
#include "vm/EnvironmentObject-inl.h"
#include "vm/Interpreter-inl.h"
#include "vm/JSScript-inl.h"
#include "vm/StringObject-inl.h"
#include "vm/UnboxedObject-inl.h"

using mozilla::DebugOnly;

namespace js {
namespace jit {

#ifdef JS_JITSPEW
void FallbackICSpew(JSContext* cx, ICFallbackStub* stub, const char* fmt, ...) {
  if (JitSpewEnabled(JitSpew_BaselineICFallback)) {
    RootedScript script(cx, GetTopJitJSScript(cx));
    jsbytecode* pc = stub->icEntry()->pc(script);

    char fmtbuf[100];
    va_list args;
    va_start(args, fmt);
    (void)VsprintfLiteral(fmtbuf, fmt, args);
    va_end(args);

    JitSpew(
        JitSpew_BaselineICFallback,
        "Fallback hit for (%s:%u:%u) (pc=%zu,line=%d,uses=%d,stubs=%zu): %s",
        script->filename(), script->lineno(), script->column(),
        script->pcToOffset(pc), PCToLineNumber(script, pc),
        script->getWarmUpCount(), stub->numOptimizedStubs(), fmtbuf);
  }
}

void TypeFallbackICSpew(JSContext* cx, ICTypeMonitor_Fallback* stub,
                        const char* fmt, ...) {
  if (JitSpewEnabled(JitSpew_BaselineICFallback)) {
    RootedScript script(cx, GetTopJitJSScript(cx));
    jsbytecode* pc = stub->icEntry()->pc(script);

    char fmtbuf[100];
    va_list args;
    va_start(args, fmt);
    (void)VsprintfLiteral(fmtbuf, fmt, args);
    va_end(args);

    JitSpew(JitSpew_BaselineICFallback,
            "Type monitor fallback hit for (%s:%u:%u) "
            "(pc=%zu,line=%d,uses=%d,stubs=%d): %s",
            script->filename(), script->lineno(), script->column(),
            script->pcToOffset(pc), PCToLineNumber(script, pc),
            script->getWarmUpCount(), (int)stub->numOptimizedMonitorStubs(),
            fmtbuf);
  }
}
#endif  // JS_JITSPEW

ICFallbackStub* ICEntry::fallbackStub() const {
  return firstStub()->getChainFallback();
}

void ICEntry::trace(JSTracer* trc) {
  for (ICStub* stub = firstStub(); stub; stub = stub->next()) {
    stub->trace(trc);
  }
}

/* static */
UniquePtr<ICScript> ICScript::create(JSContext* cx, JSScript* script) {
  MOZ_ASSERT(cx->realm()->jitRealm());
  MOZ_ASSERT(jit::IsBaselineEnabled(cx));

  FallbackICStubSpace stubSpace;
  js::Vector<ICEntry, 16, SystemAllocPolicy> icEntries;

  auto addIC = [cx, &icEntries, script](jsbytecode* pc, ICStub* stub) {
    if (!stub) {
      MOZ_ASSERT(cx->isExceptionPending());
      return false;
    }
    uint32_t offset = pc ? script->pcToOffset(pc) : ICEntry::NonOpPCOffset;
    if (!icEntries.emplaceBack(stub, offset)) {
      ReportOutOfMemory(cx);
      return false;
    }
    return true;
  };

  // Add ICEntries and fallback stubs for this/argument type checks.
  // Note: we pass a nullptr pc to indicate this is a non-op IC.
  // See ICEntry::NonOpPCOffset.
  if (JSFunction* fun = script->functionNonDelazifying()) {
    ICTypeMonitor_Fallback::Compiler compiler(cx, uint32_t(0));
    if (!addIC(nullptr, compiler.getStub(&stubSpace))) {
      return nullptr;
    }

    for (size_t i = 0; i < fun->nargs(); i++) {
      ICTypeMonitor_Fallback::Compiler compiler(cx, i + 1);
      if (!addIC(nullptr, compiler.getStub(&stubSpace))) {
        return nullptr;
      }
    }
  }

  jsbytecode const* pcEnd = script->codeEnd();

  // Add ICEntries and fallback stubs for JOF_IC bytecode ops.
  for (jsbytecode* pc = script->code(); pc < pcEnd; pc = GetNextPc(pc)) {
    JSOp op = JSOp(*pc);

    // Assert the frontend stored the correct IC index in jump target ops.
    MOZ_ASSERT_IF(BytecodeIsJumpTarget(op),
                  GET_ICINDEX(pc) == icEntries.length());

    if (!BytecodeOpHasIC(op)) {
      continue;
    }

    switch (op) {
      case JSOP_NOT:
      case JSOP_AND:
      case JSOP_OR:
      case JSOP_IFEQ:
      case JSOP_IFNE: {
        ICToBool_Fallback::Compiler stubCompiler(cx);
        if (!addIC(pc, stubCompiler.getStub(&stubSpace))) {
          return nullptr;
        }
        break;
      }
      case JSOP_BITNOT:
      case JSOP_NEG:
      case JSOP_INC:
      case JSOP_DEC: {
        ICUnaryArith_Fallback::Compiler stubCompiler(cx);
        if (!addIC(pc, stubCompiler.getStub(&stubSpace))) {
          return nullptr;
        }
        break;
      }
      case JSOP_BITOR:
      case JSOP_BITXOR:
      case JSOP_BITAND:
      case JSOP_LSH:
      case JSOP_RSH:
      case JSOP_URSH:
      case JSOP_ADD:
      case JSOP_SUB:
      case JSOP_MUL:
      case JSOP_DIV:
      case JSOP_MOD:
      case JSOP_POW: {
        ICBinaryArith_Fallback::Compiler stubCompiler(cx);
        if (!addIC(pc, stubCompiler.getStub(&stubSpace))) {
          return nullptr;
        }
        break;
      }
      case JSOP_EQ:
      case JSOP_NE:
      case JSOP_LT:
      case JSOP_LE:
      case JSOP_GT:
      case JSOP_GE:
      case JSOP_STRICTEQ:
      case JSOP_STRICTNE: {
        ICCompare_Fallback::Compiler stubCompiler(cx);
        if (!addIC(pc, stubCompiler.getStub(&stubSpace))) {
          return nullptr;
        }
        break;
      }
      case JSOP_LOOPENTRY: {
        ICWarmUpCounter_Fallback::Compiler stubCompiler(cx);
        if (!addIC(pc, stubCompiler.getStub(&stubSpace))) {
          return nullptr;
        }
        break;
      }
      case JSOP_NEWARRAY: {
        ObjectGroup* group =
            ObjectGroup::allocationSiteGroup(cx, script, pc, JSProto_Array);
        if (!group) {
          return nullptr;
        }
        ICNewArray_Fallback::Compiler stubCompiler(cx, group);
        if (!addIC(pc, stubCompiler.getStub(&stubSpace))) {
          return nullptr;
        }
        break;
      }
      case JSOP_NEWOBJECT:
      case JSOP_NEWINIT: {
        ICNewObject_Fallback::Compiler stubCompiler(cx);
        if (!addIC(pc, stubCompiler.getStub(&stubSpace))) {
          return nullptr;
        }
        break;
      }
      case JSOP_INITELEM:
      case JSOP_INITHIDDENELEM:
      case JSOP_INITELEM_ARRAY:
      case JSOP_INITELEM_INC:
      case JSOP_SETELEM:
      case JSOP_STRICTSETELEM: {
        ICSetElem_Fallback::Compiler stubCompiler(cx);
        if (!addIC(pc, stubCompiler.getStub(&stubSpace))) {
          return nullptr;
        }
        break;
      }
      case JSOP_INITPROP:
      case JSOP_INITLOCKEDPROP:
      case JSOP_INITHIDDENPROP:
      case JSOP_INITGLEXICAL:
      case JSOP_SETPROP:
      case JSOP_STRICTSETPROP:
      case JSOP_SETNAME:
      case JSOP_STRICTSETNAME:
      case JSOP_SETGNAME:
      case JSOP_STRICTSETGNAME: {
        ICSetProp_Fallback::Compiler compiler(cx);
        if (!addIC(pc, compiler.getStub(&stubSpace))) {
          return nullptr;
        }
        break;
      }
      case JSOP_GETPROP:
      case JSOP_CALLPROP:
      case JSOP_LENGTH:
      case JSOP_GETPROP_SUPER:
      case JSOP_GETBOUNDNAME: {
        bool hasReceiver = (op == JSOP_GETPROP_SUPER);
        ICGetProp_Fallback::Compiler compiler(cx, hasReceiver);
        if (!addIC(pc, compiler.getStub(&stubSpace))) {
          return nullptr;
        }
        break;
      }
      case JSOP_GETELEM:
      case JSOP_CALLELEM:
      case JSOP_GETELEM_SUPER: {
        bool hasReceiver = (op == JSOP_GETELEM_SUPER);
        ICGetElem_Fallback::Compiler stubCompiler(cx, hasReceiver);
        if (!addIC(pc, stubCompiler.getStub(&stubSpace))) {
          return nullptr;
        }
        break;
      }
      case JSOP_IN: {
        ICIn_Fallback::Compiler stubCompiler(cx);
        if (!addIC(pc, stubCompiler.getStub(&stubSpace))) {
          return nullptr;
        }
        break;
      }
      case JSOP_HASOWN: {
        ICHasOwn_Fallback::Compiler stubCompiler(cx);
        if (!addIC(pc, stubCompiler.getStub(&stubSpace))) {
          return nullptr;
        }
        break;
      }
      case JSOP_GETNAME:
      case JSOP_GETGNAME: {
        ICGetName_Fallback::Compiler stubCompiler(cx);
        if (!addIC(pc, stubCompiler.getStub(&stubSpace))) {
          return nullptr;
        }
        break;
      }
      case JSOP_BINDNAME:
      case JSOP_BINDGNAME: {
        ICBindName_Fallback::Compiler stubCompiler(cx);
        if (!addIC(pc, stubCompiler.getStub(&stubSpace))) {
          return nullptr;
        }
        break;
      }
      case JSOP_GETALIASEDVAR:
      case JSOP_GETIMPORT: {
        ICTypeMonitor_Fallback::Compiler compiler(cx, nullptr);
        if (!addIC(pc, compiler.getStub(&stubSpace))) {
          return nullptr;
        }
        break;
      }
      case JSOP_GETINTRINSIC: {
        ICGetIntrinsic_Fallback::Compiler stubCompiler(cx);
        if (!addIC(pc, stubCompiler.getStub(&stubSpace))) {
          return nullptr;
        }
        break;
      }
      case JSOP_CALL:
      case JSOP_CALL_IGNORES_RV:
      case JSOP_CALLITER:
      case JSOP_SUPERCALL:
      case JSOP_FUNCALL:
      case JSOP_FUNAPPLY:
      case JSOP_NEW:
      case JSOP_EVAL:
      case JSOP_STRICTEVAL: {
        bool construct = JSOp(*pc) == JSOP_NEW || JSOp(*pc) == JSOP_SUPERCALL;
        ICCall_Fallback::Compiler stubCompiler(cx,
                                               /* isConstructing = */ construct,
                                               /* isSpread = */ false);
        if (!addIC(pc, stubCompiler.getStub(&stubSpace))) {
          return nullptr;
        }
        break;
      }
      case JSOP_SPREADCALL:
      case JSOP_SPREADSUPERCALL:
      case JSOP_SPREADNEW:
      case JSOP_SPREADEVAL:
      case JSOP_STRICTSPREADEVAL: {
        bool construct =
            JSOp(*pc) == JSOP_SPREADNEW || JSOp(*pc) == JSOP_SPREADSUPERCALL;
        ICCall_Fallback::Compiler stubCompiler(cx,
                                               /* isConstructing = */ construct,
                                               /* isSpread = */ true);
        if (!addIC(pc, stubCompiler.getStub(&stubSpace))) {
          return nullptr;
        }
        break;
      }
      case JSOP_INSTANCEOF: {
        ICInstanceOf_Fallback::Compiler stubCompiler(cx);
        if (!addIC(pc, stubCompiler.getStub(&stubSpace))) {
          return nullptr;
        }
        break;
      }
      case JSOP_TYPEOF:
      case JSOP_TYPEOFEXPR: {
        ICTypeOf_Fallback::Compiler stubCompiler(cx);
        if (!addIC(pc, stubCompiler.getStub(&stubSpace))) {
          return nullptr;
        }
        break;
      }
      case JSOP_ITER: {
        ICGetIterator_Fallback::Compiler compiler(cx);
        if (!addIC(pc, compiler.getStub(&stubSpace))) {
          return nullptr;
        }
        break;
      }
      case JSOP_REST: {
        ArrayObject* templateObject = ObjectGroup::newArrayObject(
            cx, nullptr, 0, TenuredObject,
            ObjectGroup::NewArrayKind::UnknownIndex);
        if (!templateObject) {
          return nullptr;
        }
        ICRest_Fallback::Compiler compiler(cx, templateObject);
        if (!addIC(pc, compiler.getStub(&stubSpace))) {
          return nullptr;
        }
        break;
      }
      default:
        MOZ_CRASH("JOF_IC op not handled");
    }
  }

  UniquePtr<ICScript> icScript(
      script->zone()->pod_malloc_with_extra<ICScript, ICEntry>(
          icEntries.length()));
  if (!icScript) {
    ReportOutOfMemory(cx);
    return nullptr;
  }
  new (icScript.get()) ICScript(icEntries.length());

  // Adopt fallback stubs into the ICScript.
  icScript->fallbackStubSpace_.adoptFrom(&stubSpace);

  if (icEntries.length() > 0) {
    icScript->initICEntries(script, &icEntries[0]);
  }

  return icScript;
}

ICStubConstIterator& ICStubConstIterator::operator++() {
  MOZ_ASSERT(currentStub_ != nullptr);
  currentStub_ = currentStub_->next();
  return *this;
}

ICStubIterator::ICStubIterator(ICFallbackStub* fallbackStub, bool end)
    : icEntry_(fallbackStub->icEntry()),
      fallbackStub_(fallbackStub),
      previousStub_(nullptr),
      currentStub_(end ? fallbackStub : icEntry_->firstStub()),
      unlinked_(false) {}

ICStubIterator& ICStubIterator::operator++() {
  MOZ_ASSERT(currentStub_->next() != nullptr);
  if (!unlinked_) {
    previousStub_ = currentStub_;
  }
  currentStub_ = currentStub_->next();
  unlinked_ = false;
  return *this;
}

void ICStubIterator::unlink(JSContext* cx) {
  MOZ_ASSERT(currentStub_->next() != nullptr);
  MOZ_ASSERT(currentStub_ != fallbackStub_);
  MOZ_ASSERT(!unlinked_);

  fallbackStub_->unlinkStub(cx->zone(), previousStub_, currentStub_);

  // Mark the current iterator position as unlinked, so operator++ works
  // properly.
  unlinked_ = true;
}

/* static */
bool ICStub::NonCacheIRStubMakesGCCalls(Kind kind) {
  MOZ_ASSERT(IsValidKind(kind));
  MOZ_ASSERT(!IsCacheIRKind(kind));

  switch (kind) {
    case Call_Fallback:
    case Call_Scripted:
    case Call_AnyScripted:
    case Call_Native:
    case Call_ClassHook:
    case Call_ScriptedApplyArray:
    case Call_ScriptedApplyArguments:
    case Call_ScriptedFunCall:
    case Call_ConstStringSplit:
    case WarmUpCounter_Fallback:
    // These three fallback stubs don't actually make non-tail calls,
    // but the fallback code for the bailout path needs to pop the stub frame
    // pushed during the bailout.
    case GetProp_Fallback:
    case SetProp_Fallback:
    case GetElem_Fallback:
      return true;
    default:
      return false;
  }
}

bool ICStub::makesGCCalls() const {
  switch (kind()) {
    case CacheIR_Regular:
      return toCacheIR_Regular()->stubInfo()->makesGCCalls();
    case CacheIR_Monitored:
      return toCacheIR_Monitored()->stubInfo()->makesGCCalls();
    case CacheIR_Updated:
      return toCacheIR_Updated()->stubInfo()->makesGCCalls();
    default:
      return NonCacheIRStubMakesGCCalls(kind());
  }
}

void ICStub::traceCode(JSTracer* trc, const char* name) {
  JitCode* stubJitCode = jitCode();
  TraceManuallyBarrieredEdge(trc, &stubJitCode, name);
}

void ICStub::updateCode(JitCode* code) {
  // Write barrier on the old code.
  JitCode::writeBarrierPre(jitCode());
  stubCode_ = code->raw();
}

/* static */
void ICStub::trace(JSTracer* trc) {
  traceCode(trc, "shared-stub-jitcode");

  // If the stub is a monitored fallback stub, then trace the monitor ICs
  // hanging off of that stub.  We don't need to worry about the regular
  // monitored stubs, because the regular monitored stubs will always have a
  // monitored fallback stub that references the same stub chain.
  if (isMonitoredFallback()) {
    ICTypeMonitor_Fallback* lastMonStub =
        toMonitoredFallbackStub()->maybeFallbackMonitorStub();
    if (lastMonStub) {
      for (ICStubConstIterator iter(lastMonStub->firstMonitorStub());
           !iter.atEnd(); iter++) {
        MOZ_ASSERT_IF(iter->next() == nullptr, *iter == lastMonStub);
        iter->trace(trc);
      }
    }
  }

  if (isUpdated()) {
    for (ICStubConstIterator iter(toUpdatedStub()->firstUpdateStub());
         !iter.atEnd(); iter++) {
      MOZ_ASSERT_IF(iter->next() == nullptr, iter->isTypeUpdate_Fallback());
      iter->trace(trc);
    }
  }

  switch (kind()) {
    case ICStub::Call_Scripted: {
      ICCall_Scripted* callStub = toCall_Scripted();
      TraceEdge(trc, &callStub->callee(), "baseline-callscripted-callee");
      TraceNullableEdge(trc, &callStub->templateObject(),
                        "baseline-callscripted-template");
      break;
    }
    case ICStub::Call_Native: {
      ICCall_Native* callStub = toCall_Native();
      TraceEdge(trc, &callStub->callee(), "baseline-callnative-callee");
      TraceNullableEdge(trc, &callStub->templateObject(),
                        "baseline-callnative-template");
      break;
    }
    case ICStub::Call_ClassHook: {
      ICCall_ClassHook* callStub = toCall_ClassHook();
      TraceNullableEdge(trc, &callStub->templateObject(),
                        "baseline-callclasshook-template");
      break;
    }
    case ICStub::Call_ConstStringSplit: {
      ICCall_ConstStringSplit* callStub = toCall_ConstStringSplit();
      TraceEdge(trc, &callStub->templateObject(),
                "baseline-callstringsplit-template");
      TraceEdge(trc, &callStub->expectedSep(), "baseline-callstringsplit-sep");
      TraceEdge(trc, &callStub->expectedStr(), "baseline-callstringsplit-str");
      break;
    }
    case ICStub::TypeMonitor_SingleObject: {
      ICTypeMonitor_SingleObject* monitorStub = toTypeMonitor_SingleObject();
      TraceEdge(trc, &monitorStub->object(), "baseline-monitor-singleton");
      break;
    }
    case ICStub::TypeMonitor_ObjectGroup: {
      ICTypeMonitor_ObjectGroup* monitorStub = toTypeMonitor_ObjectGroup();
      TraceEdge(trc, &monitorStub->group(), "baseline-monitor-group");
      break;
    }
    case ICStub::TypeUpdate_SingleObject: {
      ICTypeUpdate_SingleObject* updateStub = toTypeUpdate_SingleObject();
      TraceEdge(trc, &updateStub->object(), "baseline-update-singleton");
      break;
    }
    case ICStub::TypeUpdate_ObjectGroup: {
      ICTypeUpdate_ObjectGroup* updateStub = toTypeUpdate_ObjectGroup();
      TraceEdge(trc, &updateStub->group(), "baseline-update-group");
      break;
    }
    case ICStub::NewArray_Fallback: {
      ICNewArray_Fallback* stub = toNewArray_Fallback();
      TraceNullableEdge(trc, &stub->templateObject(),
                        "baseline-newarray-template");
      TraceEdge(trc, &stub->templateGroup(),
                "baseline-newarray-template-group");
      break;
    }
    case ICStub::NewObject_Fallback: {
      ICNewObject_Fallback* stub = toNewObject_Fallback();
      TraceNullableEdge(trc, &stub->templateObject(),
                        "baseline-newobject-template");
      break;
    }
    case ICStub::Rest_Fallback: {
      ICRest_Fallback* stub = toRest_Fallback();
      TraceEdge(trc, &stub->templateObject(), "baseline-rest-template");
      break;
    }
    case ICStub::CacheIR_Regular:
      TraceCacheIRStub(trc, this, toCacheIR_Regular()->stubInfo());
      break;
    case ICStub::CacheIR_Monitored:
      TraceCacheIRStub(trc, this, toCacheIR_Monitored()->stubInfo());
      break;
    case ICStub::CacheIR_Updated: {
      ICCacheIR_Updated* stub = toCacheIR_Updated();
      TraceNullableEdge(trc, &stub->updateStubGroup(),
                        "baseline-update-stub-group");
      TraceEdge(trc, &stub->updateStubId(), "baseline-update-stub-id");
      TraceCacheIRStub(trc, this, stub->stubInfo());
      break;
    }
    default:
      break;
  }
}

// This helper handles ICState updates/transitions while attaching CacheIR
// stubs.
template <typename IRGenerator, typename... Args>
static void TryAttachStub(const char* name, JSContext* cx, BaselineFrame* frame,
                          ICFallbackStub* stub, BaselineCacheIRStubKind kind,
                          Args&&... args) {
  if (stub->state().maybeTransition()) {
    stub->discardStubs(cx);
  }

  if (stub->state().canAttachStub()) {
    RootedScript script(cx, frame->script());
    jsbytecode* pc = stub->icEntry()->pc(script);

    bool attached = false;
    IRGenerator gen(cx, script, pc, stub->state().mode(),
                    std::forward<Args>(args)...);
    if (gen.tryAttachStub()) {
      ICStub* newStub = AttachBaselineCacheIRStub(
          cx, gen.writerRef(), gen.cacheKind(), kind, script, stub, &attached);
      if (newStub) {
        JitSpew(JitSpew_BaselineIC, "  %s %s CacheIR stub",
                attached ? "Attached" : "Failed to attach", name);
      }
    }
    if (!attached) {
      stub->state().trackNotAttached();
    }
  }
}

//
// WarmUpCounter_Fallback
//

/* clang-format off */
// The following data is kept in a temporary heap-allocated buffer, stored in
// JitRuntime (high memory addresses at top, low at bottom):
//
//     +----->+=================================+  --      <---- High Address
//     |      |                                 |   |
//     |      |     ...BaselineFrame...         |   |-- Copy of BaselineFrame + stack values
//     |      |                                 |   |
//     |      +---------------------------------+   |
//     |      |                                 |   |
//     |      |     ...Locals/Stack...          |   |
//     |      |                                 |   |
//     |      +=================================+  --
//     |      |     Padding(Maybe Empty)        |
//     |      +=================================+  --
//     +------|-- baselineFrame                 |   |-- IonOsrTempData
//            |   jitcode                       |   |
//            +=================================+  --      <---- Low Address
//
// A pointer to the IonOsrTempData is returned.
/* clang-format on */

struct IonOsrTempData {
  void* jitcode;
  uint8_t* baselineFrame;
};

static IonOsrTempData* PrepareOsrTempData(JSContext* cx, BaselineFrame* frame,
                                          void* jitcode) {
  size_t numLocalsAndStackVals = frame->numValueSlots();

  // Calculate the amount of space to allocate:
  //      BaselineFrame space:
  //          (sizeof(Value) * (numLocals + numStackVals))
  //        + sizeof(BaselineFrame)
  //
  //      IonOsrTempData space:
  //          sizeof(IonOsrTempData)

  size_t frameSpace =
      sizeof(BaselineFrame) + sizeof(Value) * numLocalsAndStackVals;
  size_t ionOsrTempDataSpace = sizeof(IonOsrTempData);

  size_t totalSpace = AlignBytes(frameSpace, sizeof(Value)) +
                      AlignBytes(ionOsrTempDataSpace, sizeof(Value));

  IonOsrTempData* info = (IonOsrTempData*)cx->allocateOsrTempData(totalSpace);
  if (!info) {
    ReportOutOfMemory(cx);
    return nullptr;
  }

  memset(info, 0, totalSpace);

  info->jitcode = jitcode;

  // Copy the BaselineFrame + local/stack Values to the buffer. Arguments and
  // |this| are not copied but left on the stack: the Baseline and Ion frame
  // share the same frame prefix and Ion won't clobber these values. Note
  // that info->baselineFrame will point to the *end* of the frame data, like
  // the frame pointer register in baseline frames.
  uint8_t* frameStart =
      (uint8_t*)info + AlignBytes(ionOsrTempDataSpace, sizeof(Value));
  info->baselineFrame = frameStart + frameSpace;

  memcpy(frameStart, (uint8_t*)frame - numLocalsAndStackVals * sizeof(Value),
         frameSpace);

  JitSpew(JitSpew_BaselineOSR, "Allocated IonOsrTempData at %p", (void*)info);
  JitSpew(JitSpew_BaselineOSR, "Jitcode is %p", info->jitcode);

  // All done.
  return info;
}

bool DoWarmUpCounterFallbackOSR(JSContext* cx, BaselineFrame* frame,
                                ICWarmUpCounter_Fallback* stub,
                                IonOsrTempData** infoPtr) {
  MOZ_ASSERT(infoPtr);
  *infoPtr = nullptr;

  RootedScript script(cx, frame->script());
  jsbytecode* pc = stub->icEntry()->pc(script);
  MOZ_ASSERT(JSOp(*pc) == JSOP_LOOPENTRY);

  FallbackICSpew(cx, stub, "WarmUpCounter(%d)", int(script->pcToOffset(pc)));

  if (!IonCompileScriptForBaseline(cx, frame, pc)) {
    return false;
  }

  if (!script->hasIonScript() || script->ionScript()->osrPc() != pc ||
      script->ionScript()->bailoutExpected() || frame->isDebuggee()) {
    return true;
  }

  IonScript* ion = script->ionScript();
  MOZ_ASSERT(cx->runtime()->geckoProfiler().enabled() ==
             ion->hasProfilingInstrumentation());
  MOZ_ASSERT(ion->osrPc() == pc);

  JitSpew(JitSpew_BaselineOSR, "  OSR possible!");
  void* jitcode = ion->method()->raw() + ion->osrEntryOffset();

  // Prepare the temporary heap copy of the fake InterpreterFrame and actual
  // args list.
  JitSpew(JitSpew_BaselineOSR, "Got jitcode.  Preparing for OSR into ion.");
  IonOsrTempData* info = PrepareOsrTempData(cx, frame, jitcode);
  if (!info) {
    return false;
  }
  *infoPtr = info;

  return true;
}

bool ICWarmUpCounter_Fallback::Compiler::generateStubCode(
    MacroAssembler& masm) {
  // Push a stub frame so that we can perform a non-tail call.
  enterStubFrame(masm, R1.scratchReg());

  Label noCompiledCode;
  // Call DoWarmUpCounterFallbackOSR to compile/check-for Ion-compiled function
  {
    // Push IonOsrTempData pointer storage
    masm.subFromStackPtr(Imm32(sizeof(void*)));
    masm.push(masm.getStackPointer());

    // Push stub pointer.
    masm.push(ICStubReg);

    pushStubPayload(masm, R0.scratchReg());

    using Fn = bool (*)(JSContext*, BaselineFrame*, ICWarmUpCounter_Fallback*,
                        IonOsrTempData * *infoPtr);
    if (!callVM<Fn, DoWarmUpCounterFallbackOSR>(masm)) {
      return false;
    }

    // Pop IonOsrTempData pointer.
    masm.pop(R0.scratchReg());

    leaveStubFrame(masm);

    // If no JitCode was found, then skip just exit the IC.
    masm.branchPtr(Assembler::Equal, R0.scratchReg(), ImmPtr(nullptr),
                   &noCompiledCode);
  }

  // Get a scratch register.
  AllocatableGeneralRegisterSet regs(availableGeneralRegs(0));
  Register osrDataReg = R0.scratchReg();
  regs.take(osrDataReg);
  regs.takeUnchecked(OsrFrameReg);

  Register scratchReg = regs.takeAny();

  // At this point, stack looks like:
  //  +-> [...Calling-Frame...]
  //  |   [...Actual-Args/ThisV/ArgCount/Callee...]
  //  |   [Descriptor]
  //  |   [Return-Addr]
  //  +---[Saved-FramePtr]            <-- BaselineFrameReg points here.
  //      [...Baseline-Frame...]

  // Restore the stack pointer to point to the saved frame pointer.
  masm.moveToStackPtr(BaselineFrameReg);

  // Discard saved frame pointer, so that the return address is on top of
  // the stack.
  masm.pop(scratchReg);

#ifdef DEBUG
  // If profiler instrumentation is on, ensure that lastProfilingFrame is
  // the frame currently being OSR-ed
  {
    Label checkOk;
    AbsoluteAddress addressOfEnabled(
        cx->runtime()->geckoProfiler().addressOfEnabled());
    masm.branch32(Assembler::Equal, addressOfEnabled, Imm32(0), &checkOk);
    masm.loadPtr(AbsoluteAddress((void*)&cx->jitActivation), scratchReg);
    masm.loadPtr(
        Address(scratchReg, JitActivation::offsetOfLastProfilingFrame()),
        scratchReg);

    // It may be the case that we entered the baseline frame with
    // profiling turned off on, then in a call within a loop (i.e. a
    // callee frame), turn on profiling, then return to this frame,
    // and then OSR with profiling turned on.  In this case, allow for
    // lastProfilingFrame to be null.
    masm.branchPtr(Assembler::Equal, scratchReg, ImmWord(0), &checkOk);

    masm.branchStackPtr(Assembler::Equal, scratchReg, &checkOk);
    masm.assumeUnreachable("Baseline OSR lastProfilingFrame mismatch.");
    masm.bind(&checkOk);
  }
#endif

  // Jump into Ion.
  masm.loadPtr(Address(osrDataReg, offsetof(IonOsrTempData, jitcode)),
               scratchReg);
  masm.loadPtr(Address(osrDataReg, offsetof(IonOsrTempData, baselineFrame)),
               OsrFrameReg);
  masm.jump(scratchReg);

  // No jitcode available, do nothing.
  masm.bind(&noCompiledCode);
  EmitReturnFromIC(masm);
  return true;
}

void ICFallbackStub::unlinkStub(Zone* zone, ICStub* prev, ICStub* stub) {
  MOZ_ASSERT(stub->next());

  // If stub is the last optimized stub, update lastStubPtrAddr.
  if (stub->next() == this) {
    MOZ_ASSERT(lastStubPtrAddr_ == stub->addressOfNext());
    if (prev) {
      lastStubPtrAddr_ = prev->addressOfNext();
    } else {
      lastStubPtrAddr_ = icEntry()->addressOfFirstStub();
    }
    *lastStubPtrAddr_ = this;
  } else {
    if (prev) {
      MOZ_ASSERT(prev->next() == stub);
      prev->setNext(stub->next());
    } else {
      MOZ_ASSERT(icEntry()->firstStub() == stub);
      icEntry()->setFirstStub(stub->next());
    }
  }

  state_.trackUnlinkedStub();

  if (zone->needsIncrementalBarrier()) {
    // We are removing edges from ICStub to gcthings. Perform one final trace
    // of the stub for incremental GC, as it must know about those edges.
    stub->trace(zone->barrierTracer());
  }

  if (stub->makesGCCalls() && stub->isMonitored()) {
    // This stub can make calls so we can return to it if it's on the stack.
    // We just have to reset its firstMonitorStub_ field to avoid a stale
    // pointer when purgeOptimizedStubs destroys all optimized monitor
    // stubs (unlinked stubs won't be updated).
    ICTypeMonitor_Fallback* monitorFallback =
        toMonitoredFallbackStub()->maybeFallbackMonitorStub();
    MOZ_ASSERT(monitorFallback);
    stub->toMonitoredStub()->resetFirstMonitorStub(monitorFallback);
  }

#ifdef DEBUG
  // Poison stub code to ensure we don't call this stub again. However, if
  // this stub can make calls, a pointer to it may be stored in a stub frame
  // on the stack, so we can't touch the stubCode_ or GC will crash when
  // tracing this pointer.
  if (!stub->makesGCCalls()) {
    stub->stubCode_ = (uint8_t*)0xbad;
  }
#endif
}

void ICFallbackStub::unlinkStubsWithKind(JSContext* cx, ICStub::Kind kind) {
  for (ICStubIterator iter = beginChain(); !iter.atEnd(); iter++) {
    if (iter->kind() == kind) {
      iter.unlink(cx);
    }
  }
}

void ICFallbackStub::discardStubs(JSContext* cx) {
  for (ICStubIterator iter = beginChain(); !iter.atEnd(); iter++) {
    iter.unlink(cx);
  }
}

void ICTypeMonitor_Fallback::resetMonitorStubChain(Zone* zone) {
  if (zone->needsIncrementalBarrier()) {
    // We are removing edges from monitored stubs to gcthings (JitCode).
    // Perform one final trace of all monitor stubs for incremental GC,
    // as it must know about those edges.
    for (ICStub* s = firstMonitorStub_; !s->isTypeMonitor_Fallback();
         s = s->next()) {
      s->trace(zone->barrierTracer());
    }
  }

  firstMonitorStub_ = this;
  numOptimizedMonitorStubs_ = 0;

  if (hasFallbackStub_) {
    lastMonitorStubPtrAddr_ = nullptr;

    // Reset firstMonitorStub_ field of all monitored stubs.
    for (ICStubConstIterator iter = mainFallbackStub_->beginChainConst();
         !iter.atEnd(); iter++) {
      if (!iter->isMonitored()) {
        continue;
      }
      iter->toMonitoredStub()->resetFirstMonitorStub(this);
    }
  } else {
    icEntry_->setFirstStub(this);
    lastMonitorStubPtrAddr_ = icEntry_->addressOfFirstStub();
  }
}

void ICUpdatedStub::resetUpdateStubChain(Zone* zone) {
  while (!firstUpdateStub_->isTypeUpdate_Fallback()) {
    if (zone->needsIncrementalBarrier()) {
      // We are removing edges from update stubs to gcthings (JitCode).
      // Perform one final trace of all update stubs for incremental GC,
      // as it must know about those edges.
      firstUpdateStub_->trace(zone->barrierTracer());
    }
    firstUpdateStub_ = firstUpdateStub_->next();
  }

  numOptimizedStubs_ = 0;
}

ICMonitoredStub::ICMonitoredStub(Kind kind, JitCode* stubCode,
                                 ICStub* firstMonitorStub)
    : ICStub(kind, ICStub::Monitored, stubCode),
      firstMonitorStub_(firstMonitorStub) {
  // In order to silence Coverity - null pointer dereference checker
  MOZ_ASSERT(firstMonitorStub_);
  // If the first monitored stub is a ICTypeMonitor_Fallback stub, then
  // double check that _its_ firstMonitorStub is the same as this one.
  MOZ_ASSERT_IF(
      firstMonitorStub_->isTypeMonitor_Fallback(),
      firstMonitorStub_->toTypeMonitor_Fallback()->firstMonitorStub() ==
          firstMonitorStub_);
}

bool ICMonitoredFallbackStub::initMonitoringChain(JSContext* cx,
                                                  JSScript* script) {
  MOZ_ASSERT(fallbackMonitorStub_ == nullptr);

  ICTypeMonitor_Fallback::Compiler compiler(cx, this);
  ICStubSpace* space = script->icScript()->fallbackStubSpace();
  ICTypeMonitor_Fallback* stub = compiler.getStub(space);
  if (!stub) {
    return false;
  }
  fallbackMonitorStub_ = stub;
  return true;
}

bool ICMonitoredFallbackStub::addMonitorStubForValue(JSContext* cx,
                                                     BaselineFrame* frame,
                                                     StackTypeSet* types,
                                                     HandleValue val) {
  ICTypeMonitor_Fallback* typeMonitorFallback =
      getFallbackMonitorStub(cx, frame->script());
  if (!typeMonitorFallback) {
    return false;
  }
  return typeMonitorFallback->addMonitorStubForValue(cx, frame, types, val);
}

bool ICUpdatedStub::initUpdatingChain(JSContext* cx, ICStubSpace* space) {
  MOZ_ASSERT(firstUpdateStub_ == nullptr);

  ICTypeUpdate_Fallback::Compiler compiler(cx);
  ICTypeUpdate_Fallback* stub = compiler.getStub(space);
  if (!stub) {
    return false;
  }

  firstUpdateStub_ = stub;
  return true;
}

/* static */
ICStubSpace* ICStubCompiler::StubSpaceForStub(bool makesGCCalls,
                                              JSScript* script) {
  if (makesGCCalls) {
    return script->icScript()->fallbackStubSpace();
  }
  return script->zone()->jitZone()->optimizedStubSpace();
}

JitCode* ICStubCompiler::getStubCode() {
  JitRealm* realm = cx->realm()->jitRealm();

  // Check for existing cached stubcode.
  uint32_t stubKey = getKey();
  JitCode* stubCode = realm->getStubCode(stubKey);
  if (stubCode) {
    return stubCode;
  }

  // Compile new stubcode.
  JitContext jctx(cx, nullptr);
  StackMacroAssembler masm;
#ifndef JS_USE_LINK_REGISTER
  // The first value contains the return addres,
  // which we pull into ICTailCallReg for tail calls.
  masm.adjustFrame(sizeof(intptr_t));
#endif
#ifdef JS_CODEGEN_ARM
  masm.setSecondScratchReg(BaselineSecondScratchReg);
#endif

  if (!generateStubCode(masm)) {
    return nullptr;
  }
  Linker linker(masm, "getStubCode");
  Rooted<JitCode*> newStubCode(cx, linker.newCode(cx, CodeKind::Baseline));
  if (!newStubCode) {
    return nullptr;
  }

  // Cache newly compiled stubcode.
  if (!realm->putStubCode(cx, stubKey, newStubCode)) {
    return nullptr;
  }

  // After generating code, run postGenerateStubCode().  We must not fail
  // after this point.
  postGenerateStubCode(masm, newStubCode);

  MOZ_ASSERT(entersStubFrame_ == ICStub::NonCacheIRStubMakesGCCalls(kind));
  MOZ_ASSERT(!inStubFrame_);

#ifdef JS_ION_PERF
  writePerfSpewerJitCodeProfile(newStubCode, "BaselineIC");
#endif

  return newStubCode;
}

bool ICStubCompiler::tailCallVMInternal(MacroAssembler& masm,
                                        TailCallVMFunctionId id) {
  TrampolinePtr code = cx->runtime()->jitRuntime()->getVMWrapper(id);
  const VMFunctionData& fun = GetVMFunction(id);
  MOZ_ASSERT(fun.expectTailCall == TailCall);
  uint32_t argSize = fun.explicitStackSlots() * sizeof(void*);
  EmitBaselineTailCallVM(code, masm, argSize);
  return true;
}

bool ICStubCompiler::callVMInternal(MacroAssembler& masm, VMFunctionId id) {
  MOZ_ASSERT(inStubFrame_);

  TrampolinePtr code = cx->runtime()->jitRuntime()->getVMWrapper(id);
  MOZ_ASSERT(GetVMFunction(id).expectTailCall == NonTailCall);

  EmitBaselineCallVM(code, masm);
  return true;
}

template <typename Fn, Fn fn>
bool ICStubCompiler::callVM(MacroAssembler& masm) {
  VMFunctionId id = VMFunctionToId<Fn, fn>::id;
  return callVMInternal(masm, id);
}

template <typename Fn, Fn fn>
bool ICStubCompiler::tailCallVM(MacroAssembler& masm) {
  TailCallVMFunctionId id = TailCallVMFunctionToId<Fn, fn>::id;
  return tailCallVMInternal(masm, id);
}

void ICStubCompiler::enterStubFrame(MacroAssembler& masm, Register scratch) {
  EmitBaselineEnterStubFrame(masm, scratch);
#ifdef DEBUG
  framePushedAtEnterStubFrame_ = masm.framePushed();
#endif

  MOZ_ASSERT(!inStubFrame_);
  inStubFrame_ = true;

#ifdef DEBUG
  entersStubFrame_ = true;
#endif
}

void ICStubCompiler::assumeStubFrame() {
  MOZ_ASSERT(!inStubFrame_);
  inStubFrame_ = true;

#ifdef DEBUG
  entersStubFrame_ = true;

  // |framePushed| isn't tracked precisely in ICStubs, so simply assume it to
  // be STUB_FRAME_SIZE so that assertions don't fail in leaveStubFrame.
  framePushedAtEnterStubFrame_ = STUB_FRAME_SIZE;
#endif
}

void ICStubCompiler::leaveStubFrame(MacroAssembler& masm, bool calledIntoIon) {
  MOZ_ASSERT(entersStubFrame_ && inStubFrame_);
  inStubFrame_ = false;

#ifdef DEBUG
  masm.setFramePushed(framePushedAtEnterStubFrame_);
  if (calledIntoIon) {
    masm.adjustFrame(sizeof(intptr_t));  // Calls into ion have this extra.
  }
#endif
  EmitBaselineLeaveStubFrame(masm, calledIntoIon);
}

void ICStubCompiler::pushStubPayload(MacroAssembler& masm, Register scratch) {
  if (inStubFrame_) {
    masm.loadPtr(Address(BaselineFrameReg, 0), scratch);
    masm.pushBaselineFramePtr(scratch, scratch);
  } else {
    masm.pushBaselineFramePtr(BaselineFrameReg, scratch);
  }
}

void ICStubCompiler::PushStubPayload(MacroAssembler& masm, Register scratch) {
  pushStubPayload(masm, scratch);
  masm.adjustFrame(sizeof(intptr_t));
}

void ICScript::noteAccessedGetter(uint32_t pcOffset) {
  ICEntry& entry = icEntryFromPCOffset(pcOffset);
  ICFallbackStub* stub = entry.fallbackStub();

  if (stub->isGetProp_Fallback()) {
    stub->toGetProp_Fallback()->noteAccessedGetter();
  }
}

// TypeMonitor_Fallback
//

bool ICTypeMonitor_Fallback::addMonitorStubForValue(JSContext* cx,
                                                    BaselineFrame* frame,
                                                    StackTypeSet* types,
                                                    HandleValue val) {
  MOZ_ASSERT(types);

  // Don't attach too many SingleObject/ObjectGroup stubs. If the value is a
  // primitive or if we will attach an any-object stub, we can handle this
  // with a single PrimitiveSet or AnyValue stub so we always optimize.
  if (numOptimizedMonitorStubs_ >= MAX_OPTIMIZED_STUBS && val.isObject() &&
      !types->unknownObject()) {
    return true;
  }

  bool wasDetachedMonitorChain = lastMonitorStubPtrAddr_ == nullptr;
  MOZ_ASSERT_IF(wasDetachedMonitorChain, numOptimizedMonitorStubs_ == 0);

  if (types->unknown()) {
    // The TypeSet got marked as unknown so attach a stub that always
    // succeeds.

    // Check for existing TypeMonitor_AnyValue stubs.
    for (ICStubConstIterator iter(firstMonitorStub()); !iter.atEnd(); iter++) {
      if (iter->isTypeMonitor_AnyValue()) {
        return true;
      }
    }

    // Discard existing stubs.
    resetMonitorStubChain(cx->zone());
    wasDetachedMonitorChain = (lastMonitorStubPtrAddr_ == nullptr);

    ICTypeMonitor_AnyValue::Compiler compiler(cx);
    ICStub* stub = compiler.getStub(compiler.getStubSpace(frame->script()));
    if (!stub) {
      ReportOutOfMemory(cx);
      return false;
    }

    JitSpew(JitSpew_BaselineIC, "  Added TypeMonitor stub %p for any value",
            stub);
    addOptimizedMonitorStub(stub);

  } else if (val.isPrimitive() || types->unknownObject()) {
    if (val.isMagic(JS_UNINITIALIZED_LEXICAL)) {
      return true;
    }
    MOZ_ASSERT(!val.isMagic());
    ValueType type = val.type();

    // Check for existing TypeMonitor stub.
    ICTypeMonitor_PrimitiveSet* existingStub = nullptr;
    for (ICStubConstIterator iter(firstMonitorStub()); !iter.atEnd(); iter++) {
      if (iter->isTypeMonitor_PrimitiveSet()) {
        existingStub = iter->toTypeMonitor_PrimitiveSet();
        if (existingStub->containsType(type)) {
          return true;
        }
      }
    }

    if (val.isObject()) {
      // Check for existing SingleObject/ObjectGroup stubs and discard
      // stubs if we find one. Ideally we would discard just these stubs,
      // but unlinking individual type monitor stubs is somewhat
      // complicated.
      MOZ_ASSERT(types->unknownObject());
      bool hasObjectStubs = false;
      for (ICStubConstIterator iter(firstMonitorStub()); !iter.atEnd();
           iter++) {
        if (iter->isTypeMonitor_SingleObject() ||
            iter->isTypeMonitor_ObjectGroup()) {
          hasObjectStubs = true;
          break;
        }
      }
      if (hasObjectStubs) {
        resetMonitorStubChain(cx->zone());
        wasDetachedMonitorChain = (lastMonitorStubPtrAddr_ == nullptr);
        existingStub = nullptr;
      }
    }

    ICTypeMonitor_PrimitiveSet::Compiler compiler(cx, existingStub, type);
    ICStub* stub =
        existingStub ? compiler.updateStub()
                     : compiler.getStub(compiler.getStubSpace(frame->script()));
    if (!stub) {
      ReportOutOfMemory(cx);
      return false;
    }

    JitSpew(JitSpew_BaselineIC,
            "  %s TypeMonitor stub %p for primitive type %u",
            existingStub ? "Modified existing" : "Created new", stub,
            static_cast<uint8_t>(type));

    if (!existingStub) {
      MOZ_ASSERT(!hasStub(TypeMonitor_PrimitiveSet));
      addOptimizedMonitorStub(stub);
    }

  } else if (val.toObject().isSingleton()) {
    RootedObject obj(cx, &val.toObject());

    // Check for existing TypeMonitor stub.
    for (ICStubConstIterator iter(firstMonitorStub()); !iter.atEnd(); iter++) {
      if (iter->isTypeMonitor_SingleObject() &&
          iter->toTypeMonitor_SingleObject()->object() == obj) {
        return true;
      }
    }

    ICTypeMonitor_SingleObject::Compiler compiler(cx, obj);
    ICStub* stub = compiler.getStub(compiler.getStubSpace(frame->script()));
    if (!stub) {
      ReportOutOfMemory(cx);
      return false;
    }

    JitSpew(JitSpew_BaselineIC, "  Added TypeMonitor stub %p for singleton %p",
            stub, obj.get());

    addOptimizedMonitorStub(stub);

  } else {
    RootedObjectGroup group(cx, val.toObject().group());

    // Check for existing TypeMonitor stub.
    for (ICStubConstIterator iter(firstMonitorStub()); !iter.atEnd(); iter++) {
      if (iter->isTypeMonitor_ObjectGroup() &&
          iter->toTypeMonitor_ObjectGroup()->group() == group) {
        return true;
      }
    }

    ICTypeMonitor_ObjectGroup::Compiler compiler(cx, group);
    ICStub* stub = compiler.getStub(compiler.getStubSpace(frame->script()));
    if (!stub) {
      ReportOutOfMemory(cx);
      return false;
    }

    JitSpew(JitSpew_BaselineIC,
            "  Added TypeMonitor stub %p for ObjectGroup %p", stub,
            group.get());

    addOptimizedMonitorStub(stub);
  }

  bool firstMonitorStubAdded =
      wasDetachedMonitorChain && (numOptimizedMonitorStubs_ > 0);

  if (firstMonitorStubAdded) {
    // Was an empty monitor chain before, but a new stub was added.  This is the
    // only time that any main stubs' firstMonitorStub fields need to be updated
    // to refer to the newly added monitor stub.
    ICStub* firstStub = mainFallbackStub_->icEntry()->firstStub();
    for (ICStubConstIterator iter(firstStub); !iter.atEnd(); iter++) {
      // Non-monitored stubs are used if the result has always the same type,
      // e.g. a StringLength stub will always return int32.
      if (!iter->isMonitored()) {
        continue;
      }

      // Since we just added the first optimized monitoring stub, any
      // existing main stub's |firstMonitorStub| MUST be pointing to the
      // fallback monitor stub (i.e. this stub).
      MOZ_ASSERT(iter->toMonitoredStub()->firstMonitorStub() == this);
      iter->toMonitoredStub()->updateFirstMonitorStub(firstMonitorStub_);
    }
  }

  return true;
}

bool DoTypeMonitorFallback(JSContext* cx, BaselineFrame* frame,
                           ICTypeMonitor_Fallback* stub, HandleValue value,
                           MutableHandleValue res) {
  JSScript* script = frame->script();
  jsbytecode* pc = stub->icEntry()->pc(script);
  TypeFallbackICSpew(cx, stub, "TypeMonitor");

  // Copy input value to res.
  res.set(value);

  if (MOZ_UNLIKELY(value.isMagic())) {
    // It's possible that we arrived here from bailing out of Ion, and that
    // Ion proved that the value is dead and optimized out. In such cases,
    // do nothing. However, it's also possible that we have an uninitialized
    // this, in which case we should not look for other magic values.

    if (value.whyMagic() == JS_OPTIMIZED_OUT) {
      MOZ_ASSERT(!stub->monitorsThis());
      return true;
    }

    // In derived class constructors (including nested arrows/eval), the
    // |this| argument or GETALIASEDVAR can return the magic TDZ value.
    MOZ_ASSERT(value.isMagic(JS_UNINITIALIZED_LEXICAL));
    MOZ_ASSERT(frame->isFunctionFrame() || frame->isEvalFrame());
    MOZ_ASSERT(stub->monitorsThis() || *GetNextPc(pc) == JSOP_CHECKTHIS ||
               *GetNextPc(pc) == JSOP_CHECKTHISREINIT ||
               *GetNextPc(pc) == JSOP_CHECKRETURN);
    if (stub->monitorsThis()) {
      TypeScript::SetThis(cx, script, TypeSet::UnknownType());
    } else {
      TypeScript::Monitor(cx, script, pc, TypeSet::UnknownType());
    }
    return true;
  }

  StackTypeSet* types;
  uint32_t argument;
  if (stub->monitorsArgument(&argument)) {
    MOZ_ASSERT(pc == script->code());
    types = TypeScript::ArgTypes(script, argument);
    TypeScript::SetArgument(cx, script, argument, value);
  } else if (stub->monitorsThis()) {
    MOZ_ASSERT(pc == script->code());
    types = TypeScript::ThisTypes(script);
    TypeScript::SetThis(cx, script, value);
  } else {
    types = TypeScript::BytecodeTypes(script, pc);
    TypeScript::Monitor(cx, script, pc, types, value);
  }

  return stub->addMonitorStubForValue(cx, frame, types, value);
}

bool ICTypeMonitor_Fallback::Compiler::generateStubCode(MacroAssembler& masm) {
  MOZ_ASSERT(R0 == JSReturnOperand);

  // Restore the tail call register.
  EmitRestoreTailCallReg(masm);

  masm.pushValue(R0);
  masm.push(ICStubReg);
  masm.pushBaselineFramePtr(BaselineFrameReg, R0.scratchReg());

  using Fn = bool (*)(JSContext*, BaselineFrame*, ICTypeMonitor_Fallback*,
                      HandleValue, MutableHandleValue);
  return tailCallVM<Fn, DoTypeMonitorFallback>(masm);
}

bool ICTypeMonitor_PrimitiveSet::Compiler::generateStubCode(
    MacroAssembler& masm) {
  Label success;
  if ((flags_ & TypeToFlag(ValueType::Int32)) &&
      !(flags_ & TypeToFlag(ValueType::Double))) {
    masm.branchTestInt32(Assembler::Equal, R0, &success);
  }

  if (flags_ & TypeToFlag(ValueType::Double)) {
    masm.branchTestNumber(Assembler::Equal, R0, &success);
  }

  if (flags_ & TypeToFlag(ValueType::Undefined)) {
    masm.branchTestUndefined(Assembler::Equal, R0, &success);
  }

  if (flags_ & TypeToFlag(ValueType::Boolean)) {
    masm.branchTestBoolean(Assembler::Equal, R0, &success);
  }

  if (flags_ & TypeToFlag(ValueType::String)) {
    masm.branchTestString(Assembler::Equal, R0, &success);
  }

  if (flags_ & TypeToFlag(ValueType::Symbol)) {
    masm.branchTestSymbol(Assembler::Equal, R0, &success);
  }

  if (flags_ & TypeToFlag(ValueType::BigInt)) {
    masm.branchTestBigInt(Assembler::Equal, R0, &success);
  }

  if (flags_ & TypeToFlag(ValueType::Object)) {
    masm.branchTestObject(Assembler::Equal, R0, &success);
  }

  if (flags_ & TypeToFlag(ValueType::Null)) {
    masm.branchTestNull(Assembler::Equal, R0, &success);
  }

  EmitStubGuardFailure(masm);

  masm.bind(&success);
  EmitReturnFromIC(masm);
  return true;
}

static void MaybeWorkAroundAmdBug(MacroAssembler& masm) {
  // Attempt to work around an AMD bug (see bug 1034706 and bug 1281759), by
  // inserting 32-bytes of NOPs.
#if defined(JS_CODEGEN_X86) || defined(JS_CODEGEN_X64)
  if (CPUInfo::NeedAmdBugWorkaround()) {
    masm.nop(9);
    masm.nop(9);
    masm.nop(9);
    masm.nop(5);
  }
#endif
}

bool ICTypeMonitor_SingleObject::Compiler::generateStubCode(
    MacroAssembler& masm) {
  Label failure;
  masm.branchTestObject(Assembler::NotEqual, R0, &failure);
  MaybeWorkAroundAmdBug(masm);

  // Guard on the object's identity.
  Register obj = masm.extractObject(R0, ExtractTemp0);
  Address expectedObject(ICStubReg,
                         ICTypeMonitor_SingleObject::offsetOfObject());
  masm.branchPtr(Assembler::NotEqual, expectedObject, obj, &failure);
  MaybeWorkAroundAmdBug(masm);

  EmitReturnFromIC(masm);
  MaybeWorkAroundAmdBug(masm);

  masm.bind(&failure);
  EmitStubGuardFailure(masm);
  return true;
}

bool ICTypeMonitor_ObjectGroup::Compiler::generateStubCode(
    MacroAssembler& masm) {
  Label failure;
  masm.branchTestObject(Assembler::NotEqual, R0, &failure);
  MaybeWorkAroundAmdBug(masm);

  // Guard on the object's ObjectGroup. No Spectre mitigations are needed
  // here: we're just recording type information for Ion compilation and
  // it's safe to speculatively return.
  Register obj = masm.extractObject(R0, ExtractTemp0);
  Address expectedGroup(ICStubReg, ICTypeMonitor_ObjectGroup::offsetOfGroup());
  masm.branchTestObjGroupNoSpectreMitigations(
      Assembler::NotEqual, obj, expectedGroup, R1.scratchReg(), &failure);
  MaybeWorkAroundAmdBug(masm);

  EmitReturnFromIC(masm);
  MaybeWorkAroundAmdBug(masm);

  masm.bind(&failure);
  EmitStubGuardFailure(masm);
  return true;
}

bool ICTypeMonitor_AnyValue::Compiler::generateStubCode(MacroAssembler& masm) {
  EmitReturnFromIC(masm);
  return true;
}

bool ICUpdatedStub::addUpdateStubForValue(JSContext* cx,
                                          HandleScript outerScript,
                                          HandleObject obj,
                                          HandleObjectGroup group, HandleId id,
                                          HandleValue val) {
  EnsureTrackPropertyTypes(cx, obj, id);

  // Make sure that undefined values are explicitly included in the property
  // types for an object if generating a stub to write an undefined value.
  if (val.isUndefined() && CanHaveEmptyPropertyTypesForOwnProperty(obj)) {
    MOZ_ASSERT(obj->group() == group);
    AddTypePropertyId(cx, obj, id, val);
  }

  bool unknown = false, unknownObject = false;
  AutoSweepObjectGroup sweep(group);
  if (group->unknownProperties(sweep)) {
    unknown = unknownObject = true;
  } else {
    if (HeapTypeSet* types = group->maybeGetProperty(sweep, id)) {
      unknown = types->unknown();
      unknownObject = types->unknownObject();
    } else {
      // We don't record null/undefined types for certain TypedObject
      // properties. In these cases |types| is allowed to be nullptr
      // without implying unknown types. See DoTypeUpdateFallback.
      MOZ_ASSERT(obj->is<TypedObject>());
      MOZ_ASSERT(val.isNullOrUndefined());
    }
  }
  MOZ_ASSERT_IF(unknown, unknownObject);

  // Don't attach too many SingleObject/ObjectGroup stubs unless we can
  // replace them with a single PrimitiveSet or AnyValue stub.
  if (numOptimizedStubs_ >= MAX_OPTIMIZED_STUBS && val.isObject() &&
      !unknownObject) {
    return true;
  }

  if (unknown) {
    // Attach a stub that always succeeds. We should not have a
    // TypeUpdate_AnyValue stub yet.
    MOZ_ASSERT(!hasTypeUpdateStub(TypeUpdate_AnyValue));

    // Discard existing stubs.
    resetUpdateStubChain(cx->zone());

    ICTypeUpdate_AnyValue::Compiler compiler(cx);
    ICStub* stub = compiler.getStub(compiler.getStubSpace(outerScript));
    if (!stub) {
      return false;
    }

    JitSpew(JitSpew_BaselineIC, "  Added TypeUpdate stub %p for any value",
            stub);
    addOptimizedUpdateStub(stub);

  } else if (val.isPrimitive() || unknownObject) {
    ValueType type = val.type();

    // Check for existing TypeUpdate stub.
    ICTypeUpdate_PrimitiveSet* existingStub = nullptr;
    for (ICStubConstIterator iter(firstUpdateStub_); !iter.atEnd(); iter++) {
      if (iter->isTypeUpdate_PrimitiveSet()) {
        existingStub = iter->toTypeUpdate_PrimitiveSet();
        MOZ_ASSERT(!existingStub->containsType(type));
      }
    }

    if (val.isObject()) {
      // Discard existing ObjectGroup/SingleObject stubs.
      resetUpdateStubChain(cx->zone());
      if (existingStub) {
        addOptimizedUpdateStub(existingStub);
      }
    }

    ICTypeUpdate_PrimitiveSet::Compiler compiler(cx, existingStub, type);
    ICStub* stub = existingStub
                       ? compiler.updateStub()
                       : compiler.getStub(compiler.getStubSpace(outerScript));
    if (!stub) {
      return false;
    }
    if (!existingStub) {
      MOZ_ASSERT(!hasTypeUpdateStub(TypeUpdate_PrimitiveSet));
      addOptimizedUpdateStub(stub);
    }

    JitSpew(JitSpew_BaselineIC, "  %s TypeUpdate stub %p for primitive type %d",
            existingStub ? "Modified existing" : "Created new", stub,
            static_cast<uint8_t>(type));

  } else if (val.toObject().isSingleton()) {
    RootedObject obj(cx, &val.toObject());

#ifdef DEBUG
    // We should not have a stub for this object.
    for (ICStubConstIterator iter(firstUpdateStub_); !iter.atEnd(); iter++) {
      MOZ_ASSERT_IF(iter->isTypeUpdate_SingleObject(),
                    iter->toTypeUpdate_SingleObject()->object() != obj);
    }
#endif

    ICTypeUpdate_SingleObject::Compiler compiler(cx, obj);
    ICStub* stub = compiler.getStub(compiler.getStubSpace(outerScript));
    if (!stub) {
      return false;
    }

    JitSpew(JitSpew_BaselineIC, "  Added TypeUpdate stub %p for singleton %p",
            stub, obj.get());

    addOptimizedUpdateStub(stub);

  } else {
    RootedObjectGroup group(cx, val.toObject().group());

#ifdef DEBUG
    // We should not have a stub for this group.
    for (ICStubConstIterator iter(firstUpdateStub_); !iter.atEnd(); iter++) {
      MOZ_ASSERT_IF(iter->isTypeUpdate_ObjectGroup(),
                    iter->toTypeUpdate_ObjectGroup()->group() != group);
    }
#endif

    ICTypeUpdate_ObjectGroup::Compiler compiler(cx, group);
    ICStub* stub = compiler.getStub(compiler.getStubSpace(outerScript));
    if (!stub) {
      return false;
    }

    JitSpew(JitSpew_BaselineIC, "  Added TypeUpdate stub %p for ObjectGroup %p",
            stub, group.get());

    addOptimizedUpdateStub(stub);
  }

  return true;
}

//
// TypeUpdate_Fallback
//
bool DoTypeUpdateFallback(JSContext* cx, BaselineFrame* frame,
                          ICUpdatedStub* stub, HandleValue objval,
                          HandleValue value) {
  // This can get called from optimized stubs. Therefore it is not allowed to
  // gc.
  JS::AutoCheckCannotGC nogc;

  FallbackICSpew(cx, stub->getChainFallback(), "TypeUpdate(%s)",
                 ICStub::KindString(stub->kind()));

  MOZ_ASSERT(stub->isCacheIR_Updated());

  RootedScript script(cx, frame->script());
  RootedObject obj(cx, &objval.toObject());

  RootedId id(cx, stub->toCacheIR_Updated()->updateStubId());
  MOZ_ASSERT(id.get() != JSID_EMPTY);

  // The group should match the object's group, except when the object is
  // an unboxed expando object: in that case, the group is the group of
  // the unboxed object.
  RootedObjectGroup group(cx, stub->toCacheIR_Updated()->updateStubGroup());
#ifdef DEBUG
  if (obj->is<UnboxedExpandoObject>()) {
    MOZ_ASSERT(group->clasp() == &UnboxedPlainObject::class_);
  } else {
    MOZ_ASSERT(obj->group() == group);
  }
#endif

  // If we're storing null/undefined to a typed object property, check if
  // we want to include it in this property's type information.
  bool addType = true;
  if (MOZ_UNLIKELY(obj->is<TypedObject>()) && value.isNullOrUndefined()) {
    StructTypeDescr* structDescr =
        &obj->as<TypedObject>().typeDescr().as<StructTypeDescr>();
    size_t fieldIndex;
    MOZ_ALWAYS_TRUE(structDescr->fieldIndex(id, &fieldIndex));

    TypeDescr* fieldDescr = &structDescr->fieldDescr(fieldIndex);
    ReferenceType type = fieldDescr->as<ReferenceTypeDescr>().type();
    if (type == ReferenceType::TYPE_ANY) {
      // Ignore undefined values, which are included implicitly in type
      // information for this property.
      if (value.isUndefined()) {
        addType = false;
      }
    } else {
      MOZ_ASSERT(type == ReferenceType::TYPE_OBJECT ||
                 type == ReferenceType::TYPE_WASM_ANYREF);

      // Ignore null values being written here. Null is included
      // implicitly in type information for this property. Note that
      // non-object, non-null values are not possible here, these
      // should have been filtered out by the IR emitter.
      if (value.isNull()) {
        addType = false;
      }
    }
  }

  if (MOZ_LIKELY(addType)) {
    JSObject* maybeSingleton = obj->isSingleton() ? obj.get() : nullptr;
    AddTypePropertyId(cx, group, maybeSingleton, id, value);
  }

  if (MOZ_UNLIKELY(
          !stub->addUpdateStubForValue(cx, script, obj, group, id, value))) {
    // The calling JIT code assumes this function is infallible (for
    // instance we may reallocate dynamic slots before calling this),
    // so ignore OOMs if we failed to attach a stub.
    cx->recoverFromOutOfMemory();
  }

  return true;
}

bool ICTypeUpdate_Fallback::Compiler::generateStubCode(MacroAssembler& masm) {
  // Just store false into R1.scratchReg() and return.
  masm.move32(Imm32(0), R1.scratchReg());
  EmitReturnFromIC(masm);
  return true;
}

bool ICTypeUpdate_PrimitiveSet::Compiler::generateStubCode(
    MacroAssembler& masm) {
  Label success;
  if ((flags_ & TypeToFlag(ValueType::Int32)) &&
      !(flags_ & TypeToFlag(ValueType::Double))) {
    masm.branchTestInt32(Assembler::Equal, R0, &success);
  }

  if (flags_ & TypeToFlag(ValueType::Double)) {
    masm.branchTestNumber(Assembler::Equal, R0, &success);
  }

  if (flags_ & TypeToFlag(ValueType::Undefined)) {
    masm.branchTestUndefined(Assembler::Equal, R0, &success);
  }

  if (flags_ & TypeToFlag(ValueType::Boolean)) {
    masm.branchTestBoolean(Assembler::Equal, R0, &success);
  }

  if (flags_ & TypeToFlag(ValueType::String)) {
    masm.branchTestString(Assembler::Equal, R0, &success);
  }

  if (flags_ & TypeToFlag(ValueType::Symbol)) {
    masm.branchTestSymbol(Assembler::Equal, R0, &success);
  }

  if (flags_ & TypeToFlag(ValueType::BigInt)) {
    masm.branchTestBigInt(Assembler::Equal, R0, &success);
  }

  if (flags_ & TypeToFlag(ValueType::Object)) {
    masm.branchTestObject(Assembler::Equal, R0, &success);
  }

  if (flags_ & TypeToFlag(ValueType::Null)) {
    masm.branchTestNull(Assembler::Equal, R0, &success);
  }

  EmitStubGuardFailure(masm);

  // Type matches, load true into R1.scratchReg() and return.
  masm.bind(&success);
  masm.mov(ImmWord(1), R1.scratchReg());
  EmitReturnFromIC(masm);

  return true;
}

bool ICTypeUpdate_SingleObject::Compiler::generateStubCode(
    MacroAssembler& masm) {
  Label failure;
  masm.branchTestObject(Assembler::NotEqual, R0, &failure);

  // Guard on the object's identity.
  Register obj = masm.extractObject(R0, R1.scratchReg());
  Address expectedObject(ICStubReg,
                         ICTypeUpdate_SingleObject::offsetOfObject());
  masm.branchPtr(Assembler::NotEqual, expectedObject, obj, &failure);

  // Identity matches, load true into R1.scratchReg() and return.
  masm.mov(ImmWord(1), R1.scratchReg());
  EmitReturnFromIC(masm);

  masm.bind(&failure);
  EmitStubGuardFailure(masm);
  return true;
}

bool ICTypeUpdate_ObjectGroup::Compiler::generateStubCode(
    MacroAssembler& masm) {
  Label failure;
  masm.branchTestObject(Assembler::NotEqual, R0, &failure);

  // Guard on the object's ObjectGroup.
  Address expectedGroup(ICStubReg, ICTypeUpdate_ObjectGroup::offsetOfGroup());
  Register scratch1 = R1.scratchReg();
  masm.unboxObject(R0, scratch1);
  masm.branchTestObjGroup(Assembler::NotEqual, scratch1, expectedGroup,
                          scratch1, R0.payloadOrValueReg(), &failure);

  // Group matches, load true into R1.scratchReg() and return.
  masm.mov(ImmWord(1), R1.scratchReg());
  EmitReturnFromIC(masm);

  masm.bind(&failure);
  EmitStubGuardFailure(masm);
  return true;
}

bool ICTypeUpdate_AnyValue::Compiler::generateStubCode(MacroAssembler& masm) {
  // AnyValue always matches so return true.
  masm.mov(ImmWord(1), R1.scratchReg());
  EmitReturnFromIC(masm);
  return true;
}

//
// ToBool_Fallback
//

bool DoToBoolFallback(JSContext* cx, BaselineFrame* frame,
                      ICToBool_Fallback* stub, HandleValue arg,
                      MutableHandleValue ret) {
  stub->incrementEnteredCount();
  FallbackICSpew(cx, stub, "ToBool");

  MOZ_ASSERT(!arg.isBoolean());

  TryAttachStub<ToBoolIRGenerator>("ToBool", cx, frame, stub,
                                   BaselineCacheIRStubKind::Regular, arg);

  bool cond = ToBoolean(arg);
  ret.setBoolean(cond);

  return true;
}

bool ICToBool_Fallback::Compiler::generateStubCode(MacroAssembler& masm) {
  MOZ_ASSERT(R0 == JSReturnOperand);

  // Restore the tail call register.
  EmitRestoreTailCallReg(masm);

  // Push arguments.
  masm.pushValue(R0);
  masm.push(ICStubReg);
  pushStubPayload(masm, R0.scratchReg());

  using Fn = bool (*)(JSContext*, BaselineFrame*, ICToBool_Fallback*,
                      HandleValue, MutableHandleValue);
  return tailCallVM<Fn, DoToBoolFallback>(masm);
}

static void StripPreliminaryObjectStubs(JSContext* cx, ICFallbackStub* stub) {
  // Before the new script properties analysis has been performed on a type,
  // all instances of that type have the maximum number of fixed slots.
  // Afterwards, the objects (even the preliminary ones) might be changed
  // to reduce the number of fixed slots they have. If we generate stubs for
  // both the old and new number of fixed slots, the stub will look
  // polymorphic to IonBuilder when it is actually monomorphic. To avoid
  // this, strip out any stubs for preliminary objects before attaching a new
  // stub which isn't on a preliminary object.

  for (ICStubIterator iter = stub->beginChain(); !iter.atEnd(); iter++) {
    if (iter->isCacheIR_Regular() &&
        iter->toCacheIR_Regular()->hasPreliminaryObject()) {
      iter.unlink(cx);
    } else if (iter->isCacheIR_Monitored() &&
               iter->toCacheIR_Monitored()->hasPreliminaryObject()) {
      iter.unlink(cx);
    } else if (iter->isCacheIR_Updated() &&
               iter->toCacheIR_Updated()->hasPreliminaryObject()) {
      iter.unlink(cx);
    }
  }
}

//
// GetElem_Fallback
//

bool DoGetElemFallback(JSContext* cx, BaselineFrame* frame,
                       ICGetElem_Fallback* stub, HandleValue lhs,
                       HandleValue rhs, MutableHandleValue res) {
  stub->incrementEnteredCount();

  RootedScript script(cx, frame->script());
  jsbytecode* pc = stub->icEntry()->pc(frame->script());
  StackTypeSet* types = TypeScript::BytecodeTypes(script, pc);

  JSOp op = JSOp(*pc);
  FallbackICSpew(cx, stub, "GetElem(%s)", CodeName[op]);

  MOZ_ASSERT(op == JSOP_GETELEM || op == JSOP_CALLELEM);

  // Don't pass lhs directly, we need it when generating stubs.
  RootedValue lhsCopy(cx, lhs);

  bool isOptimizedArgs = false;
  if (lhs.isMagic(JS_OPTIMIZED_ARGUMENTS)) {
    // Handle optimized arguments[i] access.
    if (!GetElemOptimizedArguments(cx, frame, &lhsCopy, rhs, res,
                                   &isOptimizedArgs)) {
      return false;
    }
    if (isOptimizedArgs) {
      TypeScript::Monitor(cx, script, pc, types, res);
    }
  }

  bool attached = false;
  bool isTemporarilyUnoptimizable = false;

  if (stub->state().maybeTransition()) {
    stub->discardStubs(cx);
  }

  if (stub->state().canAttachStub()) {
    GetPropIRGenerator gen(cx, script, pc, CacheKind::GetElem,
                           stub->state().mode(), &isTemporarilyUnoptimizable,
                           lhs, rhs, lhs, GetPropertyResultFlags::All);
    if (gen.tryAttachStub()) {
      ICStub* newStub = AttachBaselineCacheIRStub(
          cx, gen.writerRef(), gen.cacheKind(),
          BaselineCacheIRStubKind::Monitored, script, stub, &attached);
      if (newStub) {
        JitSpew(JitSpew_BaselineIC, "  Attached GetElem CacheIR stub");
        if (gen.shouldNotePreliminaryObjectStub()) {
          newStub->toCacheIR_Monitored()->notePreliminaryObject();
        } else if (gen.shouldUnlinkPreliminaryObjectStubs()) {
          StripPreliminaryObjectStubs(cx, stub);
        }
      }
    }
    if (!attached && !isTemporarilyUnoptimizable) {
      stub->state().trackNotAttached();
    }
  }

  if (!isOptimizedArgs) {
    if (!GetElementOperation(cx, op, lhsCopy, rhs, res)) {
      return false;
    }
    TypeScript::Monitor(cx, script, pc, types, res);
  }

  // Add a type monitor stub for the resulting value.
  if (!stub->addMonitorStubForValue(cx, frame, types, res)) {
    return false;
  }

  if (attached) {
    return true;
  }

  // GetElem operations which could access negative indexes generally can't
  // be optimized without the potential for bailouts, as we can't statically
  // determine that an object has no properties on such indexes.
  if (rhs.isNumber() && rhs.toNumber() < 0) {
    stub->noteNegativeIndex();
  }

  // GetElem operations which could access non-integer indexes generally can't
  // be optimized without the potential for bailouts.
  int32_t representable;
  if (rhs.isNumber() && rhs.isDouble() &&
      !mozilla::NumberEqualsInt32(rhs.toDouble(), &representable)) {
    stub->setSawNonIntegerIndex();
  }

  return true;
}

bool DoGetElemSuperFallback(JSContext* cx, BaselineFrame* frame,
                            ICGetElem_Fallback* stub, HandleValue lhs,
                            HandleValue rhs, HandleValue receiver,
                            MutableHandleValue res) {
  stub->incrementEnteredCount();

  RootedScript script(cx, frame->script());
  jsbytecode* pc = stub->icEntry()->pc(frame->script());
  StackTypeSet* types = TypeScript::BytecodeTypes(script, pc);

  JSOp op = JSOp(*pc);
  FallbackICSpew(cx, stub, "GetElemSuper(%s)", CodeName[op]);

  MOZ_ASSERT(op == JSOP_GETELEM_SUPER);

  bool attached = false;
  bool isTemporarilyUnoptimizable = false;

  if (stub->state().maybeTransition()) {
    stub->discardStubs(cx);
  }

  if (stub->state().canAttachStub()) {
    GetPropIRGenerator gen(cx, script, pc, CacheKind::GetElemSuper,
                           stub->state().mode(), &isTemporarilyUnoptimizable,
                           lhs, rhs, receiver, GetPropertyResultFlags::All);
    if (gen.tryAttachStub()) {
      ICStub* newStub = AttachBaselineCacheIRStub(
          cx, gen.writerRef(), gen.cacheKind(),
          BaselineCacheIRStubKind::Monitored, script, stub, &attached);
      if (newStub) {
        JitSpew(JitSpew_BaselineIC, "  Attached GetElemSuper CacheIR stub");
        if (gen.shouldNotePreliminaryObjectStub()) {
          newStub->toCacheIR_Monitored()->notePreliminaryObject();
        } else if (gen.shouldUnlinkPreliminaryObjectStubs()) {
          StripPreliminaryObjectStubs(cx, stub);
        }
      }
    }
    if (!attached && !isTemporarilyUnoptimizable) {
      stub->state().trackNotAttached();
    }
  }

  // |lhs| is [[HomeObject]].[[Prototype]] which must be Object
  RootedObject lhsObj(cx, &lhs.toObject());
  if (!GetObjectElementOperation(cx, op, lhsObj, receiver, rhs, res)) {
    return false;
  }
  TypeScript::Monitor(cx, script, pc, types, res);

  // Add a type monitor stub for the resulting value.
  if (!stub->addMonitorStubForValue(cx, frame, types, res)) {
    return false;
  }

  if (attached) {
    return true;
  }

  // GetElem operations which could access negative indexes generally can't
  // be optimized without the potential for bailouts, as we can't statically
  // determine that an object has no properties on such indexes.
  if (rhs.isNumber() && rhs.toNumber() < 0) {
    stub->noteNegativeIndex();
  }

  // GetElem operations which could access non-integer indexes generally can't
  // be optimized without the potential for bailouts.
  int32_t representable;
  if (rhs.isNumber() && rhs.isDouble() &&
      !mozilla::NumberEqualsInt32(rhs.toDouble(), &representable)) {
    stub->setSawNonIntegerIndex();
  }

  return true;
}

bool ICGetElem_Fallback::Compiler::generateStubCode(MacroAssembler& masm) {
  MOZ_ASSERT(R0 == JSReturnOperand);

  // Restore the tail call register.
  EmitRestoreTailCallReg(masm);

  // Super property getters use a |this| that differs from base object
  if (hasReceiver_) {
    // State: receiver in R0, index in R1, obj on the stack

    // Ensure stack is fully synced for the expression decompiler.
    // We need: receiver, index, obj
    masm.pushValue(R0);
    masm.pushValue(R1);
    masm.pushValue(Address(masm.getStackPointer(), sizeof(Value) * 2));

    // Push arguments.
    masm.pushValue(R0);  // Receiver
    masm.pushValue(R1);  // Index
    masm.pushValue(Address(masm.getStackPointer(), sizeof(Value) * 5));  // Obj
    masm.push(ICStubReg);
    masm.pushBaselineFramePtr(BaselineFrameReg, R0.scratchReg());

    using Fn =
        bool (*)(JSContext*, BaselineFrame*, ICGetElem_Fallback*, HandleValue,
                 HandleValue, HandleValue, MutableHandleValue);
    if (!tailCallVM<Fn, DoGetElemSuperFallback>(masm)) {
      return false;
    }
  } else {
    // Ensure stack is fully synced for the expression decompiler.
    masm.pushValue(R0);
    masm.pushValue(R1);

    // Push arguments.
    masm.pushValue(R1);
    masm.pushValue(R0);
    masm.push(ICStubReg);
    masm.pushBaselineFramePtr(BaselineFrameReg, R0.scratchReg());

    using Fn = bool (*)(JSContext*, BaselineFrame*, ICGetElem_Fallback*,
                        HandleValue, HandleValue, MutableHandleValue);
    if (!tailCallVM<Fn, DoGetElemFallback>(masm)) {
      return false;
    }
  }

  // This is the resume point used when bailout rewrites call stack to undo
  // Ion inlined frames. The return address pushed onto reconstructed stack
  // will point here.
  assumeStubFrame();
  bailoutReturnOffset_.bind(masm.currentOffset());

  leaveStubFrame(masm, true);

  // When we get here, ICStubReg contains the ICGetElem_Fallback stub,
  // which we can't use to enter the TypeMonitor IC, because it's a
  // MonitoredFallbackStub instead of a MonitoredStub. So, we cheat. Note that
  // we must have a non-null fallbackMonitorStub here because InitFromBailout
  // delazifies.
  masm.loadPtr(Address(ICStubReg,
                       ICMonitoredFallbackStub::offsetOfFallbackMonitorStub()),
               ICStubReg);
  EmitEnterTypeMonitorIC(masm,
                         ICTypeMonitor_Fallback::offsetOfFirstMonitorStub());

  return true;
}

void ICGetElem_Fallback::Compiler::postGenerateStubCode(MacroAssembler& masm,
                                                        Handle<JitCode*> code) {
  BailoutReturnStub kind = hasReceiver_ ? BailoutReturnStub::GetElemSuper
                                        : BailoutReturnStub::GetElem;
  void* address = code->raw() + bailoutReturnOffset_.offset();
  cx->realm()->jitRealm()->initBailoutReturnAddr(address, getKey(), kind);
}

static void SetUpdateStubData(ICCacheIR_Updated* stub,
                              const PropertyTypeCheckInfo* info) {
  if (info->isSet()) {
    stub->updateStubGroup() = info->group();
    stub->updateStubId() = info->id();
  }
}

bool DoSetElemFallback(JSContext* cx, BaselineFrame* frame,
                       ICSetElem_Fallback* stub, Value* stack, HandleValue objv,
                       HandleValue index, HandleValue rhs) {
  stub->incrementEnteredCount();

  RootedScript script(cx, frame->script());
  RootedScript outerScript(cx, script);
  jsbytecode* pc = stub->icEntry()->pc(script);
  JSOp op = JSOp(*pc);
  FallbackICSpew(cx, stub, "SetElem(%s)", CodeName[JSOp(*pc)]);

  MOZ_ASSERT(op == JSOP_SETELEM || op == JSOP_STRICTSETELEM ||
             op == JSOP_INITELEM || op == JSOP_INITHIDDENELEM ||
             op == JSOP_INITELEM_ARRAY || op == JSOP_INITELEM_INC);

  RootedObject obj(cx, ToObjectFromStack(cx, objv));
  if (!obj) {
    return false;
  }

  RootedShape oldShape(cx, obj->maybeShape());
  RootedObjectGroup oldGroup(cx, JSObject::getGroup(cx, obj));
  if (!oldGroup) {
    return false;
  }

  if (obj->is<UnboxedPlainObject>()) {
    MOZ_ASSERT(!oldShape);
    if (UnboxedExpandoObject* expando =
            obj->as<UnboxedPlainObject>().maybeExpando()) {
      oldShape = expando->lastProperty();
    }
  }

  bool isTemporarilyUnoptimizable = false;
  bool canAddSlot = false;
  bool attached = false;

  if (stub->state().maybeTransition()) {
    stub->discardStubs(cx);
  }

  if (stub->state().canAttachStub()) {
    SetPropIRGenerator gen(cx, script, pc, CacheKind::SetElem,
                           stub->state().mode(), &isTemporarilyUnoptimizable,
                           &canAddSlot, objv, index, rhs);
    if (gen.tryAttachStub()) {
      ICStub* newStub = AttachBaselineCacheIRStub(
          cx, gen.writerRef(), gen.cacheKind(),
          BaselineCacheIRStubKind::Updated, frame->script(), stub, &attached);
      if (newStub) {
        JitSpew(JitSpew_BaselineIC, "  Attached SetElem CacheIR stub");

        SetUpdateStubData(newStub->toCacheIR_Updated(), gen.typeCheckInfo());

        if (gen.shouldNotePreliminaryObjectStub()) {
          newStub->toCacheIR_Updated()->notePreliminaryObject();
        } else if (gen.shouldUnlinkPreliminaryObjectStubs()) {
          StripPreliminaryObjectStubs(cx, stub);
        }

        if (gen.attachedTypedArrayOOBStub()) {
          stub->noteHasTypedArrayOOB();
        }
      }
    }
  }

  if (op == JSOP_INITELEM || op == JSOP_INITHIDDENELEM) {
    if (!InitElemOperation(cx, pc, obj, index, rhs)) {
      return false;
    }
  } else if (op == JSOP_INITELEM_ARRAY) {
    MOZ_ASSERT(uint32_t(index.toInt32()) <= INT32_MAX,
               "the bytecode emitter must fail to compile code that would "
               "produce JSOP_INITELEM_ARRAY with an index exceeding "
               "int32_t range");
    MOZ_ASSERT(uint32_t(index.toInt32()) == GET_UINT32(pc));
    if (!InitArrayElemOperation(cx, pc, obj, index.toInt32(), rhs)) {
      return false;
    }
  } else if (op == JSOP_INITELEM_INC) {
    if (!InitArrayElemOperation(cx, pc, obj, index.toInt32(), rhs)) {
      return false;
    }
  } else {
    if (!SetObjectElement(cx, obj, index, rhs, objv,
                          JSOp(*pc) == JSOP_STRICTSETELEM, script, pc)) {
      return false;
    }
  }

  // Don't try to attach stubs that wish to be hidden. We don't know how to
  // have different enumerability in the stubs for the moment.
  if (op == JSOP_INITHIDDENELEM) {
    return true;
  }

  // Overwrite the object on the stack (pushed for the decompiler) with the rhs.
  MOZ_ASSERT(stack[2] == objv);
  stack[2] = rhs;

  if (attached) {
    return true;
  }

  // The SetObjectElement call might have entered this IC recursively, so try
  // to transition.
  if (stub->state().maybeTransition()) {
    stub->discardStubs(cx);
  }

  if (stub->state().canAttachStub()) {
    SetPropIRGenerator gen(cx, script, pc, CacheKind::SetElem,
                           stub->state().mode(), &isTemporarilyUnoptimizable,
                           &canAddSlot, objv, index, rhs);
    if (canAddSlot && gen.tryAttachAddSlotStub(oldGroup, oldShape)) {
      ICStub* newStub = AttachBaselineCacheIRStub(
          cx, gen.writerRef(), gen.cacheKind(),
          BaselineCacheIRStubKind::Updated, frame->script(), stub, &attached);
      if (newStub) {
        JitSpew(JitSpew_BaselineIC, "  Attached SetElem CacheIR stub");

        SetUpdateStubData(newStub->toCacheIR_Updated(), gen.typeCheckInfo());

        if (gen.shouldNotePreliminaryObjectStub()) {
          newStub->toCacheIR_Updated()->notePreliminaryObject();
        } else if (gen.shouldUnlinkPreliminaryObjectStubs()) {
          StripPreliminaryObjectStubs(cx, stub);
        }
        return true;
      }
    } else {
      gen.trackAttached(IRGenerator::NotAttached);
    }
    if (!attached && !isTemporarilyUnoptimizable) {
      stub->state().trackNotAttached();
    }
  }

  return true;
}

bool ICSetElem_Fallback::Compiler::generateStubCode(MacroAssembler& masm) {
  MOZ_ASSERT(R0 == JSReturnOperand);

  EmitRestoreTailCallReg(masm);

  // State: R0: object, R1: index, stack: rhs.
  // For the decompiler, the stack has to be: object, index, rhs,
  // so we push the index, then overwrite the rhs Value with R0
  // and push the rhs value.
  masm.pushValue(R1);
  masm.loadValue(Address(masm.getStackPointer(), sizeof(Value)), R1);
  masm.storeValue(R0, Address(masm.getStackPointer(), sizeof(Value)));
  masm.pushValue(R1);

  // Push arguments.
  masm.pushValue(R1);  // RHS

  // Push index. On x86 and ARM two push instructions are emitted so use a
  // separate register to store the old stack pointer.
  masm.moveStackPtrTo(R1.scratchReg());
  masm.pushValue(Address(R1.scratchReg(), 2 * sizeof(Value)));
  masm.pushValue(R0);  // Object.

  // Push pointer to stack values, so that the stub can overwrite the object
  // (pushed for the decompiler) with the rhs.
  masm.computeEffectiveAddress(
      Address(masm.getStackPointer(), 3 * sizeof(Value)), R0.scratchReg());
  masm.push(R0.scratchReg());

  masm.push(ICStubReg);
  pushStubPayload(masm, R0.scratchReg());

  using Fn = bool (*)(JSContext*, BaselineFrame*, ICSetElem_Fallback*, Value*,
                      HandleValue, HandleValue, HandleValue);
  return tailCallVM<Fn, DoSetElemFallback>(masm);
}

void ICScript::noteHasDenseAdd(uint32_t pcOffset) {
  ICEntry& entry = icEntryFromPCOffset(pcOffset);
  ICFallbackStub* stub = entry.fallbackStub();

  if (stub->isSetElem_Fallback()) {
    stub->toSetElem_Fallback()->noteHasDenseAdd();
  }
}

template <typename T>
void EmitICUnboxedPreBarrier(MacroAssembler& masm, const T& address,
                             JSValueType type) {
  if (type == JSVAL_TYPE_OBJECT) {
    EmitPreBarrier(masm, address, MIRType::Object);
  } else if (type == JSVAL_TYPE_STRING) {
    EmitPreBarrier(masm, address, MIRType::String);
  } else {
    MOZ_ASSERT(!UnboxedTypeNeedsPreBarrier(type));
  }
}

template void EmitICUnboxedPreBarrier(MacroAssembler& masm,
                                      const Address& address, JSValueType type);

template void EmitICUnboxedPreBarrier(MacroAssembler& masm,
                                      const BaseIndex& address,
                                      JSValueType type);

template <typename T>
void StoreToTypedArray(JSContext* cx, MacroAssembler& masm, Scalar::Type type,
                       const ValueOperand& value, const T& dest,
                       Register scratch, Label* failure) {
  Label done;

  if (type == Scalar::Float32 || type == Scalar::Float64) {
    masm.ensureDouble(value, FloatReg0, failure);
    if (type == Scalar::Float32) {
      ScratchFloat32Scope fpscratch(masm);
      masm.convertDoubleToFloat32(FloatReg0, fpscratch);
      masm.storeToTypedFloatArray(type, fpscratch, dest);
    } else {
      masm.storeToTypedFloatArray(type, FloatReg0, dest);
    }
  } else if (type == Scalar::Uint8Clamped) {
    Label notInt32;
    masm.branchTestInt32(Assembler::NotEqual, value, &notInt32);
    masm.unboxInt32(value, scratch);
    masm.clampIntToUint8(scratch);

    Label clamped;
    masm.bind(&clamped);
    masm.storeToTypedIntArray(type, scratch, dest);
    masm.jump(&done);

    // If the value is a double, clamp to uint8 and jump back.
    // Else, jump to failure.
    masm.bind(&notInt32);
    masm.branchTestDouble(Assembler::NotEqual, value, failure);
    masm.unboxDouble(value, FloatReg0);
    masm.clampDoubleToUint8(FloatReg0, scratch);
    masm.jump(&clamped);
  } else {
    Label notInt32;
    masm.branchTestInt32(Assembler::NotEqual, value, &notInt32);
    masm.unboxInt32(value, scratch);

    Label isInt32;
    masm.bind(&isInt32);
    masm.storeToTypedIntArray(type, scratch, dest);
    masm.jump(&done);

    // If the value is a double, truncate and jump back.
    // Else, jump to failure.
    masm.bind(&notInt32);
    masm.branchTestDouble(Assembler::NotEqual, value, failure);
    masm.unboxDouble(value, FloatReg0);
    masm.branchTruncateDoubleMaybeModUint32(FloatReg0, scratch, failure);
    masm.jump(&isInt32);
  }

  masm.bind(&done);
}

template void StoreToTypedArray(JSContext* cx, MacroAssembler& masm,
                                Scalar::Type type, const ValueOperand& value,
                                const Address& dest, Register scratch,
                                Label* failure);

template void StoreToTypedArray(JSContext* cx, MacroAssembler& masm,
                                Scalar::Type type, const ValueOperand& value,
                                const BaseIndex& dest, Register scratch,
                                Label* failure);

//
// In_Fallback
//

bool DoInFallback(JSContext* cx, BaselineFrame* frame, ICIn_Fallback* stub,
                  HandleValue key, HandleValue objValue,
                  MutableHandleValue res) {
  stub->incrementEnteredCount();

  FallbackICSpew(cx, stub, "In");

  if (!objValue.isObject()) {
    ReportInNotObjectError(cx, key, -2, objValue, -1);
    return false;
  }

  TryAttachStub<HasPropIRGenerator>("In", cx, frame, stub,
                                    BaselineCacheIRStubKind::Regular,
                                    CacheKind::In, key, objValue);

  RootedObject obj(cx, &objValue.toObject());
  bool cond = false;
  if (!OperatorIn(cx, key, obj, &cond)) {
    return false;
  }
  res.setBoolean(cond);

  return true;
}

bool ICIn_Fallback::Compiler::generateStubCode(MacroAssembler& masm) {
  EmitRestoreTailCallReg(masm);

  // Sync for the decompiler.
  masm.pushValue(R0);
  masm.pushValue(R1);

  // Push arguments.
  masm.pushValue(R1);
  masm.pushValue(R0);
  masm.push(ICStubReg);
  pushStubPayload(masm, R0.scratchReg());

  using Fn = bool (*)(JSContext*, BaselineFrame*, ICIn_Fallback*, HandleValue,
                      HandleValue, MutableHandleValue);
  return tailCallVM<Fn, DoInFallback>(masm);
}

//
// HasOwn_Fallback
//

bool DoHasOwnFallback(JSContext* cx, BaselineFrame* frame,
                      ICHasOwn_Fallback* stub, HandleValue keyValue,
                      HandleValue objValue, MutableHandleValue res) {
  stub->incrementEnteredCount();

  FallbackICSpew(cx, stub, "HasOwn");

  TryAttachStub<HasPropIRGenerator>("HasOwn", cx, frame, stub,
                                    BaselineCacheIRStubKind::Regular,
                                    CacheKind::HasOwn, keyValue, objValue);

  bool found;
  if (!HasOwnProperty(cx, objValue, keyValue, &found)) {
    return false;
  }

  res.setBoolean(found);
  return true;
}

bool ICHasOwn_Fallback::Compiler::generateStubCode(MacroAssembler& masm) {
  EmitRestoreTailCallReg(masm);

  // Sync for the decompiler.
  masm.pushValue(R0);
  masm.pushValue(R1);

  // Push arguments.
  masm.pushValue(R1);
  masm.pushValue(R0);
  masm.push(ICStubReg);
  pushStubPayload(masm, R0.scratchReg());

  using Fn = bool (*)(JSContext*, BaselineFrame*, ICHasOwn_Fallback*,
                      HandleValue, HandleValue, MutableHandleValue);
  return tailCallVM<Fn, DoHasOwnFallback>(masm);
}

//
// GetName_Fallback
//

bool DoGetNameFallback(JSContext* cx, BaselineFrame* frame,
                       ICGetName_Fallback* stub, HandleObject envChain,
                       MutableHandleValue res) {
  stub->incrementEnteredCount();

  RootedScript script(cx, frame->script());
  jsbytecode* pc = stub->icEntry()->pc(script);
  mozilla::DebugOnly<JSOp> op = JSOp(*pc);
  FallbackICSpew(cx, stub, "GetName(%s)", CodeName[JSOp(*pc)]);

  MOZ_ASSERT(op == JSOP_GETNAME || op == JSOP_GETGNAME);

  RootedPropertyName name(cx, script->getName(pc));

  TryAttachStub<GetNameIRGenerator>("GetName", cx, frame, stub,
                                    BaselineCacheIRStubKind::Monitored,
                                    envChain, name);

  static_assert(JSOP_GETGNAME_LENGTH == JSOP_GETNAME_LENGTH,
                "Otherwise our check for JSOP_TYPEOF isn't ok");
  if (JSOp(pc[JSOP_GETGNAME_LENGTH]) == JSOP_TYPEOF) {
    if (!GetEnvironmentName<GetNameMode::TypeOf>(cx, envChain, name, res)) {
      return false;
    }
  } else {
    if (!GetEnvironmentName<GetNameMode::Normal>(cx, envChain, name, res)) {
      return false;
    }
  }

  StackTypeSet* types = TypeScript::BytecodeTypes(script, pc);
  TypeScript::Monitor(cx, script, pc, types, res);

  // Add a type monitor stub for the resulting value.
  if (!stub->addMonitorStubForValue(cx, frame, types, res)) {
    return false;
  }

  return true;
}

bool ICGetName_Fallback::Compiler::generateStubCode(MacroAssembler& masm) {
  MOZ_ASSERT(R0 == JSReturnOperand);

  EmitRestoreTailCallReg(masm);

  masm.push(R0.scratchReg());
  masm.push(ICStubReg);
  pushStubPayload(masm, R0.scratchReg());

  using Fn = bool (*)(JSContext*, BaselineFrame*, ICGetName_Fallback*,
                      HandleObject, MutableHandleValue);
  return tailCallVM<Fn, DoGetNameFallback>(masm);
}

//
// BindName_Fallback
//

bool DoBindNameFallback(JSContext* cx, BaselineFrame* frame,
                        ICBindName_Fallback* stub, HandleObject envChain,
                        MutableHandleValue res) {
  stub->incrementEnteredCount();

  jsbytecode* pc = stub->icEntry()->pc(frame->script());
  mozilla::DebugOnly<JSOp> op = JSOp(*pc);
  FallbackICSpew(cx, stub, "BindName(%s)", CodeName[JSOp(*pc)]);

  MOZ_ASSERT(op == JSOP_BINDNAME || op == JSOP_BINDGNAME);

  RootedPropertyName name(cx, frame->script()->getName(pc));

  TryAttachStub<BindNameIRGenerator>("BindName", cx, frame, stub,
                                     BaselineCacheIRStubKind::Regular, envChain,
                                     name);

  RootedObject scope(cx);
  if (!LookupNameUnqualified(cx, name, envChain, &scope)) {
    return false;
  }

  res.setObject(*scope);
  return true;
}

bool ICBindName_Fallback::Compiler::generateStubCode(MacroAssembler& masm) {
  MOZ_ASSERT(R0 == JSReturnOperand);

  EmitRestoreTailCallReg(masm);

  masm.push(R0.scratchReg());
  masm.push(ICStubReg);
  pushStubPayload(masm, R0.scratchReg());

  using Fn = bool (*)(JSContext*, BaselineFrame*, ICBindName_Fallback*,
                      HandleObject, MutableHandleValue);
  return tailCallVM<Fn, DoBindNameFallback>(masm);
}

//
// GetIntrinsic_Fallback
//

bool DoGetIntrinsicFallback(JSContext* cx, BaselineFrame* frame,
                            ICGetIntrinsic_Fallback* stub,
                            MutableHandleValue res) {
  stub->incrementEnteredCount();

  RootedScript script(cx, frame->script());
  jsbytecode* pc = stub->icEntry()->pc(script);
  mozilla::DebugOnly<JSOp> op = JSOp(*pc);
  FallbackICSpew(cx, stub, "GetIntrinsic(%s)", CodeName[JSOp(*pc)]);

  MOZ_ASSERT(op == JSOP_GETINTRINSIC);

  if (!GetIntrinsicOperation(cx, script, pc, res)) {
    return false;
  }

  // An intrinsic operation will always produce the same result, so only
  // needs to be monitored once. Attach a stub to load the resulting constant
  // directly.

  TypeScript::Monitor(cx, script, pc, res);

  TryAttachStub<GetIntrinsicIRGenerator>("GetIntrinsic", cx, frame, stub,
                                         BaselineCacheIRStubKind::Regular, res);

  return true;
}

bool ICGetIntrinsic_Fallback::Compiler::generateStubCode(MacroAssembler& masm) {
  EmitRestoreTailCallReg(masm);

  masm.push(ICStubReg);
  pushStubPayload(masm, R0.scratchReg());

  using Fn = bool (*)(JSContext*, BaselineFrame*, ICGetIntrinsic_Fallback*,
                      MutableHandleValue);
  return tailCallVM<Fn, DoGetIntrinsicFallback>(masm);
}

//
// GetProp_Fallback
//

static bool ComputeGetPropResult(JSContext* cx, BaselineFrame* frame, JSOp op,
                                 HandlePropertyName name,
                                 MutableHandleValue val,
                                 MutableHandleValue res) {
  // Handle arguments.length and arguments.callee on optimized arguments, as
  // it is not an object.
  if (val.isMagic(JS_OPTIMIZED_ARGUMENTS) && IsOptimizedArguments(frame, val)) {
    if (op == JSOP_LENGTH) {
      res.setInt32(frame->numActualArgs());
    } else {
      MOZ_ASSERT(name == cx->names().callee);
      MOZ_ASSERT(frame->script()->hasMappedArgsObj());
      res.setObject(*frame->callee());
    }
  } else {
    if (op == JSOP_GETBOUNDNAME) {
      RootedObject env(cx, &val.toObject());
      RootedId id(cx, NameToId(name));
      if (!GetNameBoundInEnvironment(cx, env, id, res)) {
        return false;
      }
    } else {
      MOZ_ASSERT(op == JSOP_GETPROP || op == JSOP_CALLPROP ||
                 op == JSOP_LENGTH);
      if (!GetProperty(cx, val, name, res)) {
        return false;
      }
    }
  }

  return true;
}

bool DoGetPropFallback(JSContext* cx, BaselineFrame* frame,
                       ICGetProp_Fallback* stub, MutableHandleValue val,
                       MutableHandleValue res) {
  stub->incrementEnteredCount();

  RootedScript script(cx, frame->script());
  jsbytecode* pc = stub->icEntry()->pc(script);
  JSOp op = JSOp(*pc);
  FallbackICSpew(cx, stub, "GetProp(%s)", CodeName[op]);

  MOZ_ASSERT(op == JSOP_GETPROP || op == JSOP_CALLPROP || op == JSOP_LENGTH ||
             op == JSOP_GETBOUNDNAME);

  RootedPropertyName name(cx, script->getName(pc));

  // There are some reasons we can fail to attach a stub that are temporary.
  // We want to avoid calling noteUnoptimizableAccess() if the reason we
  // failed to attach a stub is one of those temporary reasons, since we might
  // end up attaching a stub for the exact same access later.
  bool isTemporarilyUnoptimizable = false;

  if (stub->state().maybeTransition()) {
    stub->discardStubs(cx);
  }

  bool attached = false;
  if (stub->state().canAttachStub()) {
    RootedValue idVal(cx, StringValue(name));
    GetPropIRGenerator gen(cx, script, pc, CacheKind::GetProp,
                           stub->state().mode(), &isTemporarilyUnoptimizable,
                           val, idVal, val, GetPropertyResultFlags::All);
    if (gen.tryAttachStub()) {
      ICStub* newStub = AttachBaselineCacheIRStub(
          cx, gen.writerRef(), gen.cacheKind(),
          BaselineCacheIRStubKind::Monitored, script, stub, &attached);
      if (newStub) {
        JitSpew(JitSpew_BaselineIC, "  Attached GetProp CacheIR stub");
        if (gen.shouldNotePreliminaryObjectStub()) {
          newStub->toCacheIR_Monitored()->notePreliminaryObject();
        } else if (gen.shouldUnlinkPreliminaryObjectStubs()) {
          StripPreliminaryObjectStubs(cx, stub);
        }
      }
    }
    if (!attached && !isTemporarilyUnoptimizable) {
      stub->state().trackNotAttached();
    }
  }

  if (!ComputeGetPropResult(cx, frame, op, name, val, res)) {
    return false;
  }

  StackTypeSet* types = TypeScript::BytecodeTypes(script, pc);
  TypeScript::Monitor(cx, script, pc, types, res);

  // Add a type monitor stub for the resulting value.
  if (!stub->addMonitorStubForValue(cx, frame, types, res)) {
    return false;
  }
  return true;
}

bool DoGetPropSuperFallback(JSContext* cx, BaselineFrame* frame,
                            ICGetProp_Fallback* stub, HandleValue receiver,
                            MutableHandleValue val, MutableHandleValue res) {
  stub->incrementEnteredCount();

  RootedScript script(cx, frame->script());
  jsbytecode* pc = stub->icEntry()->pc(script);
  FallbackICSpew(cx, stub, "GetPropSuper(%s)", CodeName[JSOp(*pc)]);

  MOZ_ASSERT(JSOp(*pc) == JSOP_GETPROP_SUPER);

  RootedPropertyName name(cx, script->getName(pc));

  // There are some reasons we can fail to attach a stub that are temporary.
  // We want to avoid calling noteUnoptimizableAccess() if the reason we
  // failed to attach a stub is one of those temporary reasons, since we might
  // end up attaching a stub for the exact same access later.
  bool isTemporarilyUnoptimizable = false;

  if (stub->state().maybeTransition()) {
    stub->discardStubs(cx);
  }

  bool attached = false;
  if (stub->state().canAttachStub()) {
    RootedValue idVal(cx, StringValue(name));
    GetPropIRGenerator gen(cx, script, pc, CacheKind::GetPropSuper,
                           stub->state().mode(), &isTemporarilyUnoptimizable,
                           val, idVal, receiver, GetPropertyResultFlags::All);
    if (gen.tryAttachStub()) {
      ICStub* newStub = AttachBaselineCacheIRStub(
          cx, gen.writerRef(), gen.cacheKind(),
          BaselineCacheIRStubKind::Monitored, script, stub, &attached);
      if (newStub) {
        JitSpew(JitSpew_BaselineIC, "  Attached GetPropSuper CacheIR stub");
        if (gen.shouldNotePreliminaryObjectStub()) {
          newStub->toCacheIR_Monitored()->notePreliminaryObject();
        } else if (gen.shouldUnlinkPreliminaryObjectStubs()) {
          StripPreliminaryObjectStubs(cx, stub);
        }
      }
    }
    if (!attached && !isTemporarilyUnoptimizable) {
      stub->state().trackNotAttached();
    }
  }

  // |val| is [[HomeObject]].[[Prototype]] which must be Object
  RootedObject valObj(cx, &val.toObject());
  if (!GetProperty(cx, valObj, receiver, name, res)) {
    return false;
  }

  StackTypeSet* types = TypeScript::BytecodeTypes(script, pc);
  TypeScript::Monitor(cx, script, pc, types, res);

  // Add a type monitor stub for the resulting value.
  if (!stub->addMonitorStubForValue(cx, frame, types, res)) {
    return false;
  }

  return true;
}

bool ICGetProp_Fallback::Compiler::generateStubCode(MacroAssembler& masm) {
  MOZ_ASSERT(R0 == JSReturnOperand);

  EmitRestoreTailCallReg(masm);

  // Super property getters use a |this| that differs from base object
  if (hasReceiver_) {
    // Push arguments.
    masm.pushValue(R0);
    masm.pushValue(R1);
    masm.push(ICStubReg);
    masm.pushBaselineFramePtr(BaselineFrameReg, R0.scratchReg());

    using Fn = bool (*)(JSContext*, BaselineFrame*, ICGetProp_Fallback*,
                        HandleValue, MutableHandleValue, MutableHandleValue);
    if (!tailCallVM<Fn, DoGetPropSuperFallback>(masm)) {
      return false;
    }
  } else {
    // Ensure stack is fully synced for the expression decompiler.
    masm.pushValue(R0);

    // Push arguments.
    masm.pushValue(R0);
    masm.push(ICStubReg);
    masm.pushBaselineFramePtr(BaselineFrameReg, R0.scratchReg());

    using Fn = bool (*)(JSContext*, BaselineFrame*, ICGetProp_Fallback*,
                        MutableHandleValue, MutableHandleValue);
    if (!tailCallVM<Fn, DoGetPropFallback>(masm)) {
      return false;
    }
  }

  // This is the resume point used when bailout rewrites call stack to undo
  // Ion inlined frames. The return address pushed onto reconstructed stack
  // will point here.
  assumeStubFrame();
  bailoutReturnOffset_.bind(masm.currentOffset());

  leaveStubFrame(masm, true);

  // When we get here, ICStubReg contains the ICGetProp_Fallback stub,
  // which we can't use to enter the TypeMonitor IC, because it's a
  // MonitoredFallbackStub instead of a MonitoredStub. So, we cheat. Note that
  // we must have a non-null fallbackMonitorStub here because InitFromBailout
  // delazifies.
  masm.loadPtr(Address(ICStubReg,
                       ICMonitoredFallbackStub::offsetOfFallbackMonitorStub()),
               ICStubReg);
  EmitEnterTypeMonitorIC(masm,
                         ICTypeMonitor_Fallback::offsetOfFirstMonitorStub());

  return true;
}

void ICGetProp_Fallback::Compiler::postGenerateStubCode(MacroAssembler& masm,
                                                        Handle<JitCode*> code) {
  BailoutReturnStub kind = hasReceiver_ ? BailoutReturnStub::GetPropSuper
                                        : BailoutReturnStub::GetProp;
  void* address = code->raw() + bailoutReturnOffset_.offset();
  cx->realm()->jitRealm()->initBailoutReturnAddr(address, getKey(), kind);
}

//
// SetProp_Fallback
//

bool DoSetPropFallback(JSContext* cx, BaselineFrame* frame,
                       ICSetProp_Fallback* stub, Value* stack, HandleValue lhs,
                       HandleValue rhs) {
  stub->incrementEnteredCount();

  RootedScript script(cx, frame->script());
  jsbytecode* pc = stub->icEntry()->pc(script);
  JSOp op = JSOp(*pc);
  FallbackICSpew(cx, stub, "SetProp(%s)", CodeName[op]);

  MOZ_ASSERT(op == JSOP_SETPROP || op == JSOP_STRICTSETPROP ||
             op == JSOP_SETNAME || op == JSOP_STRICTSETNAME ||
             op == JSOP_SETGNAME || op == JSOP_STRICTSETGNAME ||
             op == JSOP_INITPROP || op == JSOP_INITLOCKEDPROP ||
             op == JSOP_INITHIDDENPROP || op == JSOP_INITGLEXICAL);

  RootedPropertyName name(cx, script->getName(pc));
  RootedId id(cx, NameToId(name));

  RootedObject obj(cx, ToObjectFromStack(cx, lhs));
  if (!obj) {
    return false;
  }
  RootedShape oldShape(cx, obj->maybeShape());
  RootedObjectGroup oldGroup(cx, JSObject::getGroup(cx, obj));
  if (!oldGroup) {
    return false;
  }

  if (obj->is<UnboxedPlainObject>()) {
    MOZ_ASSERT(!oldShape);
    if (UnboxedExpandoObject* expando =
            obj->as<UnboxedPlainObject>().maybeExpando()) {
      oldShape = expando->lastProperty();
    }
  }

  // There are some reasons we can fail to attach a stub that are temporary.
  // We want to avoid calling noteUnoptimizableAccess() if the reason we
  // failed to attach a stub is one of those temporary reasons, since we might
  // end up attaching a stub for the exact same access later.
  bool isTemporarilyUnoptimizable = false;
  bool canAddSlot = false;

  bool attached = false;
  if (stub->state().maybeTransition()) {
    stub->discardStubs(cx);
  }

  if (stub->state().canAttachStub()) {
    RootedValue idVal(cx, StringValue(name));
    SetPropIRGenerator gen(cx, script, pc, CacheKind::SetProp,
                           stub->state().mode(), &isTemporarilyUnoptimizable,
                           &canAddSlot, lhs, idVal, rhs);
    if (gen.tryAttachStub()) {
      ICStub* newStub = AttachBaselineCacheIRStub(
          cx, gen.writerRef(), gen.cacheKind(),
          BaselineCacheIRStubKind::Updated, frame->script(), stub, &attached);
      if (newStub) {
        JitSpew(JitSpew_BaselineIC, "  Attached SetProp CacheIR stub");

        SetUpdateStubData(newStub->toCacheIR_Updated(), gen.typeCheckInfo());

        if (gen.shouldNotePreliminaryObjectStub()) {
          newStub->toCacheIR_Updated()->notePreliminaryObject();
        } else if (gen.shouldUnlinkPreliminaryObjectStubs()) {
          StripPreliminaryObjectStubs(cx, stub);
        }
      }
    }
  }

  if (op == JSOP_INITPROP || op == JSOP_INITLOCKEDPROP ||
      op == JSOP_INITHIDDENPROP) {
    if (!InitPropertyOperation(cx, op, obj, name, rhs)) {
      return false;
    }
  } else if (op == JSOP_SETNAME || op == JSOP_STRICTSETNAME ||
             op == JSOP_SETGNAME || op == JSOP_STRICTSETGNAME) {
    if (!SetNameOperation(cx, script, pc, obj, rhs)) {
      return false;
    }
  } else if (op == JSOP_INITGLEXICAL) {
    RootedValue v(cx, rhs);
    LexicalEnvironmentObject* lexicalEnv;
    if (script->hasNonSyntacticScope()) {
      lexicalEnv = &NearestEnclosingExtensibleLexicalEnvironment(
          frame->environmentChain());
    } else {
      lexicalEnv = &cx->global()->lexicalEnvironment();
    }
    InitGlobalLexicalOperation(cx, lexicalEnv, script, pc, v);
  } else {
    MOZ_ASSERT(op == JSOP_SETPROP || op == JSOP_STRICTSETPROP);

    ObjectOpResult result;
    if (!SetProperty(cx, obj, id, rhs, lhs, result) ||
        !result.checkStrictErrorOrWarning(cx, obj, id,
                                          op == JSOP_STRICTSETPROP)) {
      return false;
    }
  }

  // Overwrite the LHS on the stack (pushed for the decompiler) with the RHS.
  MOZ_ASSERT(stack[1] == lhs);
  stack[1] = rhs;

  if (attached) {
    return true;
  }

  // The SetProperty call might have entered this IC recursively, so try
  // to transition.
  if (stub->state().maybeTransition()) {
    stub->discardStubs(cx);
  }

  if (stub->state().canAttachStub()) {
    RootedValue idVal(cx, StringValue(name));
    SetPropIRGenerator gen(cx, script, pc, CacheKind::SetProp,
                           stub->state().mode(), &isTemporarilyUnoptimizable,
                           &canAddSlot, lhs, idVal, rhs);
    if (canAddSlot && gen.tryAttachAddSlotStub(oldGroup, oldShape)) {
      ICStub* newStub = AttachBaselineCacheIRStub(
          cx, gen.writerRef(), gen.cacheKind(),
          BaselineCacheIRStubKind::Updated, frame->script(), stub, &attached);
      if (newStub) {
        JitSpew(JitSpew_BaselineIC, "  Attached SetProp CacheIR stub");

        SetUpdateStubData(newStub->toCacheIR_Updated(), gen.typeCheckInfo());

        if (gen.shouldNotePreliminaryObjectStub()) {
          newStub->toCacheIR_Updated()->notePreliminaryObject();
        } else if (gen.shouldUnlinkPreliminaryObjectStubs()) {
          StripPreliminaryObjectStubs(cx, stub);
        }
      }
    } else {
      gen.trackAttached(IRGenerator::NotAttached);
    }
    if (!attached && !isTemporarilyUnoptimizable) {
      stub->state().trackNotAttached();
    }
  }

  return true;
}

bool ICSetProp_Fallback::Compiler::generateStubCode(MacroAssembler& masm) {
  MOZ_ASSERT(R0 == JSReturnOperand);

  EmitRestoreTailCallReg(masm);

  // Ensure stack is fully synced for the expression decompiler.
  // Overwrite the RHS value on top of the stack with the object, then push
  // the RHS in R1 on top of that.
  masm.storeValue(R0, Address(masm.getStackPointer(), 0));
  masm.pushValue(R1);

  // Push arguments.
  masm.pushValue(R1);
  masm.pushValue(R0);

  // Push pointer to stack values, so that the stub can overwrite the object
  // (pushed for the decompiler) with the RHS.
  masm.computeEffectiveAddress(
      Address(masm.getStackPointer(), 2 * sizeof(Value)), R0.scratchReg());
  masm.push(R0.scratchReg());

  masm.push(ICStubReg);
  pushStubPayload(masm, R0.scratchReg());

  using Fn = bool (*)(JSContext*, BaselineFrame*, ICSetProp_Fallback*, Value*,
                      HandleValue, HandleValue);
  if (!tailCallVM<Fn, DoSetPropFallback>(masm)) {
    return false;
  }

  // This is the resume point used when bailout rewrites call stack to undo
  // Ion inlined frames. The return address pushed onto reconstructed stack
  // will point here.
  assumeStubFrame();
  bailoutReturnOffset_.bind(masm.currentOffset());

  leaveStubFrame(masm, true);
  EmitReturnFromIC(masm);

  return true;
}

void ICSetProp_Fallback::Compiler::postGenerateStubCode(MacroAssembler& masm,
                                                        Handle<JitCode*> code) {
  BailoutReturnStub kind = BailoutReturnStub::SetProp;
  void* address = code->raw() + bailoutReturnOffset_.offset();
  cx->realm()->jitRealm()->initBailoutReturnAddr(address, getKey(), kind);
}

//
// Call_Fallback
//

static bool TryAttachFunApplyStub(JSContext* cx, ICCall_Fallback* stub,
                                  HandleScript script, jsbytecode* pc,
                                  HandleValue thisv, uint32_t argc, Value* argv,
                                  ICTypeMonitor_Fallback* typeMonitorFallback,
                                  bool* attached) {
  if (argc != 2) {
    return true;
  }

  if (!thisv.isObject() || !thisv.toObject().is<JSFunction>()) {
    return true;
  }
  RootedFunction target(cx, &thisv.toObject().as<JSFunction>());

  // right now, only handle situation where second argument is |arguments|
  if (argv[1].isMagic(JS_OPTIMIZED_ARGUMENTS) && !script->needsArgsObj()) {
    if (target->hasJitEntry() &&
        !stub->hasStub(ICStub::Call_ScriptedApplyArguments)) {
      JitSpew(JitSpew_BaselineIC,
              "  Generating Call_ScriptedApplyArguments stub");

      ICCall_ScriptedApplyArguments::Compiler compiler(
          cx, typeMonitorFallback->firstMonitorStub(), script->pcToOffset(pc));
      ICStub* newStub = compiler.getStub(compiler.getStubSpace(script));
      if (!newStub) {
        return false;
      }

      stub->addNewStub(newStub);
      *attached = true;
      return true;
    }

    // TODO: handle FUNAPPLY for native targets.
  }

  if (argv[1].isObject() && argv[1].toObject().is<ArrayObject>()) {
    if (target->hasJitEntry() &&
        !stub->hasStub(ICStub::Call_ScriptedApplyArray)) {
      JitSpew(JitSpew_BaselineIC, "  Generating Call_ScriptedApplyArray stub");

      ICCall_ScriptedApplyArray::Compiler compiler(
          cx, typeMonitorFallback->firstMonitorStub(), script->pcToOffset(pc));
      ICStub* newStub = compiler.getStub(compiler.getStubSpace(script));
      if (!newStub) {
        return false;
      }

      stub->addNewStub(newStub);
      *attached = true;
      return true;
    }
  }
  return true;
}

static bool TryAttachFunCallStub(JSContext* cx, ICCall_Fallback* stub,
                                 HandleScript script, jsbytecode* pc,
                                 HandleValue thisv,
                                 ICTypeMonitor_Fallback* typeMonitorFallback,
                                 bool* attached) {
  // Try to attach a stub for Function.prototype.call with scripted |this|.

  *attached = false;
  if (!thisv.isObject() || !thisv.toObject().is<JSFunction>()) {
    return true;
  }
  RootedFunction target(cx, &thisv.toObject().as<JSFunction>());

  // Attach a stub if the script can be Baseline-compiled. We do this also
  // if the script is not yet compiled to avoid attaching a CallNative stub
  // that handles everything, even after the callee becomes hot.
  if (((target->hasScript() && target->nonLazyScript()->canBaselineCompile()) ||
       (target->isNativeWithJitEntry())) &&
      !stub->hasStub(ICStub::Call_ScriptedFunCall)) {
    JitSpew(JitSpew_BaselineIC, "  Generating Call_ScriptedFunCall stub");

    ICCall_ScriptedFunCall::Compiler compiler(
        cx, typeMonitorFallback->firstMonitorStub(), script->pcToOffset(pc));
    ICStub* newStub = compiler.getStub(compiler.getStubSpace(script));
    if (!newStub) {
      return false;
    }

    *attached = true;
    stub->addNewStub(newStub);
    return true;
  }

  return true;
}

static bool GetTemplateObjectForNative(JSContext* cx, HandleFunction target,
                                       const CallArgs& args,
                                       MutableHandleObject res) {
  if (!target->hasJitInfo() ||
      target->jitInfo()->type() != JSJitInfo::InlinableNative) {
    return true;
  }

  // Check for natives to which template objects can be attached. This is
  // done to provide templates to Ion for inlining these natives later on.
  switch (target->jitInfo()->inlinableNative) {
    case InlinableNative::Array: {
      // Note: the template array won't be used if its length is inaccurately
      // computed here.  (We allocate here because compilation may occur on a
      // separate thread where allocation is impossible.)
      size_t count = 0;
      if (args.length() != 1) {
        count = args.length();
      } else if (args.length() == 1 && args[0].isInt32() &&
                 args[0].toInt32() >= 0) {
        count = args[0].toInt32();
      }

      if (count > ArrayObject::EagerAllocationMaxLength) {
        return true;
      }

      // With this and other array templates, analyze the group so that
      // we don't end up with a template whose structure might change later.
      res.set(NewFullyAllocatedArrayForCallingAllocationSite(cx, count,
                                                             TenuredObject));
      return !!res;
    }

    case InlinableNative::ArraySlice: {
      if (!args.thisv().isObject()) {
        return true;
      }

      RootedObject obj(cx, &args.thisv().toObject());
      if (obj->isSingleton()) {
        return true;
      }

      res.set(NewFullyAllocatedArrayTryReuseGroup(cx, obj, 0, TenuredObject));
      return !!res;
    }

    case InlinableNative::String: {
      RootedString emptyString(cx, cx->runtime()->emptyString);
      res.set(StringObject::create(cx, emptyString, /* proto = */ nullptr,
                                   TenuredObject));
      return !!res;
    }

    case InlinableNative::ObjectCreate: {
      if (args.length() != 1 || !args[0].isObjectOrNull()) {
        return true;
      }
      RootedObject proto(cx, args[0].toObjectOrNull());
      res.set(ObjectCreateImpl(cx, proto, TenuredObject));
      return !!res;
    }

    case InlinableNative::IntrinsicNewArrayIterator: {
      res.set(NewArrayIteratorObject(cx, TenuredObject));
      return !!res;
    }

    case InlinableNative::IntrinsicNewStringIterator: {
      res.set(NewStringIteratorObject(cx, TenuredObject));
      return !!res;
    }

    case InlinableNative::IntrinsicNewRegExpStringIterator: {
      res.set(NewRegExpStringIteratorObject(cx, TenuredObject));
      return !!res;
    }

    case InlinableNative::TypedArrayConstructor: {
      return TypedArrayObject::GetTemplateObjectForNative(cx, target->native(),
                                                          args, res);
    }

    default:
      return true;
  }
}

static bool GetTemplateObjectForClassHook(JSContext* cx, JSNative hook,
                                          CallArgs& args,
                                          MutableHandleObject templateObject) {
  if (args.callee().nonCCWRealm() != cx->realm()) {
    return true;
  }

  if (hook == TypedObject::construct) {
    Rooted<TypeDescr*> descr(cx, &args.callee().as<TypeDescr>());
    templateObject.set(TypedObject::createZeroed(cx, descr, gc::TenuredHeap));
    return !!templateObject;
  }

  return true;
}

static bool IsOptimizableConstStringSplit(Realm* callerRealm,
                                          const Value& callee, int argc,
                                          Value* args) {
  if (argc != 2 || !args[0].isString() || !args[1].isString()) {
    return false;
  }

  if (!args[0].toString()->isAtom() || !args[1].toString()->isAtom()) {
    return false;
  }

  if (!callee.isObject() || !callee.toObject().is<JSFunction>()) {
    return false;
  }

  JSFunction& calleeFun = callee.toObject().as<JSFunction>();
  if (calleeFun.realm() != callerRealm) {
    return false;
  }
  if (!calleeFun.isNative() ||
      calleeFun.native() != js::intrinsic_StringSplitString) {
    return false;
  }

  return true;
}

static bool TryAttachCallStub(JSContext* cx, ICCall_Fallback* stub,
                              HandleScript script, jsbytecode* pc, JSOp op,
                              uint32_t argc, Value* vp, bool constructing,
                              bool isSpread, bool createSingleton,
                              bool* handled) {
  bool isSuper = op == JSOP_SUPERCALL || op == JSOP_SPREADSUPERCALL;

  if (createSingleton || op == JSOP_EVAL || op == JSOP_STRICTEVAL) {
    return true;
  }

  if (stub->numOptimizedStubs() >= ICCall_Fallback::MAX_OPTIMIZED_STUBS) {
    // TODO: Discard all stubs in this IC and replace with inert megamorphic
    // stub. But for now we just bail.
    return true;
  }

  RootedValue callee(cx, vp[0]);
  RootedValue thisv(cx, vp[1]);

  // Don't attach an optimized call stub if we could potentially attach an
  // optimized ConstStringSplit stub.
  if (stub->numOptimizedStubs() == 0 &&
      IsOptimizableConstStringSplit(cx->realm(), callee, argc, vp + 2)) {
    return true;
  }

  stub->unlinkStubsWithKind(cx, ICStub::Call_ConstStringSplit);

  if (!callee.isObject()) {
    return true;
  }

  ICTypeMonitor_Fallback* typeMonitorFallback =
      stub->getFallbackMonitorStub(cx, script);
  if (!typeMonitorFallback) {
    return false;
  }

  RootedObject obj(cx, &callee.toObject());
  if (!obj->is<JSFunction>()) {
    // Try to attach a stub for a call/construct hook on the object.
    if (JSNative hook = constructing ? obj->constructHook() : obj->callHook()) {
      if (op != JSOP_FUNAPPLY && !isSpread && !createSingleton) {
        RootedObject templateObject(cx);
        CallArgs args = CallArgsFromVp(argc, vp);
        if (!GetTemplateObjectForClassHook(cx, hook, args, &templateObject)) {
          return false;
        }

        JitSpew(JitSpew_BaselineIC, "  Generating Call_ClassHook stub");
        ICCall_ClassHook::Compiler compiler(
            cx, typeMonitorFallback->firstMonitorStub(), obj->getClass(), hook,
            templateObject, script->pcToOffset(pc), constructing);
        ICStub* newStub = compiler.getStub(compiler.getStubSpace(script));
        if (!newStub) {
          return false;
        }

        stub->addNewStub(newStub);
        *handled = true;
        return true;
      }
    }
    return true;
  }

  RootedFunction fun(cx, &obj->as<JSFunction>());

  bool nativeWithJitEntry = fun->isNativeWithJitEntry();
  if (fun->isInterpreted() || nativeWithJitEntry) {
    // Never attach optimized scripted call stubs for JSOP_FUNAPPLY.
    // MagicArguments may escape the frame through them.
    if (op == JSOP_FUNAPPLY) {
      return true;
    }

    // If callee is not an interpreted constructor, we have to throw.
    if (constructing && !fun->isConstructor()) {
      return true;
    }

    // Likewise, if the callee is a class constructor, we have to throw.
    if (!constructing && fun->isClassConstructor()) {
      return true;
    }

    if (!fun->hasJitEntry()) {
      // Don't treat this as an unoptimizable case, as we'll add a stub
      // when the callee is delazified.
      *handled = true;
      return true;
    }

    // If we're constructing, require the callee to have JIT code. This
    // isn't required for correctness but avoids allocating a template
    // object below for constructors that aren't hot. See bug 1419758.
    if (constructing && !fun->hasJITCode()) {
      *handled = true;
      return true;
    }

    // Check if this stub chain has already generalized scripted calls.
    if (stub->scriptedStubsAreGeneralized()) {
      JitSpew(JitSpew_BaselineIC,
              "  Chain already has generalized scripted call stub!");
      return true;
    }

    if (stub->state().mode() == ICState::Mode::Megamorphic) {
      // Create a Call_AnyScripted stub.
      JitSpew(JitSpew_BaselineIC,
              "  Generating Call_AnyScripted stub (cons=%s, spread=%s)",
              constructing ? "yes" : "no", isSpread ? "yes" : "no");
      ICCallScriptedCompiler compiler(
          cx, typeMonitorFallback->firstMonitorStub(), constructing, isSpread,
          script->pcToOffset(pc));
      ICStub* newStub = compiler.getStub(compiler.getStubSpace(script));
      if (!newStub) {
        return false;
      }

      // Before adding new stub, unlink all previous Call_Scripted.
      stub->unlinkStubsWithKind(cx, ICStub::Call_Scripted);

      // Add new generalized stub.
      stub->addNewStub(newStub);
      *handled = true;
      return true;
    }

    // Keep track of the function's |prototype| property in type
    // information, for use during Ion compilation.
    if (IsIonEnabled(cx)) {
      EnsureTrackPropertyTypes(cx, fun, NameToId(cx->names().prototype));
    }

    // Remember the template object associated with any script being called
    // as a constructor, for later use during Ion compilation. This is unsound
    // for super(), as a single callsite can have multiple possible prototype
    // object created (via different newTargets)
    RootedObject templateObject(cx);
    if (constructing && !isSuper) {
      // If we are calling a constructor for which the new script
      // properties analysis has not been performed yet, don't attach a
      // stub. After the analysis is performed, CreateThisForFunction may
      // start returning objects with a different type, and the Ion
      // compiler will get confused.

      // Only attach a stub if the function already has a prototype and
      // we can look it up without causing side effects.
      RootedObject newTarget(cx, &vp[2 + argc].toObject());
      RootedValue protov(cx);
      if (!GetPropertyPure(cx, newTarget, NameToId(cx->names().prototype),
                           protov.address())) {
        JitSpew(JitSpew_BaselineIC, "  Can't purely lookup function prototype");
        return true;
      }

      if (protov.isObject()) {
        AutoRealm ar(cx, fun);
        TaggedProto proto(&protov.toObject());
        ObjectGroup* group =
            ObjectGroup::defaultNewGroup(cx, nullptr, proto, newTarget);
        if (!group) {
          return false;
        }

        AutoSweepObjectGroup sweep(group);
        if (group->newScript(sweep) && !group->newScript(sweep)->analyzed()) {
          JitSpew(JitSpew_BaselineIC,
                  "  Function newScript has not been analyzed");

          // This is temporary until the analysis is perfomed, so
          // don't treat this as unoptimizable.
          *handled = true;
          return true;
        }
      }

      JSObject* thisObject =
          CreateThisForFunction(cx, fun, newTarget, TenuredObject);
      if (!thisObject) {
        return false;
      }

      MOZ_ASSERT(thisObject->nonCCWRealm() == fun->realm());

      if (thisObject->is<PlainObject>() ||
          thisObject->is<UnboxedPlainObject>()) {
        templateObject = thisObject;
      }
    }

    if (nativeWithJitEntry) {
      JitSpew(JitSpew_BaselineIC,
              "  Generating Call_Scripted stub (native=%p with jit entry, "
              "cons=%s, spread=%s)",
              fun->native(), constructing ? "yes" : "no",
              isSpread ? "yes" : "no");
    } else {
      JitSpew(JitSpew_BaselineIC,
              "  Generating Call_Scripted stub (fun=%p, %s:%u:%u, cons=%s, "
              "spread=%s)",
              fun.get(), fun->nonLazyScript()->filename(),
              fun->nonLazyScript()->lineno(), fun->nonLazyScript()->column(),
              constructing ? "yes" : "no", isSpread ? "yes" : "no");
    }

    bool isCrossRealm = cx->realm() != fun->realm();
    ICCallScriptedCompiler compiler(cx, typeMonitorFallback->firstMonitorStub(),
                                    fun, templateObject, constructing, isSpread,
                                    isCrossRealm, script->pcToOffset(pc));
    ICStub* newStub = compiler.getStub(compiler.getStubSpace(script));
    if (!newStub) {
      return false;
    }

    stub->addNewStub(newStub);
    *handled = true;
    return true;
  }

  if (fun->isNative() &&
      (!constructing || (constructing && fun->isConstructor()))) {
    // Generalized native call stubs are not here yet!
    MOZ_ASSERT(!stub->nativeStubsAreGeneralized());

    // Check for JSOP_FUNAPPLY
    if (op == JSOP_FUNAPPLY) {
      if (fun->native() == fun_apply) {
        return TryAttachFunApplyStub(cx, stub, script, pc, thisv, argc, vp + 2,
                                     typeMonitorFallback, handled);
      }

      // Don't try to attach a "regular" optimized call stubs for FUNAPPLY ops,
      // since MagicArguments may escape through them.
      return true;
    }

    if (op == JSOP_FUNCALL && fun->native() == fun_call) {
      if (!TryAttachFunCallStub(cx, stub, script, pc, thisv,
                                typeMonitorFallback, handled)) {
        return false;
      }
      if (*handled) {
        return true;
      }
    }

    if (stub->state().mode() == ICState::Mode::Megamorphic) {
      JitSpew(JitSpew_BaselineIC,
              "  Megamorphic Call_Native stubs. TODO: add Call_AnyNative!");
      return true;
    }

    bool isCrossRealm = cx->realm() != fun->realm();

    RootedObject templateObject(cx);
    if (MOZ_LIKELY(!isSpread && !isSuper)) {
      CallArgs args = CallArgsFromVp(argc, vp);
      AutoRealm ar(cx, fun);
      if (!GetTemplateObjectForNative(cx, fun, args, &templateObject)) {
        return false;
      }
      MOZ_ASSERT_IF(templateObject,
                    !templateObject->group()
                         ->maybePreliminaryObjectsDontCheckGeneration());
    }

    bool ignoresReturnValue =
        op == JSOP_CALL_IGNORES_RV && fun->isNative() && fun->hasJitInfo() &&
        fun->jitInfo()->type() == JSJitInfo::IgnoresReturnValueNative;

    JitSpew(JitSpew_BaselineIC,
            "  Generating Call_Native stub (fun=%p, cons=%s, spread=%s)",
            fun.get(), constructing ? "yes" : "no", isSpread ? "yes" : "no");
    ICCall_Native::Compiler compiler(
        cx, typeMonitorFallback->firstMonitorStub(), fun, templateObject,
        constructing, ignoresReturnValue, isSpread, isCrossRealm,
        script->pcToOffset(pc));
    ICStub* newStub = compiler.getStub(compiler.getStubSpace(script));
    if (!newStub) {
      return false;
    }

    stub->addNewStub(newStub);
    *handled = true;
    return true;
  }

  return true;
}

static bool TryAttachConstStringSplit(JSContext* cx, ICCall_Fallback* stub,
                                      HandleScript script, uint32_t argc,
                                      HandleValue callee, Value* vp,
                                      jsbytecode* pc, HandleValue res,
                                      bool* attached) {
  if (stub->numOptimizedStubs() != 0) {
    return true;
  }

  Value* args = vp + 2;

  if (!IsOptimizableConstStringSplit(cx->realm(), callee, argc, args)) {
    return true;
  }

  RootedString str(cx, args[0].toString());
  RootedString sep(cx, args[1].toString());
  RootedArrayObject obj(cx, &res.toObject().as<ArrayObject>());
  uint32_t initLength = obj->getDenseInitializedLength();
  MOZ_ASSERT(initLength == obj->length(),
             "string-split result is a fully initialized array");

  // Copy the array before storing in stub.
  RootedArrayObject arrObj(cx);
  arrObj =
      NewFullyAllocatedArrayTryReuseGroup(cx, obj, initLength, TenuredObject);
  if (!arrObj) {
    return false;
  }
  arrObj->ensureDenseInitializedLength(cx, 0, initLength);

  // Atomize all elements of the array.
  if (initLength > 0) {
    // Mimic NewFullyAllocatedStringArray() and directly inform TI about
    // the element type.
    AddTypePropertyId(cx, arrObj, JSID_VOID, TypeSet::StringType());

    for (uint32_t i = 0; i < initLength; i++) {
      JSAtom* str = js::AtomizeString(cx, obj->getDenseElement(i).toString());
      if (!str) {
        return false;
      }

      arrObj->initDenseElement(i, StringValue(str));
    }
  }

  ICTypeMonitor_Fallback* typeMonitorFallback =
      stub->getFallbackMonitorStub(cx, script);
  if (!typeMonitorFallback) {
    return false;
  }

  ICCall_ConstStringSplit::Compiler compiler(
      cx, typeMonitorFallback->firstMonitorStub(), script->pcToOffset(pc), str,
      sep, arrObj);
  ICStub* newStub = compiler.getStub(compiler.getStubSpace(script));
  if (!newStub) {
    return false;
  }

  stub->addNewStub(newStub);
  *attached = true;
  return true;
}

bool DoCallFallback(JSContext* cx, BaselineFrame* frame, ICCall_Fallback* stub,
                    uint32_t argc, Value* vp, MutableHandleValue res) {
  stub->incrementEnteredCount();

  RootedScript script(cx, frame->script());
  jsbytecode* pc = stub->icEntry()->pc(script);
  JSOp op = JSOp(*pc);
  FallbackICSpew(cx, stub, "Call(%s)", CodeName[op]);

  MOZ_ASSERT(argc == GET_ARGC(pc));
  bool constructing = (op == JSOP_NEW || op == JSOP_SUPERCALL);
  bool ignoresReturnValue = (op == JSOP_CALL_IGNORES_RV);

  // Ensure vp array is rooted - we may GC in here.
  size_t numValues = argc + 2 + constructing;
  AutoArrayRooter vpRoot(cx, numValues, vp);

  CallArgs callArgs = CallArgsFromSp(argc + constructing, vp + numValues,
                                     constructing, ignoresReturnValue);
  RootedValue callee(cx, vp[0]);

  // Handle funapply with JSOP_ARGUMENTS
  if (op == JSOP_FUNAPPLY && argc == 2 &&
      callArgs[1].isMagic(JS_OPTIMIZED_ARGUMENTS)) {
    if (!GuardFunApplyArgumentsOptimization(cx, frame, callArgs)) {
      return false;
    }
  }

  // Transition stub state to megamorphic or generic if warranted.
  if (stub->state().maybeTransition()) {
    stub->discardStubs(cx);
  }

  bool canAttachStub = stub->state().canAttachStub();
  bool handled = false;

  // Only bother to try optimizing JSOP_CALL with CacheIR if the chain is still
  // allowed to attach stubs.
  if (canAttachStub) {
    CallIRGenerator gen(cx, script, pc, op, stub->state().mode(), argc, callee,
                        callArgs.thisv(),
                        HandleValueArray::fromMarkedLocation(argc, vp + 2));
    if (gen.tryAttachStub()) {
      ICStub* newStub = AttachBaselineCacheIRStub(
          cx, gen.writerRef(), gen.cacheKind(), gen.cacheIRStubKind(), script,
          stub, &handled);

      if (newStub) {
        JitSpew(JitSpew_BaselineIC, "  Attached Call CacheIR stub");

        // If it's an updated stub, initialize it.
        if (gen.cacheIRStubKind() == BaselineCacheIRStubKind::Updated) {
          SetUpdateStubData(newStub->toCacheIR_Updated(), gen.typeCheckInfo());
        }
      }
    }

    // Try attaching a regular call stub, but only if the CacheIR attempt didn't
    // add any stubs.
    if (!handled) {
      bool createSingleton =
          ObjectGroup::useSingletonForNewObject(cx, script, pc);
      if (!TryAttachCallStub(cx, stub, script, pc, op, argc, vp, constructing,
                             false, createSingleton, &handled)) {
        return false;
      }
    }
  }

  if (constructing) {
    if (!ConstructFromStack(cx, callArgs)) {
      return false;
    }
    res.set(callArgs.rval());
  } else if ((op == JSOP_EVAL || op == JSOP_STRICTEVAL) &&
             cx->global()->valueIsEval(callee)) {
    if (!DirectEval(cx, callArgs.get(0), res)) {
      return false;
    }
  } else {
    MOZ_ASSERT(op == JSOP_CALL || op == JSOP_CALL_IGNORES_RV ||
               op == JSOP_CALLITER || op == JSOP_FUNCALL ||
               op == JSOP_FUNAPPLY || op == JSOP_EVAL || op == JSOP_STRICTEVAL);
    if (op == JSOP_CALLITER && callee.isPrimitive()) {
      MOZ_ASSERT(argc == 0, "thisv must be on top of the stack");
      ReportValueError(cx, JSMSG_NOT_ITERABLE, -1, callArgs.thisv(), nullptr);
      return false;
    }

    if (!CallFromStack(cx, callArgs)) {
      return false;
    }

    res.set(callArgs.rval());
  }

  StackTypeSet* types = TypeScript::BytecodeTypes(script, pc);
  TypeScript::Monitor(cx, script, pc, types, res);

  // Add a type monitor stub for the resulting value.
  if (!stub->addMonitorStubForValue(cx, frame, types, res)) {
    return false;
  }

  // Try to transition again in case we called this IC recursively.
  if (stub->state().maybeTransition()) {
    stub->discardStubs(cx);
  }
  canAttachStub = stub->state().canAttachStub();

  if (!handled && canAttachStub && !constructing) {
    // If 'callee' is a potential Call_ConstStringSplit, try to attach an
    // optimized ConstStringSplit stub. Note that vp[0] now holds the return
    // value instead of the callee, so we pass the callee as well.
    if (!TryAttachConstStringSplit(cx, stub, script, argc, callee, vp, pc, res,
                                   &handled)) {
      return false;
    }
  }

  if (!handled) {
    if (canAttachStub) {
      stub->state().trackNotAttached();
    }
  }
  return true;
}

bool DoSpreadCallFallback(JSContext* cx, BaselineFrame* frame,
                          ICCall_Fallback* stub, Value* vp,
                          MutableHandleValue res) {
  stub->incrementEnteredCount();

  RootedScript script(cx, frame->script());
  jsbytecode* pc = stub->icEntry()->pc(script);
  JSOp op = JSOp(*pc);
  bool constructing = (op == JSOP_SPREADNEW || op == JSOP_SPREADSUPERCALL);
  FallbackICSpew(cx, stub, "SpreadCall(%s)", CodeName[op]);

  // Ensure vp array is rooted - we may GC in here.
  AutoArrayRooter vpRoot(cx, 3 + constructing, vp);

  RootedValue callee(cx, vp[0]);
  RootedValue thisv(cx, vp[1]);
  RootedValue arr(cx, vp[2]);
  RootedValue newTarget(cx, constructing ? vp[3] : NullValue());

  // Try attaching a call stub.
  bool handled = false;
  if (op != JSOP_SPREADEVAL && op != JSOP_STRICTSPREADEVAL &&
      !TryAttachCallStub(cx, stub, script, pc, op, 1, vp, constructing, true,
                         false, &handled)) {
    return false;
  }

  if (!SpreadCallOperation(cx, script, pc, thisv, callee, arr, newTarget,
                           res)) {
    return false;
  }

  // Add a type monitor stub for the resulting value.
  StackTypeSet* types = TypeScript::BytecodeTypes(script, pc);
  if (!stub->addMonitorStubForValue(cx, frame, types, res)) {
    return false;
  }

  return true;
}

void ICCallStubCompiler::pushCallArguments(MacroAssembler& masm,
                                           AllocatableGeneralRegisterSet regs,
                                           Register argcReg, bool isJitCall,
                                           bool isConstructing) {
  MOZ_ASSERT(!regs.has(argcReg));

  // Account for new.target
  Register count = regs.takeAny();

  masm.move32(argcReg, count);

  // If we are setting up for a jitcall, we have to align the stack taking
  // into account the args and newTarget. We could also count callee and |this|,
  // but it's a waste of stack space. Because we want to keep argcReg unchanged,
  // just account for newTarget initially, and add the other 2 after assuring
  // allignment.
  if (isJitCall) {
    if (isConstructing) {
      masm.add32(Imm32(1), count);
    }
  } else {
    masm.add32(Imm32(2 + isConstructing), count);
  }

  // argPtr initially points to the last argument.
  Register argPtr = regs.takeAny();
  masm.moveStackPtrTo(argPtr);

  // Skip 4 pointers pushed on top of the arguments: the frame descriptor,
  // return address, old frame pointer and stub reg.
  masm.addPtr(Imm32(STUB_FRAME_SIZE), argPtr);

  // Align the stack such that the JitFrameLayout is aligned on the
  // JitStackAlignment.
  if (isJitCall) {
    masm.alignJitStackBasedOnNArgs(count);

    // Account for callee and |this|, skipped earlier
    masm.add32(Imm32(2), count);
  }

  // Push all values, starting at the last one.
  Label loop, done;
  masm.bind(&loop);
  masm.branchTest32(Assembler::Zero, count, count, &done);
  {
    masm.pushValue(Address(argPtr, 0));
    masm.addPtr(Imm32(sizeof(Value)), argPtr);

    masm.sub32(Imm32(1), count);
    masm.jump(&loop);
  }
  masm.bind(&done);
}

void ICCallStubCompiler::guardSpreadCall(MacroAssembler& masm, Register argcReg,
                                         Label* failure, bool isConstructing) {
  masm.unboxObject(Address(masm.getStackPointer(),
                           isConstructing * sizeof(Value) + ICStackValueOffset),
                   argcReg);
  masm.loadPtr(Address(argcReg, NativeObject::offsetOfElements()), argcReg);
  masm.load32(Address(argcReg, ObjectElements::offsetOfLength()), argcReg);

  // Limit actual argc to something reasonable (huge number of arguments can
  // blow the stack limit).
  static_assert(ICCall_Scripted::MAX_ARGS_SPREAD_LENGTH <= ARGS_LENGTH_MAX,
                "maximum arguments length for optimized stub should be <= "
                "ARGS_LENGTH_MAX");
  masm.branch32(Assembler::Above, argcReg,
                Imm32(ICCall_Scripted::MAX_ARGS_SPREAD_LENGTH), failure);
}

void ICCallStubCompiler::pushSpreadCallArguments(
    MacroAssembler& masm, AllocatableGeneralRegisterSet regs, Register argcReg,
    bool isJitCall, bool isConstructing) {
  // Pull the array off the stack before aligning.
  Register startReg = regs.takeAny();
  masm.unboxObject(Address(masm.getStackPointer(),
                           (isConstructing * sizeof(Value)) + STUB_FRAME_SIZE),
                   startReg);
  masm.loadPtr(Address(startReg, NativeObject::offsetOfElements()), startReg);

  // Align the stack such that the JitFrameLayout is aligned on the
  // JitStackAlignment.
  if (isJitCall) {
    Register alignReg = argcReg;
    if (isConstructing) {
      alignReg = regs.takeAny();
      masm.movePtr(argcReg, alignReg);
      masm.addPtr(Imm32(1), alignReg);
    }
    masm.alignJitStackBasedOnNArgs(alignReg);
    if (isConstructing) {
      MOZ_ASSERT(alignReg != argcReg);
      regs.add(alignReg);
    }
  }

  // Push newTarget, if necessary
  if (isConstructing) {
    masm.pushValue(Address(BaselineFrameReg, STUB_FRAME_SIZE));
  }

  // Push arguments: set up endReg to point to &array[argc]
  Register endReg = regs.takeAny();
  masm.movePtr(argcReg, endReg);
  static_assert(sizeof(Value) == 8, "Value must be 8 bytes");
  masm.lshiftPtr(Imm32(3), endReg);
  masm.addPtr(startReg, endReg);

  // Copying pre-decrements endReg by 8 until startReg is reached
  Label copyDone;
  Label copyStart;
  masm.bind(&copyStart);
  masm.branchPtr(Assembler::Equal, endReg, startReg, &copyDone);
  masm.subPtr(Imm32(sizeof(Value)), endReg);
  masm.pushValue(Address(endReg, 0));
  masm.jump(&copyStart);
  masm.bind(&copyDone);

  regs.add(startReg);
  regs.add(endReg);

  // Push the callee and |this|.
  masm.pushValue(
      Address(BaselineFrameReg,
              STUB_FRAME_SIZE + (1 + isConstructing) * sizeof(Value)));
  masm.pushValue(
      Address(BaselineFrameReg,
              STUB_FRAME_SIZE + (2 + isConstructing) * sizeof(Value)));
}

Register ICCallStubCompiler::guardFunApply(MacroAssembler& masm,
                                           AllocatableGeneralRegisterSet regs,
                                           Register argcReg,
                                           FunApplyThing applyThing,
                                           Label* failure) {
  // Ensure argc == 2
  masm.branch32(Assembler::NotEqual, argcReg, Imm32(2), failure);

  // Stack looks like:
  //      [..., CalleeV, ThisV, Arg0V, Arg1V <MaybeReturnReg>]

  Address secondArgSlot(masm.getStackPointer(), ICStackValueOffset);
  if (applyThing == FunApply_MagicArgs) {
    // Ensure that the second arg is magic arguments.
    masm.branchTestMagic(Assembler::NotEqual, secondArgSlot, failure);

    // Ensure that this frame doesn't have an arguments object.
    masm.branchTest32(
        Assembler::NonZero,
        Address(BaselineFrameReg, BaselineFrame::reverseOffsetOfFlags()),
        Imm32(BaselineFrame::HAS_ARGS_OBJ), failure);

    // Limit the length to something reasonable.
    masm.branch32(
        Assembler::Above,
        Address(BaselineFrameReg, BaselineFrame::offsetOfNumActualArgs()),
        Imm32(ICCall_ScriptedApplyArray::MAX_ARGS_ARRAY_LENGTH), failure);
  } else {
    MOZ_ASSERT(applyThing == FunApply_Array);

    AllocatableGeneralRegisterSet regsx = regs;

    // Ensure that the second arg is an array.
    ValueOperand secondArgVal = regsx.takeAnyValue();
    masm.loadValue(secondArgSlot, secondArgVal);

    masm.branchTestObject(Assembler::NotEqual, secondArgVal, failure);
    Register secondArgObj = masm.extractObject(secondArgVal, ExtractTemp1);

    regsx.add(secondArgVal);
    regsx.takeUnchecked(secondArgObj);

    masm.branchTestObjClass(Assembler::NotEqual, secondArgObj,
                            &ArrayObject::class_, regsx.getAny(), secondArgObj,
                            failure);

    // Get the array elements and ensure that initializedLength == length
    masm.loadPtr(Address(secondArgObj, NativeObject::offsetOfElements()),
                 secondArgObj);

    Register lenReg = regsx.takeAny();
    masm.load32(Address(secondArgObj, ObjectElements::offsetOfLength()),
                lenReg);

    masm.branch32(
        Assembler::NotEqual,
        Address(secondArgObj, ObjectElements::offsetOfInitializedLength()),
        lenReg, failure);

    // Limit the length to something reasonable (huge number of arguments can
    // blow the stack limit).
    masm.branch32(Assembler::Above, lenReg,
                  Imm32(ICCall_ScriptedApplyArray::MAX_ARGS_ARRAY_LENGTH),
                  failure);

    // Ensure no holes.  Loop through values in array and make sure none are
    // magic. Start address is secondArgObj, end address is secondArgObj +
    // (lenReg * sizeof(Value))
    static_assert(sizeof(Value) == 8,
                  "shift by 3 below assumes Value is 8 bytes");
    masm.lshiftPtr(Imm32(3), lenReg);
    masm.addPtr(secondArgObj, lenReg);

    Register start = secondArgObj;
    Register end = lenReg;
    Label loop;
    Label endLoop;
    masm.bind(&loop);
    masm.branchPtr(Assembler::AboveOrEqual, start, end, &endLoop);
    masm.branchTestMagic(Assembler::Equal, Address(start, 0), failure);
    masm.addPtr(Imm32(sizeof(Value)), start);
    masm.jump(&loop);
    masm.bind(&endLoop);
  }

  // Stack now confirmed to be like:
  //      [..., CalleeV, ThisV, Arg0V, MagicValue(Arguments), <MaybeReturnAddr>]

  // Load the callee, ensure that it's fun_apply
  ValueOperand val = regs.takeAnyValue();
  Address calleeSlot(masm.getStackPointer(),
                     ICStackValueOffset + (3 * sizeof(Value)));
  masm.loadValue(calleeSlot, val);

  masm.branchTestObject(Assembler::NotEqual, val, failure);
  Register callee = masm.extractObject(val, ExtractTemp1);

  masm.branchTestObjClass(Assembler::NotEqual, callee, &JSFunction::class_,
                          regs.getAny(), callee, failure);
  masm.loadPtr(Address(callee, JSFunction::offsetOfNativeOrEnv()), callee);

  masm.branchPtr(Assembler::NotEqual, callee, ImmPtr(fun_apply), failure);

  // Load the |thisv|, ensure that it's a scripted function with a valid
  // baseline or ion script, or a native function.
  Address thisSlot(masm.getStackPointer(),
                   ICStackValueOffset + (2 * sizeof(Value)));
  masm.loadValue(thisSlot, val);

  masm.branchTestObject(Assembler::NotEqual, val, failure);
  Register target = masm.extractObject(val, ExtractTemp1);
  regs.add(val);
  regs.takeUnchecked(target);

  masm.branchTestObjClass(Assembler::NotEqual, target, &JSFunction::class_,
                          regs.getAny(), target, failure);

  Register temp = regs.takeAny();
  masm.branchIfFunctionHasNoJitEntry(target, /* constructing */ false, failure);
  masm.branchFunctionKind(Assembler::Equal, JSFunction::ClassConstructor,
                          callee, temp, failure);
  regs.add(temp);
  return target;
}

void ICCallStubCompiler::pushCallerArguments(
    MacroAssembler& masm, AllocatableGeneralRegisterSet regs) {
  // Initialize copyReg to point to start caller arguments vector.
  // Initialize argcReg to poitn to the end of it.
  Register startReg = regs.takeAny();
  Register endReg = regs.takeAny();
  masm.loadPtr(Address(BaselineFrameReg, 0), startReg);
  masm.loadPtr(Address(startReg, BaselineFrame::offsetOfNumActualArgs()),
               endReg);
  masm.addPtr(Imm32(BaselineFrame::offsetOfArg(0)), startReg);
  masm.alignJitStackBasedOnNArgs(endReg);
  masm.lshiftPtr(Imm32(ValueShift), endReg);
  masm.addPtr(startReg, endReg);

  // Copying pre-decrements endReg by 8 until startReg is reached
  Label copyDone;
  Label copyStart;
  masm.bind(&copyStart);
  masm.branchPtr(Assembler::Equal, endReg, startReg, &copyDone);
  masm.subPtr(Imm32(sizeof(Value)), endReg);
  masm.pushValue(Address(endReg, 0));
  masm.jump(&copyStart);
  masm.bind(&copyDone);
}

void ICCallStubCompiler::pushArrayArguments(
    MacroAssembler& masm, Address arrayVal,
    AllocatableGeneralRegisterSet regs) {
  // Load start and end address of values to copy.
  // guardFunApply has already gauranteed that the array is packed and contains
  // no holes.
  Register startReg = regs.takeAny();
  Register endReg = regs.takeAny();
  masm.unboxObject(arrayVal, startReg);
  masm.loadPtr(Address(startReg, NativeObject::offsetOfElements()), startReg);
  masm.load32(Address(startReg, ObjectElements::offsetOfInitializedLength()),
              endReg);
  masm.alignJitStackBasedOnNArgs(endReg);
  masm.lshiftPtr(Imm32(ValueShift), endReg);
  masm.addPtr(startReg, endReg);

  // Copying pre-decrements endReg by 8 until startReg is reached
  Label copyDone;
  Label copyStart;
  masm.bind(&copyStart);
  masm.branchPtr(Assembler::Equal, endReg, startReg, &copyDone);
  masm.subPtr(Imm32(sizeof(Value)), endReg);
  masm.pushValue(Address(endReg, 0));
  masm.jump(&copyStart);
  masm.bind(&copyDone);
}

bool ICCall_Fallback::Compiler::generateStubCode(MacroAssembler& masm) {
  MOZ_ASSERT(R0 == JSReturnOperand);

  // Values are on the stack left-to-right. Calling convention wants them
  // right-to-left so duplicate them on the stack in reverse order.
  // |this| and callee are pushed last.

  AllocatableGeneralRegisterSet regs(availableGeneralRegs(0));

  if (MOZ_UNLIKELY(isSpread_)) {
    // Push a stub frame so that we can perform a non-tail call.
    enterStubFrame(masm, R1.scratchReg());

    // Use BaselineFrameReg instead of BaselineStackReg, because
    // BaselineFrameReg and BaselineStackReg hold the same value just after
    // calling enterStubFrame.

    // newTarget
    if (isConstructing_) {
      masm.pushValue(Address(BaselineFrameReg, STUB_FRAME_SIZE));
    }

    // array
    uint32_t valueOffset = isConstructing_;
    masm.pushValue(Address(BaselineFrameReg,
                           valueOffset++ * sizeof(Value) + STUB_FRAME_SIZE));

    // this
    masm.pushValue(Address(BaselineFrameReg,
                           valueOffset++ * sizeof(Value) + STUB_FRAME_SIZE));

    // callee
    masm.pushValue(Address(BaselineFrameReg,
                           valueOffset++ * sizeof(Value) + STUB_FRAME_SIZE));

    masm.push(masm.getStackPointer());
    masm.push(ICStubReg);

    PushStubPayload(masm, R0.scratchReg());

    using Fn = bool (*)(JSContext*, BaselineFrame*, ICCall_Fallback*, Value*,
                        MutableHandleValue);
    if (!callVM<Fn, DoSpreadCallFallback>(masm)) {
      return false;
    }

    leaveStubFrame(masm);
    EmitReturnFromIC(masm);

    // SPREADCALL is not yet supported in Ion, so do not generate asmcode for
    // bailout.
    return true;
  }

  // Push a stub frame so that we can perform a non-tail call.
  enterStubFrame(masm, R1.scratchReg());

  regs.take(R0.scratchReg());  // argc.

  pushCallArguments(masm, regs, R0.scratchReg(), /* isJitCall = */ false,
                    isConstructing_);

  masm.push(masm.getStackPointer());
  masm.push(R0.scratchReg());
  masm.push(ICStubReg);

  PushStubPayload(masm, R0.scratchReg());

  using Fn = bool (*)(JSContext*, BaselineFrame*, ICCall_Fallback*, uint32_t,
                      Value*, MutableHandleValue);
  if (!callVM<Fn, DoCallFallback>(masm)) {
    return false;
  }

  leaveStubFrame(masm);
  EmitReturnFromIC(masm);

  // This is the resume point used when bailout rewrites call stack to undo
  // Ion inlined frames. The return address pushed onto reconstructed stack
  // will point here.
  assumeStubFrame();
  bailoutReturnOffset_.bind(masm.currentOffset());

  // Load passed-in ThisV into R1 just in case it's needed.  Need to do this
  // before we leave the stub frame since that info will be lost.
  // Current stack:  [...., ThisV, ActualArgc, CalleeToken, Descriptor ]
  masm.loadValue(Address(masm.getStackPointer(), 3 * sizeof(size_t)), R1);

  leaveStubFrame(masm, true);

  // If this is a |constructing| call, if the callee returns a non-object, we
  // replace it with the |this| object passed in.
  if (isConstructing_) {
    MOZ_ASSERT(JSReturnOperand == R0);
    Label skipThisReplace;

    masm.branchTestObject(Assembler::Equal, JSReturnOperand, &skipThisReplace);
    masm.moveValue(R1, R0);
#ifdef DEBUG
    masm.branchTestObject(Assembler::Equal, JSReturnOperand, &skipThisReplace);
    masm.assumeUnreachable("Failed to return object in constructing call.");
#endif
    masm.bind(&skipThisReplace);
  }

  // At this point, ICStubReg points to the ICCall_Fallback stub, which is NOT
  // a MonitoredStub, but rather a MonitoredFallbackStub.  To use
  // EmitEnterTypeMonitorIC, first load the ICTypeMonitor_Fallback stub into
  // ICStubReg.  Then, use EmitEnterTypeMonitorIC with a custom struct offset.
  // Note that we must have a non-null fallbackMonitorStub here because
  // InitFromBailout delazifies.
  masm.loadPtr(Address(ICStubReg,
                       ICMonitoredFallbackStub::offsetOfFallbackMonitorStub()),
               ICStubReg);
  EmitEnterTypeMonitorIC(masm,
                         ICTypeMonitor_Fallback::offsetOfFirstMonitorStub());

  return true;
}

void ICCall_Fallback::Compiler::postGenerateStubCode(MacroAssembler& masm,
                                                     Handle<JitCode*> code) {
  if (MOZ_UNLIKELY(isSpread_)) {
    return;
  }

  void* address = code->raw() + bailoutReturnOffset_.offset();
  BailoutReturnStub kind =
      isConstructing_ ? BailoutReturnStub::New : BailoutReturnStub::Call;
  cx->realm()->jitRealm()->initBailoutReturnAddr(address, getKey(), kind);
}

bool ICCallScriptedCompiler::generateStubCode(MacroAssembler& masm) {
  Label failure;
  AllocatableGeneralRegisterSet regs(availableGeneralRegs(0));
  bool canUseTailCallReg = regs.has(ICTailCallReg);

  Register argcReg = R0.scratchReg();
  regs.take(argcReg);
  regs.takeUnchecked(ICTailCallReg);

  if (isSpread_) {
    guardSpreadCall(masm, argcReg, &failure, isConstructing_);
  }

  // Load the callee in R1, accounting for newTarget, if necessary
  // Stack Layout:
  //      [ ..., CalleeVal, ThisVal, Arg0Val, ..., ArgNVal, [newTarget],
  //        +ICStackValueOffset+ ]
  if (isSpread_) {
    unsigned skipToCallee = (2 + isConstructing_) * sizeof(Value);
    masm.loadValue(
        Address(masm.getStackPointer(), skipToCallee + ICStackValueOffset), R1);
  } else {
    // Account for newTarget, if necessary
    unsigned nonArgsSkip = (1 + isConstructing_) * sizeof(Value);
    BaseValueIndex calleeSlot(masm.getStackPointer(), argcReg,
                              ICStackValueOffset + nonArgsSkip);
    masm.loadValue(calleeSlot, R1);
  }
  regs.take(R1);

  // Ensure callee is an object.
  masm.branchTestObject(Assembler::NotEqual, R1, &failure);

  // Ensure callee is a function.
  Register callee = masm.extractObject(R1, ExtractTemp0);

  // If calling a specific script, check if the script matches.  Otherwise,
  // ensure that callee function is scripted.  Leave calleeScript in |callee|
  // reg.
  if (callee_) {
    MOZ_ASSERT(kind == ICStub::Call_Scripted);

    // Check if the object matches this callee.
    Address expectedCallee(ICStubReg, ICCall_Scripted::offsetOfCallee());
    masm.branchPtr(Assembler::NotEqual, expectedCallee, callee, &failure);

    // Guard against relazification.
    masm.branchIfFunctionHasNoJitEntry(callee, isConstructing_, &failure);
  } else {
    // Ensure the object is a function.
    masm.branchTestObjClass(Assembler::NotEqual, callee, &JSFunction::class_,
                            regs.getAny(), callee, &failure);
    if (isConstructing_) {
      masm.branchIfNotInterpretedConstructor(callee, regs.getAny(), &failure);
    } else {
      masm.branchIfFunctionHasNoJitEntry(callee, /* constructing */ false,
                                         &failure);
      masm.branchFunctionKind(Assembler::Equal, JSFunction::ClassConstructor,
                              callee, regs.getAny(), &failure);
    }
  }

  // Load the start of the target JitCode.
  Register code;
  if (!isConstructing_) {
    code = regs.takeAny();
    masm.loadJitCodeRaw(callee, code);
  }

  // We no longer need R1.
  regs.add(R1);

  // Push a stub frame so that we can perform a non-tail call.
  enterStubFrame(masm, regs.getAny());
  if (canUseTailCallReg) {
    regs.add(ICTailCallReg);
  }

  if (maybeCrossRealm_) {
    masm.switchToObjectRealm(callee, regs.getAny());
  }

  if (isConstructing_) {
    // Save argc before call.
    masm.push(argcReg);

    // Stack now looks like:
    //      [ ..., Callee, ThisV, Arg0V, ..., ArgNV, NewTarget,
    //        StubFrameHeader, ArgC ]
    masm.loadValue(
        Address(masm.getStackPointer(), STUB_FRAME_SIZE + sizeof(size_t)), R1);
    masm.push(masm.extractObject(R1, ExtractTemp0));

    if (isSpread_) {
      masm.loadValue(Address(masm.getStackPointer(),
                             3 * sizeof(Value) + STUB_FRAME_SIZE +
                                 sizeof(size_t) + sizeof(JSObject*)),
                     R1);
    } else {
      BaseValueIndex calleeSlot2(masm.getStackPointer(), argcReg,
                                 2 * sizeof(Value) + STUB_FRAME_SIZE +
                                     sizeof(size_t) + sizeof(JSObject*));
      masm.loadValue(calleeSlot2, R1);
    }
    masm.push(masm.extractObject(R1, ExtractTemp0));

    using Fn = bool (*)(JSContext * cx, HandleObject callee,
                        HandleObject newTarget, MutableHandleValue rval);
    if (!callVM<Fn, CreateThis>(masm)) {
      return false;
    }

    // Return of CreateThis must be an object or uninitialized.
#ifdef DEBUG
    Label createdThisOK;
    masm.branchTestObject(Assembler::Equal, JSReturnOperand, &createdThisOK);
    masm.branchTestMagic(Assembler::Equal, JSReturnOperand, &createdThisOK);
    masm.assumeUnreachable(
        "The return of CreateThis must be an object or uninitialized.");
    masm.bind(&createdThisOK);
#endif

    // Reset the register set from here on in.
    static_assert(JSReturnOperand == R0, "The code below needs to be adapted.");
    regs = availableGeneralRegs(0);
    regs.take(R0);
    argcReg = regs.takeAny();

    // Restore saved argc so we can use it to calculate the address to save
    // the resulting this object to.
    masm.pop(argcReg);

    // Save "this" value back into pushed arguments on stack. R0 can be
    // clobbered after that.
    //
    // Stack now looks like:
    //      [ ..., Callee, ThisV, Arg0V, ..., ArgNV, [NewTarget],
    //        StubFrameHeader ]
    if (isSpread_) {
      masm.storeValue(
          R0, Address(masm.getStackPointer(),
                      (1 + isConstructing_) * sizeof(Value) + STUB_FRAME_SIZE));
    } else {
      BaseValueIndex thisSlot(
          masm.getStackPointer(), argcReg,
          STUB_FRAME_SIZE + isConstructing_ * sizeof(Value));
      masm.storeValue(R0, thisSlot);
    }

    // Restore the stub register from the baseline stub frame.
    masm.loadPtr(Address(masm.getStackPointer(), STUB_FRAME_SAVED_STUB_OFFSET),
                 ICStubReg);

    // Reload callee script. Note that a GC triggered by CreateThis may
    // have destroyed the callee BaselineScript and IonScript. CreateThis
    // is safely repeatable though, so in this case we just leave the stub
    // frame and jump to the next stub.

    // Just need to load the script now.
    if (isSpread_) {
      unsigned skipForCallee = (2 + isConstructing_) * sizeof(Value);
      masm.loadValue(
          Address(masm.getStackPointer(), skipForCallee + STUB_FRAME_SIZE), R0);
    } else {
      // Account for newTarget, if necessary
      unsigned nonArgsSkip = (1 + isConstructing_) * sizeof(Value);
      BaseValueIndex calleeSlot3(masm.getStackPointer(), argcReg,
                                 nonArgsSkip + STUB_FRAME_SIZE);
      masm.loadValue(calleeSlot3, R0);
    }
    callee = masm.extractObject(R0, ExtractTemp0);
    regs.add(R0);
    regs.takeUnchecked(callee);

    code = regs.takeAny();
    masm.loadJitCodeRaw(callee, code);

    // Release callee register, but don't add ExtractTemp0 back into the pool
    // ExtractTemp0 is used later, and if it's allocated to some other register
    // at that point, it will get clobbered when used.
    if (callee != ExtractTemp0) {
      regs.add(callee);
    }

    if (canUseTailCallReg) {
      regs.addUnchecked(ICTailCallReg);
    }
  }
  Register scratch = regs.takeAny();

  // Values are on the stack left-to-right. Calling convention wants them
  // right-to-left so duplicate them on the stack in reverse order.
  // |this| and callee are pushed last.
  if (isSpread_) {
    pushSpreadCallArguments(masm, regs, argcReg, /* isJitCall = */ true,
                            isConstructing_);
  } else {
    pushCallArguments(masm, regs, argcReg, /* isJitCall = */ true,
                      isConstructing_);
  }

  // The callee is on top of the stack. Pop and unbox it.
  ValueOperand val = regs.takeAnyValue();
  masm.popValue(val);
  callee = masm.extractObject(val, ExtractTemp0);

  EmitBaselineCreateStubFrameDescriptor(masm, scratch, JitFrameLayout::Size());

  // Note that we use Push, not push, so that callJit will align the stack
  // properly on ARM.
  masm.Push(argcReg);
  masm.PushCalleeToken(callee, isConstructing_);
  masm.Push(scratch);

  // Handle arguments underflow.
  Label noUnderflow;
  masm.load16ZeroExtend(Address(callee, JSFunction::offsetOfNargs()), callee);
  masm.branch32(Assembler::AboveOrEqual, argcReg, callee, &noUnderflow);
  {
    // Call the arguments rectifier.
    TrampolinePtr argumentsRectifier =
        cx->runtime()->jitRuntime()->getArgumentsRectifier();
    masm.movePtr(argumentsRectifier, code);
  }

  masm.bind(&noUnderflow);
  masm.callJit(code);

  // If this is a constructing call, and the callee returns a non-object,
  // replace it with the |this| object passed in.
  if (isConstructing_) {
    Label skipThisReplace;
    masm.branchTestObject(Assembler::Equal, JSReturnOperand, &skipThisReplace);

    // Current stack: [ Padding?, ARGVALS..., ThisVal, ActualArgc, Callee,
    //                  Descriptor ]
    // However, we can't use this ThisVal, because it hasn't been traced.
    // We need to use the ThisVal higher up the stack:
    // Current stack: [ ThisVal, ARGVALS..., ...STUB FRAME..., Padding?,
    //                  ARGVALS..., ThisVal, ActualArgc, Callee, Descriptor ]

    // Restore the BaselineFrameReg based on the frame descriptor.
    //
    // BaselineFrameReg = BaselineStackReg
    //                  + sizeof(Descriptor)
    //                  + sizeof(Callee)
    //                  + sizeof(ActualArgc)
    //                  + stubFrameSize(Descriptor)
    //                  - sizeof(ICStubReg)
    //                  - sizeof(BaselineFrameReg)
    Address descriptorAddr(masm.getStackPointer(), 0);
    masm.loadPtr(descriptorAddr, BaselineFrameReg);
    masm.rshiftPtr(Imm32(FRAMESIZE_SHIFT), BaselineFrameReg);
    masm.addPtr(Imm32((3 - 2) * sizeof(size_t)), BaselineFrameReg);
    masm.addStackPtrTo(BaselineFrameReg);

    // Load the number of arguments present before the stub frame.
    Register argcReg = JSReturnOperand.scratchReg();
    if (isSpread_) {
      // Account for the Array object.
      masm.move32(Imm32(1), argcReg);
    } else {
      Address argcAddr(masm.getStackPointer(), 2 * sizeof(size_t));
      masm.loadPtr(argcAddr, argcReg);
    }

    // Current stack:
    //      [ ThisVal, ARGVALS..., ...STUB FRAME..., <-- BaselineFrameReg
    //        Padding?, ARGVALS..., ThisVal, ActualArgc, Callee, Descriptor ]
    //
    // &ThisVal = BaselineFrameReg + argc * sizeof(Value) + STUB_FRAME_SIZE +
    // sizeof(Value) This last sizeof(Value) accounts for the newTarget on the
    // end of the arguments vector which is not reflected in actualArgc
    BaseValueIndex thisSlotAddr(BaselineFrameReg, argcReg,
                                STUB_FRAME_SIZE + sizeof(Value));
    masm.loadValue(thisSlotAddr, JSReturnOperand);
#ifdef DEBUG
    masm.branchTestObject(Assembler::Equal, JSReturnOperand, &skipThisReplace);
    masm.assumeUnreachable("Return of constructing call should be an object.");
#endif
    masm.bind(&skipThisReplace);
  }

  leaveStubFrame(masm, true);

  if (maybeCrossRealm_) {
    masm.switchToBaselineFrameRealm(R1.scratchReg());
  }

  // Enter type monitor IC to type-check result.
  EmitEnterTypeMonitorIC(masm);

  masm.bind(&failure);
  EmitStubGuardFailure(masm);
  return true;
}

bool ICCall_ConstStringSplit::Compiler::generateStubCode(MacroAssembler& masm) {
  // Stack Layout:
  //      [ ..., CalleeVal, ThisVal, strVal, sepVal, +ICStackValueOffset+ ]
  static const size_t SEP_DEPTH = 0;
  static const size_t STR_DEPTH = sizeof(Value);
  static const size_t CALLEE_DEPTH = 3 * sizeof(Value);

  AllocatableGeneralRegisterSet regs(availableGeneralRegs(0));
  Label failureRestoreArgc;
#ifdef DEBUG
  Label twoArg;
  Register argcReg = R0.scratchReg();
  masm.branch32(Assembler::Equal, argcReg, Imm32(2), &twoArg);
  masm.assumeUnreachable("Expected argc == 2");
  masm.bind(&twoArg);
#endif
  Register scratchReg = regs.takeAny();

  // Guard that callee is native function js::intrinsic_StringSplitString.
  {
    Address calleeAddr(masm.getStackPointer(),
                       ICStackValueOffset + CALLEE_DEPTH);
    ValueOperand calleeVal = regs.takeAnyValue();

    // Ensure that callee is an object.
    masm.loadValue(calleeAddr, calleeVal);
    masm.branchTestObject(Assembler::NotEqual, calleeVal, &failureRestoreArgc);

    // Ensure that callee is a function.
    Register calleeObj = masm.extractObject(calleeVal, ExtractTemp0);
    masm.branchTestObjClass(Assembler::NotEqual, calleeObj, &JSFunction::class_,
                            scratchReg, calleeObj, &failureRestoreArgc);

    // Ensure that callee's function impl is the native
    // intrinsic_StringSplitString.
    masm.loadPtr(Address(calleeObj, JSFunction::offsetOfNativeOrEnv()),
                 scratchReg);
    masm.branchPtr(Assembler::NotEqual, scratchReg,
                   ImmPtr(js::intrinsic_StringSplitString),
                   &failureRestoreArgc);

    regs.add(calleeVal);
  }

  // Guard sep.
  {
    // Ensure that sep is a string.
    Address sepAddr(masm.getStackPointer(), ICStackValueOffset + SEP_DEPTH);
    ValueOperand sepVal = regs.takeAnyValue();

    masm.loadValue(sepAddr, sepVal);
    masm.branchTestString(Assembler::NotEqual, sepVal, &failureRestoreArgc);

    Register sep = sepVal.scratchReg();
    masm.unboxString(sepVal, sep);
    masm.branchPtr(Assembler::NotEqual,
                   Address(ICStubReg, offsetOfExpectedSep()), sep,
                   &failureRestoreArgc);
    regs.add(sepVal);
  }

  // Guard str.
  {
    // Ensure that str is a string.
    Address strAddr(masm.getStackPointer(), ICStackValueOffset + STR_DEPTH);
    ValueOperand strVal = regs.takeAnyValue();

    masm.loadValue(strAddr, strVal);
    masm.branchTestString(Assembler::NotEqual, strVal, &failureRestoreArgc);

    Register str = strVal.scratchReg();
    masm.unboxString(strVal, str);
    masm.branchPtr(Assembler::NotEqual,
                   Address(ICStubReg, offsetOfExpectedStr()), str,
                   &failureRestoreArgc);
    regs.add(strVal);
  }

  // Main stub body.
  {
    Register paramReg = regs.takeAny();

    // Push arguments.
    enterStubFrame(masm, scratchReg);
    masm.loadPtr(Address(ICStubReg, offsetOfTemplateObject()), paramReg);
    masm.push(paramReg);

    using Fn = bool (*)(JSContext*, HandleArrayObject, MutableHandleValue);
    if (!callVM<Fn, CopyStringSplitArray>(masm)) {
      return false;
    }
    leaveStubFrame(masm);
    regs.add(paramReg);
  }

  // Enter type monitor IC to type-check result.
  EmitEnterTypeMonitorIC(masm);

  // Guard failure path.
  masm.bind(&failureRestoreArgc);
  masm.move32(Imm32(2), R0.scratchReg());
  EmitStubGuardFailure(masm);
  return true;
}

bool ICCall_Native::Compiler::generateStubCode(MacroAssembler& masm) {
  Label failure;
  AllocatableGeneralRegisterSet regs(availableGeneralRegs(0));

  Register argcReg = R0.scratchReg();
  regs.take(argcReg);
  regs.takeUnchecked(ICTailCallReg);

  if (isSpread_) {
    guardSpreadCall(masm, argcReg, &failure, isConstructing_);
  }

  // Load the callee in R1.
  if (isSpread_) {
    unsigned skipToCallee = (2 + isConstructing_) * sizeof(Value);
    masm.loadValue(
        Address(masm.getStackPointer(), skipToCallee + ICStackValueOffset), R1);
  } else {
    unsigned nonArgsSlots = (1 + isConstructing_) * sizeof(Value);
    BaseValueIndex calleeSlot(masm.getStackPointer(), argcReg,
                              ICStackValueOffset + nonArgsSlots);
    masm.loadValue(calleeSlot, R1);
  }
  regs.take(R1);

  masm.branchTestObject(Assembler::NotEqual, R1, &failure);

  // Ensure callee matches this stub's callee.
  Register callee = masm.extractObject(R1, ExtractTemp0);
  Address expectedCallee(ICStubReg, ICCall_Native::offsetOfCallee());
  masm.branchPtr(Assembler::NotEqual, expectedCallee, callee, &failure);

  regs.add(R1);
  regs.takeUnchecked(callee);

  // Push a stub frame so that we can perform a non-tail call.
  // Note that this leaves the return address in TailCallReg.
  enterStubFrame(masm, regs.getAny());

  if (isCrossRealm_) {
    masm.switchToObjectRealm(callee, regs.getAny());
  }

  // Values are on the stack left-to-right. Calling convention wants them
  // right-to-left so duplicate them on the stack in reverse order.
  // |this| and callee are pushed last.
  if (isSpread_) {
    pushSpreadCallArguments(masm, regs, argcReg, /* isJitCall = */ false,
                            isConstructing_);
  } else {
    pushCallArguments(masm, regs, argcReg, /* isJitCall = */ false,
                      isConstructing_);
  }

  // Native functions have the signature:
  //
  //    bool (*)(JSContext*, unsigned, Value* vp)
  //
  // Where vp[0] is space for callee/return value, vp[1] is |this|, and vp[2]
  // onward are the function arguments.

  // Initialize vp.
  Register vpReg = regs.takeAny();
  masm.moveStackPtrTo(vpReg);

  // Construct a native exit frame.
  masm.push(argcReg);

  Register scratch = regs.takeAny();
  EmitBaselineCreateStubFrameDescriptor(masm, scratch, ExitFrameLayout::Size());
  masm.push(scratch);
  masm.push(ICTailCallReg);
  masm.loadJSContext(scratch);
  masm.enterFakeExitFrameForNative(scratch, scratch, isConstructing_);

  // Execute call.
  masm.setupUnalignedABICall(scratch);
  masm.loadJSContext(scratch);
  masm.passABIArg(scratch);
  masm.passABIArg(argcReg);
  masm.passABIArg(vpReg);

#ifdef JS_SIMULATOR
  // The simulator requires VM calls to be redirected to a special swi
  // instruction to handle them, so we store the redirected pointer in the
  // stub and use that instead of the original one.
  masm.callWithABI(Address(ICStubReg, ICCall_Native::offsetOfNative()));
#else
  if (ignoresReturnValue_) {
    MOZ_ASSERT(callee_->hasJitInfo());
    masm.loadPtr(Address(callee, JSFunction::offsetOfJitInfo()), callee);
    masm.callWithABI(
        Address(callee, JSJitInfo::offsetOfIgnoresReturnValueNative()));
  } else {
    masm.callWithABI(Address(callee, JSFunction::offsetOfNative()));
  }
#endif

  // Test for failure.
  masm.branchIfFalseBool(ReturnReg, masm.exceptionLabel());

  // Load the return value into R0.
  masm.loadValue(
      Address(masm.getStackPointer(), NativeExitFrameLayout::offsetOfResult()),
      R0);

  leaveStubFrame(masm);

  if (isCrossRealm_) {
    masm.switchToBaselineFrameRealm(R1.scratchReg());
  }

  // Enter type monitor IC to type-check result.
  EmitEnterTypeMonitorIC(masm);

  masm.bind(&failure);
  EmitStubGuardFailure(masm);
  return true;
}

bool ICCall_ClassHook::Compiler::generateStubCode(MacroAssembler& masm) {
  Label failure;
  AllocatableGeneralRegisterSet regs(availableGeneralRegs(0));

  Register argcReg = R0.scratchReg();
  regs.take(argcReg);
  regs.takeUnchecked(ICTailCallReg);

  // Load the callee in R1.
  unsigned nonArgSlots = (1 + isConstructing_) * sizeof(Value);
  BaseValueIndex calleeSlot(masm.getStackPointer(), argcReg,
                            ICStackValueOffset + nonArgSlots);
  masm.loadValue(calleeSlot, R1);
  regs.take(R1);

  masm.branchTestObject(Assembler::NotEqual, R1, &failure);

  // Ensure the callee's class matches the one in this stub.
  // We use |Address(ICStubReg, ICCall_ClassHook::offsetOfNative())| below
  // instead of extracting the hook from callee. As a result the callee
  // register is no longer used and we must use spectreRegToZero := ICStubReg
  // instead.
  Register callee = masm.extractObject(R1, ExtractTemp0);
  Register scratch = regs.takeAny();
  masm.branchTestObjClass(Assembler::NotEqual, callee,
                          Address(ICStubReg, ICCall_ClassHook::offsetOfClass()),
                          scratch, ICStubReg, &failure);
  regs.add(R1);
  regs.takeUnchecked(callee);

  // Push a stub frame so that we can perform a non-tail call.
  // Note that this leaves the return address in TailCallReg.
  enterStubFrame(masm, regs.getAny());

  masm.switchToObjectRealm(callee, regs.getAny());

  regs.add(scratch);
  pushCallArguments(masm, regs, argcReg, /* isJitCall = */ false,
                    isConstructing_);
  regs.take(scratch);

  masm.assertStackAlignment(sizeof(Value), 0);

  // Native functions have the signature:
  //
  //    bool (*)(JSContext*, unsigned, Value* vp)
  //
  // Where vp[0] is space for callee/return value, vp[1] is |this|, and vp[2]
  // onward are the function arguments.

  // Initialize vp.
  Register vpReg = regs.takeAny();
  masm.moveStackPtrTo(vpReg);

  // Construct a native exit frame.
  masm.push(argcReg);

  EmitBaselineCreateStubFrameDescriptor(masm, scratch, ExitFrameLayout::Size());
  masm.push(scratch);
  masm.push(ICTailCallReg);
  masm.loadJSContext(scratch);
  masm.enterFakeExitFrameForNative(scratch, scratch, isConstructing_);

  // Execute call.
  masm.setupUnalignedABICall(scratch);
  masm.loadJSContext(scratch);
  masm.passABIArg(scratch);
  masm.passABIArg(argcReg);
  masm.passABIArg(vpReg);
  masm.callWithABI(Address(ICStubReg, ICCall_ClassHook::offsetOfNative()));

  // Test for failure.
  masm.branchIfFalseBool(ReturnReg, masm.exceptionLabel());

  // Load the return value into R0.
  masm.loadValue(
      Address(masm.getStackPointer(), NativeExitFrameLayout::offsetOfResult()),
      R0);

  leaveStubFrame(masm);

  masm.switchToBaselineFrameRealm(R1.scratchReg());

  // Enter type monitor IC to type-check result.
  EmitEnterTypeMonitorIC(masm);

  masm.bind(&failure);
  EmitStubGuardFailure(masm);
  return true;
}

bool ICCall_ScriptedApplyArray::Compiler::generateStubCode(
    MacroAssembler& masm) {
  Label failure;
  AllocatableGeneralRegisterSet regs(availableGeneralRegs(0));

  Register argcReg = R0.scratchReg();
  regs.take(argcReg);
  regs.takeUnchecked(ICTailCallReg);

  //
  // Validate inputs
  //

  Register target =
      guardFunApply(masm, regs, argcReg, FunApply_Array, &failure);
  if (regs.has(target)) {
    regs.take(target);
  } else {
    // If target is already a reserved reg, take another register for it,
    // because it's probably currently an ExtractTemp, which might get clobbered
    // later.
    Register targetTemp = regs.takeAny();
    masm.movePtr(target, targetTemp);
    target = targetTemp;
  }

  // Push a stub frame so that we can perform a non-tail call.
  enterStubFrame(masm, regs.getAny());

  //
  // Push arguments
  //

  // Stack now looks like:
  //                                      BaselineFrameReg -------------------.
  //                                                                          v
  //      [..., fun_apply, TargetV, TargetThisV, ArgsArrayV, StubFrameHeader]

  // Push all array elements onto the stack:
  Address arrayVal(BaselineFrameReg, STUB_FRAME_SIZE);
  pushArrayArguments(masm, arrayVal, regs);

  // Stack now looks like:
  //                                      BaselineFrameReg -------------------.
  //                                                                          v
  //      [..., fun_apply, TargetV, TargetThisV, ArgsArrayV, StubFrameHeader,
  //       PushedArgN, ..., PushedArg0]
  // Can't fail after this, so it's ok to clobber argcReg.

  // Push actual argument 0 as |thisv| for call.
  masm.pushValue(Address(BaselineFrameReg, STUB_FRAME_SIZE + sizeof(Value)));

  // All pushes after this use Push instead of push to make sure ARM can align
  // stack properly for call.
  Register scratch = regs.takeAny();
  EmitBaselineCreateStubFrameDescriptor(masm, scratch, JitFrameLayout::Size());

  // Reload argc from length of array.
  masm.unboxObject(arrayVal, argcReg);
  masm.loadPtr(Address(argcReg, NativeObject::offsetOfElements()), argcReg);
  masm.load32(Address(argcReg, ObjectElements::offsetOfInitializedLength()),
              argcReg);

  masm.Push(argcReg);
  masm.Push(target);
  masm.Push(scratch);

  masm.switchToObjectRealm(target, scratch);

  // Load nargs into scratch for underflow check, and then load jitcode pointer
  // into target.
  masm.load16ZeroExtend(Address(target, JSFunction::offsetOfNargs()), scratch);
  masm.loadJitCodeRaw(target, target);

  // Handle arguments underflow.
  Label noUnderflow;
  masm.branch32(Assembler::AboveOrEqual, argcReg, scratch, &noUnderflow);
  {
    // Call the arguments rectifier.
    TrampolinePtr argumentsRectifier =
        cx->runtime()->jitRuntime()->getArgumentsRectifier();
    masm.movePtr(argumentsRectifier, target);
  }
  masm.bind(&noUnderflow);
  regs.add(argcReg);

  // Do call.
  masm.callJit(target);
  leaveStubFrame(masm, true);

  masm.switchToBaselineFrameRealm(R1.scratchReg());

  // Enter type monitor IC to type-check result.
  EmitEnterTypeMonitorIC(masm);

  masm.bind(&failure);
  EmitStubGuardFailure(masm);
  return true;
}

bool ICCall_ScriptedApplyArguments::Compiler::generateStubCode(
    MacroAssembler& masm) {
  Label failure;
  AllocatableGeneralRegisterSet regs(availableGeneralRegs(0));

  Register argcReg = R0.scratchReg();
  regs.take(argcReg);
  regs.takeUnchecked(ICTailCallReg);

  //
  // Validate inputs
  //

  Register target =
      guardFunApply(masm, regs, argcReg, FunApply_MagicArgs, &failure);
  if (regs.has(target)) {
    regs.take(target);
  } else {
    // If target is already a reserved reg, take another register for it,
    // because it's probably currently an ExtractTemp, which might get clobbered
    // later.
    Register targetTemp = regs.takeAny();
    masm.movePtr(target, targetTemp);
    target = targetTemp;
  }

  // Push a stub frame so that we can perform a non-tail call.
  enterStubFrame(masm, regs.getAny());

  //
  // Push arguments
  //

  // Stack now looks like:
  //      [..., fun_apply, TargetV, TargetThisV, MagicArgsV, StubFrameHeader]

  // Push all arguments supplied to caller function onto the stack.
  pushCallerArguments(masm, regs);

  // Stack now looks like:
  //                                      BaselineFrameReg -------------------.
  //                                                                          v
  //      [..., fun_apply, TargetV, TargetThisV, MagicArgsV, StubFrameHeader,
  //       PushedArgN, ..., PushedArg0]
  // Can't fail after this, so it's ok to clobber argcReg.

  // Push actual argument 0 as |thisv| for call.
  masm.pushValue(Address(BaselineFrameReg, STUB_FRAME_SIZE + sizeof(Value)));

  // All pushes after this use Push instead of push to make sure ARM can align
  // stack properly for call.
  Register scratch = regs.takeAny();
  EmitBaselineCreateStubFrameDescriptor(masm, scratch, JitFrameLayout::Size());

  masm.loadPtr(Address(BaselineFrameReg, 0), argcReg);
  masm.loadPtr(Address(argcReg, BaselineFrame::offsetOfNumActualArgs()),
               argcReg);
  masm.Push(argcReg);
  masm.Push(target);
  masm.Push(scratch);

  masm.switchToObjectRealm(target, scratch);

  // Load nargs into scratch for underflow check, and then load jitcode pointer
  // into target.
  masm.load16ZeroExtend(Address(target, JSFunction::offsetOfNargs()), scratch);
  masm.loadJitCodeRaw(target, target);

  // Handle arguments underflow.
  Label noUnderflow;
  masm.branch32(Assembler::AboveOrEqual, argcReg, scratch, &noUnderflow);
  {
    // Call the arguments rectifier.
    TrampolinePtr argumentsRectifier =
        cx->runtime()->jitRuntime()->getArgumentsRectifier();
    masm.movePtr(argumentsRectifier, target);
  }
  masm.bind(&noUnderflow);
  regs.add(argcReg);

  // Do call
  masm.callJit(target);
  leaveStubFrame(masm, true);

  masm.switchToBaselineFrameRealm(R1.scratchReg());

  // Enter type monitor IC to type-check result.
  EmitEnterTypeMonitorIC(masm);

  masm.bind(&failure);
  EmitStubGuardFailure(masm);
  return true;
}

bool ICCall_ScriptedFunCall::Compiler::generateStubCode(MacroAssembler& masm) {
  Label failure;
  AllocatableGeneralRegisterSet regs(availableGeneralRegs(0));
  bool canUseTailCallReg = regs.has(ICTailCallReg);

  Register argcReg = R0.scratchReg();
  regs.take(argcReg);
  regs.takeUnchecked(ICTailCallReg);

  // Load the callee in R1.
  // Stack Layout:
  //      [ ..., CalleeVal, ThisVal, Arg0Val, ..., ArgNVal,
  //        +ICStackValueOffset+ ]
  BaseValueIndex calleeSlot(masm.getStackPointer(), argcReg,
                            ICStackValueOffset + sizeof(Value));
  masm.loadValue(calleeSlot, R1);
  regs.take(R1);

  // Ensure callee is fun_call.
  masm.branchTestObject(Assembler::NotEqual, R1, &failure);

  Register callee = masm.extractObject(R1, ExtractTemp0);
  masm.branchTestObjClass(Assembler::NotEqual, callee, &JSFunction::class_,
                          regs.getAny(), callee, &failure);
  masm.loadPtr(Address(callee, JSFunction::offsetOfNativeOrEnv()), callee);
  masm.branchPtr(Assembler::NotEqual, callee, ImmPtr(fun_call), &failure);

  // Ensure |this| is a function with a jit entry.
  BaseIndex thisSlot(masm.getStackPointer(), argcReg, TimesEight,
                     ICStackValueOffset);
  masm.loadValue(thisSlot, R1);

  masm.branchTestObject(Assembler::NotEqual, R1, &failure);
  callee = masm.extractObject(R1, ExtractTemp0);

  masm.branchTestObjClass(Assembler::NotEqual, callee, &JSFunction::class_,
                          regs.getAny(), callee, &failure);
  masm.branchIfFunctionHasNoJitEntry(callee, /* constructing */ false,
                                     &failure);
  masm.branchFunctionKind(Assembler::Equal, JSFunction::ClassConstructor,
                          callee, regs.getAny(), &failure);

  // Load the start of the target JitCode.
  Register code = regs.takeAny();
  masm.loadJitCodeRaw(callee, code);

  // We no longer need R1.
  regs.add(R1);

  // Push a stub frame so that we can perform a non-tail call.
  enterStubFrame(masm, regs.getAny());
  if (canUseTailCallReg) {
    regs.add(ICTailCallReg);
  }

  // Decrement argc if argc > 0. If argc == 0, push |undefined| as |this|.
  Label zeroArgs, done;
  masm.branchTest32(Assembler::Zero, argcReg, argcReg, &zeroArgs);

  // Avoid the copy of the callee (function.call).
  masm.sub32(Imm32(1), argcReg);

  // Values are on the stack left-to-right. Calling convention wants them
  // right-to-left so duplicate them on the stack in reverse order.

  pushCallArguments(masm, regs, argcReg, /* isJitCall = */ true);

  // Pop scripted callee (the original |this|).
  ValueOperand val = regs.takeAnyValue();
  masm.popValue(val);

  masm.jump(&done);
  masm.bind(&zeroArgs);

  // Copy scripted callee (the original |this|).
  Address thisSlotFromStubFrame(BaselineFrameReg, STUB_FRAME_SIZE);
  masm.loadValue(thisSlotFromStubFrame, val);

  // Align the stack.
  masm.alignJitStackBasedOnNArgs(0);

  // Store the new |this|.
  masm.pushValue(UndefinedValue());

  masm.bind(&done);

  // Unbox scripted callee.
  callee = masm.extractObject(val, ExtractTemp0);

  Register scratch = regs.takeAny();
  masm.switchToObjectRealm(callee, scratch);
  EmitBaselineCreateStubFrameDescriptor(masm, scratch, JitFrameLayout::Size());

  // Note that we use Push, not push, so that callJit will align the stack
  // properly on ARM.
  masm.Push(argcReg);
  masm.Push(callee);
  masm.Push(scratch);

  // Handle arguments underflow.
  Label noUnderflow;
  masm.load16ZeroExtend(Address(callee, JSFunction::offsetOfNargs()), callee);
  masm.branch32(Assembler::AboveOrEqual, argcReg, callee, &noUnderflow);
  {
    // Call the arguments rectifier.
    TrampolinePtr argumentsRectifier =
        cx->runtime()->jitRuntime()->getArgumentsRectifier();
    masm.movePtr(argumentsRectifier, code);
  }

  masm.bind(&noUnderflow);
  masm.callJit(code);

  leaveStubFrame(masm, true);

  masm.switchToBaselineFrameRealm(R1.scratchReg());

  // Enter type monitor IC to type-check result.
  EmitEnterTypeMonitorIC(masm);

  masm.bind(&failure);
  EmitStubGuardFailure(masm);
  return true;
}

//
// GetIterator_Fallback
//

bool DoGetIteratorFallback(JSContext* cx, BaselineFrame* frame,
                           ICGetIterator_Fallback* stub, HandleValue value,
                           MutableHandleValue res) {
  stub->incrementEnteredCount();
  FallbackICSpew(cx, stub, "GetIterator");

  TryAttachStub<GetIteratorIRGenerator>(
      "GetIterator", cx, frame, stub, BaselineCacheIRStubKind::Regular, value);

  JSObject* iterobj = ValueToIterator(cx, value);
  if (!iterobj) {
    return false;
  }

  res.setObject(*iterobj);
  return true;
}

bool ICGetIterator_Fallback::Compiler::generateStubCode(MacroAssembler& masm) {
  EmitRestoreTailCallReg(masm);

  // Sync stack for the decompiler.
  masm.pushValue(R0);

  masm.pushValue(R0);
  masm.push(ICStubReg);
  pushStubPayload(masm, R0.scratchReg());

  using Fn = bool (*)(JSContext*, BaselineFrame*, ICGetIterator_Fallback*,
                      HandleValue, MutableHandleValue);
  return tailCallVM<Fn, DoGetIteratorFallback>(masm);
}

//
// InstanceOf_Fallback
//

bool DoInstanceOfFallback(JSContext* cx, BaselineFrame* frame,
                          ICInstanceOf_Fallback* stub, HandleValue lhs,
                          HandleValue rhs, MutableHandleValue res) {
  stub->incrementEnteredCount();

  FallbackICSpew(cx, stub, "InstanceOf");

  if (!rhs.isObject()) {
    ReportValueError(cx, JSMSG_BAD_INSTANCEOF_RHS, -1, rhs, nullptr);
    return false;
  }

  RootedObject obj(cx, &rhs.toObject());
  bool cond = false;
  if (!HasInstance(cx, obj, lhs, &cond)) {
    return false;
  }

  res.setBoolean(cond);

  if (!obj->is<JSFunction>()) {
    // ensure we've recorded at least one failure, so we can detect there was a
    // non-optimizable case
    if (!stub->state().hasFailures()) {
      stub->state().trackNotAttached();
    }
    return true;
  }

  // For functions, keep track of the |prototype| property in type information,
  // for use during Ion compilation.
  EnsureTrackPropertyTypes(cx, obj, NameToId(cx->names().prototype));

  TryAttachStub<InstanceOfIRGenerator>("InstanceOf", cx, frame, stub,
                                       BaselineCacheIRStubKind::Regular, lhs,
                                       obj);
  return true;
}

bool ICInstanceOf_Fallback::Compiler::generateStubCode(MacroAssembler& masm) {
  EmitRestoreTailCallReg(masm);

  // Sync stack for the decompiler.
  masm.pushValue(R0);
  masm.pushValue(R1);

  masm.pushValue(R1);
  masm.pushValue(R0);
  masm.push(ICStubReg);
  pushStubPayload(masm, R0.scratchReg());

  using Fn = bool (*)(JSContext*, BaselineFrame*, ICInstanceOf_Fallback*,
                      HandleValue, HandleValue, MutableHandleValue);
  return tailCallVM<Fn, DoInstanceOfFallback>(masm);
}

//
// TypeOf_Fallback
//

bool DoTypeOfFallback(JSContext* cx, BaselineFrame* frame,
                      ICTypeOf_Fallback* stub, HandleValue val,
                      MutableHandleValue res) {
  stub->incrementEnteredCount();
  FallbackICSpew(cx, stub, "TypeOf");

  TryAttachStub<TypeOfIRGenerator>("TypeOf", cx, frame, stub,
                                   BaselineCacheIRStubKind::Regular, val);

  JSType type = js::TypeOfValue(val);
  RootedString string(cx, TypeName(type, cx->names()));
  res.setString(string);
  return true;
}

bool ICTypeOf_Fallback::Compiler::generateStubCode(MacroAssembler& masm) {
  EmitRestoreTailCallReg(masm);

  masm.pushValue(R0);
  masm.push(ICStubReg);
  pushStubPayload(masm, R0.scratchReg());

  using Fn = bool (*)(JSContext*, BaselineFrame*, ICTypeOf_Fallback*,
                      HandleValue, MutableHandleValue);
  return tailCallVM<Fn, DoTypeOfFallback>(masm);
}

ICTypeMonitor_SingleObject::ICTypeMonitor_SingleObject(JitCode* stubCode,
                                                       JSObject* obj)
    : ICStub(TypeMonitor_SingleObject, stubCode), obj_(obj) {}

ICTypeMonitor_ObjectGroup::ICTypeMonitor_ObjectGroup(JitCode* stubCode,
                                                     ObjectGroup* group)
    : ICStub(TypeMonitor_ObjectGroup, stubCode), group_(group) {}

ICTypeUpdate_SingleObject::ICTypeUpdate_SingleObject(JitCode* stubCode,
                                                     JSObject* obj)
    : ICStub(TypeUpdate_SingleObject, stubCode), obj_(obj) {}

ICTypeUpdate_ObjectGroup::ICTypeUpdate_ObjectGroup(JitCode* stubCode,
                                                   ObjectGroup* group)
    : ICStub(TypeUpdate_ObjectGroup, stubCode), group_(group) {}

ICCall_Scripted::ICCall_Scripted(JitCode* stubCode, ICStub* firstMonitorStub,
                                 JSFunction* callee, JSObject* templateObject,
                                 uint32_t pcOffset)
    : ICMonitoredStub(ICStub::Call_Scripted, stubCode, firstMonitorStub),
      callee_(callee),
      templateObject_(templateObject),
      pcOffset_(pcOffset) {}

ICCall_Native::ICCall_Native(JitCode* stubCode, ICStub* firstMonitorStub,
                             JSFunction* callee, JSObject* templateObject,
                             uint32_t pcOffset)
    : ICMonitoredStub(ICStub::Call_Native, stubCode, firstMonitorStub),
      callee_(callee),
      templateObject_(templateObject),
      pcOffset_(pcOffset) {
#ifdef JS_SIMULATOR
  // The simulator requires VM calls to be redirected to a special swi
  // instruction to handle them. To make this work, we store the redirected
  // pointer in the stub.
  native_ = Simulator::RedirectNativeFunction(
      JS_FUNC_TO_DATA_PTR(void*, callee->native()), Args_General3);
#endif
}

ICCall_ClassHook::ICCall_ClassHook(JitCode* stubCode, ICStub* firstMonitorStub,
                                   const Class* clasp, Native native,
                                   JSObject* templateObject, uint32_t pcOffset)
    : ICMonitoredStub(ICStub::Call_ClassHook, stubCode, firstMonitorStub),
      clasp_(clasp),
      native_(JS_FUNC_TO_DATA_PTR(void*, native)),
      templateObject_(templateObject),
      pcOffset_(pcOffset) {
#ifdef JS_SIMULATOR
  // The simulator requires VM calls to be redirected to a special swi
  // instruction to handle them. To make this work, we store the redirected
  // pointer in the stub.
  native_ = Simulator::RedirectNativeFunction(native_, Args_General3);
#endif
}

//
// Rest_Fallback
//

bool DoRestFallback(JSContext* cx, BaselineFrame* frame, ICRest_Fallback* stub,
                    MutableHandleValue res) {
  unsigned numFormals = frame->numFormalArgs() - 1;
  unsigned numActuals = frame->numActualArgs();
  unsigned numRest = numActuals > numFormals ? numActuals - numFormals : 0;
  Value* rest = frame->argv() + numFormals;

  ArrayObject* obj =
      ObjectGroup::newArrayObject(cx, rest, numRest, GenericObject,
                                  ObjectGroup::NewArrayKind::UnknownIndex);
  if (!obj) {
    return false;
  }
  res.setObject(*obj);
  return true;
}

bool ICRest_Fallback::Compiler::generateStubCode(MacroAssembler& masm) {
  EmitRestoreTailCallReg(masm);

  masm.push(ICStubReg);
  pushStubPayload(masm, R0.scratchReg());

  using Fn = bool (*)(JSContext*, BaselineFrame*, ICRest_Fallback*,
                      MutableHandleValue);
  return tailCallVM<Fn, DoRestFallback>(masm);
}

//
// UnaryArith_Fallback
//

bool DoUnaryArithFallback(JSContext* cx, BaselineFrame* frame,
                          ICUnaryArith_Fallback* stub, HandleValue val,
                          MutableHandleValue res) {
  stub->incrementEnteredCount();

  RootedScript script(cx, frame->script());
  jsbytecode* pc = stub->icEntry()->pc(script);
  JSOp op = JSOp(*pc);
  FallbackICSpew(cx, stub, "UnaryArith(%s)", CodeName[op]);

  // The unary operations take a copied val because the original value is needed
  // below.
  RootedValue valCopy(cx, val);
  switch (op) {
    case JSOP_BITNOT: {
      if (!BitNot(cx, &valCopy, res)) {
        return false;
      }
      break;
    }
    case JSOP_NEG: {
      if (!NegOperation(cx, &valCopy, res)) {
        return false;
      }
      break;
    }
    case JSOP_INC: {
      if (!IncOperation(cx, &valCopy, res)) {
        return false;
      }
      break;
    }
    case JSOP_DEC: {
      if (!DecOperation(cx, &valCopy, res)) {
        return false;
      }
      break;
    }
    default:
      MOZ_CRASH("Unexpected op");
  }

  if (res.isDouble()) {
    stub->setSawDoubleResult();
  }

  TryAttachStub<UnaryArithIRGenerator>("UniaryArith", cx, frame, stub,
                                       BaselineCacheIRStubKind::Regular, op,
                                       val, res);
  return true;
}

bool ICUnaryArith_Fallback::Compiler::generateStubCode(MacroAssembler& masm) {
  MOZ_ASSERT(R0 == JSReturnOperand);

  // Restore the tail call register.
  EmitRestoreTailCallReg(masm);

  // Ensure stack is fully synced for the expression decompiler.
  masm.pushValue(R0);

  // Push arguments.
  masm.pushValue(R0);
  masm.push(ICStubReg);
  pushStubPayload(masm, R0.scratchReg());

  using Fn = bool (*)(JSContext*, BaselineFrame*, ICUnaryArith_Fallback*,
                      HandleValue, MutableHandleValue);
  return tailCallVM<Fn, DoUnaryArithFallback>(masm);
}

//
// BinaryArith_Fallback
//

bool DoBinaryArithFallback(JSContext* cx, BaselineFrame* frame,
                           ICBinaryArith_Fallback* stub, HandleValue lhs,
                           HandleValue rhs, MutableHandleValue ret) {
  stub->incrementEnteredCount();

  RootedScript script(cx, frame->script());
  jsbytecode* pc = stub->icEntry()->pc(script);
  JSOp op = JSOp(*pc);
  FallbackICSpew(
      cx, stub, "CacheIRBinaryArith(%s,%d,%d)", CodeName[op],
      int(lhs.isDouble() ? JSVAL_TYPE_DOUBLE : lhs.extractNonDoubleType()),
      int(rhs.isDouble() ? JSVAL_TYPE_DOUBLE : rhs.extractNonDoubleType()));

  // Don't pass lhs/rhs directly, we need the original values when
  // generating stubs.
  RootedValue lhsCopy(cx, lhs);
  RootedValue rhsCopy(cx, rhs);

  // Perform the compare operation.
  switch (op) {
    case JSOP_ADD:
      // Do an add.
      if (!AddValues(cx, &lhsCopy, &rhsCopy, ret)) {
        return false;
      }
      break;
    case JSOP_SUB:
      if (!SubValues(cx, &lhsCopy, &rhsCopy, ret)) {
        return false;
      }
      break;
    case JSOP_MUL:
      if (!MulValues(cx, &lhsCopy, &rhsCopy, ret)) {
        return false;
      }
      break;
    case JSOP_DIV:
      if (!DivValues(cx, &lhsCopy, &rhsCopy, ret)) {
        return false;
      }
      break;
    case JSOP_MOD:
      if (!ModValues(cx, &lhsCopy, &rhsCopy, ret)) {
        return false;
      }
      break;
    case JSOP_POW:
      if (!PowValues(cx, &lhsCopy, &rhsCopy, ret)) {
        return false;
      }
      break;
    case JSOP_BITOR: {
      if (!BitOr(cx, &lhsCopy, &rhsCopy, ret)) {
        return false;
      }
      break;
    }
    case JSOP_BITXOR: {
      if (!BitXor(cx, &lhsCopy, &rhsCopy, ret)) {
        return false;
      }
      break;
    }
    case JSOP_BITAND: {
      if (!BitAnd(cx, &lhsCopy, &rhsCopy, ret)) {
        return false;
      }
      break;
    }
    case JSOP_LSH: {
      if (!BitLsh(cx, &lhsCopy, &rhsCopy, ret)) {
        return false;
      }
      break;
    }
    case JSOP_RSH: {
      if (!BitRsh(cx, &lhsCopy, &rhsCopy, ret)) {
        return false;
      }
      break;
    }
    case JSOP_URSH: {
      if (!UrshOperation(cx, &lhsCopy, &rhsCopy, ret)) {
        return false;
      }
      break;
    }
    default:
      MOZ_CRASH("Unhandled baseline arith op");
  }

  if (ret.isDouble()) {
    stub->setSawDoubleResult();
  }

  TryAttachStub<BinaryArithIRGenerator>("BinaryArith", cx, frame, stub,
                                        BaselineCacheIRStubKind::Regular, op,
                                        lhs, rhs, ret);
  return true;
}

bool ICBinaryArith_Fallback::Compiler::generateStubCode(MacroAssembler& masm) {
  MOZ_ASSERT(R0 == JSReturnOperand);

  // Restore the tail call register.
  EmitRestoreTailCallReg(masm);

  // Ensure stack is fully synced for the expression decompiler.
  masm.pushValue(R0);
  masm.pushValue(R1);

  // Push arguments.
  masm.pushValue(R1);
  masm.pushValue(R0);
  masm.push(ICStubReg);
  pushStubPayload(masm, R0.scratchReg());

  using Fn = bool (*)(JSContext*, BaselineFrame*, ICBinaryArith_Fallback*,
                      HandleValue, HandleValue, MutableHandleValue);
  return tailCallVM<Fn, DoBinaryArithFallback>(masm);
}

//
// Compare_Fallback
//
bool DoCompareFallback(JSContext* cx, BaselineFrame* frame,
                       ICCompare_Fallback* stub, HandleValue lhs,
                       HandleValue rhs, MutableHandleValue ret) {
  stub->incrementEnteredCount();

  RootedScript script(cx, frame->script());
  jsbytecode* pc = stub->icEntry()->pc(script);
  JSOp op = JSOp(*pc);

  FallbackICSpew(cx, stub, "Compare(%s)", CodeName[op]);

  // Don't pass lhs/rhs directly, we need the original values when
  // generating stubs.
  RootedValue lhsCopy(cx, lhs);
  RootedValue rhsCopy(cx, rhs);

  // Perform the compare operation.
  bool out;
  switch (op) {
    case JSOP_LT:
      if (!LessThan(cx, &lhsCopy, &rhsCopy, &out)) {
        return false;
      }
      break;
    case JSOP_LE:
      if (!LessThanOrEqual(cx, &lhsCopy, &rhsCopy, &out)) {
        return false;
      }
      break;
    case JSOP_GT:
      if (!GreaterThan(cx, &lhsCopy, &rhsCopy, &out)) {
        return false;
      }
      break;
    case JSOP_GE:
      if (!GreaterThanOrEqual(cx, &lhsCopy, &rhsCopy, &out)) {
        return false;
      }
      break;
    case JSOP_EQ:
      if (!LooselyEqual<true>(cx, &lhsCopy, &rhsCopy, &out)) {
        return false;
      }
      break;
    case JSOP_NE:
      if (!LooselyEqual<false>(cx, &lhsCopy, &rhsCopy, &out)) {
        return false;
      }
      break;
    case JSOP_STRICTEQ:
      if (!StrictlyEqual<true>(cx, &lhsCopy, &rhsCopy, &out)) {
        return false;
      }
      break;
    case JSOP_STRICTNE:
      if (!StrictlyEqual<false>(cx, &lhsCopy, &rhsCopy, &out)) {
        return false;
      }
      break;
    default:
      MOZ_ASSERT_UNREACHABLE("Unhandled baseline compare op");
      return false;
  }

  ret.setBoolean(out);

  TryAttachStub<CompareIRGenerator>("Compare", cx, frame, stub,
                                    BaselineCacheIRStubKind::Regular, op, lhs,
                                    rhs);
  return true;
}

bool ICCompare_Fallback::Compiler::generateStubCode(MacroAssembler& masm) {
  MOZ_ASSERT(R0 == JSReturnOperand);

  // Restore the tail call register.
  EmitRestoreTailCallReg(masm);

  // Ensure stack is fully synced for the expression decompiler.
  masm.pushValue(R0);
  masm.pushValue(R1);

  // Push arguments.
  masm.pushValue(R1);
  masm.pushValue(R0);
  masm.push(ICStubReg);
  pushStubPayload(masm, R0.scratchReg());

  using Fn = bool (*)(JSContext*, BaselineFrame*, ICCompare_Fallback*,
                      HandleValue, HandleValue, MutableHandleValue);
  return tailCallVM<Fn, DoCompareFallback>(masm);
}

//
// NewArray_Fallback
//

bool DoNewArrayFallback(JSContext* cx, BaselineFrame* frame,
                        ICNewArray_Fallback* stub, uint32_t length,
                        MutableHandleValue res) {
  stub->incrementEnteredCount();
  FallbackICSpew(cx, stub, "NewArray");

  RootedObject obj(cx);
  if (stub->templateObject()) {
    RootedObject templateObject(cx, stub->templateObject());
    obj = NewArrayOperationWithTemplate(cx, templateObject);
    if (!obj) {
      return false;
    }
  } else {
    RootedScript script(cx, frame->script());
    jsbytecode* pc = stub->icEntry()->pc(script);

    obj = NewArrayOperation(cx, script, pc, length);
    if (!obj) {
      return false;
    }

    if (!obj->isSingleton()) {
      JSObject* templateObject =
          NewArrayOperation(cx, script, pc, length, TenuredObject);
      if (!templateObject) {
        return false;
      }
      stub->setTemplateObject(templateObject);
    }
  }

  res.setObject(*obj);
  return true;
}

bool ICNewArray_Fallback::Compiler::generateStubCode(MacroAssembler& masm) {
  EmitRestoreTailCallReg(masm);

  masm.push(R0.scratchReg());  // length
  masm.push(ICStubReg);        // stub.
  masm.pushBaselineFramePtr(BaselineFrameReg, R0.scratchReg());

  using Fn = bool (*)(JSContext*, BaselineFrame*, ICNewArray_Fallback*,
                      uint32_t, MutableHandleValue);
  return tailCallVM<Fn, DoNewArrayFallback>(masm);
}

//
// NewObject_Fallback
//
bool DoNewObjectFallback(JSContext* cx, BaselineFrame* frame,
                         ICNewObject_Fallback* stub, MutableHandleValue res) {
  stub->incrementEnteredCount();
  FallbackICSpew(cx, stub, "NewObject");

  RootedObject obj(cx);

  RootedObject templateObject(cx, stub->templateObject());
  if (templateObject) {
    MOZ_ASSERT(
        !templateObject->group()->maybePreliminaryObjectsDontCheckGeneration());
    obj = NewObjectOperationWithTemplate(cx, templateObject);
  } else {
    RootedScript script(cx, frame->script());
    jsbytecode* pc = stub->icEntry()->pc(script);
    obj = NewObjectOperation(cx, script, pc);

    if (obj && !obj->isSingleton() &&
        !obj->group()->maybePreliminaryObjectsDontCheckGeneration()) {
      templateObject = NewObjectOperation(cx, script, pc, TenuredObject);
      if (!templateObject) {
        return false;
      }

      TryAttachStub<NewObjectIRGenerator>("NewObject", cx, frame, stub,
                                          BaselineCacheIRStubKind::Regular,
                                          JSOp(*pc), templateObject);

      stub->setTemplateObject(templateObject);
    }
  }

  if (!obj) {
    return false;
  }

  res.setObject(*obj);
  return true;
}

bool ICNewObject_Fallback::Compiler::generateStubCode(MacroAssembler& masm) {
  EmitRestoreTailCallReg(masm);

  masm.push(ICStubReg);  // stub.
  pushStubPayload(masm, R0.scratchReg());

  using Fn = bool (*)(JSContext*, BaselineFrame*, ICNewObject_Fallback*,
                      MutableHandleValue);
  return tailCallVM<Fn, DoNewObjectFallback>(masm);
}

}  // namespace jit
}  // namespace js