summaryrefslogtreecommitdiffstats
path: root/layout/generic/nsGridContainerFrame.cpp
blob: 5eb9cde7da23a87bf85e2351b2c1e5803ecb96a8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

/* rendering object for CSS "display: grid | inline-grid" */

#include "nsGridContainerFrame.h"

#include <functional>
#include <stdlib.h>  // for div()
#include <type_traits>
#include "gfxContext.h"
#include "mozilla/AutoRestore.h"
#include "mozilla/Baseline.h"
#include "mozilla/ComputedStyle.h"
#include "mozilla/CSSAlignUtils.h"
#include "mozilla/dom/Grid.h"
#include "mozilla/dom/GridBinding.h"
#include "mozilla/IntegerRange.h"
#include "mozilla/Maybe.h"
#include "mozilla/PodOperations.h"  // for PodZero
#include "mozilla/PresShell.h"
#include "mozilla/StaticPrefs_layout.h"
#include "nsAbsoluteContainingBlock.h"
#include "nsAlgorithm.h"  // for clamped()
#include "nsCSSFrameConstructor.h"
#include "nsDisplayList.h"
#include "nsFieldSetFrame.h"
#include "nsGfxScrollFrame.h"
#include "nsHashKeys.h"
#include "nsIFrameInlines.h"  // for nsIFrame::GetLogicalNormalPosition (don't remove)
#include "nsLayoutUtils.h"
#include "nsPlaceholderFrame.h"
#include "nsPresContext.h"
#include "nsReadableUtils.h"
#include "nsTableWrapperFrame.h"

using namespace mozilla;

typedef nsAbsoluteContainingBlock::AbsPosReflowFlags AbsPosReflowFlags;
typedef nsGridContainerFrame::TrackSize TrackSize;
typedef mozilla::CSSAlignUtils::AlignJustifyFlags AlignJustifyFlags;

using GridTemplate = StyleGridTemplateComponent;
using TrackListValue =
    StyleGenericTrackListValue<LengthPercentage, StyleInteger>;
using TrackRepeat = StyleGenericTrackRepeat<LengthPercentage, StyleInteger>;
using NameList = StyleOwnedSlice<StyleCustomIdent>;
using SizingConstraint = nsGridContainerFrame::SizingConstraint;
using GridItemCachedBAxisMeasurement =
    nsGridContainerFrame::CachedBAxisMeasurement;

static mozilla::LazyLogModule gGridContainerLog("GridContainer");
#define GRID_LOG(...) \
  MOZ_LOG(gGridContainerLog, LogLevel::Debug, (__VA_ARGS__));

static const int32_t kMaxLine = StyleMAX_GRID_LINE;
static const int32_t kMinLine = StyleMIN_GRID_LINE;
// The maximum line number, in the zero-based translated grid.
static const uint32_t kTranslatedMaxLine = uint32_t(kMaxLine - kMinLine);
static const uint32_t kAutoLine = kTranslatedMaxLine + 3457U;

static const nsFrameState kIsSubgridBits =
    (NS_STATE_GRID_IS_COL_SUBGRID | NS_STATE_GRID_IS_ROW_SUBGRID);

namespace mozilla {

template <>
inline Span<const StyleOwnedSlice<StyleCustomIdent>>
GridTemplate::LineNameLists(bool aIsSubgrid) const {
  if (IsTrackList()) {
    return AsTrackList()->line_names.AsSpan();
  }
  if (IsSubgrid() && aIsSubgrid) {
    // For subgrid, we need to resolve <line-name-list> from each
    // StyleGenericLineNameListValue, so return empty.
    return {};
  }
  MOZ_ASSERT(IsNone() || IsMasonry() || (IsSubgrid() && !aIsSubgrid));
  return {};
}

template <>
inline const StyleTrackBreadth& StyleTrackSize::GetMax() const {
  if (IsBreadth()) {
    return AsBreadth();
  }
  if (IsMinmax()) {
    return AsMinmax()._1;
  }
  MOZ_ASSERT(IsFitContent());
  return AsFitContent();
}

template <>
inline const StyleTrackBreadth& StyleTrackSize::GetMin() const {
  static const StyleTrackBreadth kAuto = StyleTrackBreadth::Auto();
  if (IsBreadth()) {
    // <flex> behaves like minmax(auto, <flex>)
    return AsBreadth().IsFr() ? kAuto : AsBreadth();
  }
  if (IsMinmax()) {
    return AsMinmax()._0;
  }
  MOZ_ASSERT(IsFitContent());
  return kAuto;
}

}  // namespace mozilla

static nscoord ClampToCSSMaxBSize(nscoord aSize,
                                  const ReflowInput* aReflowInput) {
  auto maxSize = aReflowInput->ComputedMaxBSize();
  if (MOZ_UNLIKELY(maxSize != NS_UNCONSTRAINEDSIZE)) {
    MOZ_ASSERT(aReflowInput->ComputedMinBSize() <= maxSize);
    aSize = std::min(aSize, maxSize);
  }
  return aSize;
}

// Same as above and set aStatus INCOMPLETE if aSize wasn't clamped.
// (If we clamp aSize it means our size is less than the break point,
// i.e. we're effectively breaking in our overflow, so we should leave
// aStatus as is (it will likely be set to OVERFLOW_INCOMPLETE later)).
static nscoord ClampToCSSMaxBSize(nscoord aSize,
                                  const ReflowInput* aReflowInput,
                                  nsReflowStatus* aStatus) {
  auto maxSize = aReflowInput->ComputedMaxBSize();
  if (MOZ_UNLIKELY(maxSize != NS_UNCONSTRAINEDSIZE)) {
    MOZ_ASSERT(aReflowInput->ComputedMinBSize() <= maxSize);
    if (aSize < maxSize) {
      aStatus->SetIncomplete();
    } else {
      aSize = maxSize;
    }
  } else {
    aStatus->SetIncomplete();
  }
  return aSize;
}

template <typename Size>
static bool IsPercentOfIndefiniteSize(const Size& aCoord,
                                      nscoord aPercentBasis) {
  return aPercentBasis == NS_UNCONSTRAINEDSIZE && aCoord.HasPercent();
}

static nscoord ResolveToDefiniteSize(const StyleTrackBreadth& aBreadth,
                                     nscoord aPercentBasis) {
  MOZ_ASSERT(aBreadth.IsBreadth());
  if (::IsPercentOfIndefiniteSize(aBreadth.AsBreadth(), aPercentBasis)) {
    return nscoord(0);
  }
  return std::max(nscoord(0), aBreadth.AsBreadth().Resolve(aPercentBasis));
}

// Synthesize a baseline from a border box.  For an alphabetical baseline
// this is the end edge of the border box.  For a central baseline it's
// the center of the border box.
// https://drafts.csswg.org/css-align-3/#synthesize-baseline
// For a 'first baseline' the measure is from the border-box start edge and
// for a 'last baseline' the measure is from the border-box end edge.
//
// The 'LogicalAxis aAxis' represents the axis (in terms of aWM) that the
// baseline corresponds to.  (Typically, baselines are a measurement in the
// block axis; e.g. for English horizontal-tb text, a traditional baseline
// would be a y-axis measurement.  But in some cases (e.g. orthogonal WMs), we
// may need to synthesize a baseline in a child's inline axis, which is when
// this function might receive an aAxis of eLogicalAxisInline. In that case, we
// assume that the writing mode's preference for central vs. alphabetic
// baselines is irrelevant, since that's a choice about its block-axis
// baselines, and we just unconditionally use the alphabetic baseline
// (e.g. border-box bottom edge).
static nscoord SynthesizeBaselineFromBorderBox(BaselineSharingGroup aGroup,
                                               WritingMode aWM,
                                               LogicalAxis aAxis,
                                               nscoord aBorderBoxSize) {
  const bool useAlphabeticBaseline =
      (aAxis == eLogicalAxisInline) ? true : aWM.IsAlphabeticalBaseline();

  if (aGroup == BaselineSharingGroup::First) {
    return useAlphabeticBaseline ? aBorderBoxSize : aBorderBoxSize / 2;
  }
  MOZ_ASSERT(aGroup == BaselineSharingGroup::Last);
  // Round up for central baseline offset, to be consistent with eFirst.
  return useAlphabeticBaseline ? 0
                               : (aBorderBoxSize / 2) + (aBorderBoxSize % 2);
}

// The input sizes for calculating the number of repeat(auto-fill/fit) tracks.
// https://drafts.csswg.org/css-grid/#auto-repeat
struct RepeatTrackSizingInput {
  explicit RepeatTrackSizingInput(WritingMode aWM)
      : mMin(aWM, 0, 0),
        mSize(aWM, NS_UNCONSTRAINEDSIZE, NS_UNCONSTRAINEDSIZE),
        mMax(aWM, NS_UNCONSTRAINEDSIZE, NS_UNCONSTRAINEDSIZE) {}
  RepeatTrackSizingInput(const LogicalSize& aMin, const LogicalSize& aSize,
                         const LogicalSize& aMax)
      : mMin(aMin), mSize(aSize), mMax(aMax) {}

  // This should be used in intrinsic sizing (i.e. when we can't initialize
  // the sizes directly from ReflowInput values).
  void InitFromStyle(LogicalAxis aAxis, WritingMode aWM,
                     const ComputedStyle* aStyle) {
    const auto& pos = aStyle->StylePosition();
    const bool borderBoxSizing = pos->mBoxSizing == StyleBoxSizing::Border;
    nscoord bp = NS_UNCONSTRAINEDSIZE;  // a sentinel to calculate it only once
    auto adjustForBoxSizing = [borderBoxSizing, aWM, aAxis, aStyle,
                               &bp](nscoord aSize) {
      if (!borderBoxSizing) {
        return aSize;
      }
      if (bp == NS_UNCONSTRAINEDSIZE) {
        const auto& padding = aStyle->StylePadding()->mPadding;
        LogicalMargin border(aWM, aStyle->StyleBorder()->GetComputedBorder());
        // We can use zero percentage basis since this is only called from
        // intrinsic sizing code.
        const nscoord percentageBasis = 0;
        if (aAxis == eLogicalAxisInline) {
          bp = std::max(padding.GetIStart(aWM).Resolve(percentageBasis), 0) +
               std::max(padding.GetIEnd(aWM).Resolve(percentageBasis), 0) +
               border.IStartEnd(aWM);
        } else {
          bp = std::max(padding.GetBStart(aWM).Resolve(percentageBasis), 0) +
               std::max(padding.GetBEnd(aWM).Resolve(percentageBasis), 0) +
               border.BStartEnd(aWM);
        }
      }
      return std::max(aSize - bp, 0);
    };
    nscoord& min = mMin.Size(aAxis, aWM);
    nscoord& size = mSize.Size(aAxis, aWM);
    nscoord& max = mMax.Size(aAxis, aWM);
    const auto& minCoord =
        aAxis == eLogicalAxisInline ? pos->MinISize(aWM) : pos->MinBSize(aWM);
    if (minCoord.ConvertsToLength()) {
      min = adjustForBoxSizing(minCoord.ToLength());
    }
    const auto& maxCoord =
        aAxis == eLogicalAxisInline ? pos->MaxISize(aWM) : pos->MaxBSize(aWM);
    if (maxCoord.ConvertsToLength()) {
      max = std::max(min, adjustForBoxSizing(maxCoord.ToLength()));
    }
    const auto& sizeCoord =
        aAxis == eLogicalAxisInline ? pos->ISize(aWM) : pos->BSize(aWM);
    if (sizeCoord.ConvertsToLength()) {
      size = Clamp(adjustForBoxSizing(sizeCoord.ToLength()), min, max);
    }
  }

  LogicalSize mMin;
  LogicalSize mSize;
  LogicalSize mMax;
};

enum class GridLineSide {
  BeforeGridGap,
  AfterGridGap,
};

struct nsGridContainerFrame::TrackSize {
  enum StateBits : uint16_t {
    // clang-format off
    eAutoMinSizing =              0x1,
    eMinContentMinSizing =        0x2,
    eMaxContentMinSizing =        0x4,
    eMinOrMaxContentMinSizing = eMinContentMinSizing | eMaxContentMinSizing,
    eIntrinsicMinSizing = eMinOrMaxContentMinSizing | eAutoMinSizing,
    eModified =                   0x8,
    eAutoMaxSizing =             0x10,
    eMinContentMaxSizing =       0x20,
    eMaxContentMaxSizing =       0x40,
    eAutoOrMaxContentMaxSizing = eAutoMaxSizing | eMaxContentMaxSizing,
    eIntrinsicMaxSizing = eAutoOrMaxContentMaxSizing | eMinContentMaxSizing,
    eFlexMaxSizing =             0x80,
    eFrozen =                   0x100,
    eSkipGrowUnlimited1 =       0x200,
    eSkipGrowUnlimited2 =       0x400,
    eSkipGrowUnlimited = eSkipGrowUnlimited1 | eSkipGrowUnlimited2,
    eBreakBefore =              0x800,
    eFitContent =              0x1000,
    eInfinitelyGrowable =      0x2000,

    // These are only used in the masonry axis.  They share the same value
    // as *MinSizing above, but that's OK because we don't use those in
    // the masonry axis.
    //
    // This track corresponds to an item margin-box size that is stretching.
    eItemStretchSize =            0x1,
    // This bit says that we should clamp that size to mLimit.
    eClampToLimit =               0x2,
    // This bit says that the corresponding item has `auto` margin(s).
    eItemHasAutoMargin =          0x4,
    // clang-format on
  };

  StateBits Initialize(nscoord aPercentageBasis, const StyleTrackSize&);
  bool IsFrozen() const { return mState & eFrozen; }
#ifdef DEBUG
  static void DumpStateBits(StateBits aState);
  void Dump() const;
#endif

  static bool IsDefiniteMaxSizing(StateBits aStateBits) {
    return (aStateBits & (eIntrinsicMaxSizing | eFlexMaxSizing)) == 0;
  }

  nscoord mBase;
  nscoord mLimit;
  nscoord mPosition;  // zero until we apply 'align/justify-content'
  // mBaselineSubtreeSize is the size of a baseline-aligned subtree within
  // this track.  One subtree per baseline-sharing group (per track).
  PerBaseline<nscoord> mBaselineSubtreeSize;
  StateBits mState;
};

MOZ_MAKE_ENUM_CLASS_BITWISE_OPERATORS(TrackSize::StateBits)

static_assert(
    std::is_trivially_copyable<nsGridContainerFrame::TrackSize>::value,
    "Must be trivially copyable");
static_assert(
    std::is_trivially_destructible<nsGridContainerFrame::TrackSize>::value,
    "Must be trivially destructible");

TrackSize::StateBits nsGridContainerFrame::TrackSize::Initialize(
    nscoord aPercentageBasis, const StyleTrackSize& aSize) {
  using Tag = StyleTrackBreadth::Tag;

  MOZ_ASSERT(mBase == 0 && mLimit == 0 && mState == 0,
             "track size data is expected to be initialized to zero");
  mBaselineSubtreeSize[BaselineSharingGroup::First] = nscoord(0);
  mBaselineSubtreeSize[BaselineSharingGroup::Last] = nscoord(0);

  auto& min = aSize.GetMin();
  auto& max = aSize.GetMax();

  Tag minSizeTag = min.tag;
  Tag maxSizeTag = max.tag;
  if (aSize.IsFitContent()) {
    // In layout, fit-content(size) behaves as minmax(auto, max-content), with
    // 'size' as an additional upper-bound.
    mState = eFitContent;
    minSizeTag = Tag::Auto;
    maxSizeTag = Tag::MaxContent;
  }
  if (::IsPercentOfIndefiniteSize(min, aPercentageBasis)) {
    // https://drafts.csswg.org/css-grid/#valdef-grid-template-columns-percentage
    // "If the inline or block size of the grid container is indefinite,
    //  <percentage> values relative to that size are treated as 'auto'."
    minSizeTag = Tag::Auto;
  }
  if (::IsPercentOfIndefiniteSize(max, aPercentageBasis)) {
    maxSizeTag = Tag::Auto;
  }

  // http://dev.w3.org/csswg/css-grid/#algo-init
  switch (minSizeTag) {
    case Tag::Auto:
      mState |= eAutoMinSizing;
      break;
    case Tag::MinContent:
      mState |= eMinContentMinSizing;
      break;
    case Tag::MaxContent:
      mState |= eMaxContentMinSizing;
      break;
    default:
      MOZ_ASSERT(!min.IsFr(), "<flex> min-sizing is invalid as a track size");
      mBase = ::ResolveToDefiniteSize(min, aPercentageBasis);
  }
  switch (maxSizeTag) {
    case Tag::Auto:
      mState |= eAutoMaxSizing;
      mLimit = NS_UNCONSTRAINEDSIZE;
      break;
    case Tag::MinContent:
    case Tag::MaxContent:
      mState |= maxSizeTag == Tag::MinContent ? eMinContentMaxSizing
                                              : eMaxContentMaxSizing;
      mLimit = NS_UNCONSTRAINEDSIZE;
      break;
    case Tag::Fr:
      mState |= eFlexMaxSizing;
      mLimit = mBase;
      break;
    default:
      mLimit = ::ResolveToDefiniteSize(max, aPercentageBasis);
      if (mLimit < mBase) {
        mLimit = mBase;
      }
  }
  return mState;
}

/**
 * A LineRange can be definite or auto - when it's definite it represents
 * a consecutive set of tracks between a starting line and an ending line.
 * Before it's definite it can also represent an auto position with a span,
 * where mStart == kAutoLine and mEnd is the (non-zero positive) span.
 * For normal-flow items, the invariant mStart < mEnd holds when both
 * lines are definite.
 *
 * For abs.pos. grid items, mStart and mEnd may both be kAutoLine, meaning
 * "attach this side to the grid container containing block edge".
 * Additionally, mStart <= mEnd holds when both are definite (non-kAutoLine),
 * i.e. the invariant is slightly relaxed compared to normal flow items.
 */
struct nsGridContainerFrame::LineRange {
  LineRange(int32_t aStart, int32_t aEnd)
      : mUntranslatedStart(aStart), mUntranslatedEnd(aEnd) {
#ifdef DEBUG
    if (!IsAutoAuto()) {
      if (IsAuto()) {
        MOZ_ASSERT(aEnd >= kMinLine && aEnd <= kMaxLine, "invalid span");
      } else {
        MOZ_ASSERT(aStart >= kMinLine && aStart <= kMaxLine,
                   "invalid start line");
        MOZ_ASSERT(aEnd == int32_t(kAutoLine) ||
                       (aEnd >= kMinLine && aEnd <= kMaxLine),
                   "invalid end line");
      }
    }
#endif
  }
  bool IsAutoAuto() const { return mStart == kAutoLine && mEnd == kAutoLine; }
  bool IsAuto() const { return mStart == kAutoLine; }
  bool IsDefinite() const { return mStart != kAutoLine; }
  uint32_t Extent() const {
    MOZ_ASSERT(mEnd != kAutoLine, "Extent is undefined for abs.pos. 'auto'");
    if (IsAuto()) {
      MOZ_ASSERT(mEnd >= 1 && mEnd < uint32_t(kMaxLine), "invalid span");
      return mEnd;
    }
    return mEnd - mStart;
  }

  /**
   * Return an object suitable for iterating this range.
   */
  auto Range() const { return IntegerRange<uint32_t>(mStart, mEnd); }

  /**
   * Resolve this auto range to start at aStart, making it definite.
   * @param aClampMaxLine the maximum allowed line number (zero-based)
   * Precondition: this range IsAuto()
   */
  void ResolveAutoPosition(uint32_t aStart, uint32_t aClampMaxLine) {
    MOZ_ASSERT(IsAuto(), "Why call me?");
    mStart = aStart;
    mEnd += aStart;
    // Clamp to aClampMaxLine, which is where kMaxLine is in the explicit
    // grid in a non-subgrid axis; this implements clamping per
    // http://dev.w3.org/csswg/css-grid/#overlarge-grids
    // In a subgrid axis it's the end of the grid in that axis.
    if (MOZ_UNLIKELY(mStart >= aClampMaxLine)) {
      mEnd = aClampMaxLine;
      mStart = mEnd - 1;
    } else if (MOZ_UNLIKELY(mEnd > aClampMaxLine)) {
      mEnd = aClampMaxLine;
    }
  }
  /**
   * Translate the lines to account for (empty) removed tracks.  This method
   * is only for grid items and should only be called after placement.
   * aNumRemovedTracks contains a count for each line in the grid how many
   * tracks were removed between the start of the grid and that line.
   */
  void AdjustForRemovedTracks(const nsTArray<uint32_t>& aNumRemovedTracks) {
    MOZ_ASSERT(mStart != kAutoLine, "invalid resolved line for a grid item");
    MOZ_ASSERT(mEnd != kAutoLine, "invalid resolved line for a grid item");
    uint32_t numRemovedTracks = aNumRemovedTracks[mStart];
    MOZ_ASSERT(numRemovedTracks == aNumRemovedTracks[mEnd],
               "tracks that a grid item spans can't be removed");
    mStart -= numRemovedTracks;
    mEnd -= numRemovedTracks;
  }
  /**
   * Translate the lines to account for (empty) removed tracks.  This method
   * is only for abs.pos. children and should only be called after placement.
   * Same as for in-flow items, but we don't touch 'auto' lines here and we
   * also need to adjust areas that span into the removed tracks.
   */
  void AdjustAbsPosForRemovedTracks(
      const nsTArray<uint32_t>& aNumRemovedTracks) {
    if (mStart != kAutoLine) {
      mStart -= aNumRemovedTracks[mStart];
    }
    if (mEnd != kAutoLine) {
      MOZ_ASSERT(mStart == kAutoLine || mEnd > mStart, "invalid line range");
      mEnd -= aNumRemovedTracks[mEnd];
    }
  }
  /**
   * Return the contribution of this line range for step 2 in
   * http://dev.w3.org/csswg/css-grid/#auto-placement-algo
   */
  uint32_t HypotheticalEnd() const { return mEnd; }
  /**
   * Given an array of track sizes, return the starting position and length
   * of the tracks in this line range.
   */
  void ToPositionAndLength(const nsTArray<TrackSize>& aTrackSizes,
                           nscoord* aPos, nscoord* aLength) const;
  /**
   * Given an array of track sizes, return the length of the tracks in this
   * line range.
   */
  nscoord ToLength(const nsTArray<TrackSize>& aTrackSizes) const;
  /**
   * Given an array of track sizes and a grid origin coordinate, adjust the
   * abs.pos. containing block along an axis given by aPos and aLength.
   * aPos and aLength should already be initialized to the grid container
   * containing block for this axis before calling this method.
   */
  void ToPositionAndLengthForAbsPos(const Tracks& aTracks, nscoord aGridOrigin,
                                    nscoord* aPos, nscoord* aLength) const;

  void Translate(int32_t aOffset) {
    MOZ_ASSERT(IsDefinite());
    mStart += aOffset;
    mEnd += aOffset;
  }

  /** Swap the start/end sides of this range. */
  void ReverseDirection(uint32_t aGridEnd) {
    MOZ_ASSERT(IsDefinite());
    MOZ_ASSERT(aGridEnd >= mEnd);
    uint32_t newStart = aGridEnd - mEnd;
    mEnd = aGridEnd - mStart;
    mStart = newStart;
  }

  /**
   * @note We'll use the signed member while resolving definite positions
   * to line numbers (1-based), which may become negative for implicit lines
   * to the top/left of the explicit grid.  PlaceGridItems() then translates
   * the whole grid to a 0,0 origin and we'll use the unsigned member from
   * there on.
   */
  union {
    uint32_t mStart;
    int32_t mUntranslatedStart;
  };
  union {
    uint32_t mEnd;
    int32_t mUntranslatedEnd;
  };

 protected:
  LineRange() : mStart(0), mEnd(0) {}
};

/**
 * Helper class to construct a LineRange from translated lines.
 * The ctor only accepts translated definite line numbers.
 */
struct nsGridContainerFrame::TranslatedLineRange : public LineRange {
  TranslatedLineRange(uint32_t aStart, uint32_t aEnd) {
    MOZ_ASSERT(aStart < aEnd && aEnd <= kTranslatedMaxLine);
    mStart = aStart;
    mEnd = aEnd;
  }
};

/**
 * A GridArea is the area in the grid for a grid item.
 * The area is represented by two LineRanges, both of which can be auto
 * (@see LineRange) in intermediate steps while the item is being placed.
 * @see PlaceGridItems
 */
struct nsGridContainerFrame::GridArea {
  GridArea(const LineRange& aCols, const LineRange& aRows)
      : mCols(aCols), mRows(aRows) {}
  bool IsDefinite() const { return mCols.IsDefinite() && mRows.IsDefinite(); }
  LineRange& LineRangeForAxis(LogicalAxis aAxis) {
    return aAxis == eLogicalAxisInline ? mCols : mRows;
  }
  const LineRange& LineRangeForAxis(LogicalAxis aAxis) const {
    return aAxis == eLogicalAxisInline ? mCols : mRows;
  }
  LineRange mCols;
  LineRange mRows;
};

struct nsGridContainerFrame::GridItemInfo {
  /**
   * Item state per axis.
   */
  enum StateBits : uint16_t {
    // Does the item span a flex track?
    eIsFlexing = 0x1,

    // First or last baseline alignment preference. They are mutually exclusive.
    // This does *NOT* represent the baseline alignment group. See the member
    // variable for that.
    // <https://drafts.csswg.org/css-align-3/#baseline-alignment-preference>
    eFirstBaseline = 0x2,
    eLastBaseline = 0x4,
    eIsBaselineAligned = eFirstBaseline | eLastBaseline,

    // One of e[Self|Content]Baseline is set when eIsBaselineAligned is true
    eSelfBaseline = 0x8,  // is it *-self:[last ]baseline alignment?
    // Ditto *-content:[last ]baseline. Mutually exclusive w. eSelfBaseline.
    eContentBaseline = 0x10,

    // The baseline affects the margin or padding on the item's end side when
    // this bit is set.  In a grid-axis it's always set for eLastBaseline and
    // always unset for eFirstBaseline.  In a masonry-axis, it's set for
    // baseline groups in the EndStretch set and unset for the StartStretch set.
    eEndSideBaseline = 0x20,
    eAllBaselineBits = eIsBaselineAligned | eSelfBaseline | eContentBaseline |
                       eEndSideBaseline,

    // Should apply Automatic Minimum Size per:
    // https://drafts.csswg.org/css-grid/#min-size-auto
    eApplyAutoMinSize = 0x40,
    // Clamp per https://drafts.csswg.org/css-grid/#min-size-auto
    eClampMarginBoxMinSize = 0x80,
    eIsSubgrid = 0x100,
    // set on subgrids and items in subgrids if they are adjacent to the grid
    // start/end edge (excluding grid-aligned abs.pos. frames)
    eStartEdge = 0x200,
    eEndEdge = 0x400,
    eEdgeBits = eStartEdge | eEndEdge,
    // Set if this item was auto-placed in this axis.
    eAutoPlacement = 0x800,
    // Set if this item is the last item in its track (masonry layout only)
    eIsLastItemInMasonryTrack = 0x1000,
  };

  GridItemInfo(nsIFrame* aFrame, const GridArea& aArea);

  GridItemInfo(const GridItemInfo& aOther)
      : mFrame(aOther.mFrame), mArea(aOther.mArea) {
    mBaselineOffset = aOther.mBaselineOffset;
    mState = aOther.mState;
  }

  GridItemInfo& operator=(const GridItemInfo&) = delete;

  static bool BaselineAlignmentAffectsEndSide(StateBits state) {
    return state & StateBits::eEndSideBaseline;
  }

  /**
   * Inhibit subgrid layout unless the item is placed in the first "track" in
   * a parent masonry-axis, or has definite placement or spans all tracks in
   * the parent grid-axis.
   * TODO: this is stricter than what the Masonry proposal currently states
   *       (bug 1627581)
   */
  void MaybeInhibitSubgridInMasonry(nsGridContainerFrame* aParent,
                                    uint32_t aGridAxisTrackCount);

  /**
   * Inhibit subgridding in aAxis for this item.
   */
  void InhibitSubgrid(nsGridContainerFrame* aParent, LogicalAxis aAxis);

  /**
   * Return a copy of this item with its row/column data swapped.
   */
  GridItemInfo Transpose() const {
    GridItemInfo info(mFrame, GridArea(mArea.mRows, mArea.mCols));
    info.mState[eLogicalAxisBlock] = mState[eLogicalAxisInline];
    info.mState[eLogicalAxisInline] = mState[eLogicalAxisBlock];
    info.mBaselineOffset[eLogicalAxisBlock] =
        mBaselineOffset[eLogicalAxisInline];
    info.mBaselineOffset[eLogicalAxisInline] =
        mBaselineOffset[eLogicalAxisBlock];
    return info;
  }

  /** Swap the start/end sides in aAxis. */
  inline void ReverseDirection(LogicalAxis aAxis, uint32_t aGridEnd);

  // Is this item a subgrid in the given container axis?
  bool IsSubgrid(LogicalAxis aAxis) const {
    return mState[aAxis] & StateBits::eIsSubgrid;
  }

  // Is this item a subgrid in either axis?
  bool IsSubgrid() const {
    return IsSubgrid(eLogicalAxisInline) || IsSubgrid(eLogicalAxisBlock);
  }

  // Return the (inner) grid container frame associated with this subgrid item.
  nsGridContainerFrame* SubgridFrame() const {
    MOZ_ASSERT(IsSubgrid());
    nsGridContainerFrame* gridFrame = GetGridContainerFrame(mFrame);
    MOZ_ASSERT(gridFrame && gridFrame->IsSubgrid());
    return gridFrame;
  }

  /**
   * Adjust our grid areas to account for removed auto-fit tracks in aAxis.
   */
  void AdjustForRemovedTracks(LogicalAxis aAxis,
                              const nsTArray<uint32_t>& aNumRemovedTracks);

  /**
   * If the item is [align|justify]-self:[last ]baseline aligned in the given
   * axis then set aBaselineOffset to the baseline offset and return aAlign.
   * Otherwise, return a fallback alignment.
   */
  StyleAlignFlags GetSelfBaseline(StyleAlignFlags aAlign, LogicalAxis aAxis,
                                  nscoord* aBaselineOffset) const {
    MOZ_ASSERT(aAlign == StyleAlignFlags::BASELINE ||
               aAlign == StyleAlignFlags::LAST_BASELINE);
    if (!(mState[aAxis] & eSelfBaseline)) {
      return aAlign == StyleAlignFlags::BASELINE ? StyleAlignFlags::SELF_START
                                                 : StyleAlignFlags::SELF_END;
    }
    *aBaselineOffset = mBaselineOffset[aAxis];
    return aAlign;
  }

  // Return true if we should apply Automatic Minimum Size to this item.
  // https://drafts.csswg.org/css-grid/#min-size-auto
  // @note the caller should also check that the item spans at least one track
  // that has a min track sizing function that is 'auto' before applying it.
  bool ShouldApplyAutoMinSize(WritingMode aContainerWM,
                              LogicalAxis aContainerAxis,
                              nscoord aPercentageBasis) const {
    const bool isInlineAxis = aContainerAxis == eLogicalAxisInline;
    const auto* pos =
        mFrame->IsTableWrapperFrame()
            ? mFrame->PrincipalChildList().FirstChild()->StylePosition()
            : mFrame->StylePosition();
    const auto& size =
        isInlineAxis ? pos->ISize(aContainerWM) : pos->BSize(aContainerWM);
    // max-content and min-content should behave as initial value in block axis.
    // FIXME: Bug 567039: moz-fit-content and -moz-available are not supported
    // for block size dimension on sizing properties (e.g. height), so we
    // treat it as `auto`.
    bool isAuto = size.IsAuto() ||
                  (isInlineAxis ==
                       aContainerWM.IsOrthogonalTo(mFrame->GetWritingMode()) &&
                   size.BehavesLikeInitialValueOnBlockAxis());
    // NOTE: if we have a definite size then our automatic minimum size
    // can't affect our size.  Excluding these simplifies applying
    // the clamping in the right cases later.
    if (!isAuto && !::IsPercentOfIndefiniteSize(size, aPercentageBasis)) {
      return false;
    }
    const auto& minSize = isInlineAxis ? pos->MinISize(aContainerWM)
                                       : pos->MinBSize(aContainerWM);
    // max-content and min-content should behave as initial value in block axis.
    // FIXME: Bug 567039: moz-fit-content and -moz-available are not supported
    // for block size dimension on sizing properties (e.g. height), so we
    // treat it as `auto`.
    isAuto = minSize.IsAuto() ||
             (isInlineAxis ==
                  aContainerWM.IsOrthogonalTo(mFrame->GetWritingMode()) &&
              minSize.BehavesLikeInitialValueOnBlockAxis());
    return isAuto && !mFrame->StyleDisplay()->IsScrollableOverflow();
  }

#ifdef DEBUG
  void Dump() const;
#endif

  static bool IsStartRowLessThan(const GridItemInfo* a, const GridItemInfo* b) {
    return a->mArea.mRows.mStart < b->mArea.mRows.mStart;
  }

  // Sorting functions for 'masonry-auto-flow:next'.  We sort the items that
  // were placed into the first track by the Grid placement algorithm first
  // (to honor that placement).  All other items will be placed by the Masonry
  // layout algorithm (their Grid placement in the masonry axis is irrelevant).
  static bool RowMasonryOrdered(const GridItemInfo* a, const GridItemInfo* b) {
    return a->mArea.mRows.mStart == 0 && b->mArea.mRows.mStart != 0 &&
           !a->mFrame->HasAnyStateBits(NS_FRAME_OUT_OF_FLOW);
  }
  static bool ColMasonryOrdered(const GridItemInfo* a, const GridItemInfo* b) {
    return a->mArea.mCols.mStart == 0 && b->mArea.mCols.mStart != 0 &&
           !a->mFrame->HasAnyStateBits(NS_FRAME_OUT_OF_FLOW);
  }

  // Sorting functions for 'masonry-auto-flow:definite-first'.  Similar to
  // the above, but here we also sort items with a definite item placement in
  // the grid axis in track order before 'auto'-placed items. We also sort all
  // continuations first since they use the same placement as their
  // first-in-flow (we treat them as "definite" regardless of eAutoPlacement).
  static bool RowMasonryDefiniteFirst(const GridItemInfo* a,
                                      const GridItemInfo* b) {
    bool isContinuationA = a->mFrame->GetPrevInFlow();
    bool isContinuationB = b->mFrame->GetPrevInFlow();
    if (isContinuationA != isContinuationB) {
      return isContinuationA;
    }
    auto masonryA = a->mArea.mRows.mStart;
    auto gridA = a->mState[eLogicalAxisInline] & StateBits::eAutoPlacement;
    auto masonryB = b->mArea.mRows.mStart;
    auto gridB = b->mState[eLogicalAxisInline] & StateBits::eAutoPlacement;
    return (masonryA == 0 ? masonryB != 0 : (masonryB != 0 && gridA < gridB)) &&
           !a->mFrame->HasAnyStateBits(NS_FRAME_OUT_OF_FLOW);
  }
  static bool ColMasonryDefiniteFirst(const GridItemInfo* a,
                                      const GridItemInfo* b) {
    MOZ_ASSERT(!a->mFrame->GetPrevInFlow() && !b->mFrame->GetPrevInFlow(),
               "fragmentation not supported in inline axis");
    auto masonryA = a->mArea.mCols.mStart;
    auto gridA = a->mState[eLogicalAxisBlock] & StateBits::eAutoPlacement;
    auto masonryB = b->mArea.mCols.mStart;
    auto gridB = b->mState[eLogicalAxisBlock] & StateBits::eAutoPlacement;
    return (masonryA == 0 ? masonryB != 0 : (masonryB != 0 && gridA < gridB)) &&
           !a->mFrame->HasAnyStateBits(NS_FRAME_OUT_OF_FLOW);
  }

  // Return true if this items block size is dependent on the size of the
  // container it is in.
  bool IsBSizeDependentOnContainerSize(WritingMode aContainerWM) const {
    const auto IsDependentOnContainerSize = [](const auto& size) -> bool {
      return size.HasPercent() || size.IsMozAvailable();
    };

    const nsStylePosition* stylePos = mFrame->StylePosition();
    bool isItemAutoSize =
        IsDependentOnContainerSize(stylePos->BSize(aContainerWM)) ||
        IsDependentOnContainerSize(stylePos->MinBSize(aContainerWM)) ||
        IsDependentOnContainerSize(stylePos->MaxBSize(aContainerWM));

    return isItemAutoSize;
  }

  nsIFrame* const mFrame;
  GridArea mArea;

  // Offset from the margin edge to the baseline (LogicalAxis index).  It's from
  // the start edge for first baseline sharing group, otherwise from the end
  // edge.
  // It's mutable since we update the value fairly late (just before reflowing
  // the item).
  mutable PerLogicalAxis<nscoord> mBaselineOffset;

  // State bits per axis.
  mutable PerLogicalAxis<StateBits> mState;
};

using GridItemInfo = nsGridContainerFrame::GridItemInfo;
using ItemState = GridItemInfo::StateBits;
MOZ_MAKE_ENUM_CLASS_BITWISE_OPERATORS(ItemState)

GridItemInfo::GridItemInfo(nsIFrame* aFrame, const GridArea& aArea)
    : mFrame(aFrame), mArea(aArea), mBaselineOffset{0, 0} {
  mState[eLogicalAxisBlock] =
      StateBits(mArea.mRows.mStart == kAutoLine ? eAutoPlacement : 0);
  mState[eLogicalAxisInline] =
      StateBits(mArea.mCols.mStart == kAutoLine ? eAutoPlacement : 0);

  if (auto* gridFrame = GetGridContainerFrame(mFrame)) {
    auto parentWM = aFrame->GetParent()->GetWritingMode();
    bool isOrthogonal = parentWM.IsOrthogonalTo(gridFrame->GetWritingMode());
    if (gridFrame->IsColSubgrid()) {
      mState[isOrthogonal ? eLogicalAxisBlock : eLogicalAxisInline] |=
          StateBits::eIsSubgrid;
    }
    if (gridFrame->IsRowSubgrid()) {
      mState[isOrthogonal ? eLogicalAxisInline : eLogicalAxisBlock] |=
          StateBits::eIsSubgrid;
    }
  }
}

void GridItemInfo::ReverseDirection(LogicalAxis aAxis, uint32_t aGridEnd) {
  mArea.LineRangeForAxis(aAxis).ReverseDirection(aGridEnd);
  ItemState& state = mState[aAxis];
  ItemState newState = state & ~ItemState::eEdgeBits;
  if (state & ItemState::eStartEdge) {
    newState |= ItemState::eEndEdge;
  }
  if (state & ItemState::eEndEdge) {
    newState |= ItemState::eStartEdge;
  }
  state = newState;
}

void GridItemInfo::InhibitSubgrid(nsGridContainerFrame* aParent,
                                  LogicalAxis aAxis) {
  MOZ_ASSERT(IsSubgrid(aAxis));
  auto bit = NS_STATE_GRID_IS_COL_SUBGRID;
  if (aParent->GetWritingMode().IsOrthogonalTo(mFrame->GetWritingMode()) !=
      (aAxis == eLogicalAxisBlock)) {
    bit = NS_STATE_GRID_IS_ROW_SUBGRID;
  }
  MOZ_ASSERT(SubgridFrame()->HasAnyStateBits(bit));
  SubgridFrame()->RemoveStateBits(bit);
  mState[aAxis] &= StateBits(~StateBits::eIsSubgrid);
}

void GridItemInfo::MaybeInhibitSubgridInMasonry(nsGridContainerFrame* aParent,
                                                uint32_t aGridAxisTrackCount) {
  if (IsSubgrid(eLogicalAxisInline) && aParent->IsMasonry(eLogicalAxisBlock) &&
      mArea.mRows.mStart != 0 && mArea.mCols.Extent() != aGridAxisTrackCount &&
      (mState[eLogicalAxisInline] & eAutoPlacement)) {
    InhibitSubgrid(aParent, eLogicalAxisInline);
    return;
  }
  if (IsSubgrid(eLogicalAxisBlock) && aParent->IsMasonry(eLogicalAxisInline) &&
      mArea.mCols.mStart != 0 && mArea.mRows.Extent() != aGridAxisTrackCount &&
      (mState[eLogicalAxisBlock] & eAutoPlacement)) {
    InhibitSubgrid(aParent, eLogicalAxisBlock);
  }
}

// Each subgrid stores this data about its items etc on a frame property.
struct nsGridContainerFrame::Subgrid {
  Subgrid(const GridArea& aArea, bool aIsOrthogonal, WritingMode aCBWM)
      : mArea(aArea),
        mGridColEnd(0),
        mGridRowEnd(0),
        mMarginBorderPadding(aCBWM),
        mIsOrthogonal(aIsOrthogonal) {}

  // Return the relevant line range for the subgrid column axis.
  const LineRange& SubgridCols() const {
    return mIsOrthogonal ? mArea.mRows : mArea.mCols;
  }
  // Return the relevant line range for the subgrid row axis.
  const LineRange& SubgridRows() const {
    return mIsOrthogonal ? mArea.mCols : mArea.mRows;
  }

  // The subgrid's items.
  nsTArray<GridItemInfo> mGridItems;
  // The subgrid's abs.pos. items.
  nsTArray<GridItemInfo> mAbsPosItems;
  // The subgrid's area as a grid item, i.e. in its parent's grid space.
  GridArea mArea;
  // The (inner) grid size for the subgrid, zero-based.
  uint32_t mGridColEnd;
  uint32_t mGridRowEnd;
  // The margin+border+padding for the subgrid box in its parent grid's WM.
  // (This also includes the size of any scrollbars.)
  LogicalMargin mMarginBorderPadding;
  // Does the subgrid frame have orthogonal writing-mode to its parent grid
  // container?
  bool mIsOrthogonal;

  NS_DECLARE_FRAME_PROPERTY_DELETABLE(Prop, Subgrid)
};
using Subgrid = nsGridContainerFrame::Subgrid;

void GridItemInfo::AdjustForRemovedTracks(
    LogicalAxis aAxis, const nsTArray<uint32_t>& aNumRemovedTracks) {
  const bool abspos = mFrame->HasAnyStateBits(NS_FRAME_OUT_OF_FLOW);
  auto& lines = mArea.LineRangeForAxis(aAxis);
  if (abspos) {
    lines.AdjustAbsPosForRemovedTracks(aNumRemovedTracks);
  } else {
    lines.AdjustForRemovedTracks(aNumRemovedTracks);
  }
  if (IsSubgrid()) {
    auto* subgrid = SubgridFrame()->GetProperty(Subgrid::Prop());
    if (subgrid) {
      auto& lines = subgrid->mArea.LineRangeForAxis(aAxis);
      if (abspos) {
        lines.AdjustAbsPosForRemovedTracks(aNumRemovedTracks);
      } else {
        lines.AdjustForRemovedTracks(aNumRemovedTracks);
      }
    }
  }
}

/**
 * Track size data for use by subgrids (which don't do sizing of their own
 * in a subgridded axis).  A non-subgrid container stores its resolved sizes,
 * but only if it has any subgrid children.  A subgrid always stores one.
 * In a subgridded axis, we copy the parent's sizes (see CopyUsedTrackSizes).
 *
 * This struct us stored on a frame property, which may be null before the track
 * sizing step for the given container.  A null property is semantically
 * equivalent to mCanResolveLineRangeSize being false in both axes.
 * @note the axis used to access this data is in the grid container's own
 * writing-mode, same as in other track-sizing functions.
 */
struct nsGridContainerFrame::UsedTrackSizes {
  UsedTrackSizes() : mCanResolveLineRangeSize{false, false} {}

  /**
   * Setup mSizes by copying track sizes from aFrame's grid container
   * parent when aAxis is subgridded (and recurse if the parent is a subgrid
   * that doesn't have sizes yet), or by running the Track Sizing Algo when
   * the axis is not subgridded (for a subgrid).
   * Set mCanResolveLineRangeSize[aAxis] to true once we have obtained
   * sizes for an axis (if it's already true then this method is a NOP).
   */
  void ResolveTrackSizesForAxis(nsGridContainerFrame* aFrame, LogicalAxis aAxis,
                                gfxContext& aRC);

  /** Helper function for the above method */
  void ResolveSubgridTrackSizesForAxis(nsGridContainerFrame* aFrame,
                                       LogicalAxis aAxis, Subgrid* aSubgrid,
                                       gfxContext& aRC,
                                       nscoord aContentBoxSize);

  // This only has valid sizes when mCanResolveLineRangeSize is true in
  // the same axis.  It may have zero tracks (a grid with only abs.pos.
  // subgrids/items may have zero tracks).
  PerLogicalAxis<nsTArray<TrackSize>> mSizes;
  // True if mSizes can be used to resolve line range sizes in an axis.
  PerLogicalAxis<bool> mCanResolveLineRangeSize;

  NS_DECLARE_FRAME_PROPERTY_DELETABLE(Prop, UsedTrackSizes)
};
using UsedTrackSizes = nsGridContainerFrame::UsedTrackSizes;

#ifdef DEBUG
void nsGridContainerFrame::GridItemInfo::Dump() const {
  auto Dump1 = [this](const char* aMsg, LogicalAxis aAxis) {
    auto state = mState[aAxis];
    if (!state) {
      return;
    }
    printf("%s", aMsg);
    if (state & ItemState::eEdgeBits) {
      printf("subgrid-adjacent-edges(");
      if (state & ItemState::eStartEdge) {
        printf("start ");
      }
      if (state & ItemState::eEndEdge) {
        printf("end");
      }
      printf(") ");
    }
    if (state & ItemState::eAutoPlacement) {
      printf("masonry-auto ");
    }
    if (state & ItemState::eIsSubgrid) {
      printf("subgrid ");
    }
    if (state & ItemState::eIsFlexing) {
      printf("flexing ");
    }
    if (state & ItemState::eApplyAutoMinSize) {
      printf("auto-min-size ");
    }
    if (state & ItemState::eClampMarginBoxMinSize) {
      printf("clamp ");
    }
    if (state & ItemState::eIsLastItemInMasonryTrack) {
      printf("last-in-track ");
    }
    if (state & ItemState::eFirstBaseline) {
      printf("first baseline %s-alignment ",
             (state & ItemState::eSelfBaseline) ? "self" : "content");
    }
    if (state & ItemState::eLastBaseline) {
      printf("last baseline %s-alignment ",
             (state & ItemState::eSelfBaseline) ? "self" : "content");
    }
    if (state & ItemState::eIsBaselineAligned) {
      printf("%.2fpx", NSAppUnitsToFloatPixels(mBaselineOffset[aAxis],
                                               AppUnitsPerCSSPixel()));
    }
    printf("\n");
  };
  printf("grid-row: %d %d\n", mArea.mRows.mStart, mArea.mRows.mEnd);
  Dump1("  grid block-axis: ", eLogicalAxisBlock);
  printf("grid-column: %d %d\n", mArea.mCols.mStart, mArea.mCols.mEnd);
  Dump1("  grid inline-axis: ", eLogicalAxisInline);
}
#endif

/**
 * Encapsulates CSS track-sizing functions.
 */
struct nsGridContainerFrame::TrackSizingFunctions {
 private:
  TrackSizingFunctions(const GridTemplate& aTemplate,
                       const StyleImplicitGridTracks& aAutoSizing,
                       const Maybe<size_t>& aRepeatAutoIndex, bool aIsSubgrid)
      : mTemplate(aTemplate),
        mTrackListValues(aTemplate.TrackListValues()),
        mAutoSizing(aAutoSizing),
        mExplicitGridOffset(0),
        mRepeatAutoStart(aRepeatAutoIndex.valueOr(0)),
        mRepeatAutoEnd(mRepeatAutoStart),
        mHasRepeatAuto(aRepeatAutoIndex.isSome()) {
    MOZ_ASSERT(!mHasRepeatAuto || !aIsSubgrid,
               "a track-list for a subgrid can't have an <auto-repeat> track");
    if (!aIsSubgrid) {
      ExpandNonRepeatAutoTracks();
    }

#ifdef DEBUG
    if (mHasRepeatAuto) {
      MOZ_ASSERT(mExpandedTracks.Length() >= 1);
      const unsigned maxTrack = kMaxLine - 1;
      // If the exanded tracks are out of range of the maximum track, we
      // can't compare the repeat-auto start. It will be removed later during
      // grid item placement in that situation.
      if (mExpandedTracks.Length() < maxTrack) {
        MOZ_ASSERT(mRepeatAutoStart < mExpandedTracks.Length());
      }
    }
#endif
  }

 public:
  TrackSizingFunctions(const GridTemplate& aGridTemplate,
                       const StyleImplicitGridTracks& aAutoSizing,
                       bool aIsSubgrid)
      : TrackSizingFunctions(aGridTemplate, aAutoSizing,
                             aGridTemplate.RepeatAutoIndex(), aIsSubgrid) {}

 private:
  enum { ForSubgridFallbackTag };
  TrackSizingFunctions(const GridTemplate& aGridTemplate,
                       const StyleImplicitGridTracks& aAutoSizing,
                       decltype(ForSubgridFallbackTag))
      : TrackSizingFunctions(aGridTemplate, aAutoSizing, Nothing(),
                             /* aIsSubgrid */ true) {}

 public:
  /**
   * This is used in a subgridded axis to resolve sizes before its parent's
   * sizes are known for intrinsic sizing purposes.  It copies the slice of
   * the nearest non-subgridded axis' track sizing functions spanned by
   * the subgrid.
   *
   * FIXME: this was written before there was a spec... the spec now says:
   * "If calculating the layout of a grid item in this step depends on
   *  the available space in the block axis, assume the available space
   *  that it would have if any row with a definite max track sizing
   *  function had that size and all other rows were infinite."
   * https://drafts.csswg.org/css-grid-2/#subgrid-sizing
   */
  static TrackSizingFunctions ForSubgridFallback(
      nsGridContainerFrame* aSubgridFrame, const Subgrid* aSubgrid,
      nsGridContainerFrame* aParentGridContainer, LogicalAxis aParentAxis) {
    MOZ_ASSERT(aSubgrid);
    MOZ_ASSERT(aSubgridFrame->IsSubgrid(aSubgrid->mIsOrthogonal
                                            ? GetOrthogonalAxis(aParentAxis)
                                            : aParentAxis));
    nsGridContainerFrame* parent = aParentGridContainer;
    auto parentAxis = aParentAxis;
    LineRange range = aSubgrid->mArea.LineRangeForAxis(parentAxis);
    // Find our nearest non-subgridded axis and use its track sizing functions.
    while (parent->IsSubgrid(parentAxis)) {
      const auto* parentSubgrid = parent->GetProperty(Subgrid::Prop());
      auto* grandParent = parent->ParentGridContainerForSubgrid();
      auto grandParentWM = grandParent->GetWritingMode();
      bool isSameDirInAxis =
          parent->GetWritingMode().ParallelAxisStartsOnSameSide(parentAxis,
                                                                grandParentWM);
      if (MOZ_UNLIKELY(!isSameDirInAxis)) {
        auto end = parentAxis == eLogicalAxisBlock ? parentSubgrid->mGridRowEnd
                                                   : parentSubgrid->mGridColEnd;
        range.ReverseDirection(end);
        // range is now in the same direction as the grand-parent's axis
      }
      auto grandParentAxis = parentSubgrid->mIsOrthogonal
                                 ? GetOrthogonalAxis(parentAxis)
                                 : parentAxis;
      const auto& parentRange =
          parentSubgrid->mArea.LineRangeForAxis(grandParentAxis);
      range.Translate(parentRange.mStart);
      // range is now in the grand-parent's coordinates
      parentAxis = grandParentAxis;
      parent = grandParent;
    }
    const auto* pos = parent->StylePosition();
    const auto isInlineAxis = parentAxis == eLogicalAxisInline;
    const auto& szf =
        isInlineAxis ? pos->mGridTemplateRows : pos->mGridTemplateColumns;
    const auto& autoSizing =
        isInlineAxis ? pos->mGridAutoColumns : pos->mGridAutoRows;
    return TrackSizingFunctions(szf, autoSizing, ForSubgridFallbackTag);
  }

  /**
   * Initialize the number of auto-fill/fit tracks to use.
   * This can be zero if no auto-fill/fit track was specified, or if the repeat
   * begins after the maximum allowed track.
   */
  void InitRepeatTracks(const NonNegativeLengthPercentageOrNormal& aGridGap,
                        nscoord aMinSize, nscoord aSize, nscoord aMaxSize) {
    const uint32_t maxTrack = kMaxLine - 1;
    // Check for a repeat after the maximum allowed track.
    if (MOZ_UNLIKELY(mRepeatAutoStart >= maxTrack)) {
      mHasRepeatAuto = false;
      mRepeatAutoStart = 0;
      mRepeatAutoEnd = 0;
      return;
    }
    uint32_t repeatTracks =
        CalculateRepeatFillCount(aGridGap, aMinSize, aSize, aMaxSize) *
        NumRepeatTracks();
    // Clamp the number of repeat tracks to the maximum possible track.
    repeatTracks = std::min(repeatTracks, maxTrack - mRepeatAutoStart);
    SetNumRepeatTracks(repeatTracks);
    // Blank out the removed flags for each of these tracks.
    mRemovedRepeatTracks.SetLength(repeatTracks);
    for (auto& track : mRemovedRepeatTracks) {
      track = false;
    }
  }

  uint32_t CalculateRepeatFillCount(
      const NonNegativeLengthPercentageOrNormal& aGridGap, nscoord aMinSize,
      nscoord aSize, nscoord aMaxSize) const {
    if (!mHasRepeatAuto) {
      return 0;
    }
    // At this point no tracks will have been collapsed, so the RepeatEndDelta
    // should not be negative.
    MOZ_ASSERT(RepeatEndDelta() >= 0);
    // Note that this uses NumRepeatTracks and mRepeatAutoStart/End, although
    // the result of this method is used to change those values to a fully
    // expanded value. Spec quotes are from
    // https://drafts.csswg.org/css-grid/#repeat-notation
    const uint32_t numTracks = mExpandedTracks.Length() + RepeatEndDelta();
    MOZ_ASSERT(numTracks >= 1, "expected at least the repeat() track");
    if (MOZ_UNLIKELY(numTracks >= kMaxLine)) {
      // The fixed tracks plus an entire repetition is either larger or as
      // large as the maximum track, so we do not need to measure how many
      // repetitions will fit. This also avoids needing to check for if
      // kMaxLine - numTracks would underflow at the end where we clamp the
      // result.
      return 1;
    }
    nscoord maxFill = aSize != NS_UNCONSTRAINEDSIZE ? aSize : aMaxSize;
    if (maxFill == NS_UNCONSTRAINEDSIZE && aMinSize == 0) {
      // "Otherwise, the specified track list repeats only once."
      return 1;
    }
    nscoord repeatTrackSum = 0;
    // Note that one repeat() track size is included in |sum| in this loop.
    nscoord sum = 0;
    const nscoord percentBasis = aSize;
    for (uint32_t i = 0; i < numTracks; ++i) {
      // "treating each track as its max track sizing function if that is
      // definite or as its minimum track sizing function otherwise"
      // https://drafts.csswg.org/css-grid/#valdef-repeat-auto-fill
      const auto& sizingFunction = SizingFor(i);
      const auto& maxCoord = sizingFunction.GetMax();
      const auto* coord = &maxCoord;
      if (!coord->IsBreadth()) {
        coord = &sizingFunction.GetMin();
        if (!coord->IsBreadth()) {
          return 1;
        }
      }
      nscoord trackSize = ::ResolveToDefiniteSize(*coord, percentBasis);
      if (i >= mRepeatAutoStart && i < mRepeatAutoEnd) {
        // Use a minimum 1px for the repeat() track-size.
        if (trackSize < AppUnitsPerCSSPixel()) {
          trackSize = AppUnitsPerCSSPixel();
        }
        repeatTrackSum += trackSize;
      }
      sum += trackSize;
    }
    nscoord gridGap = nsLayoutUtils::ResolveGapToLength(aGridGap, aSize);
    if (numTracks > 1) {
      // Add grid-gaps for all the tracks including the repeat() track.
      sum += gridGap * (numTracks - 1);
    }
    // Calculate the max number of tracks that fits without overflow.
    nscoord available = maxFill != NS_UNCONSTRAINEDSIZE ? maxFill : aMinSize;
    nscoord spaceToFill = available - sum;
    if (spaceToFill <= 0) {
      // "if any number of repetitions would overflow, then 1 repetition"
      return 1;
    }
    // Calculate the max number of tracks that fits without overflow.
    // Since we already have one repetition in sum, we can simply add one grid
    // gap for each element in the repeat.
    div_t q = div(spaceToFill, repeatTrackSum + gridGap * NumRepeatTracks());
    // The +1 here is for the one repeat track we already accounted for above.
    uint32_t numRepeatTracks = q.quot + 1;
    if (q.rem != 0 && maxFill == NS_UNCONSTRAINEDSIZE) {
      // "Otherwise, if the grid container has a definite min size in
      // the relevant axis, the number of repetitions is the largest possible
      // positive integer that fulfills that minimum requirement."
      ++numRepeatTracks;  // one more to ensure the grid is at least min-size
    }
    // Clamp the number of repeat tracks so that the last line <= kMaxLine.
    // (note that |numTracks| already includes one repeat() track)
    MOZ_ASSERT(numTracks >= NumRepeatTracks());
    const uint32_t maxRepeatTrackCount = kMaxLine - numTracks;
    const uint32_t maxRepetitions = maxRepeatTrackCount / NumRepeatTracks();
    return std::min(numRepeatTracks, maxRepetitions);
  }

  /**
   * Compute the explicit grid end line number (in a zero-based grid).
   * @param aGridTemplateAreasEnd 'grid-template-areas' end line in this axis
   */
  uint32_t ComputeExplicitGridEnd(uint32_t aGridTemplateAreasEnd) {
    uint32_t end = NumExplicitTracks() + 1;
    end = std::max(end, aGridTemplateAreasEnd);
    end = std::min(end, uint32_t(kMaxLine));
    return end;
  }
  const StyleTrackSize& SizingFor(uint32_t aTrackIndex) const {
    static const StyleTrackSize kAutoTrackSize =
        StyleTrackSize::Breadth(StyleTrackBreadth::Auto());
    // |aIndex| is the relative index to mAutoSizing. A negative value means it
    // is the last Nth element.
    auto getImplicitSize = [this](int32_t aIndex) -> const StyleTrackSize& {
      MOZ_ASSERT(!(mAutoSizing.Length() == 1 &&
                   mAutoSizing.AsSpan()[0] == kAutoTrackSize),
                 "It's impossible to have one track with auto value because we "
                 "filter out this case during parsing");

      if (mAutoSizing.IsEmpty()) {
        return kAutoTrackSize;
      }

      // If multiple track sizes are given, the pattern is repeated as necessary
      // to find the size of the implicit tracks.
      int32_t i = aIndex % int32_t(mAutoSizing.Length());
      if (i < 0) {
        i += mAutoSizing.Length();
      }
      return mAutoSizing.AsSpan()[i];
    };

    if (MOZ_UNLIKELY(aTrackIndex < mExplicitGridOffset)) {
      // The last implicit grid track before the explicit grid receives the
      // last specified size, and so on backwards. Therefore we pass the
      // negative relative index to imply that we should get the implicit size
      // from the last Nth specified grid auto size.
      return getImplicitSize(int32_t(aTrackIndex) -
                             int32_t(mExplicitGridOffset));
    }
    uint32_t index = aTrackIndex - mExplicitGridOffset;
    MOZ_ASSERT(mRepeatAutoStart <= mRepeatAutoEnd);

    if (index >= mRepeatAutoStart) {
      if (index < mRepeatAutoEnd) {
        // Expand the repeat tracks.
        const auto& indices = mExpandedTracks[mRepeatAutoStart];
        const TrackListValue& value = mTrackListValues[indices.first];

        // We expect the default to be used for all track repeats.
        MOZ_ASSERT(indices.second == 0);

        const auto& repeatTracks = value.AsTrackRepeat().track_sizes.AsSpan();

        // Find the repeat track to use, skipping over any collapsed tracks.
        const uint32_t finalRepeatIndex = (index - mRepeatAutoStart);
        uint32_t repeatWithCollapsed = 0;
        // NOTE: We need SizingFor before the final collapsed tracks are known.
        // We know that it's invalid to have empty mRemovedRepeatTracks when
        // there are any repeat tracks, so we can detect that situation here.
        if (mRemovedRepeatTracks.IsEmpty()) {
          repeatWithCollapsed = finalRepeatIndex;
        } else {
          // Count up through the repeat tracks, until we have seen
          // finalRepeatIndex number of non-collapsed tracks.
          for (uint32_t repeatNoCollapsed = 0;
               repeatNoCollapsed < finalRepeatIndex; repeatWithCollapsed++) {
            if (!mRemovedRepeatTracks[repeatWithCollapsed]) {
              repeatNoCollapsed++;
            }
          }
          // If we stopped iterating on a collapsed track, continue to the next
          // non-collapsed track.
          while (mRemovedRepeatTracks[repeatWithCollapsed]) {
            repeatWithCollapsed++;
          }
        }
        return repeatTracks[repeatWithCollapsed % repeatTracks.Length()];
      } else {
        // The index is after the repeat auto range, adjust it to skip over the
        // repeat value. This will have no effect if there is no auto repeat,
        // since then RepeatEndDelta will return zero.
        index -= RepeatEndDelta();
      }
    }
    if (index >= mExpandedTracks.Length()) {
      return getImplicitSize(index - mExpandedTracks.Length());
    }
    auto& indices = mExpandedTracks[index];
    const TrackListValue& value = mTrackListValues[indices.first];
    if (value.IsTrackSize()) {
      MOZ_ASSERT(indices.second == 0);
      return value.AsTrackSize();
    }
    return value.AsTrackRepeat().track_sizes.AsSpan()[indices.second];
  }
  const StyleTrackBreadth& MaxSizingFor(uint32_t aTrackIndex) const {
    return SizingFor(aTrackIndex).GetMax();
  }
  const StyleTrackBreadth& MinSizingFor(uint32_t aTrackIndex) const {
    return SizingFor(aTrackIndex).GetMin();
  }
  uint32_t NumExplicitTracks() const {
    return mExpandedTracks.Length() + RepeatEndDelta();
  }
  uint32_t NumRepeatTracks() const { return mRepeatAutoEnd - mRepeatAutoStart; }
  // The difference between mExplicitGridEnd and mSizingFunctions.Length().
  int32_t RepeatEndDelta() const {
    return mHasRepeatAuto ? int32_t(NumRepeatTracks()) - 1 : 0;
  }
  void SetNumRepeatTracks(uint32_t aNumRepeatTracks) {
    MOZ_ASSERT(mHasRepeatAuto || aNumRepeatTracks == 0);
    mRepeatAutoEnd = mRepeatAutoStart + aNumRepeatTracks;
  }

  // Store mTrackListValues into mExpandedTracks with `repeat(INTEGER, ...)`
  // tracks expanded.
  void ExpandNonRepeatAutoTracks() {
    for (size_t i = 0; i < mTrackListValues.Length(); ++i) {
      auto& value = mTrackListValues[i];
      if (value.IsTrackSize()) {
        mExpandedTracks.EmplaceBack(i, 0);
        continue;
      }
      auto& repeat = value.AsTrackRepeat();
      if (!repeat.count.IsNumber()) {
        MOZ_ASSERT(i == mRepeatAutoStart);
        mRepeatAutoStart = mExpandedTracks.Length();
        mRepeatAutoEnd = mRepeatAutoStart + repeat.track_sizes.Length();
        mExpandedTracks.EmplaceBack(i, 0);
        continue;
      }
      for (auto j : IntegerRange(repeat.count.AsNumber())) {
        Unused << j;
        size_t trackSizesCount = repeat.track_sizes.Length();
        for (auto k : IntegerRange(trackSizesCount)) {
          mExpandedTracks.EmplaceBack(i, k);
        }
      }
    }
    if (MOZ_UNLIKELY(mExpandedTracks.Length() > kMaxLine - 1)) {
      mExpandedTracks.TruncateLength(kMaxLine - 1);
      if (mHasRepeatAuto && mRepeatAutoStart > kMaxLine - 1) {
        // The `repeat(auto-fill/fit)` track is outside the clamped grid.
        mHasRepeatAuto = false;
      }
    }
  }

  // Some style data references, for easy access.
  const GridTemplate& mTemplate;
  const Span<const TrackListValue> mTrackListValues;
  const StyleImplicitGridTracks& mAutoSizing;
  // An array from expanded track sizes (without expanding auto-repeat, which is
  // included just once at `mRepeatAutoStart`).
  //
  // Each entry contains two indices, the first into mTrackListValues, and a
  // second one inside mTrackListValues' repeat value, if any, or zero
  // otherwise.
  nsTArray<std::pair<size_t, size_t>> mExpandedTracks;
  // Offset from the start of the implicit grid to the first explicit track.
  uint32_t mExplicitGridOffset;
  // The index of the repeat(auto-fill/fit) track, or zero if there is none.
  // Relative to mExplicitGridOffset (repeat tracks are explicit by definition).
  uint32_t mRepeatAutoStart;
  // The (hypothetical) index of the last such repeat() track.
  uint32_t mRepeatAutoEnd;
  // True if there is a specified repeat(auto-fill/fit) track.
  bool mHasRepeatAuto;
  // True if this track (relative to mRepeatAutoStart) is a removed auto-fit.
  // Indexed relative to mExplicitGridOffset + mRepeatAutoStart.
  nsTArray<bool> mRemovedRepeatTracks;
};

/**
 * Utility class to find line names.  It provides an interface to lookup line
 * names with a dynamic number of repeat(auto-fill/fit) tracks taken into
 * account.
 */
class MOZ_STACK_CLASS nsGridContainerFrame::LineNameMap {
 public:
  /**
   * Create a LineNameMap.
   * @param aStylePosition the style for the grid container
   * @param aImplicitNamedAreas the implicit areas for the grid container
   * @param aGridTemplate is the grid-template-rows/columns data for this axis
   * @param aParentLineNameMap the parent grid's map parallel to this map, or
   *                           null if this map isn't for a subgrid
   * @param aRange the subgrid's range in the parent grid, or null
   * @param aIsSameDirection true if our axis progresses in the same direction
   *                              in the subgrid and parent
   */
  LineNameMap(const nsStylePosition* aStylePosition,
              const ImplicitNamedAreas* aImplicitNamedAreas,
              const TrackSizingFunctions& aTracks,
              const LineNameMap* aParentLineNameMap, const LineRange* aRange,
              bool aIsSameDirection)
      : mStylePosition(aStylePosition),
        mAreas(aImplicitNamedAreas),
        mRepeatAutoStart(aTracks.mRepeatAutoStart),
        mRepeatAutoEnd(aTracks.mRepeatAutoEnd),
        mRepeatEndDelta(aTracks.RepeatEndDelta()),
        mParentLineNameMap(aParentLineNameMap),
        mRange(aRange),
        mIsSameDirection(aIsSameDirection),
        mHasRepeatAuto(aTracks.mHasRepeatAuto) {
    if (MOZ_UNLIKELY(aRange)) {  // subgrid case
      mClampMinLine = 1;
      mClampMaxLine = 1 + aRange->Extent();
      MOZ_ASSERT(aTracks.mTemplate.IsSubgrid(), "Should be subgrid type");
      ExpandRepeatLineNamesForSubgrid(*aTracks.mTemplate.AsSubgrid());
      // we've expanded all subgrid auto-fill lines in
      // ExpandRepeatLineNamesForSubgrid()
      mRepeatAutoStart = 0;
      mRepeatAutoEnd = mRepeatAutoStart;
      mHasRepeatAuto = false;
    } else {
      mClampMinLine = kMinLine;
      mClampMaxLine = kMaxLine;
      if (mHasRepeatAuto) {
        mTrackAutoRepeatLineNames =
            aTracks.mTemplate.GetRepeatAutoValue()->line_names.AsSpan();
      }
      ExpandRepeatLineNames(aTracks);
    }
    if (mHasRepeatAuto) {
      // We need mTemplateLinesEnd to be after all line names.
      // mExpandedLineNames has one repetition of the repeat(auto-fit/fill)
      // track name lists already, so we must subtract the number of repeat
      // track name lists to get to the number of non-repeat tracks, minus 2
      // because the first and last line name lists are shared with the
      // preceding and following non-repeat line name lists. We then add
      // mRepeatEndDelta to include the interior line name lists from repeat
      // tracks.
      mTemplateLinesEnd = mExpandedLineNames.Length() -
                          (mTrackAutoRepeatLineNames.Length() - 2) +
                          mRepeatEndDelta;
    } else {
      mTemplateLinesEnd = mExpandedLineNames.Length();
    }
    MOZ_ASSERT(mHasRepeatAuto || mRepeatEndDelta <= 0);
    MOZ_ASSERT(!mHasRepeatAuto || aRange ||
               (mExpandedLineNames.Length() >= 2 &&
                mRepeatAutoStart <= mExpandedLineNames.Length()));
  }

  // Store line names into mExpandedLineNames with `repeat(INTEGER, ...)`
  // expanded for non-subgrid.
  void ExpandRepeatLineNames(const TrackSizingFunctions& aTracks) {
    auto lineNameLists = aTracks.mTemplate.LineNameLists(false);

    const auto& trackListValues = aTracks.mTrackListValues;
    const NameList* nameListToMerge = nullptr;
    // NOTE(emilio): We rely on std::move clearing out the array.
    SmallPointerArray<const NameList> names;
    const uint32_t end =
        std::min<uint32_t>(lineNameLists.Length(), mClampMaxLine + 1);
    for (uint32_t i = 0; i < end; ++i) {
      if (nameListToMerge) {
        names.AppendElement(nameListToMerge);
        nameListToMerge = nullptr;
      }
      names.AppendElement(&lineNameLists[i]);
      if (i >= trackListValues.Length()) {
        mExpandedLineNames.AppendElement(std::move(names));
        continue;
      }
      const auto& value = trackListValues[i];
      if (value.IsTrackSize()) {
        mExpandedLineNames.AppendElement(std::move(names));
        continue;
      }
      const auto& repeat = value.AsTrackRepeat();
      if (!repeat.count.IsNumber()) {
        const auto repeatNames = repeat.line_names.AsSpan();
        // If the repeat was truncated due to more than kMaxLine tracks, then
        // the repeat will no longer be set on mRepeatAutoStart).
        MOZ_ASSERT(!mHasRepeatAuto ||
                   mRepeatAutoStart == mExpandedLineNames.Length());
        MOZ_ASSERT(repeatNames.Length() >= 2);
        for (const auto j : IntegerRange(repeatNames.Length() - 1)) {
          names.AppendElement(&repeatNames[j]);
          mExpandedLineNames.AppendElement(std::move(names));
        }
        nameListToMerge = &repeatNames[repeatNames.Length() - 1];
        continue;
      }
      for (auto j : IntegerRange(repeat.count.AsNumber())) {
        Unused << j;
        if (nameListToMerge) {
          names.AppendElement(nameListToMerge);
          nameListToMerge = nullptr;
        }
        size_t trackSizesCount = repeat.track_sizes.Length();
        auto repeatLineNames = repeat.line_names.AsSpan();
        MOZ_ASSERT(repeatLineNames.Length() == trackSizesCount ||
                   repeatLineNames.Length() == trackSizesCount + 1);
        for (auto k : IntegerRange(trackSizesCount)) {
          names.AppendElement(&repeatLineNames[k]);
          mExpandedLineNames.AppendElement(std::move(names));
        }
        if (repeatLineNames.Length() == trackSizesCount + 1) {
          nameListToMerge = &repeatLineNames[trackSizesCount];
        }
      }
    }

    if (MOZ_UNLIKELY(mExpandedLineNames.Length() > uint32_t(mClampMaxLine))) {
      mExpandedLineNames.TruncateLength(mClampMaxLine);
    }
  }

  // Store line names into mExpandedLineNames with `repeat(INTEGER, ...)`
  // expanded, and all `repeat(...)` expanded for subgrid.
  // https://drafts.csswg.org/css-grid/#resolved-track-list-subgrid
  void ExpandRepeatLineNamesForSubgrid(
      const StyleGenericLineNameList<StyleInteger>& aStyleLineNameList) {
    const auto& lineNameList = aStyleLineNameList.line_names.AsSpan();
    const uint32_t maxCount = mClampMaxLine + 1;
    const uint32_t end = lineNameList.Length();
    for (uint32_t i = 0; i < end && mExpandedLineNames.Length() < maxCount;
         ++i) {
      const auto& item = lineNameList[i];
      if (item.IsLineNames()) {
        // <line-names> case. Just copy it.
        SmallPointerArray<const NameList> names;
        names.AppendElement(&item.AsLineNames());
        mExpandedLineNames.AppendElement(std::move(names));
        continue;
      }

      MOZ_ASSERT(item.IsRepeat());
      const auto& repeat = item.AsRepeat();
      const auto repeatLineNames = repeat.line_names.AsSpan();

      if (repeat.count.IsNumber()) {
        // Clone all <line-names>+ (repeated by N) into
        // |mExpandedLineNames|.
        for (uint32_t repeatCount = 0;
             repeatCount < (uint32_t)repeat.count.AsNumber(); ++repeatCount) {
          for (const NameList& lineNames : repeatLineNames) {
            SmallPointerArray<const NameList> names;
            names.AppendElement(&lineNames);
            mExpandedLineNames.AppendElement(std::move(names));
            if (mExpandedLineNames.Length() >= maxCount) {
              break;
            }
          }
        }
        continue;
      }

      MOZ_ASSERT(repeat.count.IsAutoFill(),
                 "RepeatCount of subgrid is number or auto-fill");

      const size_t fillLen = repeatLineNames.Length();
      const int32_t extraAutoFillLineCount =
          mClampMaxLine -
          (int32_t)aStyleLineNameList.expanded_line_names_length;
      // Maximum possible number of repeat name lists.
      // Note: |expanded_line_names_length| doesn't include auto repeat.
      const uint32_t possibleRepeatLength =
          std::max<int32_t>(0, extraAutoFillLineCount);
      const uint32_t repeatRemainder = possibleRepeatLength % fillLen;

      // Note: Expand 'auto-fill' names for subgrid for now since
      // HasNameAt() only deals with auto-repeat **tracks** currently.
      const size_t len = possibleRepeatLength - repeatRemainder;
      for (size_t j = 0; j < len; ++j) {
        SmallPointerArray<const NameList> names;
        names.AppendElement(&repeatLineNames[j % fillLen]);
        mExpandedLineNames.AppendElement(std::move(names));
        if (mExpandedLineNames.Length() >= maxCount) {
          break;
        }
      }
    }

    if (MOZ_UNLIKELY(mExpandedLineNames.Length() > uint32_t(mClampMaxLine))) {
      mExpandedLineNames.TruncateLength(mClampMaxLine);
    }
  }

  /**
   * Find the aNth occurrence of aName, searching forward if aNth is positive,
   * and in reverse if aNth is negative (aNth == 0 is invalid), starting from
   * aFromIndex (not inclusive), and return a 1-based line number.
   * Also take into account there is an unconditional match at the lines in
   * aImplicitLines.
   * Return zero if aNth occurrences can't be found.  In that case, aNth has
   * been decremented with the number of occurrences that were found (if any).
   *
   * E.g. to search for "A 2" forward from the start of the grid: aName is "A"
   * aNth is 2 and aFromIndex is zero.  To search for "A -2", aNth is -2 and
   * aFromIndex is ExplicitGridEnd + 1 (which is the line "before" the last
   * line when we're searching in reverse).  For "span A 2", aNth is 2 when
   * used on a grid-[row|column]-end property and -2 for a *-start property,
   * and aFromIndex is the line (which we should skip) on the opposite property.
   */
  uint32_t FindNamedLine(nsAtom* aName, int32_t* aNth, uint32_t aFromIndex,
                         const nsTArray<uint32_t>& aImplicitLines) const {
    MOZ_ASSERT(aName);
    MOZ_ASSERT(!aName->IsEmpty());
    MOZ_ASSERT(aNth && *aNth != 0);
    if (*aNth > 0) {
      return FindLine(aName, aNth, aFromIndex, aImplicitLines);
    }
    int32_t nth = -*aNth;
    int32_t line = RFindLine(aName, &nth, aFromIndex, aImplicitLines);
    *aNth = -nth;
    return line;
  }

  /**
   * Return a set of lines in aImplicitLines which matches the area name aName
   * on aSide.  For example, for aName "a" and aSide being an end side, it
   * returns the line numbers which would match "a-end" in the relevant axis.
   * For subgrids it includes searching the relevant axis in all ancestor
   * grids too (within this subgrid's spanned area).  If an ancestor has
   * opposite direction, we switch aSide to the opposite logical side so we
   * match on the same physical side as the original subgrid we're resolving
   * the name for.
   */
  void FindNamedAreas(nsAtom* aName, LogicalSide aSide,
                      nsTArray<uint32_t>& aImplicitLines) const {
    // True if we're currently in a map that has the same direction as 'this'.
    bool sameDirectionAsThis = true;
    uint32_t min = !mParentLineNameMap ? 1 : mClampMinLine;
    uint32_t max = mClampMaxLine;
    for (auto* map = this; true;) {
      uint32_t line = map->FindNamedArea(aName, aSide, min, max);
      if (line > 0) {
        if (MOZ_LIKELY(sameDirectionAsThis)) {
          line -= min - 1;
        } else {
          line = max - line + 1;
        }
        aImplicitLines.AppendElement(line);
      }
      auto* parent = map->mParentLineNameMap;
      if (!parent) {
        if (MOZ_UNLIKELY(aImplicitLines.Length() > 1)) {
          // Remove duplicates and sort in ascending order.
          aImplicitLines.Sort();
          for (size_t i = 0; i < aImplicitLines.Length(); ++i) {
            uint32_t prev = aImplicitLines[i];
            auto j = i + 1;
            const auto start = j;
            while (j < aImplicitLines.Length() && aImplicitLines[j] == prev) {
              ++j;
            }
            if (j != start) {
              aImplicitLines.RemoveElementsAt(start, j - start);
            }
          }
        }
        return;
      }
      if (MOZ_UNLIKELY(!map->mIsSameDirection)) {
        aSide = GetOppositeSide(aSide);
        sameDirectionAsThis = !sameDirectionAsThis;
      }
      min = map->TranslateToParentMap(min);
      max = map->TranslateToParentMap(max);
      if (min > max) {
        MOZ_ASSERT(!map->mIsSameDirection);
        std::swap(min, max);
      }
      map = parent;
    }
  }

  /**
   * Return true if any implicit named areas match aName, in this map or
   * in any of our ancestor maps.
   */
  bool HasImplicitNamedArea(nsAtom* aName) const {
    const auto* map = this;
    do {
      if (map->mAreas && map->mAreas->has(aName)) {
        return true;
      }
      map = map->mParentLineNameMap;
    } while (map);
    return false;
  }

  // For generating line name data for devtools.
  nsTArray<nsTArray<StyleCustomIdent>>
  GetResolvedLineNamesForComputedGridTrackInfo() const {
    nsTArray<nsTArray<StyleCustomIdent>> result;
    for (auto& expandedLine : mExpandedLineNames) {
      nsTArray<StyleCustomIdent> line;
      for (auto* chunk : expandedLine) {
        for (auto& name : chunk->AsSpan()) {
          line.AppendElement(name);
        }
      }
      result.AppendElement(std::move(line));
    }
    return result;
  }

  nsTArray<RefPtr<nsAtom>> GetExplicitLineNamesAtIndex(uint32_t aIndex) const {
    nsTArray<RefPtr<nsAtom>> lineNames;
    if (aIndex < mTemplateLinesEnd) {
      const auto nameLists = GetLineNamesAt(aIndex);
      for (const NameList* nameList : nameLists) {
        for (const auto& name : nameList->AsSpan()) {
          lineNames.AppendElement(name.AsAtom());
        }
      }
    }
    return lineNames;
  }

  const nsTArray<SmallPointerArray<const NameList>>& ExpandedLineNames() const {
    return mExpandedLineNames;
  }
  const Span<const StyleOwnedSlice<StyleCustomIdent>>&
  TrackAutoRepeatLineNames() const {
    return mTrackAutoRepeatLineNames;
  }
  bool HasRepeatAuto() const { return mHasRepeatAuto; }
  uint32_t NumRepeatTracks() const { return mRepeatAutoEnd - mRepeatAutoStart; }
  uint32_t RepeatAutoStart() const { return mRepeatAutoStart; }

  // The min/max line number (1-based) for clamping.
  int32_t mClampMinLine;
  int32_t mClampMaxLine;

 private:
  // Return true if this map represents a subgridded axis.
  bool IsSubgridded() const { return mParentLineNameMap != nullptr; }

  /**
   * @see FindNamedLine, this function searches forward.
   */
  uint32_t FindLine(nsAtom* aName, int32_t* aNth, uint32_t aFromIndex,
                    const nsTArray<uint32_t>& aImplicitLines) const {
    MOZ_ASSERT(aNth && *aNth > 0);
    int32_t nth = *aNth;
    // For a subgrid we need to search to the end of the grid rather than
    // the end of the local name list, since ancestors might match.
    const uint32_t end = IsSubgridded() ? mClampMaxLine : mTemplateLinesEnd;
    uint32_t line;
    uint32_t i = aFromIndex;
    for (; i < end; i = line) {
      line = i + 1;
      if (Contains(i, aName) || aImplicitLines.Contains(line)) {
        if (--nth == 0) {
          return line;
        }
      }
    }
    for (auto implicitLine : aImplicitLines) {
      if (implicitLine > i) {
        // implicitLine is after the lines we searched above so it's last.
        // (grid-template-areas has more tracks than
        // grid-template-[rows|columns])
        if (--nth == 0) {
          return implicitLine;
        }
      }
    }
    MOZ_ASSERT(nth > 0, "should have returned a valid line above already");
    *aNth = nth;
    return 0;
  }

  /**
   * @see FindNamedLine, this function searches in reverse.
   */
  uint32_t RFindLine(nsAtom* aName, int32_t* aNth, uint32_t aFromIndex,
                     const nsTArray<uint32_t>& aImplicitLines) const {
    MOZ_ASSERT(aNth && *aNth > 0);
    if (MOZ_UNLIKELY(aFromIndex == 0)) {
      return 0;  // There are no named lines beyond the start of the explicit
                 // grid.
    }
    --aFromIndex;  // (shift aFromIndex so we can treat it as inclusive)
    int32_t nth = *aNth;
    // Implicit lines may be beyond the explicit grid so we match those
    // first if it's within the mTemplateLinesEnd..aFromIndex range.
    // aImplicitLines is presumed sorted.
    // For a subgrid we need to search to the end of the grid rather than
    // the end of the local name list, since ancestors might match.
    const uint32_t end = IsSubgridded() ? mClampMaxLine : mTemplateLinesEnd;
    for (auto implicitLine : Reversed(aImplicitLines)) {
      if (implicitLine <= end) {
        break;
      }
      if (implicitLine < aFromIndex) {
        if (--nth == 0) {
          return implicitLine;
        }
      }
    }
    for (uint32_t i = std::min(aFromIndex, end); i; --i) {
      if (Contains(i - 1, aName) || aImplicitLines.Contains(i)) {
        if (--nth == 0) {
          return i;
        }
      }
    }
    MOZ_ASSERT(nth > 0, "should have returned a valid line above already");
    *aNth = nth;
    return 0;
  }

  // Return true if aName exists at aIndex in this map or any parent map.
  bool Contains(uint32_t aIndex, nsAtom* aName) const {
    const auto* map = this;
    while (true) {
      if (aIndex < map->mTemplateLinesEnd && map->HasNameAt(aIndex, aName)) {
        return true;
      }
      auto* parent = map->mParentLineNameMap;
      if (!parent) {
        return false;
      }
      uint32_t line = map->TranslateToParentMap(aIndex + 1);
      MOZ_ASSERT(line >= 1, "expected a 1-based line number");
      aIndex = line - 1;
      map = parent;
    }
    MOZ_ASSERT_UNREACHABLE("we always return from inside the loop above");
  }

  static bool Contains(Span<const StyleCustomIdent> aNames, nsAtom* aName) {
    for (auto& name : aNames) {
      if (name.AsAtom() == aName) {
        return true;
      }
    }
    return false;
  }

  // Return true if aName exists at aIndex in this map.
  bool HasNameAt(const uint32_t aIndex, nsAtom* const aName) const {
    const auto nameLists = GetLineNamesAt(aIndex);
    for (const NameList* nameList : nameLists) {
      if (Contains(nameList->AsSpan(), aName)) {
        return true;
      }
    }
    return false;
  }

  // Get the line names at an index.
  // This accounts for auto repeat. The results may be spread over multiple name
  // lists returned in the array, which is done to avoid unneccessarily copying
  // the arrays to concatenate them.
  SmallPointerArray<const NameList> GetLineNamesAt(
      const uint32_t aIndex) const {
    SmallPointerArray<const NameList> names;
    // The index into mExpandedLineNames to use, if aIndex doesn't point to a
    // name inside of a auto repeat.
    uint32_t repeatAdjustedIndex = aIndex;
    // Note: For subgrid, |mHasRepeatAuto| is always false because we have
    // expanded it in the constructor of LineNameMap.
    if (mHasRepeatAuto) {
      // If the index is inside of the auto repeat, use the repeat line
      // names. Otherwise, if the index is past the end of the repeat it must
      // be adjusted to acount for the repeat tracks.
      // mExpandedLineNames has the first and last line name lists from the
      // repeat in it already, so we can just ignore aIndex == mRepeatAutoStart
      // and treat when aIndex == mRepeatAutoEnd the same as any line after the
      // the repeat.
      const uint32_t maxRepeatLine = mTrackAutoRepeatLineNames.Length() - 1;
      if (aIndex > mRepeatAutoStart && aIndex < mRepeatAutoEnd) {
        // The index is inside the auto repeat. Calculate the lines to use,
        // including the previous repetitions final names when we roll over
        // from one repetition to the next.
        const uint32_t repeatIndex =
            (aIndex - mRepeatAutoStart) % maxRepeatLine;
        if (repeatIndex == 0) {
          // The index is at the start of a new repetition. The start of the
          // first repetition is intentionally ignored above, so this will
          // consider both the end of the previous repetition and the start
          // the one that contains aIndex.
          names.AppendElement(&mTrackAutoRepeatLineNames[maxRepeatLine]);
        }
        names.AppendElement(&mTrackAutoRepeatLineNames[repeatIndex]);
        return names;
      }
      if (aIndex != mRepeatAutoStart && aIndex >= mRepeatAutoEnd) {
        // Adjust the index to account for the line names of the repeat.
        repeatAdjustedIndex -= mRepeatEndDelta;
        repeatAdjustedIndex += mTrackAutoRepeatLineNames.Length() - 2;
      }
    }
    MOZ_ASSERT(repeatAdjustedIndex < mExpandedLineNames.Length(),
               "Incorrect repeatedAdjustedIndex");
    MOZ_ASSERT(names.IsEmpty());
    // The index is not inside the repeat tracks, or no repeat tracks exist.
    const auto& nameLists = mExpandedLineNames[repeatAdjustedIndex];
    for (const NameList* nameList : nameLists) {
      names.AppendElement(nameList);
    }
    return names;
  }

  // Translate a subgrid line (1-based) to a parent line (1-based).
  uint32_t TranslateToParentMap(uint32_t aLine) const {
    if (MOZ_LIKELY(mIsSameDirection)) {
      return aLine + mRange->mStart;
    }
    MOZ_ASSERT(mRange->mEnd + 1 >= aLine);
    return mRange->mEnd - (aLine - 1) + 1;
  }

  /**
   * Return the 1-based line that match aName in 'grid-template-areas'
   * on the side aSide.  Clamp the result to aMin..aMax but require
   * that some part of the area is inside for it to match.
   * Return zero if there is no match.
   */
  uint32_t FindNamedArea(nsAtom* aName, LogicalSide aSide, int32_t aMin,
                         int32_t aMax) const {
    if (const NamedArea* area = FindNamedArea(aName)) {
      int32_t start = IsBlock(aSide) ? area->rows.start : area->columns.start;
      int32_t end = IsBlock(aSide) ? area->rows.end : area->columns.end;
      if (IsStart(aSide)) {
        if (start >= aMin) {
          if (start <= aMax) {
            return start;
          }
        } else if (end >= aMin) {
          return aMin;
        }
      } else {
        if (end <= aMax) {
          if (end >= aMin) {
            return end;
          }
        } else if (start <= aMax) {
          return aMax;
        }
      }
    }
    return 0;  // no match
  }

  /**
   * A convenience method to lookup a name in 'grid-template-areas'.
   * @return null if not found
   */
  const NamedArea* FindNamedArea(nsAtom* aName) const {
    if (mStylePosition->mGridTemplateAreas.IsNone()) {
      return nullptr;
    }
    const auto areas = mStylePosition->mGridTemplateAreas.AsAreas();
    for (const NamedArea& area : areas->areas.AsSpan()) {
      if (area.name.AsAtom() == aName) {
        return &area;
      }
    }
    return nullptr;
  }

  // Some style data references, for easy access.
  const nsStylePosition* mStylePosition;
  const ImplicitNamedAreas* mAreas;
  // The expanded list of line-names. Each entry is usually a single NameList,
  // but can be multiple in the case where repeat() expands to something that
  // has a line name list at the end.
  nsTArray<SmallPointerArray<const NameList>> mExpandedLineNames;
  // The repeat(auto-fill/fit) track value, if any. (always empty for subgrid)
  Span<const StyleOwnedSlice<StyleCustomIdent>> mTrackAutoRepeatLineNames;
  // The index of the repeat(auto-fill/fit) track, or zero if there is none.
  uint32_t mRepeatAutoStart;
  // The index one past the end of the repeat(auto-fill/fit) tracks. Equal to
  // mRepeatAutoStart if there are no repeat(auto-fill/fit) tracks.
  uint32_t mRepeatAutoEnd;
  // The total number of repeat tracks minus 1.
  int32_t mRepeatEndDelta;
  // The end of the line name lists with repeat(auto-fill/fit) tracks accounted
  // for.
  uint32_t mTemplateLinesEnd;

  // The parent line map, or null if this map isn't for a subgrid.
  const LineNameMap* mParentLineNameMap;
  // The subgrid's range, or null if this map isn't for a subgrid.
  const LineRange* mRange;
  // True if the subgrid/parent axes progresses in the same direction.
  const bool mIsSameDirection;

  // True if there is a specified repeat(auto-fill/fit) track.
  bool mHasRepeatAuto;
};

/**
 * State for the tracks in one dimension.
 */
struct nsGridContainerFrame::Tracks {
  explicit Tracks(LogicalAxis aAxis)
      : mContentBoxSize(NS_UNCONSTRAINEDSIZE),
        mGridGap(NS_UNCONSTRAINEDSIZE),
        mStateUnion(TrackSize::StateBits{0}),
        mAxis(aAxis),
        mCanResolveLineRangeSize(false),
        mIsMasonry(false) {
    mBaselineSubtreeAlign[BaselineSharingGroup::First] = StyleAlignFlags::AUTO;
    mBaselineSubtreeAlign[BaselineSharingGroup::Last] = StyleAlignFlags::AUTO;
    mBaseline[BaselineSharingGroup::First] = NS_INTRINSIC_ISIZE_UNKNOWN;
    mBaseline[BaselineSharingGroup::Last] = NS_INTRINSIC_ISIZE_UNKNOWN;
  }

  void Initialize(const TrackSizingFunctions& aFunctions,
                  const NonNegativeLengthPercentageOrNormal& aGridGap,
                  uint32_t aNumTracks, nscoord aContentBoxSize);

  /**
   * Return the union of the state bits for the tracks in aRange.
   */
  TrackSize::StateBits StateBitsForRange(const LineRange& aRange) const;

  // Some data we collect for aligning baseline-aligned items.
  struct ItemBaselineData {
    uint32_t mBaselineTrack;
    nscoord mBaseline;
    nscoord mSize;
    GridItemInfo* mGridItem;
    static bool IsBaselineTrackLessThan(const ItemBaselineData& a,
                                        const ItemBaselineData& b) {
      return a.mBaselineTrack < b.mBaselineTrack;
    }
  };

  /**
   * Calculate baseline offsets for the given set of items.
   * Helper for InitialzeItemBaselines.
   */
  void CalculateItemBaselines(nsTArray<ItemBaselineData>& aBaselineItems,
                              BaselineSharingGroup aBaselineGroup);

  /**
   * Initialize grid item baseline state and offsets.
   */
  void InitializeItemBaselines(GridReflowInput& aState,
                               nsTArray<GridItemInfo>& aGridItems);

  /**
   * A masonry axis has four baseline alignment sets and each set can have
   * a first- and last-baseline alignment group, for a total of eight possible
   * baseline alignment groups, as follows:
   *   set 1: the first item in each `start` or `stretch` grid track
   *   set 2: the last item in each `start` grid track
   *   set 3: the last item in each `end` or `stretch` grid track
   *   set 4: the first item in each `end` grid track
   * (`start`/`end`/`stretch` refers to the relevant `align/justify-tracks`
   * value of the (grid-axis) start track for the item) Baseline-alignment for
   * set 1 and 2 always adjusts the item's padding or margin on the start side,
   * and set 3 and 4 on the end side, for both first- and last-baseline groups
   * in the set. (This is similar to regular grid which always adjusts
   * first-baseline groups on the start side and last-baseline groups on the
   * end-side.  The crux is that those groups are always aligned to the track's
   * start/end side respectively.)
   */
  struct BaselineAlignmentSet {
    bool MatchTrackAlignment(StyleAlignFlags aTrackAlignment) const {
      if (mTrackAlignmentSet == BaselineAlignmentSet::StartStretch) {
        return aTrackAlignment == StyleAlignFlags::START ||
               (aTrackAlignment == StyleAlignFlags::STRETCH &&
                mItemSet == BaselineAlignmentSet::FirstItems);
      }
      return aTrackAlignment == StyleAlignFlags::END ||
             (aTrackAlignment == StyleAlignFlags::STRETCH &&
              mItemSet == BaselineAlignmentSet::LastItems);
    }

    enum ItemSet { FirstItems, LastItems };
    ItemSet mItemSet = FirstItems;
    enum TrackAlignmentSet { StartStretch, EndStretch };
    TrackAlignmentSet mTrackAlignmentSet = StartStretch;
  };
  void InitializeItemBaselinesInMasonryAxis(
      GridReflowInput& aState, nsTArray<GridItemInfo>& aGridItems,
      BaselineAlignmentSet aSet, const nsSize& aContainerSize,
      nsTArray<nscoord>& aTrackSizes,
      nsTArray<ItemBaselineData>& aFirstBaselineItems,
      nsTArray<ItemBaselineData>& aLastBaselineItems);

  /**
   * Apply the additional alignment needed to align the baseline-aligned subtree
   * the item belongs to within its baseline track.
   */
  void AlignBaselineSubtree(const GridItemInfo& aGridItem) const;

  enum class TrackSizingPhase {
    IntrinsicMinimums,
    ContentBasedMinimums,
    MaxContentMinimums,
    IntrinsicMaximums,
    MaxContentMaximums,
  };

  // Some data we collect on each item that spans more than one track for step 3
  // and 4 of the Track Sizing Algorithm in ResolveIntrinsicSize below.
  // https://w3c.github.io/csswg-drafts/css-grid-1/#algo-spanning-items
  struct SpanningItemData final {
    uint32_t mSpan;
    TrackSize::StateBits mState;
    LineRange mLineRange;
    nscoord mMinSize;
    nscoord mMinContentContribution;
    nscoord mMaxContentContribution;
    nsIFrame* mFrame;

    static bool IsSpanLessThan(const SpanningItemData& a,
                               const SpanningItemData& b) {
      return a.mSpan < b.mSpan;
    }

    template <TrackSizingPhase phase>
    nscoord SizeContributionForPhase() const {
      switch (phase) {
        case TrackSizingPhase::IntrinsicMinimums:
          return mMinSize;
        case TrackSizingPhase::ContentBasedMinimums:
        case TrackSizingPhase::IntrinsicMaximums:
          return mMinContentContribution;
        case TrackSizingPhase::MaxContentMinimums:
        case TrackSizingPhase::MaxContentMaximums:
          return mMaxContentContribution;
      }
      MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE("Unexpected phase");
    }

#ifdef DEBUG
    void Dump() const {
      printf(
          "SpanningItemData { mSpan: %d, mState: %d, mLineRange: (%d, %d), "
          "mMinSize: %d, mMinContentContribution: %d, mMaxContentContribution: "
          "%d, mFrame: %p\n",
          mSpan, mState, mLineRange.mStart, mLineRange.mEnd, mMinSize,
          mMinContentContribution, mMaxContentContribution, mFrame);
    }
#endif
  };

  using FitContentClamper =
      std::function<bool(uint32_t aTrack, nscoord aMinSize, nscoord* aSize)>;

  // Helper method for ResolveIntrinsicSize.
  template <TrackSizingPhase phase>
  bool GrowSizeForSpanningItems(
      nsTArray<SpanningItemData>::iterator aIter,
      nsTArray<SpanningItemData>::iterator aIterEnd,
      nsTArray<uint32_t>& aTracks, nsTArray<TrackSize>& aPlan,
      nsTArray<TrackSize>& aItemPlan, TrackSize::StateBits aSelector,
      const FitContentClamper& aFitContentClamper = nullptr,
      bool aNeedInfinitelyGrowableFlag = false);
  /**
   * Resolve Intrinsic Track Sizes.
   * http://dev.w3.org/csswg/css-grid/#algo-content
   */
  void ResolveIntrinsicSize(GridReflowInput& aState,
                            nsTArray<GridItemInfo>& aGridItems,
                            const TrackSizingFunctions& aFunctions,
                            LineRange GridArea::*aRange,
                            nscoord aPercentageBasis,
                            SizingConstraint aConstraint);

  /**
   * Helper for ResolveIntrinsicSize.  It implements step 1 "size tracks to fit
   * non-spanning items" in the spec.  Return true if the track has a <flex>
   * max-sizing function, false otherwise.
   */
  bool ResolveIntrinsicSizeForNonSpanningItems(
      GridReflowInput& aState, const TrackSizingFunctions& aFunctions,
      nscoord aPercentageBasis, SizingConstraint aConstraint,
      const LineRange& aRange, const GridItemInfo& aGridItem);

  // Helper method that returns the track size to use in §11.5.1.2
  // https://drafts.csswg.org/css-grid/#extra-space
  template <TrackSizingPhase phase>
  static nscoord StartSizeInDistribution(const TrackSize& aSize) {
    switch (phase) {
      case TrackSizingPhase::IntrinsicMinimums:
      case TrackSizingPhase::ContentBasedMinimums:
      case TrackSizingPhase::MaxContentMinimums:
        return aSize.mBase;
      case TrackSizingPhase::IntrinsicMaximums:
      case TrackSizingPhase::MaxContentMaximums:
        if (aSize.mLimit == NS_UNCONSTRAINEDSIZE) {
          return aSize.mBase;
        }
        return aSize.mLimit;
    }
    MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE("Unexpected phase");
  }

  /**
   * Collect the tracks which are growable (matching aSelector) into
   * aGrowableTracks, and return the amount of space that can be used
   * to grow those tracks.  This method implements CSS Grid §11.5.1.2.
   * https://drafts.csswg.org/css-grid/#extra-space
   */
  template <TrackSizingPhase phase>
  nscoord CollectGrowable(nscoord aAvailableSpace, const LineRange& aRange,
                          TrackSize::StateBits aSelector,
                          nsTArray<uint32_t>& aGrowableTracks) const {
    MOZ_ASSERT(aAvailableSpace > 0, "why call me?");
    nscoord space = aAvailableSpace - mGridGap * (aRange.Extent() - 1);
    for (auto i : aRange.Range()) {
      const TrackSize& sz = mSizes[i];
      space -= StartSizeInDistribution<phase>(sz);
      if (space <= 0) {
        return 0;
      }
      if (sz.mState & aSelector) {
        aGrowableTracks.AppendElement(i);
      }
    }
    return aGrowableTracks.IsEmpty() ? 0 : space;
  }

  template <TrackSizingPhase phase>
  void InitializeItemPlan(nsTArray<TrackSize>& aItemPlan,
                          const nsTArray<uint32_t>& aTracks) const {
    for (uint32_t track : aTracks) {
      auto& plan = aItemPlan[track];
      const TrackSize& sz = mSizes[track];
      plan.mBase = StartSizeInDistribution<phase>(sz);
      bool unlimited = sz.mState & TrackSize::eInfinitelyGrowable;
      plan.mLimit = unlimited ? NS_UNCONSTRAINEDSIZE : sz.mLimit;
      plan.mState = sz.mState;
    }
  }

  template <TrackSizingPhase phase>
  void InitializePlan(nsTArray<TrackSize>& aPlan) const {
    for (size_t i = 0, len = aPlan.Length(); i < len; ++i) {
      auto& plan = aPlan[i];
      const auto& sz = mSizes[i];
      plan.mBase = StartSizeInDistribution<phase>(sz);
      MOZ_ASSERT(phase == TrackSizingPhase::MaxContentMaximums ||
                     !(sz.mState & TrackSize::eInfinitelyGrowable),
                 "forgot to reset the eInfinitelyGrowable bit?");
      plan.mState = sz.mState;
    }
  }

  template <TrackSizingPhase phase>
  void CopyPlanToSize(const nsTArray<TrackSize>& aPlan,
                      bool aNeedInfinitelyGrowableFlag = false) {
    for (size_t i = 0, len = mSizes.Length(); i < len; ++i) {
      const auto& plan = aPlan[i];
      MOZ_ASSERT(plan.mBase >= 0);
      auto& sz = mSizes[i];
      switch (phase) {
        case TrackSizingPhase::IntrinsicMinimums:
        case TrackSizingPhase::ContentBasedMinimums:
        case TrackSizingPhase::MaxContentMinimums:
          sz.mBase = plan.mBase;
          break;
        case TrackSizingPhase::IntrinsicMaximums:
          if (plan.mState & TrackSize::eModified) {
            if (sz.mLimit == NS_UNCONSTRAINEDSIZE &&
                aNeedInfinitelyGrowableFlag) {
              sz.mState |= TrackSize::eInfinitelyGrowable;
            }
            sz.mLimit = plan.mBase;
          }
          break;
        case TrackSizingPhase::MaxContentMaximums:
          if (plan.mState & TrackSize::eModified) {
            sz.mLimit = plan.mBase;
          }
          sz.mState &= ~TrackSize::eInfinitelyGrowable;
          break;
      }
    }
  }

  /**
   * Grow the planned size for tracks in aGrowableTracks up to their limit
   * and then freeze them (all aGrowableTracks must be unfrozen on entry).
   * Subtract the space added from aAvailableSpace and return that.
   */
  nscoord GrowTracksToLimit(nscoord aAvailableSpace, nsTArray<TrackSize>& aPlan,
                            const nsTArray<uint32_t>& aGrowableTracks,
                            const FitContentClamper& aFitContentClamper) const {
    MOZ_ASSERT(aAvailableSpace > 0 && aGrowableTracks.Length() > 0);
    nscoord space = aAvailableSpace;
    uint32_t numGrowable = aGrowableTracks.Length();
    while (true) {
      nscoord spacePerTrack = std::max<nscoord>(space / numGrowable, 1);
      for (uint32_t track : aGrowableTracks) {
        TrackSize& sz = aPlan[track];
        if (sz.IsFrozen()) {
          continue;
        }
        nscoord newBase = sz.mBase + spacePerTrack;
        nscoord limit = sz.mLimit;
        if (MOZ_UNLIKELY((sz.mState & TrackSize::eFitContent) &&
                         aFitContentClamper)) {
          // Clamp the limit to the fit-content() size, for §12.5.2 step 5/6.
          aFitContentClamper(track, sz.mBase, &limit);
        }
        if (newBase > limit) {
          nscoord consumed = limit - sz.mBase;
          if (consumed > 0) {
            space -= consumed;
            sz.mBase = limit;
          }
          sz.mState |= TrackSize::eFrozen;
          if (--numGrowable == 0) {
            return space;
          }
        } else {
          sz.mBase = newBase;
          space -= spacePerTrack;
        }
        MOZ_ASSERT(space >= 0);
        if (space == 0) {
          return 0;
        }
      }
    }
    MOZ_ASSERT_UNREACHABLE("we don't exit the loop above except by return");
    return 0;
  }

  /**
   * Helper for GrowSelectedTracksUnlimited.  For the set of tracks (S) that
   * match aMinSizingSelector: if a track in S doesn't match aMaxSizingSelector
   * then mark it with aSkipFlag.  If all tracks in S were marked then unmark
   * them.  Return aNumGrowable minus the number of tracks marked.  It is
   * assumed that aPlan have no aSkipFlag set for tracks in aGrowableTracks
   * on entry to this method.
   */
  static uint32_t MarkExcludedTracks(nsTArray<TrackSize>& aPlan,
                                     uint32_t aNumGrowable,
                                     const nsTArray<uint32_t>& aGrowableTracks,
                                     TrackSize::StateBits aMinSizingSelector,
                                     TrackSize::StateBits aMaxSizingSelector,
                                     TrackSize::StateBits aSkipFlag) {
    bool foundOneSelected = false;
    bool foundOneGrowable = false;
    uint32_t numGrowable = aNumGrowable;
    for (uint32_t track : aGrowableTracks) {
      TrackSize& sz = aPlan[track];
      const auto state = sz.mState;
      if (state & aMinSizingSelector) {
        foundOneSelected = true;
        if (state & aMaxSizingSelector) {
          foundOneGrowable = true;
          continue;
        }
        sz.mState |= aSkipFlag;
        MOZ_ASSERT(numGrowable != 0);
        --numGrowable;
      }
    }
    // 12.5 "if there are no such tracks, then all affected tracks"
    if (foundOneSelected && !foundOneGrowable) {
      for (uint32_t track : aGrowableTracks) {
        aPlan[track].mState &= ~aSkipFlag;
      }
      numGrowable = aNumGrowable;
    }
    return numGrowable;
  }

  /**
   * Mark all tracks in aGrowableTracks with an eSkipGrowUnlimited bit if
   * they *shouldn't* grow unlimited in §11.5.1.2.3 "Distribute space beyond
   * growth limits" https://drafts.csswg.org/css-grid/#extra-space
   * Return the number of tracks that are still growable.
   */
  template <TrackSizingPhase phase>
  static uint32_t MarkExcludedTracks(nsTArray<TrackSize>& aPlan,
                                     const nsTArray<uint32_t>& aGrowableTracks,
                                     TrackSize::StateBits aSelector) {
    uint32_t numGrowable = aGrowableTracks.Length();
    if (phase == TrackSizingPhase::IntrinsicMaximums ||
        phase == TrackSizingPhase::MaxContentMaximums) {
      // "when handling any intrinsic growth limit: all affected tracks"
      return numGrowable;
    }
    MOZ_ASSERT(aSelector == (aSelector & TrackSize::eIntrinsicMinSizing) &&
                   (aSelector & TrackSize::eMaxContentMinSizing),
               "Should only get here for track sizing steps 2.1 to 2.3");
    // Note that eMaxContentMinSizing is always included. We do those first:
    numGrowable = MarkExcludedTracks(
        aPlan, numGrowable, aGrowableTracks, TrackSize::eMaxContentMinSizing,
        TrackSize::eMaxContentMaxSizing, TrackSize::eSkipGrowUnlimited1);
    // Now mark min-content/auto min-sizing tracks if requested.
    auto minOrAutoSelector = aSelector & ~TrackSize::eMaxContentMinSizing;
    if (minOrAutoSelector) {
      numGrowable = MarkExcludedTracks(
          aPlan, numGrowable, aGrowableTracks, minOrAutoSelector,
          TrackSize::eIntrinsicMaxSizing, TrackSize::eSkipGrowUnlimited2);
    }
    return numGrowable;
  }

  /**
   * Increase the planned size for tracks in aGrowableTracks that aren't
   * marked with a eSkipGrowUnlimited flag beyond their limit.
   * This implements the "Distribute space beyond growth limits" step in
   * https://drafts.csswg.org/css-grid/#distribute-extra-space
   */
  void GrowSelectedTracksUnlimited(
      nscoord aAvailableSpace, nsTArray<TrackSize>& aPlan,
      const nsTArray<uint32_t>& aGrowableTracks, uint32_t aNumGrowable,
      const FitContentClamper& aFitContentClamper) const {
    MOZ_ASSERT(aAvailableSpace > 0 && aGrowableTracks.Length() > 0 &&
               aNumGrowable <= aGrowableTracks.Length());
    nscoord space = aAvailableSpace;
    DebugOnly<bool> didClamp = false;
    while (aNumGrowable) {
      nscoord spacePerTrack = std::max<nscoord>(space / aNumGrowable, 1);
      for (uint32_t track : aGrowableTracks) {
        TrackSize& sz = aPlan[track];
        if (sz.mState & TrackSize::eSkipGrowUnlimited) {
          continue;  // an excluded track
        }
        nscoord delta = spacePerTrack;
        nscoord newBase = sz.mBase + delta;
        if (MOZ_UNLIKELY((sz.mState & TrackSize::eFitContent) &&
                         aFitContentClamper)) {
          // Clamp newBase to the fit-content() size, for §12.5.2 step 5/6.
          if (aFitContentClamper(track, sz.mBase, &newBase)) {
            didClamp = true;
            delta = newBase - sz.mBase;
            MOZ_ASSERT(delta >= 0, "track size shouldn't shrink");
            sz.mState |= TrackSize::eSkipGrowUnlimited1;
            --aNumGrowable;
          }
        }
        sz.mBase = newBase;
        space -= delta;
        MOZ_ASSERT(space >= 0);
        if (space == 0) {
          return;
        }
      }
    }
    MOZ_ASSERT(didClamp,
               "we don't exit the loop above except by return, "
               "unless we clamped some track's size");
  }

  /**
   * Distribute aAvailableSpace to the planned base size for aGrowableTracks
   * up to their limits, then distribute the remaining space beyond the limits.
   */
  template <TrackSizingPhase phase>
  void DistributeToTrackSizes(nscoord aAvailableSpace,
                              nsTArray<TrackSize>& aPlan,
                              nsTArray<TrackSize>& aItemPlan,
                              nsTArray<uint32_t>& aGrowableTracks,
                              TrackSize::StateBits aSelector,
                              const FitContentClamper& aFitContentClamper) {
    InitializeItemPlan<phase>(aItemPlan, aGrowableTracks);
    nscoord space = GrowTracksToLimit(aAvailableSpace, aItemPlan,
                                      aGrowableTracks, aFitContentClamper);
    if (space > 0) {
      uint32_t numGrowable =
          MarkExcludedTracks<phase>(aItemPlan, aGrowableTracks, aSelector);
      GrowSelectedTracksUnlimited(space, aItemPlan, aGrowableTracks,
                                  numGrowable, aFitContentClamper);
    }
    for (uint32_t track : aGrowableTracks) {
      nscoord& plannedSize = aPlan[track].mBase;
      nscoord itemIncurredSize = aItemPlan[track].mBase;
      if (plannedSize < itemIncurredSize) {
        plannedSize = itemIncurredSize;
      }
    }
  }

  /**
   * Distribute aAvailableSize to the tracks.  This implements 12.6 at:
   * http://dev.w3.org/csswg/css-grid/#algo-grow-tracks
   */
  void DistributeFreeSpace(nscoord aAvailableSize) {
    const uint32_t numTracks = mSizes.Length();
    if (MOZ_UNLIKELY(numTracks == 0 || aAvailableSize <= 0)) {
      return;
    }
    if (aAvailableSize == NS_UNCONSTRAINEDSIZE) {
      for (TrackSize& sz : mSizes) {
        sz.mBase = sz.mLimit;
      }
    } else {
      // Compute free space and count growable tracks.
      nscoord space = aAvailableSize;
      uint32_t numGrowable = numTracks;
      for (const TrackSize& sz : mSizes) {
        space -= sz.mBase;
        MOZ_ASSERT(sz.mBase <= sz.mLimit);
        if (sz.mBase == sz.mLimit) {
          --numGrowable;
        }
      }
      // Distribute the free space evenly to the growable tracks. If not exactly
      // divisable the remainder is added to the leading tracks.
      while (space > 0 && numGrowable) {
        nscoord spacePerTrack = std::max<nscoord>(space / numGrowable, 1);
        for (uint32_t i = 0; i < numTracks && space > 0; ++i) {
          TrackSize& sz = mSizes[i];
          if (sz.mBase == sz.mLimit) {
            continue;
          }
          nscoord newBase = sz.mBase + spacePerTrack;
          if (newBase >= sz.mLimit) {
            space -= sz.mLimit - sz.mBase;
            sz.mBase = sz.mLimit;
            --numGrowable;
          } else {
            space -= spacePerTrack;
            sz.mBase = newBase;
          }
        }
      }
    }
  }

  /**
   * Implements "12.7.1. Find the Size of an 'fr'".
   * http://dev.w3.org/csswg/css-grid/#algo-find-fr-size
   * (The returned value is a 'nscoord' divided by a factor - a floating type
   * is used to avoid intermediary rounding errors.)
   */
  float FindFrUnitSize(const LineRange& aRange,
                       const nsTArray<uint32_t>& aFlexTracks,
                       const TrackSizingFunctions& aFunctions,
                       nscoord aSpaceToFill) const;

  /**
   * Implements the "find the used flex fraction" part of StretchFlexibleTracks.
   * (The returned value is a 'nscoord' divided by a factor - a floating type
   * is used to avoid intermediary rounding errors.)
   */
  float FindUsedFlexFraction(GridReflowInput& aState,
                             nsTArray<GridItemInfo>& aGridItems,
                             const nsTArray<uint32_t>& aFlexTracks,
                             const TrackSizingFunctions& aFunctions,
                             nscoord aAvailableSize) const;

  /**
   * Implements "12.7. Stretch Flexible Tracks"
   * http://dev.w3.org/csswg/css-grid/#algo-flex-tracks
   */
  void StretchFlexibleTracks(GridReflowInput& aState,
                             nsTArray<GridItemInfo>& aGridItems,
                             const TrackSizingFunctions& aFunctions,
                             nscoord aAvailableSize);

  /**
   * Implements "12.3. Track Sizing Algorithm"
   * http://dev.w3.org/csswg/css-grid/#algo-track-sizing
   */
  void CalculateSizes(GridReflowInput& aState,
                      nsTArray<GridItemInfo>& aGridItems,
                      const TrackSizingFunctions& aFunctions,
                      nscoord aContentBoxSize, LineRange GridArea::*aRange,
                      SizingConstraint aConstraint);

  /**
   * Apply 'align/justify-content', whichever is relevant for this axis.
   * https://drafts.csswg.org/css-align-3/#propdef-align-content
   */
  void AlignJustifyContent(const nsStylePosition* aStyle,
                           StyleContentDistribution aAligmentStyleValue,
                           WritingMode aWM, nscoord aContentBoxSize,
                           bool aIsSubgridded);

  nscoord GridLineEdge(uint32_t aLine, GridLineSide aSide) const {
    if (MOZ_UNLIKELY(mSizes.IsEmpty())) {
      // https://drafts.csswg.org/css-grid/#grid-definition
      // "... the explicit grid still contains one grid line in each axis."
      MOZ_ASSERT(aLine == 0, "We should only resolve line 1 in an empty grid");
      return nscoord(0);
    }
    MOZ_ASSERT(aLine <= mSizes.Length(), "mSizes is too small");
    if (aSide == GridLineSide::BeforeGridGap) {
      if (aLine == 0) {
        return nscoord(0);
      }
      const TrackSize& sz = mSizes[aLine - 1];
      return sz.mPosition + sz.mBase;
    }
    if (aLine == mSizes.Length()) {
      return mContentBoxSize;
    }
    return mSizes[aLine].mPosition;
  }

  nscoord SumOfGridTracksAndGaps() {
    return SumOfGridTracks() + SumOfGridGaps();
  }

  nscoord SumOfGridTracks() const {
    nscoord result = 0;
    for (const TrackSize& size : mSizes) {
      result += size.mBase;
    }
    return result;
  }

  nscoord SumOfGridGaps() const {
    auto len = mSizes.Length();
    return MOZ_LIKELY(len > 1) ? (len - 1) * mGridGap : 0;
  }

  /**
   * Break before aRow, i.e. set the eBreakBefore flag on aRow and set the grid
   * gap before aRow to zero (and shift all rows after it by the removed gap).
   */
  void BreakBeforeRow(uint32_t aRow) {
    MOZ_ASSERT(mAxis == eLogicalAxisBlock,
               "Should only be fragmenting in the block axis (between rows)");
    nscoord prevRowEndPos = 0;
    if (aRow != 0) {
      auto& prevSz = mSizes[aRow - 1];
      prevRowEndPos = prevSz.mPosition + prevSz.mBase;
    }
    auto& sz = mSizes[aRow];
    const nscoord gap = sz.mPosition - prevRowEndPos;
    sz.mState |= TrackSize::eBreakBefore;
    if (gap != 0) {
      for (uint32_t i = aRow, len = mSizes.Length(); i < len; ++i) {
        mSizes[i].mPosition -= gap;
      }
    }
  }

  /**
   * Set the size of aRow to aSize and adjust the position of all rows after it.
   */
  void ResizeRow(uint32_t aRow, nscoord aNewSize) {
    MOZ_ASSERT(mAxis == eLogicalAxisBlock,
               "Should only be fragmenting in the block axis (between rows)");
    MOZ_ASSERT(aNewSize >= 0);
    auto& sz = mSizes[aRow];
    nscoord delta = aNewSize - sz.mBase;
    NS_WARNING_ASSERTION(delta != nscoord(0), "Useless call to ResizeRow");
    sz.mBase = aNewSize;
    const uint32_t numRows = mSizes.Length();
    for (uint32_t r = aRow + 1; r < numRows; ++r) {
      mSizes[r].mPosition += delta;
    }
  }

  nscoord ResolveSize(const LineRange& aRange) const {
    MOZ_ASSERT(mCanResolveLineRangeSize);
    MOZ_ASSERT(aRange.Extent() > 0, "grid items cover at least one track");
    nscoord pos, size;
    aRange.ToPositionAndLength(mSizes, &pos, &size);
    return size;
  }

#ifdef DEBUG
  void Dump() const;
#endif

  CopyableAutoTArray<TrackSize, 32> mSizes;
  nscoord mContentBoxSize;
  nscoord mGridGap;
  // The first(last)-baseline for the first(last) track in this axis.
  PerBaseline<nscoord> mBaseline;
  // The union of the track min/max-sizing state bits in this axis.
  TrackSize::StateBits mStateUnion;
  LogicalAxis mAxis;
  // Used for aligning a baseline-aligned subtree of items.  The only possible
  // values are StyleAlignFlags::{START,END,CENTER,AUTO}.  AUTO means there are
  // no baseline-aligned items in any track in that axis.
  // There is one alignment value for each BaselineSharingGroup.
  PerBaseline<StyleAlignFlags> mBaselineSubtreeAlign;
  // True if track positions and sizes are final in this axis.
  bool mCanResolveLineRangeSize;
  // True if this axis has masonry layout.
  bool mIsMasonry;
};

#ifdef DEBUG
void nsGridContainerFrame::Tracks::Dump() const {
  printf("%zu %s %s ", mSizes.Length(), mIsMasonry ? "masonry" : "grid",
         mAxis == eLogicalAxisBlock ? "rows" : "columns");
  TrackSize::DumpStateBits(mStateUnion);
  printf("\n");
  for (uint32_t i = 0, len = mSizes.Length(); i < len; ++i) {
    printf("  %d: ", i);
    mSizes[i].Dump();
    printf("\n");
  }
  double px = AppUnitsPerCSSPixel();
  printf("Baselines: %.2fpx %2fpx\n",
         mBaseline[BaselineSharingGroup::First] / px,
         mBaseline[BaselineSharingGroup::Last] / px);
  printf("Gap: %.2fpx\n", mGridGap / px);
  printf("ContentBoxSize: %.2fpx\n", mContentBoxSize / px);
}
#endif

/**
 * Grid data shared by all continuations, owned by the first-in-flow.
 * The data is initialized from the first-in-flow's GridReflowInput at
 * the end of its reflow.  Fragmentation will modify mRows.mSizes -
 * the mPosition to remove the row gap at the break boundary, the mState
 * by setting the eBreakBefore flag, and mBase is modified when we decide
 * to grow a row.  mOriginalRowData is setup by the first-in-flow and
 * not modified after that.  It's used for undoing the changes to mRows.
 * mCols, mGridItems, mAbsPosItems are used for initializing the grid
 * reflow input for continuations, see GridReflowInput::Initialize below.
 */
struct nsGridContainerFrame::SharedGridData {
  SharedGridData()
      : mCols(eLogicalAxisInline),
        mRows(eLogicalAxisBlock),
        mGenerateComputedGridInfo(false) {}
  Tracks mCols;
  Tracks mRows;
  struct RowData {
    nscoord mBase;  // the original track size
    nscoord mGap;   // the original gap before a track
  };
  nsTArray<RowData> mOriginalRowData;
  nsTArray<GridItemInfo> mGridItems;
  nsTArray<GridItemInfo> mAbsPosItems;
  bool mGenerateComputedGridInfo;

  /**
   * Only set on the first-in-flow.  Continuations will Initialize() their
   * GridReflowInput from it.
   */
  NS_DECLARE_FRAME_PROPERTY_DELETABLE(Prop, SharedGridData)
};

struct MOZ_STACK_CLASS nsGridContainerFrame::GridReflowInput {
  GridReflowInput(nsGridContainerFrame* aFrame, const ReflowInput& aRI)
      : GridReflowInput(aFrame, *aRI.mRenderingContext, &aRI,
                        aRI.mStylePosition, aRI.GetWritingMode()) {}
  GridReflowInput(nsGridContainerFrame* aFrame, gfxContext& aRC)
      : GridReflowInput(aFrame, aRC, nullptr, aFrame->StylePosition(),
                        aFrame->GetWritingMode()) {}

  /**
   * Initialize our track sizes and grid item info using the shared
   * state from aGridContainerFrame first-in-flow.
   */
  void InitializeForContinuation(nsGridContainerFrame* aGridContainerFrame,
                                 nscoord aConsumedBSize) {
    MOZ_ASSERT(aGridContainerFrame->GetPrevInFlow(),
               "don't call this on the first-in-flow");
    MOZ_ASSERT(mGridItems.IsEmpty() && mAbsPosItems.IsEmpty(),
               "shouldn't have any item data yet");

    // Get the SharedGridData from the first-in-flow. Also calculate the number
    // of fragments before this so that we can figure out our start row below.
    uint32_t fragment = 0;
    nsIFrame* firstInFlow = aGridContainerFrame;
    for (auto pif = aGridContainerFrame->GetPrevInFlow(); pif;
         pif = pif->GetPrevInFlow()) {
      ++fragment;
      firstInFlow = pif;
    }
    mSharedGridData = firstInFlow->GetProperty(SharedGridData::Prop());
    MOZ_ASSERT(mSharedGridData, "first-in-flow must have SharedGridData");

    // Find the start row for this fragment and undo breaks after that row
    // since the breaks might be different from the last reflow.
    auto& rowSizes = mSharedGridData->mRows.mSizes;
    const uint32_t numRows = rowSizes.Length();
    mStartRow = numRows;
    for (uint32_t row = 0, breakCount = 0; row < numRows; ++row) {
      if (rowSizes[row].mState & TrackSize::eBreakBefore) {
        if (fragment == ++breakCount) {
          mStartRow = row;
          mFragBStart = rowSizes[row].mPosition;
          // Restore the original size for |row| and grid gaps / state after it.
          const auto& origRowData = mSharedGridData->mOriginalRowData;
          rowSizes[row].mBase = origRowData[row].mBase;
          nscoord prevEndPos = rowSizes[row].mPosition + rowSizes[row].mBase;
          while (++row < numRows) {
            auto& sz = rowSizes[row];
            const auto& orig = origRowData[row];
            sz.mPosition = prevEndPos + orig.mGap;
            sz.mBase = orig.mBase;
            sz.mState &= ~TrackSize::eBreakBefore;
            prevEndPos = sz.mPosition + sz.mBase;
          }
          break;
        }
      }
    }
    if (mStartRow == numRows ||
        aGridContainerFrame->IsMasonry(eLogicalAxisBlock)) {
      // All of the grid's rows fit inside of previous grid-container fragments,
      // or it's a masonry axis.
      mFragBStart = aConsumedBSize;
    }

    // Copy the shared track state.
    // XXX consider temporarily swapping the array elements instead and swapping
    // XXX them back after we're done reflowing, for better performance.
    // XXX (bug 1252002)
    mCols = mSharedGridData->mCols;
    mRows = mSharedGridData->mRows;

    if (firstInFlow->GetProperty(UsedTrackSizes::Prop())) {
      auto* prop = aGridContainerFrame->GetProperty(UsedTrackSizes::Prop());
      if (!prop) {
        prop = new UsedTrackSizes();
        aGridContainerFrame->SetProperty(UsedTrackSizes::Prop(), prop);
      }
      prop->mCanResolveLineRangeSize = {true, true};
      prop->mSizes[eLogicalAxisInline].Assign(mCols.mSizes);
      prop->mSizes[eLogicalAxisBlock].Assign(mRows.mSizes);
    }

    // Copy item data from each child's first-in-flow data in mSharedGridData.
    // XXX NOTE: This is O(n^2) in the number of items. (bug 1252186)
    mIter.Reset();
    for (; !mIter.AtEnd(); mIter.Next()) {
      nsIFrame* child = *mIter;
      nsIFrame* childFirstInFlow = child->FirstInFlow();
      DebugOnly<size_t> len = mGridItems.Length();
      for (auto& itemInfo : mSharedGridData->mGridItems) {
        if (itemInfo.mFrame == childFirstInFlow) {
          auto item =
              mGridItems.AppendElement(GridItemInfo(child, itemInfo.mArea));
          // Copy the item's baseline data so that the item's last fragment can
          // do 'last baseline' alignment if necessary.
          item->mState[eLogicalAxisBlock] |=
              itemInfo.mState[eLogicalAxisBlock] & ItemState::eAllBaselineBits;
          item->mState[eLogicalAxisInline] |=
              itemInfo.mState[eLogicalAxisInline] & ItemState::eAllBaselineBits;
          item->mBaselineOffset[eLogicalAxisBlock] =
              itemInfo.mBaselineOffset[eLogicalAxisBlock];
          item->mBaselineOffset[eLogicalAxisInline] =
              itemInfo.mBaselineOffset[eLogicalAxisInline];
          item->mState[eLogicalAxisBlock] |=
              itemInfo.mState[eLogicalAxisBlock] & ItemState::eAutoPlacement;
          item->mState[eLogicalAxisInline] |=
              itemInfo.mState[eLogicalAxisInline] & ItemState::eAutoPlacement;
          break;
        }
      }
      MOZ_ASSERT(mGridItems.Length() == len + 1, "can't find GridItemInfo");
    }

    // XXX NOTE: This is O(n^2) in the number of abs.pos. items. (bug 1252186)
    const nsFrameList& absPosChildren = aGridContainerFrame->GetChildList(
        aGridContainerFrame->GetAbsoluteListID());
    for (auto f : absPosChildren) {
      nsIFrame* childFirstInFlow = f->FirstInFlow();
      DebugOnly<size_t> len = mAbsPosItems.Length();
      for (auto& itemInfo : mSharedGridData->mAbsPosItems) {
        if (itemInfo.mFrame == childFirstInFlow) {
          mAbsPosItems.AppendElement(GridItemInfo(f, itemInfo.mArea));
          break;
        }
      }
      MOZ_ASSERT(mAbsPosItems.Length() == len + 1, "can't find GridItemInfo");
    }

    // Copy in the computed grid info state bit
    if (mSharedGridData->mGenerateComputedGridInfo) {
      aGridContainerFrame->AddStateBits(NS_STATE_GRID_COMPUTED_INFO);
    }
  }

  /**
   * Calculate our track sizes in the given axis.
   */
  void CalculateTrackSizesForAxis(LogicalAxis aAxis, const Grid& aGrid,
                                  nscoord aCBSize,
                                  SizingConstraint aConstraint);

  /**
   * Calculate our track sizes.
   */
  void CalculateTrackSizes(const Grid& aGrid, const LogicalSize& aContentBox,
                           SizingConstraint aConstraint);

  /**
   * Return the percentage basis for a grid item in its writing-mode.
   * If aAxis is eLogicalAxisInline then we return NS_UNCONSTRAINEDSIZE in
   * both axes since we know all track sizes are indefinite at this point
   * (we calculate column sizes before row sizes).  Otherwise, assert that
   * column sizes are known and calculate the size for aGridItem.mArea.mCols
   * and use NS_UNCONSTRAINEDSIZE in the other axis.
   * @param aAxis the axis we're currently calculating track sizes for
   */
  LogicalSize PercentageBasisFor(LogicalAxis aAxis,
                                 const GridItemInfo& aGridItem) const;

  /**
   * Return the containing block for a grid item occupying aArea.
   */
  LogicalRect ContainingBlockFor(const GridArea& aArea) const;

  /**
   * Return the containing block for an abs.pos. grid item occupying aArea.
   * Any 'auto' lines in the grid area will be aligned with grid container
   * containing block on that side.
   * @param aGridOrigin the origin of the grid
   * @param aGridCB the grid container containing block (its padding area)
   */
  LogicalRect ContainingBlockForAbsPos(const GridArea& aArea,
                                       const LogicalPoint& aGridOrigin,
                                       const LogicalRect& aGridCB) const;

  /**
   * Apply `align/justify-content` alignment in our masonry axis.
   * This aligns the "masonry box" within our content box size.
   */
  void AlignJustifyContentInMasonryAxis(nscoord aMasonryBoxSize,
                                        nscoord aContentBoxSize);
  /**
   * Apply `align/justify-tracks` alignment in our masonry axis.
   */
  void AlignJustifyTracksInMasonryAxis(const LogicalSize& aContentSize,
                                       const nsSize& aContainerSize);

  // Recursive helper for CollectSubgridItemsForAxis().
  static void CollectSubgridItemsForAxisHelper(
      LogicalAxis aAxis, WritingMode aContainerWM,
      const LineRange& aRangeInAxis, const LineRange& aRangeInOppositeAxis,
      const GridItemInfo& aItem, const nsTArray<GridItemInfo>& aItems,
      nsTArray<GridItemInfo>& aResult) {
    const auto oppositeAxis = GetOrthogonalAxis(aAxis);
    bool itemIsSubgridInOppositeAxis = aItem.IsSubgrid(oppositeAxis);
    auto subgridWM = aItem.mFrame->GetWritingMode();
    bool isOrthogonal = subgridWM.IsOrthogonalTo(aContainerWM);
    bool isSameDirInAxis =
        subgridWM.ParallelAxisStartsOnSameSide(aAxis, aContainerWM);
    bool isSameDirInOppositeAxis =
        subgridWM.ParallelAxisStartsOnSameSide(oppositeAxis, aContainerWM);
    if (isOrthogonal) {
      // We'll Transpose the area below so these needs to be transposed as well.
      std::swap(isSameDirInAxis, isSameDirInOppositeAxis);
    }
    uint32_t offsetInAxis = aRangeInAxis.mStart;
    uint32_t gridEndInAxis = aRangeInAxis.Extent();
    uint32_t offsetInOppositeAxis = aRangeInOppositeAxis.mStart;
    uint32_t gridEndInOppositeAxis = aRangeInOppositeAxis.Extent();
    for (const auto& subgridItem : aItems) {
      auto newItem = aResult.AppendElement(
          isOrthogonal ? subgridItem.Transpose() : subgridItem);
      if (MOZ_UNLIKELY(!isSameDirInAxis)) {
        newItem->ReverseDirection(aAxis, gridEndInAxis);
      }
      newItem->mArea.LineRangeForAxis(aAxis).Translate(offsetInAxis);
      if (itemIsSubgridInOppositeAxis) {
        if (MOZ_UNLIKELY(!isSameDirInOppositeAxis)) {
          newItem->ReverseDirection(oppositeAxis, gridEndInOppositeAxis);
        }
        LineRange& range = newItem->mArea.LineRangeForAxis(oppositeAxis);
        range.Translate(offsetInOppositeAxis);
      }
      if (newItem->IsSubgrid(aAxis)) {
        auto* subgrid =
            subgridItem.SubgridFrame()->GetProperty(Subgrid::Prop());
        CollectSubgridItemsForAxisHelper(
            aAxis, aContainerWM, newItem->mArea.LineRangeForAxis(aAxis),
            newItem->mArea.LineRangeForAxis(oppositeAxis), *newItem,
            subgrid->mGridItems, aResult);
      }
    }
  }

  // Copy all descendant items from all our subgrid children that are subgridded
  // in aAxis recursively into aResult.  All item grid area's and state are
  // translated to our coordinates.
  void CollectSubgridItemsForAxis(LogicalAxis aAxis,
                                  nsTArray<GridItemInfo>& aResult) const {
    for (const auto& item : mGridItems) {
      if (item.IsSubgrid(aAxis)) {
        const auto oppositeAxis = GetOrthogonalAxis(aAxis);
        auto* subgrid = item.SubgridFrame()->GetProperty(Subgrid::Prop());
        CollectSubgridItemsForAxisHelper(
            aAxis, mWM, item.mArea.LineRangeForAxis(aAxis),
            item.mArea.LineRangeForAxis(oppositeAxis), item,
            subgrid->mGridItems, aResult);
      }
    }
  }

  /**
   * Recursive helper for CopyBaselineMetricsToSubgridItems().
   *
   * @param aAxis The LogicalAxis for the axis whose baseline metrics we're
   *              copying here (with respect to the outermost parent grid's
   *              writing mode).
   * @param aContainerWM The writing mode of that outermost parent grid.
   * @param aSubgridFrame The subgrid whose subgrid-items we're considering
   *              in this recursive traversal (whose items we're copying over
   *              baseline-alignment metrics for).
   * @param aContainerGridItems The outermost parent grid's array of
   *              GridItemInfo objects.  (The final portion of this array is
   *              all for subgrid items, and that's the portion that we're
   *              recursively iterating over.)
   * @param aContainerGridItemsIdx [in/out] The index for the item that we're
   *              currently considering in aContainerGridItemsIdx. When
   *              this function returns, this will be the index just beyond the
   *              last item that we handled here, i.e. the index of the next
   *              item to be handled.
   */
  static void CopyBaselineMetricsToSubgridItemsHelper(
      LogicalAxis aAxis, WritingMode aContainerWM, nsIFrame* aSubgridFrame,
      const nsTArray<GridItemInfo>& aContainerGridItems,
      size_t& aContainerGridItemsIdx) {
    // Get the canonical GridItemInfo structs for the grid items that live
    // inside of aSubgridFrame:
    Subgrid* subgridProp = aSubgridFrame->GetProperty(Subgrid::Prop());
    nsTArray<GridItemInfo>& subgridItems = subgridProp->mGridItems;

    // Use aSubgridFrame's writing-mode to determine subgridAxis.
    // Grids & subgrids store various data on a per-LogicalAxis basis, with
    // respect to their own WritingMode.  Here, subgridAxis is aSubgridFrame's
    // axis that maps to the same physical axis that aAxis does for the
    // outermost parent grid.
    auto subgridWM = aSubgridFrame->GetWritingMode();
    bool isOrthogonal = subgridWM.IsOrthogonalTo(aContainerWM);
    LogicalAxis subgridAxis = isOrthogonal ? GetOrthogonalAxis(aAxis) : aAxis;

    // Do a parallel walk through (1) subgridItems and (2) the portion of
    // aContainerGridItems that starts at offset aContainerGridItems,
    // descending to traverse child subgrids own items as we encounter them in
    // subgridItems.  We expect to have an exact correspondence, because this
    // is precisely how we built up this portion of aContainerGridItems in
    // CollectSubgridItemsForAxis. (But if we happen to overstep the end of an
    // array, or find a GridItemInfo for a frame that we don't expect, we
    // gracefully bail out.)
    for (auto& subgridItem : subgridItems) {
      if (MOZ_UNLIKELY(aContainerGridItemsIdx >=
                       aContainerGridItems.Length())) {
        // We failed to make the same traversal as CollectSubgridItemsForAxis;
        // whoops! This shouldn't happen; but if it does, we gracefully bail
        // out, instead of crashing.
        MOZ_ASSERT_UNREACHABLE("Out-of-bounds aContainerGridItemsIdx");
        return;
      }
      const auto& itemFromContainer =
          aContainerGridItems[aContainerGridItemsIdx];
      aContainerGridItemsIdx++;

      if (MOZ_UNLIKELY(subgridItem.mFrame != itemFromContainer.mFrame)) {
        // We failed to make the same traversal as CollectSubgridItemsForAxis;
        // whoops! This shouldn't happen; but if it does, we gracefully bail
        // out, instead of copying baseline-alignment data for the wrong frame.
        MOZ_ASSERT_UNREACHABLE("Found unexpected frame during traversal");
        return;
      }

      // This pattern of bits will be truthy if the item is baseline-aligned in
      // this axis (in which case the exact pattern of bits will have some
      // additional significance that doesn't matter here, but we do need to
      // copy it over).
      const auto baselineStateBits =
          itemFromContainer.mState[aAxis] & ItemState::eAllBaselineBits;

      if (subgridItem.IsSubgrid(subgridAxis)) {
        // This item is in fact a nested subgrid. It shouldn't itself be
        // baseline-aligned, but we need to make a recursive call to copy
        // baseline metrics to its items.
        MOZ_ASSERT(!baselineStateBits,
                   "subgrids themselves can't be baseline-aligned "
                   "(or self-aligned in any way) in their subgrid axis");
        CopyBaselineMetricsToSubgridItemsHelper(
            aAxis, aContainerWM, subgridItem.SubgridFrame(),
            aContainerGridItems, aContainerGridItemsIdx);
      } else if (baselineStateBits) {
        // This item is a baseline-aligned grid item (in the subgrid that we're
        // traversing). Copy over its baseline metrics.
        subgridItem.mState[subgridAxis] |= baselineStateBits;
        subgridItem.mBaselineOffset[subgridAxis] =
            itemFromContainer.mBaselineOffset[aAxis];
      }
    }
  }

  /**
   * This function here is responsible for propagating baseline-alignment
   * metrics for subgrid-items from mGridItems over to the "canonical"
   * GridItemInfo structs for those grid items (which live on the subgrid that
   * owns them). The outermost parent grid *computes* those metrics as part of
   * doing track sizing, but it does this using *temporary* GridItemInfo
   * objects for any grid items that live in subgrids (aka subgrid items). So
   * that's why we need to rescue this baseline-alignment information before
   * those temporary objects are discarded.
   *
   * (The temporary subgrid-items all live at the end of mGridItems; they were
   * appended there by CollectSubgridItemsForAxis().  So, it's important that
   * we perform the exact same traversal that CollectSubgridItemsForAxis() did,
   * in order to properly match up the temporary & canonical GridItemInfo
   * objects for these subgrid items.)
   */
  // traversal that CollectSubgridItemsForAxis (and its recursive helper) does.
  void CopyBaselineMetricsToSubgridItems(LogicalAxis aAxis,
                                         size_t aOriginalLength) {
    MOZ_ASSERT(aOriginalLength <= mGridItems.Length(),
               "aOriginalLength is the length that mGridItems had *before* we "
               "appended temporary copies of subgrid items to it, so it's not "
               "possible for it to be more than the current length");

    // This index 'subgridItemIdx' traverses the final portion of mGridItems,
    // the portion that currently has temporary GridItemInfo structs that we
    // built for the items that live in our subgrids.  (Our caller is about to
    // discard this temporary portion of mGridItems, and we're trying to
    // transfer some baseline-alignment data to the canonical GridItemInfo
    // structs before that happens.)
    //
    // Our recursive helper updates subgridItemIdx internally. When this index
    // reaches mGridItems.Length(), we can stop looping; that means we've
    // finished copying out all the data from these temporary structs.
    size_t subgridItemIdx = aOriginalLength;

    for (size_t i = 0;
         (i < aOriginalLength && subgridItemIdx < mGridItems.Length()); i++) {
      const auto& item = mGridItems[i];
      if (item.IsSubgrid(aAxis)) {
        CopyBaselineMetricsToSubgridItemsHelper(aAxis, mWM, item.SubgridFrame(),
                                                mGridItems, subgridItemIdx);
      }
    }
  }

  Tracks& TracksFor(LogicalAxis aAxis) {
    return aAxis == eLogicalAxisBlock ? mRows : mCols;
  }
  const Tracks& TracksFor(LogicalAxis aAxis) const {
    return aAxis == eLogicalAxisBlock ? mRows : mCols;
  }

  CSSOrderAwareFrameIterator mIter;
  const nsStylePosition* const mGridStyle;
  Tracks mCols;
  Tracks mRows;
  TrackSizingFunctions mColFunctions;
  TrackSizingFunctions mRowFunctions;
  /**
   * Info about each (normal flow) grid item.
   */
  nsTArray<GridItemInfo> mGridItems;
  /**
   * Info about each grid-aligned abs.pos. child.
   */
  nsTArray<GridItemInfo> mAbsPosItems;

  /**
   * @note mReflowInput may be null when using the 2nd ctor above. In this case
   * we'll construct a dummy parent reflow input if we need it to calculate
   * min/max-content contributions when sizing tracks.
   */
  const ReflowInput* const mReflowInput;
  gfxContext& mRenderingContext;
  nsGridContainerFrame* const mFrame;
  SharedGridData* mSharedGridData;  // [weak] owned by mFrame's first-in-flow.
  /** Computed border+padding with mSkipSides applied. */
  LogicalMargin mBorderPadding;
  /**
   * BStart of this fragment in "grid space" (i.e. the concatenation of content
   * areas of all fragments).  Equal to mRows.mSizes[mStartRow].mPosition,
   * or, if this fragment starts after the last row, the ConsumedBSize().
   */
  nscoord mFragBStart;
  /** The start row for this fragment. */
  uint32_t mStartRow;
  /**
   * The start row for the next fragment, if any.  If mNextFragmentStartRow ==
   * mStartRow then there are no rows in this fragment.
   */
  uint32_t mNextFragmentStartRow;
  /** Our tentative ApplySkipSides bits. */
  LogicalSides mSkipSides;
  const WritingMode mWM;
  /** Initialized lazily, when we find the fragmentainer. */
  bool mInFragmentainer;

 private:
  GridReflowInput(nsGridContainerFrame* aFrame, gfxContext& aRenderingContext,
                  const ReflowInput* aReflowInput,
                  const nsStylePosition* aGridStyle, const WritingMode& aWM)
      : mIter(aFrame, FrameChildListID::Principal),
        mGridStyle(aGridStyle),
        mCols(eLogicalAxisInline),
        mRows(eLogicalAxisBlock),
        mColFunctions(mGridStyle->mGridTemplateColumns,
                      mGridStyle->mGridAutoColumns,
                      aFrame->IsSubgrid(eLogicalAxisInline)),
        mRowFunctions(mGridStyle->mGridTemplateRows, mGridStyle->mGridAutoRows,
                      aFrame->IsSubgrid(eLogicalAxisBlock)),
        mReflowInput(aReflowInput),
        mRenderingContext(aRenderingContext),
        mFrame(aFrame),
        mSharedGridData(nullptr),
        mBorderPadding(aWM),
        mFragBStart(0),
        mStartRow(0),
        mNextFragmentStartRow(0),
        mSkipSides(aFrame->GetWritingMode()),
        mWM(aWM),
        mInFragmentainer(false) {
    MOZ_ASSERT(!aReflowInput || aReflowInput->mFrame == mFrame);
    if (aReflowInput) {
      mBorderPadding = aReflowInput->ComputedLogicalBorderPadding(mWM);
      mSkipSides = aFrame->PreReflowBlockLevelLogicalSkipSides();
      mBorderPadding.ApplySkipSides(mSkipSides);
    }
    mCols.mIsMasonry = aFrame->IsMasonry(eLogicalAxisInline);
    mRows.mIsMasonry = aFrame->IsMasonry(eLogicalAxisBlock);
    MOZ_ASSERT(!(mCols.mIsMasonry && mRows.mIsMasonry),
               "can't have masonry layout in both axes");
  }
};

using GridReflowInput = nsGridContainerFrame::GridReflowInput;

/**
 * The Grid implements grid item placement and the state of the grid -
 * the size of the explicit/implicit grid, which cells are occupied etc.
 */
struct MOZ_STACK_CLASS nsGridContainerFrame::Grid {
  explicit Grid(const Grid* aParentGrid = nullptr) : mParentGrid(aParentGrid) {}

  /**
   * Place all child frames into the grid and expand the (implicit) grid as
   * needed.  The allocated GridAreas are stored in the GridAreaProperty
   * frame property on the child frame.
   * @param aRepeatSizing the container's [min-|max-]*size - used to determine
   *   the number of repeat(auto-fill/fit) tracks.
   */
  void PlaceGridItems(GridReflowInput& aState,
                      const RepeatTrackSizingInput& aRepeatSizing);

  void SubgridPlaceGridItems(GridReflowInput& aParentState, Grid* aParentGrid,
                             const GridItemInfo& aGridItem);

  /**
   * As above but for an abs.pos. child.  Any 'auto' lines will be represented
   * by kAutoLine in the LineRange result.
   * @param aGridStart the first line in the final, but untranslated grid
   * @param aGridEnd the last line in the final, but untranslated grid
   */
  LineRange ResolveAbsPosLineRange(const StyleGridLine& aStart,
                                   const StyleGridLine& aEnd,
                                   const LineNameMap& aNameMap,
                                   LogicalAxis aAxis, uint32_t aExplicitGridEnd,
                                   int32_t aGridStart, int32_t aGridEnd,
                                   const nsStylePosition* aStyle);

  /**
   * Return a GridArea for abs.pos. item with non-auto lines placed at
   * a definite line (1-based) with placement errors resolved.  One or both
   * positions may still be 'auto'.
   * @param aChild the abs.pos. grid item to place
   * @param aStyle the StylePosition() for the grid container
   */
  GridArea PlaceAbsPos(nsIFrame* aChild, const LineNameMap& aColLineNameMap,
                       const LineNameMap& aRowLineNameMap,
                       const nsStylePosition* aStyle);

  /**
   * Find the first column in row aLockedRow starting at aStartCol where aArea
   * could be placed without overlapping other items.  The returned column may
   * cause aArea to overflow the current implicit grid bounds if placed there.
   */
  uint32_t FindAutoCol(uint32_t aStartCol, uint32_t aLockedRow,
                       const GridArea* aArea) const;

  /**
   * Place aArea in the first column (in row aArea->mRows.mStart) starting at
   * aStartCol without overlapping other items.  The resulting aArea may
   * overflow the current implicit grid bounds.
   * @param aClampMaxColLine the maximum allowed column line number (zero-based)
   * Pre-condition: aArea->mRows.IsDefinite() is true.
   * Post-condition: aArea->IsDefinite() is true.
   */
  void PlaceAutoCol(uint32_t aStartCol, GridArea* aArea,
                    uint32_t aClampMaxColLine) const;

  /**
   * Find the first row in column aLockedCol starting at aStartRow where aArea
   * could be placed without overlapping other items.  The returned row may
   * cause aArea to overflow the current implicit grid bounds if placed there.
   */
  uint32_t FindAutoRow(uint32_t aLockedCol, uint32_t aStartRow,
                       const GridArea* aArea) const;

  /**
   * Place aArea in the first row (in column aArea->mCols.mStart) starting at
   * aStartRow without overlapping other items. The resulting aArea may
   * overflow the current implicit grid bounds.
   * @param aClampMaxRowLine the maximum allowed row line number (zero-based)
   * Pre-condition: aArea->mCols.IsDefinite() is true.
   * Post-condition: aArea->IsDefinite() is true.
   */
  void PlaceAutoRow(uint32_t aStartRow, GridArea* aArea,
                    uint32_t aClampMaxRowLine) const;

  /**
   * Place aArea in the first column starting at aStartCol,aStartRow without
   * causing it to overlap other items or overflow mGridColEnd.
   * If there's no such column in aStartRow, continue in position 1,aStartRow+1.
   * @param aClampMaxColLine the maximum allowed column line number (zero-based)
   * @param aClampMaxRowLine the maximum allowed row line number (zero-based)
   * Pre-condition: aArea->mCols.IsAuto() && aArea->mRows.IsAuto() is true.
   * Post-condition: aArea->IsDefinite() is true.
   */
  void PlaceAutoAutoInRowOrder(uint32_t aStartCol, uint32_t aStartRow,
                               GridArea* aArea, uint32_t aClampMaxColLine,
                               uint32_t aClampMaxRowLine) const;

  /**
   * Place aArea in the first row starting at aStartCol,aStartRow without
   * causing it to overlap other items or overflow mGridRowEnd.
   * If there's no such row in aStartCol, continue in position aStartCol+1,1.
   * @param aClampMaxColLine the maximum allowed column line number (zero-based)
   * @param aClampMaxRowLine the maximum allowed row line number (zero-based)
   * Pre-condition: aArea->mCols.IsAuto() && aArea->mRows.IsAuto() is true.
   * Post-condition: aArea->IsDefinite() is true.
   */
  void PlaceAutoAutoInColOrder(uint32_t aStartCol, uint32_t aStartRow,
                               GridArea* aArea, uint32_t aClampMaxColLine,
                               uint32_t aClampMaxRowLine) const;

  /**
   * Return aLine if it's inside the aMin..aMax range (inclusive),
   * otherwise return kAutoLine.
   */
  static int32_t AutoIfOutside(int32_t aLine, int32_t aMin, int32_t aMax) {
    MOZ_ASSERT(aMin <= aMax);
    if (aLine < aMin || aLine > aMax) {
      return kAutoLine;
    }
    return aLine;
  }

  /**
   * Inflate the implicit grid to include aArea.
   * @param aArea may be definite or auto
   */
  void InflateGridFor(const GridArea& aArea) {
    mGridColEnd = std::max(mGridColEnd, aArea.mCols.HypotheticalEnd());
    mGridRowEnd = std::max(mGridRowEnd, aArea.mRows.HypotheticalEnd());
    MOZ_ASSERT(mGridColEnd <= kTranslatedMaxLine &&
               mGridRowEnd <= kTranslatedMaxLine);
  }

  /**
   * Calculates the empty tracks in a repeat(auto-fit).
   * @param aOutNumEmptyLines Outputs the number of tracks which are empty.
   * @param aSizingFunctions Sizing functions for the relevant axis.
   * @param aNumGridLines Number of grid lines for the relevant axis.
   * @param aIsEmptyFunc Functor to check if a cell is empty. This should be
   * mCellMap.IsColEmpty or mCellMap.IsRowEmpty, depending on the axis.
   */
  template <typename IsEmptyFuncT>
  static Maybe<nsTArray<uint32_t>> CalculateAdjustForAutoFitElements(
      uint32_t* aOutNumEmptyTracks, TrackSizingFunctions& aSizingFunctions,
      uint32_t aNumGridLines, IsEmptyFuncT aIsEmptyFunc);

  /**
   * Return a line number for (non-auto) aLine, per:
   * http://dev.w3.org/csswg/css-grid/#line-placement
   * @param aLine style data for the line (must be non-auto)
   * @param aNth a number of lines to find from aFromIndex, negative if the
   *             search should be in reverse order.  In the case aLine has
   *             a specified line name, it's permitted to pass in zero which
   *             will be treated as one.
   * @param aFromIndex the zero-based index to start counting from
   * @param aLineNameList the explicit named lines
   * @param aSide the axis+edge we're resolving names for (e.g. if we're
                  resolving a grid-row-start line, pass eLogicalSideBStart)
   * @param aExplicitGridEnd the last line in the explicit grid
   * @param aStyle the StylePosition() for the grid container
   * @return a definite line (1-based), clamped to
   *   the mClampMinLine..mClampMaxLine range
   */
  int32_t ResolveLine(const StyleGridLine& aLine, int32_t aNth,
                      uint32_t aFromIndex, const LineNameMap& aNameMap,
                      LogicalSide aSide, uint32_t aExplicitGridEnd,
                      const nsStylePosition* aStyle);

  /**
   * Helper method for ResolveLineRange.
   * @see ResolveLineRange
   * @return a pair (start,end) of lines
   */
  typedef std::pair<int32_t, int32_t> LinePair;
  LinePair ResolveLineRangeHelper(const StyleGridLine& aStart,
                                  const StyleGridLine& aEnd,
                                  const LineNameMap& aNameMap,
                                  LogicalAxis aAxis, uint32_t aExplicitGridEnd,
                                  const nsStylePosition* aStyle);

  /**
   * Return a LineRange based on the given style data. Non-auto lines
   * are resolved to a definite line number (1-based) per:
   * http://dev.w3.org/csswg/css-grid/#line-placement
   * with placement errors corrected per:
   * http://dev.w3.org/csswg/css-grid/#grid-placement-errors
   * @param aStyle the StylePosition() for the grid container
   * @param aStart style data for the start line
   * @param aEnd style data for the end line
   * @param aLineNameList the explicit named lines
   * @param aAxis the axis we're resolving names in
   * @param aExplicitGridEnd the last line in the explicit grid
   * @param aStyle the StylePosition() for the grid container
   */
  LineRange ResolveLineRange(const StyleGridLine& aStart,
                             const StyleGridLine& aEnd,
                             const LineNameMap& aNameMap, LogicalAxis aAxis,
                             uint32_t aExplicitGridEnd,
                             const nsStylePosition* aStyle);

  /**
   * Return a GridArea with non-auto lines placed at a definite line (1-based)
   * with placement errors resolved.  One or both positions may still
   * be 'auto'.
   * @param aChild the grid item
   * @param aStyle the StylePosition() for the grid container
   */
  GridArea PlaceDefinite(nsIFrame* aChild, const LineNameMap& aColLineNameMap,
                         const LineNameMap& aRowLineNameMap,
                         const nsStylePosition* aStyle);

  bool HasImplicitNamedArea(nsAtom* aName) const {
    return mAreas && mAreas->has(aName);
  }

  // Return true if aString ends in aSuffix and has at least one character
  // before the suffix. Assign aIndex to where the suffix starts.
  static bool IsNameWithSuffix(nsAtom* aString, const nsString& aSuffix,
                               uint32_t* aIndex) {
    if (StringEndsWith(nsDependentAtomString(aString), aSuffix)) {
      *aIndex = aString->GetLength() - aSuffix.Length();
      return *aIndex != 0;
    }
    return false;
  }

  static bool IsNameWithEndSuffix(nsAtom* aString, uint32_t* aIndex) {
    return IsNameWithSuffix(aString, u"-end"_ns, aIndex);
  }

  static bool IsNameWithStartSuffix(nsAtom* aString, uint32_t* aIndex) {
    return IsNameWithSuffix(aString, u"-start"_ns, aIndex);
  }

  // Return the relevant parent LineNameMap for the given subgrid axis aAxis.
  const LineNameMap* ParentLineMapForAxis(bool aIsOrthogonal,
                                          LogicalAxis aAxis) const {
    if (!mParentGrid) {
      return nullptr;
    }
    bool isRows = aIsOrthogonal == (aAxis == eLogicalAxisInline);
    return isRows ? mParentGrid->mRowNameMap : mParentGrid->mColNameMap;
  }

  void SetLineMaps(const LineNameMap* aColNameMap,
                   const LineNameMap* aRowNameMap) {
    mColNameMap = aColNameMap;
    mRowNameMap = aRowNameMap;
  }

  /**
   * A CellMap holds state for each cell in the grid.
   * It's row major.  It's sparse in the sense that it only has enough rows to
   * cover the last row that has a grid item.  Each row only has enough entries
   * to cover columns that are occupied *on that row*, i.e. it's not a full
   * matrix covering the entire implicit grid.  An absent Cell means that it's
   * unoccupied by any grid item.
   */
  struct CellMap {
    struct Cell {
      constexpr Cell() : mIsOccupied(false) {}
      bool mIsOccupied : 1;
    };

    void Fill(const GridArea& aGridArea) {
      MOZ_ASSERT(aGridArea.IsDefinite());
      MOZ_ASSERT(aGridArea.mRows.mStart < aGridArea.mRows.mEnd);
      MOZ_ASSERT(aGridArea.mCols.mStart < aGridArea.mCols.mEnd);
      const auto numRows = aGridArea.mRows.mEnd;
      const auto numCols = aGridArea.mCols.mEnd;
      mCells.EnsureLengthAtLeast(numRows);
      for (auto i = aGridArea.mRows.mStart; i < numRows; ++i) {
        nsTArray<Cell>& cellsInRow = mCells[i];
        cellsInRow.EnsureLengthAtLeast(numCols);
        for (auto j = aGridArea.mCols.mStart; j < numCols; ++j) {
          cellsInRow[j].mIsOccupied = true;
        }
      }
    }

    uint32_t IsEmptyCol(uint32_t aCol) const {
      for (auto& row : mCells) {
        if (aCol < row.Length() && row[aCol].mIsOccupied) {
          return false;
        }
      }
      return true;
    }
    uint32_t IsEmptyRow(uint32_t aRow) const {
      if (aRow >= mCells.Length()) {
        return true;
      }
      for (const Cell& cell : mCells[aRow]) {
        if (cell.mIsOccupied) {
          return false;
        }
      }
      return true;
    }
#ifdef DEBUG
    void Dump() const {
      const size_t numRows = mCells.Length();
      for (size_t i = 0; i < numRows; ++i) {
        const nsTArray<Cell>& cellsInRow = mCells[i];
        const size_t numCols = cellsInRow.Length();
        printf("%lu:\t", (unsigned long)i + 1);
        for (size_t j = 0; j < numCols; ++j) {
          printf(cellsInRow[j].mIsOccupied ? "X " : ". ");
        }
        printf("\n");
      }
    }
#endif

    nsTArray<nsTArray<Cell>> mCells;
  };

  /**
   * State for each cell in the grid.
   */
  CellMap mCellMap;
  /**
   * @see HasImplicitNamedArea.
   */
  ImplicitNamedAreas* mAreas;
  /**
   * The last column grid line (1-based) in the explicit grid.
   * (i.e. the number of explicit columns + 1)
   */
  uint32_t mExplicitGridColEnd;
  /**
   * The last row grid line (1-based) in the explicit grid.
   * (i.e. the number of explicit rows + 1)
   */
  uint32_t mExplicitGridRowEnd;
  // Same for the implicit grid, except these become zero-based after
  // resolving definite lines.
  uint32_t mGridColEnd;
  uint32_t mGridRowEnd;

  /**
   * Offsets from the start of the implicit grid to the start of the translated
   * explicit grid.  They are zero if there are no implicit lines before 1,1.
   * e.g. "grid-column: span 3 / 1" makes mExplicitGridOffsetCol = 3 and the
   * corresponding GridArea::mCols will be 0 / 3 in the zero-based translated
   * grid.
   */
  uint32_t mExplicitGridOffsetCol;
  uint32_t mExplicitGridOffsetRow;

  /**
   * Our parent grid if any.
   */
  const Grid* mParentGrid;

  /**
   * Our LineNameMaps.
   */
  const LineNameMap* mColNameMap;
  const LineNameMap* mRowNameMap;
};

/**
 * Compute margin+border+padding for aGridItem.mFrame (a subgrid) and store it
 * on its Subgrid property (and return that property).
 * aPercentageBasis is in the grid item's writing-mode.
 */
static Subgrid* SubgridComputeMarginBorderPadding(
    const GridItemInfo& aGridItem, const LogicalSize& aPercentageBasis) {
  auto* subgridFrame = aGridItem.SubgridFrame();
  auto cbWM = aGridItem.mFrame->GetParent()->GetWritingMode();
  auto* subgrid = subgridFrame->GetProperty(Subgrid::Prop());
  auto wm = subgridFrame->GetWritingMode();
  auto pmPercentageBasis = cbWM.IsOrthogonalTo(wm) ? aPercentageBasis.BSize(wm)
                                                   : aPercentageBasis.ISize(wm);
  SizeComputationInput sz(subgridFrame, nullptr, cbWM, pmPercentageBasis);
  subgrid->mMarginBorderPadding =
      sz.ComputedLogicalMargin(cbWM) + sz.ComputedLogicalBorderPadding(cbWM);

  if (aGridItem.mFrame != subgridFrame) {
    nsHTMLScrollFrame* scrollFrame =
        do_QueryFrame(aGridItem.mFrame->GetScrollTargetFrame());
    if (scrollFrame) {
      MOZ_ASSERT(
          sz.ComputedLogicalMargin(cbWM) == LogicalMargin(cbWM) &&
              sz.ComputedLogicalBorder(cbWM) == LogicalMargin(cbWM),
          "A scrolled inner frame should not have any margin or border!");

      // Add the margin and border from the (outer) scroll frame.
      SizeComputationInput szScrollFrame(aGridItem.mFrame, nullptr, cbWM,
                                         pmPercentageBasis);
      subgrid->mMarginBorderPadding +=
          szScrollFrame.ComputedLogicalMargin(cbWM) +
          szScrollFrame.ComputedLogicalBorder(cbWM);

      nsMargin ssz = scrollFrame->IntrinsicScrollbarGutterSize();
      subgrid->mMarginBorderPadding += LogicalMargin(cbWM, ssz);
    }

    if (aGridItem.mFrame->IsFieldSetFrame()) {
      const auto* f = static_cast<nsFieldSetFrame*>(aGridItem.mFrame);
      const auto* inner = f->GetInner();
      auto wm = inner->GetWritingMode();
      LogicalPoint pos = inner->GetLogicalPosition(aGridItem.mFrame->GetSize());
      // The legend is always on the BStart side and it inflates the fieldset's
      // "border area" size.  The inner frame's b-start pos equals that size.
      LogicalMargin offsets(wm, pos.B(wm), 0, 0, 0);
      subgrid->mMarginBorderPadding += offsets.ConvertTo(cbWM, wm);
    }
  }
  return subgrid;
}

static void CopyUsedTrackSizes(nsTArray<TrackSize>& aResult,
                               const nsGridContainerFrame* aUsedTrackSizesFrame,
                               const UsedTrackSizes* aUsedTrackSizes,
                               const nsGridContainerFrame* aSubgridFrame,
                               const Subgrid* aSubgrid,
                               LogicalAxis aSubgridAxis) {
  MOZ_ASSERT(aSubgridFrame->ParentGridContainerForSubgrid() ==
             aUsedTrackSizesFrame);
  aResult.SetLength(aSubgridAxis == eLogicalAxisInline ? aSubgrid->mGridColEnd
                                                       : aSubgrid->mGridRowEnd);
  auto parentAxis =
      aSubgrid->mIsOrthogonal ? GetOrthogonalAxis(aSubgridAxis) : aSubgridAxis;
  const auto& parentSizes = aUsedTrackSizes->mSizes[parentAxis];
  MOZ_ASSERT(aUsedTrackSizes->mCanResolveLineRangeSize[parentAxis]);
  if (parentSizes.IsEmpty()) {
    return;
  }
  const auto& range = aSubgrid->mArea.LineRangeForAxis(parentAxis);
  const auto cbwm = aUsedTrackSizesFrame->GetWritingMode();
  const auto wm = aSubgridFrame->GetWritingMode();
  // Recompute the MBP to resolve percentages against the resolved track sizes.
  if (parentAxis == eLogicalAxisInline) {
    // Find the subgrid's grid item frame in its parent grid container.  This
    // is usually the same as aSubgridFrame but it may also have a ScrollFrame,
    // FieldSetFrame etc.  We just loop until we see the first ancestor
    // GridContainerFrame and pick the last frame we saw before that.
    // Note that all subgrids are inside a parent (sub)grid container.
    const nsIFrame* outerGridItemFrame = aSubgridFrame;
    for (nsIFrame* parent = aSubgridFrame->GetParent();
         parent != aUsedTrackSizesFrame; parent = parent->GetParent()) {
      MOZ_ASSERT(!parent->IsGridContainerFrame());
      outerGridItemFrame = parent;
    }
    auto sizeInAxis = range.ToLength(aUsedTrackSizes->mSizes[parentAxis]);
    LogicalSize pmPercentageBasis =
        aSubgrid->mIsOrthogonal ? LogicalSize(wm, nscoord(0), sizeInAxis)
                                : LogicalSize(wm, sizeInAxis, nscoord(0));
    GridItemInfo info(const_cast<nsIFrame*>(outerGridItemFrame),
                      aSubgrid->mArea);
    SubgridComputeMarginBorderPadding(info, pmPercentageBasis);
  }
  const LogicalMargin& mbp = aSubgrid->mMarginBorderPadding;
  nscoord startMBP;
  nscoord endMBP;
  if (MOZ_LIKELY(cbwm.ParallelAxisStartsOnSameSide(parentAxis, wm))) {
    startMBP = mbp.Start(parentAxis, cbwm);
    endMBP = mbp.End(parentAxis, cbwm);
    uint32_t i = range.mStart;
    nscoord startPos = parentSizes[i].mPosition + startMBP;
    for (auto& sz : aResult) {
      sz = parentSizes[i++];
      sz.mPosition -= startPos;
    }
  } else {
    startMBP = mbp.End(parentAxis, cbwm);
    endMBP = mbp.Start(parentAxis, cbwm);
    uint32_t i = range.mEnd - 1;
    const auto& parentEnd = parentSizes[i];
    nscoord parentEndPos = parentEnd.mPosition + parentEnd.mBase - startMBP;
    for (auto& sz : aResult) {
      sz = parentSizes[i--];
      sz.mPosition = parentEndPos - (sz.mPosition + sz.mBase);
    }
  }
  auto& startTrack = aResult[0];
  startTrack.mPosition = 0;
  startTrack.mBase -= startMBP;
  if (MOZ_UNLIKELY(startTrack.mBase < nscoord(0))) {
    // Our MBP doesn't fit in the start track.  Adjust the track position
    // to maintain track alignment with our parent.
    startTrack.mPosition = startTrack.mBase;
    startTrack.mBase = nscoord(0);
  }
  auto& endTrack = aResult.LastElement();
  endTrack.mBase -= endMBP;
  if (MOZ_UNLIKELY(endTrack.mBase < nscoord(0))) {
    endTrack.mBase = nscoord(0);
  }
}

void nsGridContainerFrame::UsedTrackSizes::ResolveTrackSizesForAxis(
    nsGridContainerFrame* aFrame, LogicalAxis aAxis, gfxContext& aRC) {
  if (mCanResolveLineRangeSize[aAxis]) {
    return;
  }
  if (!aFrame->IsSubgrid()) {
    // We can't resolve sizes in this axis at this point. aFrame is the top grid
    // container, which will store its final track sizes later once they're
    // resolved in this axis (in GridReflowInput::CalculateTrackSizesForAxis).
    // The single caller of this method only needs track sizes for
    // calculating a CB size and it will treat it as indefinite when
    // this happens.
    return;
  }
  auto* parent = aFrame->ParentGridContainerForSubgrid();
  auto* parentSizes = parent->GetUsedTrackSizes();
  if (!parentSizes) {
    parentSizes = new UsedTrackSizes();
    parent->SetProperty(UsedTrackSizes::Prop(), parentSizes);
  }
  auto* subgrid = aFrame->GetProperty(Subgrid::Prop());
  const auto parentAxis =
      subgrid->mIsOrthogonal ? GetOrthogonalAxis(aAxis) : aAxis;
  parentSizes->ResolveTrackSizesForAxis(parent, parentAxis, aRC);
  if (!parentSizes->mCanResolveLineRangeSize[parentAxis]) {
    if (aFrame->IsSubgrid(aAxis)) {
      ResolveSubgridTrackSizesForAxis(aFrame, aAxis, subgrid, aRC,
                                      NS_UNCONSTRAINEDSIZE);
    }
    return;
  }
  if (aFrame->IsSubgrid(aAxis)) {
    CopyUsedTrackSizes(mSizes[aAxis], parent, parentSizes, aFrame, subgrid,
                       aAxis);
    mCanResolveLineRangeSize[aAxis] = true;
  } else {
    const auto& range = subgrid->mArea.LineRangeForAxis(parentAxis);
    nscoord contentBoxSize = range.ToLength(parentSizes->mSizes[parentAxis]);
    auto parentWM = aFrame->GetParent()->GetWritingMode();
    contentBoxSize -=
        subgrid->mMarginBorderPadding.StartEnd(parentAxis, parentWM);
    contentBoxSize = std::max(nscoord(0), contentBoxSize);
    ResolveSubgridTrackSizesForAxis(aFrame, aAxis, subgrid, aRC,
                                    contentBoxSize);
  }
}

void nsGridContainerFrame::UsedTrackSizes::ResolveSubgridTrackSizesForAxis(
    nsGridContainerFrame* aFrame, LogicalAxis aAxis, Subgrid* aSubgrid,
    gfxContext& aRC, nscoord aContentBoxSize) {
  GridReflowInput state(aFrame, aRC);
  state.mGridItems = aSubgrid->mGridItems.Clone();
  Grid grid;
  grid.mGridColEnd = aSubgrid->mGridColEnd;
  grid.mGridRowEnd = aSubgrid->mGridRowEnd;
  state.CalculateTrackSizesForAxis(aAxis, grid, aContentBoxSize,
                                   SizingConstraint::NoConstraint);
  const auto& tracks = aAxis == eLogicalAxisInline ? state.mCols : state.mRows;
  mSizes[aAxis].Assign(tracks.mSizes);
  mCanResolveLineRangeSize[aAxis] = tracks.mCanResolveLineRangeSize;
  MOZ_ASSERT(mCanResolveLineRangeSize[aAxis]);
}

void nsGridContainerFrame::GridReflowInput::CalculateTrackSizesForAxis(
    LogicalAxis aAxis, const Grid& aGrid, nscoord aContentBoxSize,
    SizingConstraint aConstraint) {
  auto& tracks = aAxis == eLogicalAxisInline ? mCols : mRows;
  const auto& sizingFunctions =
      aAxis == eLogicalAxisInline ? mColFunctions : mRowFunctions;
  const auto& gapStyle = aAxis == eLogicalAxisInline ? mGridStyle->mColumnGap
                                                     : mGridStyle->mRowGap;
  if (tracks.mIsMasonry) {
    // See comment on nsGridContainerFrame::MasonryLayout().
    tracks.Initialize(sizingFunctions, gapStyle, 2, aContentBoxSize);
    tracks.mCanResolveLineRangeSize = true;
    return;
  }
  uint32_t gridEnd =
      aAxis == eLogicalAxisInline ? aGrid.mGridColEnd : aGrid.mGridRowEnd;
  Maybe<TrackSizingFunctions> fallbackTrackSizing;

  bool useParentGaps = false;
  const bool isSubgriddedAxis = mFrame->IsSubgrid(aAxis);
  if (MOZ_LIKELY(!isSubgriddedAxis)) {
    tracks.Initialize(sizingFunctions, gapStyle, gridEnd, aContentBoxSize);
  } else {
    tracks.mGridGap =
        nsLayoutUtils::ResolveGapToLength(gapStyle, aContentBoxSize);
    tracks.mContentBoxSize = aContentBoxSize;
    const auto* subgrid = mFrame->GetProperty(Subgrid::Prop());
    tracks.mSizes.SetLength(gridEnd);
    auto* parent = mFrame->ParentGridContainerForSubgrid();
    auto parentAxis = subgrid->mIsOrthogonal ? GetOrthogonalAxis(aAxis) : aAxis;
    const auto* parentSizes = parent->GetUsedTrackSizes();
    if (parentSizes && parentSizes->mCanResolveLineRangeSize[parentAxis]) {
      CopyUsedTrackSizes(tracks.mSizes, parent, parentSizes, mFrame, subgrid,
                         aAxis);
      useParentGaps = gapStyle.IsNormal();
    } else {
      fallbackTrackSizing.emplace(TrackSizingFunctions::ForSubgridFallback(
          mFrame, subgrid, parent, parentAxis));
      tracks.Initialize(*fallbackTrackSizing, gapStyle, gridEnd,
                        aContentBoxSize);
    }
  }

  // We run the Track Sizing Algorithm in non-subgridded axes, and in some
  // cases in a subgridded axis when our parent track sizes aren't resolved yet.
  if (MOZ_LIKELY(!isSubgriddedAxis) || fallbackTrackSizing.isSome()) {
    const size_t origGridItemCount = mGridItems.Length();
    const bool hasSubgridItems = mFrame->HasSubgridItems(aAxis);
    if (hasSubgridItems) {
      AutoTArray<GridItemInfo, 8> collectedItems;
      CollectSubgridItemsForAxis(aAxis, collectedItems);
      mGridItems.AppendElements(collectedItems);
    }
    tracks.CalculateSizes(
        *this, mGridItems,
        fallbackTrackSizing ? *fallbackTrackSizing : sizingFunctions,
        aContentBoxSize,
        aAxis == eLogicalAxisInline ? &GridArea::mCols : &GridArea::mRows,
        aConstraint);

    if (hasSubgridItems &&
        StaticPrefs::layout_css_grid_subgrid_baselines_enabled()) {
      // If any of the subgrid items are baseline-aligned, we've just recorded
      // their baseline-alignment offsets in our own copy of their GridItemInfo
      // structs. Before we get rid of those copies (via TruncateLength), we
      // have to copy these offsets back to the subgrids' versions of the
      // GridItemInfo structs.
      //
      // XXXdholbert This new behavior is behind a pref due to bug 1871719.
      CopyBaselineMetricsToSubgridItems(aAxis, origGridItemCount);
    }
    mGridItems.TruncateLength(origGridItemCount);
  }
  if (isSubgriddedAxis) {
    // XXXdholbert This is a bit hacky, but this is something that
    // tracks.CalculateSizes does internally (unconditionally, if there are
    // baseline-aligned items), and it seems like subgrids need to do it too,
    // or else they hit the "unexpected baseline subtree alignment"
    // fatal-assert when aligning their children with the baseline-alignment
    // information that they received from the outer grid.
    // (This might be entirely unnecessary? Aside from the default ::AUTO
    // value, it looks like the ::First entry is always set to ::START and
    // the ::Last entry is always set to ::END...)
    tracks.mBaselineSubtreeAlign[BaselineSharingGroup::First] =
        StyleAlignFlags::START;
    tracks.mBaselineSubtreeAlign[BaselineSharingGroup::Last] =
        StyleAlignFlags::END;
  }

  if (aContentBoxSize != NS_UNCONSTRAINEDSIZE) {
    auto alignment = mGridStyle->UsedContentAlignment(tracks.mAxis);
    tracks.AlignJustifyContent(mGridStyle, alignment, mWM, aContentBoxSize,
                               isSubgriddedAxis);
  } else if (!useParentGaps) {
    const nscoord gridGap = tracks.mGridGap;
    nscoord pos = 0;
    for (TrackSize& sz : tracks.mSizes) {
      sz.mPosition = pos;
      pos += sz.mBase + gridGap;
    }
  }

  if (aConstraint == SizingConstraint::NoConstraint &&
      (mFrame->HasSubgridItems() || mFrame->IsSubgrid())) {
    mFrame->StoreUsedTrackSizes(aAxis, tracks.mSizes);
  }

  // positions and sizes are now final
  tracks.mCanResolveLineRangeSize = true;
}

void nsGridContainerFrame::GridReflowInput::CalculateTrackSizes(
    const Grid& aGrid, const LogicalSize& aContentBox,
    SizingConstraint aConstraint) {
  CalculateTrackSizesForAxis(eLogicalAxisInline, aGrid, aContentBox.ISize(mWM),
                             aConstraint);
  CalculateTrackSizesForAxis(eLogicalAxisBlock, aGrid, aContentBox.BSize(mWM),
                             aConstraint);
}

// Align an item's margin box in its aAxis inside aCBSize.
static void AlignJustifySelf(StyleAlignFlags aAlignment, LogicalAxis aAxis,
                             AlignJustifyFlags aFlags, nscoord aBaselineAdjust,
                             nscoord aCBSize, const ReflowInput& aRI,
                             const LogicalSize& aChildSize,
                             LogicalPoint* aPos) {
  MOZ_ASSERT(aAlignment != StyleAlignFlags::AUTO,
             "unexpected 'auto' "
             "computed value for normal flow grid item");

  // NOTE: this is the resulting frame offset (border box).
  nscoord offset = CSSAlignUtils::AlignJustifySelf(
      aAlignment, aAxis, aFlags, aBaselineAdjust, aCBSize, aRI, aChildSize);

  // Set the position (aPos) for the requested alignment.
  if (offset != 0) {
    WritingMode wm = aRI.GetWritingMode();
    nscoord& pos = aAxis == eLogicalAxisBlock ? aPos->B(wm) : aPos->I(wm);
    pos += MOZ_LIKELY(aFlags & AlignJustifyFlags::SameSide) ? offset : -offset;
  }
}

static void AlignSelf(const nsGridContainerFrame::GridItemInfo& aGridItem,
                      StyleAlignFlags aAlignSelf, nscoord aCBSize,
                      const WritingMode aCBWM, const ReflowInput& aRI,
                      const LogicalSize& aSize, AlignJustifyFlags aFlags,
                      LogicalPoint* aPos) {
  AlignJustifyFlags flags = aFlags;
  if (aAlignSelf & StyleAlignFlags::SAFE) {
    flags |= AlignJustifyFlags::OverflowSafe;
  }
  aAlignSelf &= ~StyleAlignFlags::FLAG_BITS;

  WritingMode childWM = aRI.GetWritingMode();
  if (aCBWM.ParallelAxisStartsOnSameSide(eLogicalAxisBlock, childWM)) {
    flags |= AlignJustifyFlags::SameSide;
  }

  // Grid's 'align-self' axis is never parallel to the container's inline axis.
  if (aAlignSelf == StyleAlignFlags::LEFT ||
      aAlignSelf == StyleAlignFlags::RIGHT) {
    aAlignSelf = StyleAlignFlags::START;
  }
  if (MOZ_LIKELY(aAlignSelf == StyleAlignFlags::NORMAL)) {
    aAlignSelf = StyleAlignFlags::STRETCH;
  }

  nscoord baselineAdjust = 0;
  if (aAlignSelf == StyleAlignFlags::BASELINE ||
      aAlignSelf == StyleAlignFlags::LAST_BASELINE) {
    aAlignSelf = aGridItem.GetSelfBaseline(aAlignSelf, eLogicalAxisBlock,
                                           &baselineAdjust);
  }

  bool isOrthogonal = aCBWM.IsOrthogonalTo(childWM);
  LogicalAxis axis = isOrthogonal ? eLogicalAxisInline : eLogicalAxisBlock;
  AlignJustifySelf(aAlignSelf, axis, flags, baselineAdjust, aCBSize, aRI, aSize,
                   aPos);
}

static void JustifySelf(const nsGridContainerFrame::GridItemInfo& aGridItem,
                        StyleAlignFlags aJustifySelf, nscoord aCBSize,
                        const WritingMode aCBWM, const ReflowInput& aRI,
                        const LogicalSize& aSize, AlignJustifyFlags aFlags,
                        LogicalPoint* aPos) {
  AlignJustifyFlags flags = aFlags;
  if (aJustifySelf & StyleAlignFlags::SAFE) {
    flags |= AlignJustifyFlags::OverflowSafe;
  }
  aJustifySelf &= ~StyleAlignFlags::FLAG_BITS;

  WritingMode childWM = aRI.GetWritingMode();
  if (aCBWM.ParallelAxisStartsOnSameSide(eLogicalAxisInline, childWM)) {
    flags |= AlignJustifyFlags::SameSide;
  }

  if (MOZ_LIKELY(aJustifySelf == StyleAlignFlags::NORMAL)) {
    aJustifySelf = StyleAlignFlags::STRETCH;
  }

  nscoord baselineAdjust = 0;
  // Grid's 'justify-self' axis is always parallel to the container's inline
  // axis, so justify-self:left|right always applies.
  if (aJustifySelf == StyleAlignFlags::LEFT) {
    aJustifySelf =
        aCBWM.IsBidiLTR() ? StyleAlignFlags::START : StyleAlignFlags::END;
  } else if (aJustifySelf == StyleAlignFlags::RIGHT) {
    aJustifySelf =
        aCBWM.IsBidiLTR() ? StyleAlignFlags::END : StyleAlignFlags::START;
  } else if (aJustifySelf == StyleAlignFlags::BASELINE ||
             aJustifySelf == StyleAlignFlags::LAST_BASELINE) {
    aJustifySelf = aGridItem.GetSelfBaseline(aJustifySelf, eLogicalAxisInline,
                                             &baselineAdjust);
  }

  bool isOrthogonal = aCBWM.IsOrthogonalTo(childWM);
  LogicalAxis axis = isOrthogonal ? eLogicalAxisBlock : eLogicalAxisInline;
  AlignJustifySelf(aJustifySelf, axis, flags, baselineAdjust, aCBSize, aRI,
                   aSize, aPos);
}

static StyleAlignFlags GetAlignJustifyValue(StyleAlignFlags aAlignment,
                                            const WritingMode aWM,
                                            const bool aIsAlign,
                                            bool* aOverflowSafe) {
  *aOverflowSafe = bool(aAlignment & StyleAlignFlags::SAFE);
  aAlignment &= ~StyleAlignFlags::FLAG_BITS;

  // Map some alignment values to 'start' / 'end'.
  if (aAlignment == StyleAlignFlags::LEFT ||
      aAlignment == StyleAlignFlags::RIGHT) {
    if (aIsAlign) {
      // Grid's 'align-content' axis is never parallel to the inline axis.
      return StyleAlignFlags::START;
    }
    bool isStart = aWM.IsBidiLTR() == (aAlignment == StyleAlignFlags::LEFT);
    return isStart ? StyleAlignFlags::START : StyleAlignFlags::END;
  }
  if (aAlignment == StyleAlignFlags::FLEX_START) {
    return StyleAlignFlags::START;  // same as 'start' for Grid
  }
  if (aAlignment == StyleAlignFlags::FLEX_END) {
    return StyleAlignFlags::END;  // same as 'end' for Grid
  }
  return aAlignment;
}

static Maybe<StyleAlignFlags> GetAlignJustifyFallbackIfAny(
    const StyleContentDistribution& aDistribution, const WritingMode aWM,
    const bool aIsAlign, bool* aOverflowSafe) {
  // TODO: Eventually this should look at aDistribution's fallback alignment,
  // see https://github.com/w3c/csswg-drafts/issues/1002.
  if (aDistribution.primary == StyleAlignFlags::STRETCH ||
      aDistribution.primary == StyleAlignFlags::SPACE_BETWEEN) {
    return Some(StyleAlignFlags::START);
  }
  if (aDistribution.primary == StyleAlignFlags::SPACE_AROUND ||
      aDistribution.primary == StyleAlignFlags::SPACE_EVENLY) {
    return Some(StyleAlignFlags::CENTER);
  }
  return Nothing();
}

//----------------------------------------------------------------------

// Frame class boilerplate
// =======================

NS_QUERYFRAME_HEAD(nsGridContainerFrame)
  NS_QUERYFRAME_ENTRY(nsGridContainerFrame)
NS_QUERYFRAME_TAIL_INHERITING(nsContainerFrame)

NS_IMPL_FRAMEARENA_HELPERS(nsGridContainerFrame)

nsContainerFrame* NS_NewGridContainerFrame(PresShell* aPresShell,
                                           ComputedStyle* aStyle) {
  return new (aPresShell)
      nsGridContainerFrame(aStyle, aPresShell->GetPresContext());
}

//----------------------------------------------------------------------

// nsGridContainerFrame Method Implementations
// ===========================================

/*static*/ const nsRect& nsGridContainerFrame::GridItemCB(nsIFrame* aChild) {
  MOZ_ASSERT(aChild->IsAbsolutelyPositioned());
  nsRect* cb = aChild->GetProperty(GridItemContainingBlockRect());
  MOZ_ASSERT(cb,
             "this method must only be called on grid items, and the grid "
             "container should've reflowed this item by now and set up cb");
  return *cb;
}

void nsGridContainerFrame::AddImplicitNamedAreasInternal(
    LineNameList& aNameList,
    nsGridContainerFrame::ImplicitNamedAreas*& aAreas) {
  for (const auto& nameIdent : aNameList.AsSpan()) {
    nsAtom* name = nameIdent.AsAtom();
    uint32_t indexOfSuffix;
    if (Grid::IsNameWithStartSuffix(name, &indexOfSuffix) ||
        Grid::IsNameWithEndSuffix(name, &indexOfSuffix)) {
      // Extract the name that was found earlier.
      nsDependentSubstring areaName(nsDependentAtomString(name), 0,
                                    indexOfSuffix);

      // Lazily create the ImplicitNamedAreas.
      if (!aAreas) {
        aAreas = new nsGridContainerFrame::ImplicitNamedAreas;
        SetProperty(nsGridContainerFrame::ImplicitNamedAreasProperty(), aAreas);
      }

      RefPtr<nsAtom> name = NS_Atomize(areaName);
      auto addPtr = aAreas->lookupForAdd(name);
      if (!addPtr) {
        if (!aAreas->add(addPtr, name,
                         nsGridContainerFrame::NamedArea{
                             StyleAtom(do_AddRef(name)), {0, 0}, {0, 0}})) {
          MOZ_CRASH("OOM while adding grid name lists");
        }
      }
    }
  }
}

void nsGridContainerFrame::AddImplicitNamedAreas(
    Span<LineNameList> aLineNameLists) {
  // http://dev.w3.org/csswg/css-grid/#implicit-named-areas
  // Note: recording these names for fast lookup later is just an optimization.
  ImplicitNamedAreas* areas = GetImplicitNamedAreas();
  const uint32_t len = std::min(aLineNameLists.Length(), size_t(kMaxLine));
  for (uint32_t i = 0; i < len; ++i) {
    AddImplicitNamedAreasInternal(aLineNameLists[i], areas);
  }
}

void nsGridContainerFrame::AddImplicitNamedAreas(
    Span<StyleLineNameListValue> aLineNameList) {
  // http://dev.w3.org/csswg/css-grid/#implicit-named-areas
  // Note: recording these names for fast lookup later is just an optimization.
  uint32_t count = 0;
  ImplicitNamedAreas* areas = GetImplicitNamedAreas();
  for (const auto& nameList : aLineNameList) {
    if (nameList.IsRepeat()) {
      for (const auto& repeatNameList :
           nameList.AsRepeat().line_names.AsSpan()) {
        AddImplicitNamedAreasInternal(repeatNameList, areas);
        ++count;
      }
    } else {
      MOZ_ASSERT(nameList.IsLineNames());
      AddImplicitNamedAreasInternal(nameList.AsLineNames(), areas);
      ++count;
    }

    if (count >= size_t(kMaxLine)) {
      break;
    }
  }
}

void nsGridContainerFrame::InitImplicitNamedAreas(
    const nsStylePosition* aStyle) {
  ImplicitNamedAreas* areas = GetImplicitNamedAreas();
  if (areas) {
    // Clear it, but reuse the hashtable itself for now.  We'll remove it
    // below if it isn't needed anymore.
    areas->clear();
  }
  auto Add = [&](const GridTemplate& aTemplate, bool aIsSubgrid) {
    AddImplicitNamedAreas(aTemplate.LineNameLists(aIsSubgrid));
    for (auto& value : aTemplate.TrackListValues()) {
      if (value.IsTrackRepeat()) {
        AddImplicitNamedAreas(value.AsTrackRepeat().line_names.AsSpan());
      }
    }

    if (aIsSubgrid && aTemplate.IsSubgrid()) {
      // For subgrid, |aTemplate.LineNameLists(aIsSubgrid)| returns an empty
      // list so we have to manually add each item.
      AddImplicitNamedAreas(aTemplate.AsSubgrid()->line_names.AsSpan());
    }
  };
  Add(aStyle->mGridTemplateColumns, IsSubgrid(eLogicalAxisInline));
  Add(aStyle->mGridTemplateRows, IsSubgrid(eLogicalAxisBlock));
  if (areas && areas->count() == 0) {
    RemoveProperty(ImplicitNamedAreasProperty());
  }
}

int32_t nsGridContainerFrame::Grid::ResolveLine(
    const StyleGridLine& aLine, int32_t aNth, uint32_t aFromIndex,
    const LineNameMap& aNameMap, LogicalSide aSide, uint32_t aExplicitGridEnd,
    const nsStylePosition* aStyle) {
  MOZ_ASSERT(!aLine.IsAuto());
  int32_t line = 0;
  if (aLine.LineName()->IsEmpty()) {
    MOZ_ASSERT(aNth != 0, "css-grid 9.2: <integer> must not be zero.");
    line = int32_t(aFromIndex) + aNth;
  } else {
    if (aNth == 0) {
      // <integer> was omitted; treat it as 1.
      aNth = 1;
    }
    bool isNameOnly = !aLine.is_span && aLine.line_num == 0;
    if (isNameOnly) {
      AutoTArray<uint32_t, 16> implicitLines;
      aNameMap.FindNamedAreas(aLine.ident.AsAtom(), aSide, implicitLines);
      if (!implicitLines.IsEmpty() ||
          aNameMap.HasImplicitNamedArea(aLine.LineName())) {
        // aName is a named area - look for explicit lines named
        // <name>-start/-end depending on which side we're resolving.
        // http://dev.w3.org/csswg/css-grid/#grid-placement-slot
        nsAutoString lineName(nsDependentAtomString(aLine.LineName()));
        if (IsStart(aSide)) {
          lineName.AppendLiteral("-start");
        } else {
          lineName.AppendLiteral("-end");
        }
        RefPtr<nsAtom> name = NS_Atomize(lineName);
        line = aNameMap.FindNamedLine(name, &aNth, aFromIndex, implicitLines);
      }
    }

    if (line == 0) {
      // If LineName() ends in -start/-end, try the prefix as a named area.
      AutoTArray<uint32_t, 16> implicitLines;
      uint32_t index;
      bool useStart = IsNameWithStartSuffix(aLine.LineName(), &index);
      if (useStart || IsNameWithEndSuffix(aLine.LineName(), &index)) {
        auto side = MakeLogicalSide(
            GetAxis(aSide), useStart ? eLogicalEdgeStart : eLogicalEdgeEnd);
        RefPtr<nsAtom> name = NS_Atomize(nsDependentSubstring(
            nsDependentAtomString(aLine.LineName()), 0, index));
        aNameMap.FindNamedAreas(name, side, implicitLines);
      }
      line = aNameMap.FindNamedLine(aLine.LineName(), &aNth, aFromIndex,
                                    implicitLines);
    }

    if (line == 0) {
      MOZ_ASSERT(aNth != 0, "we found all N named lines but 'line' is zero!");
      int32_t edgeLine;
      if (aLine.is_span) {
        // http://dev.w3.org/csswg/css-grid/#grid-placement-span-int
        // 'span <custom-ident> N'
        edgeLine = IsStart(aSide) ? 1 : aExplicitGridEnd;
      } else {
        // http://dev.w3.org/csswg/css-grid/#grid-placement-int
        // '<custom-ident> N'
        edgeLine = aNth < 0 ? 1 : aExplicitGridEnd;
      }
      // "If not enough lines with that name exist, all lines in the implicit
      // grid are assumed to have that name..."
      line = edgeLine + aNth;
    }
  }
  // Note: at this point, 'line' might be outside of aNameMap's allowed range,
  // [mClampMinLin, mClampMaxLine]. This is fine; we'll clamp once we've
  // resolved *both* the start and end line -- in particular, we clamp in
  // ResolveLineRange(). If we clamped here, it'd be premature -- if one line
  // is definite and the other is specified as a span to some named line
  // (i.e. we need to perform a name-search that starts from the definite
  // line), then it matters whether we clamp the definite line before or after
  // that search. See https://bugzilla.mozilla.org/show_bug.cgi?id=1800566#c6
  // for more.
  return line;
}

nsGridContainerFrame::Grid::LinePair
nsGridContainerFrame::Grid::ResolveLineRangeHelper(
    const StyleGridLine& aStart, const StyleGridLine& aEnd,
    const LineNameMap& aNameMap, LogicalAxis aAxis, uint32_t aExplicitGridEnd,
    const nsStylePosition* aStyle) {
  MOZ_ASSERT(int32_t(kAutoLine) > kMaxLine);

  if (aStart.is_span) {
    if (aEnd.is_span || aEnd.IsAuto()) {
      // http://dev.w3.org/csswg/css-grid/#grid-placement-errors
      if (aStart.LineName()->IsEmpty()) {
        // span <integer> / span *
        // span <integer> / auto
        return LinePair(kAutoLine, aStart.line_num);
      }
      // span <custom-ident> / span *
      // span <custom-ident> / auto
      return LinePair(kAutoLine, 1);  // XXX subgrid explicit size instead of 1?
    }

    uint32_t from = aEnd.line_num < 0 ? aExplicitGridEnd + 1 : 0;
    auto end = ResolveLine(aEnd, aEnd.line_num, from, aNameMap,
                           MakeLogicalSide(aAxis, eLogicalEdgeEnd),
                           aExplicitGridEnd, aStyle);
    int32_t span = aStart.line_num == 0 ? 1 : aStart.line_num;
    if (end <= 1) {
      // The end is at or before the first explicit line, thus all lines before
      // it match <custom-ident> since they're implicit.
      int32_t start = std::max(end - span, aNameMap.mClampMinLine);
      return LinePair(start, end);
    }
    auto start = ResolveLine(aStart, -span, end, aNameMap,
                             MakeLogicalSide(aAxis, eLogicalEdgeStart),
                             aExplicitGridEnd, aStyle);
    return LinePair(start, end);
  }

  int32_t start = kAutoLine;
  if (aStart.IsAuto()) {
    if (aEnd.IsAuto()) {
      // auto / auto
      return LinePair(start, 1);  // XXX subgrid explicit size instead of 1?
    }
    if (aEnd.is_span) {
      if (aEnd.LineName()->IsEmpty()) {
        // auto / span <integer>
        MOZ_ASSERT(aEnd.line_num != 0);
        return LinePair(start, aEnd.line_num);
      }
      // http://dev.w3.org/csswg/css-grid/#grid-placement-errors
      // auto / span <custom-ident>
      return LinePair(start, 1);  // XXX subgrid explicit size instead of 1?
    }
  } else {
    uint32_t from = aStart.line_num < 0 ? aExplicitGridEnd + 1 : 0;
    start = ResolveLine(aStart, aStart.line_num, from, aNameMap,
                        MakeLogicalSide(aAxis, eLogicalEdgeStart),
                        aExplicitGridEnd, aStyle);
    if (aEnd.IsAuto()) {
      // A "definite line / auto" should resolve the auto to 'span 1'.
      // The error handling in ResolveLineRange will make that happen and also
      // clamp the end line correctly if we return "start / start".
      return LinePair(start, start);
    }
  }

  uint32_t from;
  int32_t nth = aEnd.line_num == 0 ? 1 : aEnd.line_num;
  if (aEnd.is_span) {
    if (MOZ_UNLIKELY(start < 0)) {
      if (aEnd.LineName()->IsEmpty()) {
        return LinePair(start, start + nth);
      }
      from = 0;
    } else {
      if (start >= int32_t(aExplicitGridEnd)) {
        // The start is at or after the last explicit line, thus all lines
        // after it match <custom-ident> since they're implicit.
        return LinePair(start, std::min(start + nth, aNameMap.mClampMaxLine));
      }
      from = start;
    }
  } else {
    from = aEnd.line_num < 0 ? aExplicitGridEnd + 1 : 0;
  }
  auto end = ResolveLine(aEnd, nth, from, aNameMap,
                         MakeLogicalSide(aAxis, eLogicalEdgeEnd),
                         aExplicitGridEnd, aStyle);
  if (start == int32_t(kAutoLine)) {
    // auto / definite line
    start = std::max(aNameMap.mClampMinLine, end - 1);
  }
  return LinePair(start, end);
}

nsGridContainerFrame::LineRange nsGridContainerFrame::Grid::ResolveLineRange(
    const StyleGridLine& aStart, const StyleGridLine& aEnd,
    const LineNameMap& aNameMap, LogicalAxis aAxis, uint32_t aExplicitGridEnd,
    const nsStylePosition* aStyle) {
  LinePair r = ResolveLineRangeHelper(aStart, aEnd, aNameMap, aAxis,
                                      aExplicitGridEnd, aStyle);
  MOZ_ASSERT(r.second != int32_t(kAutoLine));

  if (r.first == int32_t(kAutoLine)) {
    // r.second is a span, clamp it to aNameMap.mClampMaxLine - 1 so that
    // the returned range has a HypotheticalEnd <= aNameMap.mClampMaxLine.
    // http://dev.w3.org/csswg/css-grid/#overlarge-grids
    r.second = std::min(r.second, aNameMap.mClampMaxLine - 1);
  } else {
    // Clamp the lines to be within our limits, per
    // https://www.w3.org/TR/css-grid-2/#overlarge-grids
    // Note that our limits here might come from the [kMinLine, kMaxLine]
    // extremes; or, they might just be the bounds of a subgrid's explicit
    // grid. We use the same clamping approach either way, per
    // https://www.w3.org/TR/css-grid-2/#subgrid-implicit ("using the same
    // procedure as for clamping placement in an overly-large grid").
    //
    // Note that these two clamped() assignments might collapse our range to
    // have both edges pointing at the same line (spanning 0 tracks); this
    // might happen here if e.g. r.first were mClampMaxLine, and r.second gets
    // clamped from some higher number down to mClampMaxLine. We'll handle this
    // by shifting the inner line (r.first in this hypothetical) inwards by 1,
    // in the #grid-placement-errors section; that achieves the outcome of
    // the #overlarge-grids clamping spec text that says "its span must be
    // truncated to 1" when clamping an item that was completely outside the
    // limits.
    r.first = clamped(r.first, aNameMap.mClampMinLine, aNameMap.mClampMaxLine);
    r.second =
        clamped(r.second, aNameMap.mClampMinLine, aNameMap.mClampMaxLine);

    // Handle grid placement errors.
    // http://dev.w3.org/csswg/css-grid/#grid-placement-errors
    if (r.first > r.second) {
      std::swap(r.first, r.second);
    } else if (r.first == r.second) {
      // (This is #grid-placement-errors fixup, but it's also where we ensure
      // that any #overlarge-grids fixup that we did above will end up
      // truncating the range to a span of 1 rather than 0 -- i.e. sliding
      // inwards if needed.)
      if (MOZ_UNLIKELY(r.first == aNameMap.mClampMaxLine)) {
        r.first = aNameMap.mClampMaxLine - 1;
      }
      r.second = r.first + 1;
    }
  }
  return LineRange(r.first, r.second);
}

nsGridContainerFrame::GridArea nsGridContainerFrame::Grid::PlaceDefinite(
    nsIFrame* aChild, const LineNameMap& aColLineNameMap,
    const LineNameMap& aRowLineNameMap, const nsStylePosition* aStyle) {
  const nsStylePosition* itemStyle = aChild->StylePosition();
  return GridArea(
      ResolveLineRange(itemStyle->mGridColumnStart, itemStyle->mGridColumnEnd,
                       aColLineNameMap, eLogicalAxisInline, mExplicitGridColEnd,
                       aStyle),
      ResolveLineRange(itemStyle->mGridRowStart, itemStyle->mGridRowEnd,
                       aRowLineNameMap, eLogicalAxisBlock, mExplicitGridRowEnd,
                       aStyle));
}

nsGridContainerFrame::LineRange
nsGridContainerFrame::Grid::ResolveAbsPosLineRange(
    const StyleGridLine& aStart, const StyleGridLine& aEnd,
    const LineNameMap& aNameMap, LogicalAxis aAxis, uint32_t aExplicitGridEnd,
    int32_t aGridStart, int32_t aGridEnd, const nsStylePosition* aStyle) {
  if (aStart.IsAuto()) {
    if (aEnd.IsAuto()) {
      return LineRange(kAutoLine, kAutoLine);
    }
    uint32_t from = aEnd.line_num < 0 ? aExplicitGridEnd + 1 : 0;
    int32_t end = ResolveLine(aEnd, aEnd.line_num, from, aNameMap,
                              MakeLogicalSide(aAxis, eLogicalEdgeEnd),
                              aExplicitGridEnd, aStyle);
    if (aEnd.is_span) {
      ++end;
    }
    // A line outside the existing grid is treated as 'auto' for abs.pos (10.1).
    end = AutoIfOutside(end, aGridStart, aGridEnd);
    return LineRange(kAutoLine, end);
  }

  if (aEnd.IsAuto()) {
    uint32_t from = aStart.line_num < 0 ? aExplicitGridEnd + 1 : 0;
    int32_t start = ResolveLine(aStart, aStart.line_num, from, aNameMap,
                                MakeLogicalSide(aAxis, eLogicalEdgeStart),
                                aExplicitGridEnd, aStyle);
    if (aStart.is_span) {
      start = std::max(aGridEnd - start, aGridStart);
    }
    start = AutoIfOutside(start, aGridStart, aGridEnd);
    return LineRange(start, kAutoLine);
  }

  LineRange r =
      ResolveLineRange(aStart, aEnd, aNameMap, aAxis, aExplicitGridEnd, aStyle);
  if (r.IsAuto()) {
    MOZ_ASSERT(aStart.is_span && aEnd.is_span,
               "span / span is the only case "
               "leading to IsAuto here -- we dealt with the other cases above");
    // The second span was ignored per 9.2.1.  For abs.pos., 10.1 says that this
    // case should result in "auto / auto" unlike normal flow grid items.
    return LineRange(kAutoLine, kAutoLine);
  }

  return LineRange(AutoIfOutside(r.mUntranslatedStart, aGridStart, aGridEnd),
                   AutoIfOutside(r.mUntranslatedEnd, aGridStart, aGridEnd));
}

nsGridContainerFrame::GridArea nsGridContainerFrame::Grid::PlaceAbsPos(
    nsIFrame* aChild, const LineNameMap& aColLineNameMap,
    const LineNameMap& aRowLineNameMap, const nsStylePosition* aStyle) {
  const nsStylePosition* itemStyle = aChild->StylePosition();
  int32_t gridColStart = 1 - mExplicitGridOffsetCol;
  int32_t gridRowStart = 1 - mExplicitGridOffsetRow;
  return GridArea(ResolveAbsPosLineRange(
                      itemStyle->mGridColumnStart, itemStyle->mGridColumnEnd,
                      aColLineNameMap, eLogicalAxisInline, mExplicitGridColEnd,
                      gridColStart, mGridColEnd, aStyle),
                  ResolveAbsPosLineRange(
                      itemStyle->mGridRowStart, itemStyle->mGridRowEnd,
                      aRowLineNameMap, eLogicalAxisBlock, mExplicitGridRowEnd,
                      gridRowStart, mGridRowEnd, aStyle));
}

uint32_t nsGridContainerFrame::Grid::FindAutoCol(uint32_t aStartCol,
                                                 uint32_t aLockedRow,
                                                 const GridArea* aArea) const {
  const uint32_t extent = aArea->mCols.Extent();
  const uint32_t iStart = aLockedRow;
  const uint32_t iEnd = iStart + aArea->mRows.Extent();
  uint32_t candidate = aStartCol;
  for (uint32_t i = iStart; i < iEnd;) {
    if (i >= mCellMap.mCells.Length()) {
      break;
    }
    const nsTArray<CellMap::Cell>& cellsInRow = mCellMap.mCells[i];
    const uint32_t len = cellsInRow.Length();
    const uint32_t lastCandidate = candidate;
    // Find the first gap in the current row that's at least 'extent' wide.
    // ('gap' tracks how wide the current column gap is.)
    for (uint32_t j = candidate, gap = 0; j < len && gap < extent; ++j) {
      if (!cellsInRow[j].mIsOccupied) {
        ++gap;
        continue;
      }
      candidate = j + 1;
      gap = 0;
    }
    if (lastCandidate < candidate && i != iStart) {
      // Couldn't fit 'extent' tracks at 'lastCandidate' here so we must
      // restart from the beginning with the new 'candidate'.
      i = iStart;
    } else {
      ++i;
    }
  }
  return candidate;
}

void nsGridContainerFrame::Grid::PlaceAutoCol(uint32_t aStartCol,
                                              GridArea* aArea,
                                              uint32_t aClampMaxColLine) const {
  MOZ_ASSERT(aArea->mRows.IsDefinite() && aArea->mCols.IsAuto());
  uint32_t col = FindAutoCol(aStartCol, aArea->mRows.mStart, aArea);
  aArea->mCols.ResolveAutoPosition(col, aClampMaxColLine);
  MOZ_ASSERT(aArea->IsDefinite());
}

uint32_t nsGridContainerFrame::Grid::FindAutoRow(uint32_t aLockedCol,
                                                 uint32_t aStartRow,
                                                 const GridArea* aArea) const {
  const uint32_t extent = aArea->mRows.Extent();
  const uint32_t jStart = aLockedCol;
  const uint32_t jEnd = jStart + aArea->mCols.Extent();
  const uint32_t iEnd = mCellMap.mCells.Length();
  uint32_t candidate = aStartRow;
  // Find the first gap in the rows that's at least 'extent' tall.
  // ('gap' tracks how tall the current row gap is.)
  for (uint32_t i = candidate, gap = 0; i < iEnd && gap < extent; ++i) {
    ++gap;  // tentative, but we may reset it below if a column is occupied
    const nsTArray<CellMap::Cell>& cellsInRow = mCellMap.mCells[i];
    const uint32_t clampedJEnd = std::min<uint32_t>(jEnd, cellsInRow.Length());
    // Check if the current row is unoccupied from jStart to jEnd.
    for (uint32_t j = jStart; j < clampedJEnd; ++j) {
      if (cellsInRow[j].mIsOccupied) {
        // Couldn't fit 'extent' rows at 'candidate' here; we hit something
        // at row 'i'.  So, try the row after 'i' as our next candidate.
        candidate = i + 1;
        gap = 0;
        break;
      }
    }
  }
  return candidate;
}

void nsGridContainerFrame::Grid::PlaceAutoRow(uint32_t aStartRow,
                                              GridArea* aArea,
                                              uint32_t aClampMaxRowLine) const {
  MOZ_ASSERT(aArea->mCols.IsDefinite() && aArea->mRows.IsAuto());
  uint32_t row = FindAutoRow(aArea->mCols.mStart, aStartRow, aArea);
  aArea->mRows.ResolveAutoPosition(row, aClampMaxRowLine);
  MOZ_ASSERT(aArea->IsDefinite());
}

void nsGridContainerFrame::Grid::PlaceAutoAutoInRowOrder(
    uint32_t aStartCol, uint32_t aStartRow, GridArea* aArea,
    uint32_t aClampMaxColLine, uint32_t aClampMaxRowLine) const {
  MOZ_ASSERT(aArea->mCols.IsAuto() && aArea->mRows.IsAuto());
  const uint32_t colExtent = aArea->mCols.Extent();
  const uint32_t gridRowEnd = mGridRowEnd;
  const uint32_t gridColEnd = mGridColEnd;
  uint32_t col = aStartCol;
  uint32_t row = aStartRow;
  for (; row < gridRowEnd; ++row) {
    col = FindAutoCol(col, row, aArea);
    if (col + colExtent <= gridColEnd) {
      break;
    }
    col = 0;
  }
  MOZ_ASSERT(row < gridRowEnd || col == 0,
             "expected column 0 for placing in a new row");
  aArea->mCols.ResolveAutoPosition(col, aClampMaxColLine);
  aArea->mRows.ResolveAutoPosition(row, aClampMaxRowLine);
  MOZ_ASSERT(aArea->IsDefinite());
}

void nsGridContainerFrame::Grid::PlaceAutoAutoInColOrder(
    uint32_t aStartCol, uint32_t aStartRow, GridArea* aArea,
    uint32_t aClampMaxColLine, uint32_t aClampMaxRowLine) const {
  MOZ_ASSERT(aArea->mCols.IsAuto() && aArea->mRows.IsAuto());
  const uint32_t rowExtent = aArea->mRows.Extent();
  const uint32_t gridRowEnd = mGridRowEnd;
  const uint32_t gridColEnd = mGridColEnd;
  uint32_t col = aStartCol;
  uint32_t row = aStartRow;
  for (; col < gridColEnd; ++col) {
    row = FindAutoRow(col, row, aArea);
    if (row + rowExtent <= gridRowEnd) {
      break;
    }
    row = 0;
  }
  MOZ_ASSERT(col < gridColEnd || row == 0,
             "expected row 0 for placing in a new column");
  aArea->mCols.ResolveAutoPosition(col, aClampMaxColLine);
  aArea->mRows.ResolveAutoPosition(row, aClampMaxRowLine);
  MOZ_ASSERT(aArea->IsDefinite());
}

template <typename IsEmptyFuncT>
Maybe<nsTArray<uint32_t>>
nsGridContainerFrame::Grid::CalculateAdjustForAutoFitElements(
    uint32_t* const aOutNumEmptyLines, TrackSizingFunctions& aSizingFunctions,
    uint32_t aNumGridLines, IsEmptyFuncT aIsEmptyFunc) {
  Maybe<nsTArray<uint32_t>> trackAdjust;
  uint32_t& numEmptyLines = *aOutNumEmptyLines;
  numEmptyLines = 0;
  if (aSizingFunctions.NumRepeatTracks() > 0) {
    MOZ_ASSERT(aSizingFunctions.mHasRepeatAuto);
    // Since this loop is concerned with just the repeat tracks, we
    // iterate from 0..NumRepeatTracks() which is the natural range of
    // mRemoveRepeatTracks. This means we have to add
    // (mExplicitGridOffset + mRepeatAutoStart) to get a zero-based
    // index for arrays like mCellMap/aIsEmptyFunc and trackAdjust. We'll then
    // fill out the trackAdjust array for all the remaining lines.
    const uint32_t repeatStart = (aSizingFunctions.mExplicitGridOffset +
                                  aSizingFunctions.mRepeatAutoStart);
    const uint32_t numRepeats = aSizingFunctions.NumRepeatTracks();
    for (uint32_t i = 0; i < numRepeats; ++i) {
      if (numEmptyLines) {
        MOZ_ASSERT(trackAdjust.isSome());
        (*trackAdjust)[repeatStart + i] = numEmptyLines;
      }
      if (aIsEmptyFunc(repeatStart + i)) {
        ++numEmptyLines;
        if (trackAdjust.isNothing()) {
          trackAdjust.emplace(aNumGridLines);
          trackAdjust->SetLength(aNumGridLines);
          PodZero(trackAdjust->Elements(), trackAdjust->Length());
        }

        aSizingFunctions.mRemovedRepeatTracks[i] = true;
      }
    }
    // Fill out the trackAdjust array for all the tracks after the repeats.
    if (numEmptyLines) {
      for (uint32_t line = repeatStart + numRepeats; line < aNumGridLines;
           ++line) {
        (*trackAdjust)[line] = numEmptyLines;
      }
    }
  }

  return trackAdjust;
}

void nsGridContainerFrame::Grid::SubgridPlaceGridItems(
    GridReflowInput& aParentState, Grid* aParentGrid,
    const GridItemInfo& aGridItem) {
  MOZ_ASSERT(aGridItem.mArea.IsDefinite() ||
                 aGridItem.mFrame->HasAnyStateBits(NS_FRAME_OUT_OF_FLOW),
             "the subgrid's lines should be resolved by now");
  if (aGridItem.IsSubgrid(eLogicalAxisInline)) {
    aParentState.mFrame->AddStateBits(NS_STATE_GRID_HAS_COL_SUBGRID_ITEM);
  }
  if (aGridItem.IsSubgrid(eLogicalAxisBlock)) {
    aParentState.mFrame->AddStateBits(NS_STATE_GRID_HAS_ROW_SUBGRID_ITEM);
  }
  auto* childGrid = aGridItem.SubgridFrame();
  const auto* pos = childGrid->StylePosition();
  childGrid->NormalizeChildLists();
  GridReflowInput state(childGrid, aParentState.mRenderingContext);
  childGrid->InitImplicitNamedAreas(pos);

  const bool isOrthogonal = aParentState.mWM.IsOrthogonalTo(state.mWM);
  // Record the subgrid's GridArea in a frame property.
  auto* subgrid = childGrid->GetProperty(Subgrid::Prop());
  if (!subgrid) {
    subgrid = new Subgrid(aGridItem.mArea, isOrthogonal, aParentState.mWM);
    childGrid->SetProperty(Subgrid::Prop(), subgrid);
  } else {
    subgrid->mArea = aGridItem.mArea;
    subgrid->mIsOrthogonal = isOrthogonal;
    subgrid->mGridItems.Clear();
    subgrid->mAbsPosItems.Clear();
  }

  // Abs.pos. subgrids may have kAutoLine in their area.  Map those to the edge
  // line in the parent's grid (zero-based line numbers).
  if (MOZ_UNLIKELY(subgrid->mArea.mCols.mStart == kAutoLine)) {
    subgrid->mArea.mCols.mStart = 0;
  }
  if (MOZ_UNLIKELY(subgrid->mArea.mCols.mEnd == kAutoLine)) {
    subgrid->mArea.mCols.mEnd = aParentGrid->mGridColEnd - 1;
  }
  if (MOZ_UNLIKELY(subgrid->mArea.mRows.mStart == kAutoLine)) {
    subgrid->mArea.mRows.mStart = 0;
  }
  if (MOZ_UNLIKELY(subgrid->mArea.mRows.mEnd == kAutoLine)) {
    subgrid->mArea.mRows.mEnd = aParentGrid->mGridRowEnd - 1;
  }

  MOZ_ASSERT((subgrid->mArea.mCols.Extent() > 0 &&
              subgrid->mArea.mRows.Extent() > 0) ||
                 state.mGridItems.IsEmpty(),
             "subgrid needs at least one track for its items");

  // The min/sz/max sizes are the input to the "repeat-to-fill" algorithm:
  // https://drafts.csswg.org/css-grid/#auto-repeat
  // They're only used for auto-repeat in a non-subgridded axis so we skip
  // computing them otherwise.
  RepeatTrackSizingInput repeatSizing(state.mWM);
  if (!childGrid->IsColSubgrid() && state.mColFunctions.mHasRepeatAuto) {
    repeatSizing.InitFromStyle(eLogicalAxisInline, state.mWM,
                               state.mFrame->Style());
  }
  if (!childGrid->IsRowSubgrid() && state.mRowFunctions.mHasRepeatAuto) {
    repeatSizing.InitFromStyle(eLogicalAxisBlock, state.mWM,
                               state.mFrame->Style());
  }

  PlaceGridItems(state, repeatSizing);

  subgrid->mGridItems = std::move(state.mGridItems);
  subgrid->mAbsPosItems = std::move(state.mAbsPosItems);
  subgrid->mGridColEnd = mGridColEnd;
  subgrid->mGridRowEnd = mGridRowEnd;
}

void nsGridContainerFrame::Grid::PlaceGridItems(
    GridReflowInput& aState, const RepeatTrackSizingInput& aSizes) {
  MOZ_ASSERT(mCellMap.mCells.IsEmpty(), "unexpected entries in cell map");

  mAreas = aState.mFrame->GetImplicitNamedAreas();

  if (aState.mFrame->HasSubgridItems() || aState.mFrame->IsSubgrid()) {
    if (auto* uts = aState.mFrame->GetUsedTrackSizes()) {
      uts->mCanResolveLineRangeSize = {false, false};
      uts->mSizes[eLogicalAxisInline].ClearAndRetainStorage();
      uts->mSizes[eLogicalAxisBlock].ClearAndRetainStorage();
    }
  }

  // SubgridPlaceGridItems will set these if we find any subgrid items.
  aState.mFrame->RemoveStateBits(NS_STATE_GRID_HAS_COL_SUBGRID_ITEM |
                                 NS_STATE_GRID_HAS_ROW_SUBGRID_ITEM);

  // http://dev.w3.org/csswg/css-grid/#grid-definition
  // Initialize the end lines of the Explicit Grid (mExplicitGridCol[Row]End).
  // This is determined by the larger of the number of rows/columns defined
  // by 'grid-template-areas' and the 'grid-template-rows'/'-columns', plus one.
  // Also initialize the Implicit Grid (mGridCol[Row]End) to the same values.
  // Note that this is for a grid with a 1,1 origin.  We'll change that
  // to a 0,0 based grid after placing definite lines.
  const nsStylePosition* const gridStyle = aState.mGridStyle;
  const auto* areas = gridStyle->mGridTemplateAreas.IsNone()
                          ? nullptr
                          : &*gridStyle->mGridTemplateAreas.AsAreas();
  const LineNameMap* parentLineNameMap = nullptr;
  const LineRange* subgridRange = nullptr;
  bool subgridAxisIsSameDirection = true;
  if (!aState.mFrame->IsColSubgrid()) {
    aState.mColFunctions.InitRepeatTracks(
        gridStyle->mColumnGap, aSizes.mMin.ISize(aState.mWM),
        aSizes.mSize.ISize(aState.mWM), aSizes.mMax.ISize(aState.mWM));
    uint32_t areaCols = areas ? areas->width + 1 : 1;
    mExplicitGridColEnd = aState.mColFunctions.ComputeExplicitGridEnd(areaCols);
  } else {
    const auto* subgrid = aState.mFrame->GetProperty(Subgrid::Prop());
    subgridRange = &subgrid->SubgridCols();
    uint32_t extent = subgridRange->Extent();
    mExplicitGridColEnd = extent + 1;  // the grid is 1-based at this point
    parentLineNameMap =
        ParentLineMapForAxis(subgrid->mIsOrthogonal, eLogicalAxisInline);
    auto parentWM =
        aState.mFrame->ParentGridContainerForSubgrid()->GetWritingMode();
    subgridAxisIsSameDirection =
        aState.mWM.ParallelAxisStartsOnSameSide(eLogicalAxisInline, parentWM);
  }
  mGridColEnd = mExplicitGridColEnd;
  LineNameMap colLineNameMap(gridStyle, mAreas, aState.mColFunctions,
                             parentLineNameMap, subgridRange,
                             subgridAxisIsSameDirection);

  if (!aState.mFrame->IsRowSubgrid()) {
    const Maybe<nscoord> containBSize = aState.mFrame->ContainIntrinsicBSize();
    const nscoord repeatTrackSizingBSize = [&] {
      // This clamping only applies to auto sizes.
      if (containBSize &&
          aSizes.mSize.BSize(aState.mWM) == NS_UNCONSTRAINEDSIZE) {
        return NS_CSS_MINMAX(*containBSize, aSizes.mMin.BSize(aState.mWM),
                             aSizes.mMax.BSize(aState.mWM));
      }
      return aSizes.mSize.BSize(aState.mWM);
    }();
    aState.mRowFunctions.InitRepeatTracks(
        gridStyle->mRowGap, aSizes.mMin.BSize(aState.mWM),
        repeatTrackSizingBSize, aSizes.mMax.BSize(aState.mWM));
    uint32_t areaRows = areas ? areas->strings.Length() + 1 : 1;
    mExplicitGridRowEnd = aState.mRowFunctions.ComputeExplicitGridEnd(areaRows);
    parentLineNameMap = nullptr;
    subgridRange = nullptr;
  } else {
    const auto* subgrid = aState.mFrame->GetProperty(Subgrid::Prop());
    subgridRange = &subgrid->SubgridRows();
    uint32_t extent = subgridRange->Extent();
    mExplicitGridRowEnd = extent + 1;  // the grid is 1-based at this point
    parentLineNameMap =
        ParentLineMapForAxis(subgrid->mIsOrthogonal, eLogicalAxisBlock);
    auto parentWM =
        aState.mFrame->ParentGridContainerForSubgrid()->GetWritingMode();
    subgridAxisIsSameDirection =
        aState.mWM.ParallelAxisStartsOnSameSide(eLogicalAxisBlock, parentWM);
  }
  mGridRowEnd = mExplicitGridRowEnd;
  LineNameMap rowLineNameMap(gridStyle, mAreas, aState.mRowFunctions,
                             parentLineNameMap, subgridRange,
                             subgridAxisIsSameDirection);

  const bool isSubgridOrItemInSubgrid =
      aState.mFrame->IsSubgrid() || !!mParentGrid;
  auto SetSubgridChildEdgeBits =
      [this, isSubgridOrItemInSubgrid](GridItemInfo& aItem) -> void {
    if (isSubgridOrItemInSubgrid) {
      const auto& area = aItem.mArea;
      if (area.mCols.mStart == 0) {
        aItem.mState[eLogicalAxisInline] |= ItemState::eStartEdge;
      }
      if (area.mCols.mEnd == mGridColEnd) {
        aItem.mState[eLogicalAxisInline] |= ItemState::eEndEdge;
      }
      if (area.mRows.mStart == 0) {
        aItem.mState[eLogicalAxisBlock] |= ItemState::eStartEdge;
      }
      if (area.mRows.mEnd == mGridRowEnd) {
        aItem.mState[eLogicalAxisBlock] |= ItemState::eEndEdge;
      }
    }
  };

  SetLineMaps(&colLineNameMap, &rowLineNameMap);

  // http://dev.w3.org/csswg/css-grid/#line-placement
  // Resolve definite positions per spec chap 9.2.
  int32_t minCol = 1;
  int32_t minRow = 1;
  aState.mGridItems.ClearAndRetainStorage();
  aState.mIter.Reset();
  for (; !aState.mIter.AtEnd(); aState.mIter.Next()) {
    nsIFrame* child = *aState.mIter;
    GridItemInfo* info = aState.mGridItems.AppendElement(GridItemInfo(
        child,
        PlaceDefinite(child, colLineNameMap, rowLineNameMap, gridStyle)));
    MOZ_ASSERT(aState.mIter.ItemIndex() == aState.mGridItems.Length() - 1,
               "ItemIndex() is broken");
    GridArea& area = info->mArea;
    if (area.mCols.IsDefinite()) {
      minCol = std::min(minCol, area.mCols.mUntranslatedStart);
    }
    if (area.mRows.IsDefinite()) {
      minRow = std::min(minRow, area.mRows.mUntranslatedStart);
    }
  }

  // Translate the whole grid so that the top-/left-most area is at 0,0.
  mExplicitGridOffsetCol = 1 - minCol;  // minCol/Row is always <= 1, see above
  mExplicitGridOffsetRow = 1 - minRow;
  aState.mColFunctions.mExplicitGridOffset = mExplicitGridOffsetCol;
  aState.mRowFunctions.mExplicitGridOffset = mExplicitGridOffsetRow;
  const int32_t offsetToColZero = int32_t(mExplicitGridOffsetCol) - 1;
  const int32_t offsetToRowZero = int32_t(mExplicitGridOffsetRow) - 1;
  const bool isRowMasonry = aState.mFrame->IsMasonry(eLogicalAxisBlock);
  const bool isColMasonry = aState.mFrame->IsMasonry(eLogicalAxisInline);
  const bool isMasonry = isColMasonry || isRowMasonry;
  mGridColEnd += offsetToColZero;
  mGridRowEnd += offsetToRowZero;
  const uint32_t gridAxisTrackCount = isRowMasonry ? mGridColEnd : mGridRowEnd;
  aState.mIter.Reset();
  for (; !aState.mIter.AtEnd(); aState.mIter.Next()) {
    auto& item = aState.mGridItems[aState.mIter.ItemIndex()];
    GridArea& area = item.mArea;
    if (area.mCols.IsDefinite()) {
      area.mCols.mStart = area.mCols.mUntranslatedStart + offsetToColZero;
      area.mCols.mEnd = area.mCols.mUntranslatedEnd + offsetToColZero;
    }
    if (area.mRows.IsDefinite()) {
      area.mRows.mStart = area.mRows.mUntranslatedStart + offsetToRowZero;
      area.mRows.mEnd = area.mRows.mUntranslatedEnd + offsetToRowZero;
    }
    if (area.IsDefinite()) {
      if (isMasonry) {
        item.MaybeInhibitSubgridInMasonry(aState.mFrame, gridAxisTrackCount);
      }
      if (item.IsSubgrid()) {
        Grid grid(this);
        grid.SubgridPlaceGridItems(aState, this, item);
      }
      mCellMap.Fill(area);
      InflateGridFor(area);
      SetSubgridChildEdgeBits(item);
    }
  }

  // http://dev.w3.org/csswg/css-grid/#auto-placement-algo
  // Step 1, place 'auto' items that have one definite position -
  // definite row (column) for grid-auto-flow:row (column).
  auto flowStyle = gridStyle->mGridAutoFlow;
  const bool isRowOrder =
      isMasonry ? isRowMasonry : !!(flowStyle & StyleGridAutoFlow::ROW);
  const bool isSparse = !(flowStyle & StyleGridAutoFlow::DENSE);
  uint32_t clampMaxColLine = colLineNameMap.mClampMaxLine + offsetToColZero;
  uint32_t clampMaxRowLine = rowLineNameMap.mClampMaxLine + offsetToRowZero;
  // We need 1 cursor per row (or column) if placement is sparse.
  {
    Maybe<nsTHashMap<nsUint32HashKey, uint32_t>> cursors;
    if (isSparse) {
      cursors.emplace();
    }
    auto placeAutoMinorFunc =
        isRowOrder ? &Grid::PlaceAutoCol : &Grid::PlaceAutoRow;
    uint32_t clampMaxLine = isRowOrder ? clampMaxColLine : clampMaxRowLine;
    aState.mIter.Reset();
    for (; !aState.mIter.AtEnd(); aState.mIter.Next()) {
      auto& item = aState.mGridItems[aState.mIter.ItemIndex()];
      GridArea& area = item.mArea;
      LineRange& major = isRowOrder ? area.mRows : area.mCols;
      LineRange& minor = isRowOrder ? area.mCols : area.mRows;
      if (major.IsDefinite() && minor.IsAuto()) {
        // Items with 'auto' in the minor dimension only.
        const uint32_t cursor = isSparse ? cursors->Get(major.mStart) : 0;
        (this->*placeAutoMinorFunc)(cursor, &area, clampMaxLine);
        if (isMasonry) {
          item.MaybeInhibitSubgridInMasonry(aState.mFrame, gridAxisTrackCount);
        }
        if (item.IsSubgrid()) {
          Grid grid(this);
          grid.SubgridPlaceGridItems(aState, this, item);
        }
        mCellMap.Fill(area);
        SetSubgridChildEdgeBits(item);
        if (isSparse) {
          cursors->InsertOrUpdate(major.mStart, minor.mEnd);
        }
      }
      InflateGridFor(area);  // Step 2, inflating for auto items too
    }
  }

  // XXX NOTE possible spec issue.
  // XXX It's unclear if the remaining major-dimension auto and
  // XXX auto in both dimensions should use the same cursor or not,
  // XXX https://www.w3.org/Bugs/Public/show_bug.cgi?id=16044
  // XXX seems to indicate it shouldn't.
  // XXX http://dev.w3.org/csswg/css-grid/#auto-placement-cursor
  // XXX now says it should (but didn't in earlier versions)

  // Step 3, place the remaining grid items
  uint32_t cursorMajor = 0;  // for 'dense' these two cursors will stay at 0,0
  uint32_t cursorMinor = 0;
  auto placeAutoMajorFunc =
      isRowOrder ? &Grid::PlaceAutoRow : &Grid::PlaceAutoCol;
  uint32_t clampMaxMajorLine = isRowOrder ? clampMaxRowLine : clampMaxColLine;
  aState.mIter.Reset();
  for (; !aState.mIter.AtEnd(); aState.mIter.Next()) {
    auto& item = aState.mGridItems[aState.mIter.ItemIndex()];
    GridArea& area = item.mArea;
    MOZ_ASSERT(*aState.mIter == item.mFrame,
               "iterator out of sync with aState.mGridItems");
    LineRange& major = isRowOrder ? area.mRows : area.mCols;
    LineRange& minor = isRowOrder ? area.mCols : area.mRows;
    if (major.IsAuto()) {
      if (minor.IsDefinite()) {
        // Items with 'auto' in the major dimension only.
        if (isSparse) {
          if (minor.mStart < cursorMinor) {
            ++cursorMajor;
          }
          cursorMinor = minor.mStart;
        }
        (this->*placeAutoMajorFunc)(cursorMajor, &area, clampMaxMajorLine);
        if (isSparse) {
          cursorMajor = major.mStart;
        }
      } else {
        // Items with 'auto' in both dimensions.
        if (isRowOrder) {
          PlaceAutoAutoInRowOrder(cursorMinor, cursorMajor, &area,
                                  clampMaxColLine, clampMaxRowLine);
        } else {
          PlaceAutoAutoInColOrder(cursorMajor, cursorMinor, &area,
                                  clampMaxColLine, clampMaxRowLine);
        }
        if (isSparse) {
          cursorMajor = major.mStart;
          cursorMinor = minor.mEnd;
#ifdef DEBUG
          uint32_t gridMajorEnd = isRowOrder ? mGridRowEnd : mGridColEnd;
          uint32_t gridMinorEnd = isRowOrder ? mGridColEnd : mGridRowEnd;
          MOZ_ASSERT(cursorMajor <= gridMajorEnd,
                     "we shouldn't need to place items further than 1 track "
                     "past the current end of the grid, in major dimension");
          MOZ_ASSERT(cursorMinor <= gridMinorEnd,
                     "we shouldn't add implicit minor tracks for auto/auto");
#endif
        }
      }
      if (isMasonry) {
        item.MaybeInhibitSubgridInMasonry(aState.mFrame, gridAxisTrackCount);
      }
      if (item.IsSubgrid()) {
        Grid grid(this);
        grid.SubgridPlaceGridItems(aState, this, item);
      }
      mCellMap.Fill(area);
      InflateGridFor(area);
      SetSubgridChildEdgeBits(item);
      // XXXmats it might be possible to optimize this a bit for masonry layout
      // if this item was placed in the 2nd row && !isSparse, or the 1st row
      // is full.  Still gotta inflate the grid for all items though to make
      // the grid large enough...
    }
  }

  // Force all items into the 1st/2nd track and have span 1 in the masonry axis.
  // (See comment on nsGridContainerFrame::MasonryLayout().)
  if (isMasonry) {
    auto masonryAxis = isRowMasonry ? eLogicalAxisBlock : eLogicalAxisInline;
    aState.mIter.Reset();
    for (; !aState.mIter.AtEnd(); aState.mIter.Next()) {
      auto& item = aState.mGridItems[aState.mIter.ItemIndex()];
      auto& masonryRange = item.mArea.LineRangeForAxis(masonryAxis);
      masonryRange.mStart = std::min(masonryRange.mStart, 1U);
      masonryRange.mEnd = masonryRange.mStart + 1U;
    }
  }

  if (aState.mFrame->IsAbsoluteContainer()) {
    // 9.4 Absolutely-positioned Grid Items
    // http://dev.w3.org/csswg/css-grid/#abspos-items
    // We only resolve definite lines here; we'll align auto positions to the
    // grid container later during reflow.
    const nsFrameList& children =
        aState.mFrame->GetChildList(aState.mFrame->GetAbsoluteListID());
    const int32_t offsetToColZero = int32_t(mExplicitGridOffsetCol) - 1;
    const int32_t offsetToRowZero = int32_t(mExplicitGridOffsetRow) - 1;
    // Untranslate the grid again temporarily while resolving abs.pos. lines.
    AutoRestore<uint32_t> zeroOffsetGridColEnd(mGridColEnd);
    AutoRestore<uint32_t> zeroOffsetGridRowEnd(mGridRowEnd);
    mGridColEnd -= offsetToColZero;
    mGridRowEnd -= offsetToRowZero;
    aState.mAbsPosItems.ClearAndRetainStorage();
    for (nsIFrame* child : children) {
      GridItemInfo* info = aState.mAbsPosItems.AppendElement(GridItemInfo(
          child,
          PlaceAbsPos(child, colLineNameMap, rowLineNameMap, gridStyle)));
      GridArea& area = info->mArea;
      if (area.mCols.mUntranslatedStart != int32_t(kAutoLine)) {
        area.mCols.mStart = area.mCols.mUntranslatedStart + offsetToColZero;
        if (isColMasonry) {
          // XXXmats clamp any non-auto line to 0 or 1. This is intended to
          // allow authors to address the start/end of the masonry box.
          // This is experimental at this point though and needs author feedback
          // and spec work to sort out what is desired and how it should work.
          // See https://github.com/w3c/csswg-drafts/issues/4650
          area.mCols.mStart = std::min(area.mCols.mStart, 1U);
        }
      }
      if (area.mCols.mUntranslatedEnd != int32_t(kAutoLine)) {
        area.mCols.mEnd = area.mCols.mUntranslatedEnd + offsetToColZero;
        if (isColMasonry) {
          // ditto
          area.mCols.mEnd = std::min(area.mCols.mEnd, 1U);
        }
      }
      if (area.mRows.mUntranslatedStart != int32_t(kAutoLine)) {
        area.mRows.mStart = area.mRows.mUntranslatedStart + offsetToRowZero;
        if (isRowMasonry) {
          // ditto
          area.mRows.mStart = std::min(area.mRows.mStart, 1U);
        }
      }
      if (area.mRows.mUntranslatedEnd != int32_t(kAutoLine)) {
        area.mRows.mEnd = area.mRows.mUntranslatedEnd + offsetToRowZero;
        if (isRowMasonry) {
          // ditto
          area.mRows.mEnd = std::min(area.mRows.mEnd, 1U);
        }
      }
      if (isMasonry) {
        info->MaybeInhibitSubgridInMasonry(aState.mFrame, gridAxisTrackCount);
      }

      // An abs.pos. subgrid with placement auto/1 or -1/auto technically
      // doesn't span any parent tracks.  Inhibit subgridding in this case.
      if (info->IsSubgrid(eLogicalAxisInline)) {
        if (info->mArea.mCols.mStart == zeroOffsetGridColEnd.SavedValue() ||
            info->mArea.mCols.mEnd == 0) {
          info->InhibitSubgrid(aState.mFrame, eLogicalAxisInline);
        }
      }
      if (info->IsSubgrid(eLogicalAxisBlock)) {
        if (info->mArea.mRows.mStart == zeroOffsetGridRowEnd.SavedValue() ||
            info->mArea.mRows.mEnd == 0) {
          info->InhibitSubgrid(aState.mFrame, eLogicalAxisBlock);
        }
      }

      if (info->IsSubgrid()) {
        Grid grid(this);
        grid.SubgridPlaceGridItems(aState, this, *info);
      }
    }
  }

  // Count empty 'auto-fit' tracks in the repeat() range.
  // |colAdjust| will have a count for each line in the grid of how many
  // tracks were empty between the start of the grid and that line.

  Maybe<nsTArray<uint32_t>> colAdjust;
  uint32_t numEmptyCols = 0;
  if (aState.mColFunctions.mHasRepeatAuto &&
      gridStyle->mGridTemplateColumns.GetRepeatAutoValue()->count.IsAutoFit()) {
    const auto& cellMap = mCellMap;
    colAdjust = CalculateAdjustForAutoFitElements(
        &numEmptyCols, aState.mColFunctions, mGridColEnd + 1,
        [&cellMap](uint32_t i) -> bool { return cellMap.IsEmptyCol(i); });
  }

  // Do similar work for the row tracks, with the same logic.
  Maybe<nsTArray<uint32_t>> rowAdjust;
  uint32_t numEmptyRows = 0;
  if (aState.mRowFunctions.mHasRepeatAuto &&
      gridStyle->mGridTemplateRows.GetRepeatAutoValue()->count.IsAutoFit()) {
    const auto& cellMap = mCellMap;
    rowAdjust = CalculateAdjustForAutoFitElements(
        &numEmptyRows, aState.mRowFunctions, mGridRowEnd + 1,
        [&cellMap](uint32_t i) -> bool { return cellMap.IsEmptyRow(i); });
  }
  MOZ_ASSERT((numEmptyCols > 0) == colAdjust.isSome());
  MOZ_ASSERT((numEmptyRows > 0) == rowAdjust.isSome());
  // Remove the empty 'auto-fit' tracks we found above, if any.
  if (numEmptyCols || numEmptyRows) {
    // Adjust the line numbers in the grid areas.
    for (auto& item : aState.mGridItems) {
      if (numEmptyCols) {
        item.AdjustForRemovedTracks(eLogicalAxisInline, *colAdjust);
      }
      if (numEmptyRows) {
        item.AdjustForRemovedTracks(eLogicalAxisBlock, *rowAdjust);
      }
    }
    for (auto& item : aState.mAbsPosItems) {
      if (numEmptyCols) {
        item.AdjustForRemovedTracks(eLogicalAxisInline, *colAdjust);
      }
      if (numEmptyRows) {
        item.AdjustForRemovedTracks(eLogicalAxisBlock, *rowAdjust);
      }
    }
    // Adjust the grid size.
    mGridColEnd -= numEmptyCols;
    mExplicitGridColEnd -= numEmptyCols;
    mGridRowEnd -= numEmptyRows;
    mExplicitGridRowEnd -= numEmptyRows;
    // Adjust the track mapping to unmap the removed tracks.
    auto colRepeatCount = aState.mColFunctions.NumRepeatTracks();
    aState.mColFunctions.SetNumRepeatTracks(colRepeatCount - numEmptyCols);
    auto rowRepeatCount = aState.mRowFunctions.NumRepeatTracks();
    aState.mRowFunctions.SetNumRepeatTracks(rowRepeatCount - numEmptyRows);
  }

  // Update the line boundaries of the implicit grid areas, if needed.
  if (mAreas && aState.mFrame->HasAnyStateBits(NS_STATE_GRID_COMPUTED_INFO)) {
    for (auto iter = mAreas->iter(); !iter.done(); iter.next()) {
      auto& areaInfo = iter.get().value();

      // Resolve the lines for the area. We use the name of the area as the
      // name of the lines, knowing that the line placement algorithm will
      // add the -start and -end suffixes as appropriate for layout.
      StyleGridLine lineStartAndEnd;
      lineStartAndEnd.ident._0 = areaInfo.name;

      LineRange columnLines =
          ResolveLineRange(lineStartAndEnd, lineStartAndEnd, colLineNameMap,
                           eLogicalAxisInline, mExplicitGridColEnd, gridStyle);

      LineRange rowLines =
          ResolveLineRange(lineStartAndEnd, lineStartAndEnd, rowLineNameMap,
                           eLogicalAxisBlock, mExplicitGridRowEnd, gridStyle);

      // Put the resolved line indices back into the area structure.
      areaInfo.columns.start = columnLines.mStart + mExplicitGridOffsetCol;
      areaInfo.columns.end = columnLines.mEnd + mExplicitGridOffsetCol;
      areaInfo.rows.start = rowLines.mStart + mExplicitGridOffsetRow;
      areaInfo.rows.end = rowLines.mEnd + mExplicitGridOffsetRow;
    }
  }
}

void nsGridContainerFrame::Tracks::Initialize(
    const TrackSizingFunctions& aFunctions,
    const NonNegativeLengthPercentageOrNormal& aGridGap, uint32_t aNumTracks,
    nscoord aContentBoxSize) {
  mSizes.SetLength(aNumTracks);
  PodZero(mSizes.Elements(), mSizes.Length());
  for (uint32_t i = 0, len = mSizes.Length(); i < len; ++i) {
    auto& sz = mSizes[i];
    mStateUnion |= sz.Initialize(aContentBoxSize, aFunctions.SizingFor(i));
    if (mIsMasonry) {
      sz.mBase = aContentBoxSize;
      sz.mLimit = aContentBoxSize;
    }
  }
  mGridGap = nsLayoutUtils::ResolveGapToLength(aGridGap, aContentBoxSize);
  mContentBoxSize = aContentBoxSize;
}

/**
 * Reflow aChild in the given aAvailableSize.
 */
static nscoord MeasuringReflow(nsIFrame* aChild,
                               const ReflowInput* aReflowInput, gfxContext* aRC,
                               const LogicalSize& aAvailableSize,
                               const LogicalSize& aCBSize,
                               nscoord aIMinSizeClamp = NS_MAXSIZE,
                               nscoord aBMinSizeClamp = NS_MAXSIZE) {
  MOZ_ASSERT(aChild->IsGridItem(), "aChild should be a grid item!");
  auto* parent = static_cast<nsGridContainerFrame*>(aChild->GetParent());
  nsPresContext* pc = aChild->PresContext();
  Maybe<ReflowInput> dummyParentState;
  const ReflowInput* rs = aReflowInput;
  if (!aReflowInput) {
    MOZ_ASSERT(!parent->HasAnyStateBits(NS_FRAME_IN_REFLOW));
    dummyParentState.emplace(
        pc, parent, aRC,
        LogicalSize(parent->GetWritingMode(), 0, NS_UNCONSTRAINEDSIZE),
        ReflowInput::InitFlag::DummyParentReflowInput);
    rs = dummyParentState.ptr();
  }
#ifdef DEBUG
  // This will suppress various ABSURD_SIZE warnings for this reflow.
  parent->SetProperty(nsContainerFrame::DebugReflowingWithInfiniteISize(),
                      true);
#endif
  auto wm = aChild->GetWritingMode();
  ComputeSizeFlags csFlags = ComputeSizeFlag::IsGridMeasuringReflow;
  // Shrink-wrap grid items that will be aligned (rather than stretched) in
  // their own inline axis.
  if (!parent->GridItemShouldStretch(aChild, eLogicalAxisInline)) {
    csFlags += ComputeSizeFlag::ShrinkWrap;
  }
  if (aAvailableSize.ISize(wm) == INFINITE_ISIZE_COORD) {
    csFlags += ComputeSizeFlag::ShrinkWrap;
  }
  if (aIMinSizeClamp != NS_MAXSIZE) {
    csFlags += ComputeSizeFlag::IClampMarginBoxMinSize;
  }
  if (aBMinSizeClamp != NS_MAXSIZE) {
    csFlags += ComputeSizeFlag::BClampMarginBoxMinSize;
    aChild->SetProperty(nsIFrame::BClampMarginBoxMinSizeProperty(),
                        aBMinSizeClamp);
  } else {
    aChild->RemoveProperty(nsIFrame::BClampMarginBoxMinSizeProperty());
  }
  ReflowInput childRI(pc, *rs, aChild, aAvailableSize, Some(aCBSize), {}, {},
                      csFlags);

  // FIXME (perf): It would be faster to do this only if the previous reflow of
  // the child was not a measuring reflow, and only if the child does some of
  // the things that are affected by ComputeSizeFlag::IsGridMeasuringReflow.
  childRI.SetBResize(true);
  // Not 100% sure this is needed, but be conservative for now:
  childRI.mFlags.mIsBResizeForPercentages = true;

  ReflowOutput childSize(childRI);
  nsReflowStatus childStatus;
  const nsIFrame::ReflowChildFlags flags =
      nsIFrame::ReflowChildFlags::NoMoveFrame |
      nsIFrame::ReflowChildFlags::NoSizeView |
      nsIFrame::ReflowChildFlags::NoDeleteNextInFlowChild;

  bool found;
  GridItemCachedBAxisMeasurement cachedMeasurement =
      aChild->GetProperty(GridItemCachedBAxisMeasurement::Prop(), &found);
  if (found && cachedMeasurement.IsValidFor(aChild, aCBSize)) {
    childSize.BSize(wm) = cachedMeasurement.BSize();
    childSize.ISize(wm) = aChild->ISize(wm);
    nsContainerFrame::FinishReflowChild(aChild, pc, childSize, &childRI, wm,
                                        LogicalPoint(wm), nsSize(), flags);
    GRID_LOG(
        "[perf] MeasuringReflow accepted cached value=%d, child=%p, "
        "aCBSize.ISize=%d",
        cachedMeasurement.BSize(), aChild,
        aCBSize.ISize(aChild->GetWritingMode()));
    return cachedMeasurement.BSize();
  }

  parent->ReflowChild(aChild, pc, childSize, childRI, wm, LogicalPoint(wm),
                      nsSize(), flags, childStatus);
  nsContainerFrame::FinishReflowChild(aChild, pc, childSize, &childRI, wm,
                                      LogicalPoint(wm), nsSize(), flags);
#ifdef DEBUG
  parent->RemoveProperty(nsContainerFrame::DebugReflowingWithInfiniteISize());
#endif
  if (!found &&
      GridItemCachedBAxisMeasurement::CanCacheMeasurement(aChild, aCBSize)) {
    GridItemCachedBAxisMeasurement cachedMeasurement(aChild, aCBSize,
                                                     childSize.BSize(wm));
    aChild->SetProperty(GridItemCachedBAxisMeasurement::Prop(),
                        cachedMeasurement);
    GRID_LOG(
        "[perf] MeasuringReflow created new cached value=%d, child=%p, "
        "aCBSize.ISize=%d",
        cachedMeasurement.BSize(), aChild,
        aCBSize.ISize(aChild->GetWritingMode()));
  } else if (found) {
    if (GridItemCachedBAxisMeasurement::CanCacheMeasurement(aChild, aCBSize)) {
      cachedMeasurement.Update(aChild, aCBSize, childSize.BSize(wm));
      GRID_LOG(
          "[perf] MeasuringReflow rejected but updated cached value=%d, "
          "child=%p, aCBSize.ISize=%d",
          cachedMeasurement.BSize(), aChild,
          aCBSize.ISize(aChild->GetWritingMode()));
      aChild->SetProperty(GridItemCachedBAxisMeasurement::Prop(),
                          cachedMeasurement);
    } else {
      aChild->RemoveProperty(GridItemCachedBAxisMeasurement::Prop());
      GRID_LOG(
          "[perf] MeasuringReflow rejected and removed cached value, "
          "child=%p",
          aChild);
    }
  }

  return childSize.BSize(wm);
}

/**
 * Reflow aChild in the given aAvailableSize, using aNewContentBoxSize as its
 * computed size in aChildAxis.
 */
static void PostReflowStretchChild(
    nsIFrame* aChild, const ReflowInput& aReflowInput,
    const LogicalSize& aAvailableSize, const LogicalSize& aCBSize,
    LogicalAxis aChildAxis, const nscoord aNewContentBoxSize,
    nscoord aIMinSizeClamp = NS_MAXSIZE, nscoord aBMinSizeClamp = NS_MAXSIZE) {
  nsPresContext* pc = aChild->PresContext();
  ComputeSizeFlags csFlags;
  if (aIMinSizeClamp != NS_MAXSIZE) {
    csFlags += ComputeSizeFlag::IClampMarginBoxMinSize;
  }
  if (aBMinSizeClamp != NS_MAXSIZE) {
    csFlags += ComputeSizeFlag::BClampMarginBoxMinSize;
    aChild->SetProperty(nsIFrame::BClampMarginBoxMinSizeProperty(),
                        aBMinSizeClamp);
  } else {
    aChild->RemoveProperty(nsIFrame::BClampMarginBoxMinSizeProperty());
  }
  ReflowInput ri(pc, aReflowInput, aChild, aAvailableSize, Some(aCBSize), {},
                 {}, csFlags);
  if (aChildAxis == eLogicalAxisBlock) {
    ri.SetComputedBSize(ri.ApplyMinMaxBSize(aNewContentBoxSize));
  } else {
    ri.SetComputedISize(ri.ApplyMinMaxISize(aNewContentBoxSize));
  }
  ReflowOutput childSize(ri);
  nsReflowStatus childStatus;
  const nsIFrame::ReflowChildFlags flags =
      nsIFrame::ReflowChildFlags::NoMoveFrame |
      nsIFrame::ReflowChildFlags::NoDeleteNextInFlowChild;
  auto wm = aChild->GetWritingMode();
  nsContainerFrame* parent = aChild->GetParent();
  parent->ReflowChild(aChild, pc, childSize, ri, wm, LogicalPoint(wm), nsSize(),
                      flags, childStatus);
  nsContainerFrame::FinishReflowChild(aChild, pc, childSize, &ri, wm,
                                      LogicalPoint(wm), nsSize(), flags);
}

/**
 * Return the accumulated margin+border+padding in aAxis for aFrame (a subgrid)
 * and its ancestor subgrids.
 */
static LogicalMargin SubgridAccumulatedMarginBorderPadding(
    nsIFrame* aFrame, const Subgrid* aSubgrid, WritingMode aResultWM,
    LogicalAxis aAxis) {
  MOZ_ASSERT(aFrame->IsGridContainerFrame());
  auto* subgridFrame = static_cast<nsGridContainerFrame*>(aFrame);
  LogicalMargin result(aSubgrid->mMarginBorderPadding);
  auto* parent = subgridFrame->ParentGridContainerForSubgrid();
  auto subgridCBWM = parent->GetWritingMode();
  auto childRange = aSubgrid->mArea.LineRangeForAxis(aAxis);
  bool skipStartSide = false;
  bool skipEndSide = false;
  auto axis = aSubgrid->mIsOrthogonal ? GetOrthogonalAxis(aAxis) : aAxis;
  // If aFrame's parent is also a subgrid, then add its MBP on the edges that
  // are adjacent (i.e. start or end in the same track), recursively.
  // ("parent" refers to the grid-frame we're currently adding MBP for,
  // and "grandParent" its parent, as we walk up the chain.)
  while (parent->IsSubgrid(axis)) {
    auto* parentSubgrid = parent->GetProperty(Subgrid::Prop());
    auto* grandParent = parent->ParentGridContainerForSubgrid();
    auto parentCBWM = grandParent->GetWritingMode();
    if (parentCBWM.IsOrthogonalTo(subgridCBWM)) {
      axis = GetOrthogonalAxis(axis);
    }
    const auto& parentRange = parentSubgrid->mArea.LineRangeForAxis(axis);
    bool sameDir = parentCBWM.ParallelAxisStartsOnSameSide(axis, subgridCBWM);
    if (sameDir) {
      skipStartSide |= childRange.mStart != 0;
      skipEndSide |= childRange.mEnd != parentRange.Extent();
    } else {
      skipEndSide |= childRange.mStart != 0;
      skipStartSide |= childRange.mEnd != parentRange.Extent();
    }
    if (skipStartSide && skipEndSide) {
      break;
    }
    auto mbp =
        parentSubgrid->mMarginBorderPadding.ConvertTo(subgridCBWM, parentCBWM);
    if (skipStartSide) {
      mbp.Start(aAxis, subgridCBWM) = nscoord(0);
    }
    if (skipEndSide) {
      mbp.End(aAxis, subgridCBWM) = nscoord(0);
    }
    result += mbp;
    parent = grandParent;
    childRange = parentRange;
  }
  return result.ConvertTo(aResultWM, subgridCBWM);
}

/**
 * Return the [min|max]-content contribution of aChild to its parent (i.e.
 * the child's margin-box) in aAxis.
 */
static nscoord ContentContribution(
    const GridItemInfo& aGridItem, const GridReflowInput& aState,
    gfxContext* aRC, WritingMode aCBWM, LogicalAxis aAxis,
    const Maybe<LogicalSize>& aPercentageBasis, IntrinsicISizeType aConstraint,
    nscoord aMinSizeClamp = NS_MAXSIZE, uint32_t aFlags = 0) {
  nsIFrame* child = aGridItem.mFrame;

  nscoord extraMargin = 0;
  nsGridContainerFrame::Subgrid* subgrid = nullptr;
  if (child->GetParent() != aState.mFrame) {
    // |child| is a subgrid descendant, so it contributes its subgrids'
    // margin+border+padding for any edge tracks that it spans.
    auto* subgridFrame = child->GetParent();
    subgrid = subgridFrame->GetProperty(Subgrid::Prop());
    const auto itemEdgeBits = aGridItem.mState[aAxis] & ItemState::eEdgeBits;
    if (itemEdgeBits) {
      LogicalMargin mbp = SubgridAccumulatedMarginBorderPadding(
          subgridFrame, subgrid, aCBWM, aAxis);
      if (itemEdgeBits & ItemState::eStartEdge) {
        extraMargin += mbp.Start(aAxis, aCBWM);
      }
      if (itemEdgeBits & ItemState::eEndEdge) {
        extraMargin += mbp.End(aAxis, aCBWM);
      }
    }
    // It also contributes (half of) the subgrid's gap on its edges (if any)
    // subtracted by the non-subgrid ancestor grid container's gap.
    // Note that this can also be negative since it's considered a margin.
    if (itemEdgeBits != ItemState::eEdgeBits) {
      auto subgridAxis = aCBWM.IsOrthogonalTo(subgridFrame->GetWritingMode())
                             ? GetOrthogonalAxis(aAxis)
                             : aAxis;
      auto& gapStyle = subgridAxis == eLogicalAxisBlock
                           ? subgridFrame->StylePosition()->mRowGap
                           : subgridFrame->StylePosition()->mColumnGap;
      if (!gapStyle.IsNormal()) {
        auto subgridExtent = subgridAxis == eLogicalAxisBlock
                                 ? subgrid->mGridRowEnd
                                 : subgrid->mGridColEnd;
        if (subgridExtent > 1) {
          nscoord subgridGap =
              nsLayoutUtils::ResolveGapToLength(gapStyle, NS_UNCONSTRAINEDSIZE);
          auto& tracks =
              aAxis == eLogicalAxisBlock ? aState.mRows : aState.mCols;
          auto gapDelta = subgridGap - tracks.mGridGap;
          if (!itemEdgeBits) {
            extraMargin += gapDelta;
          } else {
            extraMargin += gapDelta / 2;
          }
        }
      }
    }
  }

  PhysicalAxis axis(aCBWM.PhysicalAxis(aAxis));
  nscoord size = nsLayoutUtils::IntrinsicForAxis(
      axis, aRC, child, aConstraint, aPercentageBasis,
      aFlags | nsLayoutUtils::BAIL_IF_REFLOW_NEEDED, aMinSizeClamp);
  auto childWM = child->GetWritingMode();
  const bool isOrthogonal = childWM.IsOrthogonalTo(aCBWM);
  auto childAxis = isOrthogonal ? GetOrthogonalAxis(aAxis) : aAxis;
  if (size == NS_INTRINSIC_ISIZE_UNKNOWN && childAxis == eLogicalAxisBlock) {
    // We need to reflow the child to find its BSize contribution.
    // XXX this will give mostly correct results for now (until bug 1174569).
    nscoord availISize = INFINITE_ISIZE_COORD;
    nscoord availBSize = NS_UNCONSTRAINEDSIZE;
    // The next two variables are MinSizeClamp values in the child's axes.
    nscoord iMinSizeClamp = NS_MAXSIZE;
    nscoord bMinSizeClamp = NS_MAXSIZE;
    LogicalSize cbSize(childWM, 0, NS_UNCONSTRAINEDSIZE);
    // Below, we try to resolve the child's grid-area size in its inline-axis
    // to use as the CB/Available size in the MeasuringReflow that follows.
    if (child->GetParent() != aState.mFrame) {
      // This item is a child of a subgrid descendant.
      auto* subgridFrame =
          static_cast<nsGridContainerFrame*>(child->GetParent());
      MOZ_ASSERT(subgridFrame->IsGridContainerFrame());
      auto* uts = subgridFrame->GetProperty(UsedTrackSizes::Prop());
      if (!uts) {
        uts = new UsedTrackSizes();
        subgridFrame->SetProperty(UsedTrackSizes::Prop(), uts);
      }
      // The grid-item's inline-axis as expressed in the subgrid's WM.
      auto subgridAxis = childWM.IsOrthogonalTo(subgridFrame->GetWritingMode())
                             ? eLogicalAxisBlock
                             : eLogicalAxisInline;
      uts->ResolveTrackSizesForAxis(subgridFrame, subgridAxis, *aRC);
      if (uts->mCanResolveLineRangeSize[subgridAxis]) {
        auto* subgrid =
            subgridFrame->GetProperty(nsGridContainerFrame::Subgrid::Prop());
        const GridItemInfo* originalItem = nullptr;
        for (const auto& item : subgrid->mGridItems) {
          if (item.mFrame == child) {
            originalItem = &item;
            break;
          }
        }
        MOZ_ASSERT(originalItem, "huh?");
        const auto& range = originalItem->mArea.LineRangeForAxis(subgridAxis);
        nscoord pos, sz;
        range.ToPositionAndLength(uts->mSizes[subgridAxis], &pos, &sz);
        if (childWM.IsOrthogonalTo(subgridFrame->GetWritingMode())) {
          availBSize = sz;
          cbSize.BSize(childWM) = sz;
          if (aGridItem.mState[aAxis] & ItemState::eClampMarginBoxMinSize) {
            bMinSizeClamp = sz;
          }
        } else {
          availISize = sz;
          cbSize.ISize(childWM) = sz;
          if (aGridItem.mState[aAxis] & ItemState::eClampMarginBoxMinSize) {
            iMinSizeClamp = sz;
          }
        }
      }
    } else if (aState.mCols.mCanResolveLineRangeSize) {
      nscoord sz = aState.mCols.ResolveSize(aGridItem.mArea.mCols);
      if (isOrthogonal) {
        availBSize = sz;
        cbSize.BSize(childWM) = sz;
        if (aGridItem.mState[aAxis] & ItemState::eClampMarginBoxMinSize) {
          bMinSizeClamp = sz;
        }
      } else {
        availISize = sz;
        cbSize.ISize(childWM) = sz;
        if (aGridItem.mState[aAxis] & ItemState::eClampMarginBoxMinSize) {
          iMinSizeClamp = sz;
        }
      }
    }
    if (isOrthogonal == (aAxis == eLogicalAxisInline)) {
      bMinSizeClamp = aMinSizeClamp;
    } else {
      iMinSizeClamp = aMinSizeClamp;
    }
    LogicalSize availableSize(childWM, availISize, availBSize);
    size = ::MeasuringReflow(child, aState.mReflowInput, aRC, availableSize,
                             cbSize, iMinSizeClamp, bMinSizeClamp);
    size += child->GetLogicalUsedMargin(childWM).BStartEnd(childWM);
    nscoord overflow = size - aMinSizeClamp;
    if (MOZ_UNLIKELY(overflow > 0)) {
      nscoord contentSize = child->ContentBSize(childWM);
      nscoord newContentSize = std::max(nscoord(0), contentSize - overflow);
      // XXXmats deal with percentages better, see bug 1300369 comment 27.
      size -= contentSize - newContentSize;
    }
  }
  MOZ_ASSERT(aGridItem.mBaselineOffset[aAxis] >= 0,
             "baseline offset should be non-negative at this point");
  MOZ_ASSERT((aGridItem.mState[aAxis] & ItemState::eIsBaselineAligned) ||
                 aGridItem.mBaselineOffset[aAxis] == nscoord(0),
             "baseline offset should be zero when not baseline-aligned");
  size += aGridItem.mBaselineOffset[aAxis];
  size += extraMargin;
  return std::max(size, 0);
}

struct CachedIntrinsicSizes {
  Maybe<nscoord> mMinSize;
  Maybe<nscoord> mMinContentContribution;
  Maybe<nscoord> mMaxContentContribution;

  // The item's percentage basis for intrinsic sizing purposes.
  Maybe<LogicalSize> mPercentageBasis;

  // "if the grid item spans only grid tracks that have a fixed max track
  // sizing function, its automatic minimum size in that dimension is
  // further clamped to less than or equal to the size necessary to fit its
  // margin box within the resulting grid area (flooring at zero)"
  // https://drafts.csswg.org/css-grid/#min-size-auto
  // This is the clamp value to use for that:
  nscoord mMinSizeClamp = NS_MAXSIZE;
};

static nscoord MinContentContribution(const GridItemInfo& aGridItem,
                                      const GridReflowInput& aState,
                                      gfxContext* aRC, WritingMode aCBWM,
                                      LogicalAxis aAxis,
                                      CachedIntrinsicSizes* aCache) {
  if (aCache->mMinContentContribution.isSome()) {
    return aCache->mMinContentContribution.value();
  }
  if (aCache->mPercentageBasis.isNothing()) {
    aCache->mPercentageBasis.emplace(
        aState.PercentageBasisFor(aAxis, aGridItem));
  }
  nscoord s = ContentContribution(
      aGridItem, aState, aRC, aCBWM, aAxis, aCache->mPercentageBasis,
      IntrinsicISizeType::MinISize, aCache->mMinSizeClamp);
  aCache->mMinContentContribution.emplace(s);
  return s;
}

static nscoord MaxContentContribution(const GridItemInfo& aGridItem,
                                      const GridReflowInput& aState,
                                      gfxContext* aRC, WritingMode aCBWM,
                                      LogicalAxis aAxis,
                                      CachedIntrinsicSizes* aCache) {
  if (aCache->mMaxContentContribution.isSome()) {
    return aCache->mMaxContentContribution.value();
  }
  if (aCache->mPercentageBasis.isNothing()) {
    aCache->mPercentageBasis.emplace(
        aState.PercentageBasisFor(aAxis, aGridItem));
  }
  nscoord s = ContentContribution(
      aGridItem, aState, aRC, aCBWM, aAxis, aCache->mPercentageBasis,
      IntrinsicISizeType::PrefISize, aCache->mMinSizeClamp);
  aCache->mMaxContentContribution.emplace(s);
  return s;
}

// Computes the min-size contribution for a grid item, as defined at
// https://drafts.csswg.org/css-grid/#min-size-contribution
static nscoord MinSize(const GridItemInfo& aGridItem,
                       const GridReflowInput& aState, gfxContext* aRC,
                       WritingMode aCBWM, LogicalAxis aAxis,
                       CachedIntrinsicSizes* aCache) {
  if (aCache->mMinSize.isSome()) {
    return aCache->mMinSize.value();
  }
  nsIFrame* child = aGridItem.mFrame;
  PhysicalAxis axis(aCBWM.PhysicalAxis(aAxis));
  const nsStylePosition* stylePos = child->StylePosition();
  StyleSize sizeStyle =
      axis == eAxisHorizontal ? stylePos->mWidth : stylePos->mHeight;

  auto ourInlineAxis = child->GetWritingMode().PhysicalAxis(eLogicalAxisInline);
  // max-content and min-content should behave as initial value in block axis.
  // FIXME: Bug 567039: moz-fit-content and -moz-available are not supported
  // for block size dimension on sizing properties (e.g. height), so we
  // treat it as `auto`.
  if (axis != ourInlineAxis && sizeStyle.BehavesLikeInitialValueOnBlockAxis()) {
    sizeStyle = StyleSize::Auto();
  }

  if (!sizeStyle.IsAuto() && !sizeStyle.HasPercent()) {
    nscoord s =
        MinContentContribution(aGridItem, aState, aRC, aCBWM, aAxis, aCache);
    aCache->mMinSize.emplace(s);
    return s;
  }

  if (aCache->mPercentageBasis.isNothing()) {
    aCache->mPercentageBasis.emplace(
        aState.PercentageBasisFor(aAxis, aGridItem));
  }

  // https://drafts.csswg.org/css-grid/#min-size-auto
  // This calculates the min-content contribution from either a definite
  // min-width (or min-height depending on aAxis), or the "specified /
  // transferred size" for min-width:auto if overflow == visible (as min-width:0
  // otherwise), or NS_UNCONSTRAINEDSIZE for other min-width intrinsic values
  // (which results in always taking the "content size" part below).
  MOZ_ASSERT(aGridItem.mBaselineOffset[aAxis] >= 0,
             "baseline offset should be non-negative at this point");
  MOZ_ASSERT((aGridItem.mState[aAxis] & ItemState::eIsBaselineAligned) ||
                 aGridItem.mBaselineOffset[aAxis] == nscoord(0),
             "baseline offset should be zero when not baseline-aligned");
  nscoord sz = aGridItem.mBaselineOffset[aAxis] +
               nsLayoutUtils::MinSizeContributionForAxis(
                   axis, aRC, child, IntrinsicISizeType::MinISize,
                   *aCache->mPercentageBasis);
  const StyleSize& style =
      axis == eAxisHorizontal ? stylePos->mMinWidth : stylePos->mMinHeight;
  // max-content and min-content should behave as initial value in block axis.
  // FIXME: Bug 567039: moz-fit-content and -moz-available are not supported
  // for block size dimension on sizing properties (e.g. height), so we
  // treat it as `auto`.
  const bool inInlineAxis = axis == ourInlineAxis;
  const bool isAuto =
      style.IsAuto() ||
      (!inInlineAxis && style.BehavesLikeInitialValueOnBlockAxis());
  if ((inInlineAxis && nsIFrame::ToExtremumLength(style)) ||
      (isAuto && !child->StyleDisplay()->IsScrollableOverflow())) {
    // Now calculate the "content size" part and return whichever is smaller.
    MOZ_ASSERT(isAuto || sz == NS_UNCONSTRAINEDSIZE);
    sz = std::min(sz, ContentContribution(aGridItem, aState, aRC, aCBWM, aAxis,
                                          aCache->mPercentageBasis,
                                          IntrinsicISizeType::MinISize,
                                          aCache->mMinSizeClamp,
                                          nsLayoutUtils::MIN_INTRINSIC_ISIZE));
  }
  aCache->mMinSize.emplace(sz);
  return sz;
}

void nsGridContainerFrame::Tracks::CalculateSizes(
    GridReflowInput& aState, nsTArray<GridItemInfo>& aGridItems,
    const TrackSizingFunctions& aFunctions, nscoord aContentBoxSize,
    LineRange GridArea::*aRange, SizingConstraint aConstraint) {
  nscoord percentageBasis = aContentBoxSize;
  if (percentageBasis == NS_UNCONSTRAINEDSIZE) {
    percentageBasis = 0;
  }
  InitializeItemBaselines(aState, aGridItems);
  ResolveIntrinsicSize(aState, aGridItems, aFunctions, aRange, percentageBasis,
                       aConstraint);
  if (aConstraint != SizingConstraint::MinContent) {
    nscoord freeSpace = aContentBoxSize;
    if (freeSpace != NS_UNCONSTRAINEDSIZE) {
      freeSpace -= SumOfGridGaps();
    }
    DistributeFreeSpace(freeSpace);
    StretchFlexibleTracks(aState, aGridItems, aFunctions, freeSpace);
  }
}

TrackSize::StateBits nsGridContainerFrame::Tracks::StateBitsForRange(
    const LineRange& aRange) const {
  MOZ_ASSERT(!aRange.IsAuto(), "must have a definite range");
  TrackSize::StateBits state = TrackSize::StateBits{0};
  for (auto i : aRange.Range()) {
    state |= mSizes[i].mState;
  }
  return state;
}

static void AddSubgridContribution(TrackSize& aSize,
                                   nscoord aMarginBorderPadding) {
  if (aSize.mState & TrackSize::eIntrinsicMinSizing) {
    aSize.mBase = std::max(aSize.mBase, aMarginBorderPadding);
    aSize.mLimit = std::max(aSize.mLimit, aSize.mBase);
  }
  // XXX maybe eFlexMaxSizing too?
  // (once we implement https://github.com/w3c/csswg-drafts/issues/2177)
  if (aSize.mState &
      (TrackSize::eIntrinsicMaxSizing | TrackSize::eFitContent)) {
    aSize.mLimit = std::max(aSize.mLimit, aMarginBorderPadding);
  }
}

bool nsGridContainerFrame::Tracks::ResolveIntrinsicSizeForNonSpanningItems(
    GridReflowInput& aState, const TrackSizingFunctions& aFunctions,
    nscoord aPercentageBasis, SizingConstraint aConstraint,
    const LineRange& aRange, const GridItemInfo& aGridItem) {
  gfxContext* rc = &aState.mRenderingContext;
  WritingMode wm = aState.mWM;
  CachedIntrinsicSizes cache;
  TrackSize& sz = mSizes[aRange.mStart];

  // min sizing
  if (sz.mState & TrackSize::eAutoMinSizing) {
    nscoord s;
    // Check if we need to apply "Automatic Minimum Size" and cache it.
    if (aGridItem.ShouldApplyAutoMinSize(wm, mAxis, aPercentageBasis)) {
      aGridItem.mState[mAxis] |= ItemState::eApplyAutoMinSize;
      // Clamp it if it's spanning a definite track max-sizing function.
      if (TrackSize::IsDefiniteMaxSizing(sz.mState)) {
        cache.mMinSizeClamp = aFunctions.MaxSizingFor(aRange.mStart)
                                  .AsBreadth()
                                  .Resolve(aPercentageBasis);
        aGridItem.mState[mAxis] |= ItemState::eClampMarginBoxMinSize;
      }
      if (aConstraint != SizingConstraint::MaxContent) {
        s = MinContentContribution(aGridItem, aState, rc, wm, mAxis, &cache);
      } else {
        s = MaxContentContribution(aGridItem, aState, rc, wm, mAxis, &cache);
      }
    } else {
      s = MinSize(aGridItem, aState, rc, wm, mAxis, &cache);
    }
    sz.mBase = std::max(sz.mBase, s);
  } else if (sz.mState & TrackSize::eMinContentMinSizing) {
    auto s = MinContentContribution(aGridItem, aState, rc, wm, mAxis, &cache);
    sz.mBase = std::max(sz.mBase, s);
  } else if (sz.mState & TrackSize::eMaxContentMinSizing) {
    auto s = MaxContentContribution(aGridItem, aState, rc, wm, mAxis, &cache);
    sz.mBase = std::max(sz.mBase, s);
  }

  // max sizing
  if (sz.mState & TrackSize::eMinContentMaxSizing) {
    auto s = MinContentContribution(aGridItem, aState, rc, wm, mAxis, &cache);
    if (sz.mLimit == NS_UNCONSTRAINEDSIZE) {
      sz.mLimit = s;
    } else {
      sz.mLimit = std::max(sz.mLimit, s);
    }
  } else if (sz.mState &
             (TrackSize::eAutoMaxSizing | TrackSize::eMaxContentMaxSizing)) {
    auto s = MaxContentContribution(aGridItem, aState, rc, wm, mAxis, &cache);
    if (sz.mLimit == NS_UNCONSTRAINEDSIZE) {
      sz.mLimit = s;
    } else {
      sz.mLimit = std::max(sz.mLimit, s);
    }
    if (MOZ_UNLIKELY(sz.mState & TrackSize::eFitContent)) {
      // Clamp mLimit to the fit-content() size, for §12.5.1.
      nscoord fitContentClamp = aFunctions.SizingFor(aRange.mStart)
                                    .AsFitContent()
                                    .AsBreadth()
                                    .Resolve(aPercentageBasis);
      sz.mLimit = std::min(sz.mLimit, fitContentClamp);
    }
  }

  if (sz.mLimit < sz.mBase) {
    sz.mLimit = sz.mBase;
  }

  return sz.mState & TrackSize::eFlexMaxSizing;
}

void nsGridContainerFrame::Tracks::CalculateItemBaselines(
    nsTArray<ItemBaselineData>& aBaselineItems,
    BaselineSharingGroup aBaselineGroup) {
  if (aBaselineItems.IsEmpty()) {
    return;
  }

  // Sort the collected items on their baseline track.
  std::sort(aBaselineItems.begin(), aBaselineItems.end(),
            ItemBaselineData::IsBaselineTrackLessThan);

  MOZ_ASSERT(mSizes.Length() > 0, "having an item implies at least one track");
  const uint32_t lastTrack = mSizes.Length() - 1;
  nscoord maxBaseline = 0;
  nscoord maxDescent = 0;
  uint32_t currentTrack = kAutoLine;  // guaranteed to not match any item
  uint32_t trackStartIndex = 0;
  for (uint32_t i = 0, len = aBaselineItems.Length(); true; ++i) {
    // Find the maximum baseline and descent in the current track.
    if (i != len) {
      const ItemBaselineData& item = aBaselineItems[i];
      if (currentTrack == item.mBaselineTrack) {
        maxBaseline = std::max(maxBaseline, item.mBaseline);
        maxDescent = std::max(maxDescent, item.mSize - item.mBaseline);
        continue;
      }
    }
    // Iterate the current track again and update the baseline offsets making
    // all items baseline-aligned within this group in this track.
    for (uint32_t j = trackStartIndex; j < i; ++j) {
      const ItemBaselineData& item = aBaselineItems[j];
      item.mGridItem->mBaselineOffset[mAxis] = maxBaseline - item.mBaseline;
      MOZ_ASSERT(item.mGridItem->mBaselineOffset[mAxis] >= 0);
    }
    if (i != 0) {
      // Store the size of this baseline-aligned subtree.
      mSizes[currentTrack].mBaselineSubtreeSize[aBaselineGroup] =
          maxBaseline + maxDescent;
      // Record the first(last) baseline for the first(last) track.
      if (currentTrack == 0 && aBaselineGroup == BaselineSharingGroup::First) {
        mBaseline[aBaselineGroup] = maxBaseline;
      }
      if (currentTrack == lastTrack &&
          aBaselineGroup == BaselineSharingGroup::Last) {
        mBaseline[aBaselineGroup] = maxBaseline;
      }
    }
    if (i == len) {
      break;
    }
    // Initialize data for the next track with baseline-aligned items.
    const ItemBaselineData& item = aBaselineItems[i];
    currentTrack = item.mBaselineTrack;
    trackStartIndex = i;
    maxBaseline = item.mBaseline;
    maxDescent = item.mSize - item.mBaseline;
  }
}

void nsGridContainerFrame::Tracks::InitializeItemBaselines(
    GridReflowInput& aState, nsTArray<GridItemInfo>& aGridItems) {
  MOZ_ASSERT(!mIsMasonry);
  if (aState.mFrame->IsSubgrid(mAxis)) {
    // A grid container's subgridded axis doesn't have a baseline.
    return;
  }

  nsTArray<ItemBaselineData> firstBaselineItems;
  nsTArray<ItemBaselineData> lastBaselineItems;
  const WritingMode containerWM = aState.mWM;
  ComputedStyle* containerStyle = aState.mFrame->Style();

  // The physical side of the container's block start side.  We use it to match
  // against the physical block start side of the child to determine its
  // baseline sharing group.
  auto containerBlockStartSide =
      containerWM.PhysicalSide(MakeLogicalSide(mAxis, eLogicalEdgeStart));

  for (GridItemInfo& gridItem : aGridItems) {
    if (gridItem.IsSubgrid(mAxis)) {
      // A subgrid itself is never baseline-aligned.
      continue;
    }

    nsIFrame* child = gridItem.mFrame;
    uint32_t baselineTrack = kAutoLine;
    auto state = ItemState(0);
    const auto childWM = child->GetWritingMode();

    const bool isOrthogonal = containerWM.IsOrthogonalTo(childWM);
    const bool isInlineAxis = mAxis == eLogicalAxisInline;  // i.e. columns

    // XXX update the line below to include orthogonal grid/table boxes
    // XXX since they have baselines in both dimensions. And flexbox with
    // XXX reversed main/cross axis?
    const bool itemHasBaselineParallelToTrack = isInlineAxis == isOrthogonal;
    if (itemHasBaselineParallelToTrack) {
      // [align|justify]-self:[last ]baseline.
      auto selfAlignment =
          isOrthogonal
              ? child->StylePosition()->UsedJustifySelf(containerStyle)._0
              : child->StylePosition()->UsedAlignSelf(containerStyle)._0;
      selfAlignment &= ~StyleAlignFlags::FLAG_BITS;
      if (selfAlignment == StyleAlignFlags::BASELINE) {
        state |= ItemState::eFirstBaseline | ItemState::eSelfBaseline;
        const GridArea& area = gridItem.mArea;
        baselineTrack = isInlineAxis ? area.mCols.mStart : area.mRows.mStart;
      } else if (selfAlignment == StyleAlignFlags::LAST_BASELINE) {
        state |= ItemState::eLastBaseline | ItemState::eSelfBaseline;
        const GridArea& area = gridItem.mArea;
        baselineTrack = (isInlineAxis ? area.mCols.mEnd : area.mRows.mEnd) - 1;
      }

      // [align|justify]-content:[last ]baseline.
      // https://drafts.csswg.org/css-align-3/#baseline-align-content
      // "[...] and its computed 'align-self' or 'justify-self' (whichever
      // affects its block axis) is 'stretch' or 'self-start' ('self-end').
      // For this purpose, the 'start', 'end', 'flex-start', and 'flex-end'
      // values of 'align-self' are treated as either 'self-start' or
      // 'self-end', whichever they end up equivalent to.
      auto alignContent = child->StylePosition()->mAlignContent.primary;
      alignContent &= ~StyleAlignFlags::FLAG_BITS;
      if (alignContent == StyleAlignFlags::BASELINE ||
          alignContent == StyleAlignFlags::LAST_BASELINE) {
        const auto selfAlignEdge = alignContent == StyleAlignFlags::BASELINE
                                       ? StyleAlignFlags::SELF_START
                                       : StyleAlignFlags::SELF_END;
        bool validCombo = selfAlignment == StyleAlignFlags::NORMAL ||
                          selfAlignment == StyleAlignFlags::STRETCH ||
                          selfAlignment == selfAlignEdge;
        if (!validCombo) {
          // We're doing alignment in the axis that's orthogonal to mAxis here.
          LogicalAxis alignAxis = GetOrthogonalAxis(mAxis);
          // |sameSide| is true if the container's start side in this axis is
          // the same as the child's start side, in the child's parallel axis.
          bool sameSide =
              containerWM.ParallelAxisStartsOnSameSide(alignAxis, childWM);
          if (selfAlignment == StyleAlignFlags::LEFT) {
            selfAlignment = !isInlineAxis || containerWM.IsBidiLTR()
                                ? StyleAlignFlags::START
                                : StyleAlignFlags::END;
          } else if (selfAlignment == StyleAlignFlags::RIGHT) {
            selfAlignment = isInlineAxis && containerWM.IsBidiLTR()
                                ? StyleAlignFlags::END
                                : StyleAlignFlags::START;
          }

          if (selfAlignment == StyleAlignFlags::START ||
              selfAlignment == StyleAlignFlags::FLEX_START) {
            validCombo =
                sameSide == (alignContent == StyleAlignFlags::BASELINE);
          } else if (selfAlignment == StyleAlignFlags::END ||
                     selfAlignment == StyleAlignFlags::FLEX_END) {
            validCombo =
                sameSide == (alignContent == StyleAlignFlags::LAST_BASELINE);
          }
        }
        if (validCombo) {
          const GridArea& area = gridItem.mArea;
          if (alignContent == StyleAlignFlags::BASELINE) {
            state |= ItemState::eFirstBaseline | ItemState::eContentBaseline;
            baselineTrack =
                isInlineAxis ? area.mCols.mStart : area.mRows.mStart;
          } else if (alignContent == StyleAlignFlags::LAST_BASELINE) {
            state |= ItemState::eLastBaseline | ItemState::eContentBaseline;
            baselineTrack =
                (isInlineAxis ? area.mCols.mEnd : area.mRows.mEnd) - 1;
          }
        }
      }
    }

    if (state & ItemState::eIsBaselineAligned) {
      // The item is baseline aligned, so calculate the baseline sharing group.
      // <https://drafts.csswg.org/css-align-3/#baseline-terms>
      BaselineSharingGroup baselineAlignment =
          (state & ItemState::eFirstBaseline) ? BaselineSharingGroup::First
                                              : BaselineSharingGroup::Last;

      BaselineSharingGroup baselineSharingGroup = [&]() {
        {
          auto childAxis = isOrthogonal ? GetOrthogonalAxis(mAxis) : mAxis;
          auto childBlockStartSide = childWM.PhysicalSide(
              MakeLogicalSide(childAxis, eLogicalEdgeStart));
          bool isFirstBaseline = (state & ItemState::eFirstBaseline) != 0;
          const bool containerAndChildHasEqualBaselineSide =
              containerBlockStartSide == childBlockStartSide;

          return isFirstBaseline == containerAndChildHasEqualBaselineSide
                     ? BaselineSharingGroup::First
                     : BaselineSharingGroup::Last;
        }
      }();

      // XXXmats if |child| is a descendant of a subgrid then the metrics
      // below needs to account for the accumulated MPB somehow...

      // XXX available size issue
      LogicalSize avail(childWM, INFINITE_ISIZE_COORD, NS_UNCONSTRAINEDSIZE);
      auto* rc = &aState.mRenderingContext;
      // XXX figure out if we can avoid/merge this reflow with the main reflow.
      // XXX (after bug 1174569 is sorted out)
      //
      // XXX How should we handle percentage padding here? (bug 1330866)
      // XXX (see ::ContentContribution and how it deals with percentages)
      // XXX What if the true baseline after line-breaking differs from this
      // XXX hypothetical baseline based on an infinite inline size?
      // XXX Maybe we should just call ::ContentContribution here instead?
      // XXX For now we just pass an unconstrined-bsize CB:
      LogicalSize cbSize(childWM, 0, NS_UNCONSTRAINEDSIZE);
      ::MeasuringReflow(child, aState.mReflowInput, rc, avail, cbSize);

      nsGridContainerFrame* grid = do_QueryFrame(child);
      auto frameSize =
          isInlineAxis ? child->ISize(containerWM) : child->BSize(containerWM);
      auto margin = child->GetLogicalUsedMargin(containerWM);
      auto alignSize =
          frameSize + (isInlineAxis ? margin.IStartEnd(containerWM)
                                    : margin.BStartEnd(containerWM));

      Maybe<nscoord> baseline;
      if (grid) {
        baseline.emplace((isOrthogonal == isInlineAxis)
                             ? grid->GetBBaseline(baselineAlignment)
                             : grid->GetIBaseline(baselineAlignment));
      } else {
        baseline = child->GetNaturalBaselineBOffset(
            childWM, baselineAlignment, BaselineExportContext::Other);

        if (!baseline) {
          // If baseline alignment is specified on a grid item whose size in
          // that axis depends on the size of an intrinsically-sized track, that
          // item does not participate in baseline alignment, and instead uses
          // its fallback alignment as if that were originally specified.
          // https://drafts.csswg.org/css-grid-1/#row-align

          // Check if the item crosses any tracks that are intrinsically sized.
          auto range = gridItem.mArea.LineRangeForAxis(mAxis).Range();
          auto isTrackAutoSize =
              std::find_if(range.begin(), range.end(), [&](auto track) {
                constexpr auto intrinsicSizeFlags =
                    TrackSize::eIntrinsicMinSizing |
                    TrackSize::eIntrinsicMaxSizing | TrackSize::eFitContent |
                    TrackSize::eFlexMaxSizing;
                return (mSizes[track].mState & intrinsicSizeFlags) != 0;
              }) != range.end();

          // If either the track or the item is not auto sized, then the item
          // participates in baseline alignment.
          if (!isTrackAutoSize ||
              !gridItem.IsBSizeDependentOnContainerSize(containerWM)) {
            baseline.emplace(Baseline::SynthesizeBOffsetFromBorderBox(
                child, containerWM, baselineAlignment));
          }
        }
      }

      if (baseline) {
        nscoord finalBaseline = *baseline;
        NS_ASSERTION(finalBaseline != NS_INTRINSIC_ISIZE_UNKNOWN,
                     "about to use an unknown baseline");

        nscoord marginAdjust = 0;
        if (baselineSharingGroup == BaselineSharingGroup::First) {
          marginAdjust = isInlineAxis ? margin.IStart(containerWM)
                                      : margin.BStart(containerWM);
        } else {
          marginAdjust = isInlineAxis ? margin.IEnd(containerWM)
                                      : margin.BEnd(containerWM);

          // This flag is used in ::AlignSelf(...) to check whether the item is
          // last baseline aligned, but this flag should go away.
          state |= GridItemInfo::eEndSideBaseline;
        }
        finalBaseline += marginAdjust;

        auto& baselineItems =
            (baselineSharingGroup == BaselineSharingGroup::First)
                ? firstBaselineItems
                : lastBaselineItems;
        baselineItems.AppendElement(ItemBaselineData{
            baselineTrack, finalBaseline, alignSize, &gridItem});
      } else {
        state &= ~ItemState::eAllBaselineBits;
      }
    }

    MOZ_ASSERT(
        (state & (ItemState::eFirstBaseline | ItemState::eLastBaseline)) !=
            (ItemState::eFirstBaseline | ItemState::eLastBaseline),
        "first/last baseline bits are mutually exclusive");
    MOZ_ASSERT(
        (state & (ItemState::eSelfBaseline | ItemState::eContentBaseline)) !=
            (ItemState::eSelfBaseline | ItemState::eContentBaseline),
        "*-self and *-content baseline bits are mutually exclusive");
    MOZ_ASSERT(
        !(state & (ItemState::eFirstBaseline | ItemState::eLastBaseline)) ==
            !(state & (ItemState::eSelfBaseline | ItemState::eContentBaseline)),
        "first/last bit requires self/content bit and vice versa");

    gridItem.mState[mAxis] |= state;
    gridItem.mBaselineOffset[mAxis] = nscoord(0);
  }

  if (firstBaselineItems.IsEmpty() && lastBaselineItems.IsEmpty()) {
    return;
  }

  // TODO: CSS Align spec issue - how to align a baseline subtree in a track?
  // https://lists.w3.org/Archives/Public/www-style/2016May/0141.html
  mBaselineSubtreeAlign[BaselineSharingGroup::First] = StyleAlignFlags::START;
  mBaselineSubtreeAlign[BaselineSharingGroup::Last] = StyleAlignFlags::END;

  CalculateItemBaselines(firstBaselineItems, BaselineSharingGroup::First);
  CalculateItemBaselines(lastBaselineItems, BaselineSharingGroup::Last);
}

// TODO: we store the wrong baseline group offset in some cases (bug 1632200)
void nsGridContainerFrame::Tracks::InitializeItemBaselinesInMasonryAxis(
    GridReflowInput& aState, nsTArray<GridItemInfo>& aGridItems,
    BaselineAlignmentSet aSet, const nsSize& aContainerSize,
    nsTArray<nscoord>& aTrackSizes,
    nsTArray<ItemBaselineData>& aFirstBaselineItems,
    nsTArray<ItemBaselineData>& aLastBaselineItems) {
  MOZ_ASSERT(mIsMasonry);
  WritingMode wm = aState.mWM;
  ComputedStyle* containerSC = aState.mFrame->Style();
  for (GridItemInfo& gridItem : aGridItems) {
    if (gridItem.IsSubgrid(mAxis)) {
      // A subgrid itself is never baseline-aligned.
      continue;
    }
    const auto& area = gridItem.mArea;
    if (aSet.mItemSet == BaselineAlignmentSet::LastItems) {
      // NOTE: eIsLastItemInMasonryTrack is set also if the item is the ONLY
      // item in its track; the eIsBaselineAligned check excludes it though
      // since it participates in the start baseline groups in that case.
      //
      // XXX what if it's the only item in THAT baseline group?
      // XXX should it participate in the last-item group instead then
      // if there are more baseline-aligned items there?
      if (!(gridItem.mState[mAxis] & ItemState::eIsLastItemInMasonryTrack) ||
          (gridItem.mState[mAxis] & ItemState::eIsBaselineAligned)) {
        continue;
      }
    } else {
      if (area.LineRangeForAxis(mAxis).mStart > 0 ||
          (gridItem.mState[mAxis] & ItemState::eIsBaselineAligned)) {
        continue;
      }
    }
    auto trackAlign =
        aState.mGridStyle
            ->UsedTracksAlignment(
                mAxis, area.LineRangeForAxis(GetOrthogonalAxis(mAxis)).mStart)
            .primary;
    if (!aSet.MatchTrackAlignment(trackAlign)) {
      continue;
    }

    nsIFrame* child = gridItem.mFrame;
    uint32_t baselineTrack = kAutoLine;
    auto state = ItemState(0);
    auto childWM = child->GetWritingMode();
    const bool isOrthogonal = wm.IsOrthogonalTo(childWM);
    const bool isInlineAxis = mAxis == eLogicalAxisInline;  // i.e. columns
    // XXX update the line below to include orthogonal grid/table boxes
    // XXX since they have baselines in both dimensions. And flexbox with
    // XXX reversed main/cross axis?
    const bool itemHasBaselineParallelToTrack = isInlineAxis == isOrthogonal;
    if (itemHasBaselineParallelToTrack) {
      const auto* pos = child->StylePosition();
      // [align|justify]-self:[last ]baseline.
      auto selfAlignment = pos->UsedSelfAlignment(mAxis, containerSC);
      selfAlignment &= ~StyleAlignFlags::FLAG_BITS;
      if (selfAlignment == StyleAlignFlags::BASELINE) {
        state |= ItemState::eFirstBaseline | ItemState::eSelfBaseline;
        baselineTrack = isInlineAxis ? area.mCols.mStart : area.mRows.mStart;
      } else if (selfAlignment == StyleAlignFlags::LAST_BASELINE) {
        state |= ItemState::eLastBaseline | ItemState::eSelfBaseline;
        baselineTrack = (isInlineAxis ? area.mCols.mEnd : area.mRows.mEnd) - 1;
      } else {
        // [align|justify]-content:[last ]baseline.
        auto childAxis = isOrthogonal ? GetOrthogonalAxis(mAxis) : mAxis;
        auto alignContent = pos->UsedContentAlignment(childAxis).primary;
        alignContent &= ~StyleAlignFlags::FLAG_BITS;
        if (alignContent == StyleAlignFlags::BASELINE) {
          state |= ItemState::eFirstBaseline | ItemState::eContentBaseline;
          baselineTrack = isInlineAxis ? area.mCols.mStart : area.mRows.mStart;
        } else if (alignContent == StyleAlignFlags::LAST_BASELINE) {
          state |= ItemState::eLastBaseline | ItemState::eContentBaseline;
          baselineTrack =
              (isInlineAxis ? area.mCols.mEnd : area.mRows.mEnd) - 1;
        }
      }
    }

    if (state & ItemState::eIsBaselineAligned) {
      // XXXmats if |child| is a descendant of a subgrid then the metrics
      // below needs to account for the accumulated MPB somehow...

      nscoord baseline;
      nsGridContainerFrame* grid = do_QueryFrame(child);
      if (state & ItemState::eFirstBaseline) {
        if (grid) {
          if (isOrthogonal == isInlineAxis) {
            baseline = grid->GetBBaseline(BaselineSharingGroup::First);
          } else {
            baseline = grid->GetIBaseline(BaselineSharingGroup::First);
          }
        }
        if (grid || nsLayoutUtils::GetFirstLineBaseline(wm, child, &baseline)) {
          NS_ASSERTION(baseline != NS_INTRINSIC_ISIZE_UNKNOWN,
                       "about to use an unknown baseline");
          auto frameSize = isInlineAxis ? child->ISize(wm) : child->BSize(wm);
          nscoord alignSize;
          LogicalPoint pos =
              child->GetLogicalNormalPosition(wm, aContainerSize);
          baseline += pos.Pos(mAxis, wm);
          if (aSet.mTrackAlignmentSet == BaselineAlignmentSet::EndStretch) {
            state |= ItemState::eEndSideBaseline;
            // Convert to distance from the track end.
            baseline =
                aTrackSizes[gridItem.mArea
                                .LineRangeForAxis(GetOrthogonalAxis(mAxis))
                                .mStart] -
                baseline;
          }
          alignSize = frameSize;
          aFirstBaselineItems.AppendElement(ItemBaselineData(
              {baselineTrack, baseline, alignSize, &gridItem}));
        } else {
          state &= ~ItemState::eAllBaselineBits;
        }
      } else {
        if (grid) {
          if (isOrthogonal == isInlineAxis) {
            baseline = grid->GetBBaseline(BaselineSharingGroup::Last);
          } else {
            baseline = grid->GetIBaseline(BaselineSharingGroup::Last);
          }
        }
        if (grid || nsLayoutUtils::GetLastLineBaseline(wm, child, &baseline)) {
          NS_ASSERTION(baseline != NS_INTRINSIC_ISIZE_UNKNOWN,
                       "about to use an unknown baseline");
          auto frameSize = isInlineAxis ? child->ISize(wm) : child->BSize(wm);
          auto m = child->GetLogicalUsedMargin(wm);
          if (!grid &&
              aSet.mTrackAlignmentSet == BaselineAlignmentSet::EndStretch) {
            // Convert to distance from border-box end.
            state |= ItemState::eEndSideBaseline;
            LogicalPoint pos =
                child->GetLogicalNormalPosition(wm, aContainerSize);
            baseline += pos.Pos(mAxis, wm);
            baseline =
                aTrackSizes[gridItem.mArea
                                .LineRangeForAxis(GetOrthogonalAxis(mAxis))
                                .mStart] -
                baseline;
          } else if (grid && aSet.mTrackAlignmentSet ==
                                 BaselineAlignmentSet::StartStretch) {
            // Convert to distance from border-box start.
            baseline = frameSize - baseline;
          }
          if (aSet.mItemSet == BaselineAlignmentSet::LastItems &&
              aSet.mTrackAlignmentSet == BaselineAlignmentSet::StartStretch) {
            LogicalPoint pos =
                child->GetLogicalNormalPosition(wm, aContainerSize);
            baseline += pos.B(wm);
          }
          if (aSet.mTrackAlignmentSet == BaselineAlignmentSet::EndStretch) {
            state |= ItemState::eEndSideBaseline;
          }
          auto descent =
              baseline + ((state & ItemState::eEndSideBaseline)
                              ? (isInlineAxis ? m.IEnd(wm) : m.BEnd(wm))
                              : (isInlineAxis ? m.IStart(wm) : m.BStart(wm)));
          auto alignSize =
              frameSize + (isInlineAxis ? m.IStartEnd(wm) : m.BStartEnd(wm));
          aLastBaselineItems.AppendElement(
              ItemBaselineData({baselineTrack, descent, alignSize, &gridItem}));
        } else {
          state &= ~ItemState::eAllBaselineBits;
        }
      }
    }
    MOZ_ASSERT(
        (state & (ItemState::eFirstBaseline | ItemState::eLastBaseline)) !=
            (ItemState::eFirstBaseline | ItemState::eLastBaseline),
        "first/last baseline bits are mutually exclusive");
    MOZ_ASSERT(
        (state & (ItemState::eSelfBaseline | ItemState::eContentBaseline)) !=
            (ItemState::eSelfBaseline | ItemState::eContentBaseline),
        "*-self and *-content baseline bits are mutually exclusive");
    MOZ_ASSERT(
        !(state & (ItemState::eFirstBaseline | ItemState::eLastBaseline)) ==
            !(state & (ItemState::eSelfBaseline | ItemState::eContentBaseline)),
        "first/last bit requires self/content bit and vice versa");
    gridItem.mState[mAxis] |= state;
    gridItem.mBaselineOffset[mAxis] = nscoord(0);
  }

  CalculateItemBaselines(aFirstBaselineItems, BaselineSharingGroup::First);
  CalculateItemBaselines(aLastBaselineItems, BaselineSharingGroup::Last);

  // TODO: make sure the mBaselines (i.e. the baselines we export from
  // the grid container) are offset from the correct container edge.
  // Also, which of the baselines do we pick to export exactly?

  MOZ_ASSERT(aFirstBaselineItems.Length() != 1 ||
                 aFirstBaselineItems[0].mGridItem->mBaselineOffset[mAxis] == 0,
             "a baseline group that contains only one item should not "
             "produce a non-zero item baseline offset");
  MOZ_ASSERT(aLastBaselineItems.Length() != 1 ||
                 aLastBaselineItems[0].mGridItem->mBaselineOffset[mAxis] == 0,
             "a baseline group that contains only one item should not "
             "produce a non-zero item baseline offset");
}

void nsGridContainerFrame::Tracks::AlignBaselineSubtree(
    const GridItemInfo& aGridItem) const {
  if (mIsMasonry) {
    return;
  }
  auto state = aGridItem.mState[mAxis];
  if (!(state & ItemState::eIsBaselineAligned)) {
    return;
  }
  const GridArea& area = aGridItem.mArea;
  int32_t baselineTrack;
  const bool isFirstBaseline = state & ItemState::eFirstBaseline;
  if (isFirstBaseline) {
    baselineTrack =
        mAxis == eLogicalAxisBlock ? area.mRows.mStart : area.mCols.mStart;
  } else {
    baselineTrack =
        (mAxis == eLogicalAxisBlock ? area.mRows.mEnd : area.mCols.mEnd) - 1;
  }
  const TrackSize& sz = mSizes[baselineTrack];
  auto baselineGroup = isFirstBaseline ? BaselineSharingGroup::First
                                       : BaselineSharingGroup::Last;
  nscoord delta = sz.mBase - sz.mBaselineSubtreeSize[baselineGroup];
  const auto subtreeAlign = mBaselineSubtreeAlign[baselineGroup];
  if (subtreeAlign == StyleAlignFlags::START) {
    if (state & ItemState::eLastBaseline) {
      aGridItem.mBaselineOffset[mAxis] += delta;
    }
  } else if (subtreeAlign == StyleAlignFlags::END) {
    if (isFirstBaseline) {
      aGridItem.mBaselineOffset[mAxis] += delta;
    }
  } else if (subtreeAlign == StyleAlignFlags::CENTER) {
    aGridItem.mBaselineOffset[mAxis] += delta / 2;
  } else {
    MOZ_ASSERT_UNREACHABLE("unexpected baseline subtree alignment");
  }
}

template <nsGridContainerFrame::Tracks::TrackSizingPhase phase>
bool nsGridContainerFrame::Tracks::GrowSizeForSpanningItems(
    nsTArray<SpanningItemData>::iterator aIter,
    nsTArray<SpanningItemData>::iterator aIterEnd, nsTArray<uint32_t>& aTracks,
    nsTArray<TrackSize>& aPlan, nsTArray<TrackSize>& aItemPlan,
    TrackSize::StateBits aSelector, const FitContentClamper& aFitContentClamper,
    bool aNeedInfinitelyGrowableFlag) {
  constexpr bool isMaxSizingPhase =
      phase == TrackSizingPhase::IntrinsicMaximums ||
      phase == TrackSizingPhase::MaxContentMaximums;
  bool needToUpdateSizes = false;
  InitializePlan<phase>(aPlan);
  for (; aIter != aIterEnd; ++aIter) {
    const SpanningItemData& item = *aIter;
    if (!(item.mState & aSelector)) {
      continue;
    }
    if (isMaxSizingPhase) {
      for (auto i : item.mLineRange.Range()) {
        aPlan[i].mState |= TrackSize::eModified;
      }
    }
    nscoord space = item.SizeContributionForPhase<phase>();
    if (space <= 0) {
      continue;
    }
    aTracks.ClearAndRetainStorage();
    space = CollectGrowable<phase>(space, item.mLineRange, aSelector, aTracks);
    if (space > 0) {
      DistributeToTrackSizes<phase>(space, aPlan, aItemPlan, aTracks, aSelector,
                                    aFitContentClamper);
      needToUpdateSizes = true;
    }
  }
  if (isMaxSizingPhase) {
    needToUpdateSizes = true;
  }
  if (needToUpdateSizes) {
    CopyPlanToSize<phase>(aPlan, aNeedInfinitelyGrowableFlag);
  }
  return needToUpdateSizes;
}

void nsGridContainerFrame::Tracks::ResolveIntrinsicSize(
    GridReflowInput& aState, nsTArray<GridItemInfo>& aGridItems,
    const TrackSizingFunctions& aFunctions, LineRange GridArea::*aRange,
    nscoord aPercentageBasis, SizingConstraint aConstraint) {
  // Resolve Intrinsic Track Sizes
  // https://w3c.github.io/csswg-drafts/css-grid-1/#algo-content
  // We're also setting eIsFlexing on the item state here to speed up
  // FindUsedFlexFraction later.

  gfxContext* rc = &aState.mRenderingContext;
  WritingMode wm = aState.mWM;

  // Data we accumulate when grouping similar sized spans together.
  struct PerSpanData {
    uint32_t mItemCountWithSameSpan = 0;
    TrackSize::StateBits mStateBits = TrackSize::StateBits{0};
  };
  AutoTArray<PerSpanData, 16> perSpanData;

  nsTArray<SpanningItemData> spanningItems;
  uint32_t maxSpan = 0;  // max span of items in `spanningItems`.

  // Setup track selector for step 3.2:
  const auto contentBasedMinSelector =
      aConstraint == SizingConstraint::MinContent
          ? TrackSize::eIntrinsicMinSizing
          : TrackSize::eMinOrMaxContentMinSizing;

  // Setup track selector for step 3.3:
  const auto maxContentMinSelector =
      aConstraint == SizingConstraint::MaxContent
          ? (TrackSize::eMaxContentMinSizing | TrackSize::eAutoMinSizing)
          : TrackSize::eMaxContentMinSizing;

  const auto orthogonalAxis = GetOrthogonalAxis(mAxis);
  const bool isMasonryInOtherAxis = aState.mFrame->IsMasonry(orthogonalAxis);

  for (auto& gridItem : aGridItems) {
    MOZ_ASSERT(!(gridItem.mState[mAxis] &
                 (ItemState::eApplyAutoMinSize | ItemState::eIsFlexing |
                  ItemState::eClampMarginBoxMinSize)),
               "Why are any of these bits set already?");

    const GridArea& area = gridItem.mArea;
    const LineRange& lineRange = area.*aRange;

    // If we have masonry layout in the other axis then skip this item unless
    // it's in the first masonry track, or has definite placement in this axis,
    // or spans all tracks in this axis (since that implies it will be placed
    // at line 1 regardless of layout results of other items).
    if (isMasonryInOtherAxis &&
        gridItem.mArea.LineRangeForAxis(orthogonalAxis).mStart != 0 &&
        (gridItem.mState[mAxis] & ItemState::eAutoPlacement) &&
        gridItem.mArea.LineRangeForAxis(mAxis).Extent() != mSizes.Length()) {
      continue;
    }

    uint32_t span = lineRange.Extent();
    if (MOZ_UNLIKELY(gridItem.mState[mAxis] & ItemState::eIsSubgrid)) {
      auto itemWM = gridItem.mFrame->GetWritingMode();
      auto percentageBasis = aState.PercentageBasisFor(mAxis, gridItem);

      if (percentageBasis.ISize(itemWM) == NS_UNCONSTRAINEDSIZE) {
        percentageBasis.ISize(itemWM) = nscoord(0);
      }

      if (percentageBasis.BSize(itemWM) == NS_UNCONSTRAINEDSIZE) {
        percentageBasis.BSize(itemWM) = nscoord(0);
      }

      auto* subgrid =
          SubgridComputeMarginBorderPadding(gridItem, percentageBasis);
      LogicalMargin mbp = SubgridAccumulatedMarginBorderPadding(
          gridItem.SubgridFrame(), subgrid, wm, mAxis);

      if (span == 1) {
        AddSubgridContribution(mSizes[lineRange.mStart],
                               mbp.StartEnd(mAxis, wm));
      } else {
        AddSubgridContribution(mSizes[lineRange.mStart], mbp.Start(mAxis, wm));
        AddSubgridContribution(mSizes[lineRange.mEnd - 1], mbp.End(mAxis, wm));
      }
      continue;
    }

    if (span == 1) {
      // Step 2. Size tracks to fit non-spanning items.
      if (ResolveIntrinsicSizeForNonSpanningItems(aState, aFunctions,
                                                  aPercentageBasis, aConstraint,
                                                  lineRange, gridItem)) {
        gridItem.mState[mAxis] |= ItemState::eIsFlexing;
      }
    } else {
      TrackSize::StateBits state = StateBitsForRange(lineRange);

      // Check if we need to apply "Automatic Minimum Size" and cache it.
      if ((state & TrackSize::eAutoMinSizing) &&
          !(state & TrackSize::eFlexMaxSizing) &&
          gridItem.ShouldApplyAutoMinSize(wm, mAxis, aPercentageBasis)) {
        gridItem.mState[mAxis] |= ItemState::eApplyAutoMinSize;
      }

      if (state & TrackSize::eFlexMaxSizing) {
        gridItem.mState[mAxis] |= ItemState::eIsFlexing;
      } else if (state & (TrackSize::eIntrinsicMinSizing |
                          TrackSize::eIntrinsicMaxSizing)) {
        // Collect data for Step 3.
        maxSpan = std::max(maxSpan, span);
        if (span >= perSpanData.Length()) {
          perSpanData.SetLength(2 * span);
        }

        perSpanData[span].mItemCountWithSameSpan++;
        perSpanData[span].mStateBits |= state;

        CachedIntrinsicSizes cache;

        // Calculate data for "Automatic Minimum Size" clamping, if needed.
        if (TrackSize::IsDefiniteMaxSizing(state) &&
            (gridItem.mState[mAxis] & ItemState::eApplyAutoMinSize)) {
          nscoord minSizeClamp = 0;
          for (auto i : lineRange.Range()) {
            minSizeClamp += aFunctions.MaxSizingFor(i).AsBreadth().Resolve(
                aPercentageBasis);
          }
          minSizeClamp += mGridGap * (span - 1);
          cache.mMinSizeClamp = minSizeClamp;
          gridItem.mState[mAxis] |= ItemState::eClampMarginBoxMinSize;
        }

        // Collect the various grid item size contributions we need.
        nscoord minSize = 0;
        if (state & TrackSize::eIntrinsicMinSizing) {  // for 3.1
          minSize = MinSize(gridItem, aState, rc, wm, mAxis, &cache);
        }
        nscoord minContent = 0;
        if (state & (contentBasedMinSelector |           // for 3.2
                     TrackSize::eIntrinsicMaxSizing)) {  // for 3.5
          minContent =
              MinContentContribution(gridItem, aState, rc, wm, mAxis, &cache);
        }
        nscoord maxContent = 0;
        if (state & (maxContentMinSelector |                    // for 3.3
                     TrackSize::eAutoOrMaxContentMaxSizing)) {  // for 3.6
          maxContent =
              MaxContentContribution(gridItem, aState, rc, wm, mAxis, &cache);
        }

        spanningItems.AppendElement(
            SpanningItemData({span, state, lineRange, minSize, minContent,
                              maxContent, gridItem.mFrame}));
      }
    }

    MOZ_ASSERT(!(gridItem.mState[mAxis] & ItemState::eClampMarginBoxMinSize) ||
                   (gridItem.mState[mAxis] & ItemState::eApplyAutoMinSize),
               "clamping only applies to Automatic Minimum Size");
  }

  // Step 3 - Increase sizes to accommodate spanning items crossing
  // content-sized tracks.
  if (maxSpan) {
    auto fitContentClamper = [&aFunctions, aPercentageBasis](uint32_t aTrack,
                                                             nscoord aMinSize,
                                                             nscoord* aSize) {
      nscoord fitContentLimit = ::ResolveToDefiniteSize(
          aFunctions.MaxSizingFor(aTrack), aPercentageBasis);
      if (*aSize > fitContentLimit) {
        *aSize = std::max(aMinSize, fitContentLimit);
        return true;
      }
      return false;
    };

    // Sort the collected items on span length, shortest first.  There's no need
    // for a stable sort here since the sizing isn't order dependent within
    // a group of items with the same span length.
    std::sort(spanningItems.begin(), spanningItems.end(),
              SpanningItemData::IsSpanLessThan);

    nsTArray<uint32_t> tracks(maxSpan);
    nsTArray<TrackSize> plan(mSizes.Length());
    plan.SetLength(mSizes.Length());
    nsTArray<TrackSize> itemPlan(mSizes.Length());
    itemPlan.SetLength(mSizes.Length());
    // Start / end iterator for items of the same span length:
    auto spanGroupStart = spanningItems.begin();
    auto spanGroupEnd = spanGroupStart;
    const auto end = spanningItems.end();
    for (; spanGroupStart != end; spanGroupStart = spanGroupEnd) {
      const uint32_t span = spanGroupStart->mSpan;
      spanGroupEnd = spanGroupStart + perSpanData[span].mItemCountWithSameSpan;
      TrackSize::StateBits stateBitsForSpan = perSpanData[span].mStateBits;
      bool updatedBase = false;  // Did we update any mBase in step 3.1..3.3?
      TrackSize::StateBits selector(TrackSize::eIntrinsicMinSizing);
      if (stateBitsForSpan & selector) {
        // Step 3.1 MinSize to intrinsic min-sizing.
        updatedBase =
            GrowSizeForSpanningItems<TrackSizingPhase::IntrinsicMinimums>(
                spanGroupStart, spanGroupEnd, tracks, plan, itemPlan, selector);
      }

      selector = contentBasedMinSelector;
      if (stateBitsForSpan & selector) {
        // Step 3.2 MinContentContribution to min-/max-content (and 'auto' when
        // sizing under a min-content constraint) min-sizing.
        updatedBase |=
            GrowSizeForSpanningItems<TrackSizingPhase::ContentBasedMinimums>(
                spanGroupStart, spanGroupEnd, tracks, plan, itemPlan, selector);
      }

      selector = maxContentMinSelector;
      if (stateBitsForSpan & selector) {
        // Step 3.3 MaxContentContribution to max-content (and 'auto' when
        // sizing under a max-content constraint) min-sizing.
        updatedBase |=
            GrowSizeForSpanningItems<TrackSizingPhase::MaxContentMinimums>(
                spanGroupStart, spanGroupEnd, tracks, plan, itemPlan, selector);
      }

      if (updatedBase) {
        // Step 3.4
        for (TrackSize& sz : mSizes) {
          if (sz.mBase > sz.mLimit) {
            sz.mLimit = sz.mBase;
          }
        }
      }

      selector = TrackSize::eIntrinsicMaxSizing;
      if (stateBitsForSpan & selector) {
        const bool willRunStep3_6 =
            stateBitsForSpan & TrackSize::eAutoOrMaxContentMaxSizing;
        // Step 3.5 MinContentContribution to intrinsic max-sizing.
        GrowSizeForSpanningItems<TrackSizingPhase::IntrinsicMaximums>(
            spanGroupStart, spanGroupEnd, tracks, plan, itemPlan, selector,
            fitContentClamper, willRunStep3_6);

        if (willRunStep3_6) {
          // Step 2.6 MaxContentContribution to max-content max-sizing.
          selector = TrackSize::eAutoOrMaxContentMaxSizing;
          GrowSizeForSpanningItems<TrackSizingPhase::MaxContentMaximums>(
              spanGroupStart, spanGroupEnd, tracks, plan, itemPlan, selector,
              fitContentClamper);
        }
      }
    }
  }

  // Step 5 - If any track still has an infinite growth limit, set its growth
  // limit to its base size.
  for (TrackSize& sz : mSizes) {
    if (sz.mLimit == NS_UNCONSTRAINEDSIZE) {
      sz.mLimit = sz.mBase;
    }
  }
}

float nsGridContainerFrame::Tracks::FindFrUnitSize(
    const LineRange& aRange, const nsTArray<uint32_t>& aFlexTracks,
    const TrackSizingFunctions& aFunctions, nscoord aSpaceToFill) const {
  MOZ_ASSERT(aSpaceToFill > 0 && !aFlexTracks.IsEmpty());
  float flexFactorSum = 0.0f;
  nscoord leftOverSpace = aSpaceToFill;
  for (auto i : aRange.Range()) {
    const TrackSize& sz = mSizes[i];
    if (sz.mState & TrackSize::eFlexMaxSizing) {
      flexFactorSum += aFunctions.MaxSizingFor(i).AsFr();
    } else {
      leftOverSpace -= sz.mBase;
      if (leftOverSpace <= 0) {
        return 0.0f;
      }
    }
  }
  bool restart;
  float hypotheticalFrSize;
  nsTArray<uint32_t> flexTracks(aFlexTracks.Clone());
  uint32_t numFlexTracks = flexTracks.Length();
  do {
    restart = false;
    hypotheticalFrSize = leftOverSpace / std::max(flexFactorSum, 1.0f);
    for (uint32_t i = 0, len = flexTracks.Length(); i < len; ++i) {
      uint32_t track = flexTracks[i];
      if (track == kAutoLine) {
        continue;  // Track marked as inflexible in a prev. iter of this loop.
      }
      float flexFactor = aFunctions.MaxSizingFor(track).AsFr();
      const nscoord base = mSizes[track].mBase;
      if (flexFactor * hypotheticalFrSize < base) {
        // 12.7.1.4: Treat this track as inflexible.
        flexTracks[i] = kAutoLine;
        flexFactorSum -= flexFactor;
        leftOverSpace -= base;
        --numFlexTracks;
        if (numFlexTracks == 0 || leftOverSpace <= 0) {
          return 0.0f;
        }
        restart = true;
        // break; XXX (bug 1176621 comment 16) measure which is more common
      }
    }
  } while (restart);
  return hypotheticalFrSize;
}

float nsGridContainerFrame::Tracks::FindUsedFlexFraction(
    GridReflowInput& aState, nsTArray<GridItemInfo>& aGridItems,
    const nsTArray<uint32_t>& aFlexTracks,
    const TrackSizingFunctions& aFunctions, nscoord aAvailableSize) const {
  if (aAvailableSize != NS_UNCONSTRAINEDSIZE) {
    // Use all of the grid tracks and a 'space to fill' of the available space.
    const TranslatedLineRange range(0, mSizes.Length());
    return FindFrUnitSize(range, aFlexTracks, aFunctions, aAvailableSize);
  }

  // The used flex fraction is the maximum of:
  // ... each flexible track's base size divided by its flex factor (which is
  // floored at 1).
  float fr = 0.0f;
  for (uint32_t track : aFlexTracks) {
    float flexFactor = aFunctions.MaxSizingFor(track).AsFr();
    float possiblyDividedBaseSize = (flexFactor > 1.0f)
                                        ? mSizes[track].mBase / flexFactor
                                        : mSizes[track].mBase;
    fr = std::max(fr, possiblyDividedBaseSize);
  }
  WritingMode wm = aState.mWM;
  gfxContext* rc = &aState.mRenderingContext;
  // ... the result of 'finding the size of an fr' for each item that spans
  // a flex track with its max-content contribution as 'space to fill'
  for (const GridItemInfo& item : aGridItems) {
    if (item.mState[mAxis] & ItemState::eIsFlexing) {
      // XXX optimize: bug 1194446
      auto pb = Some(aState.PercentageBasisFor(mAxis, item));
      nscoord spaceToFill = ContentContribution(item, aState, rc, wm, mAxis, pb,
                                                IntrinsicISizeType::PrefISize);
      const LineRange& range =
          mAxis == eLogicalAxisInline ? item.mArea.mCols : item.mArea.mRows;
      MOZ_ASSERT(range.Extent() >= 1);
      const auto spannedGaps = range.Extent() - 1;
      if (spannedGaps > 0) {
        spaceToFill -= mGridGap * spannedGaps;
      }
      if (spaceToFill <= 0) {
        continue;
      }
      // ... and all its spanned tracks as input.
      nsTArray<uint32_t> itemFlexTracks;
      for (auto i : range.Range()) {
        if (mSizes[i].mState & TrackSize::eFlexMaxSizing) {
          itemFlexTracks.AppendElement(i);
        }
      }
      float itemFr =
          FindFrUnitSize(range, itemFlexTracks, aFunctions, spaceToFill);
      fr = std::max(fr, itemFr);
    }
  }
  return fr;
}

void nsGridContainerFrame::Tracks::StretchFlexibleTracks(
    GridReflowInput& aState, nsTArray<GridItemInfo>& aGridItems,
    const TrackSizingFunctions& aFunctions, nscoord aAvailableSize) {
  if (aAvailableSize <= 0) {
    return;
  }
  nsTArray<uint32_t> flexTracks(mSizes.Length());
  for (uint32_t i = 0, len = mSizes.Length(); i < len; ++i) {
    if (mSizes[i].mState & TrackSize::eFlexMaxSizing) {
      flexTracks.AppendElement(i);
    }
  }
  if (flexTracks.IsEmpty()) {
    return;
  }
  nscoord minSize = 0;
  nscoord maxSize = NS_UNCONSTRAINEDSIZE;
  if (aState.mReflowInput) {
    auto* ri = aState.mReflowInput;
    minSize = mAxis == eLogicalAxisBlock ? ri->ComputedMinBSize()
                                         : ri->ComputedMinISize();
    maxSize = mAxis == eLogicalAxisBlock ? ri->ComputedMaxBSize()
                                         : ri->ComputedMaxISize();
  }
  Maybe<CopyableAutoTArray<TrackSize, 32>> origSizes;
  bool applyMinMax = (minSize != 0 || maxSize != NS_UNCONSTRAINEDSIZE) &&
                     aAvailableSize == NS_UNCONSTRAINEDSIZE;
  // We iterate twice at most.  The 2nd time if the grid size changed after
  // applying a min/max-size (can only occur if aAvailableSize is indefinite).
  while (true) {
    float fr = FindUsedFlexFraction(aState, aGridItems, flexTracks, aFunctions,
                                    aAvailableSize);
    if (fr != 0.0f) {
      for (uint32_t i : flexTracks) {
        float flexFactor = aFunctions.MaxSizingFor(i).AsFr();
        nscoord flexLength = NSToCoordRound(flexFactor * fr);
        nscoord& base = mSizes[i].mBase;
        if (flexLength > base) {
          if (applyMinMax && origSizes.isNothing()) {
            origSizes.emplace(mSizes);
          }
          base = flexLength;
        }
      }
    }
    if (applyMinMax) {
      applyMinMax = false;
      // https://drafts.csswg.org/css-grid/#algo-flex-tracks
      // "If using this flex fraction would cause the grid to be smaller than
      // the grid container’s min-width/height (or larger than the grid
      // container’s max-width/height), then redo this step, treating the free
      // space as definite [...]"
      const auto sumOfGridGaps = SumOfGridGaps();
      nscoord newSize = SumOfGridTracks() + sumOfGridGaps;
      if (newSize > maxSize) {
        aAvailableSize = maxSize;
      } else if (newSize < minSize) {
        aAvailableSize = minSize;
      }
      if (aAvailableSize != NS_UNCONSTRAINEDSIZE) {
        aAvailableSize = std::max(0, aAvailableSize - sumOfGridGaps);
        // Restart with the original track sizes and definite aAvailableSize.
        if (origSizes.isSome()) {
          mSizes = std::move(*origSizes);
          origSizes.reset();
        }  // else, no mSizes[].mBase were changed above so it's still correct
        if (aAvailableSize == 0) {
          break;  // zero available size wouldn't change any sizes though...
        }
        continue;
      }
    }
    break;
  }
}

void nsGridContainerFrame::Tracks::AlignJustifyContent(
    const nsStylePosition* aStyle, StyleContentDistribution aAligmentStyleValue,
    WritingMode aWM, nscoord aContentBoxSize, bool aIsSubgriddedAxis) {
  const bool isAlign = mAxis == eLogicalAxisBlock;
  // Align-/justify-content doesn't apply in a subgridded axis.
  // Gap properties do apply though so we need to stretch/position the tracks
  // to center-align the gaps with the parent's gaps.
  if (MOZ_UNLIKELY(aIsSubgriddedAxis)) {
    auto& gap = isAlign ? aStyle->mRowGap : aStyle->mColumnGap;
    if (gap.IsNormal()) {
      return;
    }
    auto len = mSizes.Length();
    if (len <= 1) {
      return;
    }
    // This stores the gap deltas between the subgrid gap and the gaps in
    // the used track sizes (as encoded in its tracks' mPosition):
    nsTArray<nscoord> gapDeltas;
    const size_t numGaps = len - 1;
    gapDeltas.SetLength(numGaps);
    for (size_t i = 0; i < numGaps; ++i) {
      TrackSize& sz1 = mSizes[i];
      TrackSize& sz2 = mSizes[i + 1];
      nscoord currentGap = sz2.mPosition - (sz1.mPosition + sz1.mBase);
      gapDeltas[i] = mGridGap - currentGap;
    }
    // Recompute the tracks' size/position so that they end up with
    // a subgrid-gap centered on the original track gap.
    nscoord currentPos = mSizes[0].mPosition;
    nscoord lastHalfDelta(0);
    for (size_t i = 0; i < numGaps; ++i) {
      TrackSize& sz = mSizes[i];
      nscoord delta = gapDeltas[i];
      nscoord halfDelta;
      nscoord roundingError = NSCoordDivRem(delta, 2, &halfDelta);
      auto newSize = sz.mBase - (halfDelta + roundingError) - lastHalfDelta;
      lastHalfDelta = halfDelta;
      // If the gap delta (in particular 'halfDelta + lastHalfDelta') is larger
      // than the current track size, newSize can be negative. Don't let the new
      // track size (mBase) be negative.
      sz.mBase = std::max(newSize, 0);
      sz.mPosition = currentPos;
      currentPos += newSize + mGridGap;
    }
    auto& lastTrack = mSizes.LastElement();
    auto newSize = lastTrack.mBase - lastHalfDelta;
    lastTrack.mBase = std::max(newSize, 0);
    lastTrack.mPosition = currentPos;
    return;
  }

  if (mSizes.IsEmpty()) {
    return;
  }

  bool overflowSafe;
  auto alignment = ::GetAlignJustifyValue(aAligmentStyleValue.primary, aWM,
                                          isAlign, &overflowSafe);
  if (alignment == StyleAlignFlags::NORMAL) {
    alignment = StyleAlignFlags::STRETCH;
    // we may need a fallback for 'stretch' below
    aAligmentStyleValue = {alignment};
  }

  // Compute the free space and count auto-sized tracks.
  size_t numAutoTracks = 0;
  nscoord space;
  if (alignment != StyleAlignFlags::START) {
    nscoord trackSizeSum = 0;
    if (aIsSubgriddedAxis) {
      numAutoTracks = mSizes.Length();
    } else {
      for (const TrackSize& sz : mSizes) {
        trackSizeSum += sz.mBase;
        if (sz.mState & TrackSize::eAutoMaxSizing) {
          ++numAutoTracks;
        }
      }
    }
    space = aContentBoxSize - trackSizeSum - SumOfGridGaps();
    // Use the fallback value instead when applicable.
    if (space < 0 ||
        (alignment == StyleAlignFlags::SPACE_BETWEEN && mSizes.Length() == 1)) {
      auto fallback = ::GetAlignJustifyFallbackIfAny(aAligmentStyleValue, aWM,
                                                     isAlign, &overflowSafe);
      if (fallback) {
        alignment = *fallback;
      }
    }
    if (space == 0 || (space < 0 && overflowSafe)) {
      // XXX check that this makes sense also for [last ]baseline (bug 1151204).
      alignment = StyleAlignFlags::START;
    }
  }

  // Optimize the cases where we just need to set each track's position.
  nscoord pos = 0;
  bool distribute = true;
  if (alignment == StyleAlignFlags::BASELINE ||
      alignment == StyleAlignFlags::LAST_BASELINE) {
    NS_WARNING("NYI: 'first/last baseline' (bug 1151204)");  // XXX
    alignment = StyleAlignFlags::START;
  }
  if (alignment == StyleAlignFlags::START) {
    distribute = false;
  } else if (alignment == StyleAlignFlags::END) {
    pos = space;
    distribute = false;
  } else if (alignment == StyleAlignFlags::CENTER) {
    pos = space / 2;
    distribute = false;
  } else if (alignment == StyleAlignFlags::STRETCH) {
    distribute = numAutoTracks != 0;
  }
  if (!distribute) {
    for (TrackSize& sz : mSizes) {
      sz.mPosition = pos;
      pos += sz.mBase + mGridGap;
    }
    return;
  }

  // Distribute free space to/between tracks and set their position.
  MOZ_ASSERT(space > 0, "should've handled that on the fallback path above");
  nscoord between, roundingError;
  if (alignment == StyleAlignFlags::STRETCH) {
    MOZ_ASSERT(numAutoTracks > 0, "we handled numAutoTracks == 0 above");
    // The outer loop typically only runs once - it repeats only in a masonry
    // axis when some stretchable items reach their `max-size`.
    // It's O(n^2) worst case; if all items are stretchable with a `max-size`
    // and exactly one item reaches its `max-size` each round.
    while (space) {
      pos = 0;
      nscoord spacePerTrack;
      roundingError = NSCoordDivRem(space, numAutoTracks, &spacePerTrack);
      space = 0;
      for (TrackSize& sz : mSizes) {
        sz.mPosition = pos;
        if (!(sz.mState & TrackSize::eAutoMaxSizing)) {
          pos += sz.mBase + mGridGap;
          continue;
        }
        nscoord stretch = spacePerTrack;
        if (roundingError) {
          roundingError -= 1;
          stretch += 1;
        }
        nscoord newBase = sz.mBase + stretch;
        if (mIsMasonry && (sz.mState & TrackSize::eClampToLimit)) {
          auto clampedSize = std::min(newBase, sz.mLimit);
          auto sizeOverLimit = newBase - clampedSize;
          if (sizeOverLimit > 0) {
            newBase = clampedSize;
            sz.mState &= ~(sz.mState & TrackSize::eAutoMaxSizing);
            // This repeats the outer loop to distribute the superfluous space:
            space += sizeOverLimit;
            if (--numAutoTracks == 0) {
              // ... except if we don't have any stretchable items left.
              space = 0;
            }
          }
        }
        sz.mBase = newBase;
        pos += newBase + mGridGap;
      }
    }
    MOZ_ASSERT(!roundingError, "we didn't distribute all rounding error?");
    return;
  }
  if (alignment == StyleAlignFlags::SPACE_BETWEEN) {
    MOZ_ASSERT(mSizes.Length() > 1, "should've used a fallback above");
    roundingError = NSCoordDivRem(space, mSizes.Length() - 1, &between);
  } else if (alignment == StyleAlignFlags::SPACE_AROUND) {
    roundingError = NSCoordDivRem(space, mSizes.Length(), &between);
    pos = between / 2;
  } else if (alignment == StyleAlignFlags::SPACE_EVENLY) {
    roundingError = NSCoordDivRem(space, mSizes.Length() + 1, &between);
    pos = between;
  } else {
    MOZ_ASSERT_UNREACHABLE("unknown align-/justify-content value");
    between = 0;        // just to avoid a compiler warning
    roundingError = 0;  // just to avoid a compiler warning
  }
  between += mGridGap;
  for (TrackSize& sz : mSizes) {
    sz.mPosition = pos;
    nscoord spacing = between;
    if (roundingError) {
      roundingError -= 1;
      spacing += 1;
    }
    pos += sz.mBase + spacing;
  }
  MOZ_ASSERT(!roundingError, "we didn't distribute all rounding error?");
}

void nsGridContainerFrame::LineRange::ToPositionAndLength(
    const nsTArray<TrackSize>& aTrackSizes, nscoord* aPos,
    nscoord* aLength) const {
  MOZ_ASSERT(mStart != kAutoLine && mEnd != kAutoLine,
             "expected a definite LineRange");
  MOZ_ASSERT(mStart < mEnd);
  nscoord startPos = aTrackSizes[mStart].mPosition;
  const TrackSize& sz = aTrackSizes[mEnd - 1];
  *aPos = startPos;
  *aLength = (sz.mPosition + sz.mBase) - startPos;
}

nscoord nsGridContainerFrame::LineRange::ToLength(
    const nsTArray<TrackSize>& aTrackSizes) const {
  MOZ_ASSERT(mStart != kAutoLine && mEnd != kAutoLine,
             "expected a definite LineRange");
  MOZ_ASSERT(mStart < mEnd);
  nscoord startPos = aTrackSizes[mStart].mPosition;
  const TrackSize& sz = aTrackSizes[mEnd - 1];
  return (sz.mPosition + sz.mBase) - startPos;
}

void nsGridContainerFrame::LineRange::ToPositionAndLengthForAbsPos(
    const Tracks& aTracks, nscoord aGridOrigin, nscoord* aPos,
    nscoord* aLength) const {
  // kAutoLine for abspos children contributes the corresponding edge
  // of the grid container's padding-box.
  if (mEnd == kAutoLine) {
    if (mStart == kAutoLine) {
      // done
    } else {
      const nscoord endPos = *aPos + *aLength;
      auto side = mStart == aTracks.mSizes.Length()
                      ? GridLineSide::BeforeGridGap
                      : GridLineSide::AfterGridGap;
      nscoord startPos = aTracks.GridLineEdge(mStart, side);
      *aPos = aGridOrigin + startPos;
      *aLength = std::max(endPos - *aPos, 0);
    }
  } else {
    if (mStart == kAutoLine) {
      auto side =
          mEnd == 0 ? GridLineSide::AfterGridGap : GridLineSide::BeforeGridGap;
      nscoord endPos = aTracks.GridLineEdge(mEnd, side);
      *aLength = std::max(aGridOrigin + endPos, 0);
    } else if (MOZ_LIKELY(mStart != mEnd)) {
      nscoord pos;
      ToPositionAndLength(aTracks.mSizes, &pos, aLength);
      *aPos = aGridOrigin + pos;
    } else {
      // The grid area only covers removed 'auto-fit' tracks.
      nscoord pos = aTracks.GridLineEdge(mStart, GridLineSide::BeforeGridGap);
      *aPos = aGridOrigin + pos;
      *aLength = nscoord(0);
    }
  }
}

LogicalSize nsGridContainerFrame::GridReflowInput::PercentageBasisFor(
    LogicalAxis aAxis, const GridItemInfo& aGridItem) const {
  auto wm = aGridItem.mFrame->GetWritingMode();
  const auto* itemParent = aGridItem.mFrame->GetParent();
  if (MOZ_UNLIKELY(itemParent != mFrame)) {
    // The item comes from a descendant subgrid.  Use the subgrid's
    // used track sizes to resolve the grid area size, if present.
    MOZ_ASSERT(itemParent->IsGridContainerFrame());
    auto* subgridFrame = static_cast<const nsGridContainerFrame*>(itemParent);
    MOZ_ASSERT(subgridFrame->IsSubgrid());
    if (auto* uts = subgridFrame->GetUsedTrackSizes()) {
      auto subgridWM = subgridFrame->GetWritingMode();
      LogicalSize cbSize(subgridWM, NS_UNCONSTRAINEDSIZE, NS_UNCONSTRAINEDSIZE);
      if (!subgridFrame->IsSubgrid(eLogicalAxisInline) &&
          uts->mCanResolveLineRangeSize[eLogicalAxisInline]) {
        // NOTE: At this point aGridItem.mArea is in this->mFrame coordinates
        // and thus may have been transposed.  The range values in a non-
        // subgridded axis still has its original values in subgridFrame's
        // coordinates though.
        auto rangeAxis = subgridWM.IsOrthogonalTo(mWM) ? eLogicalAxisBlock
                                                       : eLogicalAxisInline;
        const auto& range = aGridItem.mArea.LineRangeForAxis(rangeAxis);
        cbSize.ISize(subgridWM) =
            range.ToLength(uts->mSizes[eLogicalAxisInline]);
      }
      if (!subgridFrame->IsSubgrid(eLogicalAxisBlock) &&
          uts->mCanResolveLineRangeSize[eLogicalAxisBlock]) {
        auto rangeAxis = subgridWM.IsOrthogonalTo(mWM) ? eLogicalAxisInline
                                                       : eLogicalAxisBlock;
        const auto& range = aGridItem.mArea.LineRangeForAxis(rangeAxis);
        cbSize.BSize(subgridWM) =
            range.ToLength(uts->mSizes[eLogicalAxisBlock]);
      }
      return cbSize.ConvertTo(wm, subgridWM);
    }

    return LogicalSize(wm, NS_UNCONSTRAINEDSIZE, NS_UNCONSTRAINEDSIZE);
  }

  if (aAxis == eLogicalAxisInline || !mCols.mCanResolveLineRangeSize) {
    return LogicalSize(wm, NS_UNCONSTRAINEDSIZE, NS_UNCONSTRAINEDSIZE);
  }
  // Note: for now, we only resolve transferred percentages to row sizing.
  // We may need to adjust these assertions once we implement bug 1300366.
  MOZ_ASSERT(!mRows.mCanResolveLineRangeSize);
  nscoord colSize = aGridItem.mArea.mCols.ToLength(mCols.mSizes);
  nscoord rowSize = NS_UNCONSTRAINEDSIZE;
  return !wm.IsOrthogonalTo(mWM) ? LogicalSize(wm, colSize, rowSize)
                                 : LogicalSize(wm, rowSize, colSize);
}

LogicalRect nsGridContainerFrame::GridReflowInput::ContainingBlockFor(
    const GridArea& aArea) const {
  nscoord i, b, iSize, bSize;
  MOZ_ASSERT(aArea.mCols.Extent() > 0, "grid items cover at least one track");
  MOZ_ASSERT(aArea.mRows.Extent() > 0, "grid items cover at least one track");
  aArea.mCols.ToPositionAndLength(mCols.mSizes, &i, &iSize);
  aArea.mRows.ToPositionAndLength(mRows.mSizes, &b, &bSize);
  return LogicalRect(mWM, i, b, iSize, bSize);
}

LogicalRect nsGridContainerFrame::GridReflowInput::ContainingBlockForAbsPos(
    const GridArea& aArea, const LogicalPoint& aGridOrigin,
    const LogicalRect& aGridCB) const {
  nscoord i = aGridCB.IStart(mWM);
  nscoord b = aGridCB.BStart(mWM);
  nscoord iSize = aGridCB.ISize(mWM);
  nscoord bSize = aGridCB.BSize(mWM);
  aArea.mCols.ToPositionAndLengthForAbsPos(mCols, aGridOrigin.I(mWM), &i,
                                           &iSize);
  aArea.mRows.ToPositionAndLengthForAbsPos(mRows, aGridOrigin.B(mWM), &b,
                                           &bSize);
  return LogicalRect(mWM, i, b, iSize, bSize);
}

void nsGridContainerFrame::GridReflowInput::AlignJustifyContentInMasonryAxis(
    nscoord aMasonryBoxSize, nscoord aContentBoxSize) {
  if (aContentBoxSize == NS_UNCONSTRAINEDSIZE) {
    aContentBoxSize = aMasonryBoxSize;
  }
  auto& masonryAxisTracks = mRows.mIsMasonry ? mRows : mCols;
  MOZ_ASSERT(masonryAxisTracks.mSizes.Length() == 2,
             "unexpected masonry axis tracks");
  const auto masonryAxis = masonryAxisTracks.mAxis;
  const auto contentAlignment = mGridStyle->UsedContentAlignment(masonryAxis);
  if (contentAlignment.primary == StyleAlignFlags::NORMAL ||
      contentAlignment.primary == StyleAlignFlags::STRETCH) {
    // Stretch the "masonry box" to the full content box if it's smaller.
    nscoord cbSize = std::max(aMasonryBoxSize, aContentBoxSize);
    for (auto& sz : masonryAxisTracks.mSizes) {
      sz.mBase = cbSize;
    }
    return;
  }

  // Save our current track sizes; replace them with one track sized to
  // the masonry box and align that within our content box.
  auto savedTrackSizes(std::move(masonryAxisTracks.mSizes));
  masonryAxisTracks.mSizes.AppendElement(savedTrackSizes[0]);
  masonryAxisTracks.mSizes[0].mBase = aMasonryBoxSize;
  masonryAxisTracks.AlignJustifyContent(mGridStyle, contentAlignment, mWM,
                                        aContentBoxSize, false);
  nscoord masonryBoxOffset = masonryAxisTracks.mSizes[0].mPosition;
  // Restore the original track sizes...
  masonryAxisTracks.mSizes = std::move(savedTrackSizes);
  // ...then reposition and resize all of them to the aligned result.
  for (auto& sz : masonryAxisTracks.mSizes) {
    sz.mPosition = masonryBoxOffset;
    sz.mBase = aMasonryBoxSize;
  }
}

// Note: this is called after all items have been positioned/reflowed.
// The masonry-axis tracks have the size of the "masonry box" at this point
// and are positioned according to 'align/justify-content'.
void nsGridContainerFrame::GridReflowInput::AlignJustifyTracksInMasonryAxis(
    const LogicalSize& aContentSize, const nsSize& aContainerSize) {
  auto& masonryAxisTracks = mRows.mIsMasonry ? mRows : mCols;
  MOZ_ASSERT(masonryAxisTracks.mSizes.Length() == 2,
             "unexpected masonry axis tracks");
  const auto masonryAxis = masonryAxisTracks.mAxis;
  auto gridAxis = GetOrthogonalAxis(masonryAxis);
  auto& gridAxisTracks = TracksFor(gridAxis);
  AutoTArray<TrackSize, 32> savedSizes;
  savedSizes.AppendElements(masonryAxisTracks.mSizes);
  auto wm = mWM;
  nscoord contentAreaStart = mBorderPadding.Start(masonryAxis, wm);
  // The offset to the "masonry box" from our content-box start edge.
  nscoord masonryBoxOffset = masonryAxisTracks.mSizes[0].mPosition;
  nscoord alignmentContainerSize = masonryAxisTracks.mSizes[0].mBase;

  for (auto i : IntegerRange(gridAxisTracks.mSizes.Length())) {
    auto tracksAlignment = mGridStyle->UsedTracksAlignment(masonryAxis, i);
    if (tracksAlignment.primary != StyleAlignFlags::START) {
      masonryAxisTracks.mSizes.ClearAndRetainStorage();
      for (const auto& item : mGridItems) {
        if (item.mArea.LineRangeForAxis(gridAxis).mStart == i) {
          const auto* child = item.mFrame;
          LogicalRect rect = child->GetLogicalRect(wm, aContainerSize);
          TrackSize sz = {0, 0, 0, {0, 0}, TrackSize::StateBits{0}};
          const auto& margin = child->GetLogicalUsedMargin(wm);
          sz.mPosition = rect.Start(masonryAxis, wm) -
                         margin.Start(masonryAxis, wm) - contentAreaStart;
          sz.mBase =
              rect.Size(masonryAxis, wm) + margin.StartEnd(masonryAxis, wm);
          // Account for a align-self baseline offset on the end side.
          // XXXmats hmm, it seems it would be a lot simpler to just store
          // these baseline adjustments into the UsedMarginProperty instead
          auto state = item.mState[masonryAxis];
          if ((state & ItemState::eSelfBaseline) &&
              (state & ItemState::eEndSideBaseline)) {
            sz.mBase += item.mBaselineOffset[masonryAxis];
          }
          if (tracksAlignment.primary == StyleAlignFlags::STRETCH) {
            const auto* pos = child->StylePosition();
            auto itemAlignment =
                pos->UsedSelfAlignment(masonryAxis, mFrame->Style());
            if (child->StyleMargin()->HasAuto(masonryAxis, wm)) {
              sz.mState |= TrackSize::eAutoMaxSizing;
              sz.mState |= TrackSize::eItemHasAutoMargin;
            } else if (pos->Size(masonryAxis, wm).IsAuto() &&
                       (itemAlignment == StyleAlignFlags::NORMAL ||
                        itemAlignment == StyleAlignFlags::STRETCH)) {
              sz.mState |= TrackSize::eAutoMaxSizing;
              sz.mState |= TrackSize::eItemStretchSize;
              const auto& max = pos->MaxSize(masonryAxis, wm);
              if (max.ConvertsToLength()) {  // XXX deal with percentages
                // XXX add in baselineOffset ? use actual frame size - content
                // size?
                nscoord boxSizingAdjust =
                    child->GetLogicalUsedBorderAndPadding(wm).StartEnd(
                        masonryAxis, wm);
                if (pos->mBoxSizing == StyleBoxSizing::Border) {
                  boxSizingAdjust = 0;
                }
                sz.mLimit = nsLayoutUtils::ComputeBSizeValue(
                    aContentSize.Size(masonryAxis, wm), boxSizingAdjust,
                    max.AsLengthPercentage());
                sz.mLimit += margin.StartEnd(masonryAxis, wm);
                sz.mState |= TrackSize::eClampToLimit;
              }
            }
          }
          masonryAxisTracks.mSizes.AppendElement(std::move(sz));
        }
      }
      masonryAxisTracks.AlignJustifyContent(mGridStyle, tracksAlignment, wm,
                                            alignmentContainerSize, false);
      auto iter = mGridItems.begin();
      auto end = mGridItems.end();
      // We limit the loop to the number of items we found in the current
      // grid-axis axis track (in the outer loop) as an optimization.
      for (auto r : IntegerRange(masonryAxisTracks.mSizes.Length())) {
        GridItemInfo* item = nullptr;
        auto& sz = masonryAxisTracks.mSizes[r];
        // Find the next item in the current grid-axis axis track.
        for (; iter != end; ++iter) {
          if (iter->mArea.LineRangeForAxis(gridAxis).mStart == i) {
            item = &*iter;
            ++iter;
            break;
          }
        }
        nsIFrame* child = item->mFrame;
        const auto childWM = child->GetWritingMode();
        auto masonryChildAxis =
            childWM.IsOrthogonalTo(wm) ? gridAxis : masonryAxis;
        LogicalMargin margin = child->GetLogicalUsedMargin(childWM);
        bool forceReposition = false;
        if (sz.mState & TrackSize::eItemStretchSize) {
          auto size = child->GetLogicalSize().Size(masonryChildAxis, childWM);
          auto newSize = sz.mBase - margin.StartEnd(masonryChildAxis, childWM);
          if (size != newSize) {
            // XXX need to pass aIMinSizeClamp aBMinSizeClamp ?
            LogicalSize cb =
                ContainingBlockFor(item->mArea).Size(wm).ConvertTo(childWM, wm);
            LogicalSize availableSize = cb;
            cb.Size(masonryChildAxis, childWM) = alignmentContainerSize;
            availableSize.Size(eLogicalAxisBlock, childWM) =
                NS_UNCONSTRAINEDSIZE;
            const auto& bp = child->GetLogicalUsedBorderAndPadding(childWM);
            newSize -= bp.StartEnd(masonryChildAxis, childWM);
            ::PostReflowStretchChild(child, *mReflowInput, availableSize, cb,
                                     masonryChildAxis, newSize);
            if (childWM.IsPhysicalRTL()) {
              // The NormalPosition of this child is frame-size dependent so we
              // need to reset its stored position below.
              forceReposition = true;
            }
          }
        } else if (sz.mState & TrackSize::eItemHasAutoMargin) {
          // Re-compute the auto-margin(s) in the masonry axis.
          auto size = child->GetLogicalSize().Size(masonryChildAxis, childWM);
          auto spaceToFill = sz.mBase - size;
          if (spaceToFill > nscoord(0)) {
            const auto& marginStyle = child->StyleMargin();
            if (marginStyle->mMargin.Start(masonryChildAxis, childWM)
                    .IsAuto()) {
              if (marginStyle->mMargin.End(masonryChildAxis, childWM)
                      .IsAuto()) {
                nscoord half;
                nscoord roundingError = NSCoordDivRem(spaceToFill, 2, &half);
                margin.Start(masonryChildAxis, childWM) = half;
                margin.End(masonryChildAxis, childWM) = half + roundingError;
              } else {
                margin.Start(masonryChildAxis, childWM) = spaceToFill;
              }
            } else {
              MOZ_ASSERT(
                  marginStyle->mMargin.End(masonryChildAxis, childWM).IsAuto());
              margin.End(masonryChildAxis, childWM) = spaceToFill;
            }
            nsMargin* propValue =
                child->GetProperty(nsIFrame::UsedMarginProperty());
            if (propValue) {
              *propValue = margin.GetPhysicalMargin(childWM);
            } else {
              child->AddProperty(
                  nsIFrame::UsedMarginProperty(),
                  new nsMargin(margin.GetPhysicalMargin(childWM)));
            }
          }
        }
        nscoord newPos = contentAreaStart + masonryBoxOffset + sz.mPosition +
                         margin.Start(masonryChildAxis, childWM);
        LogicalPoint pos = child->GetLogicalNormalPosition(wm, aContainerSize);
        auto delta = newPos - pos.Pos(masonryAxis, wm);
        if (delta != 0 || forceReposition) {
          LogicalPoint logicalDelta(wm);
          logicalDelta.Pos(masonryAxis, wm) = delta;
          child->MovePositionBy(wm, logicalDelta);
        }
      }
    } else if (masonryBoxOffset != nscoord(0)) {
      // TODO move placeholders too
      auto delta = masonryBoxOffset;
      LogicalPoint logicalDelta(wm);
      logicalDelta.Pos(masonryAxis, wm) = delta;
      for (const auto& item : mGridItems) {
        if (item.mArea.LineRangeForAxis(gridAxis).mStart != i) {
          continue;
        }
        item.mFrame->MovePositionBy(wm, logicalDelta);
      }
    }
  }
  masonryAxisTracks.mSizes = std::move(savedSizes);
}

/**
 * Return a Fragmentainer object if we have a fragmentainer frame in our
 * ancestor chain of containing block (CB) reflow inputs.  We'll only
 * continue traversing the ancestor chain as long as the CBs have
 * the same writing-mode and have overflow:visible.
 */
Maybe<nsGridContainerFrame::Fragmentainer>
nsGridContainerFrame::GetNearestFragmentainer(
    const GridReflowInput& aState) const {
  Maybe<nsGridContainerFrame::Fragmentainer> data;
  const ReflowInput* gridRI = aState.mReflowInput;
  if (!gridRI->IsInFragmentedContext()) {
    return data;
  }
  WritingMode wm = aState.mWM;
  const ReflowInput* cbRI = gridRI->mCBReflowInput;
  for (; cbRI; cbRI = cbRI->mCBReflowInput) {
    nsIScrollableFrame* sf = do_QueryFrame(cbRI->mFrame);
    if (sf) {
      break;
    }
    if (wm.IsOrthogonalTo(cbRI->GetWritingMode())) {
      break;
    }
    LayoutFrameType frameType = cbRI->mFrame->Type();
    if ((frameType == LayoutFrameType::Canvas &&
         PresContext()->IsPaginated()) ||
        frameType == LayoutFrameType::ColumnSet) {
      data.emplace();
      data->mIsTopOfPage = gridRI->mFlags.mIsTopOfPage;
      if (gridRI->AvailableBSize() != NS_UNCONSTRAINEDSIZE) {
        data->mToFragmentainerEnd = aState.mFragBStart +
                                    gridRI->AvailableBSize() -
                                    aState.mBorderPadding.BStart(wm);
      } else {
        // This occurs when nsColumnSetFrame reflows its last column in
        // unconstrained available block-size.
        data->mToFragmentainerEnd = NS_UNCONSTRAINEDSIZE;
      }
      const auto numRows = aState.mRows.mSizes.Length();
      data->mCanBreakAtStart =
          numRows > 0 && aState.mRows.mSizes[0].mPosition > 0;
      nscoord bSize = gridRI->ComputedBSize();
      data->mIsAutoBSize = bSize == NS_UNCONSTRAINEDSIZE;
      if (data->mIsAutoBSize) {
        bSize = gridRI->ComputedMinBSize();
      } else {
        bSize = gridRI->ApplyMinMaxBSize(bSize);
      }
      nscoord gridEnd =
          aState.mRows.GridLineEdge(numRows, GridLineSide::BeforeGridGap);
      data->mCanBreakAtEnd = bSize > gridEnd && bSize > aState.mFragBStart;
      break;
    }
  }
  return data;
}

void nsGridContainerFrame::ReflowInFlowChild(
    nsIFrame* aChild, const GridItemInfo* aGridItemInfo, nsSize aContainerSize,
    const Maybe<nscoord>& aStretchBSize, const Fragmentainer* aFragmentainer,
    const GridReflowInput& aState, const LogicalRect& aContentArea,
    ReflowOutput& aDesiredSize, nsReflowStatus& aStatus) {
  nsPresContext* pc = PresContext();
  ComputedStyle* containerSC = Style();
  WritingMode wm = aState.mReflowInput->GetWritingMode();
  const bool isGridItem = !!aGridItemInfo;
  MOZ_ASSERT(isGridItem == !aChild->IsPlaceholderFrame());
  LogicalRect cb(wm);
  WritingMode childWM = aChild->GetWritingMode();
  bool isConstrainedBSize = false;
  nscoord toFragmentainerEnd;
  // The part of the child's grid area that's in previous container fragments.
  nscoord consumedGridAreaBSize = 0;
  const bool isOrthogonal = wm.IsOrthogonalTo(childWM);
  if (MOZ_LIKELY(isGridItem)) {
    MOZ_ASSERT(aGridItemInfo->mFrame == aChild);
    const GridArea& area = aGridItemInfo->mArea;
    MOZ_ASSERT(area.IsDefinite());
    cb = aState.ContainingBlockFor(area);
    if (aFragmentainer && !wm.IsOrthogonalTo(childWM)) {
      // |gridAreaBOffset| is the offset of the child's grid area in this
      // container fragment (if negative, that distance is the child CB size
      // consumed in previous container fragments).  Note that cb.BStart
      // (initially) and aState.mFragBStart are in "global" grid coordinates
      // (like all track positions).
      nscoord gridAreaBOffset = cb.BStart(wm) - aState.mFragBStart;
      consumedGridAreaBSize = std::max(0, -gridAreaBOffset);
      cb.BStart(wm) = std::max(0, gridAreaBOffset);
      if (aFragmentainer->mToFragmentainerEnd != NS_UNCONSTRAINEDSIZE) {
        toFragmentainerEnd = aFragmentainer->mToFragmentainerEnd -
                             aState.mFragBStart - cb.BStart(wm);
        toFragmentainerEnd = std::max(toFragmentainerEnd, 0);
        isConstrainedBSize = true;
      }
    }
    cb += aContentArea.Origin(wm);
    aState.mRows.AlignBaselineSubtree(*aGridItemInfo);
    aState.mCols.AlignBaselineSubtree(*aGridItemInfo);
    // Setup [align|justify]-content:[last ]baseline related frame properties.
    // These are added to the padding in SizeComputationInput::InitOffsets.
    // (a negative value signals the value is for 'last baseline' and should be
    //  added to the (logical) end padding)
    typedef const FramePropertyDescriptor<SmallValueHolder<nscoord>>* Prop;
    auto SetProp = [aGridItemInfo, aChild](LogicalAxis aGridAxis, Prop aProp) {
      auto state = aGridItemInfo->mState[aGridAxis];
      auto baselineAdjust = (state & ItemState::eContentBaseline)
                                ? aGridItemInfo->mBaselineOffset[aGridAxis]
                                : nscoord(0);
      if (baselineAdjust < nscoord(0)) {
        // This happens when the subtree overflows its track.
        // XXX spec issue? it's unclear how to handle this.
        baselineAdjust = nscoord(0);
      } else if (state & ItemState::eLastBaseline) {
        // FIXME: We're not setting the ItemState::eEndSideBaseline flag any
        // more as the new baseline sharing group calculation handles most of
        // the cases we need.  For non-masonry grids this flag was always set
        // for LAST_BASELINE items, so we're just mimicking that behavior here.
        // That said, masonry grids might not work 100% any more..
        baselineAdjust = -baselineAdjust;
      }
      if (baselineAdjust != nscoord(0)) {
        aChild->SetProperty(aProp, baselineAdjust);
      } else {
        aChild->RemoveProperty(aProp);
      }
    };
    SetProp(eLogicalAxisBlock,
            isOrthogonal ? IBaselinePadProperty() : BBaselinePadProperty());
    SetProp(eLogicalAxisInline,
            isOrthogonal ? BBaselinePadProperty() : IBaselinePadProperty());
  } else {
    // By convention, for frames that perform CSS Box Alignment, we position
    // placeholder children at the start corner of their alignment container,
    // and in this case that's usually the grid's content-box.
    // ("Usually" - the exception is when the grid *also* forms the
    // abs.pos. containing block. In that case, the alignment container isn't
    // the content-box -- it's some grid area instead.  But that case doesn't
    // require any special handling here, because we handle it later using a
    // special flag (ReflowInput::InitFlag::StaticPosIsCBOrigin) which will make
    // us ignore the placeholder's position entirely.)
    cb = aContentArea;
    aChild->AddStateBits(PLACEHOLDER_STATICPOS_NEEDS_CSSALIGN);
  }

  LogicalSize reflowSize(cb.Size(wm));
  if (isConstrainedBSize) {
    reflowSize.BSize(wm) = toFragmentainerEnd;
  }
  LogicalSize childCBSize = reflowSize.ConvertTo(childWM, wm);

  // Setup the ClampMarginBoxMinSize reflow flags and property, if needed.
  ComputeSizeFlags csFlags;
  if (aGridItemInfo) {
    const auto childIAxisInWM =
        isOrthogonal ? eLogicalAxisBlock : eLogicalAxisInline;
    // Clamp during reflow if we're stretching in that axis.
    if (GridItemShouldStretch(aChild, eLogicalAxisInline)) {
      if (aGridItemInfo->mState[childIAxisInWM] &
          ItemState::eClampMarginBoxMinSize) {
        csFlags += ComputeSizeFlag::IClampMarginBoxMinSize;
      }
    } else {
      csFlags += ComputeSizeFlag::ShrinkWrap;
    }

    const auto childBAxisInWM = GetOrthogonalAxis(childIAxisInWM);
    if (GridItemShouldStretch(aChild, eLogicalAxisBlock) &&
        aGridItemInfo->mState[childBAxisInWM] &
            ItemState::eClampMarginBoxMinSize) {
      csFlags += ComputeSizeFlag::BClampMarginBoxMinSize;
      aChild->SetProperty(BClampMarginBoxMinSizeProperty(),
                          childCBSize.BSize(childWM));
    } else {
      aChild->RemoveProperty(BClampMarginBoxMinSizeProperty());
    }

    if ((aGridItemInfo->mState[childIAxisInWM] &
         ItemState::eApplyAutoMinSize)) {
      csFlags += ComputeSizeFlag::IApplyAutoMinSize;
    }
  }

  if (!isConstrainedBSize) {
    childCBSize.BSize(childWM) = NS_UNCONSTRAINEDSIZE;
  }
  LogicalSize percentBasis(cb.Size(wm).ConvertTo(childWM, wm));
  ReflowInput childRI(pc, *aState.mReflowInput, aChild, childCBSize,
                      Some(percentBasis), {}, {}, csFlags);
  childRI.mFlags.mIsTopOfPage =
      aFragmentainer ? aFragmentainer->mIsTopOfPage : false;

  // FIXME (perf): It would be faster to do this only if the previous reflow of
  // the child was a measuring reflow, and only if the child does some of the
  // things that are affected by ComputeSizeFlag::IsGridMeasuringReflow.
  childRI.SetBResize(true);
  childRI.mFlags.mIsBResizeForPercentages = true;

  // If the child is stretching in its block axis, and we might be fragmenting
  // it in that axis, then setup a frame property to tell
  // nsBlockFrame::ComputeFinalSize the size.
  if (isConstrainedBSize && !wm.IsOrthogonalTo(childWM)) {
    const bool stretch = childRI.mStylePosition->BSize(childWM).IsAuto() &&
                         GridItemShouldStretch(aChild, eLogicalAxisBlock);
    if (stretch) {
      aChild->SetProperty(FragStretchBSizeProperty(), *aStretchBSize);
    } else {
      aChild->RemoveProperty(FragStretchBSizeProperty());
    }
  }

  // We need the width of the child before we can correctly convert
  // the writing-mode of its origin, so we reflow at (0, 0) using a dummy
  // aContainerSize, and then pass the correct position to FinishReflowChild.
  ReflowOutput childSize(childRI);
  const nsSize dummyContainerSize;

  ReflowChild(aChild, pc, childSize, childRI, childWM, LogicalPoint(childWM),
              dummyContainerSize, ReflowChildFlags::Default, aStatus);
  LogicalPoint childPos = cb.Origin(wm).ConvertTo(
      childWM, wm, aContainerSize - childSize.PhysicalSize());
  // Apply align/justify-self and reflow again if that affects the size.
  if (MOZ_LIKELY(isGridItem)) {
    LogicalSize size = childSize.Size(childWM);  // from the ReflowChild()
    auto applyItemSelfAlignment = [&](LogicalAxis aAxis, nscoord aCBSize) {
      auto align =
          childRI.mStylePosition->UsedSelfAlignment(aAxis, containerSC);
      auto state = aGridItemInfo->mState[aAxis];
      auto flags = AlignJustifyFlags::NoFlags;
      if (IsMasonry(aAxis)) {
        // In a masonry axis, we inhibit applying 'stretch' and auto-margins
        // here since AlignJustifyTracksInMasonryAxis deals with that.
        // The only other {align,justify}-{self,content} values that have an
        // effect are '[last] baseline', the rest behave as 'start'.
        if (MOZ_LIKELY(!(state & ItemState::eSelfBaseline))) {
          align = {StyleAlignFlags::START};
        } else {
          auto group = (state & ItemState::eFirstBaseline)
                           ? BaselineSharingGroup::First
                           : BaselineSharingGroup::Last;
          auto itemStart = aGridItemInfo->mArea.LineRangeForAxis(aAxis).mStart;
          aCBSize = aState.TracksFor(aAxis)
                        .mSizes[itemStart]
                        .mBaselineSubtreeSize[group];
        }
        flags = AlignJustifyFlags::IgnoreAutoMargins;
      } else if (state & ItemState::eContentBaseline) {
        align = {(state & ItemState::eFirstBaseline)
                     ? StyleAlignFlags::SELF_START
                     : StyleAlignFlags::SELF_END};
      }
      if (aAxis == eLogicalAxisBlock) {
        AlignSelf(*aGridItemInfo, align, aCBSize, wm, childRI, size, flags,
                  &childPos);
      } else {
        JustifySelf(*aGridItemInfo, align, aCBSize, wm, childRI, size, flags,
                    &childPos);
      }
    };
    if (aStatus.IsComplete()) {
      applyItemSelfAlignment(eLogicalAxisBlock,
                             cb.BSize(wm) - consumedGridAreaBSize);
    }
    applyItemSelfAlignment(eLogicalAxisInline, cb.ISize(wm));
  }  // else, nsAbsoluteContainingBlock.cpp will handle align/justify-self.

  FinishReflowChild(aChild, pc, childSize, &childRI, childWM, childPos,
                    aContainerSize, ReflowChildFlags::ApplyRelativePositioning);
  ConsiderChildOverflow(aDesiredSize.mOverflowAreas, aChild);
}

nscoord nsGridContainerFrame::ReflowInFragmentainer(
    GridReflowInput& aState, const LogicalRect& aContentArea,
    ReflowOutput& aDesiredSize, nsReflowStatus& aStatus,
    Fragmentainer& aFragmentainer, const nsSize& aContainerSize) {
  MOZ_ASSERT(aStatus.IsEmpty());
  MOZ_ASSERT(aState.mReflowInput);

  // Collect our grid items and sort them in row order.  Collect placeholders
  // and put them in a separate array.
  nsTArray<const GridItemInfo*> sortedItems(aState.mGridItems.Length());
  nsTArray<nsIFrame*> placeholders(aState.mAbsPosItems.Length());
  aState.mIter.Reset(CSSOrderAwareFrameIterator::ChildFilter::IncludeAll);
  for (; !aState.mIter.AtEnd(); aState.mIter.Next()) {
    nsIFrame* child = *aState.mIter;
    if (!child->IsPlaceholderFrame()) {
      const GridItemInfo* info = &aState.mGridItems[aState.mIter.ItemIndex()];
      sortedItems.AppendElement(info);
    } else {
      placeholders.AppendElement(child);
    }
  }
  // NOTE: We don't need stable_sort here, except in Masonry layout.  There are
  // no dependencies on having content order between items on the same row in
  // the code below in the non-Masonry case.
  if (IsMasonry()) {
    std::stable_sort(sortedItems.begin(), sortedItems.end(),
                     GridItemInfo::IsStartRowLessThan);
  } else {
    std::sort(sortedItems.begin(), sortedItems.end(),
              GridItemInfo::IsStartRowLessThan);
  }

  // Reflow our placeholder children; they must all be complete.
  for (auto child : placeholders) {
    nsReflowStatus childStatus;
    ReflowInFlowChild(child, nullptr, aContainerSize, Nothing(),
                      &aFragmentainer, aState, aContentArea, aDesiredSize,
                      childStatus);
    MOZ_ASSERT(childStatus.IsComplete(),
               "nsPlaceholderFrame should never need to be fragmented");
  }

  // The available size for children - we'll set this to the edge of the last
  // row in most cases below, but for now use the full size.
  nscoord childAvailableSize = aFragmentainer.mToFragmentainerEnd;
  const uint32_t startRow = aState.mStartRow;
  const uint32_t numRows = aState.mRows.mSizes.Length();
  bool isBDBClone = aState.mReflowInput->mStyleBorder->mBoxDecorationBreak ==
                    StyleBoxDecorationBreak::Clone;
  nscoord bpBEnd = aState.mBorderPadding.BEnd(aState.mWM);

  // Set |endRow| to the first row that doesn't fit.
  uint32_t endRow = numRows;
  for (uint32_t row = startRow; row < numRows; ++row) {
    auto& sz = aState.mRows.mSizes[row];
    const nscoord bEnd = sz.mPosition + sz.mBase;
    nscoord remainingAvailableSize = childAvailableSize - bEnd;
    if (remainingAvailableSize < 0 ||
        (isBDBClone && remainingAvailableSize < bpBEnd)) {
      endRow = row;
      break;
    }
  }

  // Check for forced breaks on the items if available block-size for children
  // is constrained. That is, ignore forced breaks if available block-size for
  // children is unconstrained since our parent expected us to be fully
  // complete.
  bool isForcedBreak = false;
  const bool avoidBreakInside = ShouldAvoidBreakInside(*aState.mReflowInput);
  if (childAvailableSize != NS_UNCONSTRAINEDSIZE) {
    const bool isTopOfPage = aFragmentainer.mIsTopOfPage;
    for (const GridItemInfo* info : sortedItems) {
      uint32_t itemStartRow = info->mArea.mRows.mStart;
      if (itemStartRow == endRow) {
        break;
      }
      const auto* disp = info->mFrame->StyleDisplay();
      if (disp->BreakBefore()) {
        // Propagate break-before on the first row to the container unless we're
        // already at top-of-page.
        if ((itemStartRow == 0 && !isTopOfPage) || avoidBreakInside) {
          aStatus.SetInlineLineBreakBeforeAndReset();
          return aState.mFragBStart;
        }
        if ((itemStartRow > startRow ||
             (itemStartRow == startRow && !isTopOfPage)) &&
            itemStartRow < endRow) {
          endRow = itemStartRow;
          isForcedBreak = true;
          // reset any BREAK_AFTER we found on an earlier item
          aStatus.Reset();
          break;  // we're done since the items are sorted in row order
        }
      }
      uint32_t itemEndRow = info->mArea.mRows.mEnd;
      if (disp->BreakAfter()) {
        if (itemEndRow != numRows) {
          if (itemEndRow > startRow && itemEndRow < endRow) {
            endRow = itemEndRow;
            isForcedBreak = true;
            // No "break;" here since later items with break-after may have
            // a shorter span.
          }
        } else {
          // Propagate break-after on the last row to the container, we may
          // still find a break-before on this row though (and reset aStatus).
          aStatus.SetInlineLineBreakAfter();  // tentative
        }
      }
    }

    // Consume at least one row in each fragment until we have consumed them
    // all. Except for the first row if there's a break opportunity before it.
    if (startRow == endRow && startRow != numRows &&
        (startRow != 0 || !aFragmentainer.mCanBreakAtStart)) {
      ++endRow;
    }

    // Honor break-inside:avoid if we can't fit all rows.
    if (avoidBreakInside && endRow < numRows) {
      aStatus.SetInlineLineBreakBeforeAndReset();
      return aState.mFragBStart;
    }
  }

  // Calculate the block-size including this fragment.
  nscoord bEndRow =
      aState.mRows.GridLineEdge(endRow, GridLineSide::BeforeGridGap);
  nscoord bSize;
  if (aFragmentainer.mIsAutoBSize) {
    // We only apply min-bsize once all rows are complete (when bsize is auto).
    if (endRow < numRows) {
      bSize = bEndRow;
      auto clampedBSize = ClampToCSSMaxBSize(bSize, aState.mReflowInput);
      if (MOZ_UNLIKELY(clampedBSize != bSize)) {
        // We apply max-bsize in all fragments though.
        bSize = clampedBSize;
      } else if (!isBDBClone) {
        // The max-bsize won't make this fragment COMPLETE, so the block-end
        // border will be in a later fragment.
        bpBEnd = 0;
      }
    } else {
      bSize = aState.mReflowInput->ApplyMinMaxBSize(bEndRow);
    }
  } else {
    bSize = aState.mReflowInput->ApplyMinMaxBSize(
        aState.mReflowInput->ComputedBSize());
  }

  // Check for overflow and set aStatus INCOMPLETE if so.
  bool overflow = bSize + bpBEnd > childAvailableSize;
  if (overflow) {
    if (avoidBreakInside) {
      aStatus.SetInlineLineBreakBeforeAndReset();
      return aState.mFragBStart;
    }
    bool breakAfterLastRow = endRow == numRows && aFragmentainer.mCanBreakAtEnd;
    if (breakAfterLastRow) {
      MOZ_ASSERT(bEndRow < bSize, "bogus aFragmentainer.mCanBreakAtEnd");
      nscoord availableSize = childAvailableSize;
      if (isBDBClone) {
        availableSize -= bpBEnd;
      }
      // Pretend we have at least 1px available size, otherwise we'll never make
      // progress in consuming our bSize.
      availableSize =
          std::max(availableSize, aState.mFragBStart + AppUnitsPerCSSPixel());
      // Fill the fragmentainer, but not more than our desired block-size and
      // at least to the size of the last row (even if that overflows).
      nscoord newBSize = std::min(bSize, availableSize);
      newBSize = std::max(newBSize, bEndRow);
      // If it's just the border+padding that is overflowing and we have
      // box-decoration-break:clone then we are technically COMPLETE.  There's
      // no point in creating another zero-bsize fragment in this case.
      if (newBSize < bSize || !isBDBClone) {
        aStatus.SetIncomplete();
      }
      bSize = newBSize;
    } else if (bSize <= bEndRow && startRow + 1 < endRow) {
      if (endRow == numRows) {
        // We have more than one row in this fragment, so we can break before
        // the last row instead.
        --endRow;
        bEndRow =
            aState.mRows.GridLineEdge(endRow, GridLineSide::BeforeGridGap);
        bSize = bEndRow;
        if (aFragmentainer.mIsAutoBSize) {
          bSize = ClampToCSSMaxBSize(bSize, aState.mReflowInput);
        }
      }
      aStatus.SetIncomplete();
    } else if (endRow < numRows) {
      bSize = ClampToCSSMaxBSize(bEndRow, aState.mReflowInput, &aStatus);
    }  // else - no break opportunities.
  } else {
    // Even though our block-size fits we need to honor forced breaks, or if
    // a row doesn't fit in an auto-sized container (unless it's constrained
    // by a max-bsize which make us overflow-incomplete).
    if (endRow < numRows &&
        (isForcedBreak || (aFragmentainer.mIsAutoBSize && bEndRow == bSize))) {
      bSize = ClampToCSSMaxBSize(bEndRow, aState.mReflowInput, &aStatus);
    }
  }

  // If we can't fit all rows then we're at least overflow-incomplete.
  if (endRow < numRows) {
    childAvailableSize = bEndRow;
    if (aStatus.IsComplete()) {
      aStatus.SetOverflowIncomplete();
      aStatus.SetNextInFlowNeedsReflow();
    }
  } else {
    // Children always have the full size of the rows in this fragment.
    childAvailableSize = std::max(childAvailableSize, bEndRow);
  }

  return ReflowRowsInFragmentainer(aState, aContentArea, aDesiredSize, aStatus,
                                   aFragmentainer, aContainerSize, sortedItems,
                                   startRow, endRow, bSize, childAvailableSize);
}

nscoord nsGridContainerFrame::ReflowRowsInFragmentainer(
    GridReflowInput& aState, const LogicalRect& aContentArea,
    ReflowOutput& aDesiredSize, nsReflowStatus& aStatus,
    Fragmentainer& aFragmentainer, const nsSize& aContainerSize,
    const nsTArray<const GridItemInfo*>& aSortedItems, uint32_t aStartRow,
    uint32_t aEndRow, nscoord aBSize, nscoord aAvailableSize) {
  FrameHashtable pushedItems;
  FrameHashtable incompleteItems;
  FrameHashtable overflowIncompleteItems;
  Maybe<nsTArray<nscoord>> masonryAxisPos;
  const auto rowCount = aState.mRows.mSizes.Length();
  nscoord masonryAxisGap;
  const auto wm = aState.mWM;
  const bool isColMasonry = IsMasonry(eLogicalAxisInline);
  if (isColMasonry) {
    for (auto& sz : aState.mCols.mSizes) {
      sz.mPosition = 0;
    }
    masonryAxisGap = nsLayoutUtils::ResolveGapToLength(
        aState.mGridStyle->mColumnGap, aContentArea.ISize(wm));
    aState.mCols.mGridGap = masonryAxisGap;
    masonryAxisPos.emplace(rowCount);
    masonryAxisPos->SetLength(rowCount);
    PodZero(masonryAxisPos->Elements(), rowCount);
  }
  bool isBDBClone = aState.mReflowInput->mStyleBorder->mBoxDecorationBreak ==
                    StyleBoxDecorationBreak::Clone;
  bool didGrowRow = false;
  // As we walk across rows, we track whether the current row is at the top
  // of its grid-fragment, to help decide whether we can break before it. When
  // this function starts, our row is at the top of the current fragment if:
  //  - we're starting with a nonzero row (i.e. we're a continuation)
  // OR:
  //  - we're starting with the first row, & we're not allowed to break before
  //    it (which makes it effectively at the top of its grid-fragment).
  bool isRowTopOfPage = aStartRow != 0 || !aFragmentainer.mCanBreakAtStart;
  const bool isStartRowTopOfPage = isRowTopOfPage;
  // Save our full available size for later.
  const nscoord gridAvailableSize = aFragmentainer.mToFragmentainerEnd;
  // Propagate the constrained size to our children.
  aFragmentainer.mToFragmentainerEnd = aAvailableSize;
  // Reflow the items in row order up to |aEndRow| and push items after that.
  uint32_t row = 0;
  // |i| is intentionally signed, so we can set it to -1 to restart the loop.
  for (int32_t i = 0, len = aSortedItems.Length(); i < len; ++i) {
    const GridItemInfo* const info = aSortedItems[i];
    nsIFrame* child = info->mFrame;
    row = info->mArea.mRows.mStart;
    MOZ_ASSERT(child->GetPrevInFlow() ? row < aStartRow : row >= aStartRow,
               "unexpected child start row");
    if (row >= aEndRow) {
      pushedItems.Insert(child);
      continue;
    }

    bool rowCanGrow = false;
    nscoord maxRowSize = 0;
    if (row >= aStartRow) {
      if (row > aStartRow) {
        isRowTopOfPage = false;
      }
      // Can we grow this row?  Only consider span=1 items per spec...
      rowCanGrow = !didGrowRow && info->mArea.mRows.Extent() == 1;
      if (rowCanGrow) {
        auto& sz = aState.mRows.mSizes[row];
        // and only min-/max-content rows or flex rows in an auto-sized
        // container
        rowCanGrow = (sz.mState & TrackSize::eMinOrMaxContentMinSizing) ||
                     ((sz.mState & TrackSize::eFlexMaxSizing) &&
                      aFragmentainer.mIsAutoBSize);
        if (rowCanGrow) {
          if (isBDBClone) {
            maxRowSize = gridAvailableSize - aState.mBorderPadding.BEnd(wm);
          } else {
            maxRowSize = gridAvailableSize;
          }
          maxRowSize -= sz.mPosition;
          // ...and only if there is space for it to grow.
          rowCanGrow = maxRowSize > sz.mBase;
        }
      }
    }

    if (isColMasonry) {
      const auto& cols = info->mArea.mCols;
      MOZ_ASSERT((cols.mStart == 0 || cols.mStart == 1) && cols.Extent() == 1);
      aState.mCols.mSizes[cols.mStart].mPosition = masonryAxisPos.ref()[row];
    }

    // aFragmentainer.mIsTopOfPage is propagated to the child reflow input.
    // When it's false the child may request InlineBreak::Before.  We set it
    // to false when the row is growable (as determined in the CSS Grid
    // Fragmentation spec) and there is a non-zero space between it and the
    // fragmentainer end (that can be used to grow it).  If the child reports
    // a forced break in this case, we grow this row to fill the fragment and
    // restart the loop.  We also restart the loop with |aEndRow = row|
    // (but without growing any row) for a InlineBreak::Before child if it spans
    // beyond the last row in this fragment.  This is to avoid fragmenting it.
    // We only restart the loop once.
    aFragmentainer.mIsTopOfPage = isRowTopOfPage && !rowCanGrow;
    nsReflowStatus childStatus;
    // Pass along how much to stretch this fragment, in case it's needed.
    nscoord bSize =
        aState.mRows.GridLineEdge(std::min(aEndRow, info->mArea.mRows.mEnd),
                                  GridLineSide::BeforeGridGap) -
        aState.mRows.GridLineEdge(std::max(aStartRow, row),
                                  GridLineSide::AfterGridGap);
    ReflowInFlowChild(child, info, aContainerSize, Some(bSize), &aFragmentainer,
                      aState, aContentArea, aDesiredSize, childStatus);
    MOZ_ASSERT(childStatus.IsInlineBreakBefore() ||
                   !childStatus.IsFullyComplete() || !child->GetNextInFlow(),
               "fully-complete reflow should destroy any NIFs");

    if (childStatus.IsInlineBreakBefore()) {
      MOZ_ASSERT(
          !child->GetPrevInFlow(),
          "continuations should never report InlineBreak::Before status");
      MOZ_ASSERT(!aFragmentainer.mIsTopOfPage,
                 "got IsInlineBreakBefore() at top of page");
      if (!didGrowRow) {
        if (rowCanGrow) {
          // Grow this row and restart with the next row as |aEndRow|.
          aState.mRows.ResizeRow(row, maxRowSize);
          if (aState.mSharedGridData) {
            aState.mSharedGridData->mRows.ResizeRow(row, maxRowSize);
          }
          didGrowRow = true;
          aEndRow = row + 1;  // growing this row makes the next one not fit
          i = -1;             // i == 0 after the next loop increment
          isRowTopOfPage = isStartRowTopOfPage;
          overflowIncompleteItems.Clear();
          incompleteItems.Clear();
          nscoord bEndRow =
              aState.mRows.GridLineEdge(aEndRow, GridLineSide::BeforeGridGap);
          aFragmentainer.mToFragmentainerEnd = bEndRow;
          if (aFragmentainer.mIsAutoBSize) {
            aBSize = ClampToCSSMaxBSize(bEndRow, aState.mReflowInput, &aStatus);
          } else if (aStatus.IsIncomplete()) {
            aBSize = aState.mReflowInput->ApplyMinMaxBSize(
                aState.mReflowInput->ComputedBSize());
            aBSize = std::min(bEndRow, aBSize);
          }
          continue;
        }

        if (!isRowTopOfPage) {
          // We can break before this row - restart with it as the new end row.
          aEndRow = row;
          aBSize =
              aState.mRows.GridLineEdge(aEndRow, GridLineSide::BeforeGridGap);
          i = -1;  // i == 0 after the next loop increment
          isRowTopOfPage = isStartRowTopOfPage;
          overflowIncompleteItems.Clear();
          incompleteItems.Clear();
          aStatus.SetIncomplete();
          continue;
        }
        NS_ERROR("got InlineBreak::Before at top-of-page");
        childStatus.Reset();
      } else {
        // We got InlineBreak::Before again after growing the row - this can
        // happen if the child isn't splittable, e.g. some form controls.
        childStatus.Reset();
        if (child->GetNextInFlow()) {
          // The child already has a fragment, so we know it's splittable.
          childStatus.SetIncomplete();
        }  // else, report that it's complete
      }
    } else if (childStatus.IsInlineBreakAfter()) {
      MOZ_ASSERT_UNREACHABLE("unexpected child reflow status");
    }

    MOZ_ASSERT(!childStatus.IsInlineBreakBefore(),
               "should've handled InlineBreak::Before above");
    if (childStatus.IsIncomplete()) {
      incompleteItems.Insert(child);
    } else if (!childStatus.IsFullyComplete()) {
      overflowIncompleteItems.Insert(child);
    }
    if (isColMasonry) {
      auto childWM = child->GetWritingMode();
      auto childAxis =
          !childWM.IsOrthogonalTo(wm) ? eLogicalAxisInline : eLogicalAxisBlock;
      auto normalPos = child->GetLogicalNormalPosition(wm, aContainerSize);
      auto sz =
          childAxis == eLogicalAxisBlock ? child->BSize() : child->ISize();
      auto pos = normalPos.Pos(eLogicalAxisInline, wm) + sz +
                 child->GetLogicalUsedMargin(childWM).End(childAxis, childWM);
      masonryAxisPos.ref()[row] =
          pos + masonryAxisGap - aContentArea.Start(eLogicalAxisInline, wm);
    }
  }

  // Record a break before |aEndRow|.
  aState.mNextFragmentStartRow = aEndRow;
  if (aEndRow < rowCount) {
    aState.mRows.BreakBeforeRow(aEndRow);
    if (aState.mSharedGridData) {
      aState.mSharedGridData->mRows.BreakBeforeRow(aEndRow);
    }
  }

  const bool childrenMoved = PushIncompleteChildren(
      pushedItems, incompleteItems, overflowIncompleteItems);
  if (childrenMoved && aStatus.IsComplete()) {
    aStatus.SetOverflowIncomplete();
    aStatus.SetNextInFlowNeedsReflow();
  }
  if (!pushedItems.IsEmpty()) {
    AddStateBits(NS_STATE_GRID_DID_PUSH_ITEMS);
    // NOTE since we messed with our child list here, we intentionally
    // make aState.mIter invalid to avoid any use of it after this point.
    aState.mIter.Invalidate();
  }
  if (!incompleteItems.IsEmpty()) {
    // NOTE since we messed with our child list here, we intentionally
    // make aState.mIter invalid to avoid any use of it after this point.
    aState.mIter.Invalidate();
  }

  if (isColMasonry) {
    nscoord maxSize = 0;
    for (auto pos : masonryAxisPos.ref()) {
      maxSize = std::max(maxSize, pos);
    }
    maxSize = std::max(nscoord(0), maxSize - masonryAxisGap);
    aState.AlignJustifyContentInMasonryAxis(maxSize, aContentArea.ISize(wm));
  }

  return aBSize;
}

// Here's a brief overview of how Masonry layout is implemented:
// We setup two synthetic tracks in the Masonry axis so that the Reflow code
// can treat it the same as for normal grid layout.  The first track is
// fixed (during item placement/layout) at the content box start and contains
// the start items for each grid-axis track.  The second track contains
// all other items and is moved to the position where we want to position
// the currently laid out item (like a sliding window as we place items).
// Once item layout is done, the tracks are resized to be the size of
// the "masonry box", which is the offset from the content box start to
// the margin-box end of the item that is furthest away (this happens in
// AlignJustifyContentInMasonryAxis() called at the end of this method).
// This is to prepare for AlignJustifyTracksInMasonryAxis, which is called
// later by our caller.
// Both tracks store their first-/last-baseline group offsets as usual.
// The first-baseline of the start track, and the last-baseline of the last
// track (if they exist) are exported as the grid container's baselines, or
// we fall back to picking an item's baseline (all this is per normal grid
// layout).  There's a slight difference in which items belongs to which
// group though - see InitializeItemBaselinesInMasonryAxis for details.
// This method returns the "masonry box" size (in the masonry axis).
nscoord nsGridContainerFrame::MasonryLayout(GridReflowInput& aState,
                                            const LogicalRect& aContentArea,
                                            SizingConstraint aConstraint,
                                            ReflowOutput& aDesiredSize,
                                            nsReflowStatus& aStatus,
                                            Fragmentainer* aFragmentainer,
                                            const nsSize& aContainerSize) {
  using BaselineAlignmentSet = Tracks::BaselineAlignmentSet;

  auto recordAutoPlacement = [this, &aState](GridItemInfo* aItem,
                                             LogicalAxis aGridAxis) {
    // When we're auto-placing an item in a continuation we need to record
    // the placement in mSharedGridData.
    if (MOZ_UNLIKELY(aState.mSharedGridData && GetPrevInFlow()) &&
        (aItem->mState[aGridAxis] & ItemState::eAutoPlacement)) {
      auto* child = aItem->mFrame;
      MOZ_RELEASE_ASSERT(!child->GetPrevInFlow(),
                         "continuations should never be auto-placed");
      for (auto& sharedItem : aState.mSharedGridData->mGridItems) {
        if (sharedItem.mFrame == child) {
          sharedItem.mArea.LineRangeForAxis(aGridAxis) =
              aItem->mArea.LineRangeForAxis(aGridAxis);
          MOZ_ASSERT(sharedItem.mState[aGridAxis] & ItemState::eAutoPlacement);
          sharedItem.mState[aGridAxis] &= ~ItemState::eAutoPlacement;
          break;
        }
      }
    }
    aItem->mState[aGridAxis] &= ~ItemState::eAutoPlacement;
  };

  // Collect our grid items and sort them in grid order.
  nsTArray<GridItemInfo*> sortedItems(aState.mGridItems.Length());
  aState.mIter.Reset(CSSOrderAwareFrameIterator::ChildFilter::IncludeAll);
  size_t absposIndex = 0;
  const LogicalAxis masonryAxis =
      IsMasonry(eLogicalAxisBlock) ? eLogicalAxisBlock : eLogicalAxisInline;
  const auto wm = aState.mWM;
  for (; !aState.mIter.AtEnd(); aState.mIter.Next()) {
    nsIFrame* child = *aState.mIter;
    if (MOZ_LIKELY(!child->IsPlaceholderFrame())) {
      GridItemInfo* item = &aState.mGridItems[aState.mIter.ItemIndex()];
      sortedItems.AppendElement(item);
    } else if (aConstraint == SizingConstraint::NoConstraint) {
      // (we only collect placeholders in the NoConstraint case since they
      //  don't affect intrinsic sizing in any way)
      GridItemInfo* item = nullptr;
      auto* ph = static_cast<nsPlaceholderFrame*>(child);
      if (ph->GetOutOfFlowFrame()->GetParent() == this) {
        item = &aState.mAbsPosItems[absposIndex++];
        MOZ_RELEASE_ASSERT(item->mFrame == ph->GetOutOfFlowFrame());
        auto masonryStart = item->mArea.LineRangeForAxis(masonryAxis).mStart;
        // If the item was placed by the author at line 1 (masonryStart == 0)
        // then include it to be placed at the masonry-box start.  If it's
        // auto-placed and has an `auto` inset value in the masonry axis then
        // we include it to be placed after the last grid item with the same
        // grid-axis start track.
        // XXXmats this is all a bit experimental at this point, pending a spec
        if (masonryStart == 0 ||
            (masonryStart == kAutoLine && item->mFrame->StylePosition()
                                              ->mOffset.Start(masonryAxis, wm)
                                              .IsAuto())) {
          sortedItems.AppendElement(item);
        } else {
          item = nullptr;
        }
      }
      if (!item) {
        // It wasn't included above - just reflow it and be done with it.
        nsReflowStatus childStatus;
        ReflowInFlowChild(child, nullptr, aContainerSize, Nothing(), nullptr,
                          aState, aContentArea, aDesiredSize, childStatus);
      }
    }
  }
  const auto masonryAutoFlow = aState.mGridStyle->mMasonryAutoFlow;
  const bool definiteFirst =
      masonryAutoFlow.order == StyleMasonryItemOrder::DefiniteFirst;
  if (masonryAxis == eLogicalAxisBlock) {
    std::stable_sort(sortedItems.begin(), sortedItems.end(),
                     definiteFirst ? GridItemInfo::RowMasonryDefiniteFirst
                                   : GridItemInfo::RowMasonryOrdered);
  } else {
    std::stable_sort(sortedItems.begin(), sortedItems.end(),
                     definiteFirst ? GridItemInfo::ColMasonryDefiniteFirst
                                   : GridItemInfo::ColMasonryOrdered);
  }

  FrameHashtable pushedItems;
  FrameHashtable incompleteItems;
  FrameHashtable overflowIncompleteItems;
  nscoord toFragmentainerEnd = nscoord_MAX;
  nscoord fragStartPos = aState.mFragBStart;
  const bool avoidBreakInside =
      aFragmentainer && ShouldAvoidBreakInside(*aState.mReflowInput);
  const bool isTopOfPageAtStart =
      aFragmentainer && aFragmentainer->mIsTopOfPage;
  if (aFragmentainer) {
    toFragmentainerEnd = std::max(0, aFragmentainer->mToFragmentainerEnd);
  }
  const LogicalAxis gridAxis = GetOrthogonalAxis(masonryAxis);
  const auto gridAxisTrackCount = aState.TracksFor(gridAxis).mSizes.Length();
  auto& masonryTracks = aState.TracksFor(masonryAxis);
  auto& masonrySizes = masonryTracks.mSizes;
  MOZ_ASSERT(masonrySizes.Length() == 2);
  for (auto& sz : masonrySizes) {
    sz.mPosition = fragStartPos;
  }
  // The current running position for each grid-axis track where the next item
  // should be positioned.  When an item is placed we'll update the tracks it
  // spans to the end of its margin box + 'gap'.
  nsTArray<nscoord> currentPos(gridAxisTrackCount);
  currentPos.SetLength(gridAxisTrackCount);
  for (auto& sz : currentPos) {
    sz = fragStartPos;
  }
  nsTArray<nscoord> lastPos(currentPos.Clone());
  nsTArray<GridItemInfo*> lastItems(gridAxisTrackCount);
  lastItems.SetLength(gridAxisTrackCount);
  PodZero(lastItems.Elements(), gridAxisTrackCount);
  const nscoord gap = nsLayoutUtils::ResolveGapToLength(
      masonryAxis == eLogicalAxisBlock ? aState.mGridStyle->mRowGap
                                       : aState.mGridStyle->mColumnGap,
      masonryTracks.mContentBoxSize);
  masonryTracks.mGridGap = gap;
  uint32_t cursor = 0;
  const auto containerToMasonryBoxOffset =
      fragStartPos - aContentArea.Start(masonryAxis, wm);
  const bool isPack = masonryAutoFlow.placement == StyleMasonryPlacement::Pack;
  bool didAlignStartAlignedFirstItems = false;

  // Return true if any of the lastItems in aRange are baseline-aligned in
  // the masonry axis.
  auto lastItemHasBaselineAlignment = [&](const LineRange& aRange) {
    for (auto i : aRange.Range()) {
      if (auto* child = lastItems[i] ? lastItems[i]->mFrame : nullptr) {
        const auto& pos = child->StylePosition();
        auto selfAlignment = pos->UsedSelfAlignment(masonryAxis, this->Style());
        if (selfAlignment == StyleAlignFlags::BASELINE ||
            selfAlignment == StyleAlignFlags::LAST_BASELINE) {
          return true;
        }
        auto childAxis = masonryAxis;
        if (child->GetWritingMode().IsOrthogonalTo(wm)) {
          childAxis = gridAxis;
        }
        auto contentAlignment = pos->UsedContentAlignment(childAxis).primary;
        if (contentAlignment == StyleAlignFlags::BASELINE ||
            contentAlignment == StyleAlignFlags::LAST_BASELINE) {
          return true;
        }
      }
    }
    return false;
  };

  // Resolve aItem's placement, unless it's definite already.  Return its
  // masonry axis position with that placement.
  auto placeItem = [&](GridItemInfo* aItem) -> nscoord {
    auto& masonryAxisRange = aItem->mArea.LineRangeForAxis(masonryAxis);
    MOZ_ASSERT(masonryAxisRange.mStart != 0, "item placement is already final");
    auto& gridAxisRange = aItem->mArea.LineRangeForAxis(gridAxis);
    bool isAutoPlaced = aItem->mState[gridAxis] & ItemState::eAutoPlacement;
    uint32_t start = isAutoPlaced ? 0 : gridAxisRange.mStart;
    if (isAutoPlaced && !isPack) {
      start = cursor;
      isAutoPlaced = false;
    }
    const uint32_t extent = gridAxisRange.Extent();
    if (start + extent > gridAxisTrackCount) {
      // Note that this will only happen to auto-placed items since the grid is
      // always wide enough to fit other items.
      start = 0;
    }
    // This keeps track of the smallest `maxPosForRange` value that
    // we discover in the loop below:
    nscoord minPos = nscoord_MAX;
    MOZ_ASSERT(extent <= gridAxisTrackCount);
    const uint32_t iEnd = gridAxisTrackCount + 1 - extent;
    for (uint32_t i = start; i < iEnd; ++i) {
      // Find the max `currentPos` value for the tracks that we would span
      // if we were to use `i` as our start track:
      nscoord maxPosForRange = 0;
      for (auto j = i, jEnd = j + extent; j < jEnd; ++j) {
        maxPosForRange = std::max(currentPos[j], maxPosForRange);
      }
      if (maxPosForRange < minPos) {
        minPos = maxPosForRange;
        start = i;
      }
      if (!isAutoPlaced) {
        break;
      }
    }
    gridAxisRange.mStart = start;
    gridAxisRange.mEnd = start + extent;
    bool isFirstItem = true;
    for (uint32_t i : gridAxisRange.Range()) {
      if (lastItems[i]) {
        isFirstItem = false;
        break;
      }
    }
    // If this is the first item in its spanned grid tracks, then place it in
    // the first masonry track. Otherwise, place it in the second masonry track.
    masonryAxisRange.mStart = isFirstItem ? 0 : 1;
    masonryAxisRange.mEnd = masonryAxisRange.mStart + 1;
    return minPos;
  };

  // Handle the resulting reflow status after reflowing aItem.
  // This may set aStatus to BreakBefore which the caller is expected
  // to handle by returning from MasonryLayout.
  // @return true if this item should consume all remaining space
  auto handleChildStatus = [&](GridItemInfo* aItem,
                               const nsReflowStatus& aChildStatus) {
    bool result = false;
    if (MOZ_UNLIKELY(aFragmentainer)) {
      auto* child = aItem->mFrame;
      if (!aChildStatus.IsComplete() || aChildStatus.IsInlineBreakBefore() ||
          aChildStatus.IsInlineBreakAfter() ||
          child->StyleDisplay()->BreakAfter()) {
        if (!isTopOfPageAtStart && avoidBreakInside) {
          aStatus.SetInlineLineBreakBeforeAndReset();
          return result;
        }
        result = true;
      }
      if (aChildStatus.IsInlineBreakBefore()) {
        aStatus.SetIncomplete();
        pushedItems.Insert(child);
      } else if (aChildStatus.IsIncomplete()) {
        recordAutoPlacement(aItem, gridAxis);
        aStatus.SetIncomplete();
        incompleteItems.Insert(child);
      } else if (!aChildStatus.IsFullyComplete()) {
        recordAutoPlacement(aItem, gridAxis);
        overflowIncompleteItems.Insert(child);
      }
    }
    return result;
  };

  // @return the distance from the masonry-box start to the end of the margin-
  // box of aChild
  auto offsetToMarginBoxEnd = [&](nsIFrame* aChild) {
    auto childWM = aChild->GetWritingMode();
    auto childAxis = !childWM.IsOrthogonalTo(wm) ? masonryAxis : gridAxis;
    auto normalPos = aChild->GetLogicalNormalPosition(wm, aContainerSize);
    auto sz =
        childAxis == eLogicalAxisBlock ? aChild->BSize() : aChild->ISize();
    return containerToMasonryBoxOffset + normalPos.Pos(masonryAxis, wm) + sz +
           aChild->GetLogicalUsedMargin(childWM).End(childAxis, childWM);
  };

  // Apply baseline alignment to items belonging to the given set.
  nsTArray<Tracks::ItemBaselineData> firstBaselineItems;
  nsTArray<Tracks::ItemBaselineData> lastBaselineItems;
  auto applyBaselineAlignment = [&](BaselineAlignmentSet aSet) {
    firstBaselineItems.ClearAndRetainStorage();
    lastBaselineItems.ClearAndRetainStorage();
    masonryTracks.InitializeItemBaselinesInMasonryAxis(
        aState, aState.mGridItems, aSet, aContainerSize, currentPos,
        firstBaselineItems, lastBaselineItems);

    bool didBaselineAdjustment = false;
    nsTArray<Tracks::ItemBaselineData>* baselineItems[] = {&firstBaselineItems,
                                                           &lastBaselineItems};
    for (const auto* items : baselineItems) {
      for (const auto& data : *items) {
        GridItemInfo* item = data.mGridItem;
        MOZ_ASSERT((item->mState[masonryAxis] & ItemState::eIsBaselineAligned));
        nscoord baselineOffset = item->mBaselineOffset[masonryAxis];
        if (baselineOffset == nscoord(0)) {
          continue;  // no adjustment needed for this item
        }
        didBaselineAdjustment = true;
        auto* child = item->mFrame;
        auto masonryAxisStart =
            item->mArea.LineRangeForAxis(masonryAxis).mStart;
        auto gridAxisRange = item->mArea.LineRangeForAxis(gridAxis);
        masonrySizes[masonryAxisStart].mPosition =
            aSet.mItemSet == BaselineAlignmentSet::LastItems
                ? lastPos[gridAxisRange.mStart]
                : fragStartPos;
        bool consumeAllSpace = false;
        const auto state = item->mState[masonryAxis];
        if ((state & ItemState::eContentBaseline) ||
            MOZ_UNLIKELY(aFragmentainer)) {
          if (MOZ_UNLIKELY(aFragmentainer)) {
            aFragmentainer->mIsTopOfPage =
                isTopOfPageAtStart &&
                masonrySizes[masonryAxisStart].mPosition == fragStartPos;
          }
          nsReflowStatus childStatus;
          ReflowInFlowChild(child, item, aContainerSize, Nothing(),
                            aFragmentainer, aState, aContentArea, aDesiredSize,
                            childStatus);
          consumeAllSpace = handleChildStatus(item, childStatus);
          if (aStatus.IsInlineBreakBefore()) {
            return false;
          }
        } else if (!(state & ItemState::eEndSideBaseline)) {
          // `align/justify-self` baselines on the start side can be handled by
          // just moving the frame (except in a fragmentainer in which case we
          // reflow it above instead since it might make it INCOMPLETE).
          LogicalPoint logicalDelta(wm);
          logicalDelta.Pos(masonryAxis, wm) = baselineOffset;
          child->MovePositionBy(wm, logicalDelta);
        }
        if ((state & ItemState::eEndSideBaseline) && !consumeAllSpace) {
          // Account for an end-side baseline adjustment.
          for (uint32_t i : gridAxisRange.Range()) {
            currentPos[i] += baselineOffset;
          }
        } else {
          nscoord pos = consumeAllSpace ? toFragmentainerEnd
                                        : offsetToMarginBoxEnd(child);
          pos += gap;
          for (uint32_t i : gridAxisRange.Range()) {
            currentPos[i] = pos;
          }
        }
      }
    }
    return didBaselineAdjustment;
  };

  // Place and reflow items.  We'll use two fake tracks in the masonry axis.
  // The first contains items that were placed there by the regular grid
  // placement algo (PlaceGridItems) and we may add some items here if there
  // are still empty slots.  The second track contains all other items.
  // Both tracks always have the size of the content box in the masonry axis.
  // The position of the first track is always at the start.  The position
  // of the second track is updated as we go to a position where we want
  // the current item to be positioned.
  for (GridItemInfo* item : sortedItems) {
    auto* child = item->mFrame;
    auto& masonryRange = item->mArea.LineRangeForAxis(masonryAxis);
    auto& gridRange = item->mArea.LineRangeForAxis(gridAxis);
    nsReflowStatus childStatus;
    if (MOZ_UNLIKELY(child->HasAnyStateBits(NS_FRAME_OUT_OF_FLOW))) {
      auto contentArea = aContentArea;
      nscoord pos = nscoord_MAX;
      // XXXmats take mEnd into consideration...
      if (gridRange.mStart == kAutoLine) {
        for (auto p : currentPos) {
          pos = std::min(p, pos);
        }
      } else if (gridRange.mStart < currentPos.Length()) {
        pos = currentPos[gridRange.mStart];
      } else if (currentPos.Length() > 0) {
        pos = currentPos.LastElement();
      }
      if (pos == nscoord_MAX) {
        pos = nscoord(0);
      }
      contentArea.Start(masonryAxis, wm) = pos;
      child = child->GetPlaceholderFrame();
      ReflowInFlowChild(child, nullptr, aContainerSize, Nothing(), nullptr,
                        aState, contentArea, aDesiredSize, childStatus);
    } else {
      MOZ_ASSERT(gridRange.Extent() > 0 &&
                 gridRange.Extent() <= gridAxisTrackCount);
      MOZ_ASSERT((masonryRange.mStart == 0 || masonryRange.mStart == 1) &&
                 masonryRange.Extent() == 1);
      if (masonryRange.mStart != 0) {
        masonrySizes[1].mPosition = placeItem(item);
      }

      // If this is the first item NOT in the first track and if any of
      // the grid-axis tracks we span has a baseline-aligned item then we
      // need to do that baseline alignment now since it may affect
      // the placement of this and later items.
      if (!didAlignStartAlignedFirstItems &&
          aConstraint == SizingConstraint::NoConstraint &&
          masonryRange.mStart != 0 && lastItemHasBaselineAlignment(gridRange)) {
        didAlignStartAlignedFirstItems = true;
        if (applyBaselineAlignment({BaselineAlignmentSet::FirstItems,
                                    BaselineAlignmentSet::StartStretch})) {
          // Baseline alignment resized some items - redo our placement.
          masonrySizes[1].mPosition = placeItem(item);
        }
        if (aStatus.IsInlineBreakBefore()) {
          return fragStartPos;
        }
      }

      for (uint32_t i : gridRange.Range()) {
        lastItems[i] = item;
      }
      cursor = gridRange.mEnd;
      if (cursor >= gridAxisTrackCount) {
        cursor = 0;
      }

      nscoord pos;
      if (aConstraint == SizingConstraint::NoConstraint) {
        const auto* disp = child->StyleDisplay();
        if (MOZ_UNLIKELY(aFragmentainer)) {
          aFragmentainer->mIsTopOfPage =
              isTopOfPageAtStart &&
              masonrySizes[masonryRange.mStart].mPosition == fragStartPos;
          if (!aFragmentainer->mIsTopOfPage &&
              (disp->BreakBefore() ||
               masonrySizes[masonryRange.mStart].mPosition >=
                   toFragmentainerEnd)) {
            childStatus.SetInlineLineBreakBeforeAndReset();
          }
        }
        if (!childStatus.IsInlineBreakBefore()) {
          ReflowInFlowChild(child, item, aContainerSize, Nothing(),
                            aFragmentainer, aState, aContentArea, aDesiredSize,
                            childStatus);
        }
        bool consumeAllSpace = handleChildStatus(item, childStatus);
        if (aStatus.IsInlineBreakBefore()) {
          return fragStartPos;
        }
        pos =
            consumeAllSpace ? toFragmentainerEnd : offsetToMarginBoxEnd(child);
      } else {
        LogicalSize percentBasis(
            aState.PercentageBasisFor(eLogicalAxisInline, *item));
        IntrinsicISizeType type = aConstraint == SizingConstraint::MaxContent
                                      ? IntrinsicISizeType::PrefISize
                                      : IntrinsicISizeType::MinISize;
        auto sz =
            ::ContentContribution(*item, aState, &aState.mRenderingContext, wm,
                                  masonryAxis, Some(percentBasis), type);
        pos = sz + masonrySizes[masonryRange.mStart].mPosition;
      }
      pos += gap;
      for (uint32_t i : gridRange.Range()) {
        lastPos[i] = currentPos[i];
        currentPos[i] = pos;
      }
    }
  }

  // Do the remaining baseline alignment sets.
  if (aConstraint == SizingConstraint::NoConstraint) {
    for (auto*& item : lastItems) {
      if (item) {
        item->mState[masonryAxis] |= ItemState::eIsLastItemInMasonryTrack;
      }
    }
    BaselineAlignmentSet baselineSets[] = {
        {BaselineAlignmentSet::FirstItems, BaselineAlignmentSet::StartStretch},
        {BaselineAlignmentSet::FirstItems, BaselineAlignmentSet::EndStretch},
        {BaselineAlignmentSet::LastItems, BaselineAlignmentSet::StartStretch},
        {BaselineAlignmentSet::LastItems, BaselineAlignmentSet::EndStretch},
    };
    for (uint32_t i = 0; i < ArrayLength(baselineSets); ++i) {
      if (i == 0 && didAlignStartAlignedFirstItems) {
        continue;
      }
      applyBaselineAlignment(baselineSets[i]);
    }
  }

  const bool childrenMoved = PushIncompleteChildren(
      pushedItems, incompleteItems, overflowIncompleteItems);
  if (childrenMoved && aStatus.IsComplete()) {
    aStatus.SetOverflowIncomplete();
    aStatus.SetNextInFlowNeedsReflow();
  }
  if (!pushedItems.IsEmpty()) {
    AddStateBits(NS_STATE_GRID_DID_PUSH_ITEMS);
    // NOTE since we messed with our child list here, we intentionally
    // make aState.mIter invalid to avoid any use of it after this point.
    aState.mIter.Invalidate();
  }
  if (!incompleteItems.IsEmpty()) {
    // NOTE since we messed with our child list here, we intentionally
    // make aState.mIter invalid to avoid any use of it after this point.
    aState.mIter.Invalidate();
  }

  nscoord masonryBoxSize = 0;
  for (auto pos : currentPos) {
    masonryBoxSize = std::max(masonryBoxSize, pos);
  }
  masonryBoxSize = std::max(nscoord(0), masonryBoxSize - gap);
  if (aConstraint == SizingConstraint::NoConstraint) {
    aState.AlignJustifyContentInMasonryAxis(masonryBoxSize,
                                            masonryTracks.mContentBoxSize);
  }
  return masonryBoxSize;
}

nsGridContainerFrame* nsGridContainerFrame::ParentGridContainerForSubgrid()
    const {
  MOZ_ASSERT(IsSubgrid());
  nsIFrame* p = GetParent();
  while (p->GetContent() == GetContent()) {
    p = p->GetParent();
  }
  MOZ_ASSERT(p->IsGridContainerFrame());
  auto* parent = static_cast<nsGridContainerFrame*>(p);
  MOZ_ASSERT(parent->HasSubgridItems());
  return parent;
}

nscoord nsGridContainerFrame::ReflowChildren(GridReflowInput& aState,
                                             const LogicalRect& aContentArea,
                                             const nsSize& aContainerSize,
                                             ReflowOutput& aDesiredSize,
                                             nsReflowStatus& aStatus) {
  WritingMode wm = aState.mReflowInput->GetWritingMode();
  nscoord bSize = aContentArea.BSize(wm);
  MOZ_ASSERT(aState.mReflowInput);
  MOZ_ASSERT(aStatus.IsEmpty(), "Caller should pass a fresh reflow status!");
  if (HidesContentForLayout()) {
    return bSize;
  }

  OverflowAreas ocBounds;
  nsReflowStatus ocStatus;
  if (GetPrevInFlow()) {
    ReflowOverflowContainerChildren(PresContext(), *aState.mReflowInput,
                                    ocBounds, ReflowChildFlags::Default,
                                    ocStatus, MergeSortedFrameListsFor);
  }

  Maybe<Fragmentainer> fragmentainer = GetNearestFragmentainer(aState);
  // MasonryLayout() can only handle fragmentation in the masonry-axis,
  // so we let ReflowInFragmentainer() deal with grid-axis fragmentation
  // in the else-clause below.
  if (IsMasonry() &&
      !(IsMasonry(eLogicalAxisInline) && fragmentainer.isSome())) {
    aState.mInFragmentainer = fragmentainer.isSome();
    nscoord sz = MasonryLayout(
        aState, aContentArea, SizingConstraint::NoConstraint, aDesiredSize,
        aStatus, fragmentainer.ptrOr(nullptr), aContainerSize);
    if (IsMasonry(eLogicalAxisBlock)) {
      bSize = aState.mReflowInput->ComputedBSize();
      if (bSize == NS_UNCONSTRAINEDSIZE) {
        bSize = aState.mReflowInput->ApplyMinMaxBSize(sz);
      }
    }
  } else if (MOZ_UNLIKELY(fragmentainer.isSome())) {
    if (IsMasonry(eLogicalAxisInline) && !GetPrevInFlow()) {
      // First we do an unconstrained reflow to resolve the item placement
      // which is then kept as-is in the constrained reflow below.
      MasonryLayout(aState, aContentArea, SizingConstraint::NoConstraint,
                    aDesiredSize, aStatus, nullptr, aContainerSize);
    }
    aState.mInFragmentainer = true;
    bSize = ReflowInFragmentainer(aState, aContentArea, aDesiredSize, aStatus,
                                  *fragmentainer, aContainerSize);
  } else {
    aState.mIter.Reset(CSSOrderAwareFrameIterator::ChildFilter::IncludeAll);
    for (; !aState.mIter.AtEnd(); aState.mIter.Next()) {
      nsIFrame* child = *aState.mIter;
      const GridItemInfo* info = nullptr;
      if (!child->IsPlaceholderFrame()) {
        info = &aState.mGridItems[aState.mIter.ItemIndex()];
      }
      ReflowInFlowChild(child, info, aContainerSize, Nothing(), nullptr, aState,
                        aContentArea, aDesiredSize, aStatus);
      MOZ_ASSERT(aStatus.IsComplete(),
                 "child should be complete in unconstrained reflow");
    }
  }

  // Merge overflow container bounds and status.
  aDesiredSize.mOverflowAreas.UnionWith(ocBounds);
  aStatus.MergeCompletionStatusFrom(ocStatus);

  if (IsAbsoluteContainer()) {
    const nsFrameList& children = GetChildList(GetAbsoluteListID());
    if (!children.IsEmpty()) {
      // 'gridOrigin' is the origin of the grid (the start of the first track),
      // with respect to the grid container's padding-box (CB).
      LogicalMargin pad(aState.mReflowInput->ComputedLogicalPadding(wm));
      const LogicalPoint gridOrigin(wm, pad.IStart(wm), pad.BStart(wm));
      const LogicalRect gridCB(wm, 0, 0,
                               aContentArea.ISize(wm) + pad.IStartEnd(wm),
                               bSize + pad.BStartEnd(wm));
      const nsSize gridCBPhysicalSize = gridCB.Size(wm).GetPhysicalSize(wm);
      size_t i = 0;
      for (nsIFrame* child : children) {
        MOZ_ASSERT(i < aState.mAbsPosItems.Length());
        MOZ_ASSERT(aState.mAbsPosItems[i].mFrame == child);
        GridArea& area = aState.mAbsPosItems[i].mArea;
        LogicalRect itemCB =
            aState.ContainingBlockForAbsPos(area, gridOrigin, gridCB);
        // nsAbsoluteContainingBlock::Reflow uses physical coordinates.
        nsRect* cb = child->GetProperty(GridItemContainingBlockRect());
        if (!cb) {
          cb = new nsRect;
          child->SetProperty(GridItemContainingBlockRect(), cb);
        }
        *cb = itemCB.GetPhysicalRect(wm, gridCBPhysicalSize);
        ++i;
      }
      // We pass a dummy rect as CB because each child has its own CB rect.
      // The eIsGridContainerCB flag tells nsAbsoluteContainingBlock::Reflow to
      // use those instead.
      nsRect dummyRect;
      AbsPosReflowFlags flags =
          AbsPosReflowFlags::CBWidthAndHeightChanged;  // XXX could be optimized
      flags |= AbsPosReflowFlags::ConstrainHeight;
      flags |= AbsPosReflowFlags::IsGridContainerCB;
      GetAbsoluteContainingBlock()->Reflow(
          this, PresContext(), *aState.mReflowInput, aStatus, dummyRect, flags,
          &aDesiredSize.mOverflowAreas);
    }
  }
  return bSize;
}

void nsGridContainerFrame::Reflow(nsPresContext* aPresContext,
                                  ReflowOutput& aDesiredSize,
                                  const ReflowInput& aReflowInput,
                                  nsReflowStatus& aStatus) {
  if (IsHiddenByContentVisibilityOfInFlowParentForLayout()) {
    return;
  }

  MarkInReflow();
  DO_GLOBAL_REFLOW_COUNT("nsGridContainerFrame");
  DISPLAY_REFLOW(aPresContext, this, aReflowInput, aDesiredSize, aStatus);
  MOZ_ASSERT(aStatus.IsEmpty(), "Caller should pass a fresh reflow status!");

  if (IsFrameTreeTooDeep(aReflowInput, aDesiredSize, aStatus)) {
    return;
  }

  NormalizeChildLists();

#ifdef DEBUG
  mDidPushItemsBitMayLie = false;
  SanityCheckChildListsBeforeReflow();
#endif  // DEBUG

  for (auto& perAxisBaseline : mBaseline) {
    for (auto& baseline : perAxisBaseline) {
      baseline = NS_INTRINSIC_ISIZE_UNKNOWN;
    }
  }

  const nsStylePosition* stylePos = aReflowInput.mStylePosition;
  auto prevInFlow = static_cast<nsGridContainerFrame*>(GetPrevInFlow());
  if (MOZ_LIKELY(!prevInFlow)) {
    InitImplicitNamedAreas(stylePos);
  } else {
    MOZ_ASSERT(prevInFlow->HasAnyStateBits(kIsSubgridBits) ==
                   HasAnyStateBits(kIsSubgridBits),
               "continuations should have same kIsSubgridBits");
  }
  GridReflowInput gridReflowInput(this, aReflowInput);
  if (gridReflowInput.mIter.ItemsAreAlreadyInOrder()) {
    AddStateBits(NS_STATE_GRID_NORMAL_FLOW_CHILDREN_IN_CSS_ORDER);
  } else {
    RemoveStateBits(NS_STATE_GRID_NORMAL_FLOW_CHILDREN_IN_CSS_ORDER);
  }
  if (gridReflowInput.mIter.AtEnd() ||
      aReflowInput.mStyleDisplay->IsContainLayout()) {
    // We have no grid items, or we're layout-contained. So, we have no
    // baseline, and our parent should synthesize a baseline if needed.
    AddStateBits(NS_STATE_GRID_SYNTHESIZE_BASELINE);
  } else {
    RemoveStateBits(NS_STATE_GRID_SYNTHESIZE_BASELINE);
  }
  const nscoord computedBSize = aReflowInput.ComputedBSize();
  const nscoord computedISize = aReflowInput.ComputedISize();
  const WritingMode& wm = gridReflowInput.mWM;
  const LogicalSize computedSize(wm, computedISize, computedBSize);

  nscoord consumedBSize = 0;
  nscoord bSize = 0;
  if (MOZ_LIKELY(!prevInFlow)) {
    Grid grid;
    if (MOZ_LIKELY(!IsSubgrid())) {
      RepeatTrackSizingInput repeatSizing(aReflowInput.ComputedMinSize(),
                                          computedSize,
                                          aReflowInput.ComputedMaxSize());
      grid.PlaceGridItems(gridReflowInput, repeatSizing);
    } else {
      auto* subgrid = GetProperty(Subgrid::Prop());
      MOZ_ASSERT(subgrid, "an ancestor forgot to call PlaceGridItems?");
      gridReflowInput.mGridItems = subgrid->mGridItems.Clone();
      gridReflowInput.mAbsPosItems = subgrid->mAbsPosItems.Clone();
      grid.mGridColEnd = subgrid->mGridColEnd;
      grid.mGridRowEnd = subgrid->mGridRowEnd;
    }
    // XXX Technically incorrect: 'contain-intrinsic-block-size: none' is
    // treated as 0, ignoring our row sizes, when really we should use them but
    // *they* should be computed as if we had no children. To be fixed in bug
    // 1488878.
    const Maybe<nscoord> containBSize =
        aReflowInput.mFrame->ContainIntrinsicBSize();
    const nscoord trackSizingBSize = [&] {
      // This clamping only applies to auto sizes.
      if (containBSize && computedBSize == NS_UNCONSTRAINEDSIZE) {
        return aReflowInput.ApplyMinMaxBSize(*containBSize);
      }
      return computedBSize;
    }();
    const LogicalSize containLogicalSize(wm, computedISize, trackSizingBSize);
    gridReflowInput.CalculateTrackSizes(grid, containLogicalSize,
                                        SizingConstraint::NoConstraint);
    if (containBSize) {
      bSize = *containBSize;
    } else {
      if (IsMasonry(eLogicalAxisBlock)) {
        bSize = computedBSize;
      } else {
        const auto& rowSizes = gridReflowInput.mRows.mSizes;
        if (MOZ_LIKELY(!IsSubgrid(eLogicalAxisBlock))) {
          // Note: we can't use GridLineEdge here since we haven't calculated
          // the rows' mPosition yet (happens in AlignJustifyContent below).
          for (const auto& sz : rowSizes) {
            bSize += sz.mBase;
          }
          bSize += gridReflowInput.mRows.SumOfGridGaps();
        } else if (computedBSize == NS_UNCONSTRAINEDSIZE) {
          bSize = gridReflowInput.mRows.GridLineEdge(
              rowSizes.Length(), GridLineSide::BeforeGridGap);
        }
      }
    }
  } else {
    consumedBSize = CalcAndCacheConsumedBSize();
    gridReflowInput.InitializeForContinuation(this, consumedBSize);
    // XXX Technically incorrect: 'contain-intrinsic-block-size: none' is
    // treated as 0, ignoring our row sizes, when really we should use them but
    // *they* should be computed as if we had no children. To be fixed in bug
    // 1488878.
    if (Maybe<nscoord> containBSize =
            aReflowInput.mFrame->ContainIntrinsicBSize()) {
      bSize = *containBSize;
    } else {
      const uint32_t numRows = gridReflowInput.mRows.mSizes.Length();
      bSize = gridReflowInput.mRows.GridLineEdge(numRows,
                                                 GridLineSide::AfterGridGap);
    }
  }
  if (computedBSize == NS_UNCONSTRAINEDSIZE) {
    bSize = aReflowInput.ApplyMinMaxBSize(bSize);
  } else if (aReflowInput.ShouldApplyAutomaticMinimumOnBlockAxis()) {
    nscoord contentBSize = aReflowInput.ApplyMinMaxBSize(bSize);
    bSize = std::max(contentBSize, computedBSize);
  } else {
    bSize = computedBSize;
  }
  if (bSize != NS_UNCONSTRAINEDSIZE) {
    bSize = std::max(bSize - consumedBSize, 0);
  }
  auto& bp = gridReflowInput.mBorderPadding;
  LogicalRect contentArea(wm, bp.IStart(wm), bp.BStart(wm), computedISize,
                          bSize);

  if (!prevInFlow) {
    const auto& rowSizes = gridReflowInput.mRows.mSizes;
    if (!IsRowSubgrid()) {
      // Apply 'align-content' to the grid.
      if (computedBSize == NS_UNCONSTRAINEDSIZE &&
          stylePos->mRowGap.IsLengthPercentage() &&
          stylePos->mRowGap.AsLengthPercentage().HasPercent()) {
        // Re-resolve the row-gap now that we know our intrinsic block-size.
        gridReflowInput.mRows.mGridGap =
            nsLayoutUtils::ResolveGapToLength(stylePos->mRowGap, bSize);
      }
      if (!gridReflowInput.mRows.mIsMasonry) {
        auto alignment = stylePos->mAlignContent;
        gridReflowInput.mRows.AlignJustifyContent(stylePos, alignment, wm,
                                                  bSize, false);
      }
    } else {
      if (computedBSize == NS_UNCONSTRAINEDSIZE) {
        bSize = gridReflowInput.mRows.GridLineEdge(rowSizes.Length(),
                                                   GridLineSide::BeforeGridGap);
        contentArea.BSize(wm) = std::max(bSize, nscoord(0));
      }
    }
    // Save the final row sizes for use by subgrids, if needed.
    if (HasSubgridItems() || IsSubgrid()) {
      StoreUsedTrackSizes(eLogicalAxisBlock, rowSizes);
    }
  }

  nsSize containerSize = contentArea.Size(wm).GetPhysicalSize(wm);
  bool repositionChildren = false;
  if (containerSize.width == NS_UNCONSTRAINEDSIZE && wm.IsVerticalRL()) {
    // Note that writing-mode:vertical-rl is the only case where the block
    // logical direction progresses in a negative physical direction, and
    // therefore block-dir coordinate conversion depends on knowing the width
    // of the coordinate space in order to translate between the logical and
    // physical origins.
    //
    // A masonry axis size may be unconstrained, otherwise in a regular grid
    // our intrinsic size is always known by now.  We'll re-position
    // the children below once our size is known.
    repositionChildren = true;
    containerSize.width = 0;
  }
  containerSize.width += bp.LeftRight(wm);
  containerSize.height += bp.TopBottom(wm);

  bSize = ReflowChildren(gridReflowInput, contentArea, containerSize,
                         aDesiredSize, aStatus);
  bSize = std::max(bSize - consumedBSize, 0);

  // Skip our block-end border if we're INCOMPLETE.
  if (!aStatus.IsComplete() && !gridReflowInput.mSkipSides.BEnd() &&
      StyleBorder()->mBoxDecorationBreak != StyleBoxDecorationBreak::Clone) {
    bp.BEnd(wm) = nscoord(0);
  }

  LogicalSize desiredSize(wm, computedISize + bp.IStartEnd(wm),
                          bSize + bp.BStartEnd(wm));
  aDesiredSize.SetSize(wm, desiredSize);
  nsRect frameRect(0, 0, aDesiredSize.Width(), aDesiredSize.Height());
  aDesiredSize.mOverflowAreas.UnionAllWith(frameRect);

  if (repositionChildren) {
    nsPoint physicalDelta(aDesiredSize.Width() - bp.LeftRight(wm), 0);
    for (const auto& item : gridReflowInput.mGridItems) {
      auto* child = item.mFrame;
      child->MovePositionBy(physicalDelta);
      ConsiderChildOverflow(aDesiredSize.mOverflowAreas, child);
    }
  }

  if (Style()->GetPseudoType() == PseudoStyleType::scrolledContent) {
    // Per spec, the grid area is included in a grid container's scrollable
    // overflow region [1], as well as the padding on the end-edge sides that
    // would satisfy the requirements of 'place-content: end' alignment [2].
    //
    // Note that we include the padding from all sides of the grid area, not
    // just the end sides; this is fine because the grid area is relative to our
    // content-box origin. The inflated bounds won't go beyond our padding-box
    // edges on the start sides.
    //
    // The margin areas of grid item boxes are also included in the scrollable
    // overflow region [2].
    //
    // [1] https://drafts.csswg.org/css-grid-1/#overflow
    // [2] https://drafts.csswg.org/css-overflow-3/#scrollable

    // Synthesize a grid area covering all columns and rows, and compute its
    // rect relative to our border-box.
    //
    // Note: the grid columns and rows exist only if there is an explicit grid;
    // or when an implicit grid is needed to place any grid items. See
    // nsGridContainerFrame::Grid::PlaceGridItems().
    const auto numCols =
        static_cast<int32_t>(gridReflowInput.mCols.mSizes.Length());
    const auto numRows =
        static_cast<int32_t>(gridReflowInput.mRows.mSizes.Length());
    if (numCols > 0 && numRows > 0) {
      const GridArea gridArea(LineRange(0, numCols), LineRange(0, numRows));
      const LogicalRect gridAreaRect =
          gridReflowInput.ContainingBlockFor(gridArea) +
          LogicalPoint(wm, bp.IStart(wm), bp.BStart(wm));

      MOZ_ASSERT(bp == aReflowInput.ComputedLogicalPadding(wm),
                 "A scrolled inner frame shouldn't have any border!");
      const LogicalMargin& padding = bp;
      nsRect physicalGridAreaRectWithPadding =
          gridAreaRect.GetPhysicalRect(wm, containerSize);
      physicalGridAreaRectWithPadding.Inflate(padding.GetPhysicalMargin(wm));
      aDesiredSize.mOverflowAreas.UnionAllWith(physicalGridAreaRectWithPadding);
    }

    nsRect gridItemMarginBoxBounds;
    for (const auto& item : gridReflowInput.mGridItems) {
      gridItemMarginBoxBounds =
          gridItemMarginBoxBounds.Union(item.mFrame->GetMarginRect());
    }
    aDesiredSize.mOverflowAreas.UnionAllWith(gridItemMarginBoxBounds);
  }

  // TODO: fix align-tracks alignment in fragments
  if ((IsMasonry(eLogicalAxisBlock) && !prevInFlow) ||
      IsMasonry(eLogicalAxisInline)) {
    gridReflowInput.AlignJustifyTracksInMasonryAxis(
        contentArea.Size(wm), aDesiredSize.PhysicalSize());
  }

  // Convert INCOMPLETE -> OVERFLOW_INCOMPLETE and zero bsize if we're an OC.
  if (HasAnyStateBits(NS_FRAME_IS_OVERFLOW_CONTAINER)) {
    if (!aStatus.IsComplete()) {
      aStatus.SetOverflowIncomplete();
      aStatus.SetNextInFlowNeedsReflow();
    }
    bSize = 0;
    desiredSize.BSize(wm) = bSize + bp.BStartEnd(wm);
    aDesiredSize.SetSize(wm, desiredSize);
  }

  if (!gridReflowInput.mInFragmentainer) {
    MOZ_ASSERT(gridReflowInput.mIter.IsValid());
    auto sz = frameRect.Size();
    CalculateBaselines(BaselineSet::eBoth, &gridReflowInput.mIter,
                       &gridReflowInput.mGridItems, gridReflowInput.mCols, 0,
                       gridReflowInput.mCols.mSizes.Length(), wm, sz,
                       bp.IStart(wm), bp.IEnd(wm), desiredSize.ISize(wm));
    CalculateBaselines(BaselineSet::eBoth, &gridReflowInput.mIter,
                       &gridReflowInput.mGridItems, gridReflowInput.mRows, 0,
                       gridReflowInput.mRows.mSizes.Length(), wm, sz,
                       bp.BStart(wm), bp.BEnd(wm), desiredSize.BSize(wm));
  } else {
    // Only compute 'first baseline' if this fragment contains the first track.
    // XXXmats maybe remove this condition? bug 1306499
    BaselineSet baselines = BaselineSet::eNone;
    if (gridReflowInput.mStartRow == 0 &&
        gridReflowInput.mStartRow != gridReflowInput.mNextFragmentStartRow) {
      baselines = BaselineSet::eFirst;
    }
    // Only compute 'last baseline' if this fragment contains the last track.
    // XXXmats maybe remove this condition? bug 1306499
    uint32_t len = gridReflowInput.mRows.mSizes.Length();
    if (gridReflowInput.mStartRow != len &&
        gridReflowInput.mNextFragmentStartRow == len) {
      baselines = BaselineSet(baselines | BaselineSet::eLast);
    }
    Maybe<CSSOrderAwareFrameIterator> iter;
    Maybe<nsTArray<GridItemInfo>> gridItems;
    if (baselines != BaselineSet::eNone) {
      // We need to create a new iterator and GridItemInfo array because we
      // might have pushed some children at this point.
      // Even if the gridReflowInput iterator is invalid we can reuse its
      // state about order to optimize initialization of the new iterator.
      // An ordered child list can't become unordered by pushing frames.
      // An unordered list can become ordered in a number of cases, but we
      // ignore that here and guess that the child list is still unordered.
      // XXX this is O(n^2) in the number of items in this fragment: bug 1306705
      using Filter = CSSOrderAwareFrameIterator::ChildFilter;
      using Order = CSSOrderAwareFrameIterator::OrderState;
      bool ordered = gridReflowInput.mIter.ItemsAreAlreadyInOrder();
      auto orderState = ordered ? Order::Ordered : Order::Unordered;
      iter.emplace(this, FrameChildListID::Principal, Filter::SkipPlaceholders,
                   orderState);
      gridItems.emplace();
      for (; !iter->AtEnd(); iter->Next()) {
        auto child = **iter;
        for (const auto& info : gridReflowInput.mGridItems) {
          if (info.mFrame == child) {
            gridItems->AppendElement(info);
          }
        }
      }
    }
    auto sz = frameRect.Size();
    CalculateBaselines(baselines, iter.ptrOr(nullptr), gridItems.ptrOr(nullptr),
                       gridReflowInput.mCols, 0,
                       gridReflowInput.mCols.mSizes.Length(), wm, sz,
                       bp.IStart(wm), bp.IEnd(wm), desiredSize.ISize(wm));
    CalculateBaselines(baselines, iter.ptrOr(nullptr), gridItems.ptrOr(nullptr),
                       gridReflowInput.mRows, gridReflowInput.mStartRow,
                       gridReflowInput.mNextFragmentStartRow, wm, sz,
                       bp.BStart(wm), bp.BEnd(wm), desiredSize.BSize(wm));
  }

  if (HasAnyStateBits(NS_STATE_GRID_COMPUTED_INFO)) {
    // This state bit will never be cleared, since reflow can be called
    // multiple times in fragmented grids, and it's challenging to scope
    // the bit to only that sequence of calls. This is relatively harmless
    // since this bit is only set by accessing a ChromeOnly property, and
    // therefore can't unduly slow down normal web browsing.

    // Clear our GridFragmentInfo property, which might be holding a stale
    // dom::Grid object built from previously-computed info. This will
    // ensure that the next call to GetGridFragments will create a new one.
    if (mozilla::dom::Grid* grid = TakeProperty(GridFragmentInfo())) {
      grid->ForgetFrame();
    }

    // Now that we know column and row sizes and positions, set
    // the ComputedGridTrackInfo and related properties

    const auto* subgrid = GetProperty(Subgrid::Prop());
    const auto* subgridColRange = subgrid && IsSubgrid(eLogicalAxisInline)
                                      ? &subgrid->SubgridCols()
                                      : nullptr;

    LineNameMap colLineNameMap(
        gridReflowInput.mGridStyle, GetImplicitNamedAreas(),
        gridReflowInput.mColFunctions, nullptr, subgridColRange, true);
    uint32_t colTrackCount = gridReflowInput.mCols.mSizes.Length();
    nsTArray<nscoord> colTrackPositions(colTrackCount);
    nsTArray<nscoord> colTrackSizes(colTrackCount);
    nsTArray<uint32_t> colTrackStates(colTrackCount);
    nsTArray<bool> colRemovedRepeatTracks(
        gridReflowInput.mColFunctions.mRemovedRepeatTracks.Clone());
    uint32_t col = 0;
    for (const TrackSize& sz : gridReflowInput.mCols.mSizes) {
      colTrackPositions.AppendElement(sz.mPosition);
      colTrackSizes.AppendElement(sz.mBase);
      bool isRepeat =
          ((col >= gridReflowInput.mColFunctions.mRepeatAutoStart) &&
           (col < gridReflowInput.mColFunctions.mRepeatAutoEnd));
      colTrackStates.AppendElement(
          isRepeat ? (uint32_t)mozilla::dom::GridTrackState::Repeat
                   : (uint32_t)mozilla::dom::GridTrackState::Static);

      col++;
    }
    // Get the number of explicit tracks first. The order of argument evaluation
    // is implementation-defined. We should be OK here because colTrackSizes is
    // taken by rvalue, but computing the size first prevents any changes in the
    // argument types of the constructor from breaking this.
    const uint32_t numColExplicitTracks =
        IsSubgrid(eLogicalAxisInline)
            ? colTrackSizes.Length()
            : gridReflowInput.mColFunctions.NumExplicitTracks();
    ComputedGridTrackInfo* colInfo = new ComputedGridTrackInfo(
        gridReflowInput.mColFunctions.mExplicitGridOffset, numColExplicitTracks,
        0, col, std::move(colTrackPositions), std::move(colTrackSizes),
        std::move(colTrackStates), std::move(colRemovedRepeatTracks),
        gridReflowInput.mColFunctions.mRepeatAutoStart,
        colLineNameMap.GetResolvedLineNamesForComputedGridTrackInfo(),
        IsSubgrid(eLogicalAxisInline), IsMasonry(eLogicalAxisInline));
    SetProperty(GridColTrackInfo(), colInfo);

    const auto* subgridRowRange = subgrid && IsSubgrid(eLogicalAxisBlock)
                                      ? &subgrid->SubgridRows()
                                      : nullptr;
    LineNameMap rowLineNameMap(
        gridReflowInput.mGridStyle, GetImplicitNamedAreas(),
        gridReflowInput.mRowFunctions, nullptr, subgridRowRange, true);
    uint32_t rowTrackCount = gridReflowInput.mRows.mSizes.Length();
    nsTArray<nscoord> rowTrackPositions(rowTrackCount);
    nsTArray<nscoord> rowTrackSizes(rowTrackCount);
    nsTArray<uint32_t> rowTrackStates(rowTrackCount);
    nsTArray<bool> rowRemovedRepeatTracks(
        gridReflowInput.mRowFunctions.mRemovedRepeatTracks.Clone());
    uint32_t row = 0;
    for (const TrackSize& sz : gridReflowInput.mRows.mSizes) {
      rowTrackPositions.AppendElement(sz.mPosition);
      rowTrackSizes.AppendElement(sz.mBase);
      bool isRepeat =
          ((row >= gridReflowInput.mRowFunctions.mRepeatAutoStart) &&
           (row < gridReflowInput.mRowFunctions.mRepeatAutoEnd));
      rowTrackStates.AppendElement(
          isRepeat ? (uint32_t)mozilla::dom::GridTrackState::Repeat
                   : (uint32_t)mozilla::dom::GridTrackState::Static);

      row++;
    }
    // Get the number of explicit tracks first. The order of argument evaluation
    // is implementation-defined. We should be OK here because colTrackSizes is
    // taken by rvalue, but computing the size first prevents any changes in the
    // argument types of the constructor from breaking this.
    const uint32_t numRowExplicitTracks =
        IsSubgrid(eLogicalAxisBlock)
            ? rowTrackSizes.Length()
            : gridReflowInput.mRowFunctions.NumExplicitTracks();
    // Row info has to accommodate fragmentation of the grid, which may happen
    // in later calls to Reflow. For now, presume that no more fragmentation
    // will occur.
    ComputedGridTrackInfo* rowInfo = new ComputedGridTrackInfo(
        gridReflowInput.mRowFunctions.mExplicitGridOffset, numRowExplicitTracks,
        gridReflowInput.mStartRow, row, std::move(rowTrackPositions),
        std::move(rowTrackSizes), std::move(rowTrackStates),
        std::move(rowRemovedRepeatTracks),
        gridReflowInput.mRowFunctions.mRepeatAutoStart,
        rowLineNameMap.GetResolvedLineNamesForComputedGridTrackInfo(),
        IsSubgrid(eLogicalAxisBlock), IsMasonry(eLogicalAxisBlock));
    SetProperty(GridRowTrackInfo(), rowInfo);

    if (prevInFlow) {
      // This frame is fragmenting rows from a previous frame, so patch up
      // the prior GridRowTrackInfo with a new end row.

      // FIXME: This can be streamlined and/or removed when bug 1151204 lands.

      ComputedGridTrackInfo* priorRowInfo =
          prevInFlow->GetProperty(GridRowTrackInfo());

      // Adjust track positions based on the first track in this fragment.
      if (priorRowInfo->mPositions.Length() >
          priorRowInfo->mStartFragmentTrack) {
        nscoord delta =
            priorRowInfo->mPositions[priorRowInfo->mStartFragmentTrack];
        for (nscoord& pos : priorRowInfo->mPositions) {
          pos -= delta;
        }
      }

      ComputedGridTrackInfo* revisedPriorRowInfo = new ComputedGridTrackInfo(
          priorRowInfo->mNumLeadingImplicitTracks,
          priorRowInfo->mNumExplicitTracks, priorRowInfo->mStartFragmentTrack,
          gridReflowInput.mStartRow, std::move(priorRowInfo->mPositions),
          std::move(priorRowInfo->mSizes), std::move(priorRowInfo->mStates),
          std::move(priorRowInfo->mRemovedRepeatTracks),
          priorRowInfo->mRepeatFirstTrack,
          std::move(priorRowInfo->mResolvedLineNames), priorRowInfo->mIsSubgrid,
          priorRowInfo->mIsMasonry);
      prevInFlow->SetProperty(GridRowTrackInfo(), revisedPriorRowInfo);
    }

    // Generate the line info properties. We need to provide the number of
    // repeat tracks produced in the reflow. Only explicit names are assigned
    // to lines here; the mozilla::dom::GridLines class will later extract
    // implicit names from grid areas and assign them to the appropriate lines.

    auto& colFunctions = gridReflowInput.mColFunctions;

    // Generate column lines first.
    uint32_t capacity = gridReflowInput.mCols.mSizes.Length();
    nsTArray<nsTArray<RefPtr<nsAtom>>> columnLineNames(capacity);
    for (col = 0; col <= gridReflowInput.mCols.mSizes.Length(); col++) {
      // Offset col by the explicit grid offset, to get the original names.
      nsTArray<RefPtr<nsAtom>> explicitNames =
          colLineNameMap.GetExplicitLineNamesAtIndex(
              col - colFunctions.mExplicitGridOffset);

      columnLineNames.EmplaceBack(std::move(explicitNames));
    }
    // Get the explicit names that follow a repeat auto declaration.
    nsTArray<RefPtr<nsAtom>> colNamesFollowingRepeat;
    nsTArray<RefPtr<nsAtom>> colBeforeRepeatAuto;
    nsTArray<RefPtr<nsAtom>> colAfterRepeatAuto;
    // Note: the following is only used for a non-subgridded axis.
    if (colLineNameMap.HasRepeatAuto()) {
      MOZ_ASSERT(!colFunctions.mTemplate.IsSubgrid());
      // The line name list after the repeatAutoIndex holds the line names
      // for the first explicit line after the repeat auto declaration.
      uint32_t repeatAutoEnd = colLineNameMap.RepeatAutoStart() + 1;
      for (auto* list : colLineNameMap.ExpandedLineNames()[repeatAutoEnd]) {
        for (auto& name : list->AsSpan()) {
          colNamesFollowingRepeat.AppendElement(name.AsAtom());
        }
      }
      auto names = colLineNameMap.TrackAutoRepeatLineNames();
      for (auto& name : names[0].AsSpan()) {
        colBeforeRepeatAuto.AppendElement(name.AsAtom());
      }
      for (auto& name : names[1].AsSpan()) {
        colAfterRepeatAuto.AppendElement(name.AsAtom());
      }
    }

    ComputedGridLineInfo* columnLineInfo = new ComputedGridLineInfo(
        std::move(columnLineNames), std::move(colBeforeRepeatAuto),
        std::move(colAfterRepeatAuto), std::move(colNamesFollowingRepeat));
    SetProperty(GridColumnLineInfo(), columnLineInfo);

    // Generate row lines next.
    auto& rowFunctions = gridReflowInput.mRowFunctions;
    capacity = gridReflowInput.mRows.mSizes.Length();
    nsTArray<nsTArray<RefPtr<nsAtom>>> rowLineNames(capacity);
    for (row = 0; row <= gridReflowInput.mRows.mSizes.Length(); row++) {
      // Offset row by the explicit grid offset, to get the original names.
      nsTArray<RefPtr<nsAtom>> explicitNames =
          rowLineNameMap.GetExplicitLineNamesAtIndex(
              row - rowFunctions.mExplicitGridOffset);
      rowLineNames.EmplaceBack(std::move(explicitNames));
    }
    // Get the explicit names that follow a repeat auto declaration.
    nsTArray<RefPtr<nsAtom>> rowNamesFollowingRepeat;
    nsTArray<RefPtr<nsAtom>> rowBeforeRepeatAuto;
    nsTArray<RefPtr<nsAtom>> rowAfterRepeatAuto;
    // Note: the following is only used for a non-subgridded axis.
    if (rowLineNameMap.HasRepeatAuto()) {
      MOZ_ASSERT(!rowFunctions.mTemplate.IsSubgrid());
      // The line name list after the repeatAutoIndex holds the line names
      // for the first explicit line after the repeat auto declaration.
      uint32_t repeatAutoEnd = rowLineNameMap.RepeatAutoStart() + 1;
      for (auto* list : rowLineNameMap.ExpandedLineNames()[repeatAutoEnd]) {
        for (auto& name : list->AsSpan()) {
          rowNamesFollowingRepeat.AppendElement(name.AsAtom());
        }
      }
      auto names = rowLineNameMap.TrackAutoRepeatLineNames();
      for (auto& name : names[0].AsSpan()) {
        rowBeforeRepeatAuto.AppendElement(name.AsAtom());
      }
      for (auto& name : names[1].AsSpan()) {
        rowAfterRepeatAuto.AppendElement(name.AsAtom());
      }
    }

    ComputedGridLineInfo* rowLineInfo = new ComputedGridLineInfo(
        std::move(rowLineNames), std::move(rowBeforeRepeatAuto),
        std::move(rowAfterRepeatAuto), std::move(rowNamesFollowingRepeat));
    SetProperty(GridRowLineInfo(), rowLineInfo);

    // Generate area info for explicit areas. Implicit areas are handled
    // elsewhere.
    if (!gridReflowInput.mGridStyle->mGridTemplateAreas.IsNone()) {
      auto* areas = new StyleOwnedSlice<NamedArea>(
          gridReflowInput.mGridStyle->mGridTemplateAreas.AsAreas()->areas);
      SetProperty(ExplicitNamedAreasProperty(), areas);
    } else {
      RemoveProperty(ExplicitNamedAreasProperty());
    }
  }

  if (!prevInFlow) {
    SharedGridData* sharedGridData = GetProperty(SharedGridData::Prop());
    if (!aStatus.IsFullyComplete()) {
      if (!sharedGridData) {
        sharedGridData = new SharedGridData;
        SetProperty(SharedGridData::Prop(), sharedGridData);
      }
      sharedGridData->mCols.mSizes = std::move(gridReflowInput.mCols.mSizes);
      sharedGridData->mCols.mContentBoxSize =
          gridReflowInput.mCols.mContentBoxSize;
      sharedGridData->mCols.mBaselineSubtreeAlign =
          gridReflowInput.mCols.mBaselineSubtreeAlign;
      sharedGridData->mCols.mIsMasonry = gridReflowInput.mCols.mIsMasonry;
      sharedGridData->mRows.mSizes = std::move(gridReflowInput.mRows.mSizes);
      // Save the original row grid sizes and gaps so we can restore them later
      // in GridReflowInput::Initialize for the continuations.
      auto& origRowData = sharedGridData->mOriginalRowData;
      origRowData.ClearAndRetainStorage();
      origRowData.SetCapacity(sharedGridData->mRows.mSizes.Length());
      nscoord prevTrackEnd = 0;
      for (auto& sz : sharedGridData->mRows.mSizes) {
        SharedGridData::RowData data = {sz.mBase, sz.mPosition - prevTrackEnd};
        origRowData.AppendElement(data);
        prevTrackEnd = sz.mPosition + sz.mBase;
      }
      sharedGridData->mRows.mContentBoxSize =
          gridReflowInput.mRows.mContentBoxSize;
      sharedGridData->mRows.mBaselineSubtreeAlign =
          gridReflowInput.mRows.mBaselineSubtreeAlign;
      sharedGridData->mRows.mIsMasonry = gridReflowInput.mRows.mIsMasonry;
      sharedGridData->mGridItems = std::move(gridReflowInput.mGridItems);
      sharedGridData->mAbsPosItems = std::move(gridReflowInput.mAbsPosItems);

      sharedGridData->mGenerateComputedGridInfo =
          HasAnyStateBits(NS_STATE_GRID_COMPUTED_INFO);
    } else if (sharedGridData && !GetNextInFlow()) {
      RemoveProperty(SharedGridData::Prop());
    }
  }

  FinishAndStoreOverflow(&aDesiredSize);
}

void nsGridContainerFrame::UpdateSubgridFrameState() {
  nsFrameState oldBits = GetStateBits() & kIsSubgridBits;
  nsFrameState newBits = ComputeSelfSubgridMasonryBits() & kIsSubgridBits;
  if (newBits != oldBits) {
    RemoveStateBits(kIsSubgridBits);
    if (!newBits) {
      RemoveProperty(Subgrid::Prop());
    } else {
      AddStateBits(newBits);
    }
  }
}

nsFrameState nsGridContainerFrame::ComputeSelfSubgridMasonryBits() const {
  nsFrameState bits = nsFrameState(0);
  const auto* pos = StylePosition();

  // We can only have masonry layout in one axis.
  if (pos->mGridTemplateRows.IsMasonry()) {
    bits |= NS_STATE_GRID_IS_ROW_MASONRY;
  } else if (pos->mGridTemplateColumns.IsMasonry()) {
    bits |= NS_STATE_GRID_IS_COL_MASONRY;
  }

  // NOTE: The rest of this function is only relevant if we're a subgrid;
  // hence, we return early as soon as we rule out that possibility.

  // 'contain:layout/paint' makes us an "independent formatting context",
  // which prevents us from being a subgrid in this case (but not always).
  // We will also need to check our containing scroll frame for this property.
  // https://drafts.csswg.org/css-display-3/#establish-an-independent-formatting-context
  if (ShouldInhibitSubgridDueToIFC(this)) {
    return bits;
  }

  // Skip over our scroll frame and such if we have it, to find our "parent
  // grid", if we have one.

  // After this loop, 'parent' will represent the parent of the outermost frame
  // that shares our content node. (Normally this is just our parent frame, but
  // if we're e.g. a scrolled frame, then this will be the parent of our
  // wrapper-scrollable-frame.) If 'parent' turns out to be a grid container,
  // then it's our "parent grid", and we could potentially be a subgrid of it.
  auto* parent = GetParent();
  while (parent && parent->GetContent() == GetContent()) {
    // If we find our containing frame (e.g. our scroll frame) can't be a
    // subgrid, then we can't be a subgrid, for the same reasons as above. This
    // can happen when this frame is itself a grid item with "overflow:scroll"
    // or similar.
    if (ShouldInhibitSubgridDueToIFC(parent)) {
      return bits;
    }
    parent = parent->GetParent();
  }
  const nsGridContainerFrame* parentGrid = do_QueryFrame(parent);
  if (parentGrid) {
    bool isOrthogonal =
        GetWritingMode().IsOrthogonalTo(parent->GetWritingMode());
    bool isColSubgrid = pos->mGridTemplateColumns.IsSubgrid();
    // Subgridding a parent masonry axis makes us use masonry layout too,
    // unless our other axis is a masonry axis.
    if (isColSubgrid &&
        parent->HasAnyStateBits(isOrthogonal ? NS_STATE_GRID_IS_ROW_MASONRY
                                             : NS_STATE_GRID_IS_COL_MASONRY)) {
      isColSubgrid = false;
      if (!HasAnyStateBits(NS_STATE_GRID_IS_ROW_MASONRY)) {
        bits |= NS_STATE_GRID_IS_COL_MASONRY;
      }
    }
    if (isColSubgrid) {
      bits |= NS_STATE_GRID_IS_COL_SUBGRID;
    }

    bool isRowSubgrid = pos->mGridTemplateRows.IsSubgrid();
    if (isRowSubgrid &&
        parent->HasAnyStateBits(isOrthogonal ? NS_STATE_GRID_IS_COL_MASONRY
                                             : NS_STATE_GRID_IS_ROW_MASONRY)) {
      isRowSubgrid = false;
      if (!HasAnyStateBits(NS_STATE_GRID_IS_COL_MASONRY)) {
        bits |= NS_STATE_GRID_IS_ROW_MASONRY;
      }
    }
    if (isRowSubgrid) {
      bits |= NS_STATE_GRID_IS_ROW_SUBGRID;
    }
  }
  return bits;
}

void nsGridContainerFrame::Init(nsIContent* aContent, nsContainerFrame* aParent,
                                nsIFrame* aPrevInFlow) {
  nsContainerFrame::Init(aContent, aParent, aPrevInFlow);

  if (HasAnyStateBits(NS_FRAME_FONT_INFLATION_CONTAINER)) {
    AddStateBits(NS_FRAME_FONT_INFLATION_FLOW_ROOT);
  }

  nsFrameState bits = nsFrameState(0);
  if (MOZ_LIKELY(!aPrevInFlow)) {
    bits = ComputeSelfSubgridMasonryBits();
  } else {
    bits = aPrevInFlow->GetStateBits() &
           (NS_STATE_GRID_IS_ROW_MASONRY | NS_STATE_GRID_IS_COL_MASONRY |
            kIsSubgridBits | NS_STATE_GRID_HAS_COL_SUBGRID_ITEM |
            NS_STATE_GRID_HAS_ROW_SUBGRID_ITEM);
  }
  AddStateBits(bits);
}

void nsGridContainerFrame::DidSetComputedStyle(ComputedStyle* aOldStyle) {
  nsContainerFrame::DidSetComputedStyle(aOldStyle);

  if (!aOldStyle) {
    return;  // Init() already initialized the bits.
  }
  UpdateSubgridFrameState();
}

nscoord nsGridContainerFrame::IntrinsicISize(gfxContext* aRenderingContext,
                                             IntrinsicISizeType aType) {
  // Calculate the sum of column sizes under intrinsic sizing.
  // http://dev.w3.org/csswg/css-grid/#intrinsic-sizes
  NormalizeChildLists();
  GridReflowInput state(this, *aRenderingContext);
  InitImplicitNamedAreas(state.mGridStyle);  // XXX optimize

  // The min/sz/max sizes are the input to the "repeat-to-fill" algorithm:
  // https://drafts.csswg.org/css-grid/#auto-repeat
  // They're only used for auto-repeat so we skip computing them otherwise.
  RepeatTrackSizingInput repeatSizing(state.mWM);
  if (!IsColSubgrid() && state.mColFunctions.mHasRepeatAuto) {
    repeatSizing.InitFromStyle(eLogicalAxisInline, state.mWM,
                               state.mFrame->Style());
  }
  if ((!IsRowSubgrid() && state.mRowFunctions.mHasRepeatAuto &&
       !(state.mGridStyle->mGridAutoFlow & StyleGridAutoFlow::ROW)) ||
      IsMasonry(eLogicalAxisInline)) {
    // Only 'grid-auto-flow:column' can create new implicit columns, so that's
    // the only case where our block-size can affect the number of columns.
    // Masonry layout always depends on how many rows we have though.
    repeatSizing.InitFromStyle(eLogicalAxisBlock, state.mWM,
                               state.mFrame->Style());
  }

  Grid grid;
  if (MOZ_LIKELY(!IsSubgrid())) {
    grid.PlaceGridItems(state, repeatSizing);  // XXX optimize
  } else {
    auto* subgrid = GetProperty(Subgrid::Prop());
    state.mGridItems = subgrid->mGridItems.Clone();
    state.mAbsPosItems = subgrid->mAbsPosItems.Clone();
    grid.mGridColEnd = subgrid->mGridColEnd;
    grid.mGridRowEnd = subgrid->mGridRowEnd;
  }

  auto constraint = aType == IntrinsicISizeType::MinISize
                        ? SizingConstraint::MinContent
                        : SizingConstraint::MaxContent;
  if (IsMasonry(eLogicalAxisInline)) {
    ReflowOutput desiredSize(state.mWM);
    nsSize containerSize;
    LogicalRect contentArea(state.mWM);
    nsReflowStatus status;
    state.mRows.mSizes.SetLength(grid.mGridRowEnd);
    state.CalculateTrackSizesForAxis(eLogicalAxisInline, grid,
                                     NS_UNCONSTRAINEDSIZE, constraint);
    return MasonryLayout(state, contentArea, constraint, desiredSize, status,
                         nullptr, containerSize);
  }

  if (grid.mGridColEnd == 0) {
    return nscoord(0);
  }

  state.CalculateTrackSizesForAxis(eLogicalAxisInline, grid,
                                   NS_UNCONSTRAINEDSIZE, constraint);

  if (MOZ_LIKELY(!IsSubgrid())) {
    return state.mCols.SumOfGridTracksAndGaps();
  }
  const auto& last = state.mCols.mSizes.LastElement();
  return last.mPosition + last.mBase;
}

nscoord nsGridContainerFrame::GetMinISize(gfxContext* aRC) {
  auto* f = static_cast<nsGridContainerFrame*>(FirstContinuation());
  if (f != this) {
    return f->GetMinISize(aRC);
  }

  DISPLAY_MIN_INLINE_SIZE(this, mCachedMinISize);
  if (mCachedMinISize == NS_INTRINSIC_ISIZE_UNKNOWN) {
    Maybe<nscoord> containISize = ContainIntrinsicISize();
    mCachedMinISize = containISize
                          ? *containISize
                          : IntrinsicISize(aRC, IntrinsicISizeType::MinISize);
  }
  return mCachedMinISize;
}

nscoord nsGridContainerFrame::GetPrefISize(gfxContext* aRC) {
  auto* f = static_cast<nsGridContainerFrame*>(FirstContinuation());
  if (f != this) {
    return f->GetPrefISize(aRC);
  }

  DISPLAY_PREF_INLINE_SIZE(this, mCachedPrefISize);
  if (mCachedPrefISize == NS_INTRINSIC_ISIZE_UNKNOWN) {
    Maybe<nscoord> containISize = ContainIntrinsicISize();
    mCachedPrefISize = containISize
                           ? *containISize
                           : IntrinsicISize(aRC, IntrinsicISizeType::PrefISize);
  }
  return mCachedPrefISize;
}

void nsGridContainerFrame::MarkIntrinsicISizesDirty() {
  mCachedMinISize = NS_INTRINSIC_ISIZE_UNKNOWN;
  mCachedPrefISize = NS_INTRINSIC_ISIZE_UNKNOWN;
  for (auto& perAxisBaseline : mBaseline) {
    for (auto& baseline : perAxisBaseline) {
      baseline = NS_INTRINSIC_ISIZE_UNKNOWN;
    }
  }
  nsContainerFrame::MarkIntrinsicISizesDirty();
}

void nsGridContainerFrame::BuildDisplayList(nsDisplayListBuilder* aBuilder,
                                            const nsDisplayListSet& aLists) {
  DisplayBorderBackgroundOutline(aBuilder, aLists);
  if (GetPrevInFlow()) {
    DisplayOverflowContainers(aBuilder, aLists);
  }

  // Our children are all grid-level boxes, which behave the same as
  // inline-blocks in painting, so their borders/backgrounds all go on
  // the BlockBorderBackgrounds list.
  typedef CSSOrderAwareFrameIterator::OrderState OrderState;
  OrderState order =
      HasAnyStateBits(NS_STATE_GRID_NORMAL_FLOW_CHILDREN_IN_CSS_ORDER)
          ? OrderState::Ordered
          : OrderState::Unordered;
  CSSOrderAwareFrameIterator iter(
      this, FrameChildListID::Principal,
      CSSOrderAwareFrameIterator::ChildFilter::IncludeAll, order);
  const auto flags = DisplayFlagsForFlexOrGridItem();
  for (; !iter.AtEnd(); iter.Next()) {
    nsIFrame* child = *iter;
    BuildDisplayListForChild(aBuilder, child, aLists, flags);
  }
}

bool nsGridContainerFrame::DrainSelfOverflowList() {
  return DrainAndMergeSelfOverflowList();
}

void nsGridContainerFrame::AppendFrames(ChildListID aListID,
                                        nsFrameList&& aFrameList) {
  NoteNewChildren(aListID, aFrameList);
  nsContainerFrame::AppendFrames(aListID, std::move(aFrameList));
}

void nsGridContainerFrame::InsertFrames(
    ChildListID aListID, nsIFrame* aPrevFrame,
    const nsLineList::iterator* aPrevFrameLine, nsFrameList&& aFrameList) {
  NoteNewChildren(aListID, aFrameList);
  nsContainerFrame::InsertFrames(aListID, aPrevFrame, aPrevFrameLine,
                                 std::move(aFrameList));
}

void nsGridContainerFrame::RemoveFrame(DestroyContext& aContext,
                                       ChildListID aListID,
                                       nsIFrame* aOldFrame) {
  MOZ_ASSERT(aListID == FrameChildListID::Principal, "unexpected child list");

#ifdef DEBUG
  SetDidPushItemsBitIfNeeded(aListID, aOldFrame);
#endif

  nsContainerFrame::RemoveFrame(aContext, aListID, aOldFrame);
}

StyleAlignFlags nsGridContainerFrame::CSSAlignmentForAbsPosChild(
    const ReflowInput& aChildRI, LogicalAxis aLogicalAxis) const {
  MOZ_ASSERT(aChildRI.mFrame->IsAbsolutelyPositioned(),
             "This method should only be called for abspos children");

  StyleAlignFlags alignment =
      (aLogicalAxis == eLogicalAxisInline)
          ? aChildRI.mStylePosition->UsedJustifySelf(Style())._0
          : aChildRI.mStylePosition->UsedAlignSelf(Style())._0;

  // Extract and strip the flag bits
  StyleAlignFlags alignmentFlags = alignment & StyleAlignFlags::FLAG_BITS;
  alignment &= ~StyleAlignFlags::FLAG_BITS;

  if (alignment == StyleAlignFlags::NORMAL) {
    // "the 'normal' keyword behaves as 'start' on replaced
    // absolutely-positioned boxes, and behaves as 'stretch' on all other
    // absolutely-positioned boxes."
    // https://drafts.csswg.org/css-align/#align-abspos
    // https://drafts.csswg.org/css-align/#justify-abspos
    alignment = aChildRI.mFrame->IsReplaced() ? StyleAlignFlags::START
                                              : StyleAlignFlags::STRETCH;
  } else if (alignment == StyleAlignFlags::FLEX_START) {
    alignment = StyleAlignFlags::START;
  } else if (alignment == StyleAlignFlags::FLEX_END) {
    alignment = StyleAlignFlags::END;
  } else if (alignment == StyleAlignFlags::LEFT ||
             alignment == StyleAlignFlags::RIGHT) {
    if (aLogicalAxis == eLogicalAxisInline) {
      const bool isLeft = (alignment == StyleAlignFlags::LEFT);
      WritingMode wm = GetWritingMode();
      alignment = (isLeft == wm.IsBidiLTR()) ? StyleAlignFlags::START
                                             : StyleAlignFlags::END;
    } else {
      alignment = StyleAlignFlags::START;
    }
  } else if (alignment == StyleAlignFlags::BASELINE) {
    alignment = StyleAlignFlags::START;
  } else if (alignment == StyleAlignFlags::LAST_BASELINE) {
    alignment = StyleAlignFlags::END;
  }

  return (alignment | alignmentFlags);
}

nscoord nsGridContainerFrame::SynthesizeBaseline(
    const FindItemInGridOrderResult& aGridOrderItem, LogicalAxis aAxis,
    BaselineSharingGroup aGroup, const nsSize& aCBPhysicalSize, nscoord aCBSize,
    WritingMode aCBWM) {
  if (MOZ_UNLIKELY(!aGridOrderItem.mItem)) {
    // No item in this fragment - synthesize a baseline from our border-box.
    return ::SynthesizeBaselineFromBorderBox(aGroup, aCBWM, aAxis, aCBSize);
  }

  nsIFrame* child = aGridOrderItem.mItem->mFrame;
  nsGridContainerFrame* grid = do_QueryFrame(child);
  auto childWM = child->GetWritingMode();
  bool isOrthogonal = aCBWM.IsOrthogonalTo(childWM);
  const LogicalAxis childAxis = isOrthogonal ? GetOrthogonalAxis(aAxis) : aAxis;
  nscoord baseline;
  nscoord start;
  nscoord size;

  if (aAxis == eLogicalAxisBlock) {
    start = child->GetLogicalNormalPosition(aCBWM, aCBPhysicalSize).B(aCBWM);
    size = child->BSize(aCBWM);
    if (grid && aGridOrderItem.mIsInEdgeTrack) {
      baseline = isOrthogonal ? grid->GetIBaseline(aGroup)
                              : grid->GetBBaseline(aGroup);
    } else if (!isOrthogonal && aGridOrderItem.mIsInEdgeTrack) {
      // This assertion is mostly for documentation purposes; it must hold,
      // given the checks in our 'if' statements. (We know aAxis is
      // eLogicalAxisBlock, and isOrthogonal is false, which means childAxis
      // must be eLogicalAxisBlock). If instead we got here with a childAxis of
      // eLogicalAxisInline, then our call to
      // Baseline::SynthesizeBaselineFromBorderBox might incorrectly think
      // it makes sense to use a central baseline, in an axis where that
      // doesn't make sense.
      MOZ_ASSERT(childAxis == eLogicalAxisBlock, "unexpected childAxis");
      baseline = child
                     ->GetNaturalBaselineBOffset(childWM, aGroup,
                                                 BaselineExportContext::Other)
                     .valueOrFrom([aGroup, child, childWM]() {
                       return Baseline::SynthesizeBOffsetFromBorderBox(
                           child, childWM, aGroup);
                     });
    } else {
      baseline =
          ::SynthesizeBaselineFromBorderBox(aGroup, childWM, childAxis, size);
    }
  } else {
    start = child->GetLogicalNormalPosition(aCBWM, aCBPhysicalSize).I(aCBWM);
    size = child->ISize(aCBWM);
    if (grid && aGridOrderItem.mIsInEdgeTrack) {
      baseline = isOrthogonal ? grid->GetBBaseline(aGroup)
                              : grid->GetIBaseline(aGroup);
    } else if (isOrthogonal && aGridOrderItem.mIsInEdgeTrack) {
      baseline = child
                     ->GetNaturalBaselineBOffset(childWM, aGroup,
                                                 BaselineExportContext::Other)
                     .valueOrFrom([aGroup, childWM, childAxis, size]() {
                       return ::SynthesizeBaselineFromBorderBox(
                           aGroup, childWM, childAxis, size);
                     });
    } else {
      baseline =
          ::SynthesizeBaselineFromBorderBox(aGroup, childWM, childAxis, size);
    }
  }
  return aGroup == BaselineSharingGroup::First
             ? start + baseline
             : aCBSize - start - size + baseline;
}

void nsGridContainerFrame::CalculateBaselines(
    BaselineSet aBaselineSet, CSSOrderAwareFrameIterator* aIter,
    const nsTArray<GridItemInfo>* aGridItems, const Tracks& aTracks,
    uint32_t aFragmentStartTrack, uint32_t aFirstExcludedTrack, WritingMode aWM,
    const nsSize& aCBPhysicalSize, nscoord aCBBorderPaddingStart,
    nscoord aCBBorderPaddingEnd, nscoord aCBSize) {
  const auto axis = aTracks.mAxis;
  auto firstBaseline = aTracks.mBaseline[BaselineSharingGroup::First];
  if (!(aBaselineSet & BaselineSet::eFirst)) {
    mBaseline[axis][BaselineSharingGroup::First] =
        ::SynthesizeBaselineFromBorderBox(BaselineSharingGroup::First, aWM,
                                          axis, aCBSize);
  } else if (firstBaseline == NS_INTRINSIC_ISIZE_UNKNOWN) {
    FindItemInGridOrderResult gridOrderFirstItem = FindFirstItemInGridOrder(
        *aIter, *aGridItems,
        axis == eLogicalAxisBlock ? &GridArea::mRows : &GridArea::mCols,
        axis == eLogicalAxisBlock ? &GridArea::mCols : &GridArea::mRows,
        aFragmentStartTrack);
    mBaseline[axis][BaselineSharingGroup::First] = SynthesizeBaseline(
        gridOrderFirstItem, axis, BaselineSharingGroup::First, aCBPhysicalSize,
        aCBSize, aWM);
  } else {
    // We have a 'first baseline' group in the start track in this fragment.
    // Convert it from track to grid container border-box coordinates.
    MOZ_ASSERT(!aGridItems->IsEmpty());
    nscoord gapBeforeStartTrack =
        aFragmentStartTrack == 0
            ? aTracks.GridLineEdge(aFragmentStartTrack,
                                   GridLineSide::AfterGridGap)
            : nscoord(0);  // no content gap at start of fragment
    mBaseline[axis][BaselineSharingGroup::First] =
        aCBBorderPaddingStart + gapBeforeStartTrack + firstBaseline;
  }

  auto lastBaseline = aTracks.mBaseline[BaselineSharingGroup::Last];
  if (!(aBaselineSet & BaselineSet::eLast)) {
    mBaseline[axis][BaselineSharingGroup::Last] =
        ::SynthesizeBaselineFromBorderBox(BaselineSharingGroup::Last, aWM, axis,
                                          aCBSize);
  } else if (lastBaseline == NS_INTRINSIC_ISIZE_UNKNOWN) {
    // For finding items for the 'last baseline' we need to create a reverse
    // iterator ('aIter' is the forward iterator from the GridReflowInput).
    using Iter = ReverseCSSOrderAwareFrameIterator;
    auto orderState = aIter->ItemsAreAlreadyInOrder()
                          ? Iter::OrderState::Ordered
                          : Iter::OrderState::Unordered;
    Iter iter(this, FrameChildListID::Principal,
              Iter::ChildFilter::SkipPlaceholders, orderState);
    iter.SetItemCount(aGridItems->Length());
    FindItemInGridOrderResult gridOrderLastItem = FindLastItemInGridOrder(
        iter, *aGridItems,
        axis == eLogicalAxisBlock ? &GridArea::mRows : &GridArea::mCols,
        axis == eLogicalAxisBlock ? &GridArea::mCols : &GridArea::mRows,
        aFragmentStartTrack, aFirstExcludedTrack);
    mBaseline[axis][BaselineSharingGroup::Last] =
        SynthesizeBaseline(gridOrderLastItem, axis, BaselineSharingGroup::Last,
                           aCBPhysicalSize, aCBSize, aWM);
  } else {
    // We have a 'last baseline' group in the end track in this fragment.
    // Convert it from track to grid container border-box coordinates.
    MOZ_ASSERT(!aGridItems->IsEmpty());
    auto borderBoxStartToEndOfEndTrack =
        aCBBorderPaddingStart +
        aTracks.GridLineEdge(aFirstExcludedTrack, GridLineSide::BeforeGridGap) -
        aTracks.GridLineEdge(aFragmentStartTrack, GridLineSide::BeforeGridGap);
    mBaseline[axis][BaselineSharingGroup::Last] =
        (aCBSize - borderBoxStartToEndOfEndTrack) + lastBaseline;
  }
}

#ifdef DEBUG_FRAME_DUMP
nsresult nsGridContainerFrame::GetFrameName(nsAString& aResult) const {
  return MakeFrameName(u"GridContainer"_ns, aResult);
}

void nsGridContainerFrame::ExtraContainerFrameInfo(nsACString& aTo) const {
  if (const void* const subgrid = GetProperty(Subgrid::Prop())) {
    aTo += nsPrintfCString(" [subgrid=%p]", subgrid);
  }
}

#endif

/* static */ nsGridContainerFrame::FindItemInGridOrderResult
nsGridContainerFrame::FindFirstItemInGridOrder(
    CSSOrderAwareFrameIterator& aIter, const nsTArray<GridItemInfo>& aGridItems,
    LineRange GridArea::*aMajor, LineRange GridArea::*aMinor,
    uint32_t aFragmentStartTrack) {
  FindItemInGridOrderResult result = {nullptr, false};
  uint32_t minMajor = kTranslatedMaxLine + 1;
  uint32_t minMinor = kTranslatedMaxLine + 1;
  aIter.Reset();
  for (; !aIter.AtEnd(); aIter.Next()) {
    const GridItemInfo& item = aGridItems[aIter.ItemIndex()];
    if ((item.mArea.*aMajor).mEnd <= aFragmentStartTrack) {
      continue;  // item doesn't span any track in this fragment
    }
    uint32_t major = (item.mArea.*aMajor).mStart;
    uint32_t minor = (item.mArea.*aMinor).mStart;
    if (major < minMajor || (major == minMajor && minor < minMinor)) {
      minMajor = major;
      minMinor = minor;
      result.mItem = &item;
      result.mIsInEdgeTrack = major == 0U;
    }
  }
  return result;
}

/* static */ nsGridContainerFrame::FindItemInGridOrderResult
nsGridContainerFrame::FindLastItemInGridOrder(
    ReverseCSSOrderAwareFrameIterator& aIter,
    const nsTArray<GridItemInfo>& aGridItems, LineRange GridArea::*aMajor,
    LineRange GridArea::*aMinor, uint32_t aFragmentStartTrack,
    uint32_t aFirstExcludedTrack) {
  FindItemInGridOrderResult result = {nullptr, false};
  int32_t maxMajor = -1;
  int32_t maxMinor = -1;
  aIter.Reset();
  int32_t lastMajorTrack = int32_t(aFirstExcludedTrack) - 1;
  for (; !aIter.AtEnd(); aIter.Next()) {
    const GridItemInfo& item = aGridItems[aIter.ItemIndex()];
    // Subtract 1 from the end line to get the item's last track index.
    int32_t major = (item.mArea.*aMajor).mEnd - 1;
    // Currently, this method is only called with aFirstExcludedTrack ==
    // the first track in the next fragment, so we take the opportunity
    // to assert this item really belongs to this fragment.
    MOZ_ASSERT((item.mArea.*aMajor).mStart < aFirstExcludedTrack,
               "found an item that belongs to some later fragment");
    if (major < int32_t(aFragmentStartTrack)) {
      continue;  // item doesn't span any track in this fragment
    }
    int32_t minor = (item.mArea.*aMinor).mEnd - 1;
    MOZ_ASSERT(minor >= 0 && major >= 0, "grid item must have span >= 1");
    if (major > maxMajor || (major == maxMajor && minor > maxMinor)) {
      maxMajor = major;
      maxMinor = minor;
      result.mItem = &item;
      result.mIsInEdgeTrack = major == lastMajorTrack;
    }
  }
  return result;
}

nsGridContainerFrame::UsedTrackSizes* nsGridContainerFrame::GetUsedTrackSizes()
    const {
  return GetProperty(UsedTrackSizes::Prop());
}

void nsGridContainerFrame::StoreUsedTrackSizes(
    LogicalAxis aAxis, const nsTArray<TrackSize>& aSizes) {
  auto* uts = GetUsedTrackSizes();
  if (!uts) {
    uts = new UsedTrackSizes();
    SetProperty(UsedTrackSizes::Prop(), uts);
  }
  uts->mSizes[aAxis] = aSizes.Clone();
  uts->mCanResolveLineRangeSize[aAxis] = true;
  // XXX is resetting these bits necessary?
  for (auto& sz : uts->mSizes[aAxis]) {
    sz.mState &= ~(TrackSize::eFrozen | TrackSize::eSkipGrowUnlimited |
                   TrackSize::eInfinitelyGrowable);
  }
}

#ifdef DEBUG
void nsGridContainerFrame::SetInitialChildList(ChildListID aListID,
                                               nsFrameList&& aChildList) {
  ChildListIDs supportedLists = {FrameChildListID::Principal};
  // We don't handle the FrameChildListID::Backdrop frames in any way, but it
  // only contains a placeholder for ::backdrop which is OK to not reflow (for
  // now anyway).
  supportedLists += FrameChildListID::Backdrop;
  MOZ_ASSERT(supportedLists.contains(aListID), "unexpected child list");

  return nsContainerFrame::SetInitialChildList(aListID, std::move(aChildList));
}

void nsGridContainerFrame::TrackSize::DumpStateBits(StateBits aState) {
  printf("min:");
  if (aState & eAutoMinSizing) {
    printf("auto-min ");
  } else if (aState & eMinContentMinSizing) {
    printf("min-content ");
  } else if (aState & eMaxContentMinSizing) {
    printf("max-content ");
  }
  printf(" max:");
  if (aState & eAutoMaxSizing) {
    printf("auto ");
  } else if (aState & eMinContentMaxSizing) {
    printf("min-content ");
  } else if (aState & eMaxContentMaxSizing) {
    printf("max-content ");
  } else if (aState & eFlexMaxSizing) {
    printf("flex ");
  }
  if (aState & eFrozen) {
    printf("frozen ");
  }
  if (aState & eModified) {
    printf("modified ");
  }
  if (aState & eBreakBefore) {
    printf("break-before ");
  }
}

void nsGridContainerFrame::TrackSize::Dump() const {
  printf("mPosition=%d mBase=%d mLimit=%d ", mPosition, mBase, mLimit);
  DumpStateBits(mState);
}

#endif  // DEBUG

bool nsGridContainerFrame::GridItemShouldStretch(const nsIFrame* aChild,
                                                 LogicalAxis aAxis) const {
  MOZ_ASSERT(aChild->IsGridItem());

  if (aChild->IsGridContainerFrame()) {
    // The subgrid is always stretched in its subgridded dimensions.
    // https://drafts.csswg.org/css-grid/#subgrid-box-alignment
    const auto* gridContainer =
        static_cast<const nsGridContainerFrame*>(aChild);
    if (gridContainer->IsSubgrid(aAxis)) {
      return true;
    }
  }

  const auto wm = aChild->GetWritingMode();
  if (aChild->StyleMargin()->HasAuto(aAxis, wm)) {
    // Per https://drafts.csswg.org/css-grid/#auto-margins, any 'auto' margin in
    // an axis disables the alignment property in that axis.
    return false;
  }

  const auto cbwm = GetWritingMode();
  const bool isOrthogonal = wm.IsOrthogonalTo(cbwm);
  if (IsMasonry(isOrthogonal ? GetOrthogonalAxis(aAxis) : aAxis)) {
    // The child is in the container's masonry-axis.
    // AlignJustifyTracksInMasonryAxis will stretch it, so we don't report that
    // here.
    return false;
  }

  const auto* pos = aChild->StylePosition();
  const auto alignment = (aAxis == eLogicalAxisInline) == !isOrthogonal
                             ? pos->UsedJustifySelf(Style())._0
                             : pos->UsedAlignSelf(Style())._0;
  return alignment == StyleAlignFlags::NORMAL ||
         alignment == StyleAlignFlags::STRETCH;
}

bool nsGridContainerFrame::ShouldInhibitSubgridDueToIFC(
    const nsIFrame* aFrame) {
  // Just checking for things that make us establish an independent formatting
  // context (IFC) and hence prevent us from being a subgrid:
  // * Out-of-flow (e.g. abspos) frames also establish an IFC.  Note, our
  // NS_FRAME_OUT_OF_FLOW bit potentially isn't set yet, so we check our style.
  // * contain:layout and contain:paint each make us establish an IFC.
  const auto* display = aFrame->StyleDisplay();
  return display->IsAbsolutelyPositionedStyle() || display->IsContainLayout() ||
         display->IsContainPaint();
}

nsGridContainerFrame* nsGridContainerFrame::GetGridContainerFrame(
    nsIFrame* aFrame) {
  nsGridContainerFrame* gridFrame = nullptr;

  if (aFrame) {
    nsIFrame* inner = aFrame;
    if (MOZ_UNLIKELY(aFrame->IsFieldSetFrame())) {
      inner = static_cast<nsFieldSetFrame*>(aFrame)->GetInner();
    }
    // Since "Get" methods like GetInner and GetContentInsertionFrame can
    // return null, we check the return values before dereferencing. Our
    // calling pattern makes this unlikely, but we're being careful.
    nsIFrame* insertionFrame =
        inner ? inner->GetContentInsertionFrame() : nullptr;
    nsIFrame* possibleGridFrame = insertionFrame ? insertionFrame : aFrame;
    gridFrame = possibleGridFrame->IsGridContainerFrame()
                    ? static_cast<nsGridContainerFrame*>(possibleGridFrame)
                    : nullptr;
  }
  return gridFrame;
}

nsGridContainerFrame* nsGridContainerFrame::GetGridFrameWithComputedInfo(
    nsIFrame* aFrame) {
  nsGridContainerFrame* gridFrame = GetGridContainerFrame(aFrame);
  if (!gridFrame) {
    return nullptr;
  }

  auto HasComputedInfo = [](const nsGridContainerFrame& aFrame) -> bool {
    return aFrame.HasProperty(GridColTrackInfo()) &&
           aFrame.HasProperty(GridRowTrackInfo()) &&
           aFrame.HasProperty(GridColumnLineInfo()) &&
           aFrame.HasProperty(GridRowLineInfo());
  };

  if (HasComputedInfo(*gridFrame)) {
    return gridFrame;
  }

  // Trigger a reflow that generates additional grid property data.
  // Hold onto aFrame while we do this, in case reflow destroys it.
  AutoWeakFrame weakFrameRef(gridFrame);

  RefPtr<mozilla::PresShell> presShell = gridFrame->PresShell();
  gridFrame->AddStateBits(NS_STATE_GRID_COMPUTED_INFO);
  presShell->FrameNeedsReflow(gridFrame, IntrinsicDirty::None,
                              NS_FRAME_IS_DIRTY);
  presShell->FlushPendingNotifications(FlushType::Layout);

  // If the weakFrameRef is no longer valid, then we must bail out.
  if (!weakFrameRef.IsAlive()) {
    return nullptr;
  }

  // This can happen if for some reason we ended up not reflowing, like in print
  // preview under some circumstances.
  if (MOZ_UNLIKELY(!HasComputedInfo(*gridFrame))) {
    return nullptr;
  }

  return gridFrame;
}

// TODO: This is a rather dumb implementation of nsILineIterator, but it's
// better than our pre-existing behavior. Ideally, we should probably use the
// grid information to return a meaningful number of lines etc.
bool nsGridContainerFrame::IsLineIteratorFlowRTL() { return false; }

int32_t nsGridContainerFrame::GetNumLines() const {
  return mFrames.GetLength();
}

Result<nsILineIterator::LineInfo, nsresult> nsGridContainerFrame::GetLine(
    int32_t aLineNumber) {
  if (aLineNumber < 0 || aLineNumber >= GetNumLines()) {
    return Err(NS_ERROR_FAILURE);
  }
  LineInfo rv;
  nsIFrame* f = mFrames.FrameAt(aLineNumber);
  rv.mLineBounds = f->GetRect();
  rv.mFirstFrameOnLine = f;
  rv.mNumFramesOnLine = 1;
  return rv;
}

int32_t nsGridContainerFrame::FindLineContaining(nsIFrame* aFrame,
                                                 int32_t aStartLine) {
  const int32_t index = mFrames.IndexOf(aFrame);
  if (index < 0) {
    return -1;
  }
  if (index < aStartLine) {
    return -1;
  }
  return index;
}

NS_IMETHODIMP
nsGridContainerFrame::CheckLineOrder(int32_t aLine, bool* aIsReordered,
                                     nsIFrame** aFirstVisual,
                                     nsIFrame** aLastVisual) {
  *aIsReordered = false;
  *aFirstVisual = nullptr;
  *aLastVisual = nullptr;
  return NS_OK;
}

NS_IMETHODIMP
nsGridContainerFrame::FindFrameAt(int32_t aLineNumber, nsPoint aPos,
                                  nsIFrame** aFrameFound,
                                  bool* aPosIsBeforeFirstFrame,
                                  bool* aPosIsAfterLastFrame) {
  const auto wm = GetWritingMode();
  const LogicalPoint pos(wm, aPos, GetSize());

  *aFrameFound = nullptr;
  *aPosIsBeforeFirstFrame = true;
  *aPosIsAfterLastFrame = false;

  nsIFrame* f = mFrames.FrameAt(aLineNumber);
  if (!f) {
    return NS_OK;
  }

  auto rect = f->GetLogicalRect(wm, GetSize());
  *aFrameFound = f;
  *aPosIsBeforeFirstFrame = pos.I(wm) < rect.IStart(wm);
  *aPosIsAfterLastFrame = pos.I(wm) > rect.IEnd(wm);
  return NS_OK;
}