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
|
// Copyright 2017 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "src/wasm/module-compiler.h"
#include <algorithm>
#include <mutex> // NOLINT(build/c++11)
#include <queue>
#include <shared_mutex>
#include "src/api/api-inl.h"
#include "src/base/enum-set.h"
#include "src/base/optional.h"
#include "src/base/platform/mutex.h"
#include "src/base/platform/semaphore.h"
#include "src/base/platform/time.h"
#include "src/compiler/wasm-compiler.h"
#include "src/debug/debug.h"
#include "src/handles/global-handles-inl.h"
#include "src/heap/heap-inl.h" // For CodePageCollectionMemoryModificationScope.
#include "src/logging/counters-scopes.h"
#include "src/logging/metrics.h"
#include "src/tracing/trace-event.h"
#include "src/wasm/assembler-buffer-cache.h"
#include "src/wasm/code-space-access.h"
#include "src/wasm/module-decoder.h"
#include "src/wasm/streaming-decoder.h"
#include "src/wasm/wasm-code-manager.h"
#include "src/wasm/wasm-engine.h"
#include "src/wasm/wasm-import-wrapper-cache.h"
#include "src/wasm/wasm-js.h"
#include "src/wasm/wasm-limits.h"
#include "src/wasm/wasm-objects-inl.h"
#include "src/wasm/wasm-result.h"
#include "src/wasm/wasm-serialization.h"
#define TRACE_COMPILE(...) \
do { \
if (v8_flags.trace_wasm_compiler) PrintF(__VA_ARGS__); \
} while (false)
#define TRACE_STREAMING(...) \
do { \
if (v8_flags.trace_wasm_streaming) PrintF(__VA_ARGS__); \
} while (false)
#define TRACE_LAZY(...) \
do { \
if (v8_flags.trace_wasm_lazy_compilation) PrintF(__VA_ARGS__); \
} while (false)
namespace v8 {
namespace internal {
namespace wasm {
namespace {
enum class CompileStrategy : uint8_t {
// Compiles functions on first use. In this case, execution will block until
// the function's baseline is reached and top tier compilation starts in
// background (if applicable).
// Lazy compilation can help to reduce startup time and code size at the risk
// of blocking execution.
kLazy,
// Compiles baseline ahead of execution and starts top tier compilation in
// background (if applicable).
kEager,
// Triggers baseline compilation on first use (just like {kLazy}) with the
// difference that top tier compilation is started eagerly.
// This strategy can help to reduce startup time at the risk of blocking
// execution, but only in its early phase (until top tier compilation
// finishes).
kLazyBaselineEagerTopTier,
// Marker for default strategy.
kDefault = kEager,
};
class CompilationStateImpl;
class CompilationUnitBuilder;
class V8_NODISCARD BackgroundCompileScope {
public:
explicit BackgroundCompileScope(std::weak_ptr<NativeModule> native_module)
: native_module_(native_module.lock()) {}
NativeModule* native_module() const {
DCHECK(native_module_);
return native_module_.get();
}
inline CompilationStateImpl* compilation_state() const;
bool cancelled() const;
private:
// Keep the native module alive while in this scope.
std::shared_ptr<NativeModule> native_module_;
};
enum CompileBaselineOnly : bool {
kBaselineOnly = true,
kBaselineOrTopTier = false
};
// A set of work-stealing queues (vectors of units). Each background compile
// task owns one of the queues and steals from all others once its own queue
// runs empty.
class CompilationUnitQueues {
public:
// Public API for QueueImpl.
struct Queue {
bool ShouldPublish(int num_processed_units) const;
};
explicit CompilationUnitQueues(int num_declared_functions)
: num_declared_functions_(num_declared_functions) {
// Add one first queue, to add units to.
queues_.emplace_back(std::make_unique<QueueImpl>(0));
#if !defined(__cpp_lib_atomic_value_initialization) || \
__cpp_lib_atomic_value_initialization < 201911L
for (auto& atomic_counter : num_units_) {
std::atomic_init(&atomic_counter, size_t{0});
}
#endif
top_tier_compiled_ =
std::make_unique<std::atomic<bool>[]>(num_declared_functions);
#if !defined(__cpp_lib_atomic_value_initialization) || \
__cpp_lib_atomic_value_initialization < 201911L
for (int i = 0; i < num_declared_functions; i++) {
std::atomic_init(&top_tier_compiled_.get()[i], false);
}
#endif
}
Queue* GetQueueForTask(int task_id) {
int required_queues = task_id + 1;
{
std::shared_lock<std::shared_mutex> queues_guard{queues_mutex_};
if (V8_LIKELY(static_cast<int>(queues_.size()) >= required_queues)) {
return queues_[task_id].get();
}
}
// Otherwise increase the number of queues.
std::unique_lock<std::shared_mutex> queues_guard{queues_mutex_};
int num_queues = static_cast<int>(queues_.size());
while (num_queues < required_queues) {
int steal_from = num_queues + 1;
queues_.emplace_back(std::make_unique<QueueImpl>(steal_from));
++num_queues;
}
// Update the {publish_limit}s of all queues.
// We want background threads to publish regularly (to avoid contention when
// they are all publishing at the end). On the other side, each publishing
// has some overhead (part of it for synchronizing between threads), so it
// should not happen *too* often. Thus aim for 4-8 publishes per thread, but
// distribute it such that publishing is likely to happen at different
// times.
int units_per_thread = num_declared_functions_ / num_queues;
int min = std::max(10, units_per_thread / 8);
int queue_id = 0;
for (auto& queue : queues_) {
// Set a limit between {min} and {2*min}, but not smaller than {10}.
int limit = min + (min * queue_id / num_queues);
queue->publish_limit.store(limit, std::memory_order_relaxed);
++queue_id;
}
return queues_[task_id].get();
}
base::Optional<WasmCompilationUnit> GetNextUnit(
Queue* queue, CompileBaselineOnly baseline_only) {
// As long as any lower-tier units are outstanding we need to steal them
// before executing own higher-tier units.
int max_tier = baseline_only ? kBaseline : kTopTier;
for (int tier = GetLowestTierWithUnits(); tier <= max_tier; ++tier) {
if (auto unit = GetNextUnitOfTier(queue, tier)) {
size_t old_units_count =
num_units_[tier].fetch_sub(1, std::memory_order_relaxed);
DCHECK_LE(1, old_units_count);
USE(old_units_count);
return unit;
}
}
return {};
}
void AddUnits(base::Vector<WasmCompilationUnit> baseline_units,
base::Vector<WasmCompilationUnit> top_tier_units,
const WasmModule* module) {
DCHECK_LT(0, baseline_units.size() + top_tier_units.size());
// Add to the individual queues in a round-robin fashion. No special care is
// taken to balance them; they will be balanced by work stealing.
QueueImpl* queue;
{
int queue_to_add = next_queue_to_add.load(std::memory_order_relaxed);
std::shared_lock<std::shared_mutex> queues_guard{queues_mutex_};
while (!next_queue_to_add.compare_exchange_weak(
queue_to_add, next_task_id(queue_to_add, queues_.size()),
std::memory_order_relaxed)) {
// Retry with updated {queue_to_add}.
}
queue = queues_[queue_to_add].get();
}
base::MutexGuard guard(&queue->mutex);
base::Optional<base::MutexGuard> big_units_guard;
for (auto pair : {std::make_pair(int{kBaseline}, baseline_units),
std::make_pair(int{kTopTier}, top_tier_units)}) {
int tier = pair.first;
base::Vector<WasmCompilationUnit> units = pair.second;
if (units.empty()) continue;
num_units_[tier].fetch_add(units.size(), std::memory_order_relaxed);
for (WasmCompilationUnit unit : units) {
size_t func_size = module->functions[unit.func_index()].code.length();
if (func_size <= kBigUnitsLimit) {
queue->units[tier].push_back(unit);
} else {
if (!big_units_guard) {
big_units_guard.emplace(&big_units_queue_.mutex);
}
big_units_queue_.has_units[tier].store(true,
std::memory_order_relaxed);
big_units_queue_.units[tier].emplace(func_size, unit);
}
}
}
}
void AddTopTierPriorityUnit(WasmCompilationUnit unit, size_t priority) {
std::shared_lock<std::shared_mutex> queues_guard{queues_mutex_};
// Add to the individual queues in a round-robin fashion. No special care is
// taken to balance them; they will be balanced by work stealing.
// Priorities should only be seen as a hint here; without balancing, we
// might pop a unit with lower priority from one queue while other queues
// still hold higher-priority units.
// Since updating priorities in a std::priority_queue is difficult, we just
// add new units with higher priorities, and use the
// {CompilationUnitQueues::top_tier_compiled_} array to discard units for
// functions which are already being compiled.
int queue_to_add = next_queue_to_add.load(std::memory_order_relaxed);
while (!next_queue_to_add.compare_exchange_weak(
queue_to_add, next_task_id(queue_to_add, queues_.size()),
std::memory_order_relaxed)) {
// Retry with updated {queue_to_add}.
}
{
auto* queue = queues_[queue_to_add].get();
base::MutexGuard guard(&queue->mutex);
queue->top_tier_priority_units.emplace(priority, unit);
}
num_priority_units_.fetch_add(1, std::memory_order_relaxed);
num_units_[kTopTier].fetch_add(1, std::memory_order_relaxed);
}
// Get the current total number of units in all queues. This is only a
// momentary snapshot, it's not guaranteed that {GetNextUnit} returns a unit
// if this method returns non-zero.
size_t GetTotalSize() const {
size_t total = 0;
for (auto& atomic_counter : num_units_) {
total += atomic_counter.load(std::memory_order_relaxed);
}
return total;
}
private:
// Store tier in int so we can easily loop over it:
static constexpr int kBaseline = 0;
static constexpr int kTopTier = 1;
static constexpr int kNumTiers = kTopTier + 1;
// Functions bigger than {kBigUnitsLimit} will be compiled first, in ascending
// order of their function body size.
static constexpr size_t kBigUnitsLimit = 4096;
struct BigUnit {
BigUnit(size_t func_size, WasmCompilationUnit unit)
: func_size{func_size}, unit(unit) {}
size_t func_size;
WasmCompilationUnit unit;
bool operator<(const BigUnit& other) const {
return func_size < other.func_size;
}
};
struct TopTierPriorityUnit {
TopTierPriorityUnit(int priority, WasmCompilationUnit unit)
: priority(priority), unit(unit) {}
size_t priority;
WasmCompilationUnit unit;
bool operator<(const TopTierPriorityUnit& other) const {
return priority < other.priority;
}
};
struct BigUnitsQueue {
BigUnitsQueue() {
#if !defined(__cpp_lib_atomic_value_initialization) || \
__cpp_lib_atomic_value_initialization < 201911L
for (auto& atomic : has_units) std::atomic_init(&atomic, false);
#endif
}
base::Mutex mutex;
// Can be read concurrently to check whether any elements are in the queue.
std::atomic<bool> has_units[kNumTiers];
// Protected by {mutex}:
std::priority_queue<BigUnit> units[kNumTiers];
};
struct QueueImpl : public Queue {
explicit QueueImpl(int next_steal_task_id)
: next_steal_task_id(next_steal_task_id) {}
// Number of units after which the task processing this queue should publish
// compilation results. Updated (reduced, using relaxed ordering) when new
// queues are allocated. If there is only one thread running, we can delay
// publishing arbitrarily.
std::atomic<int> publish_limit{kMaxInt};
base::Mutex mutex;
// All fields below are protected by {mutex}.
std::vector<WasmCompilationUnit> units[kNumTiers];
std::priority_queue<TopTierPriorityUnit> top_tier_priority_units;
int next_steal_task_id;
};
int next_task_id(int task_id, size_t num_queues) const {
int next = task_id + 1;
return next == static_cast<int>(num_queues) ? 0 : next;
}
int GetLowestTierWithUnits() const {
for (int tier = 0; tier < kNumTiers; ++tier) {
if (num_units_[tier].load(std::memory_order_relaxed) > 0) return tier;
}
return kNumTiers;
}
base::Optional<WasmCompilationUnit> GetNextUnitOfTier(Queue* public_queue,
int tier) {
QueueImpl* queue = static_cast<QueueImpl*>(public_queue);
// First check whether there is a priority unit. Execute that first.
if (tier == kTopTier) {
if (auto unit = GetTopTierPriorityUnit(queue)) {
return unit;
}
}
// Then check whether there is a big unit of that tier.
if (auto unit = GetBigUnitOfTier(tier)) return unit;
// Finally check whether our own queue has a unit of the wanted tier. If
// so, return it, otherwise get the task id to steal from.
int steal_task_id;
{
base::MutexGuard mutex_guard(&queue->mutex);
if (!queue->units[tier].empty()) {
auto unit = queue->units[tier].back();
queue->units[tier].pop_back();
return unit;
}
steal_task_id = queue->next_steal_task_id;
}
// Try to steal from all other queues. If this succeeds, return one of the
// stolen units.
{
std::shared_lock<std::shared_mutex> guard{queues_mutex_};
for (size_t steal_trials = 0; steal_trials < queues_.size();
++steal_trials, ++steal_task_id) {
if (steal_task_id >= static_cast<int>(queues_.size())) {
steal_task_id = 0;
}
if (auto unit = StealUnitsAndGetFirst(queue, steal_task_id, tier)) {
return unit;
}
}
}
// If we reach here, we didn't find any unit of the requested tier.
return {};
}
base::Optional<WasmCompilationUnit> GetBigUnitOfTier(int tier) {
// Fast path without locking.
if (!big_units_queue_.has_units[tier].load(std::memory_order_relaxed)) {
return {};
}
base::MutexGuard guard(&big_units_queue_.mutex);
if (big_units_queue_.units[tier].empty()) return {};
WasmCompilationUnit unit = big_units_queue_.units[tier].top().unit;
big_units_queue_.units[tier].pop();
if (big_units_queue_.units[tier].empty()) {
big_units_queue_.has_units[tier].store(false, std::memory_order_relaxed);
}
return unit;
}
base::Optional<WasmCompilationUnit> GetTopTierPriorityUnit(QueueImpl* queue) {
// Fast path without locking.
if (num_priority_units_.load(std::memory_order_relaxed) == 0) {
return {};
}
int steal_task_id;
{
base::MutexGuard mutex_guard(&queue->mutex);
while (!queue->top_tier_priority_units.empty()) {
auto unit = queue->top_tier_priority_units.top().unit;
queue->top_tier_priority_units.pop();
num_priority_units_.fetch_sub(1, std::memory_order_relaxed);
if (!top_tier_compiled_[unit.func_index()].exchange(
true, std::memory_order_relaxed)) {
return unit;
}
num_units_[kTopTier].fetch_sub(1, std::memory_order_relaxed);
}
steal_task_id = queue->next_steal_task_id;
}
// Try to steal from all other queues. If this succeeds, return one of the
// stolen units.
{
std::shared_lock<std::shared_mutex> guard{queues_mutex_};
for (size_t steal_trials = 0; steal_trials < queues_.size();
++steal_trials, ++steal_task_id) {
if (steal_task_id >= static_cast<int>(queues_.size())) {
steal_task_id = 0;
}
if (auto unit = StealTopTierPriorityUnit(queue, steal_task_id)) {
return unit;
}
}
}
return {};
}
// Steal units of {wanted_tier} from {steal_from_task_id} to {queue}. Return
// first stolen unit (rest put in queue of {task_id}), or {nullopt} if
// {steal_from_task_id} had no units of {wanted_tier}.
// Hold a shared lock on {queues_mutex_} when calling this method.
base::Optional<WasmCompilationUnit> StealUnitsAndGetFirst(
QueueImpl* queue, int steal_from_task_id, int wanted_tier) {
auto* steal_queue = queues_[steal_from_task_id].get();
// Cannot steal from own queue.
if (steal_queue == queue) return {};
std::vector<WasmCompilationUnit> stolen;
base::Optional<WasmCompilationUnit> returned_unit;
{
base::MutexGuard guard(&steal_queue->mutex);
auto* steal_from_vector = &steal_queue->units[wanted_tier];
if (steal_from_vector->empty()) return {};
size_t remaining = steal_from_vector->size() / 2;
auto steal_begin = steal_from_vector->begin() + remaining;
returned_unit = *steal_begin;
stolen.assign(steal_begin + 1, steal_from_vector->end());
steal_from_vector->erase(steal_begin, steal_from_vector->end());
}
base::MutexGuard guard(&queue->mutex);
auto* target_queue = &queue->units[wanted_tier];
target_queue->insert(target_queue->end(), stolen.begin(), stolen.end());
queue->next_steal_task_id = steal_from_task_id + 1;
return returned_unit;
}
// Steal one priority unit from {steal_from_task_id} to {task_id}. Return
// stolen unit, or {nullopt} if {steal_from_task_id} had no priority units.
// Hold a shared lock on {queues_mutex_} when calling this method.
base::Optional<WasmCompilationUnit> StealTopTierPriorityUnit(
QueueImpl* queue, int steal_from_task_id) {
auto* steal_queue = queues_[steal_from_task_id].get();
// Cannot steal from own queue.
if (steal_queue == queue) return {};
base::Optional<WasmCompilationUnit> returned_unit;
{
base::MutexGuard guard(&steal_queue->mutex);
while (true) {
if (steal_queue->top_tier_priority_units.empty()) return {};
auto unit = steal_queue->top_tier_priority_units.top().unit;
steal_queue->top_tier_priority_units.pop();
num_priority_units_.fetch_sub(1, std::memory_order_relaxed);
if (!top_tier_compiled_[unit.func_index()].exchange(
true, std::memory_order_relaxed)) {
returned_unit = unit;
break;
}
num_units_[kTopTier].fetch_sub(1, std::memory_order_relaxed);
}
}
base::MutexGuard guard(&queue->mutex);
queue->next_steal_task_id = steal_from_task_id + 1;
return returned_unit;
}
// {queues_mutex_} protectes {queues_};
std::shared_mutex queues_mutex_;
std::vector<std::unique_ptr<QueueImpl>> queues_;
const int num_declared_functions_;
BigUnitsQueue big_units_queue_;
std::atomic<size_t> num_units_[kNumTiers];
std::atomic<size_t> num_priority_units_{0};
std::unique_ptr<std::atomic<bool>[]> top_tier_compiled_;
std::atomic<int> next_queue_to_add{0};
};
bool CompilationUnitQueues::Queue::ShouldPublish(
int num_processed_units) const {
auto* queue = static_cast<const QueueImpl*>(this);
return num_processed_units >=
queue->publish_limit.load(std::memory_order_relaxed);
}
// The {CompilationStateImpl} keeps track of the compilation state of the
// owning NativeModule, i.e. which functions are left to be compiled.
// It contains a task manager to allow parallel and asynchronous background
// compilation of functions.
// Its public interface {CompilationState} lives in compilation-environment.h.
class CompilationStateImpl {
public:
CompilationStateImpl(const std::shared_ptr<NativeModule>& native_module,
std::shared_ptr<Counters> async_counters,
DynamicTiering dynamic_tiering);
~CompilationStateImpl() {
if (compile_job_->IsValid()) compile_job_->CancelAndDetach();
}
// Call right after the constructor, after the {compilation_state_} field in
// the {NativeModule} has been initialized.
void InitCompileJob();
// {kCancelUnconditionally}: Cancel all compilation.
// {kCancelInitialCompilation}: Cancel all compilation if initial (baseline)
// compilation is not finished yet.
enum CancellationPolicy { kCancelUnconditionally, kCancelInitialCompilation };
void CancelCompilation(CancellationPolicy);
bool cancelled() const;
// Apply a compilation hint to the initial compilation progress, updating all
// internal fields accordingly.
void ApplyCompilationHintToInitialProgress(const WasmCompilationHint& hint,
size_t hint_idx);
// Initialize compilation progress. Set compilation tiers to expect for
// baseline and top tier compilation. Must be set before
// {CommitCompilationUnits} is invoked which triggers background compilation.
void InitializeCompilationProgress(int num_import_wrappers,
int num_export_wrappers);
// Initialize the compilation progress after deserialization. This is needed
// for recompilation (e.g. for tier down) to work later.
void InitializeCompilationProgressAfterDeserialization(
base::Vector<const int> lazy_functions,
base::Vector<const int> eager_functions);
// Initializes compilation units based on the information encoded in the
// {compilation_progress_}.
void InitializeCompilationUnits(
std::unique_ptr<CompilationUnitBuilder> builder);
// Adds compilation units for another function to the
// {CompilationUnitBuilder}. This function is the streaming compilation
// equivalent to {InitializeCompilationUnits}.
void AddCompilationUnit(CompilationUnitBuilder* builder, int func_index);
// Initialize recompilation of the whole module: Setup compilation progress
// for recompilation and add the respective compilation units. The callback is
// called immediately if no recompilation is needed, or called later
// otherwise.
void InitializeRecompilation(TieringState new_tiering_state,
std::unique_ptr<CompilationEventCallback>
recompilation_finished_callback);
// Add the callback to be called on compilation events. Needs to be
// set before {CommitCompilationUnits} is run to ensure that it receives all
// events. The callback object must support being deleted from any thread.
void AddCallback(std::unique_ptr<CompilationEventCallback> callback);
// Inserts new functions to compile and kicks off compilation.
void CommitCompilationUnits(
base::Vector<WasmCompilationUnit> baseline_units,
base::Vector<WasmCompilationUnit> top_tier_units,
base::Vector<std::shared_ptr<JSToWasmWrapperCompilationUnit>>
js_to_wasm_wrapper_units);
void CommitTopTierCompilationUnit(WasmCompilationUnit);
void AddTopTierPriorityCompilationUnit(WasmCompilationUnit, size_t);
CompilationUnitQueues::Queue* GetQueueForCompileTask(int task_id);
base::Optional<WasmCompilationUnit> GetNextCompilationUnit(
CompilationUnitQueues::Queue*, CompileBaselineOnly);
std::shared_ptr<JSToWasmWrapperCompilationUnit>
GetNextJSToWasmWrapperCompilationUnit();
void FinalizeJSToWasmWrappers(Isolate* isolate, const WasmModule* module);
void OnFinishedUnits(base::Vector<WasmCode*>);
void OnFinishedJSToWasmWrapperUnits(int num);
void OnCompilationStopped(WasmFeatures detected);
void PublishDetectedFeatures(Isolate*);
void SchedulePublishCompilationResults(
std::vector<std::unique_ptr<WasmCode>> unpublished_code);
size_t NumOutstandingCompilations() const;
void SetError();
void WaitForCompilationEvent(CompilationEvent event);
void SetHighPriority() {
// TODO(wasm): Keep a lower priority for TurboFan-only jobs.
compile_job_->UpdatePriority(TaskPriority::kUserBlocking);
}
bool failed() const {
return compile_failed_.load(std::memory_order_relaxed);
}
bool baseline_compilation_finished() const {
base::MutexGuard guard(&callbacks_mutex_);
return outstanding_baseline_units_ == 0 &&
outstanding_export_wrappers_ == 0;
}
bool recompilation_finished() const {
base::MutexGuard guard(&callbacks_mutex_);
return outstanding_recompilation_functions_ == 0;
}
DynamicTiering dynamic_tiering() const { return dynamic_tiering_; }
Counters* counters() const { return async_counters_.get(); }
void SetWireBytesStorage(
std::shared_ptr<WireBytesStorage> wire_bytes_storage) {
base::MutexGuard guard(&mutex_);
wire_bytes_storage_ = std::move(wire_bytes_storage);
}
std::shared_ptr<WireBytesStorage> GetWireBytesStorage() const {
base::MutexGuard guard(&mutex_);
DCHECK_NOT_NULL(wire_bytes_storage_);
return wire_bytes_storage_;
}
void set_compilation_id(int compilation_id) {
DCHECK_EQ(compilation_id_, kInvalidCompilationID);
compilation_id_ = compilation_id;
}
std::weak_ptr<NativeModule> const native_module_weak() const {
return native_module_weak_;
}
private:
// Returns the potentially-updated {function_progress}.
uint8_t AddCompilationUnitInternal(CompilationUnitBuilder* builder,
int function_index,
uint8_t function_progress);
// Trigger callbacks according to the internal counters below
// (outstanding_...), plus the given events.
// Hold the {callbacks_mutex_} when calling this method.
void TriggerCallbacks(base::EnumSet<CompilationEvent> additional_events = {});
void PublishCompilationResults(
std::vector<std::unique_ptr<WasmCode>> unpublished_code);
void PublishCode(base::Vector<std::unique_ptr<WasmCode>> codes);
NativeModule* const native_module_;
std::weak_ptr<NativeModule> const native_module_weak_;
const std::shared_ptr<Counters> async_counters_;
// Compilation error, atomically updated. This flag can be updated and read
// using relaxed semantics.
std::atomic<bool> compile_failed_{false};
// True if compilation was cancelled and worker threads should return. This
// flag can be updated and read using relaxed semantics.
std::atomic<bool> compile_cancelled_{false};
CompilationUnitQueues compilation_unit_queues_;
// Number of wrappers to be compiled. Initialized once, counted down in
// {GetNextJSToWasmWrapperCompilationUnit}.
std::atomic<size_t> outstanding_js_to_wasm_wrappers_{0};
// Wrapper compilation units are stored in shared_ptrs so that they are kept
// alive by the tasks even if the NativeModule dies.
std::vector<std::shared_ptr<JSToWasmWrapperCompilationUnit>>
js_to_wasm_wrapper_units_;
// Cache the dynamic tiering configuration to be consistent for the whole
// compilation.
const DynamicTiering dynamic_tiering_;
// This mutex protects all information of this {CompilationStateImpl} which is
// being accessed concurrently.
mutable base::Mutex mutex_;
// The compile job handle, initialized right after construction of
// {CompilationStateImpl}.
std::unique_ptr<JobHandle> compile_job_;
// The compilation id to identify trace events linked to this compilation.
static constexpr int kInvalidCompilationID = -1;
int compilation_id_ = kInvalidCompilationID;
//////////////////////////////////////////////////////////////////////////////
// Protected by {mutex_}:
// Features detected to be used in this module. Features can be detected
// as a module is being compiled.
WasmFeatures detected_features_ = WasmFeatures::None();
// Abstraction over the storage of the wire bytes. Held in a shared_ptr so
// that background compilation jobs can keep the storage alive while
// compiling.
std::shared_ptr<WireBytesStorage> wire_bytes_storage_;
// End of fields protected by {mutex_}.
//////////////////////////////////////////////////////////////////////////////
// This mutex protects the callbacks vector, and the counters used to
// determine which callbacks to call. The counters plus the callbacks
// themselves need to be synchronized to ensure correct order of events.
mutable base::Mutex callbacks_mutex_;
//////////////////////////////////////////////////////////////////////////////
// Protected by {callbacks_mutex_}:
// Callbacks to be called on compilation events.
std::vector<std::unique_ptr<CompilationEventCallback>> callbacks_;
// Events that already happened.
base::EnumSet<CompilationEvent> finished_events_;
int outstanding_baseline_units_ = 0;
int outstanding_export_wrappers_ = 0;
// The amount of generated top tier code since the last
// {kFinishedCompilationChunk} event.
size_t bytes_since_last_chunk_ = 0;
std::vector<uint8_t> compilation_progress_;
int outstanding_recompilation_functions_ = 0;
TieringState tiering_state_ = kTieredUp;
// End of fields protected by {callbacks_mutex_}.
//////////////////////////////////////////////////////////////////////////////
// {publish_mutex_} protects {publish_queue_} and {publisher_running_}.
base::Mutex publish_mutex_;
std::vector<std::unique_ptr<WasmCode>> publish_queue_;
bool publisher_running_ = false;
// Encoding of fields in the {compilation_progress_} vector.
using RequiredBaselineTierField = base::BitField8<ExecutionTier, 0, 2>;
using RequiredTopTierField = base::BitField8<ExecutionTier, 2, 2>;
using ReachedTierField = base::BitField8<ExecutionTier, 4, 2>;
using MissingRecompilationField = base::BitField8<bool, 6, 1>;
};
CompilationStateImpl* Impl(CompilationState* compilation_state) {
return reinterpret_cast<CompilationStateImpl*>(compilation_state);
}
const CompilationStateImpl* Impl(const CompilationState* compilation_state) {
return reinterpret_cast<const CompilationStateImpl*>(compilation_state);
}
CompilationStateImpl* BackgroundCompileScope::compilation_state() const {
DCHECK(native_module_);
return Impl(native_module_->compilation_state());
}
bool BackgroundCompileScope::cancelled() const {
return native_module_ == nullptr ||
Impl(native_module_->compilation_state())->cancelled();
}
void UpdateFeatureUseCounts(Isolate* isolate, const WasmFeatures& detected) {
using Feature = v8::Isolate::UseCounterFeature;
constexpr static std::pair<WasmFeature, Feature> kUseCounters[] = {
{kFeature_reftypes, Feature::kWasmRefTypes},
{kFeature_simd, Feature::kWasmSimdOpcodes},
{kFeature_threads, Feature::kWasmThreadOpcodes},
{kFeature_eh, Feature::kWasmExceptionHandling}};
for (auto& feature : kUseCounters) {
if (detected.contains(feature.first)) isolate->CountUsage(feature.second);
}
}
} // namespace
//////////////////////////////////////////////////////
// PIMPL implementation of {CompilationState}.
CompilationState::~CompilationState() { Impl(this)->~CompilationStateImpl(); }
void CompilationState::InitCompileJob() { Impl(this)->InitCompileJob(); }
void CompilationState::CancelCompilation() {
Impl(this)->CancelCompilation(CompilationStateImpl::kCancelUnconditionally);
}
void CompilationState::CancelInitialCompilation() {
Impl(this)->CancelCompilation(
CompilationStateImpl::kCancelInitialCompilation);
}
void CompilationState::SetError() { Impl(this)->SetError(); }
void CompilationState::SetWireBytesStorage(
std::shared_ptr<WireBytesStorage> wire_bytes_storage) {
Impl(this)->SetWireBytesStorage(std::move(wire_bytes_storage));
}
std::shared_ptr<WireBytesStorage> CompilationState::GetWireBytesStorage()
const {
return Impl(this)->GetWireBytesStorage();
}
void CompilationState::AddCallback(
std::unique_ptr<CompilationEventCallback> callback) {
return Impl(this)->AddCallback(std::move(callback));
}
void CompilationState::SetHighPriority() { Impl(this)->SetHighPriority(); }
void CompilationState::InitializeAfterDeserialization(
base::Vector<const int> lazy_functions,
base::Vector<const int> eager_functions) {
Impl(this)->InitializeCompilationProgressAfterDeserialization(
lazy_functions, eager_functions);
}
bool CompilationState::failed() const { return Impl(this)->failed(); }
bool CompilationState::baseline_compilation_finished() const {
return Impl(this)->baseline_compilation_finished();
}
bool CompilationState::recompilation_finished() const {
return Impl(this)->recompilation_finished();
}
void CompilationState::set_compilation_id(int compilation_id) {
Impl(this)->set_compilation_id(compilation_id);
}
DynamicTiering CompilationState::dynamic_tiering() const {
return Impl(this)->dynamic_tiering();
}
// static
std::unique_ptr<CompilationState> CompilationState::New(
const std::shared_ptr<NativeModule>& native_module,
std::shared_ptr<Counters> async_counters, DynamicTiering dynamic_tiering) {
return std::unique_ptr<CompilationState>(reinterpret_cast<CompilationState*>(
new CompilationStateImpl(std::move(native_module),
std::move(async_counters), dynamic_tiering)));
}
// End of PIMPL implementation of {CompilationState}.
//////////////////////////////////////////////////////
namespace {
ExecutionTier ApplyHintToExecutionTier(WasmCompilationHintTier hint,
ExecutionTier default_tier) {
switch (hint) {
case WasmCompilationHintTier::kDefault:
return default_tier;
case WasmCompilationHintTier::kBaseline:
return ExecutionTier::kLiftoff;
case WasmCompilationHintTier::kOptimized:
return ExecutionTier::kTurbofan;
}
UNREACHABLE();
}
const WasmCompilationHint* GetCompilationHint(const WasmModule* module,
uint32_t func_index) {
DCHECK_LE(module->num_imported_functions, func_index);
uint32_t hint_index = declared_function_index(module, func_index);
const std::vector<WasmCompilationHint>& compilation_hints =
module->compilation_hints;
if (hint_index < compilation_hints.size()) {
return &compilation_hints[hint_index];
}
return nullptr;
}
CompileStrategy GetCompileStrategy(const WasmModule* module,
const WasmFeatures& enabled_features,
uint32_t func_index, bool lazy_module) {
if (lazy_module) return CompileStrategy::kLazy;
if (!enabled_features.has_compilation_hints()) {
return CompileStrategy::kDefault;
}
auto* hint = GetCompilationHint(module, func_index);
if (hint == nullptr) return CompileStrategy::kDefault;
switch (hint->strategy) {
case WasmCompilationHintStrategy::kLazy:
return CompileStrategy::kLazy;
case WasmCompilationHintStrategy::kEager:
return CompileStrategy::kEager;
case WasmCompilationHintStrategy::kLazyBaselineEagerTopTier:
return CompileStrategy::kLazyBaselineEagerTopTier;
case WasmCompilationHintStrategy::kDefault:
return CompileStrategy::kDefault;
}
}
struct ExecutionTierPair {
ExecutionTier baseline_tier;
ExecutionTier top_tier;
};
ExecutionTierPair GetDefaultTiersPerModule(NativeModule* native_module,
DynamicTiering dynamic_tiering,
bool lazy_module) {
const WasmModule* module = native_module->module();
if (is_asmjs_module(module)) {
return {ExecutionTier::kTurbofan, ExecutionTier::kTurbofan};
}
// TODO(13224): Use lazy compilation for debug code.
if (native_module->IsTieredDown()) {
return {ExecutionTier::kLiftoff, ExecutionTier::kLiftoff};
}
if (lazy_module) {
return {ExecutionTier::kNone, ExecutionTier::kNone};
}
ExecutionTier baseline_tier =
v8_flags.liftoff ? ExecutionTier::kLiftoff : ExecutionTier::kTurbofan;
bool eager_tier_up = !dynamic_tiering && v8_flags.wasm_tier_up;
ExecutionTier top_tier =
eager_tier_up ? ExecutionTier::kTurbofan : baseline_tier;
return {baseline_tier, top_tier};
}
ExecutionTierPair GetLazyCompilationTiers(NativeModule* native_module,
uint32_t func_index) {
DynamicTiering dynamic_tiering =
Impl(native_module->compilation_state())->dynamic_tiering();
// For lazy compilation, get the tiers we would use if lazy compilation is
// disabled.
constexpr bool kNotLazy = false;
ExecutionTierPair tiers =
GetDefaultTiersPerModule(native_module, dynamic_tiering, kNotLazy);
// Check if compilation hints override default tiering behaviour.
if (native_module->enabled_features().has_compilation_hints()) {
if (auto* hint = GetCompilationHint(native_module->module(), func_index)) {
tiers.baseline_tier =
ApplyHintToExecutionTier(hint->baseline_tier, tiers.baseline_tier);
tiers.top_tier = ApplyHintToExecutionTier(hint->top_tier, tiers.top_tier);
}
}
if (V8_UNLIKELY(v8_flags.wasm_tier_up_filter >= 0 &&
func_index !=
static_cast<uint32_t>(v8_flags.wasm_tier_up_filter))) {
tiers.top_tier = tiers.baseline_tier;
}
// Correct top tier if necessary.
static_assert(ExecutionTier::kLiftoff < ExecutionTier::kTurbofan,
"Assume an order on execution tiers");
if (tiers.baseline_tier > tiers.top_tier) {
tiers.top_tier = tiers.baseline_tier;
}
return tiers;
}
// The {CompilationUnitBuilder} builds compilation units and stores them in an
// internal buffer. The buffer is moved into the working queue of the
// {CompilationStateImpl} when {Commit} is called.
class CompilationUnitBuilder {
public:
explicit CompilationUnitBuilder(NativeModule* native_module)
: native_module_(native_module) {}
void AddImportUnit(uint32_t func_index) {
DCHECK_GT(native_module_->module()->num_imported_functions, func_index);
baseline_units_.emplace_back(func_index, ExecutionTier::kNone,
kNoDebugging);
}
void AddJSToWasmWrapperUnit(
std::shared_ptr<JSToWasmWrapperCompilationUnit> unit) {
js_to_wasm_wrapper_units_.emplace_back(std::move(unit));
}
void AddBaselineUnit(int func_index, ExecutionTier tier) {
baseline_units_.emplace_back(func_index, tier, kNoDebugging);
}
void AddTopTierUnit(int func_index, ExecutionTier tier) {
tiering_units_.emplace_back(func_index, tier, kNoDebugging);
}
void AddDebugUnit(int func_index) {
baseline_units_.emplace_back(func_index, ExecutionTier::kLiftoff,
kForDebugging);
}
void AddRecompilationUnit(int func_index, ExecutionTier tier) {
// For recompilation, just treat all units like baseline units.
baseline_units_.emplace_back(
func_index, tier,
tier == ExecutionTier::kLiftoff ? kForDebugging : kNoDebugging);
}
bool Commit() {
if (baseline_units_.empty() && tiering_units_.empty() &&
js_to_wasm_wrapper_units_.empty()) {
return false;
}
compilation_state()->CommitCompilationUnits(
base::VectorOf(baseline_units_), base::VectorOf(tiering_units_),
base::VectorOf(js_to_wasm_wrapper_units_));
Clear();
return true;
}
void Clear() {
baseline_units_.clear();
tiering_units_.clear();
js_to_wasm_wrapper_units_.clear();
}
const WasmModule* module() { return native_module_->module(); }
private:
CompilationStateImpl* compilation_state() const {
return Impl(native_module_->compilation_state());
}
NativeModule* const native_module_;
std::vector<WasmCompilationUnit> baseline_units_;
std::vector<WasmCompilationUnit> tiering_units_;
std::vector<std::shared_ptr<JSToWasmWrapperCompilationUnit>>
js_to_wasm_wrapper_units_;
};
WasmError GetWasmErrorWithName(ModuleWireBytes wire_bytes,
const WasmFunction* func,
const WasmModule* module, WasmError error) {
WasmName name = wire_bytes.GetNameOrNull(func, module);
if (name.begin() == nullptr) {
return WasmError(error.offset(), "Compiling function #%d failed: %s",
func->func_index, error.message().c_str());
} else {
TruncatedUserString<> truncated_name(name);
return WasmError(error.offset(),
"Compiling function #%d:\"%.*s\" failed: %s",
func->func_index, truncated_name.length(),
truncated_name.start(), error.message().c_str());
}
}
void SetCompileError(ErrorThrower* thrower, ModuleWireBytes wire_bytes,
const WasmFunction* func, const WasmModule* module,
WasmError error) {
thrower->CompileFailed(GetWasmErrorWithName(std::move(wire_bytes), func,
module, std::move(error)));
}
DecodeResult ValidateSingleFunction(const WasmModule* module, int func_index,
base::Vector<const uint8_t> code,
AccountingAllocator* allocator,
WasmFeatures enabled_features) {
const WasmFunction* func = &module->functions[func_index];
FunctionBody body{func->sig, func->code.offset(), code.begin(), code.end()};
WasmFeatures detected_features;
return ValidateFunctionBody(allocator, enabled_features, module,
&detected_features, body);
}
enum OnlyLazyFunctions : bool {
kAllFunctions = false,
kOnlyLazyFunctions = true,
};
void ValidateSequentially(
const WasmModule* module, NativeModule* native_module, Counters* counters,
AccountingAllocator* allocator, ErrorThrower* thrower, bool lazy_module,
OnlyLazyFunctions only_lazy_functions = kAllFunctions) {
DCHECK(!thrower->error());
uint32_t start = module->num_imported_functions;
uint32_t end = start + module->num_declared_functions;
auto enabled_features = native_module->enabled_features();
for (uint32_t func_index = start; func_index < end; func_index++) {
// Skip non-lazy functions if requested.
if (only_lazy_functions) {
CompileStrategy strategy =
GetCompileStrategy(module, enabled_features, func_index, lazy_module);
if (strategy != CompileStrategy::kLazy &&
strategy != CompileStrategy::kLazyBaselineEagerTopTier) {
continue;
}
}
ModuleWireBytes wire_bytes{native_module->wire_bytes()};
const WasmFunction* func = &module->functions[func_index];
base::Vector<const uint8_t> code = wire_bytes.GetFunctionBytes(func);
DecodeResult result = ValidateSingleFunction(module, func_index, code,
allocator, enabled_features);
if (result.failed()) {
SetCompileError(thrower, wire_bytes, func, module, result.error());
}
}
}
bool IsLazyModule(const WasmModule* module) {
return v8_flags.wasm_lazy_compilation ||
(v8_flags.asm_wasm_lazy_compilation && is_asmjs_module(module));
}
class CompileLazyTimingScope {
public:
CompileLazyTimingScope(Counters* counters, NativeModule* native_module)
: counters_(counters), native_module_(native_module) {
timer_.Start();
}
~CompileLazyTimingScope() {
base::TimeDelta elapsed = timer_.Elapsed();
native_module_->AddLazyCompilationTimeSample(elapsed.InMicroseconds());
counters_->wasm_lazy_compile_time()->AddTimedSample(elapsed);
}
private:
Counters* counters_;
NativeModule* native_module_;
base::ElapsedTimer timer_;
};
} // namespace
bool CompileLazy(Isolate* isolate, Handle<WasmInstanceObject> instance,
int func_index) {
Handle<WasmModuleObject> module_object(instance->module_object(), isolate);
NativeModule* native_module = module_object->native_module();
Counters* counters = isolate->counters();
// Put the timer scope around everything, including the {CodeSpaceWriteScope}
// and its destruction, to measure complete overhead (apart from the runtime
// function itself, which has constant overhead).
base::Optional<CompileLazyTimingScope> lazy_compile_time_scope;
if (base::TimeTicks::IsHighResolution()) {
lazy_compile_time_scope.emplace(counters, native_module);
}
DCHECK(!native_module->lazy_compile_frozen());
TRACE_LAZY("Compiling wasm-function#%d.\n", func_index);
base::ThreadTicks thread_ticks = base::ThreadTicks::IsSupported()
? base::ThreadTicks::Now()
: base::ThreadTicks();
CompilationStateImpl* compilation_state =
Impl(native_module->compilation_state());
ExecutionTierPair tiers = GetLazyCompilationTiers(native_module, func_index);
DCHECK_LE(native_module->num_imported_functions(), func_index);
DCHECK_LT(func_index, native_module->num_functions());
WasmCompilationUnit baseline_unit{func_index, tiers.baseline_tier,
kNoDebugging};
CompilationEnv env = native_module->CreateCompilationEnv();
// TODO(wasm): Use an assembler buffer cache for lazy compilation.
AssemblerBufferCache* assembler_buffer_cache = nullptr;
WasmFeatures detected_features;
WasmCompilationResult result = baseline_unit.ExecuteCompilation(
&env, compilation_state->GetWireBytesStorage().get(), counters,
assembler_buffer_cache, &detected_features);
compilation_state->OnCompilationStopped(detected_features);
if (!thread_ticks.IsNull()) {
native_module->UpdateCPUDuration(
(base::ThreadTicks::Now() - thread_ticks).InMicroseconds(),
tiers.baseline_tier);
}
// During lazy compilation, we can only get compilation errors when
// {--wasm-lazy-validation} is enabled. Otherwise, the module was fully
// verified before starting its execution.
CHECK_IMPLIES(result.failed(), v8_flags.wasm_lazy_validation);
if (result.failed()) {
return false;
}
WasmCodeRefScope code_ref_scope;
WasmCode* code;
{
CodeSpaceWriteScope code_space_write_scope(native_module);
code = native_module->PublishCode(
native_module->AddCompiledCode(std::move(result)));
}
DCHECK_EQ(func_index, code->index());
if (WasmCode::ShouldBeLogged(isolate)) {
DisallowGarbageCollection no_gc;
Object url_obj = module_object->script().name();
DCHECK(url_obj.IsString() || url_obj.IsUndefined());
std::unique_ptr<char[]> url =
url_obj.IsString() ? String::cast(url_obj).ToCString() : nullptr;
code->LogCode(isolate, url.get(), module_object->script().id());
}
counters->wasm_lazily_compiled_functions()->Increment();
const WasmModule* module = native_module->module();
const bool lazy_module = IsLazyModule(module);
if (GetCompileStrategy(module, native_module->enabled_features(), func_index,
lazy_module) == CompileStrategy::kLazy &&
tiers.baseline_tier < tiers.top_tier) {
WasmCompilationUnit tiering_unit{func_index, tiers.top_tier, kNoDebugging};
compilation_state->CommitTopTierCompilationUnit(tiering_unit);
}
// Allocate feedback vector if needed.
int feedback_vector_slots = NumFeedbackSlots(module, func_index);
if (feedback_vector_slots > 0) {
DCHECK(v8_flags.wasm_speculative_inlining);
Handle<FixedArray> vector =
isolate->factory()->NewFixedArrayWithZeroes(feedback_vector_slots);
instance->feedback_vectors().set(
declared_function_index(module, func_index), *vector);
}
return true;
}
void ThrowLazyCompilationError(Isolate* isolate,
const NativeModule* native_module,
int func_index) {
const WasmModule* module = native_module->module();
CompilationStateImpl* compilation_state =
Impl(native_module->compilation_state());
const WasmFunction* func = &module->functions[func_index];
base::Vector<const uint8_t> code =
compilation_state->GetWireBytesStorage()->GetCode(func->code);
WasmEngine* engine = GetWasmEngine();
auto enabled_features = native_module->enabled_features();
DecodeResult decode_result = ValidateSingleFunction(
module, func_index, code, engine->allocator(), enabled_features);
CHECK(decode_result.failed());
wasm::ErrorThrower thrower(isolate, nullptr);
SetCompileError(&thrower, ModuleWireBytes(native_module->wire_bytes()), func,
module, decode_result.error());
}
class TransitiveTypeFeedbackProcessor {
public:
static void Process(WasmInstanceObject instance, int func_index) {
TransitiveTypeFeedbackProcessor{instance, func_index}.ProcessQueue();
}
private:
TransitiveTypeFeedbackProcessor(WasmInstanceObject instance, int func_index)
: instance_(instance),
module_(instance.module()),
mutex_guard(&module_->type_feedback.mutex),
feedback_for_function_(module_->type_feedback.feedback_for_function) {
queue_.insert(func_index);
}
~TransitiveTypeFeedbackProcessor() { DCHECK(queue_.empty()); }
void ProcessQueue() {
while (!queue_.empty()) {
auto next = queue_.cbegin();
ProcessFunction(*next);
queue_.erase(next);
}
}
void ProcessFunction(int func_index);
void EnqueueCallees(const std::vector<CallSiteFeedback>& feedback) {
for (size_t i = 0; i < feedback.size(); i++) {
const CallSiteFeedback& csf = feedback[i];
for (int j = 0; j < csf.num_cases(); j++) {
int func = csf.function_index(j);
// Don't spend time on calls that have never been executed.
if (csf.call_count(j) == 0) continue;
// Don't recompute feedback that has already been processed.
auto existing = feedback_for_function_.find(func);
if (existing != feedback_for_function_.end() &&
existing->second.feedback_vector.size() > 0) {
continue;
}
queue_.insert(func);
}
}
}
DisallowGarbageCollection no_gc_scope_;
WasmInstanceObject instance_;
const WasmModule* const module_;
base::MutexGuard mutex_guard;
std::unordered_map<uint32_t, FunctionTypeFeedback>& feedback_for_function_;
std::set<int> queue_;
};
class FeedbackMaker {
public:
FeedbackMaker(WasmInstanceObject instance, int func_index, int num_calls)
: instance_(instance),
num_imported_functions_(
static_cast<int>(instance.module()->num_imported_functions)),
func_index_(func_index) {
result_.reserve(num_calls);
}
void AddCandidate(Object maybe_function, int count) {
if (!maybe_function.IsWasmInternalFunction()) return;
WasmInternalFunction function = WasmInternalFunction::cast(maybe_function);
if (!WasmExportedFunction::IsWasmExportedFunction(function.external())) {
return;
}
WasmExportedFunction target =
WasmExportedFunction::cast(function.external());
if (target.instance() != instance_) return;
if (target.function_index() < num_imported_functions_) return;
AddCall(target.function_index(), count);
}
void AddCall(int target, int count) {
// Keep the cache sorted (using insertion-sort), highest count first.
int insertion_index = 0;
while (insertion_index < cache_usage_ &&
counts_cache_[insertion_index] >= count) {
insertion_index++;
}
for (int shifted_index = cache_usage_ - 1; shifted_index >= insertion_index;
shifted_index--) {
targets_cache_[shifted_index + 1] = targets_cache_[shifted_index];
counts_cache_[shifted_index + 1] = counts_cache_[shifted_index];
}
targets_cache_[insertion_index] = target;
counts_cache_[insertion_index] = count;
cache_usage_++;
}
void FinalizeCall() {
if (cache_usage_ == 0) {
result_.emplace_back();
} else if (cache_usage_ == 1) {
if (v8_flags.trace_wasm_speculative_inlining) {
PrintF("[Function #%d call_ref #%zu inlineable (monomorphic)]\n",
func_index_, result_.size());
}
result_.emplace_back(targets_cache_[0], counts_cache_[0]);
} else {
if (v8_flags.trace_wasm_speculative_inlining) {
PrintF("[Function #%d call_ref #%zu inlineable (polymorphic %d)]\n",
func_index_, result_.size(), cache_usage_);
}
CallSiteFeedback::PolymorphicCase* polymorphic =
new CallSiteFeedback::PolymorphicCase[cache_usage_];
for (int i = 0; i < cache_usage_; i++) {
polymorphic[i].function_index = targets_cache_[i];
polymorphic[i].absolute_call_frequency = counts_cache_[i];
}
result_.emplace_back(polymorphic, cache_usage_);
}
cache_usage_ = 0;
}
// {GetResult} can only be called on a r-value reference to make it more
// obvious at call sites that {this} should not be used after this operation.
std::vector<CallSiteFeedback>&& GetResult() && { return std::move(result_); }
private:
const WasmInstanceObject instance_;
std::vector<CallSiteFeedback> result_;
const int num_imported_functions_;
const int func_index_;
int cache_usage_{0};
int targets_cache_[kMaxPolymorphism];
int counts_cache_[kMaxPolymorphism];
};
void TransitiveTypeFeedbackProcessor::ProcessFunction(int func_index) {
int which_vector = declared_function_index(module_, func_index);
Object maybe_feedback = instance_.feedback_vectors().get(which_vector);
if (!maybe_feedback.IsFixedArray()) return;
FixedArray feedback = FixedArray::cast(maybe_feedback);
base::Vector<uint32_t> call_direct_targets =
module_->type_feedback.feedback_for_function[func_index]
.call_targets.as_vector();
DCHECK_EQ(feedback.length(), call_direct_targets.size() * 2);
FeedbackMaker fm(instance_, func_index, feedback.length() / 2);
for (int i = 0; i < feedback.length(); i += 2) {
Object value = feedback.get(i);
if (value.IsWasmInternalFunction()) {
// Monomorphic.
int count = Smi::cast(feedback.get(i + 1)).value();
fm.AddCandidate(value, count);
} else if (value.IsFixedArray()) {
// Polymorphic.
FixedArray polymorphic = FixedArray::cast(value);
for (int j = 0; j < polymorphic.length(); j += 2) {
Object function = polymorphic.get(j);
int count = Smi::cast(polymorphic.get(j + 1)).value();
fm.AddCandidate(function, count);
}
} else if (value.IsSmi()) {
// Uninitialized, or a direct call collecting call count.
uint32_t target = call_direct_targets[i / 2];
if (target != FunctionTypeFeedback::kNonDirectCall) {
int count = Smi::cast(value).value();
fm.AddCall(static_cast<int>(target), count);
} else if (v8_flags.trace_wasm_speculative_inlining) {
PrintF("[Function #%d call #%d: uninitialized]\n", func_index, i / 2);
}
} else if (v8_flags.trace_wasm_speculative_inlining) {
if (value == ReadOnlyRoots(instance_.GetIsolate()).megamorphic_symbol()) {
PrintF("[Function #%d call #%d: megamorphic]\n", func_index, i / 2);
}
}
fm.FinalizeCall();
}
std::vector<CallSiteFeedback> result = std::move(fm).GetResult();
EnqueueCallees(result);
feedback_for_function_[func_index].feedback_vector = std::move(result);
}
void TriggerTierUp(WasmInstanceObject instance, int func_index) {
NativeModule* native_module = instance.module_object().native_module();
CompilationStateImpl* compilation_state =
Impl(native_module->compilation_state());
WasmCompilationUnit tiering_unit{func_index, ExecutionTier::kTurbofan,
kNoDebugging};
const WasmModule* module = native_module->module();
int priority;
{
base::MutexGuard mutex_guard(&module->type_feedback.mutex);
int array_index =
wasm::declared_function_index(instance.module(), func_index);
instance.tiering_budget_array()[array_index] = v8_flags.wasm_tiering_budget;
int& stored_priority =
module->type_feedback.feedback_for_function[func_index].tierup_priority;
if (stored_priority < kMaxInt) ++stored_priority;
priority = stored_priority;
}
// Only create a compilation unit if this is the first time we detect this
// function as hot (priority == 1), or if the priority increased
// significantly. The latter is assumed to be the case if the priority
// increased at least to four, and is a power of two.
if (priority == 2 || !base::bits::IsPowerOfTwo(priority)) return;
// Before adding the tier-up unit or increasing priority, do process type
// feedback for best code generation.
if (v8_flags.wasm_speculative_inlining) {
// TODO(jkummerow): we could have collisions here if different instances
// of the same module have collected different feedback. If that ever
// becomes a problem, figure out a solution.
TransitiveTypeFeedbackProcessor::Process(instance, func_index);
}
compilation_state->AddTopTierPriorityCompilationUnit(tiering_unit, priority);
}
void TierUpNowForTesting(Isolate* isolate, WasmInstanceObject instance,
int func_index) {
if (v8_flags.wasm_speculative_inlining) {
TransitiveTypeFeedbackProcessor::Process(instance, func_index);
}
auto* native_module = instance.module_object().native_module();
wasm::GetWasmEngine()->CompileFunction(isolate, native_module, func_index,
wasm::ExecutionTier::kTurbofan);
CHECK(!native_module->compilation_state()->failed());
}
namespace {
void RecordStats(CodeT codet, Counters* counters) {
if (codet.is_off_heap_trampoline()) return;
Code code = FromCodeT(codet);
counters->wasm_generated_code_size()->Increment(code.raw_body_size());
counters->wasm_reloc_size()->Increment(code.relocation_info().length());
}
enum CompilationExecutionResult : int8_t { kNoMoreUnits, kYield };
CompilationExecutionResult ExecuteJSToWasmWrapperCompilationUnits(
std::weak_ptr<NativeModule> native_module, JobDelegate* delegate) {
std::shared_ptr<JSToWasmWrapperCompilationUnit> wrapper_unit = nullptr;
int num_processed_wrappers = 0;
OperationsBarrier::Token wrapper_compilation_token;
Isolate* isolate;
{
BackgroundCompileScope compile_scope(native_module);
if (compile_scope.cancelled()) return kYield;
wrapper_unit = compile_scope.compilation_state()
->GetNextJSToWasmWrapperCompilationUnit();
if (!wrapper_unit) return kNoMoreUnits;
isolate = wrapper_unit->isolate();
wrapper_compilation_token =
wasm::GetWasmEngine()->StartWrapperCompilation(isolate);
if (!wrapper_compilation_token) return kNoMoreUnits;
}
TRACE_EVENT0("v8.wasm", "wasm.JSToWasmWrapperCompilation");
while (true) {
DCHECK_EQ(isolate, wrapper_unit->isolate());
wrapper_unit->Execute();
++num_processed_wrappers;
bool yield = delegate && delegate->ShouldYield();
BackgroundCompileScope compile_scope(native_module);
if (compile_scope.cancelled()) return kYield;
if (yield ||
!(wrapper_unit = compile_scope.compilation_state()
->GetNextJSToWasmWrapperCompilationUnit())) {
compile_scope.compilation_state()->OnFinishedJSToWasmWrapperUnits(
num_processed_wrappers);
return yield ? kYield : kNoMoreUnits;
}
}
}
namespace {
const char* GetCompilationEventName(const WasmCompilationUnit& unit,
const CompilationEnv& env) {
ExecutionTier tier = unit.tier();
if (tier == ExecutionTier::kLiftoff) {
return "wasm.BaselineCompilation";
}
if (tier == ExecutionTier::kTurbofan) {
return "wasm.TopTierCompilation";
}
if (unit.func_index() <
static_cast<int>(env.module->num_imported_functions)) {
return "wasm.WasmToJSWrapperCompilation";
}
return "wasm.OtherCompilation";
}
} // namespace
constexpr uint8_t kMainTaskId = 0;
// Run by the {BackgroundCompileJob} (on any thread).
CompilationExecutionResult ExecuteCompilationUnits(
std::weak_ptr<NativeModule> native_module, Counters* counters,
JobDelegate* delegate, CompileBaselineOnly baseline_only) {
TRACE_EVENT0("v8.wasm", "wasm.ExecuteCompilationUnits");
// Execute JS to Wasm wrapper units first, so that they are ready to be
// finalized by the main thread when the kFinishedBaselineCompilation event is
// triggered.
if (ExecuteJSToWasmWrapperCompilationUnits(native_module, delegate) ==
kYield) {
return kYield;
}
// These fields are initialized in a {BackgroundCompileScope} before
// starting compilation.
base::Optional<CompilationEnv> env;
std::shared_ptr<WireBytesStorage> wire_bytes;
std::shared_ptr<const WasmModule> module;
// Task 0 is any main thread (there might be multiple from multiple isolates),
// worker threads start at 1 (thus the "+ 1").
static_assert(kMainTaskId == 0);
int task_id = delegate ? (int{delegate->GetTaskId()} + 1) : kMainTaskId;
DCHECK_LE(0, task_id);
CompilationUnitQueues::Queue* queue;
base::Optional<WasmCompilationUnit> unit;
WasmFeatures detected_features = WasmFeatures::None();
base::ThreadTicks thread_ticks = base::ThreadTicks::IsSupported()
? base::ThreadTicks::Now()
: base::ThreadTicks();
// Preparation (synchronized): Initialize the fields above and get the first
// compilation unit.
{
BackgroundCompileScope compile_scope(native_module);
if (compile_scope.cancelled()) return kYield;
env.emplace(compile_scope.native_module()->CreateCompilationEnv());
wire_bytes = compile_scope.compilation_state()->GetWireBytesStorage();
module = compile_scope.native_module()->shared_module();
queue = compile_scope.compilation_state()->GetQueueForCompileTask(task_id);
unit = compile_scope.compilation_state()->GetNextCompilationUnit(
queue, baseline_only);
if (!unit) return kNoMoreUnits;
}
TRACE_COMPILE("ExecuteCompilationUnits (task id %d)\n", task_id);
// If PKU is enabled, use an assembler buffer cache to avoid many expensive
// buffer allocations. Otherwise, malloc/free is efficient enough to prefer
// that bit of overhead over the memory consumption increase by the cache.
base::Optional<AssemblerBufferCache> optional_assembler_buffer_cache;
AssemblerBufferCache* assembler_buffer_cache = nullptr;
// Also, open a CodeSpaceWriteScope now to have (thread-local) write access to
// the assembler buffers.
base::Optional<CodeSpaceWriteScope> write_scope_for_assembler_buffers;
if (WasmCodeManager::MemoryProtectionKeysEnabled()) {
optional_assembler_buffer_cache.emplace();
assembler_buffer_cache = &*optional_assembler_buffer_cache;
write_scope_for_assembler_buffers.emplace(nullptr);
}
std::vector<WasmCompilationResult> results_to_publish;
while (true) {
ExecutionTier current_tier = unit->tier();
const char* event_name = GetCompilationEventName(unit.value(), env.value());
TRACE_EVENT0("v8.wasm", event_name);
while (unit->tier() == current_tier) {
// (asynchronous): Execute the compilation.
WasmCompilationResult result =
unit->ExecuteCompilation(&env.value(), wire_bytes.get(), counters,
assembler_buffer_cache, &detected_features);
results_to_publish.emplace_back(std::move(result));
bool yield = delegate && delegate->ShouldYield();
// (synchronized): Publish the compilation result and get the next unit.
BackgroundCompileScope compile_scope(native_module);
if (compile_scope.cancelled()) return kYield;
if (!results_to_publish.back().succeeded()) {
compile_scope.compilation_state()->SetError();
return kNoMoreUnits;
}
if (!unit->for_debugging() && result.result_tier != current_tier) {
compile_scope.native_module()->AddLiftoffBailout();
}
// Yield or get next unit.
if (yield ||
!(unit = compile_scope.compilation_state()->GetNextCompilationUnit(
queue, baseline_only))) {
if (!thread_ticks.IsNull()) {
compile_scope.native_module()->UpdateCPUDuration(
(base::ThreadTicks::Now() - thread_ticks).InMicroseconds(),
current_tier);
}
std::vector<std::unique_ptr<WasmCode>> unpublished_code =
compile_scope.native_module()->AddCompiledCode(
base::VectorOf(std::move(results_to_publish)));
results_to_publish.clear();
compile_scope.compilation_state()->SchedulePublishCompilationResults(
std::move(unpublished_code));
compile_scope.compilation_state()->OnCompilationStopped(
detected_features);
return yield ? kYield : kNoMoreUnits;
}
// Publish after finishing a certain amount of units, to avoid contention
// when all threads publish at the end.
bool batch_full =
queue->ShouldPublish(static_cast<int>(results_to_publish.size()));
// Also publish each time the compilation tier changes from Liftoff to
// TurboFan, such that we immediately publish the baseline compilation
// results to start execution, and do not wait for a batch to fill up.
bool liftoff_finished = unit->tier() != current_tier &&
unit->tier() == ExecutionTier::kTurbofan;
if (batch_full || liftoff_finished) {
if (!thread_ticks.IsNull()) {
base::ThreadTicks thread_ticks_now = base::ThreadTicks::Now();
compile_scope.native_module()->UpdateCPUDuration(
(thread_ticks_now - thread_ticks).InMicroseconds(), current_tier);
thread_ticks = thread_ticks_now;
}
std::vector<std::unique_ptr<WasmCode>> unpublished_code =
compile_scope.native_module()->AddCompiledCode(
base::VectorOf(std::move(results_to_publish)));
results_to_publish.clear();
compile_scope.compilation_state()->SchedulePublishCompilationResults(
std::move(unpublished_code));
}
}
}
UNREACHABLE();
}
// (function is imported, canonical type index)
using JSToWasmWrapperKey = std::pair<bool, uint32_t>;
// Returns the number of units added.
int AddExportWrapperUnits(Isolate* isolate, NativeModule* native_module,
CompilationUnitBuilder* builder) {
std::unordered_set<JSToWasmWrapperKey, base::hash<JSToWasmWrapperKey>> keys;
for (auto exp : native_module->module()->export_table) {
if (exp.kind != kExternalFunction) continue;
auto& function = native_module->module()->functions[exp.index];
uint32_t canonical_type_index =
native_module->module()
->isorecursive_canonical_type_ids[function.sig_index];
JSToWasmWrapperKey key(function.imported, canonical_type_index);
if (keys.insert(key).second) {
auto unit = std::make_shared<JSToWasmWrapperCompilationUnit>(
isolate, function.sig, canonical_type_index, native_module->module(),
function.imported, native_module->enabled_features(),
JSToWasmWrapperCompilationUnit::kAllowGeneric);
builder->AddJSToWasmWrapperUnit(std::move(unit));
}
}
return static_cast<int>(keys.size());
}
// Returns the number of units added.
int AddImportWrapperUnits(NativeModule* native_module,
CompilationUnitBuilder* builder) {
std::unordered_set<WasmImportWrapperCache::CacheKey,
WasmImportWrapperCache::CacheKeyHash>
keys;
int num_imported_functions = native_module->num_imported_functions();
for (int func_index = 0; func_index < num_imported_functions; func_index++) {
const WasmFunction& function =
native_module->module()->functions[func_index];
if (!IsJSCompatibleSignature(function.sig, native_module->module(),
native_module->enabled_features())) {
continue;
}
uint32_t canonical_type_index =
native_module->module()
->isorecursive_canonical_type_ids[function.sig_index];
WasmImportWrapperCache::CacheKey key(
compiler::kDefaultImportCallKind, canonical_type_index,
static_cast<int>(function.sig->parameter_count()), kNoSuspend);
auto it = keys.insert(key);
if (it.second) {
// Ensure that all keys exist in the cache, so that we can populate the
// cache later without locking.
(*native_module->import_wrapper_cache())[key] = nullptr;
builder->AddImportUnit(func_index);
}
}
return static_cast<int>(keys.size());
}
void InitializeLazyCompilation(NativeModule* native_module) {
const bool lazy_module = IsLazyModule(native_module->module());
auto* module = native_module->module();
uint32_t start = module->num_imported_functions;
uint32_t end = start + module->num_declared_functions;
base::Optional<CodeSpaceWriteScope> lazy_code_space_write_scope;
for (uint32_t func_index = start; func_index < end; func_index++) {
CompileStrategy strategy = GetCompileStrategy(
module, native_module->enabled_features(), func_index, lazy_module);
if (strategy == CompileStrategy::kLazy ||
strategy == CompileStrategy::kLazyBaselineEagerTopTier) {
// Open a single scope for all following calls to {UseLazyStub()}, instead
// of flipping page permissions for each {func_index} individually.
if (!lazy_code_space_write_scope.has_value()) {
lazy_code_space_write_scope.emplace(native_module);
}
native_module->UseLazyStub(func_index);
}
}
}
std::unique_ptr<CompilationUnitBuilder> InitializeCompilation(
Isolate* isolate, NativeModule* native_module) {
InitializeLazyCompilation(native_module);
CompilationStateImpl* compilation_state =
Impl(native_module->compilation_state());
auto builder = std::make_unique<CompilationUnitBuilder>(native_module);
int num_import_wrappers = AddImportWrapperUnits(native_module, builder.get());
int num_export_wrappers =
AddExportWrapperUnits(isolate, native_module, builder.get());
compilation_state->InitializeCompilationProgress(num_import_wrappers,
num_export_wrappers);
return builder;
}
bool MayCompriseLazyFunctions(const WasmModule* module,
const WasmFeatures& enabled_features,
bool lazy_module) {
if (lazy_module || enabled_features.has_compilation_hints()) return true;
#ifdef ENABLE_SLOW_DCHECKS
int start = module->num_imported_functions;
int end = start + module->num_declared_functions;
for (int func_index = start; func_index < end; func_index++) {
SLOW_DCHECK(GetCompileStrategy(module, enabled_features, func_index,
lazy_module) != CompileStrategy::kLazy);
}
#endif
return false;
}
class CompilationTimeCallback : public CompilationEventCallback {
public:
enum CompileMode { kSynchronous, kAsync, kStreaming };
explicit CompilationTimeCallback(
std::shared_ptr<Counters> async_counters,
std::shared_ptr<metrics::Recorder> metrics_recorder,
v8::metrics::Recorder::ContextId context_id,
std::weak_ptr<NativeModule> native_module, CompileMode compile_mode)
: start_time_(base::TimeTicks::Now()),
async_counters_(std::move(async_counters)),
metrics_recorder_(std::move(metrics_recorder)),
context_id_(context_id),
native_module_(std::move(native_module)),
compile_mode_(compile_mode) {}
void call(CompilationEvent compilation_event) override {
DCHECK(base::TimeTicks::IsHighResolution());
std::shared_ptr<NativeModule> native_module = native_module_.lock();
if (!native_module) return;
auto now = base::TimeTicks::Now();
auto duration = now - start_time_;
if (compilation_event == CompilationEvent::kFinishedBaselineCompilation) {
// Reset {start_time_} to measure tier-up time.
start_time_ = now;
if (compile_mode_ != kSynchronous) {
TimedHistogram* histogram =
compile_mode_ == kAsync
? async_counters_->wasm_async_compile_wasm_module_time()
: async_counters_->wasm_streaming_compile_wasm_module_time();
histogram->AddSample(static_cast<int>(duration.InMicroseconds()));
}
v8::metrics::WasmModuleCompiled event{
(compile_mode_ != kSynchronous), // async
(compile_mode_ == kStreaming), // streamed
false, // cached
false, // deserialized
v8_flags.wasm_lazy_compilation, // lazy
true, // success
native_module->liftoff_code_size(), // code_size_in_bytes
native_module->liftoff_bailout_count(), // liftoff_bailout_count
duration.InMicroseconds(), // wall_clock_duration_in_us
static_cast<int64_t>( // cpu_time_duration_in_us
native_module->baseline_compilation_cpu_duration())};
metrics_recorder_->DelayMainThreadEvent(event, context_id_);
}
if (compilation_event == CompilationEvent::kFailedCompilation) {
v8::metrics::WasmModuleCompiled event{
(compile_mode_ != kSynchronous), // async
(compile_mode_ == kStreaming), // streamed
false, // cached
false, // deserialized
v8_flags.wasm_lazy_compilation, // lazy
false, // success
native_module->liftoff_code_size(), // code_size_in_bytes
native_module->liftoff_bailout_count(), // liftoff_bailout_count
duration.InMicroseconds(), // wall_clock_duration_in_us
static_cast<int64_t>( // cpu_time_duration_in_us
native_module->baseline_compilation_cpu_duration())};
metrics_recorder_->DelayMainThreadEvent(event, context_id_);
}
}
private:
base::TimeTicks start_time_;
const std::shared_ptr<Counters> async_counters_;
std::shared_ptr<metrics::Recorder> metrics_recorder_;
v8::metrics::Recorder::ContextId context_id_;
std::weak_ptr<NativeModule> native_module_;
const CompileMode compile_mode_;
};
void CompileNativeModule(Isolate* isolate,
v8::metrics::Recorder::ContextId context_id,
ErrorThrower* thrower, const WasmModule* wasm_module,
std::shared_ptr<NativeModule> native_module) {
CHECK(!v8_flags.jitless);
ModuleWireBytes wire_bytes(native_module->wire_bytes());
const bool lazy_module = IsLazyModule(wasm_module);
if (!v8_flags.wasm_lazy_validation && wasm_module->origin == kWasmOrigin &&
MayCompriseLazyFunctions(wasm_module, native_module->enabled_features(),
lazy_module)) {
// Validate wasm modules for lazy compilation if requested. Never validate
// asm.js modules as these are valid by construction (additionally a CHECK
// will catch this during lazy compilation).
ValidateSequentially(wasm_module, native_module.get(), isolate->counters(),
isolate->allocator(), thrower, lazy_module,
kOnlyLazyFunctions);
// On error: Return and leave the module in an unexecutable state.
if (thrower->error()) return;
}
DCHECK_GE(kMaxInt, native_module->module()->num_declared_functions);
// The callback captures a shared ptr to the semaphore.
auto* compilation_state = Impl(native_module->compilation_state());
if (base::TimeTicks::IsHighResolution()) {
compilation_state->AddCallback(std::make_unique<CompilationTimeCallback>(
isolate->async_counters(), isolate->metrics_recorder(), context_id,
native_module, CompilationTimeCallback::kSynchronous));
}
// Initialize the compilation units and kick off background compile tasks.
std::unique_ptr<CompilationUnitBuilder> builder =
InitializeCompilation(isolate, native_module.get());
compilation_state->InitializeCompilationUnits(std::move(builder));
compilation_state->WaitForCompilationEvent(
CompilationEvent::kFinishedExportWrappers);
if (compilation_state->failed()) {
DCHECK_IMPLIES(lazy_module, !v8_flags.wasm_lazy_validation);
ValidateSequentially(wasm_module, native_module.get(), isolate->counters(),
isolate->allocator(), thrower, lazy_module);
CHECK(thrower->error());
return;
}
compilation_state->FinalizeJSToWasmWrappers(isolate, native_module->module());
compilation_state->WaitForCompilationEvent(
CompilationEvent::kFinishedBaselineCompilation);
compilation_state->PublishDetectedFeatures(isolate);
if (compilation_state->failed()) {
DCHECK_IMPLIES(lazy_module, !v8_flags.wasm_lazy_validation);
ValidateSequentially(wasm_module, native_module.get(), isolate->counters(),
isolate->allocator(), thrower, lazy_module);
CHECK(thrower->error());
}
}
class BackgroundCompileJob final : public JobTask {
public:
explicit BackgroundCompileJob(std::weak_ptr<NativeModule> native_module,
std::shared_ptr<Counters> async_counters)
: native_module_(std::move(native_module)),
engine_barrier_(GetWasmEngine()->GetBarrierForBackgroundCompile()),
async_counters_(std::move(async_counters)) {}
void Run(JobDelegate* delegate) override {
auto engine_scope = engine_barrier_->TryLock();
if (!engine_scope) return;
ExecuteCompilationUnits(native_module_, async_counters_.get(), delegate,
kBaselineOrTopTier);
}
size_t GetMaxConcurrency(size_t worker_count) const override {
BackgroundCompileScope compile_scope(native_module_);
if (compile_scope.cancelled()) return 0;
// NumOutstandingCompilations() does not reflect the units that running
// workers are processing, thus add the current worker count to that number.
return std::min(
static_cast<size_t>(v8_flags.wasm_num_compilation_tasks),
worker_count +
compile_scope.compilation_state()->NumOutstandingCompilations());
}
private:
std::weak_ptr<NativeModule> native_module_;
std::shared_ptr<OperationsBarrier> engine_barrier_;
const std::shared_ptr<Counters> async_counters_;
};
} // namespace
std::shared_ptr<NativeModule> CompileToNativeModule(
Isolate* isolate, const WasmFeatures& enabled, ErrorThrower* thrower,
std::shared_ptr<const WasmModule> module, const ModuleWireBytes& wire_bytes,
int compilation_id, v8::metrics::Recorder::ContextId context_id) {
const WasmModule* wasm_module = module.get();
WasmEngine* engine = GetWasmEngine();
base::OwnedVector<uint8_t> wire_bytes_copy =
base::OwnedVector<uint8_t>::Of(wire_bytes.module_bytes());
// Prefer {wire_bytes_copy} to {wire_bytes.module_bytes()} for the temporary
// cache key. When we eventually install the module in the cache, the wire
// bytes of the temporary key and the new key have the same base pointer and
// we can skip the full bytes comparison.
std::shared_ptr<NativeModule> native_module = engine->MaybeGetNativeModule(
wasm_module->origin, wire_bytes_copy.as_vector(), isolate);
if (native_module) {
CompileJsToWasmWrappers(isolate, wasm_module);
return native_module;
}
base::Optional<TimedHistogramScope> wasm_compile_module_time_scope;
if (base::TimeTicks::IsHighResolution()) {
wasm_compile_module_time_scope.emplace(SELECT_WASM_COUNTER(
isolate->counters(), wasm_module->origin, wasm_compile, module_time));
}
// Embedder usage count for declared shared memories.
if (wasm_module->has_shared_memory) {
isolate->CountUsage(v8::Isolate::UseCounterFeature::kWasmSharedMemory);
}
// Create a new {NativeModule} first.
const bool include_liftoff =
module->origin == kWasmOrigin && v8_flags.liftoff;
size_t code_size_estimate =
wasm::WasmCodeManager::EstimateNativeModuleCodeSize(
module.get(), include_liftoff,
DynamicTiering{v8_flags.wasm_dynamic_tiering.value()});
native_module =
engine->NewNativeModule(isolate, enabled, module, code_size_estimate);
native_module->SetWireBytes(std::move(wire_bytes_copy));
native_module->compilation_state()->set_compilation_id(compilation_id);
// Sync compilation is user blocking, so we increase the priority.
native_module->compilation_state()->SetHighPriority();
CompileNativeModule(isolate, context_id, thrower, wasm_module, native_module);
bool cache_hit = !engine->UpdateNativeModuleCache(thrower->error(),
&native_module, isolate);
if (thrower->error()) return {};
if (cache_hit) {
CompileJsToWasmWrappers(isolate, wasm_module);
return native_module;
}
// Ensure that the code objects are logged before returning.
engine->LogOutstandingCodesForIsolate(isolate);
return native_module;
}
void RecompileNativeModule(NativeModule* native_module,
TieringState tiering_state) {
// Install a callback to notify us once background recompilation finished.
auto recompilation_finished_semaphore = std::make_shared<base::Semaphore>(0);
auto* compilation_state = Impl(native_module->compilation_state());
class RecompilationFinishedCallback : public CompilationEventCallback {
public:
explicit RecompilationFinishedCallback(
std::shared_ptr<base::Semaphore> recompilation_finished_semaphore)
: recompilation_finished_semaphore_(
std::move(recompilation_finished_semaphore)) {}
void call(CompilationEvent event) override {
DCHECK_NE(CompilationEvent::kFailedCompilation, event);
if (event == CompilationEvent::kFinishedRecompilation) {
recompilation_finished_semaphore_->Signal();
}
}
private:
std::shared_ptr<base::Semaphore> recompilation_finished_semaphore_;
};
// The callback captures a shared ptr to the semaphore.
// Initialize the compilation units and kick off background compile tasks.
compilation_state->InitializeRecompilation(
tiering_state, std::make_unique<RecompilationFinishedCallback>(
recompilation_finished_semaphore));
constexpr JobDelegate* kNoDelegate = nullptr;
ExecuteCompilationUnits(compilation_state->native_module_weak(),
compilation_state->counters(), kNoDelegate,
kBaselineOnly);
recompilation_finished_semaphore->Wait();
DCHECK(!compilation_state->failed());
}
AsyncCompileJob::AsyncCompileJob(
Isolate* isolate, const WasmFeatures& enabled,
std::unique_ptr<byte[]> bytes_copy, size_t length, Handle<Context> context,
Handle<Context> incumbent_context, const char* api_method_name,
std::shared_ptr<CompilationResultResolver> resolver, int compilation_id)
: isolate_(isolate),
api_method_name_(api_method_name),
enabled_features_(enabled),
dynamic_tiering_(DynamicTiering{v8_flags.wasm_dynamic_tiering.value()}),
wasm_lazy_compilation_(v8_flags.wasm_lazy_compilation),
start_time_(base::TimeTicks::Now()),
bytes_copy_(std::move(bytes_copy)),
wire_bytes_(bytes_copy_.get(), bytes_copy_.get() + length),
resolver_(std::move(resolver)),
compilation_id_(compilation_id) {
TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("v8.wasm.detailed"),
"wasm.AsyncCompileJob");
CHECK(v8_flags.wasm_async_compilation);
CHECK(!v8_flags.jitless);
v8::Isolate* v8_isolate = reinterpret_cast<v8::Isolate*>(isolate);
v8::Platform* platform = V8::GetCurrentPlatform();
foreground_task_runner_ = platform->GetForegroundTaskRunner(v8_isolate);
native_context_ =
isolate->global_handles()->Create(context->native_context());
incumbent_context_ = isolate->global_handles()->Create(*incumbent_context);
DCHECK(native_context_->IsNativeContext());
context_id_ = isolate->GetOrRegisterRecorderContextId(native_context_);
metrics_event_.async = true;
}
void AsyncCompileJob::Start() {
DoAsync<DecodeModule>(isolate_->counters(),
isolate_->metrics_recorder()); // --
}
void AsyncCompileJob::Abort() {
// Removing this job will trigger the destructor, which will cancel all
// compilation.
GetWasmEngine()->RemoveCompileJob(this);
}
class AsyncStreamingProcessor final : public StreamingProcessor {
public:
explicit AsyncStreamingProcessor(AsyncCompileJob* job,
std::shared_ptr<Counters> counters,
AccountingAllocator* allocator);
~AsyncStreamingProcessor() override;
bool ProcessModuleHeader(base::Vector<const uint8_t> bytes,
uint32_t offset) override;
bool ProcessSection(SectionCode section_code,
base::Vector<const uint8_t> bytes,
uint32_t offset) override;
bool ProcessCodeSectionHeader(int num_functions,
uint32_t functions_mismatch_error_offset,
std::shared_ptr<WireBytesStorage>,
int code_section_start,
int code_section_length) override;
void ProcessFunctionBody(base::Vector<const uint8_t> bytes,
uint32_t offset) override;
void OnFinishedChunk() override;
void OnFinishedStream(base::OwnedVector<uint8_t> bytes) override;
void OnError(const WasmError&) override;
void OnAbort() override;
bool Deserialize(base::Vector<const uint8_t> wire_bytes,
base::Vector<const uint8_t> module_bytes) override;
private:
enum ErrorLocation { kErrorInFunction, kErrorInSection };
// Finishes the AsyncCompileJob with an error.
void FinishAsyncCompileJobWithError(
const WasmError&, ErrorLocation error_location = kErrorInSection);
void CommitCompilationUnits();
ModuleDecoder decoder_;
AsyncCompileJob* job_;
std::unique_ptr<CompilationUnitBuilder> compilation_unit_builder_;
int num_functions_ = 0;
bool prefix_cache_hit_ = false;
bool before_code_section_ = true;
std::shared_ptr<Counters> async_counters_;
AccountingAllocator* allocator_;
// Running hash of the wire bytes up to code section size, but excluding the
// code section itself. Used by the {NativeModuleCache} to detect potential
// duplicate modules.
size_t prefix_hash_;
};
std::shared_ptr<StreamingDecoder> AsyncCompileJob::CreateStreamingDecoder() {
DCHECK_NULL(stream_);
stream_ = StreamingDecoder::CreateAsyncStreamingDecoder(
std::make_unique<AsyncStreamingProcessor>(
this, isolate_->async_counters(), isolate_->allocator()));
return stream_;
}
AsyncCompileJob::~AsyncCompileJob() {
// Note: This destructor always runs on the foreground thread of the isolate.
background_task_manager_.CancelAndWait();
// If initial compilation did not finish yet we can abort it.
if (native_module_) {
Impl(native_module_->compilation_state())
->CancelCompilation(CompilationStateImpl::kCancelInitialCompilation);
}
// Tell the streaming decoder that the AsyncCompileJob is not available
// anymore.
// TODO(ahaas): Is this notification really necessary? Check
// https://crbug.com/888170.
if (stream_) stream_->NotifyCompilationEnded();
CancelPendingForegroundTask();
isolate_->global_handles()->Destroy(native_context_.location());
isolate_->global_handles()->Destroy(incumbent_context_.location());
if (!module_object_.is_null()) {
isolate_->global_handles()->Destroy(module_object_.location());
}
}
void AsyncCompileJob::CreateNativeModule(
std::shared_ptr<const WasmModule> module, size_t code_size_estimate) {
// Embedder usage count for declared shared memories.
if (module->has_shared_memory) {
isolate_->CountUsage(v8::Isolate::UseCounterFeature::kWasmSharedMemory);
}
// TODO(wasm): Improve efficiency of storing module wire bytes. Only store
// relevant sections, not function bodies
// Create the module object and populate with compiled functions and
// information needed at instantiation time.
native_module_ = GetWasmEngine()->NewNativeModule(
isolate_, enabled_features_, std::move(module), code_size_estimate);
native_module_->SetWireBytes({std::move(bytes_copy_), wire_bytes_.length()});
native_module_->compilation_state()->set_compilation_id(compilation_id_);
}
bool AsyncCompileJob::GetOrCreateNativeModule(
std::shared_ptr<const WasmModule> module, size_t code_size_estimate) {
native_module_ = GetWasmEngine()->MaybeGetNativeModule(
module->origin, wire_bytes_.module_bytes(), isolate_);
if (native_module_ == nullptr) {
CreateNativeModule(std::move(module), code_size_estimate);
return false;
}
return true;
}
void AsyncCompileJob::PrepareRuntimeObjects() {
// Create heap objects for script and module bytes to be stored in the
// module object. Asm.js is not compiled asynchronously.
DCHECK(module_object_.is_null());
auto source_url =
stream_ ? base::VectorOf(stream_->url()) : base::Vector<const char>();
auto script =
GetWasmEngine()->GetOrCreateScript(isolate_, native_module_, source_url);
Handle<WasmModuleObject> module_object =
WasmModuleObject::New(isolate_, native_module_, script);
module_object_ = isolate_->global_handles()->Create(*module_object);
}
// This function assumes that it is executed in a HandleScope, and that a
// context is set on the isolate.
void AsyncCompileJob::FinishCompile(bool is_after_cache_hit) {
TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("v8.wasm.detailed"),
"wasm.FinishAsyncCompile");
bool is_after_deserialization = !module_object_.is_null();
auto compilation_state = Impl(native_module_->compilation_state());
if (!is_after_deserialization) {
if (stream_) {
stream_->NotifyNativeModuleCreated(native_module_);
}
PrepareRuntimeObjects();
}
// Measure duration of baseline compilation or deserialization from cache.
if (base::TimeTicks::IsHighResolution()) {
base::TimeDelta duration = base::TimeTicks::Now() - start_time_;
int duration_usecs = static_cast<int>(duration.InMicroseconds());
isolate_->counters()->wasm_streaming_finish_wasm_module_time()->AddSample(
duration_usecs);
if (is_after_cache_hit || is_after_deserialization) {
v8::metrics::WasmModuleCompiled event{
true, // async
true, // streamed
is_after_cache_hit, // cached
is_after_deserialization, // deserialized
wasm_lazy_compilation_, // lazy
!compilation_state->failed(), // success
native_module_->turbofan_code_size(), // code_size_in_bytes
native_module_->liftoff_bailout_count(), // liftoff_bailout_count
duration.InMicroseconds(), // wall_clock_duration_in_us
static_cast<int64_t>( // cpu_time_duration_in_us
native_module_->baseline_compilation_cpu_duration())};
isolate_->metrics_recorder()->DelayMainThreadEvent(event, context_id_);
}
}
DCHECK(!isolate_->context().is_null());
// Finish the wasm script now and make it public to the debugger.
Handle<Script> script(module_object_->script(), isolate_);
const WasmModule* module = module_object_->module();
if (script->type() == Script::TYPE_WASM &&
module->debug_symbols.type == WasmDebugSymbols::Type::SourceMap &&
!module->debug_symbols.external_url.is_empty()) {
ModuleWireBytes wire_bytes(module_object_->native_module()->wire_bytes());
MaybeHandle<String> src_map_str = isolate_->factory()->NewStringFromUtf8(
wire_bytes.GetNameOrNull(module->debug_symbols.external_url),
AllocationType::kOld);
script->set_source_mapping_url(*src_map_str.ToHandleChecked());
}
{
TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("v8.wasm.detailed"),
"wasm.Debug.OnAfterCompile");
isolate_->debug()->OnAfterCompile(script);
}
// TODO(bbudge) Allow deserialization without wrapper compilation, so we can
// just compile wrappers here.
if (!is_after_deserialization) {
if (is_after_cache_hit) {
// TODO(thibaudm): Look into sharing wrappers.
CompileJsToWasmWrappers(isolate_, module);
} else {
compilation_state->FinalizeJSToWasmWrappers(isolate_, module);
}
}
// We can only update the feature counts once the entire compile is done.
compilation_state->PublishDetectedFeatures(isolate_);
// We might need to recompile the module for debugging, if the debugger was
// enabled while streaming compilation was running. Since handling this while
// compiling via streaming is tricky, we just tier down now, before publishing
// the module.
if (native_module_->IsTieredDown()) native_module_->RecompileForTiering();
// Finally, log all generated code (it does not matter if this happens
// repeatedly in case the script is shared).
native_module_->LogWasmCodes(isolate_, module_object_->script());
FinishModule();
}
void AsyncCompileJob::DecodeFailed(const WasmError& error) {
ErrorThrower thrower(isolate_, api_method_name_);
thrower.CompileFailed(error);
// {job} keeps the {this} pointer alive.
std::shared_ptr<AsyncCompileJob> job =
GetWasmEngine()->RemoveCompileJob(this);
resolver_->OnCompilationFailed(thrower.Reify());
}
void AsyncCompileJob::AsyncCompileFailed() {
ErrorThrower thrower(isolate_, api_method_name_);
DCHECK_EQ(native_module_->module()->origin, kWasmOrigin);
const bool lazy_module = wasm_lazy_compilation_;
ValidateSequentially(native_module_->module(), native_module_.get(),
isolate_->counters(), isolate_->allocator(), &thrower,
lazy_module);
DCHECK(thrower.error());
// {job} keeps the {this} pointer alive.
std::shared_ptr<AsyncCompileJob> job =
GetWasmEngine()->RemoveCompileJob(this);
resolver_->OnCompilationFailed(thrower.Reify());
}
void AsyncCompileJob::AsyncCompileSucceeded(Handle<WasmModuleObject> result) {
TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("v8.wasm.detailed"),
"wasm.OnCompilationSucceeded");
// We have to make sure that an "incumbent context" is available in case
// the module's start function calls out to Blink.
Local<v8::Context> backup_incumbent_context =
Utils::ToLocal(incumbent_context_);
v8::Context::BackupIncumbentScope incumbent(backup_incumbent_context);
resolver_->OnCompilationSucceeded(result);
}
class AsyncCompileJob::CompilationStateCallback
: public CompilationEventCallback {
public:
explicit CompilationStateCallback(AsyncCompileJob* job) : job_(job) {}
void call(CompilationEvent event) override {
// This callback is only being called from a foreground task.
switch (event) {
case CompilationEvent::kFinishedExportWrappers:
// Even if baseline compilation units finish first, we trigger the
// "kFinishedExportWrappers" event first.
DCHECK(!last_event_.has_value());
break;
case CompilationEvent::kFinishedBaselineCompilation:
DCHECK_EQ(CompilationEvent::kFinishedExportWrappers, last_event_);
if (job_->DecrementAndCheckFinisherCount(kCompilation)) {
// Install the native module in the cache, or reuse a conflicting one.
// If we get a conflicting module, wait until we are back in the
// main thread to update {job_->native_module_} to avoid a data race.
std::shared_ptr<NativeModule> native_module = job_->native_module_;
bool cache_hit = !GetWasmEngine()->UpdateNativeModuleCache(
false, &native_module, job_->isolate_);
DCHECK_EQ(cache_hit, native_module != job_->native_module_);
job_->DoSync<CompileFinished>(cache_hit ? std::move(native_module)
: nullptr);
}
break;
case CompilationEvent::kFinishedCompilationChunk:
DCHECK(CompilationEvent::kFinishedBaselineCompilation == last_event_ ||
CompilationEvent::kFinishedCompilationChunk == last_event_);
break;
case CompilationEvent::kFailedCompilation:
DCHECK(!last_event_.has_value() ||
last_event_ == CompilationEvent::kFinishedExportWrappers);
if (job_->DecrementAndCheckFinisherCount(kCompilation)) {
// Don't update {job_->native_module_} to avoid data races with other
// compilation threads. Use a copy of the shared pointer instead.
std::shared_ptr<NativeModule> native_module = job_->native_module_;
GetWasmEngine()->UpdateNativeModuleCache(true, &native_module,
job_->isolate_);
job_->DoSync<CompileFailed>();
}
break;
case CompilationEvent::kFinishedRecompilation:
// This event can happen out of order, hence don't remember this in
// {last_event_}.
return;
}
#ifdef DEBUG
last_event_ = event;
#endif
}
private:
AsyncCompileJob* job_;
#ifdef DEBUG
// This will be modified by different threads, but they externally
// synchronize, so no explicit synchronization (currently) needed here.
base::Optional<CompilationEvent> last_event_;
#endif
};
// A closure to run a compilation step (either as foreground or background
// task) and schedule the next step(s), if any.
class AsyncCompileJob::CompileStep {
public:
virtual ~CompileStep() = default;
void Run(AsyncCompileJob* job, bool on_foreground) {
if (on_foreground) {
HandleScope scope(job->isolate_);
SaveAndSwitchContext saved_context(job->isolate_, *job->native_context_);
RunInForeground(job);
} else {
RunInBackground(job);
}
}
virtual void RunInForeground(AsyncCompileJob*) { UNREACHABLE(); }
virtual void RunInBackground(AsyncCompileJob*) { UNREACHABLE(); }
};
class AsyncCompileJob::CompileTask : public CancelableTask {
public:
CompileTask(AsyncCompileJob* job, bool on_foreground)
// We only manage the background tasks with the {CancelableTaskManager} of
// the {AsyncCompileJob}. Foreground tasks are managed by the system's
// {CancelableTaskManager}. Background tasks cannot spawn tasks managed by
// their own task manager.
: CancelableTask(on_foreground ? job->isolate_->cancelable_task_manager()
: &job->background_task_manager_),
job_(job),
on_foreground_(on_foreground) {}
~CompileTask() override {
if (job_ != nullptr && on_foreground_) ResetPendingForegroundTask();
}
void RunInternal() final {
if (!job_) return;
if (on_foreground_) ResetPendingForegroundTask();
job_->step_->Run(job_, on_foreground_);
// After execution, reset {job_} such that we don't try to reset the pending
// foreground task when the task is deleted.
job_ = nullptr;
}
void Cancel() {
DCHECK_NOT_NULL(job_);
job_ = nullptr;
}
private:
// {job_} will be cleared to cancel a pending task.
AsyncCompileJob* job_;
bool on_foreground_;
void ResetPendingForegroundTask() const {
DCHECK_EQ(this, job_->pending_foreground_task_);
job_->pending_foreground_task_ = nullptr;
}
};
void AsyncCompileJob::StartForegroundTask() {
DCHECK_NULL(pending_foreground_task_);
auto new_task = std::make_unique<CompileTask>(this, true);
pending_foreground_task_ = new_task.get();
foreground_task_runner_->PostTask(std::move(new_task));
}
void AsyncCompileJob::ExecuteForegroundTaskImmediately() {
DCHECK_NULL(pending_foreground_task_);
auto new_task = std::make_unique<CompileTask>(this, true);
pending_foreground_task_ = new_task.get();
new_task->Run();
}
void AsyncCompileJob::CancelPendingForegroundTask() {
if (!pending_foreground_task_) return;
pending_foreground_task_->Cancel();
pending_foreground_task_ = nullptr;
}
void AsyncCompileJob::StartBackgroundTask() {
auto task = std::make_unique<CompileTask>(this, false);
// If --wasm-num-compilation-tasks=0 is passed, do only spawn foreground
// tasks. This is used to make timing deterministic.
if (v8_flags.wasm_num_compilation_tasks > 0) {
V8::GetCurrentPlatform()->CallOnWorkerThread(std::move(task));
} else {
foreground_task_runner_->PostTask(std::move(task));
}
}
template <typename Step,
AsyncCompileJob::UseExistingForegroundTask use_existing_fg_task,
typename... Args>
void AsyncCompileJob::DoSync(Args&&... args) {
NextStep<Step>(std::forward<Args>(args)...);
if (use_existing_fg_task && pending_foreground_task_ != nullptr) return;
StartForegroundTask();
}
template <typename Step, typename... Args>
void AsyncCompileJob::DoImmediately(Args&&... args) {
NextStep<Step>(std::forward<Args>(args)...);
ExecuteForegroundTaskImmediately();
}
template <typename Step, typename... Args>
void AsyncCompileJob::DoAsync(Args&&... args) {
NextStep<Step>(std::forward<Args>(args)...);
StartBackgroundTask();
}
template <typename Step, typename... Args>
void AsyncCompileJob::NextStep(Args&&... args) {
step_.reset(new Step(std::forward<Args>(args)...));
}
//==========================================================================
// Step 1: (async) Decode the module.
//==========================================================================
class AsyncCompileJob::DecodeModule : public AsyncCompileJob::CompileStep {
public:
explicit DecodeModule(Counters* counters,
std::shared_ptr<metrics::Recorder> metrics_recorder)
: counters_(counters), metrics_recorder_(std::move(metrics_recorder)) {}
void RunInBackground(AsyncCompileJob* job) override {
ModuleResult result;
{
DisallowHandleAllocation no_handle;
DisallowGarbageCollection no_gc;
// Decode the module bytes.
TRACE_COMPILE("(1) Decoding module...\n");
TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("v8.wasm.detailed"),
"wasm.DecodeModule");
auto enabled_features = job->enabled_features_;
result = DecodeWasmModule(
enabled_features, job->wire_bytes_.start(), job->wire_bytes_.end(),
false, kWasmOrigin, counters_, metrics_recorder_, job->context_id(),
DecodingMethod::kAsync, GetWasmEngine()->allocator());
// Validate lazy functions here if requested.
if (!v8_flags.wasm_lazy_validation && result.ok()) {
const WasmModule* module = result.value().get();
DCHECK_EQ(module->origin, kWasmOrigin);
const bool lazy_module = job->wasm_lazy_compilation_;
if (MayCompriseLazyFunctions(module, enabled_features, lazy_module)) {
auto allocator = GetWasmEngine()->allocator();
int start = module->num_imported_functions;
int end = start + module->num_declared_functions;
for (int func_index = start; func_index < end; func_index++) {
const WasmFunction* func = &module->functions[func_index];
base::Vector<const uint8_t> code =
job->wire_bytes_.GetFunctionBytes(func);
CompileStrategy strategy = GetCompileStrategy(
module, enabled_features, func_index, lazy_module);
bool validate_lazily_compiled_function =
strategy == CompileStrategy::kLazy ||
strategy == CompileStrategy::kLazyBaselineEagerTopTier;
if (validate_lazily_compiled_function) {
DecodeResult function_result = ValidateSingleFunction(
module, func_index, code, allocator, enabled_features);
if (function_result.failed()) {
WasmError error = function_result.error();
WasmError error_with_name = GetWasmErrorWithName(
job->wire_bytes_, func, module, std::move(error));
result = ModuleResult(std::move(error_with_name));
break;
}
}
}
}
}
}
if (result.failed()) {
// Decoding failure; reject the promise and clean up.
job->DoSync<DecodeFail>(std::move(result).error());
} else {
// Decode passed.
std::shared_ptr<WasmModule> module = std::move(result).value();
const bool include_liftoff = v8_flags.liftoff;
size_t code_size_estimate =
wasm::WasmCodeManager::EstimateNativeModuleCodeSize(
module.get(), include_liftoff, job->dynamic_tiering_);
job->DoSync<PrepareAndStartCompile>(std::move(module), true,
code_size_estimate);
}
}
private:
Counters* const counters_;
std::shared_ptr<metrics::Recorder> metrics_recorder_;
};
//==========================================================================
// Step 1b: (sync) Fail decoding the module.
//==========================================================================
class AsyncCompileJob::DecodeFail : public CompileStep {
public:
explicit DecodeFail(WasmError error) : error_(std::move(error)) {}
private:
WasmError error_;
void RunInForeground(AsyncCompileJob* job) override {
TRACE_COMPILE("(1b) Decoding failed.\n");
// {job_} is deleted in DecodeFailed, therefore the {return}.
return job->DecodeFailed(error_);
}
};
//==========================================================================
// Step 2 (sync): Create heap-allocated data and start compile.
//==========================================================================
class AsyncCompileJob::PrepareAndStartCompile : public CompileStep {
public:
PrepareAndStartCompile(std::shared_ptr<const WasmModule> module,
bool start_compilation, size_t code_size_estimate)
: module_(std::move(module)),
start_compilation_(start_compilation),
code_size_estimate_(code_size_estimate) {}
private:
void RunInForeground(AsyncCompileJob* job) override {
TRACE_COMPILE("(2) Prepare and start compile...\n");
const bool streaming = job->wire_bytes_.length() == 0;
if (streaming) {
// Streaming compilation already checked for cache hits.
job->CreateNativeModule(module_, code_size_estimate_);
} else if (job->GetOrCreateNativeModule(std::move(module_),
code_size_estimate_)) {
job->FinishCompile(true);
return;
}
// Make sure all compilation tasks stopped running. Decoding (async step)
// is done.
job->background_task_manager_.CancelAndWait();
CompilationStateImpl* compilation_state =
Impl(job->native_module_->compilation_state());
compilation_state->AddCallback(
std::make_unique<CompilationStateCallback>(job));
if (base::TimeTicks::IsHighResolution()) {
auto compile_mode = job->stream_ == nullptr
? CompilationTimeCallback::kAsync
: CompilationTimeCallback::kStreaming;
compilation_state->AddCallback(std::make_unique<CompilationTimeCallback>(
job->isolate_->async_counters(), job->isolate_->metrics_recorder(),
job->context_id_, job->native_module_, compile_mode));
}
if (start_compilation_) {
std::unique_ptr<CompilationUnitBuilder> builder =
InitializeCompilation(job->isolate(), job->native_module_.get());
compilation_state->InitializeCompilationUnits(std::move(builder));
// We are in single-threaded mode, so there are no worker tasks that will
// do the compilation. We call {WaitForCompilationEvent} here so that the
// main thread paticipates and finishes the compilation.
if (v8_flags.wasm_num_compilation_tasks == 0) {
compilation_state->WaitForCompilationEvent(
CompilationEvent::kFinishedBaselineCompilation);
}
}
}
const std::shared_ptr<const WasmModule> module_;
const bool start_compilation_;
const size_t code_size_estimate_;
};
//==========================================================================
// Step 3a (sync): Compilation failed.
//==========================================================================
class AsyncCompileJob::CompileFailed : public CompileStep {
private:
void RunInForeground(AsyncCompileJob* job) override {
TRACE_COMPILE("(3a) Compilation failed\n");
DCHECK(job->native_module_->compilation_state()->failed());
// {job_} is deleted in AsyncCompileFailed, therefore the {return}.
return job->AsyncCompileFailed();
}
};
//==========================================================================
// Step 3b (sync): Compilation finished.
//==========================================================================
class AsyncCompileJob::CompileFinished : public CompileStep {
public:
explicit CompileFinished(std::shared_ptr<NativeModule> cached_native_module)
: cached_native_module_(std::move(cached_native_module)) {}
private:
void RunInForeground(AsyncCompileJob* job) override {
TRACE_COMPILE("(3b) Compilation finished\n");
if (cached_native_module_) {
job->native_module_ = cached_native_module_;
} else {
DCHECK(!job->native_module_->compilation_state()->failed());
// Sample the generated code size when baseline compilation finished.
job->native_module_->SampleCodeSize(job->isolate_->counters(),
NativeModule::kAfterBaseline);
}
// Then finalize and publish the generated module.
job->FinishCompile(cached_native_module_ != nullptr);
}
std::shared_ptr<NativeModule> cached_native_module_;
};
void AsyncCompileJob::FinishModule() {
TRACE_COMPILE("(4) Finish module...\n");
AsyncCompileSucceeded(module_object_);
GetWasmEngine()->RemoveCompileJob(this);
}
AsyncStreamingProcessor::AsyncStreamingProcessor(
AsyncCompileJob* job, std::shared_ptr<Counters> async_counters,
AccountingAllocator* allocator)
: decoder_(job->enabled_features_),
job_(job),
compilation_unit_builder_(nullptr),
async_counters_(async_counters),
allocator_(allocator) {}
AsyncStreamingProcessor::~AsyncStreamingProcessor() {
if (job_->native_module_ && job_->native_module_->wire_bytes().empty()) {
// Clean up the temporary cache entry.
GetWasmEngine()->StreamingCompilationFailed(prefix_hash_);
}
}
void AsyncStreamingProcessor::FinishAsyncCompileJobWithError(
const WasmError& error, ErrorLocation error_location) {
DCHECK(error.has_error());
// Make sure all background tasks stopped executing before we change the state
// of the AsyncCompileJob to DecodeFail.
job_->background_task_manager_.CancelAndWait();
// Record event metrics.
auto duration = base::TimeTicks::Now() - job_->start_time_;
job_->metrics_event_.success = false;
job_->metrics_event_.streamed = true;
job_->metrics_event_.module_size_in_bytes = job_->wire_bytes_.length();
job_->metrics_event_.function_count = num_functions_;
job_->metrics_event_.wall_clock_duration_in_us = duration.InMicroseconds();
job_->isolate_->metrics_recorder()->DelayMainThreadEvent(job_->metrics_event_,
job_->context_id_);
// Check if there is already a CompiledModule, in which case we have to clean
// up the CompilationStateImpl as well.
if (job_->native_module_) {
CompilationStateImpl* impl =
Impl(job_->native_module_->compilation_state());
if (error_location == kErrorInFunction) {
impl->SetError();
}
impl->CancelCompilation(CompilationStateImpl::kCancelUnconditionally);
if (error_location == kErrorInSection) {
job_->DoSync<AsyncCompileJob::DecodeFail,
AsyncCompileJob::kUseExistingForegroundTask>(error);
}
// Clear the {compilation_unit_builder_} if it exists. This is needed
// because there is a check in the destructor of the
// {CompilationUnitBuilder} that it is empty.
if (compilation_unit_builder_) compilation_unit_builder_->Clear();
} else {
job_->DoSync<AsyncCompileJob::DecodeFail>(error);
}
}
// Process the module header.
bool AsyncStreamingProcessor::ProcessModuleHeader(
base::Vector<const uint8_t> bytes, uint32_t offset) {
TRACE_STREAMING("Process module header...\n");
decoder_.StartDecoding(job_->isolate()->counters(),
job_->isolate()->metrics_recorder(),
job_->context_id(), GetWasmEngine()->allocator());
decoder_.DecodeModuleHeader(bytes, offset);
if (!decoder_.ok()) {
FinishAsyncCompileJobWithError(decoder_.FinishDecoding().error());
return false;
}
prefix_hash_ = GetWireBytesHash(bytes);
return true;
}
// Process all sections except for the code section.
bool AsyncStreamingProcessor::ProcessSection(SectionCode section_code,
base::Vector<const uint8_t> bytes,
uint32_t offset) {
TRACE_STREAMING("Process section %d ...\n", section_code);
if (compilation_unit_builder_) {
// We reached a section after the code section, we do not need the
// compilation_unit_builder_ anymore.
CommitCompilationUnits();
compilation_unit_builder_.reset();
}
if (before_code_section_) {
// Combine section hashes until code section.
prefix_hash_ = base::hash_combine(prefix_hash_, GetWireBytesHash(bytes));
}
if (section_code == SectionCode::kUnknownSectionCode) {
size_t bytes_consumed = ModuleDecoder::IdentifyUnknownSection(
&decoder_, bytes, offset, §ion_code);
if (!decoder_.ok()) {
FinishAsyncCompileJobWithError(decoder_.FinishDecoding().error());
return false;
}
if (section_code == SectionCode::kUnknownSectionCode) {
// Skip unknown sections that we do not know how to handle.
return true;
}
// Remove the unknown section tag from the payload bytes.
offset += bytes_consumed;
bytes = bytes.SubVector(bytes_consumed, bytes.size());
}
decoder_.DecodeSection(section_code, bytes, offset);
if (!decoder_.ok()) {
FinishAsyncCompileJobWithError(decoder_.FinishDecoding().error());
return false;
}
return true;
}
// Start the code section.
bool AsyncStreamingProcessor::ProcessCodeSectionHeader(
int num_functions, uint32_t functions_mismatch_error_offset,
std::shared_ptr<WireBytesStorage> wire_bytes_storage,
int code_section_start, int code_section_length) {
DCHECK_LE(0, code_section_length);
before_code_section_ = false;
TRACE_STREAMING("Start the code section with %d functions...\n",
num_functions);
prefix_hash_ = base::hash_combine(prefix_hash_,
static_cast<uint32_t>(code_section_length));
if (!decoder_.CheckFunctionsCount(static_cast<uint32_t>(num_functions),
functions_mismatch_error_offset)) {
FinishAsyncCompileJobWithError(decoder_.FinishDecoding().error());
return false;
}
decoder_.StartCodeSection({static_cast<uint32_t>(code_section_start),
static_cast<uint32_t>(code_section_length)});
if (!GetWasmEngine()->GetStreamingCompilationOwnership(prefix_hash_)) {
// Known prefix, wait until the end of the stream and check the cache.
prefix_cache_hit_ = true;
return true;
}
// Execute the PrepareAndStartCompile step immediately and not in a separate
// task.
int num_imported_functions =
static_cast<int>(decoder_.module()->num_imported_functions);
DCHECK_EQ(kWasmOrigin, decoder_.module()->origin);
const bool include_liftoff = v8_flags.liftoff;
size_t code_size_estimate =
wasm::WasmCodeManager::EstimateNativeModuleCodeSize(
num_functions, num_imported_functions, code_section_length,
include_liftoff, job_->dynamic_tiering_);
job_->DoImmediately<AsyncCompileJob::PrepareAndStartCompile>(
decoder_.shared_module(), false, code_size_estimate);
auto* compilation_state = Impl(job_->native_module_->compilation_state());
compilation_state->SetWireBytesStorage(std::move(wire_bytes_storage));
DCHECK_EQ(job_->native_module_->module()->origin, kWasmOrigin);
// Set outstanding_finishers_ to 2, because both the AsyncCompileJob and the
// AsyncStreamingProcessor have to finish.
job_->outstanding_finishers_ = 2;
compilation_unit_builder_ =
InitializeCompilation(job_->isolate(), job_->native_module_.get());
return true;
}
// Process a function body.
void AsyncStreamingProcessor::ProcessFunctionBody(
base::Vector<const uint8_t> bytes, uint32_t offset) {
TRACE_STREAMING("Process function body %d ...\n", num_functions_);
uint32_t func_index =
decoder_.module()->num_imported_functions + num_functions_;
++num_functions_;
// In case of {prefix_cache_hit} we still need the function body to be
// decoded. Otherwise a later cache miss cannot be handled.
decoder_.DecodeFunctionBody(func_index, static_cast<uint32_t>(bytes.length()),
offset, false);
if (prefix_cache_hit_) {
// Don't compile yet if we might have a cache hit.
return;
}
// Bail out after the {prefix_cache_hit_}, because if {prefix_cache_hit_} is
// true, the native module does not exist.
if (job_->native_module_->compilation_state()->failed()) {
// There has already been an error, there is no need to do any more
// validation or compiling.
return;
}
const WasmModule* module = decoder_.module();
auto enabled_features = job_->enabled_features_;
DCHECK_EQ(module->origin, kWasmOrigin);
const bool lazy_module = job_->wasm_lazy_compilation_;
CompileStrategy strategy =
GetCompileStrategy(module, enabled_features, func_index, lazy_module);
bool validate_lazily_compiled_function =
!v8_flags.wasm_lazy_validation &&
(strategy == CompileStrategy::kLazy ||
strategy == CompileStrategy::kLazyBaselineEagerTopTier);
if (validate_lazily_compiled_function) {
// The native module does not own the wire bytes until {SetWireBytes} is
// called in {OnFinishedStream}. Validation must use {bytes} parameter.
DecodeResult result = ValidateSingleFunction(module, func_index, bytes,
allocator_, enabled_features);
if (result.failed()) {
FinishAsyncCompileJobWithError(result.error(), kErrorInFunction);
return;
}
}
auto* compilation_state = Impl(job_->native_module_->compilation_state());
compilation_state->AddCompilationUnit(compilation_unit_builder_.get(),
func_index);
}
void AsyncStreamingProcessor::CommitCompilationUnits() {
DCHECK(compilation_unit_builder_);
compilation_unit_builder_->Commit();
}
void AsyncStreamingProcessor::OnFinishedChunk() {
TRACE_STREAMING("FinishChunk...\n");
if (compilation_unit_builder_) CommitCompilationUnits();
}
// Finish the processing of the stream.
void AsyncStreamingProcessor::OnFinishedStream(
base::OwnedVector<uint8_t> bytes) {
TRACE_STREAMING("Finish stream...\n");
DCHECK_EQ(NativeModuleCache::PrefixHash(bytes.as_vector()), prefix_hash_);
ModuleResult result = decoder_.FinishDecoding();
if (result.failed()) {
FinishAsyncCompileJobWithError(result.error());
return;
}
job_->wire_bytes_ = ModuleWireBytes(bytes.as_vector());
job_->bytes_copy_ = bytes.ReleaseData();
// Record event metrics.
auto duration = base::TimeTicks::Now() - job_->start_time_;
job_->metrics_event_.success = true;
job_->metrics_event_.streamed = true;
job_->metrics_event_.module_size_in_bytes = job_->wire_bytes_.length();
job_->metrics_event_.function_count = num_functions_;
job_->metrics_event_.wall_clock_duration_in_us = duration.InMicroseconds();
job_->isolate_->metrics_recorder()->DelayMainThreadEvent(job_->metrics_event_,
job_->context_id_);
if (prefix_cache_hit_) {
// Restart as an asynchronous, non-streaming compilation. Most likely
// {PrepareAndStartCompile} will get the native module from the cache.
const bool include_liftoff = v8_flags.liftoff;
size_t code_size_estimate =
wasm::WasmCodeManager::EstimateNativeModuleCodeSize(
result.value().get(), include_liftoff, job_->dynamic_tiering_);
job_->DoSync<AsyncCompileJob::PrepareAndStartCompile>(
std::move(result).value(), true, code_size_estimate);
return;
}
// We have to open a HandleScope and prepare the Context for
// CreateNativeModule, PrepareRuntimeObjects and FinishCompile as this is a
// callback from the embedder.
HandleScope scope(job_->isolate_);
SaveAndSwitchContext saved_context(job_->isolate_, *job_->native_context_);
// Record the size of the wire bytes. In synchronous and asynchronous
// (non-streaming) compilation, this happens in {DecodeWasmModule}.
auto* histogram = job_->isolate_->counters()->wasm_wasm_module_size_bytes();
histogram->AddSample(job_->wire_bytes_.module_bytes().length());
const bool has_code_section = job_->native_module_ != nullptr;
bool cache_hit = false;
if (!has_code_section) {
// We are processing a WebAssembly module without code section. Create the
// native module now (would otherwise happen in {PrepareAndStartCompile} or
// {ProcessCodeSectionHeader}).
constexpr size_t kCodeSizeEstimate = 0;
cache_hit = job_->GetOrCreateNativeModule(std::move(result).value(),
kCodeSizeEstimate);
} else {
job_->native_module_->SetWireBytes(
{std::move(job_->bytes_copy_), job_->wire_bytes_.length()});
}
const bool needs_finish =
job_->DecrementAndCheckFinisherCount(AsyncCompileJob::kStreamingDecoder);
DCHECK_IMPLIES(!has_code_section, needs_finish);
if (needs_finish) {
const bool failed = job_->native_module_->compilation_state()->failed();
if (!cache_hit) {
cache_hit = !GetWasmEngine()->UpdateNativeModuleCache(
failed, &job_->native_module_, job_->isolate_);
}
if (failed) {
job_->AsyncCompileFailed();
} else {
job_->FinishCompile(cache_hit);
}
}
}
// Report an error detected in the StreamingDecoder.
void AsyncStreamingProcessor::OnError(const WasmError& error) {
TRACE_STREAMING("Stream error...\n");
FinishAsyncCompileJobWithError(error);
}
void AsyncStreamingProcessor::OnAbort() {
TRACE_STREAMING("Abort stream...\n");
job_->Abort();
}
bool AsyncStreamingProcessor::Deserialize(
base::Vector<const uint8_t> module_bytes,
base::Vector<const uint8_t> wire_bytes) {
TRACE_EVENT0("v8.wasm", "wasm.Deserialize");
base::Optional<TimedHistogramScope> time_scope;
if (base::TimeTicks::IsHighResolution()) {
time_scope.emplace(job_->isolate()->counters()->wasm_deserialization_time(),
job_->isolate());
}
// DeserializeNativeModule and FinishCompile assume that they are executed in
// a HandleScope, and that a context is set on the isolate.
HandleScope scope(job_->isolate_);
SaveAndSwitchContext saved_context(job_->isolate_, *job_->native_context_);
MaybeHandle<WasmModuleObject> result =
DeserializeNativeModule(job_->isolate_, module_bytes, wire_bytes,
base::VectorOf(job_->stream_->url()));
if (result.is_null()) return false;
job_->module_object_ =
job_->isolate_->global_handles()->Create(*result.ToHandleChecked());
job_->native_module_ = job_->module_object_->shared_native_module();
job_->wire_bytes_ = ModuleWireBytes(job_->native_module_->wire_bytes());
job_->FinishCompile(false);
return true;
}
CompilationStateImpl::CompilationStateImpl(
const std::shared_ptr<NativeModule>& native_module,
std::shared_ptr<Counters> async_counters, DynamicTiering dynamic_tiering)
: native_module_(native_module.get()),
native_module_weak_(std::move(native_module)),
async_counters_(std::move(async_counters)),
compilation_unit_queues_(native_module->num_functions()),
dynamic_tiering_(dynamic_tiering) {}
void CompilationStateImpl::InitCompileJob() {
DCHECK_NULL(compile_job_);
// Create the job, but don't spawn workers yet. This will happen on
// {NotifyConcurrencyIncrease}.
compile_job_ = V8::GetCurrentPlatform()->CreateJob(
TaskPriority::kUserVisible, std::make_unique<BackgroundCompileJob>(
native_module_weak_, async_counters_));
}
void CompilationStateImpl::CancelCompilation(
CompilationStateImpl::CancellationPolicy cancellation_policy) {
base::MutexGuard callbacks_guard(&callbacks_mutex_);
if (cancellation_policy == kCancelInitialCompilation &&
finished_events_.contains(
CompilationEvent::kFinishedBaselineCompilation)) {
// Initial compilation already finished; cannot be cancelled.
return;
}
// std::memory_order_relaxed is sufficient because no other state is
// synchronized with |compile_cancelled_|.
compile_cancelled_.store(true, std::memory_order_relaxed);
// No more callbacks after abort.
callbacks_.clear();
}
bool CompilationStateImpl::cancelled() const {
return compile_cancelled_.load(std::memory_order_relaxed);
}
void CompilationStateImpl::ApplyCompilationHintToInitialProgress(
const WasmCompilationHint& hint, size_t hint_idx) {
// Get old information.
uint8_t& progress = compilation_progress_[hint_idx];
ExecutionTier old_baseline_tier = RequiredBaselineTierField::decode(progress);
ExecutionTier old_top_tier = RequiredTopTierField::decode(progress);
// Compute new information.
ExecutionTier new_baseline_tier =
ApplyHintToExecutionTier(hint.baseline_tier, old_baseline_tier);
ExecutionTier new_top_tier =
ApplyHintToExecutionTier(hint.top_tier, old_top_tier);
switch (hint.strategy) {
case WasmCompilationHintStrategy::kDefault:
// Be careful not to switch from lazy to non-lazy.
if (old_baseline_tier == ExecutionTier::kNone) {
new_baseline_tier = ExecutionTier::kNone;
}
if (old_top_tier == ExecutionTier::kNone) {
new_top_tier = ExecutionTier::kNone;
}
break;
case WasmCompilationHintStrategy::kLazy:
new_baseline_tier = ExecutionTier::kNone;
new_top_tier = ExecutionTier::kNone;
break;
case WasmCompilationHintStrategy::kEager:
// Nothing to do, use the encoded (new) tiers.
break;
case WasmCompilationHintStrategy::kLazyBaselineEagerTopTier:
new_baseline_tier = ExecutionTier::kNone;
break;
}
progress = RequiredBaselineTierField::update(progress, new_baseline_tier);
progress = RequiredTopTierField::update(progress, new_top_tier);
// Update counter for outstanding baseline units.
outstanding_baseline_units_ += (new_baseline_tier != ExecutionTier::kNone) -
(old_baseline_tier != ExecutionTier::kNone);
}
void CompilationStateImpl::InitializeCompilationProgress(
int num_import_wrappers, int num_export_wrappers) {
DCHECK(!failed());
auto* module = native_module_->module();
base::MutexGuard guard(&callbacks_mutex_);
DCHECK_EQ(0, outstanding_baseline_units_);
DCHECK_EQ(0, outstanding_export_wrappers_);
// Compute the default compilation progress for all functions, and set it.
const ExecutionTierPair default_tiers = GetDefaultTiersPerModule(
native_module_, dynamic_tiering_, IsLazyModule(module));
const uint8_t default_progress =
RequiredBaselineTierField::encode(default_tiers.baseline_tier) |
RequiredTopTierField::encode(default_tiers.top_tier) |
ReachedTierField::encode(ExecutionTier::kNone);
compilation_progress_.assign(module->num_declared_functions,
default_progress);
if (default_tiers.baseline_tier != ExecutionTier::kNone) {
outstanding_baseline_units_ += module->num_declared_functions;
}
// Apply compilation hints, if enabled.
if (native_module_->enabled_features().has_compilation_hints()) {
size_t num_hints = std::min(module->compilation_hints.size(),
size_t{module->num_declared_functions});
for (size_t hint_idx = 0; hint_idx < num_hints; ++hint_idx) {
const auto& hint = module->compilation_hints[hint_idx];
ApplyCompilationHintToInitialProgress(hint, hint_idx);
}
}
// Account for outstanding wrapper compilation.
outstanding_baseline_units_ += num_import_wrappers;
outstanding_export_wrappers_ = num_export_wrappers;
// Trigger callbacks if module needs no baseline or top tier compilation. This
// can be the case for an empty or fully lazy module.
TriggerCallbacks();
}
uint8_t CompilationStateImpl::AddCompilationUnitInternal(
CompilationUnitBuilder* builder, int function_index,
uint8_t function_progress) {
ExecutionTier required_baseline_tier =
CompilationStateImpl::RequiredBaselineTierField::decode(
function_progress);
ExecutionTier required_top_tier =
CompilationStateImpl::RequiredTopTierField::decode(function_progress);
ExecutionTier reached_tier =
CompilationStateImpl::ReachedTierField::decode(function_progress);
if (v8_flags.experimental_wasm_gc && !v8_flags.wasm_lazy_compilation) {
// The Turbofan optimizations we enable for WasmGC code can (for now)
// take a very long time, so skip Turbofan compilation for super-large
// functions.
// Besides, module serialization currently requires that all functions
// have been TF-compiled. By enabling this limit only for WasmGC, we
// make sure that non-experimental modules can be serialize as usual.
// TODO(jkummerow): This is a stop-gap solution to avoid excessive
// compile times. We would like to replace this hard threshold with
// a better solution (TBD) eventually.
constexpr uint32_t kMaxWasmFunctionSizeForTurbofan = 500 * KB;
uint32_t size = builder->module()->functions[function_index].code.length();
if (size > kMaxWasmFunctionSizeForTurbofan) {
required_baseline_tier = ExecutionTier::kLiftoff;
if (required_top_tier == ExecutionTier::kTurbofan) {
required_top_tier = ExecutionTier::kLiftoff;
}
}
}
if (reached_tier < required_baseline_tier) {
builder->AddBaselineUnit(function_index, required_baseline_tier);
}
if (reached_tier < required_top_tier &&
required_baseline_tier != required_top_tier) {
builder->AddTopTierUnit(function_index, required_top_tier);
}
return CompilationStateImpl::RequiredBaselineTierField::encode(
required_baseline_tier) |
CompilationStateImpl::RequiredTopTierField::encode(required_top_tier) |
CompilationStateImpl::ReachedTierField::encode(reached_tier);
}
void CompilationStateImpl::InitializeCompilationUnits(
std::unique_ptr<CompilationUnitBuilder> builder) {
int offset = native_module_->module()->num_imported_functions;
if (native_module_->IsTieredDown()) {
for (size_t i = 0; i < compilation_progress_.size(); ++i) {
int func_index = offset + static_cast<int>(i);
builder->AddDebugUnit(func_index);
}
} else {
base::MutexGuard guard(&callbacks_mutex_);
for (size_t i = 0; i < compilation_progress_.size(); ++i) {
uint8_t function_progress = compilation_progress_[i];
int func_index = offset + static_cast<int>(i);
compilation_progress_[i] = AddCompilationUnitInternal(
builder.get(), func_index, function_progress);
}
}
builder->Commit();
}
void CompilationStateImpl::AddCompilationUnit(CompilationUnitBuilder* builder,
int func_index) {
if (native_module_->IsTieredDown()) {
builder->AddDebugUnit(func_index);
return;
}
int offset = native_module_->module()->num_imported_functions;
int progress_index = func_index - offset;
uint8_t function_progress;
{
// TODO(ahaas): This lock may cause overhead. If so, we could get rid of the
// lock as follows:
// 1) Make compilation_progress_ an array of atomic<uint8_t>, and access it
// lock-free.
// 2) Have a copy of compilation_progress_ that we use for initialization.
// 3) Just re-calculate the content of compilation_progress_.
base::MutexGuard guard(&callbacks_mutex_);
function_progress = compilation_progress_[progress_index];
}
uint8_t updated_function_progress =
AddCompilationUnitInternal(builder, func_index, function_progress);
if (updated_function_progress != function_progress) {
// This should happen very rarely (only for super-large functions), so we're
// not worried about overhead.
base::MutexGuard guard(&callbacks_mutex_);
compilation_progress_[progress_index] = updated_function_progress;
}
}
void CompilationStateImpl::InitializeCompilationProgressAfterDeserialization(
base::Vector<const int> lazy_functions,
base::Vector<const int> eager_functions) {
TRACE_EVENT2("v8.wasm", "wasm.CompilationAfterDeserialization",
"num_lazy_functions", lazy_functions.size(),
"num_eager_functions", eager_functions.size());
base::Optional<TimedHistogramScope> lazy_compile_time_scope;
if (base::TimeTicks::IsHighResolution()) {
lazy_compile_time_scope.emplace(
counters()->wasm_compile_after_deserialize());
}
auto* module = native_module_->module();
base::Optional<CodeSpaceWriteScope> lazy_code_space_write_scope;
if (IsLazyModule(module) || !lazy_functions.empty()) {
lazy_code_space_write_scope.emplace(native_module_);
}
{
base::MutexGuard guard(&callbacks_mutex_);
DCHECK(compilation_progress_.empty());
// Initialize the compilation progress as if everything was
// TurboFan-compiled.
constexpr uint8_t kProgressAfterTurbofanDeserialization =
RequiredBaselineTierField::encode(ExecutionTier::kTurbofan) |
RequiredTopTierField::encode(ExecutionTier::kTurbofan) |
ReachedTierField::encode(ExecutionTier::kTurbofan);
compilation_progress_.assign(module->num_declared_functions,
kProgressAfterTurbofanDeserialization);
// Update compilation state for lazy functions.
constexpr uint8_t kProgressForLazyFunctions =
RequiredBaselineTierField::encode(ExecutionTier::kNone) |
RequiredTopTierField::encode(ExecutionTier::kNone) |
ReachedTierField::encode(ExecutionTier::kNone);
for (auto func_index : lazy_functions) {
native_module_->UseLazyStub(func_index);
compilation_progress_[declared_function_index(module, func_index)] =
kProgressForLazyFunctions;
}
// Update compilation state for eagerly compiled functions.
constexpr bool kNotLazy = false;
ExecutionTierPair default_tiers =
GetDefaultTiersPerModule(native_module_, dynamic_tiering_, kNotLazy);
uint8_t progress_for_eager_functions =
RequiredBaselineTierField::encode(default_tiers.baseline_tier) |
RequiredTopTierField::encode(default_tiers.top_tier) |
ReachedTierField::encode(ExecutionTier::kNone);
for (auto func_index : eager_functions) {
// Check that {func_index} is not contained in {lazy_functions}.
DCHECK_EQ(
compilation_progress_[declared_function_index(module, func_index)],
kProgressAfterTurbofanDeserialization);
compilation_progress_[declared_function_index(module, func_index)] =
progress_for_eager_functions;
}
DCHECK_NE(ExecutionTier::kNone, default_tiers.baseline_tier);
outstanding_baseline_units_ += eager_functions.size();
// Export wrappers are compiled synchronously after deserialization, so set
// that as finished already. Baseline compilation is done if we do not have
// any Liftoff functions to compile.
finished_events_.Add(CompilationEvent::kFinishedExportWrappers);
if (eager_functions.empty()) {
finished_events_.Add(CompilationEvent::kFinishedBaselineCompilation);
}
}
auto builder = std::make_unique<CompilationUnitBuilder>(native_module_);
InitializeCompilationUnits(std::move(builder));
WaitForCompilationEvent(CompilationEvent::kFinishedBaselineCompilation);
}
void CompilationStateImpl::InitializeRecompilation(
TieringState new_tiering_state,
std::unique_ptr<CompilationEventCallback> recompilation_finished_callback) {
DCHECK(!failed());
// Hold the mutex as long as possible, to synchronize between multiple
// recompilations that are triggered at the same time (e.g. when the profiler
// is disabled).
base::Optional<base::MutexGuard> guard(&callbacks_mutex_);
// As long as there are outstanding recompilation functions, take part in
// compilation. This is to avoid recompiling for the same tier or for
// different tiers concurrently. Note that the compilation unit queues can run
// empty before {outstanding_recompilation_functions_} drops to zero. In this
// case, we do not wait for the last running compilation threads to finish
// their units, but just start our own recompilation already.
while (outstanding_recompilation_functions_ > 0 &&
compilation_unit_queues_.GetTotalSize() > 0) {
guard.reset();
constexpr JobDelegate* kNoDelegate = nullptr;
ExecuteCompilationUnits(native_module_weak_, async_counters_.get(),
kNoDelegate, kBaselineOrTopTier);
guard.emplace(&callbacks_mutex_);
}
// Information about compilation progress is shared between this class and the
// NativeModule. Before updating information here, consult the NativeModule to
// find all functions that need recompilation.
// Since the current tiering state is updated on the NativeModule before
// triggering recompilation, it's OK if the information is slightly outdated.
// If we compile functions twice, the NativeModule will ignore all redundant
// code (or code compiled for the wrong tier).
std::vector<int> recompile_function_indexes =
native_module_->FindFunctionsToRecompile(new_tiering_state);
callbacks_.emplace_back(std::move(recompilation_finished_callback));
tiering_state_ = new_tiering_state;
// If compilation progress is not initialized yet, then compilation didn't
// start yet, and new code will be kept tiered-down from the start. For
// streaming compilation, there is a special path to tier down later, when
// the module is complete. In any case, we don't need to recompile here.
base::Optional<CompilationUnitBuilder> builder;
if (compilation_progress_.size() > 0) {
builder.emplace(native_module_);
const WasmModule* module = native_module_->module();
DCHECK_EQ(module->num_declared_functions, compilation_progress_.size());
DCHECK_GE(module->num_declared_functions,
recompile_function_indexes.size());
outstanding_recompilation_functions_ =
static_cast<int>(recompile_function_indexes.size());
// Restart recompilation if another recompilation is already happening.
for (auto& progress : compilation_progress_) {
progress = MissingRecompilationField::update(progress, false);
}
auto new_tier = new_tiering_state == kTieredDown ? ExecutionTier::kLiftoff
: ExecutionTier::kTurbofan;
int imported = module->num_imported_functions;
// Generate necessary compilation units on the fly.
for (int function_index : recompile_function_indexes) {
DCHECK_LE(imported, function_index);
int slot_index = function_index - imported;
auto& progress = compilation_progress_[slot_index];
progress = MissingRecompilationField::update(progress, true);
builder->AddRecompilationUnit(function_index, new_tier);
}
}
// Trigger callback if module needs no recompilation.
if (outstanding_recompilation_functions_ == 0) {
TriggerCallbacks(base::EnumSet<CompilationEvent>(
{CompilationEvent::kFinishedRecompilation}));
}
if (builder.has_value()) {
// Avoid holding lock while scheduling a compile job.
guard.reset();
builder->Commit();
}
}
void CompilationStateImpl::AddCallback(
std::unique_ptr<CompilationEventCallback> callback) {
base::MutexGuard callbacks_guard(&callbacks_mutex_);
// Immediately trigger events that already happened.
for (auto event : {CompilationEvent::kFinishedExportWrappers,
CompilationEvent::kFinishedBaselineCompilation,
CompilationEvent::kFailedCompilation}) {
if (finished_events_.contains(event)) {
callback->call(event);
}
}
constexpr base::EnumSet<CompilationEvent> kFinalEvents{
CompilationEvent::kFailedCompilation};
if (!finished_events_.contains_any(kFinalEvents)) {
callbacks_.emplace_back(std::move(callback));
}
}
void CompilationStateImpl::CommitCompilationUnits(
base::Vector<WasmCompilationUnit> baseline_units,
base::Vector<WasmCompilationUnit> top_tier_units,
base::Vector<std::shared_ptr<JSToWasmWrapperCompilationUnit>>
js_to_wasm_wrapper_units) {
if (!js_to_wasm_wrapper_units.empty()) {
// |js_to_wasm_wrapper_units_| will only be initialized once.
DCHECK_EQ(0, outstanding_js_to_wasm_wrappers_.load());
js_to_wasm_wrapper_units_.insert(js_to_wasm_wrapper_units_.end(),
js_to_wasm_wrapper_units.begin(),
js_to_wasm_wrapper_units.end());
// Use release semantics such that updates to {js_to_wasm_wrapper_units_}
// are available to other threads doing an acquire load.
outstanding_js_to_wasm_wrappers_.store(js_to_wasm_wrapper_units.size(),
std::memory_order_release);
}
if (!baseline_units.empty() || !top_tier_units.empty()) {
compilation_unit_queues_.AddUnits(baseline_units, top_tier_units,
native_module_->module());
}
ResetPKUPermissionsForThreadSpawning pku_reset_scope;
compile_job_->NotifyConcurrencyIncrease();
}
void CompilationStateImpl::CommitTopTierCompilationUnit(
WasmCompilationUnit unit) {
CommitCompilationUnits({}, {&unit, 1}, {});
}
void CompilationStateImpl::AddTopTierPriorityCompilationUnit(
WasmCompilationUnit unit, size_t priority) {
compilation_unit_queues_.AddTopTierPriorityUnit(unit, priority);
// We should not have a {CodeSpaceWriteScope} open at this point, as
// {NotifyConcurrencyIncrease} can spawn new threads which could inherit PKU
// permissions (which would be a security issue).
DCHECK(!CodeSpaceWriteScope::IsInScope());
compile_job_->NotifyConcurrencyIncrease();
}
std::shared_ptr<JSToWasmWrapperCompilationUnit>
CompilationStateImpl::GetNextJSToWasmWrapperCompilationUnit() {
size_t outstanding_units =
outstanding_js_to_wasm_wrappers_.load(std::memory_order_relaxed);
// Use acquire semantics such that initialization of
// {js_to_wasm_wrapper_units_} is available.
while (outstanding_units &&
!outstanding_js_to_wasm_wrappers_.compare_exchange_weak(
outstanding_units, outstanding_units - 1,
std::memory_order_acquire)) {
// Retry with updated {outstanding_units}.
}
if (outstanding_units == 0) return nullptr;
return js_to_wasm_wrapper_units_[outstanding_units - 1];
}
void CompilationStateImpl::FinalizeJSToWasmWrappers(Isolate* isolate,
const WasmModule* module) {
// TODO(6792): Wrappers below are allocated with {Factory::NewCode}. As an
// optimization we create a code memory modification scope that avoids
// changing the page permissions back-and-forth between RWX and RX, because
// many such wrapper are allocated in sequence below.
TRACE_EVENT1(TRACE_DISABLED_BY_DEFAULT("v8.wasm.detailed"),
"wasm.FinalizeJSToWasmWrappers", "wrappers",
js_to_wasm_wrapper_units_.size());
isolate->heap()->EnsureWasmCanonicalRttsSize(module->MaxCanonicalTypeIndex() +
1);
CodePageCollectionMemoryModificationScope modification_scope(isolate->heap());
for (auto& unit : js_to_wasm_wrapper_units_) {
DCHECK_EQ(isolate, unit->isolate());
Handle<CodeT> code = unit->Finalize();
uint32_t index =
GetExportWrapperIndex(unit->canonical_sig_index(), unit->is_import());
isolate->heap()->js_to_wasm_wrappers().Set(index,
MaybeObject::FromObject(*code));
RecordStats(*code, isolate->counters());
}
}
CompilationUnitQueues::Queue* CompilationStateImpl::GetQueueForCompileTask(
int task_id) {
return compilation_unit_queues_.GetQueueForTask(task_id);
}
base::Optional<WasmCompilationUnit>
CompilationStateImpl::GetNextCompilationUnit(
CompilationUnitQueues::Queue* queue, CompileBaselineOnly baseline_only) {
return compilation_unit_queues_.GetNextUnit(queue, baseline_only);
}
void CompilationStateImpl::OnFinishedUnits(
base::Vector<WasmCode*> code_vector) {
TRACE_EVENT1(TRACE_DISABLED_BY_DEFAULT("v8.wasm.detailed"),
"wasm.OnFinishedUnits", "units", code_vector.size());
base::MutexGuard guard(&callbacks_mutex_);
// Assume an order of execution tiers that represents the quality of their
// generated code.
static_assert(ExecutionTier::kNone < ExecutionTier::kLiftoff &&
ExecutionTier::kLiftoff < ExecutionTier::kTurbofan,
"Assume an order on execution tiers");
DCHECK_EQ(compilation_progress_.size(),
native_module_->module()->num_declared_functions);
base::EnumSet<CompilationEvent> triggered_events;
for (size_t i = 0; i < code_vector.size(); i++) {
WasmCode* code = code_vector[i];
DCHECK_NOT_NULL(code);
DCHECK_LT(code->index(), native_module_->num_functions());
if (code->index() <
static_cast<int>(native_module_->num_imported_functions())) {
// Import wrapper.
DCHECK_EQ(code->tier(), ExecutionTier::kTurbofan);
outstanding_baseline_units_--;
} else {
// Function.
DCHECK_NE(code->tier(), ExecutionTier::kNone);
// Read function's compilation progress.
// This view on the compilation progress may differ from the actually
// compiled code. Any lazily compiled function does not contribute to the
// compilation progress but may publish code to the code manager.
int slot_index =
declared_function_index(native_module_->module(), code->index());
uint8_t function_progress = compilation_progress_[slot_index];
ExecutionTier required_baseline_tier =
RequiredBaselineTierField::decode(function_progress);
ExecutionTier reached_tier = ReachedTierField::decode(function_progress);
// Check whether required baseline or top tier are reached.
if (reached_tier < required_baseline_tier &&
required_baseline_tier <= code->tier()) {
DCHECK_GT(outstanding_baseline_units_, 0);
outstanding_baseline_units_--;
}
if (code->tier() == ExecutionTier::kTurbofan) {
bytes_since_last_chunk_ += code->instructions().size();
}
if (V8_UNLIKELY(MissingRecompilationField::decode(function_progress))) {
DCHECK_LT(0, outstanding_recompilation_functions_);
// If tiering up, accept any TurboFan code. For tiering down, look at
// the {for_debugging} flag. The tier can be Liftoff or TurboFan and is
// irrelevant here. In particular, we want to ignore any outstanding
// non-debugging units.
bool matches = tiering_state_ == kTieredDown
? code->for_debugging()
: code->tier() == ExecutionTier::kTurbofan;
if (matches) {
outstanding_recompilation_functions_--;
compilation_progress_[slot_index] = MissingRecompilationField::update(
compilation_progress_[slot_index], false);
if (outstanding_recompilation_functions_ == 0) {
triggered_events.Add(CompilationEvent::kFinishedRecompilation);
}
}
}
// Update function's compilation progress.
if (code->tier() > reached_tier) {
compilation_progress_[slot_index] = ReachedTierField::update(
compilation_progress_[slot_index], code->tier());
}
DCHECK_LE(0, outstanding_baseline_units_);
}
}
TriggerCallbacks(triggered_events);
}
void CompilationStateImpl::OnFinishedJSToWasmWrapperUnits(int num) {
if (num == 0) return;
base::MutexGuard guard(&callbacks_mutex_);
DCHECK_GE(outstanding_export_wrappers_, num);
outstanding_export_wrappers_ -= num;
TriggerCallbacks();
}
void CompilationStateImpl::TriggerCallbacks(
base::EnumSet<CompilationEvent> triggered_events) {
DCHECK(!callbacks_mutex_.TryLock());
if (outstanding_export_wrappers_ == 0) {
triggered_events.Add(CompilationEvent::kFinishedExportWrappers);
if (outstanding_baseline_units_ == 0) {
triggered_events.Add(CompilationEvent::kFinishedBaselineCompilation);
}
}
// For dynamic tiering, trigger "compilation chunk finished" after a new chunk
// of size {v8_flags.wasm_caching_threshold}.
if (dynamic_tiering_ && static_cast<size_t>(v8_flags.wasm_caching_threshold) <
bytes_since_last_chunk_) {
triggered_events.Add(CompilationEvent::kFinishedCompilationChunk);
bytes_since_last_chunk_ = 0;
}
if (compile_failed_.load(std::memory_order_relaxed)) {
// *Only* trigger the "failed" event.
triggered_events =
base::EnumSet<CompilationEvent>({CompilationEvent::kFailedCompilation});
}
if (triggered_events.empty()) return;
// Don't trigger past events again.
triggered_events -= finished_events_;
// Recompilation can happen multiple times, thus do not store this. There can
// also be multiple compilation chunks.
finished_events_ |= triggered_events -
CompilationEvent::kFinishedRecompilation -
CompilationEvent::kFinishedCompilationChunk;
for (auto event :
{std::make_pair(CompilationEvent::kFailedCompilation,
"wasm.CompilationFailed"),
std::make_pair(CompilationEvent::kFinishedExportWrappers,
"wasm.ExportWrappersFinished"),
std::make_pair(CompilationEvent::kFinishedBaselineCompilation,
"wasm.BaselineFinished"),
std::make_pair(CompilationEvent::kFinishedCompilationChunk,
"wasm.CompilationChunkFinished"),
std::make_pair(CompilationEvent::kFinishedRecompilation,
"wasm.RecompilationFinished")}) {
if (!triggered_events.contains(event.first)) continue;
DCHECK_NE(compilation_id_, kInvalidCompilationID);
TRACE_EVENT1("v8.wasm", event.second, "id", compilation_id_);
for (auto& callback : callbacks_) {
callback->call(event.first);
}
}
if (outstanding_baseline_units_ == 0 && outstanding_export_wrappers_ == 0 &&
outstanding_recompilation_functions_ == 0) {
auto new_end = std::remove_if(
callbacks_.begin(), callbacks_.end(), [](const auto& callback) {
return callback->release_after_final_event();
});
callbacks_.erase(new_end, callbacks_.end());
}
}
void CompilationStateImpl::OnCompilationStopped(WasmFeatures detected) {
base::MutexGuard guard(&mutex_);
detected_features_.Add(detected);
}
void CompilationStateImpl::PublishDetectedFeatures(Isolate* isolate) {
// Notifying the isolate of the feature counts must take place under
// the mutex, because even if we have finished baseline compilation,
// tiering compilations may still occur in the background.
base::MutexGuard guard(&mutex_);
UpdateFeatureUseCounts(isolate, detected_features_);
}
void CompilationStateImpl::PublishCompilationResults(
std::vector<std::unique_ptr<WasmCode>> unpublished_code) {
if (unpublished_code.empty()) return;
// For import wrapper compilation units, add result to the cache.
int num_imported_functions = native_module_->num_imported_functions();
WasmImportWrapperCache* cache = native_module_->import_wrapper_cache();
for (const auto& code : unpublished_code) {
int func_index = code->index();
DCHECK_LE(0, func_index);
DCHECK_LT(func_index, native_module_->num_functions());
if (func_index < num_imported_functions) {
const WasmFunction& function =
native_module_->module()->functions[func_index];
uint32_t canonical_type_index =
native_module_->module()
->isorecursive_canonical_type_ids[function.sig_index];
WasmImportWrapperCache::CacheKey key(
compiler::kDefaultImportCallKind, canonical_type_index,
static_cast<int>(function.sig->parameter_count()), kNoSuspend);
// If two imported functions have the same key, only one of them should
// have been added as a compilation unit. So it is always the first time
// we compile a wrapper for this key here.
DCHECK_NULL((*cache)[key]);
(*cache)[key] = code.get();
code->IncRef();
}
}
PublishCode(base::VectorOf(unpublished_code));
}
void CompilationStateImpl::PublishCode(
base::Vector<std::unique_ptr<WasmCode>> code) {
WasmCodeRefScope code_ref_scope;
std::vector<WasmCode*> published_code =
native_module_->PublishCode(std::move(code));
// Defer logging code in case wire bytes were not fully received yet.
if (native_module_->HasWireBytes()) {
GetWasmEngine()->LogCode(base::VectorOf(published_code));
}
OnFinishedUnits(base::VectorOf(std::move(published_code)));
}
void CompilationStateImpl::SchedulePublishCompilationResults(
std::vector<std::unique_ptr<WasmCode>> unpublished_code) {
{
base::MutexGuard guard(&publish_mutex_);
if (publisher_running_) {
// Add new code to the queue and return.
publish_queue_.reserve(publish_queue_.size() + unpublished_code.size());
for (auto& c : unpublished_code) {
publish_queue_.emplace_back(std::move(c));
}
return;
}
publisher_running_ = true;
}
CodeSpaceWriteScope code_space_write_scope(native_module_);
while (true) {
PublishCompilationResults(std::move(unpublished_code));
unpublished_code.clear();
// Keep publishing new code that came in.
base::MutexGuard guard(&publish_mutex_);
DCHECK(publisher_running_);
if (publish_queue_.empty()) {
publisher_running_ = false;
return;
}
unpublished_code.swap(publish_queue_);
}
}
size_t CompilationStateImpl::NumOutstandingCompilations() const {
size_t outstanding_wrappers =
outstanding_js_to_wasm_wrappers_.load(std::memory_order_relaxed);
size_t outstanding_functions = compilation_unit_queues_.GetTotalSize();
return outstanding_wrappers + outstanding_functions;
}
void CompilationStateImpl::SetError() {
compile_cancelled_.store(true, std::memory_order_relaxed);
if (compile_failed_.exchange(true, std::memory_order_relaxed)) {
return; // Already failed before.
}
base::MutexGuard callbacks_guard(&callbacks_mutex_);
TriggerCallbacks();
callbacks_.clear();
}
void CompilationStateImpl::WaitForCompilationEvent(
CompilationEvent expect_event) {
class WaitForCompilationEventCallback : public CompilationEventCallback {
public:
WaitForCompilationEventCallback(std::shared_ptr<base::Semaphore> semaphore,
std::shared_ptr<std::atomic<bool>> done,
base::EnumSet<CompilationEvent> events)
: semaphore_(std::move(semaphore)),
done_(std::move(done)),
events_(events) {}
void call(CompilationEvent event) override {
if (!events_.contains(event)) return;
done_->store(true, std::memory_order_relaxed);
semaphore_->Signal();
}
private:
std::shared_ptr<base::Semaphore> semaphore_;
std::shared_ptr<std::atomic<bool>> done_;
base::EnumSet<CompilationEvent> events_;
};
auto semaphore = std::make_shared<base::Semaphore>(0);
auto done = std::make_shared<std::atomic<bool>>(false);
base::EnumSet<CompilationEvent> events{expect_event,
CompilationEvent::kFailedCompilation};
{
base::MutexGuard callbacks_guard(&callbacks_mutex_);
if (finished_events_.contains_any(events)) return;
callbacks_.emplace_back(std::make_unique<WaitForCompilationEventCallback>(
semaphore, done, events));
}
class WaitForEventDelegate final : public JobDelegate {
public:
explicit WaitForEventDelegate(std::shared_ptr<std::atomic<bool>> done)
: done_(std::move(done)) {}
bool ShouldYield() override {
return done_->load(std::memory_order_relaxed);
}
bool IsJoiningThread() const override { return true; }
void NotifyConcurrencyIncrease() override { UNIMPLEMENTED(); }
uint8_t GetTaskId() override { return kMainTaskId; }
private:
std::shared_ptr<std::atomic<bool>> done_;
};
WaitForEventDelegate delegate{done};
ExecuteCompilationUnits(native_module_weak_, async_counters_.get(), &delegate,
kBaselineOnly);
semaphore->Wait();
}
namespace {
using JSToWasmWrapperQueue = WrapperQueue<JSToWasmWrapperKey, std::nullptr_t,
base::hash<JSToWasmWrapperKey>>;
using JSToWasmWrapperUnitMap =
std::unordered_map<JSToWasmWrapperKey,
std::unique_ptr<JSToWasmWrapperCompilationUnit>,
base::hash<JSToWasmWrapperKey>>;
class CompileJSToWasmWrapperJob final : public JobTask {
public:
CompileJSToWasmWrapperJob(JSToWasmWrapperQueue* queue,
JSToWasmWrapperUnitMap* compilation_units)
: queue_(queue),
compilation_units_(compilation_units),
outstanding_units_(queue->size()) {}
void Run(JobDelegate* delegate) override {
while (base::Optional<std::pair<JSToWasmWrapperKey, std::nullptr_t>> key =
queue_->pop()) {
JSToWasmWrapperCompilationUnit* unit =
(*compilation_units_)[key->first].get();
unit->Execute();
outstanding_units_.fetch_sub(1, std::memory_order_relaxed);
if (delegate && delegate->ShouldYield()) return;
}
}
size_t GetMaxConcurrency(size_t /* worker_count */) const override {
DCHECK_GE(v8_flags.wasm_num_compilation_tasks, 1);
// {outstanding_units_} includes the units that other workers are currently
// working on, so we can safely ignore the {worker_count} and just return
// the current number of outstanding units.
return std::min(static_cast<size_t>(v8_flags.wasm_num_compilation_tasks),
outstanding_units_.load(std::memory_order_relaxed));
}
private:
JSToWasmWrapperQueue* const queue_;
JSToWasmWrapperUnitMap* const compilation_units_;
std::atomic<size_t> outstanding_units_;
};
} // namespace
void CompileJsToWasmWrappers(Isolate* isolate, const WasmModule* module) {
TRACE_EVENT0("v8.wasm", "wasm.CompileJsToWasmWrappers");
isolate->heap()->EnsureWasmCanonicalRttsSize(module->MaxCanonicalTypeIndex() +
1);
JSToWasmWrapperQueue queue;
JSToWasmWrapperUnitMap compilation_units;
WasmFeatures enabled_features = WasmFeatures::FromIsolate(isolate);
// Prepare compilation units in the main thread.
for (auto exp : module->export_table) {
if (exp.kind != kExternalFunction) continue;
auto& function = module->functions[exp.index];
uint32_t canonical_type_index =
module->isorecursive_canonical_type_ids[function.sig_index];
int wrapper_index =
GetExportWrapperIndex(canonical_type_index, function.imported);
auto existing_wrapper =
isolate->heap()->js_to_wasm_wrappers().Get(wrapper_index);
if (existing_wrapper.IsStrongOrWeak() &&
!existing_wrapper.GetHeapObject().IsUndefined()) {
continue;
}
JSToWasmWrapperKey key(function.imported, canonical_type_index);
if (queue.insert(key, nullptr)) {
auto unit = std::make_unique<JSToWasmWrapperCompilationUnit>(
isolate, function.sig, canonical_type_index, module,
function.imported, enabled_features,
JSToWasmWrapperCompilationUnit::kAllowGeneric);
compilation_units.emplace(key, std::move(unit));
}
}
{
// This is nested inside the event above, so the name can be less
// descriptive. It's mainly to log the number of wrappers.
TRACE_EVENT1("v8.wasm", "wasm.JsToWasmWrapperCompilation", "num_wrappers",
compilation_units.size());
auto job =
std::make_unique<CompileJSToWasmWrapperJob>(&queue, &compilation_units);
if (v8_flags.wasm_num_compilation_tasks > 0) {
auto job_handle = V8::GetCurrentPlatform()->CreateJob(
TaskPriority::kUserVisible, std::move(job));
// Wait for completion, while contributing to the work.
job_handle->Join();
} else {
job->Run(nullptr);
}
}
// Finalize compilation jobs in the main thread.
// TODO(6792): Wrappers below are allocated with {Factory::NewCode}. As an
// optimization we create a code memory modification scope that avoids
// changing the page permissions back-and-forth between RWX and RX, because
// many such wrapper are allocated in sequence below.
CodePageCollectionMemoryModificationScope modification_scope(isolate->heap());
for (auto& pair : compilation_units) {
JSToWasmWrapperKey key = pair.first;
JSToWasmWrapperCompilationUnit* unit = pair.second.get();
DCHECK_EQ(isolate, unit->isolate());
Handle<CodeT> code = unit->Finalize();
int wrapper_index = GetExportWrapperIndex(key.second, key.first);
isolate->heap()->js_to_wasm_wrappers().Set(
wrapper_index, HeapObjectReference::Strong(*code));
RecordStats(*code, isolate->counters());
}
}
WasmCode* CompileImportWrapper(
NativeModule* native_module, Counters* counters,
compiler::WasmImportCallKind kind, const FunctionSig* sig,
uint32_t canonical_type_index, int expected_arity, Suspend suspend,
WasmImportWrapperCache::ModificationScope* cache_scope) {
// Entry should exist, so that we don't insert a new one and invalidate
// other threads' iterators/references, but it should not have been compiled
// yet.
WasmImportWrapperCache::CacheKey key(kind, canonical_type_index,
expected_arity, suspend);
DCHECK_NULL((*cache_scope)[key]);
bool source_positions = is_asmjs_module(native_module->module());
// Keep the {WasmCode} alive until we explicitly call {IncRef}.
WasmCodeRefScope code_ref_scope;
CompilationEnv env = native_module->CreateCompilationEnv();
WasmCompilationResult result = compiler::CompileWasmImportCallWrapper(
&env, kind, sig, source_positions, expected_arity, suspend);
WasmCode* published_code;
{
CodeSpaceWriteScope code_space_write_scope(native_module);
std::unique_ptr<WasmCode> wasm_code = native_module->AddCode(
result.func_index, result.code_desc, result.frame_slot_count,
result.tagged_parameter_slots,
result.protected_instructions_data.as_vector(),
result.source_positions.as_vector(), GetCodeKind(result),
ExecutionTier::kNone, kNoDebugging);
published_code = native_module->PublishCode(std::move(wasm_code));
}
(*cache_scope)[key] = published_code;
published_code->IncRef();
counters->wasm_generated_code_size()->Increment(
published_code->instructions().length());
counters->wasm_reloc_size()->Increment(published_code->reloc_info().length());
return published_code;
}
} // namespace wasm
} // namespace internal
} // namespace v8
#undef TRACE_COMPILE
#undef TRACE_STREAMING
#undef TRACE_LAZY
|