File: MCCASObjectV1.cpp

package info (click to toggle)
swiftlang 6.0.3-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,519,992 kB
  • sloc: cpp: 9,107,863; ansic: 2,040,022; asm: 1,135,751; python: 296,500; objc: 82,456; f90: 60,502; lisp: 34,951; pascal: 19,946; sh: 18,133; perl: 7,482; ml: 4,937; javascript: 4,117; makefile: 3,840; awk: 3,535; xml: 914; fortran: 619; cs: 573; ruby: 573
file content (4212 lines) | stat: -rw-r--r-- 151,336 bytes parent folder | download
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
//===- MC/MCCASObjectV1.cpp -----------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//

#include "llvm/MCCAS/MCCASObjectV1.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/BinaryFormat/MachO.h"
#include "llvm/CAS/CASID.h"
#include "llvm/CAS/ObjectStore.h"
#include "llvm/DebugInfo/DWARF/DWARFCompileUnit.h"
#include "llvm/DebugInfo/DWARF/DWARFContext.h"
#include "llvm/DebugInfo/DWARF/DWARFDataExtractor.h"
#include "llvm/DebugInfo/DWARF/DWARFDebugAbbrev.h"
#include "llvm/DebugInfo/DWARF/DWARFDebugLine.h"
#include "llvm/MC/MCAsmBackend.h"
#include "llvm/MC/MCContext.h"
#include "llvm/MC/MCObjectFileInfo.h"
#include "llvm/MCCAS/MCCASDebugV1.h"
#include "llvm/Support/BinaryStreamWriter.h"
#include "llvm/Support/Compression.h"
#include "llvm/Support/Endian.h"
#include "llvm/Support/EndianStream.h"
#include <memory>

// FIXME: Fix dependency here.
#include "llvm/CASObjectFormats/Encoding.h"
#include "llvm/Support/CommandLine.h"

using namespace llvm;
using namespace llvm::mccasformats;
using namespace llvm::mccasformats::v1;
using namespace llvm::mccasformats::reader;

using namespace llvm::casobjectformats::encoding;

constexpr StringLiteral MCAssemblerRef::KindString;
constexpr StringLiteral PaddingRef::KindString;

#define CASV1_SIMPLE_DATA_REF(RefName, IdentifierName)                         \
  constexpr StringLiteral RefName::KindString;
#define CASV1_SIMPLE_GROUP_REF(RefName, IdentifierName)                        \
  constexpr StringLiteral RefName::KindString;
#define MCFRAGMENT_NODE_REF(MCFragmentName, MCEnumName, MCEnumIdentifier)      \
  constexpr StringLiteral MCFragmentName##Ref::KindString;
#include "llvm/MCCAS/MCCASObjectV1.def"
constexpr StringLiteral DebugInfoSectionRef::KindString;

void MCSchema::anchor() {}
char MCSchema::ID = 0;

cl::opt<unsigned>
    MCDataMergeThreshold("mc-cas-data-merge-threshold",
                         cl::desc("MCDataFragment merge threshold"),
                         cl::init(1024));
cl::opt<bool>
    DebugInfoUnopt("debug-info-unopt",
                   cl::desc("Whether debug info storage should be optimized or "
                            "just stored as one cas block per section"),
                   cl::init(false));

enum RelEncodeLoc {
  Atom,
  Section,
  CompileUnit,
};

cl::opt<RelEncodeLoc> RelocLocation(
    "mc-cas-reloc-encode-in", cl::desc("Where to put relocation in encoding"),
    cl::values(clEnumVal(Atom, "In atom"), clEnumVal(Section, "In section"),
               clEnumVal(CompileUnit, "In compile unit")),
    cl::init(Atom));

class AbbrevSetWriter;

/// A DWARFObject implementation that can be used to dwarfdump CAS-formatted
/// debug info.
class InMemoryCASDWARFObject : public DWARFObject {
  ArrayRef<char> DebugAbbrevSection;
  DWARFSection DebugStringOffsetsSection;
  bool IsLittleEndian;
  uint8_t AddressSize;

public:
  InMemoryCASDWARFObject(ArrayRef<char> AbbrevContents,
                         ArrayRef<char> StringOffsetsContents,
                         bool IsLittleEndian, uint8_t AddressSize)
      : DebugAbbrevSection(AbbrevContents),
        DebugStringOffsetsSection({toStringRef(StringOffsetsContents)}),
        IsLittleEndian(IsLittleEndian), AddressSize(AddressSize) {}
  bool isLittleEndian() const override { return IsLittleEndian; }

  StringRef getAbbrevSection() const override {
    return toStringRef(DebugAbbrevSection);
  }

  const DWARFSection &getStrOffsetsSection() const override {
    return DebugStringOffsetsSection;
  }

  std::optional<RelocAddrEntry> find(const DWARFSection &Sec,
                                     uint64_t Pos) const override {
    return {};
  }

  /// Create a DwarfCompileUnit that represents the compile unit at \p CUOffset
  /// in the debug info section, and iterate over the individual DIEs to
  /// identify and separate the Forms that do not deduplicate in
  /// PartitionedDebugInfoSection::FormsToPartition and those that do
  /// deduplicate. Store both kinds of Forms in their own buffers per compile
  /// unit.
  Error partitionCUData(ArrayRef<char> DebugInfoData, uint64_t AbbrevOffset,
                        DWARFContext *Ctx, MCCASBuilder &Builder,
                        AbbrevSetWriter &AbbrevWriter, uint16_t DwarfVersion);
};

struct CUInfo {
  uint64_t CUSize;
  uint32_t AbbrevOffset;
  uint16_t DwarfVersion;
};
static Expected<CUInfo> getAndSetDebugAbbrevOffsetAndSkip(
    MutableArrayRef<char> CUData, support::endianness Endian,
    std::optional<uint32_t> NewOffset, uint8_t AddressSize);
Expected<cas::ObjectProxy>
MCSchema::createFromMCAssemblerImpl(MachOCASWriter &ObjectWriter,
                                    MCAssembler &Asm, const MCAsmLayout &Layout,
                                    raw_ostream *DebugOS) const {
  return MCAssemblerRef::create(*this, ObjectWriter, Asm, Layout, DebugOS);
}

Error MCSchema::serializeObjectFile(cas::ObjectProxy RootNode,
                                    raw_ostream &OS) const {
  if (!isRootNode(RootNode))
    return createStringError(inconvertibleErrorCode(), "invalid root node");
  auto Asm = MCAssemblerRef::get(*this, RootNode.getRef());
  if (!Asm)
    return Asm.takeError();

  return Asm->materialize(OS);
}

// Helper function to load the list of references inside an ObjectProxy.
SmallVector<cas::ObjectRef> loadReferences(const cas::ObjectProxy &Proxy) {
  SmallVector<cas::ObjectRef> Refs;
  if (auto E = Proxy.forEachReference([&](cas::ObjectRef ID) -> Error {
        Refs.push_back(ID);
        return Error::success();
      }))
    llvm_unreachable("Callback never returns an error");
  return Refs;
}

MCSchema::MCSchema(cas::ObjectStore &CAS) : MCSchema::RTTIExtends(CAS) {
  // Fill the cache immediately to preserve thread-safety.
  if (Error E = fillCache())
    report_fatal_error(std::move(E));
}

Error MCSchema::fillCache() {
  std::optional<cas::ObjectRef> RootKindID;
  const unsigned Version = 0; // Bump this to error on old object files.
  if (Error E = CAS.storeFromString(std::nullopt,
                                    "mc:v1:schema:" + Twine(Version).str())
                    .moveInto(RootKindID))
    return E;

  StringRef AllKindStrings[] = {
      PaddingRef::KindString,
      MCAssemblerRef::KindString,
      DebugInfoSectionRef::KindString,
#define CASV1_SIMPLE_DATA_REF(RefName, IdentifierName) RefName::KindString,
#define CASV1_SIMPLE_GROUP_REF(RefName, IdentifierName) RefName::KindString,
#define MCFRAGMENT_NODE_REF(MCFragmentName, MCEnumName, MCEnumIdentifier)      \
  MCFragmentName##Ref::KindString,
#include "llvm/MCCAS/MCCASObjectV1.def"
  };
  cas::ObjectRef Refs[] = {*RootKindID};
  SmallVector<cas::ObjectRef> IDs = {*RootKindID};
  for (StringRef KS : AllKindStrings) {
    auto ExpectedID = CAS.storeFromString(Refs, KS);
    if (!ExpectedID)
      return ExpectedID.takeError();
    IDs.push_back(*ExpectedID);
    KindStrings.push_back(std::make_pair(KindStrings.size(), KS));
    assert(KindStrings.size() < UCHAR_MAX &&
           "Ran out of bits for kind strings");
  }

  return CAS.storeFromString(IDs, "mc:v1:root").moveInto(RootNodeTypeID);
}

std::optional<StringRef>
MCSchema::getKindString(const cas::ObjectProxy &Node) const {
  assert(&Node.getCAS() == &CAS);
  StringRef Data = Node.getData();
  if (Data.empty())
    return std::nullopt;

  unsigned char ID = Data[0];
  for (auto &I : KindStrings)
    if (I.first == ID)
      return I.second;
  return std::nullopt;
}

bool MCSchema::isRootNode(const cas::ObjectProxy &Node) const {
  if (Node.getNumReferences() < 1)
    return false;
  return Node.getReference(0) == *RootNodeTypeID;
}

bool MCSchema::isNode(const cas::ObjectProxy &Node) const {
  // This is a very weak check!
  return bool(getKindString(Node));
}

Expected<MCObjectProxy::Builder>
MCObjectProxy::Builder::startRootNode(const MCSchema &Schema,
                                      StringRef KindString) {
  Builder B(Schema);
  B.Refs.push_back(Schema.getRootNodeTypeID());

  if (Error E = B.startNodeImpl(KindString))
    return std::move(E);
  return std::move(B);
}

Error MCObjectProxy::Builder::startNodeImpl(StringRef KindString) {
  std::optional<unsigned char> TypeID = Schema->getKindStringID(KindString);
  if (!TypeID)
    return createStringError(inconvertibleErrorCode(),
                             "invalid mc format kind string: " + KindString);
  Data.push_back(*TypeID);
  return Error::success();
}

Expected<MCObjectProxy::Builder>
MCObjectProxy::Builder::startNode(const MCSchema &Schema,
                                  StringRef KindString) {
  Builder B(Schema);
  if (Error E = B.startNodeImpl(KindString))
    return std::move(E);
  return std::move(B);
}

Expected<MCObjectProxy> MCObjectProxy::Builder::build() {
  return MCObjectProxy::get(*Schema, Schema->CAS.createProxy(Refs, Data));
}

StringRef MCObjectProxy::getKindString() const {
  std::optional<StringRef> KS = getSchema().getKindString(*this);
  assert(KS && "Expected valid kind string");
  return *KS;
}

std::optional<unsigned char>
MCSchema::getKindStringID(StringRef KindString) const {
  for (auto &I : KindStrings)
    if (I.second == KindString)
      return I.first;
  return std::nullopt;
}

Expected<MCObjectProxy> MCObjectProxy::get(const MCSchema &Schema,
                                           Expected<cas::ObjectProxy> Ref) {
  if (!Ref)
    return Ref.takeError();
  if (!Schema.isNode(*Ref))
    return createStringError(inconvertibleErrorCode(),
                             "invalid kind-string for node in mc-cas-schema");
  return MCObjectProxy(Schema, *Ref);
}

static Expected<StringRef> consumeDataOfSize(StringRef &Data, unsigned Size) {
  if (Data.size() < Size)
    return createStringError(inconvertibleErrorCode(),
                             "Requested data go beyond the buffer");

  auto Ret = Data.take_front(Size);
  Data = Data.drop_front(Size);

  return Ret;
}

#define CASV1_SIMPLE_DATA_REF(RefName, IdentifierName)                         \
  Expected<RefName> RefName::create(MCCASBuilder &MB, StringRef Name) {        \
    auto B = Builder::startNode(MB.Schema, KindString);                        \
    if (!B)                                                                    \
      return B.takeError();                                                    \
    B->Data.append(Name);                                                      \
    return get(B->build());                                                    \
  }                                                                            \
  Expected<RefName> RefName::get(Expected<MCObjectProxy> Ref) {                \
    auto Specific = SpecificRefT::getSpecific(std::move(Ref));                 \
    if (!Specific)                                                             \
      return Specific.takeError();                                             \
    return RefName(*Specific);                                                 \
  }
#include "llvm/MCCAS/MCCASObjectV1.def"

Expected<PaddingRef> PaddingRef::create(MCCASBuilder &MB, uint64_t Size) {
  // Fake a FT_Fill Fragment that is zero filled.
  Expected<Builder> B = Builder::startNode(MB.Schema, KindString);
  if (!B)
    return B.takeError();

  writeVBR8(Size, B->Data);
  return get(B->build());
}

Expected<uint64_t> PaddingRef::materialize(raw_ostream &OS) const {
  StringRef Remaining = getData();
  uint64_t Size;
  if (auto E = consumeVBR8(Remaining, Size))
    return std::move(E);
  OS.write_zeros(Size);
  return Size;
}

Expected<PaddingRef> PaddingRef::get(Expected<MCObjectProxy> Ref) {
  auto Specific = SpecificRefT::getSpecific(std::move(Ref));
  if (!Specific)
    return Specific.takeError();

  return PaddingRef(*Specific);
}

static void writeRelocations(ArrayRef<MachO::any_relocation_info> Rels,
                             SmallVectorImpl<char> &Data) {
  for (auto Rel : Rels) {
    // FIXME: Might be better just encode raw data?
    writeVBR8(Rel.r_word0, Data);
    writeVBR8(Rel.r_word1, Data);
  }
}

static Error decodeRelocations(MCCASReader &Reader, StringRef Data) {
  while (!Data.empty()) {
    MachO::any_relocation_info Rel;
    if (auto E = consumeVBR8(Data, Rel.r_word0))
      return E;
    if (auto E = consumeVBR8(Data, Rel.r_word1))
      return E;
    Reader.Relocations.back().push_back(Rel);
  }
  return Error::success();
}

Error MCObjectProxy::encodeReferences(ArrayRef<cas::ObjectRef> Refs,
                                      SmallVectorImpl<char> &Data,
                                      SmallVectorImpl<cas::ObjectRef> &IDs) {
  DenseMap<cas::ObjectRef, unsigned> RefMap;
  SmallVector<cas::ObjectRef> CompactRefs;
  for (const auto &ID : Refs) {
    auto I = RefMap.try_emplace(ID, CompactRefs.size());
    if (I.second)
      CompactRefs.push_back(ID);
  }

  // Guess the size of the encoding. Made an assumption that VBR8 encoding is
  // 1 byte (the minimal).
  size_t ReferenceSize = Refs.size() * sizeof(void *);
  size_t CompactSize = CompactRefs.size() * sizeof(void *) + Refs.size();
  if (ReferenceSize <= CompactSize) {
    writeVBR8(0, Data);
    IDs.append(Refs.begin(), Refs.end());
    return Error::success();
  }

  writeVBR8(Refs.size(), Data);
  for (const auto &ID : Refs) {
    auto Idx = RefMap.find(ID);
    assert(Idx != RefMap.end() && "ID must be in the map");
    writeVBR8(Idx->second, Data);
  }

  IDs.append(CompactRefs.begin(), CompactRefs.end());
  return Error::success();
}

Expected<SmallVector<cas::ObjectRef>>
MCObjectProxy::decodeReferences(const MCObjectProxy &Node,
                                StringRef &Remaining) {
  SmallVector<cas::ObjectRef> Refs = loadReferences(Node);

  unsigned Size = 0;
  if (auto E = consumeVBR8(Remaining, Size))
    return std::move(E);

  if (!Size)
    return Refs;

  SmallVector<cas::ObjectRef> CompactRefs;
  for (unsigned I = 0; I < Size; ++I) {
    unsigned Idx = 0;
    if (auto E = consumeVBR8(Remaining, Idx))
      return std::move(E);

    if (Idx >= Refs.size())
      return createStringError(inconvertibleErrorCode(), "invalid ref index");

    CompactRefs.push_back(Refs[Idx]);
  }

  return CompactRefs;
}

Expected<GroupRef> GroupRef::create(MCCASBuilder &MB,
                                    ArrayRef<cas::ObjectRef> Fragments) {
  Expected<Builder> B = Builder::startNode(MB.Schema, KindString);
  if (!B)
    return B.takeError();

  if (auto E = encodeReferences(Fragments, B->Data, B->Refs))
    return std::move(E);

  return get(B->build());
}

template <typename RefTy>
static Expected<SmallVector<RefTy, 0>> findRefs(MCCASReader &Reader,
                                                ArrayRef<cas::ObjectRef> Refs) {
  SmallVector<RefTy, 0> TopRefs;
  for (auto ID : Refs) {
    auto Node = Reader.getObjectProxy(ID);
    if (!Node)
      return Node.takeError();
    if (auto TopRef = RefTy::Cast(*Node))
      TopRefs.push_back(*TopRef);
  }
  if (TopRefs.size())
    return std::move(TopRefs);
  return createStringError(inconvertibleErrorCode(),
                           "failed to find reference");
}

template <typename RefTy>
static Expected<RefTy> findRef(MCCASReader &Reader,
                               ArrayRef<cas::ObjectRef> Refs) {
  auto FoundRefs = findRefs<RefTy>(Reader, Refs);
  if (!FoundRefs) return FoundRefs.takeError();
  return FoundRefs->front();
}

Expected<uint64_t> materializeAbbrevFromTagImpl(MCCASReader &Reader,
                                                DebugAbbrevSectionRef AbbrevRef,
                                                ArrayRef<cas::ObjectRef> Refs) {
  auto MaybeDebugInfoSectionRef = findRef<DebugInfoSectionRef>(Reader, Refs);
  if (!MaybeDebugInfoSectionRef)
    return MaybeDebugInfoSectionRef.takeError();
  SmallVector<cas::ObjectRef> DebugInfoSectionRefs =
      loadReferences(*MaybeDebugInfoSectionRef);

  auto TopRefs = findRefs<DIETopLevelRef>(Reader, DebugInfoSectionRefs);
  if (!TopRefs)
    return TopRefs.takeError();

  uint64_t Size = 0;
  uint64_t MaxDIEAbbrevCount = 1;
  for (auto TopRef : *TopRefs) {
    auto LoadedTopRef = loadDIETopLevel(TopRef);
    if (!LoadedTopRef)
      return LoadedTopRef.takeError();
    Size += reconstructAbbrevSection(
        Reader.OS, LoadedTopRef->AbbrevEntries, MaxDIEAbbrevCount,
        Reader.getEndian() == support::endianness::little,
        Reader.getAddressSize());
  }

  // FIXME: Currently, one DIELevelTopRef corresponds to one Compile Unit, but
  // multiple compile units could refer to the same abbreviation contribution,
  // such is the case with swift, where both Compile Units have the abbr_offset
  // of 0.
  // Dwarf 5: Section 7.5.3: The abbreviations for a given compilation
  // unit end with an entry consisting of a 0 byte for the abbreviation code.
  Reader.OS.write_zeros(1);
  Size += 1;

  auto MaybePaddingRef = findRef<PaddingRef>(Reader, loadReferences(AbbrevRef));
  if (!MaybePaddingRef)
    return MaybePaddingRef.takeError();

  Expected<uint64_t> MaybePaddingSize = MaybePaddingRef->materialize(Reader.OS);
  if (!MaybePaddingSize)
    return MaybePaddingSize.takeError();

  return Size + *MaybePaddingSize;
}

static Error materializeDebugInfoOpt(MCCASReader &Reader,
                                     ArrayRef<cas::ObjectRef> Refs,
                                     raw_ostream *SectionStream) {

  auto MaybeTopRefs = findRefs<DIETopLevelRef>(Reader, Refs);
  auto HeaderCallback = [&](StringRef HeaderData) {
    *SectionStream << HeaderData;
  };

  auto StartTagCallback = [&](dwarf::Tag, uint64_t AbbrevIdx) {
    encodeULEB128(decodeAbbrevIndexAsDwarfAbbrevIdx(AbbrevIdx), *SectionStream);
  };

  auto AttrCallback = [&](dwarf::Attribute, dwarf::Form Form,
                          StringRef FormData, bool) {
    if (Form == dwarf::Form::DW_FORM_ref4_cas ||
        Form == dwarf::Form::DW_FORM_strp_cas) {
      DataExtractor Extractor(FormData, Reader.isLittleEndian(),
                              Reader.getAddressSize());
      DataExtractor::Cursor Cursor(0);
      uint64_t Data64 = Extractor.getULEB128(Cursor);
      if (!Cursor)
        handleAllErrors(Cursor.takeError());
      uint32_t Data32 = Data64;
      assert(Data32 == Data64 && Extractor.eof(Cursor));
      SectionStream->write(reinterpret_cast<char *>(&Data32), sizeof(Data32));
    } else
      *SectionStream << FormData;
  };

  auto EndTagCallback = [&](bool HadChildren) {
    SectionStream->write_zeros(HadChildren);
  };

  if (!MaybeTopRefs)
    return MaybeTopRefs.takeError();

  SmallVector<StringRef, 0> TotAbbrevEntries;
  for (auto MaybeTopRef : *MaybeTopRefs) {

    if (auto E = visitDebugInfo(TotAbbrevEntries, std::move(MaybeTopRef),
                                HeaderCallback, StartTagCallback, AttrCallback,
                                EndTagCallback, Reader.isLittleEndian(),
                                Reader.getAddressSize()))
      return E;
  }
  return Error::success();
}

static Error materializeDebugInfoUnopt(MCCASReader &Reader,
                                       ArrayRef<cas::ObjectRef> Refs,
                                       SmallVectorImpl<char> &SectionContents) {

  for (auto Ref : Refs) {
    auto Node = Reader.getObjectProxy(Ref);
    if (!Node)
      return Node.takeError();
    if (auto F = DebugInfoUnoptRef::Cast(*Node)) {
      append_range(SectionContents, F->getData());
      continue;
    }
    if (auto F = PaddingRef::Cast(*Node)) {
      raw_svector_ostream OS(SectionContents);
      auto Size = F->materialize(OS);
      if (!Size)
        return Size.takeError();
      continue;
    }
    llvm_unreachable("Incorrect CAS Object in SectionContents");
  }
  return Error::success();
}

static Expected<uint64_t>
materializeDebugInfoFromTagImpl(MCCASReader &Reader,
                                DebugInfoSectionRef SectionRef) {
  SmallVector<cas::ObjectRef> Refs = loadReferences(SectionRef);
  SmallVector<char, 0> SectionContents;
  raw_svector_ostream SectionStream(SectionContents);
  auto Node = Reader.getObjectProxy(Refs[0]);
  if (!Node)
    return Node.takeError();
  if (auto UnoptRef = DebugInfoUnoptRef::Cast(*Node)) {
    if (Refs.size() > 2)
      return createStringError(
          inconvertibleErrorCode(),
          "If a DebugInfoUnoptRef is seen, there should be no more than 2 "
          "CAS objects under the DebugInfoSectionRef!");
    if (Error E = materializeDebugInfoUnopt(Reader, Refs, SectionContents))
      return std::move(E);
  } else {
    if (Error E = materializeDebugInfoOpt(Reader, Refs, &SectionStream))
      return std::move(E);
  }
  Reader.Relocations.emplace_back();
  if (auto E = decodeRelocations(Reader, SectionRef.getData()))
    return std::move(E);

  auto MaybePaddingRef = findRef<PaddingRef>(Reader, Refs);
  if (!MaybePaddingRef)
    return MaybePaddingRef.takeError();

  Expected<uint64_t> Size = MaybePaddingRef->materialize(SectionStream);
  if (!Size)
    return Size.takeError();

  Reader.OS << SectionContents;
  return SectionContents.size();
}

Expected<uint64_t> GroupRef::materialize(MCCASReader &Reader,
                                         raw_ostream *Stream) const {
  unsigned Size = 0;
  StringRef Remaining = getData();
  auto Refs = decodeReferences(*this, Remaining);
  if (!Refs)
    return Refs.takeError();

  for (auto ID : *Refs) {
    auto Node = Reader.getObjectProxy(ID);
    uint64_t FragSize = 0;
    if (!Node)
      return Node.takeError();
    if (auto AbbrevRef = DebugAbbrevSectionRef::Cast(*Node)) {
      auto AbbrevRefs = loadReferences(*Node);
      auto Obj = Reader.getObjectProxy(AbbrevRefs[0]);
      if (!Obj)
        return Obj.takeError();
      if (auto MaybeUnoptRef = DebugAbbrevUnoptRef::Cast(*Obj)) {
        if (Refs->size() > 2)
          return createStringError(
              inconvertibleErrorCode(),
              "If a DebugAbbrevUnoptRef is seen, there should be no more than "
              "2 CAS objects under the DebugAbbrevSectionRef!");
        auto FragmentSize =
            Reader.materializeDebugAbbrevUnopt(ArrayRef(AbbrevRefs));
        if (!FragmentSize)
          return FragmentSize.takeError();
        FragSize = *FragmentSize;
      } else {
        auto FragmentSize =
            materializeAbbrevFromTagImpl(Reader, *AbbrevRef, ArrayRef(*Refs));
        if (!FragmentSize)
          return FragmentSize.takeError();
        FragSize = *FragmentSize;
      }
      Size += FragSize;
      continue;
    }
    auto FragmentSize = Reader.materializeGroup(ID);
    if (!FragmentSize)
      return FragmentSize.takeError();
    Size += *FragmentSize;
  }

  if (!Remaining.empty())
    return createStringError(inconvertibleErrorCode(),
                             "Group should not have relocations");

  return Size;
}

Expected<SymbolTableRef>
SymbolTableRef::create(MCCASBuilder &MB, ArrayRef<cas::ObjectRef> Fragments) {
  Expected<Builder> B = Builder::startNode(MB.Schema, KindString);
  if (!B)
    return B.takeError();

  if (auto E = encodeReferences(Fragments, B->Data, B->Refs))
    return std::move(E);

  return get(B->build());
}

Expected<uint64_t> SymbolTableRef::materialize(MCCASReader &Reader,
                                               raw_ostream *Stream) const {
  unsigned Size = 0;
  StringRef Remaining = getData();
  auto Refs = decodeReferences(*this, Remaining);
  if (!Refs)
    return Refs.takeError();

  for (auto ID : *Refs) {
    auto FragmentSize = Reader.materializeGroup(ID);
    if (!FragmentSize)
      return FragmentSize.takeError();
    Size += *FragmentSize;
  }

  return Size;
}

Expected<SectionRef> SectionRef::create(MCCASBuilder &MB,
                                        ArrayRef<cas::ObjectRef> Fragments) {
  Expected<Builder> B = Builder::startNode(MB.Schema, KindString);
  if (!B)
    return B.takeError();

  if (auto E = encodeReferences(Fragments, B->Data, B->Refs))
    return std::move(E);

  writeRelocations(MB.getSectionRelocs(), B->Data);

  return get(B->build());
}

Expected<DebugInfoSectionRef>
DebugInfoSectionRef::create(MCCASBuilder &MB,
                            ArrayRef<cas::ObjectRef> ChildrenNode) {
  Expected<Builder> B = Builder::startNode(MB.Schema, KindString);
  if (!B)
    return B.takeError();

  append_range(B->Refs, ChildrenNode);
  writeRelocations(MB.getSectionRelocs(), B->Data);
  return get(B->build());
}

Expected<DebugAbbrevSectionRef>
DebugAbbrevSectionRef::create(MCCASBuilder &MB,
                              ArrayRef<cas::ObjectRef> Fragments) {
  Expected<Builder> B = Builder::startNode(MB.Schema, KindString);
  if (!B)
    return B.takeError();

  if (auto E = encodeReferences(Fragments, B->Data, B->Refs))
    return std::move(E);

  writeRelocations(MB.getSectionRelocs(), B->Data);
  return get(B->build());
}

Expected<DebugLineSectionRef>
DebugLineSectionRef::create(MCCASBuilder &MB,
                            ArrayRef<cas::ObjectRef> Fragments) {
  Expected<Builder> B = Builder::startNode(MB.Schema, KindString);
  if (!B)
    return B.takeError();

  if (auto E = encodeReferences(Fragments, B->Data, B->Refs))
    return std::move(E);

  writeRelocations(MB.getSectionRelocs(), B->Data);
  return get(B->build());
}

Expected<DebugStringSectionRef>
DebugStringSectionRef::create(MCCASBuilder &MB,
                              ArrayRef<cas::ObjectRef> Fragments) {
  Expected<Builder> B = Builder::startNode(MB.Schema, KindString);
  if (!B)
    return B.takeError();

  if (auto E = encodeReferences(Fragments, B->Data, B->Refs))
    return std::move(E);

  writeRelocations(MB.getSectionRelocs(), B->Data);
  return get(B->build());
}

// Creating a Debug Section CAS Object is the same for most sections, this
// function improve code reuse.
template <typename SectionTy>
static Error createGenericDebugSection(MCCASBuilder &MB,
                                       ArrayRef<cas::ObjectRef> Fragments,
                                       SmallVectorImpl<char> &Data,
                                       SmallVectorImpl<cas::ObjectRef> &Refs) {

  if (auto E = SectionTy::encodeReferences(Fragments, Data, Refs))
    return E;

  writeRelocations(MB.getSectionRelocs(), Data);
  return Error::success();
}

Expected<DebugStringOffsetsSectionRef>
DebugStringOffsetsSectionRef::create(MCCASBuilder &MB,
                                     ArrayRef<cas::ObjectRef> Fragments) {
  Expected<Builder> B = Builder::startNode(MB.Schema, KindString);
  if (!B)
    return B.takeError();

  if (auto E = createGenericDebugSection<DebugStringOffsetsSectionRef>(
          MB, Fragments, B->Data, B->Refs))
    return E;

  return get(B->build());
}

Expected<DebugLocSectionRef>
DebugLocSectionRef::create(MCCASBuilder &MB,
                           ArrayRef<cas::ObjectRef> Fragments) {
  Expected<Builder> B = Builder::startNode(MB.Schema, KindString);
  if (!B)
    return B.takeError();

  if (auto E = createGenericDebugSection<DebugLocSectionRef>(MB, Fragments,
                                                             B->Data, B->Refs))
    return E;

  return get(B->build());
}

Expected<DebugLoclistsSectionRef>
DebugLoclistsSectionRef::create(MCCASBuilder &MB,
                                ArrayRef<cas::ObjectRef> Fragments) {
  Expected<Builder> B = Builder::startNode(MB.Schema, KindString);
  if (!B)
    return B.takeError();

  if (auto E = createGenericDebugSection<DebugLoclistsSectionRef>(
          MB, Fragments, B->Data, B->Refs))
    return E;

  return get(B->build());
}

Expected<DebugRangesSectionRef>
DebugRangesSectionRef::create(MCCASBuilder &MB,
                              ArrayRef<cas::ObjectRef> Fragments) {
  Expected<Builder> B = Builder::startNode(MB.Schema, KindString);
  if (!B)
    return B.takeError();

  if (auto E = createGenericDebugSection<DebugRangesSectionRef>(
          MB, Fragments, B->Data, B->Refs))
    return E;

  return get(B->build());
}

Expected<DebugRangelistsSectionRef>
DebugRangelistsSectionRef::create(MCCASBuilder &MB,
                                  ArrayRef<cas::ObjectRef> Fragments) {
  Expected<Builder> B = Builder::startNode(MB.Schema, KindString);
  if (!B)
    return B.takeError();

  if (auto E = createGenericDebugSection<DebugRangelistsSectionRef>(
          MB, Fragments, B->Data, B->Refs))
    return E;

  return get(B->build());
}

Expected<DebugLineStrSectionRef>
DebugLineStrSectionRef::create(MCCASBuilder &MB,
                               ArrayRef<cas::ObjectRef> Fragments) {
  Expected<Builder> B = Builder::startNode(MB.Schema, KindString);
  if (!B)
    return B.takeError();

  if (auto E = createGenericDebugSection<DebugLineStrSectionRef>(
          MB, Fragments, B->Data, B->Refs))
    return E;

  return get(B->build());
}

Expected<DebugNamesSectionRef>
DebugNamesSectionRef::create(MCCASBuilder &MB,
                             ArrayRef<cas::ObjectRef> Fragments) {
  Expected<Builder> B = Builder::startNode(MB.Schema, KindString);
  if (!B)
    return B.takeError();

  if (auto E = createGenericDebugSection<DebugNamesSectionRef>(
          MB, Fragments, B->Data, B->Refs))
    return E;

  return get(B->build());
}

Expected<AppleNamesSectionRef>
AppleNamesSectionRef::create(MCCASBuilder &MB,
                             ArrayRef<cas::ObjectRef> Fragments) {
  Expected<Builder> B = Builder::startNode(MB.Schema, KindString);
  if (!B)
    return B.takeError();

  if (auto E = createGenericDebugSection<AppleNamesSectionRef>(
          MB, Fragments, B->Data, B->Refs))
    return E;

  return get(B->build());
}

Expected<AppleTypesSectionRef>
AppleTypesSectionRef::create(MCCASBuilder &MB,
                             ArrayRef<cas::ObjectRef> Fragments) {
  Expected<Builder> B = Builder::startNode(MB.Schema, KindString);
  if (!B)
    return B.takeError();

  if (auto E = createGenericDebugSection<AppleTypesSectionRef>(
          MB, Fragments, B->Data, B->Refs))
    return E;

  return get(B->build());
}

Expected<AppleNamespaceSectionRef>
AppleNamespaceSectionRef::create(MCCASBuilder &MB,
                                 ArrayRef<cas::ObjectRef> Fragments) {
  Expected<Builder> B = Builder::startNode(MB.Schema, KindString);
  if (!B)
    return B.takeError();

  if (auto E = createGenericDebugSection<AppleNamespaceSectionRef>(
          MB, Fragments, B->Data, B->Refs))
    return E;

  return get(B->build());
}

Expected<AppleObjCSectionRef>
AppleObjCSectionRef::create(MCCASBuilder &MB,
                                 ArrayRef<cas::ObjectRef> Fragments) {
  Expected<Builder> B = Builder::startNode(MB.Schema, KindString);
  if (!B)
    return B.takeError();

  if (auto E = createGenericDebugSection<AppleObjCSectionRef>(MB, Fragments,
                                                              B->Data, B->Refs))
    return E;

  return get(B->build());
}

Expected<uint64_t> SectionRef::materialize(MCCASReader &Reader,
                                           raw_ostream *Stream) const {
  // Start a new section for relocations.
  Reader.Relocations.emplace_back();
  SmallVector<char, 0> SectionContents;
  raw_svector_ostream SectionStream(SectionContents);

  unsigned Size = 0;
  StringRef Remaining = getData();
  auto Refs = decodeReferences(*this, Remaining);
  if (!Refs)
    return Refs.takeError();

  if (auto E = Reader.checkIfAddendRefExistsAndCopy(*Refs))
    return std::move(E);

  if (auto E = decodeRelocations(Reader, Remaining))
    return std::move(E);

  SmallVector<char, 0> FragmentContents;
  raw_svector_ostream FragmentStream(FragmentContents);

  for (auto ID : *Refs) {
    auto FragmentSize = Reader.materializeSection(ID, &FragmentStream);
    if (!FragmentSize)
      return FragmentSize.takeError();
    Size += *FragmentSize;
  }

  auto AddendSize =
      Reader.reconstructSection(SectionContents, FragmentContents);
  if (!AddendSize)
    return AddendSize.takeError();

  Size += *AddendSize;

  Reader.OS << SectionContents;
  // Reset the state for section materialization.
  Reader.AddendBufferIndex = 0;
  Reader.Addends.clear();

  return Size;
}

struct LineTablePrologue {
  uint64_t Length;
  uint16_t Version;
  uint32_t PrologueLength;
  uint64_t Offset;
  uint8_t OpcodeBase;
  dwarf::DwarfFormat Format;
};

static Expected<LineTablePrologue>
getLineTableLengthInfoAndVersion(DWARFDataExtractor &LineTableDataReader,
                                 uint64_t *OffsetPtr) {
  LineTablePrologue Prologue;
  Error Err = Error::success();
  // From DWARF 5 section 7.4:
  // In the 32-bit DWARF format, an initial length field [...] is an unsigned
  // 4-byte integer (which must be less than 0xfffffff0);
  auto Length = LineTableDataReader.getU32(OffsetPtr, &Err);
  if (Err)
    return std::move(Err);
  if (Length >= 0xfffffff0)
    return createStringError(inconvertibleErrorCode(),
                             "DWARF input is not in the 32-bit format");
  Prologue.Length = Length;
  Prologue.Format = llvm::dwarf::DWARF32;
  auto Version = LineTableDataReader.getU16(OffsetPtr, &Err);
  if (Err)
    return std::move(Err);
  if (Version >= 5) {
    // Dwarf 5 Section 6.2.4:
    // Line Table Header Format is now changed with an address_size and
    // segment_selector_size after the version. Parse both values from the
    // header.
    auto AddressSize = LineTableDataReader.getU8(OffsetPtr, &Err);
    if (Err)
      return std::move(Err);
    if (AddressSize != LineTableDataReader.getAddressSize())
      return createStringError(
          inconvertibleErrorCode(),
          "Address size in line table header is not the same as Address size "
          "for the target architecture, something went really wrong!");
    LineTableDataReader.getU8(OffsetPtr, &Err);
    if (Err)
      return std::move(Err);
  }

  Prologue.Version = Version;
  // Since we do not support 64 bit DWARF, the prologue length is 4 bytes in
  // size.
  auto PrologueLength = LineTableDataReader.getU32(OffsetPtr, &Err);
  if (Err)
    return std::move(Err);

  Prologue.PrologueLength = PrologueLength;
  Prologue.Offset = *OffsetPtr + PrologueLength;
  return Prologue;
}

static Expected<LineTablePrologue>
parseLineTableHeaderAndSkip(DWARFDataExtractor &LineTableDataReader) {
  uint64_t Offset = 0;
  uint64_t *OffsetPtr = &Offset;
  auto Prologue =
      getLineTableLengthInfoAndVersion(LineTableDataReader, OffsetPtr);
  if (!Prologue)
    return Prologue.takeError();
  Error Err = Error::success();
  // Parse Minimum instruction length.
  LineTableDataReader.getU8(OffsetPtr, &Err);
  // Parse Maximum Operands Per Instruction, if it exists.
  if (Prologue->Version >= 4)
    LineTableDataReader.getU8(OffsetPtr, &Err);
  // Parse DefaultIsStmt, LineBase, and LineRange.
  LineTableDataReader.getU8(OffsetPtr, &Err);
  LineTableDataReader.getU8(OffsetPtr, &Err);
  LineTableDataReader.getU8(OffsetPtr, &Err);
  // Parse OpcodeBase.
  Prologue->OpcodeBase = LineTableDataReader.getU8(OffsetPtr, &Err);
  if (Err)
    return std::move(Err);
  return Prologue;
}

static Error
handleExtendedOpcodesForLineTable(DWARFDataExtractor &LineTableDataReader,
                                  DWARFDataExtractor::Cursor &LineTableCursor,
                                  uint8_t SubOpcode, uint64_t Len,
                                  bool &IsEndSequence, bool &IsRelocation) {
  switch (SubOpcode) {
  case dwarf::DW_LNE_end_sequence: {
    // Takes no operand, it needs to be handled specially when materializing and
    // creating the CAS.
    IsEndSequence = true;
  } break;
  case dwarf::DW_LNE_set_address: {
    // Takes a relocatable address size, move cursor to the end of the
    // address.
    if (LineTableDataReader.getAddressSize() != Len - 1)
      return createStringError(inconvertibleErrorCode(),
                               "Address size mismatch");
    IsRelocation = true;
  } break;
  case dwarf::DW_LNE_define_file: {
    // Takes 4 arguments. The first is a null terminated string containing
    // a source file name. The second is an unsigned LEB128 number
    // representing the directory index of the directory in which the file
    // was found. The third is an unsigned LEB128 number representing the
    // time of last modification of the file. The fourth is an unsigned
    // LEB128 number representing the length in bytes of the file. Move
    // cursor to the end of the arguments.
    LineTableDataReader.getCStr(LineTableCursor);
    LineTableDataReader.getULEB128(LineTableCursor);
    LineTableDataReader.getULEB128(LineTableCursor);
    LineTableDataReader.getULEB128(LineTableCursor);
  } break;
  case dwarf::DW_LNE_set_discriminator:
    // Takes one operand, a ULEB128 value. Move cursor to end of operand.
    LineTableDataReader.getULEB128(LineTableCursor);
    break;
  default:
    llvm_unreachable("Unknown special opcode for line table");
    break;
  }
  return Error::success();
}

static Error
handleStandardOpcodesForLineTable(DWARFDataExtractor &LineTableDataReader,
                                  DWARFDataExtractor::Cursor &LineTableCursor,
                                  uint8_t Opcode, bool &IsSetFile,
                                  bool &IsRelocation) {
  switch (Opcode) {
  case dwarf::DW_LNS_copy:
  case dwarf::DW_LNS_negate_stmt:
  case dwarf::DW_LNS_set_basic_block:
  case dwarf::DW_LNS_const_add_pc:
  case dwarf::DW_LNS_set_prologue_end:
  case dwarf::DW_LNS_set_epilogue_begin:
    // Takes no arguments, move on
    break;
  case dwarf::DW_LNS_advance_pc:
  case dwarf::DW_LNS_advance_line:
  case dwarf::DW_LNS_set_column:
  case dwarf::DW_LNS_set_isa: {
    // Takes a single unsigned LEB128 operand, move cursor to the end of
    // operand.
    LineTableDataReader.getULEB128(LineTableCursor);
  } break;
  case dwarf::DW_LNS_set_file: {
    // Takes a single unsigned LEB128 operand, it needs to be handled specially
    // when materializing and creating the CAS.
    IsSetFile = true;
  } break;
  case dwarf::DW_LNS_fixed_advance_pc: {
    // Takes a single uhalf operand, move cursor to the end of operand.
    IsRelocation = true;
  } break;
  default:
    llvm_unreachable("Unknown standard opcode for line table");
    break;
  }
  return Error::success();
}

static Expected<std::pair<uint64_t, uint64_t>>
getOpcodeAndOperandSize(StringRef DistinctData, StringRef LineTableData,
                        uint64_t DistinctOffset, uint64_t LineTableOffset,
                        bool IsLittleEndian, uint8_t OpcodeBase,
                        uint8_t AddressSize) {
  DWARFDataExtractor LineTableDataReader(LineTableData, IsLittleEndian,
                                         AddressSize);
  DWARFDataExtractor DistinctDataReader(DistinctData, IsLittleEndian,
                                        AddressSize);
  DWARFDataExtractor::Cursor LineTableCursor(LineTableOffset);
  DWARFDataExtractor::Cursor DistinctCursor(DistinctOffset);

  auto Opcode = LineTableDataReader.getU8(LineTableCursor);
  if (Opcode == 0) {
    // Extended Opcodes always start with a zero opcode followed by
    // a uleb128 length so you can skip ones you don't know about
    uint64_t Len = LineTableDataReader.getULEB128(LineTableCursor);
    if (Len == 0)
      return createStringError(inconvertibleErrorCode(),
                               "0 Length for an extended opcode is wrong");

    uint8_t SubOpcode = LineTableDataReader.getU8(LineTableCursor);
    bool IsEndSequence = false;
    bool IsRelocation = false;
    auto Err = handleExtendedOpcodesForLineTable(
        LineTableDataReader, LineTableCursor, SubOpcode, Len, IsEndSequence,
        IsRelocation);
    if (Err)
      return std::move(Err);
    if (IsRelocation)
      DistinctDataReader.getRelocatedAddress(DistinctCursor);

    if (IsEndSequence) {
      // The SubOpcode is a DW_LNE_end_sequence, it takes no operand, but check
      // if this is the end of the line table and return.
      assert(LineTableData.size() == LineTableCursor.tell() &&
             "Malformed Line Table, data exists after a DW_LNE_end_sequence");
    }
  } else if (Opcode < OpcodeBase) {
    bool IsSetFile = false;
    bool IsRelocation = false;
    auto Err = handleStandardOpcodesForLineTable(
        LineTableDataReader, LineTableCursor, Opcode, IsSetFile, IsRelocation);
    if (Err)
      return std::move(Err);
    if (IsRelocation)
      DistinctDataReader.getRelocatedValue(DistinctCursor, 2);

    if (IsSetFile) {
      // The Opcode is DW_LNS_set_file, this means we need to get the file
      // number from the DistinctData, which is stored as a ULEB.
      DistinctDataReader.getULEB128(DistinctCursor);
    }
  } else {
    // Special Opcodes, do nothing.
  }

  if (!LineTableCursor)
    return LineTableCursor.takeError();
  if (!DistinctCursor)
    return DistinctCursor.takeError();

  return std::make_pair(LineTableCursor.tell() - LineTableOffset,
                        DistinctCursor.tell() - DistinctOffset);
}

static Expected<SmallVector<char, 0>>
materializeDebugLineSection(MCCASReader &Reader,
                            ArrayRef<cas::ObjectRef> Refs) {
  SmallVector<char, 0> DistinctData;
  uint64_t DistinctOffset = 0;
  uint8_t OpcodeBase = 0;
  SmallVector<char, 0> DebugLineSection;
  bool DistinctDebugLineRefSeen = false;
  bool DebugLineUnoptRefSeen = false;
  for (auto Ref : Refs) {
    auto Node = Reader.getObjectProxy(Ref);
    if (!Node)
      return Node.takeError();
    if (auto PadRef = PaddingRef::Cast(*Node)) {
      if (!DistinctDebugLineRefSeen && !DebugLineUnoptRefSeen)
        return createStringError(
            inconvertibleErrorCode(),
            "Line Table layout is incorrect, unexpected "
            "PaddingRef before a DistinctDebugLineRef or a DebugLineUnoptRef");
      raw_svector_ostream OS(DebugLineSection);
      auto Size = PadRef->materialize(OS);
      if (!Size)
        return Size.takeError();
      continue;
    }

    if (DebugLineUnoptRefSeen)
      return createStringError(
          inconvertibleErrorCode(),
          "DebugLineUnoptRef seen, only block allowed after is a PaddingRef");

    if (auto LineUnoptRef = DebugLineUnoptRef::Cast(*Node)) {

      DebugLineUnoptRefSeen = true;
      auto Data = LineUnoptRef->getData();
      DebugLineSection.append(Data.begin(), Data.end());
      continue;
    }
    if (auto DistinctRef = DistinctDebugLineRef::Cast(*Node)) {
      if (DistinctDebugLineRefSeen) {
        // This is the start of a new line table.
        DistinctOffset = 0;
        DistinctData.clear();
      }

      DistinctDebugLineRefSeen = true;
      auto Data = DistinctRef->getData();
      DistinctData.append(Data.begin(), Data.end());
      DWARFDataExtractor LineTableDataReader(Data, Reader.getEndian(),
                                             Reader.getAddressSize());
      auto Prologue = parseLineTableHeaderAndSkip(LineTableDataReader);
      if (!Prologue)
        return Prologue.takeError();
      DistinctOffset = Prologue->Offset;
      OpcodeBase = Prologue->OpcodeBase;
      // Copy line table prologue into final debug line section.
      DebugLineSection.append(DistinctData.begin(),
                              DistinctData.begin() + DistinctOffset);
      continue;
    }
    if (auto LineRef = DebugLineRef::Cast(*Node)) {

      if (!DistinctDebugLineRefSeen)
        return createStringError(inconvertibleErrorCode(),
                                 "Line Table layout is incorrect, unexpected "
                                 "DebugLineRef before a DistinctDebugLineRef");
      auto Data = LineRef->getData();
      uint64_t LineTableOffset = 0;
      while (LineTableOffset < Data.size()) {
        auto Sizes = getOpcodeAndOperandSize(
            toStringRef(DistinctData), Data, DistinctOffset, LineTableOffset,
            Reader.getEndian(), OpcodeBase, Reader.getAddressSize());
        if (!Sizes)
          return Sizes.takeError();
        // Copy opcode and operand, only in the case of DW_LNS_set_file, the
        // operand will be in the DistinctData.
        DebugLineSection.append(Data.begin() + LineTableOffset,
                                Data.begin() + LineTableOffset + Sizes->first);
        LineTableOffset += Sizes->first;
        if (Sizes->second) {
          DebugLineSection.append(DistinctData.begin() + DistinctOffset,
                                  DistinctData.begin() + DistinctOffset +
                                      Sizes->second);
          DistinctOffset += Sizes->second;
        }
      }
      continue;
    }
    return createStringError(inconvertibleErrorCode(),
                             "Unknown cas node type for debug line section");
  }
  return DebugLineSection;
}

Expected<uint64_t> DebugLineSectionRef::materialize(MCCASReader &Reader,
                                                    raw_ostream *Stream) const {
  // Start a new section for relocations.
  Reader.Relocations.emplace_back();

  StringRef Remaining = getData();
  auto Refs = decodeReferences(*this, Remaining);
  if (!Refs)
    return Refs.takeError();

  auto SectionContents = materializeDebugLineSection(Reader, *Refs);
  if (!SectionContents)
    return SectionContents.takeError();

  if (auto E = decodeRelocations(Reader, Remaining))
    return std::move(E);
  Reader.OS << *SectionContents;

  return SectionContents->size();
}

Expected<uint64_t>
DebugStringSectionRef::materialize(MCCASReader &Reader,
                                   raw_ostream *Stream) const {
  // Start a new section for relocations.
  Reader.Relocations.emplace_back();
  SmallVector<char, 0> SectionContents;
  raw_svector_ostream SectionStream(SectionContents);

  unsigned Size = 0;
  StringRef Remaining = getData();
  auto Refs = decodeReferences(*this, Remaining);
  if (!Refs)
    return Refs.takeError();

  for (auto ID : *Refs) {
    auto FragmentSize = Reader.materializeSection(ID, &SectionStream);
    if (!FragmentSize)
      return FragmentSize.takeError();
    Size += *FragmentSize;
  }

  if (auto E = decodeRelocations(Reader, Remaining))
    return std::move(E);
  Reader.OS << SectionContents;

  return Size;
}

// Materializing a Debug Section CAS Object is the same for most sections, this
// function improve code reuse.
template <typename SectionTy>
static Expected<uint64_t> materializeGenericDebugSection(MCCASReader &Reader,
                                                         StringRef Remaining,
                                                         SectionTy Section) {
  // Start a new section for relocations.
  Reader.Relocations.emplace_back();
  SmallVector<char, 0> SectionContents;
  raw_svector_ostream SectionStream(SectionContents);

  unsigned Size = 0;
  auto Refs = SectionTy::decodeReferences(Section, Remaining);
  if (!Refs)
    return Refs.takeError();

  for (auto ID : *Refs) {
    auto FragmentSize = Reader.materializeSection(ID, &SectionStream);
    if (!FragmentSize)
      return FragmentSize.takeError();
    Size += *FragmentSize;
  }

  if (auto E = decodeRelocations(Reader, Remaining))
    return std::move(E);
  Reader.OS << SectionContents;

  return Size;
}

Expected<uint64_t>
DebugStringOffsetsSectionRef::materialize(MCCASReader &Reader,
                                          raw_ostream *Stream) const {
  // Start a new section for relocations.
  Reader.Relocations.emplace_back();
  SmallVector<char, 0> SectionContents;
  raw_svector_ostream SectionStream(SectionContents);

  unsigned Size = 0;
  StringRef Remaining = getData();
  auto Refs = DebugStringOffsetsSectionRef::decodeReferences(*this, Remaining);
  if (!Refs)
    return Refs.takeError();

  for (auto ID : *Refs) {
    auto FragmentSize = Reader.materializeSection(ID, &SectionStream);
    if (!FragmentSize)
      return FragmentSize.takeError();
    Size += *FragmentSize;
  }

  if (auto E = decodeRelocations(Reader, Remaining))
    return std::move(E);

#if LLVM_ENABLE_ZLIB
  StringRef SectionStringRef = toStringRef(SectionContents);
  ArrayRef<uint8_t> BufRef = arrayRefFromStringRef(SectionStringRef);
  assert(BufRef.size() >= 8 &&
         "Debug String Offset buffer less than 8 bytes in size!");
  // The zlib decompress function needs to know the uncompressed size of the
  // buffer. That size is stored as a ULEB at the end of the buffer
  auto UncompressedSize = decodeULEB128(BufRef.data() + BufRef.size() - 8);
  BufRef = BufRef.drop_back(8);
  SmallVector<uint8_t> OutBuff;
  if (auto E = compression::zlib::decompress(BufRef, OutBuff, UncompressedSize))
    return E;
  SectionStringRef = toStringRef(OutBuff);
  Reader.OS << SectionStringRef;
  return UncompressedSize;
#endif

  Reader.OS << SectionContents;
  return Size;
}

Expected<uint64_t> DebugLocSectionRef::materialize(MCCASReader &Reader,
                                                   raw_ostream *Stream) const {
  StringRef Remaining = getData();
  return materializeGenericDebugSection<DebugLocSectionRef>(Reader, Remaining,
                                                            *this);
}

Expected<uint64_t>
DebugLoclistsSectionRef::materialize(MCCASReader &Reader,
                                     raw_ostream *Stream) const {
  StringRef Remaining = getData();
  return materializeGenericDebugSection<DebugLoclistsSectionRef>(
      Reader, Remaining, *this);
}

Expected<uint64_t>
DebugRangesSectionRef::materialize(MCCASReader &Reader,
                                   raw_ostream *Stream) const {
  StringRef Remaining = getData();
  return materializeGenericDebugSection<DebugRangesSectionRef>(
      Reader, Remaining, *this);
}

Expected<uint64_t>
DebugRangelistsSectionRef::materialize(MCCASReader &Reader,
                                       raw_ostream *Stream) const {
  StringRef Remaining = getData();
  return materializeGenericDebugSection<DebugRangelistsSectionRef>(
      Reader, Remaining, *this);
}

Expected<uint64_t>
DebugLineStrSectionRef::materialize(MCCASReader &Reader,
                                    raw_ostream *Stream) const {
  StringRef Remaining = getData();
  return materializeGenericDebugSection<DebugLineStrSectionRef>(
      Reader, Remaining, *this);
}

Expected<uint64_t>
DebugNamesSectionRef::materialize(MCCASReader &Reader,
                                  raw_ostream *Stream) const {
  StringRef Remaining = getData();
  return materializeGenericDebugSection<DebugNamesSectionRef>(Reader, Remaining,
                                                              *this);
}

Expected<uint64_t>
AppleNamesSectionRef::materialize(MCCASReader &Reader,
                                  raw_ostream *Stream) const {
  StringRef Remaining = getData();
  return materializeGenericDebugSection<AppleNamesSectionRef>(Reader, Remaining,
                                                              *this);
}

Expected<uint64_t>
AppleTypesSectionRef::materialize(MCCASReader &Reader,
                                  raw_ostream *Stream) const {
  StringRef Remaining = getData();
  return materializeGenericDebugSection<AppleTypesSectionRef>(Reader, Remaining,
                                                              *this);
}

Expected<uint64_t>
AppleNamespaceSectionRef::materialize(MCCASReader &Reader,
                                      raw_ostream *Stream) const {
  StringRef Remaining = getData();
  return materializeGenericDebugSection<AppleNamespaceSectionRef>(
      Reader, Remaining, *this);
}

Expected<uint64_t> AppleObjCSectionRef::materialize(MCCASReader &Reader,
                                                    raw_ostream *Stream) const {
  StringRef Remaining = getData();
  return materializeGenericDebugSection<AppleObjCSectionRef>(Reader, Remaining,
                                                             *this);
}

Expected<AtomRef> AtomRef::create(MCCASBuilder &MB,
                                  ArrayRef<cas::ObjectRef> Fragments) {
  Expected<Builder> B = Builder::startNode(MB.Schema, KindString);
  if (!B)
    return B.takeError();

  if (auto E = encodeReferences(Fragments, B->Data, B->Refs))
    return std::move(E);

  writeRelocations(MB.getAtomRelocs(), B->Data);

  return get(B->build());
}

Expected<uint64_t> AtomRef::materialize(MCCASReader &Reader,
                                        raw_ostream *Stream) const {
  unsigned Size = 0;
  StringRef Remaining = getData();
  auto Refs = decodeReferences(*this, Remaining);
  if (!Refs)
    return Refs.takeError();

  if (auto E = decodeRelocations(Reader, Remaining))
    return std::move(E);

  for (auto ID : *Refs) {
    auto FragmentSize = Reader.materializeAtom(ID, Stream);
    if (!FragmentSize)
      return FragmentSize.takeError();

    Size += *FragmentSize;
  }

  return Size;
}

Expected<MCAlignFragmentRef>
MCAlignFragmentRef::create(MCCASBuilder &MB, const MCAlignFragment &F,
                           unsigned FragmentSize,
                           ArrayRef<char> FragmentContents) {
  Expected<Builder> B = Builder::startNode(MB.Schema, KindString);
  if (!B)
    return B.takeError();

  uint64_t Count = FragmentSize / F.getValueSize();
  if (F.hasEmitNops()) {
    // Write 0 as size and use backend to emit nop.
    writeVBR8(0, B->Data);
    if (!MB.Asm.getBackend().writeNopData(MB.FragmentOS, Count,
                                          F.getSubtargetInfo()))
      report_fatal_error("unable to write nop sequence of " + Twine(Count) +
                         " bytes");
    B->Data.append(MB.FragmentData);
    return get(B->build());
  }
  writeVBR8(Count, B->Data);
  writeVBR8(F.getValue(), B->Data);
  writeVBR8(F.getValueSize(), B->Data);
  return get(B->build());
}

Expected<uint64_t> MCAlignFragmentRef::materialize(MCCASReader &Reader,
                                                   raw_ostream *Stream) const {
  uint64_t Count;
  auto Remaining = getData();
  auto Endian = Reader.getEndian();
  if (auto E = consumeVBR8(Remaining, Count))
    return std::move(E);

  // hasEmitNops.
  if (!Count) {
    *Stream << Remaining;
    return Remaining.size();
  }
  int64_t Value;
  unsigned ValueSize;
  if (auto E = consumeVBR8(Remaining, Value))
    return std::move(E);
  if (auto E = consumeVBR8(Remaining, ValueSize))
    return std::move(E);

  for (uint64_t I = 0; I != Count; ++I) {
    switch (ValueSize) {
    default:
      llvm_unreachable("Invalid size!");
    case 1:
      *Stream << char(Value);
      break;
    case 2:
      support::endian::write<uint16_t>(*Stream, Value, Endian);
      break;
    case 4:
      support::endian::write<uint32_t>(*Stream, Value, Endian);
      break;
    case 8:
      support::endian::write<uint64_t>(*Stream, Value, Endian);
      break;
    }
  }
  return Count * ValueSize;
}

Expected<MCBoundaryAlignFragmentRef> MCBoundaryAlignFragmentRef::create(
    MCCASBuilder &MB, const MCBoundaryAlignFragment &F, unsigned FragmentSize,
    ArrayRef<char> FragmentContents) {
  Expected<Builder> B = Builder::startNode(MB.Schema, KindString);
  if (!B)
    return B.takeError();
  if (!MB.Asm.getBackend().writeNopData(MB.FragmentOS, FragmentSize,
                                        F.getSubtargetInfo()))
    report_fatal_error("unable to write nop sequence of " +
                       Twine(FragmentSize) + " bytes");
  B->Data.append(MB.FragmentData);
  return get(B->build());
}

Expected<uint64_t>
MCBoundaryAlignFragmentRef::materialize(MCCASReader &Reader,
                                        raw_ostream *Stream) const {
  *Stream << getData();
  return getData().size();
}

Expected<MCCVInlineLineTableFragmentRef> MCCVInlineLineTableFragmentRef::create(
    MCCASBuilder &MB, const MCCVInlineLineTableFragment &F,
    unsigned FragmentSize, ArrayRef<char> FragmentContents) {
  Expected<Builder> B = Builder::startNode(MB.Schema, KindString);
  if (!B)
    return B.takeError();
  B->Data.append(F.getContents());
  return get(B->build());
}

Expected<uint64_t>
MCCVInlineLineTableFragmentRef::materialize(MCCASReader &Reader,
                                            raw_ostream *Stream) const {
  *Stream << getData();
  return getData().size();
}

Expected<MCDummyFragmentRef>
MCDummyFragmentRef::create(MCCASBuilder &MB, const MCDummyFragment &F,
                           unsigned FragmentSize,
                           ArrayRef<char> FragmentContents) {
  llvm_unreachable("Should not have been added");
}

Expected<uint64_t> MCDummyFragmentRef::materialize(MCCASReader &Reader,
                                                   raw_ostream *Stream) const {
  llvm_unreachable("Should not have been added");
}

Expected<MCFillFragmentRef>
MCFillFragmentRef::create(MCCASBuilder &MB, const MCFillFragment &F,
                          unsigned FragmentSize,
                          ArrayRef<char> FragmentContents) {
  Expected<Builder> B = Builder::startNode(MB.Schema, KindString);
  if (!B)
    return B.takeError();
  writeVBR8(FragmentSize, B->Data);
  writeVBR8(F.getValue(), B->Data);
  writeVBR8(F.getValueSize(), B->Data);
  return get(B->build());
}

Expected<uint64_t> MCFillFragmentRef::materialize(MCCASReader &Reader,
                                                  raw_ostream *Stream) const {
  StringRef Remaining = getData();
  uint64_t Size;
  uint64_t Value;
  unsigned ValueSize;
  if (auto E = consumeVBR8(Remaining, Size))
    return std::move(E);
  if (auto E = consumeVBR8(Remaining, Value))
    return std::move(E);
  if (auto E = consumeVBR8(Remaining, ValueSize))
    return std::move(E);

  // FIXME: Code duplication from writeFragment.
  const unsigned MaxChunkSize = 16;
  char Data[MaxChunkSize];
  for (unsigned I = 0; I != ValueSize; ++I) {
    unsigned Index =
        Reader.getEndian() == support::little ? I : (ValueSize - I - 1);
    Data[I] = uint8_t(Value >> (Index * 8));
  }
  for (unsigned I = ValueSize; I < MaxChunkSize; ++I)
    Data[I] = Data[I - ValueSize];

  const unsigned NumPerChunk = MaxChunkSize / ValueSize;
  const unsigned ChunkSize = ValueSize * NumPerChunk;

  StringRef Ref(Data, ChunkSize);
  for (uint64_t I = 0, E = Size / ChunkSize; I != E; ++I)
    *Stream << Ref;

  unsigned TrailingCount = Size % ChunkSize;
  if (TrailingCount)
    Stream->write(Data, TrailingCount);
  return Size;
}

Expected<MCLEBFragmentRef>
MCLEBFragmentRef::create(MCCASBuilder &MB, const MCLEBFragment &F,
                         unsigned FragmentSize,
                         ArrayRef<char> FragmentContents) {
  Expected<Builder> B = Builder::startNode(MB.Schema, KindString);
  if (!B)
    return B.takeError();
  B->Data.append(F.getContents());
  return get(B->build());
}

Expected<uint64_t> MCLEBFragmentRef::materialize(MCCASReader &Reader,
                                                 raw_ostream *Stream) const {
  *Stream << getData();
  return getData().size();
}

Expected<MCNopsFragmentRef>
MCNopsFragmentRef::create(MCCASBuilder &MB, const MCNopsFragment &F,
                          unsigned FragmentSize,
                          ArrayRef<char> FragmentContents) {
  Expected<Builder> B = Builder::startNode(MB.Schema, KindString);
  if (!B)
    return B.takeError();
  int64_t NumBytes = F.getNumBytes();
  int64_t ControlledNopLength = F.getControlledNopLength();
  int64_t MaximumNopLength =
      MB.Asm.getBackend().getMaximumNopSize(*F.getSubtargetInfo());
  if (ControlledNopLength > MaximumNopLength)
    ControlledNopLength = MaximumNopLength;
  if (!ControlledNopLength)
    ControlledNopLength = MaximumNopLength;
  while (NumBytes) {
    uint64_t NumBytesToEmit = (uint64_t)std::min(NumBytes, ControlledNopLength);
    assert(NumBytesToEmit && "try to emit empty NOP instruction");
    if (!MB.Asm.getBackend().writeNopData(MB.FragmentOS, NumBytesToEmit,
                                          F.getSubtargetInfo())) {
      report_fatal_error("unable to write nop sequence of the remaining " +
                         Twine(NumBytesToEmit) + " bytes");
      break;
    }
    NumBytes -= NumBytesToEmit;
  }
  B->Data.append(MB.FragmentData);
  return get(B->build());
}

Expected<uint64_t> MCNopsFragmentRef::materialize(MCCASReader &Reader,
                                                  raw_ostream *Stream) const {
  *Stream << getData();
  return getData().size();
}

Expected<MCOrgFragmentRef>
MCOrgFragmentRef::create(MCCASBuilder &MB, const MCOrgFragment &F,
                         unsigned FragmentSize,
                         ArrayRef<char> FragmentContents) {
  Expected<Builder> B = Builder::startNode(MB.Schema, KindString);
  if (!B)
    return B.takeError();
  writeVBR8(FragmentSize, B->Data);
  writeVBR8((char)F.getValue(), B->Data);
  return get(B->build());
}

Expected<uint64_t> MCOrgFragmentRef::materialize(MCCASReader &Reader,
                                                 raw_ostream *Stream) const {
  *Stream << getData();
  return getData().size();
}

Expected<MCSymbolIdFragmentRef>
MCSymbolIdFragmentRef::create(MCCASBuilder &MB, const MCSymbolIdFragment &F,
                              unsigned FragmentSize,
                              ArrayRef<char> FragmentContents) {
  Expected<Builder> B = Builder::startNode(MB.Schema, KindString);
  if (!B)
    return B.takeError();
  writeVBR8(F.getSymbol()->getIndex(), B->Data);
  return get(B->build());
}

Expected<uint64_t>
MCSymbolIdFragmentRef::materialize(MCCASReader &Reader,
                                   raw_ostream *Stream) const {
  *Stream << getData();
  return getData().size();
}

#define MCFRAGMENT_NODE_REF(MCFragmentName, MCEnumName, MCEnumIdentifier)      \
  Expected<MCFragmentName##Ref> MCFragmentName##Ref::create(                   \
      MCCASBuilder &MB, const MCFragmentName &F, unsigned FragmentSize,        \
      ArrayRef<char> FragmentContents) {                                       \
    Expected<Builder> B = Builder::startNode(MB.Schema, KindString);           \
    if (!B)                                                                    \
      return B.takeError();                                                    \
    MB.Asm.writeFragmentPadding(MB.FragmentOS, F, FragmentSize);               \
    ArrayRef<char> Contents = F.getContents();                                 \
    B->Data.append(MB.FragmentData);                                           \
    B->Data.append(FragmentContents.begin(), FragmentContents.end());          \
    assert(((MB.FragmentData.empty() && Contents.empty()) ||                   \
            (MB.FragmentData.size() + Contents.size() == FragmentSize)) &&     \
           "Size should match");                                               \
    return get(B->build());                                                    \
  }                                                                            \
  Expected<uint64_t> MCFragmentName##Ref::materialize(                         \
      MCCASReader &Reader, raw_ostream *Stream) const {                        \
    *Stream << getData();                                                      \
    return getData().size();                                                   \
  }
#define MCFRAGMENT_ENCODED_FRAGMENT_ONLY
#include "llvm/MCCAS/MCCASObjectV1.def"

Expected<MCAssemblerRef> MCAssemblerRef::get(Expected<MCObjectProxy> Ref) {
  auto Specific = SpecificRefT::getSpecific(std::move(Ref));
  if (!Specific)
    return Specific.takeError();

  return MCAssemblerRef(*Specific);
}

DwarfSectionsCache mccasformats::v1::getDwarfSections(MCAssembler &Asm) {
  return DwarfSectionsCache{
      Asm.getContext().getObjectFileInfo()->getDwarfInfoSection(),
      Asm.getContext().getObjectFileInfo()->getDwarfLineSection(),
      Asm.getContext().getObjectFileInfo()->getDwarfStrSection(),
      Asm.getContext().getObjectFileInfo()->getDwarfAbbrevSection(),
      Asm.getContext().getObjectFileInfo()->getDwarfStrOffSection(),
      Asm.getContext().getObjectFileInfo()->getDwarfLocSection(),
      Asm.getContext().getObjectFileInfo()->getDwarfLoclistsSection(),
      Asm.getContext().getObjectFileInfo()->getDwarfRangesSection(),
      Asm.getContext().getObjectFileInfo()->getDwarfRnglistsSection(),
      Asm.getContext().getObjectFileInfo()->getDwarfLineStrSection(),
      Asm.getContext().getObjectFileInfo()->getDwarfDebugNamesSection(),
      Asm.getContext().getObjectFileInfo()->getDwarfAccelNamesSection(),
      Asm.getContext().getObjectFileInfo()->getDwarfAccelTypesSection(),
      Asm.getContext().getObjectFileInfo()->getDwarfAccelNamespaceSection(),
      Asm.getContext().getObjectFileInfo()->getDwarfAccelObjCSection()};
}

Error MCCASBuilder::prepare() {
  ObjectWriter.resetBuffer();
  ObjectWriter.prepareObject(Asm, Layout);
  assert(ObjectWriter.getContent().empty() &&
         "prepare stage writes no content");
  return Error::success();
}

Error MCCASBuilder::buildMachOHeader() {
  ObjectWriter.resetBuffer();
  ObjectWriter.writeMachOHeader(Asm, Layout);
  auto Header = HeaderRef::create(*this, ObjectWriter.getContent());
  if (!Header)
    return Header.takeError();

  addNode(*Header);
  return Error::success();
}

Error MCCASBuilder::buildFragment(const MCFragment &F, unsigned Size,
                                  ArrayRef<char> FragmentContents) {
  FragmentData.clear();
  switch (F.getKind()) {
#define MCFRAGMENT_NODE_REF(MCFragmentName, MCEnumName, MCEnumIdentifier)      \
  case MCFragment::MCEnumName: {                                               \
    const MCFragmentName &SF = cast<MCFragmentName>(F);                        \
    auto FN = MCFragmentName##Ref::create(*this, SF, Size, FragmentContents);  \
    if (!FN)                                                                   \
      return FN.takeError();                                                   \
    addNode(*FN);                                                              \
    return Error::success();                                                   \
  }
#include "llvm/MCCAS/MCCASObjectV1.def"
  }
  llvm_unreachable("unknown fragment");
}

class MCDataFragmentMerger {
public:
  MCDataFragmentMerger(MCCASBuilder &Builder, const MCSection *Sec)
      : Builder(Builder) {}
  ~MCDataFragmentMerger() { assert(MergeCandidates.empty() && "Not flushed"); }

  Error tryMerge(const MCFragment &F, unsigned Size,
                 ArrayRef<char> FinalFragmentContents);
  Error flush() { return emitMergedFragments(); }
  SmallVector<SmallVector<char, 0>> MergeCandidatesContents;

private:
  Error emitMergedFragments();
  void reset();

  MCCASBuilder &Builder;
  unsigned CurrentSize = 0;
  std::vector<std::pair<const MCFragment *, unsigned>> MergeCandidates;
};

Error MCDataFragmentMerger::tryMerge(const MCFragment &F, unsigned Size,
                                     ArrayRef<char> FinalFragmentContents) {
  bool IsSameAtom = Builder.getCurrentAtom() == F.getAtom();
  bool Oversized = CurrentSize + Size > MCDataMergeThreshold;
  // TODO: Try merge align fragment?
  bool IsMergeableFragment =
      isa<MCEncodedFragment>(F) || isa<MCAlignFragment>(F);
  // If not the same atom, flush merge candidate and return false.
  if (!IsSameAtom || !IsMergeableFragment || Oversized) {
    if (auto E = emitMergedFragments())
      return E;

    // If it is a new Atom, start a new sub-section.
    if (!IsSameAtom) {
      if (auto E = Builder.finalizeAtom())
        return E;
      Builder.startAtom(F.getAtom());
    }
  }

  // Emit none Data segments.
  if (!IsMergeableFragment) {
    if (auto E = Builder.buildFragment(F, Size, FinalFragmentContents))
      return E;

    return Error::success();
  }

  // Add the fragment to the merge candidate.
  CurrentSize += Size;
  MergeCandidates.emplace_back(&F, Size);
  MergeCandidatesContents.push_back({});
  MergeCandidatesContents.back().append(FinalFragmentContents.begin(),
                                        FinalFragmentContents.end());

  return Error::success();
}

static Error writeAlignFragment(MCCASBuilder &Builder,
                                const MCAlignFragment &AF, raw_ostream &OS,
                                unsigned FragmentSize) {
  uint64_t Count = FragmentSize / AF.getValueSize();
  if (AF.hasEmitNops()) {
    if (!Builder.Asm.getBackend().writeNopData(OS, Count,
                                               AF.getSubtargetInfo()))
      return createStringError(inconvertibleErrorCode(),
                               "unable to write nop sequence of " +
                                   Twine(Count) + " bytes");
    return Error::success();
  }
  auto Endian = Builder.ObjectWriter.Target.isLittleEndian() ? support::little
                                                             : support::big;
  for (uint64_t I = 0; I != Count; ++I) {
    switch (AF.getValueSize()) {
    default:
      llvm_unreachable("Invalid size!");
    case 1:
      OS << char(AF.getValue());
      break;
    case 2:
      support::endian::write<uint16_t>(OS, AF.getValue(), Endian);
      break;
    case 4:
      support::endian::write<uint32_t>(OS, AF.getValue(), Endian);
      break;
    case 8:
      support::endian::write<uint64_t>(OS, AF.getValue(), Endian);
      break;
    }
  }
  return Error::success();
}

Error MCDataFragmentMerger::emitMergedFragments() {
  if (MergeCandidates.empty())
    return Error::success();

  // Use normal node to store the node.
  if (MergeCandidates.size() == 1) {
    auto E = Builder.buildFragment(*MergeCandidates.front().first,
                                   MergeCandidates.front().second,
                                   MergeCandidatesContents.back());
    reset();
    return E;
  }
  SmallString<8> FragmentData;
  raw_svector_ostream FragmentOS(FragmentData);
  for (const auto &[Candidate, CandidateContents] :
       llvm::zip(MergeCandidates, MergeCandidatesContents)) {
    switch (Candidate.first->getKind()) {
#define MCFRAGMENT_NODE_REF(MCFragmentName, MCEnumName, MCEnumIdentifier)      \
  case MCFragment::MCEnumName: {                                               \
    const MCFragmentName *SF = cast<MCFragmentName>(Candidate.first);          \
    Builder.Asm.writeFragmentPadding(FragmentOS, *SF, Candidate.second);       \
    FragmentData.append(CandidateContents);                                    \
    break;                                                                     \
  }
#define MCFRAGMENT_ENCODED_FRAGMENT_ONLY
#include "llvm/MCCAS/MCCASObjectV1.def"
    case MCFragment::FT_Align: {
      const MCAlignFragment *AF = cast<MCAlignFragment>(Candidate.first);
      if (auto E =
              writeAlignFragment(Builder, *AF, FragmentOS, Candidate.second))
        return E;
      break;
    }
    default:
      llvm_unreachable("other framgents should not be added");
    }
  }

  auto FN = MergedFragmentRef::create(Builder, FragmentData);
  if (!FN)
    return FN.takeError();
  Builder.addNode(*FN);

  // Clear state.
  reset();
  return Error::success();
}

void MCDataFragmentMerger::reset() {
  CurrentSize = 0;
  MergeCandidates.clear();
  MergeCandidatesContents.clear();
}

Error MCCASBuilder::createPaddingRef(const MCSection *Sec) {
  uint64_t Pad = ObjectWriter.getPaddingSize(Sec, Layout);
  auto Fill = PaddingRef::create(*this, Pad);
  if (!Fill)
    return Fill.takeError();
  addNode(*Fill);
  return Error::success();
}

Error MCCASBuilder::createStringSection(
    StringRef S, std::function<Error(StringRef)> CreateFn) {
  assert(S.endswith("\0") && "String sections are null terminated");
  if (DebugInfoUnopt)
    // Drop the null terminator at the end when not splitting the debug_string
    // section as it is always added when materializing.
    return CreateFn(S.drop_back());

  while (!S.empty()) {
    auto SplitSym = S.split('\0');
    if (auto E = CreateFn(SplitSym.first))
      return E;

    S = SplitSym.second;
  }
  return Error::success();
}

/// Reads and returns the length field of a dwarf header contained in Reader,
/// assuming Reader is positioned at the beginning of the header. The Reader's
/// state is advanced to the first byte after the header.
static Expected<size_t> getSizeFromDwarfHeader(DataExtractor &Extractor,
                                               DataExtractor::Cursor &Cursor) {
  // From DWARF 5 section 7.4:
  // In the 32-bit DWARF format, an initial length field [...] is an unsigned
  // 4-byte integer (which must be less than 0xfffffff0);
  uint32_t Word1 = Extractor.getU32(Cursor);
  if (!Cursor)
    return Cursor.takeError();

  // TODO: handle 64-bit DWARF format.
  if (Word1 >= 0xfffffff0)
    return createStringError(inconvertibleErrorCode(),
                             "DWARF input is not in the 32-bit format");

  return Word1;
}

/// Returns the Abbreviation Offset field of a Dwarf Compilation Unit (CU)
/// contained in CUData, as well as the total number of bytes taken by the CU.
/// Note: this is different from the length field of the Dwarf header, which
/// does not account for the header size.
static Expected<CUInfo> getAndSetDebugAbbrevOffsetAndSkip(
    MutableArrayRef<char> CUData, support::endianness Endian,
    std::optional<uint32_t> NewOffset, uint8_t AddressSize) {
  DataExtractor Extractor(toStringRef(CUData),
                          Endian == support::endianness::little, AddressSize);
  DataExtractor::Cursor Cursor(0);
  Expected<size_t> Size = getSizeFromDwarfHeader(Extractor, Cursor);
  if (!Size)
    return Size.takeError();

  size_t AfterSizeOffset = Cursor.tell();

  // 2-byte Dwarf version identifier.
  uint16_t DwarfVersion = Extractor.getU16(Cursor);
  if (!Cursor)
    return Cursor.takeError();

  if (DwarfVersion >= 5) {
    // From Dwarf 5 Section 7.5.1.1:
    // Compile Unit Header Format is now changed with unit_type and address_size
    // after the version. Parse both values from the header.
    uint8_t UnitType = Extractor.getU8(Cursor);
    if (!Cursor)
      return Cursor.takeError();
    if (UnitType != dwarf::DW_UT_compile)
      return createStringError(
          inconvertibleErrorCode(),
          "Unit type is not DW_UT_compile, and is incompatible with MCCAS!");
    uint8_t HeaderAddressSize = Extractor.getU8(Cursor);
    if (!Cursor)
      return Cursor.takeError();
    if (HeaderAddressSize != AddressSize)
      return createStringError(
          inconvertibleErrorCode(),
          "Address size in Compile Unit header is not the same as Address size "
          "for the target architecture, something went really wrong!");
  }

  // TODO: Handle Dwarf 64 format, which uses 8 bytes.
  size_t AbbrevPosition = Cursor.tell();
  uint32_t AbbrevOffset = Extractor.getU32(Cursor);
  if (!Cursor)
    return Cursor.takeError();

  if (NewOffset.has_value()) {
    // FIXME: safe but ugly cast. Similar to: llvm::arrayRefFromStringRef.
    auto UnsignedData = MutableArrayRef(
        reinterpret_cast<uint8_t *>(CUData.data()), CUData.size());
    BinaryStreamWriter Writer(UnsignedData, Endian);
    Writer.setOffset(AbbrevPosition);
    if (auto E = Writer.writeInteger(*NewOffset))
      return std::move(E);
  }

  Cursor.seek(AfterSizeOffset + *Size);
  return CUInfo{Cursor.tell(), AbbrevOffset, DwarfVersion};
}

/// Given a list of MCFragments, return a vector with the concatenation of their
/// data contents.
/// If any fragment is not an MCDataFragment, or the fragment is an
/// MCDwarfLineAddrFragment and the section containing that fragment is not a
/// debug_line section, an error is returned.
Expected<SmallVector<char, 0>> MCCASBuilder::mergeMCFragmentContents(
    const MCSection::FragmentListType &FragmentList, bool IsDebugLineSection) {
  SmallVector<char, 0> mergedData;
  for (const MCFragment &Fragment : FragmentList) {
    if (const auto *DataFragment = dyn_cast<MCDataFragment>(&Fragment))
      llvm::append_range(mergedData, DataFragment->getContents());
    else if (const auto *CompactEncodedInstFragment =
                 dyn_cast<MCCompactEncodedInstFragment>(&Fragment))
      llvm::append_range(mergedData, CompactEncodedInstFragment->getContents());
    else if (const auto *RelaxableFragment =
                 dyn_cast<MCRelaxableFragment>(&Fragment))
      llvm::append_range(mergedData, RelaxableFragment->getContents());
    else if (const auto *DwarfLineAddrFrag =
                 dyn_cast<MCDwarfLineAddrFragment>(&Fragment))
      if (IsDebugLineSection)
        llvm::append_range(mergedData, DwarfLineAddrFrag->getContents());
      else
        return createStringError(
            inconvertibleErrorCode(),
            "Invalid MCDwarfLineAddrFragment in a non debug line section");
    else if (const auto *DwarfCallFrameFragment =
                 dyn_cast<MCDwarfCallFrameFragment>(&Fragment))
      llvm::append_range(mergedData, DwarfCallFrameFragment->getContents());
    else if (const auto *CVDefRangeFragment =
                 dyn_cast<MCCVDefRangeFragment>(&Fragment))
      llvm::append_range(mergedData, CVDefRangeFragment->getContents());
    else if (const auto *PseudoProbeAddrFragment =
                 dyn_cast<MCPseudoProbeAddrFragment>(&Fragment))
      llvm::append_range(mergedData, PseudoProbeAddrFragment->getContents());
    else if (const auto *LEBFragment = dyn_cast<MCLEBFragment>(&Fragment))
      llvm::append_range(mergedData, LEBFragment->getContents());
    else if (const auto *CVInlineLineTableFragment =
                 dyn_cast<MCCVInlineLineTableFragment>(&Fragment))
      llvm::append_range(mergedData, CVInlineLineTableFragment->getContents());
    else if (const auto *AlignFragment = dyn_cast<MCAlignFragment>(&Fragment)) {
      auto FragmentSize = Asm.computeFragmentSize(Layout, Fragment);
      raw_svector_ostream OS(mergedData);
      if (auto E = writeAlignFragment(*this, *AlignFragment, OS, FragmentSize))
        return std::move(E);
    } else
      // All other fragment types can be considered empty, see
      // getFragmentContents() for all fragments that have contents.
      continue;
  }
  return mergedData;
}

Expected<MCCASBuilder::CUSplit>
MCCASBuilder::splitDebugInfoSectionData(MutableArrayRef<char> DebugInfoData) {
  CUSplit Split;
  // CU splitting loop.
  while (!DebugInfoData.empty()) {
    Expected<CUInfo> Info = getAndSetDebugAbbrevOffsetAndSkip(
        DebugInfoData, Asm.getBackend().Endian, /*NewOffset*/ 0,
        ObjectWriter.getAddressSize());
    if (!Info)
      return Info.takeError();
    Split.SplitCUData.push_back(DebugInfoData.take_front(Info->CUSize));
    Split.AbbrevOffsets.push_back(Info->AbbrevOffset);
    Split.DwarfVersions.push_back(Info->DwarfVersion);
    DebugInfoData = DebugInfoData.drop_front(Info->CUSize);
  }

  return Split;
}

Error MCCASBuilder::createDebugInfoSection() {
  startSection(DwarfSections.DebugInfo);

  if (DebugInfoUnopt) {
    Expected<SmallVector<char, 0>> DebugInfoData = mergeMCFragmentContents(
        DwarfSections.DebugInfo->getFragmentList(), true);
    if (!DebugInfoData)
      return DebugInfoData.takeError();
    auto DbgInfoUnoptRef =
        DebugInfoUnoptRef::create(*this, toStringRef(*DebugInfoData));
    if (!DbgInfoUnoptRef)
      return DbgInfoUnoptRef.takeError();
    addNode(*DbgInfoUnoptRef);
  } else {
    if (auto E = splitDebugInfoAndAbbrevSections())
      return E;
  }

  if (auto E = createPaddingRef(DwarfSections.DebugInfo))
    return E;
  return finalizeSection<DebugInfoSectionRef>();
}

Error MCCASBuilder::createDebugAbbrevSection() {
  startSection(DwarfSections.Abbrev);
  if (DebugInfoUnopt) {
    Expected<SmallVector<char, 0>> DebugAbbrevData =
        mergeMCFragmentContents(DwarfSections.Abbrev->getFragmentList(), true);
    if (!DebugAbbrevData)
      return DebugAbbrevData.takeError();
    auto DbgAbbrevUnoptRef =
        DebugAbbrevUnoptRef::create(*this, toStringRef(*DebugAbbrevData));
    if (!DbgAbbrevUnoptRef)
      return DbgAbbrevUnoptRef.takeError();
    addNode(*DbgAbbrevUnoptRef);
  }
  if (auto E = createPaddingRef(DwarfSections.Abbrev))
    return E;
  return finalizeSection<DebugAbbrevSectionRef>();
}

/// Helper class to create DIEDataRefs by keeping track of references to
/// children blocks.
struct DIEDataWriter : public DataWriter {

  /// Saves the main data stream and any children to a new DIEDataRef node.
  Expected<DIEDataRef> getCASNode(MCCASBuilder &CASBuilder) {
    auto Ref = DIEDataRef::create(CASBuilder, toStringRef(Data));
    return Ref;
  }
};

/// Helper class to create DIEDistinctDataRefs.
/// These nodes contain raw data that is not expected to deduplicate. This data
/// is described by some DIEAbbrevRef block.
struct DistinctDataWriter : public DataWriter {
  Expected<DIEDistinctDataRef> getCASNode(MCCASBuilder &CASBuilder) {
#if LLVM_ENABLE_ZLIB
    SmallVector<uint8_t> CompressedBuff;
    compression::zlib::compress(arrayRefFromStringRef(toStringRef(Data)),
                                CompressedBuff);
    // Reserve 8 bytes for ULEB to store the size of the uncompressed data.
    CompressedBuff.append(8, 0);
    encodeULEB128(Data.size(), CompressedBuff.end() - 8, 8 /*Pad to*/);
    return DIEDistinctDataRef::create(CASBuilder, toStringRef(CompressedBuff));
#else
    return DIEDistinctDataRef::create(CASBuilder, toStringRef(Data));
#endif
  }
};

/// Helper class to create DIEAbbrevSetRefs and DIEAbbrevRefs.
/// A DIEAbbrevSetRef has no data, only references to DIEAbbrevRefs.
/// A DIEAbbrevRef has no references, and its data follow the format of a DWARF
/// abbreviation entry exactly.
class AbbrevSetWriter : public AbbrevEntryWriter {
  DenseMap<cas::ObjectRef, unsigned> Children;
  uint32_t PrevSize = 0;

public:
  Expected<unsigned> createAbbrevEntry(DWARFDie DIE, MCCASBuilder &CASBuilder) {
    writeAbbrevEntry(DIE);
    auto MaybeAbbrev = DIEAbbrevRef::create(CASBuilder, toStringRef(Data));
    if (!MaybeAbbrev)
      return MaybeAbbrev.takeError();
    Data.clear();

    // Assign the smallest possible index to the new Abbrev.
    auto [it, inserted] =
        Children.try_emplace(MaybeAbbrev->getRef(), Children.size());
    return it->getSecond();
  }

  /// Creates a DIEAbbrevSetRef with all the DIEAbbrevRefs created so far.
  Expected<DIEAbbrevSetRef> endAbbrevSet(MCCASBuilder &CASBuilder) {
    if (Children.empty())
      return createStringError(inconvertibleErrorCode(),
                               "Abbrev Set cannot be empty");

    // Initialize the vector with copies of an arbitrary element, because we
    // need to assign elements in a random order and ObjectRefs can't be
    // default constructed.
    SmallVector<cas::ObjectRef, 0> ChildrenArray(Children.size() - PrevSize,
                                                 Children.begin()->getFirst());

    // Order the DIEAbbrevRefs based on their creation order.
    for (auto [Obj, Idx] : Children)
      if ((Idx + 1) > PrevSize)
        ChildrenArray[Idx - PrevSize] = Obj;
    auto DIEAbbrevRef = DIEAbbrevSetRef::create(CASBuilder, ChildrenArray);
    ChildrenArray.clear();
    PrevSize = Children.size();
    return DIEAbbrevRef;
  }
};

/// Helper class to convert DIEs into CAS objects.
struct DIEToCASConverter {
  DIEToCASConverter(ArrayRef<char> DebugInfoData, MCCASBuilder &CASBuilder,
                    bool IsLittleEndian, uint8_t AddressSize)
      : DebugInfoData(DebugInfoData), CASBuilder(CASBuilder),
        IsLittleEndian(IsLittleEndian), AddressSize(AddressSize) {}

  /// Converts a DIE into three types of CAS objects:
  /// 1. A tree of DIEDataRefs, containing data expected to deduplicate.
  /// 2. A single DIEAbbrevSetRef, containing all the abbreviations used by the
  /// DIE as DIEAbbrevRef objects.
  /// 3. A single DIEDistinctDataRef, containing data that is not expected to
  /// deduplicate.
  /// These nodes are wrapped into a DIETopLevelRef for convenience.
  Expected<DIETopLevelRef> convert(DWARFDie DIE, ArrayRef<char> HeaderData,
                                   AbbrevSetWriter &AbbrevWriter);

private:
  ArrayRef<char> DebugInfoData;
  MCCASBuilder &CASBuilder;
  bool IsLittleEndian;
  uint8_t AddressSize;

  struct ParentAndChildDIE {
    DWARFDie Parent;
    bool ParentAlreadyWritten;
    DIEDataWriter &Writer;
    std::optional<DWARFDie> Child;
  };

  Error
  convertImpl(DWARFDie DIE, DistinctDataWriter &DistinctWriter,
              AbbrevSetWriter &AbbrevWriter,
              SmallVectorImpl<std::unique_ptr<DIEDataWriter>> &DIEWriters);
};

Error InMemoryCASDWARFObject::partitionCUData(ArrayRef<char> DebugInfoData,
                                              uint64_t AbbrevOffset,
                                              DWARFContext *Ctx,
                                              MCCASBuilder &Builder,
                                              AbbrevSetWriter &AbbrevWriter,
                                              uint16_t DwarfVersion) {
  StringRef AbbrevSectionContribution =
      getAbbrevSection().drop_front(AbbrevOffset);
  DataExtractor Data(AbbrevSectionContribution, isLittleEndian(),
                     Builder.ObjectWriter.getAddressSize());
  DWARFDebugAbbrev Abbrev(Data);
  uint64_t OffsetPtr = 0;
  DWARFUnitHeader Header;
  DWARFSection Section = {toStringRef(DebugInfoData), 0 /*Address*/};
  Header.extract(*Ctx,
                 DWARFDataExtractor(*this, Section, isLittleEndian(),
                                    Builder.ObjectWriter.getAddressSize()),
                 &OffsetPtr, DWARFSectionKind::DW_SECT_INFO);

  DWARFUnitVector UV;
  DWARFCompileUnit DCU(*Ctx, Section, Header, &Abbrev, &getRangesSection(),
                       &getLocSection(), getStrSection(),
                       getStrOffsetsSection(), &getAddrSection(),
                       getLocSection(), isLittleEndian(), false, UV);

  DWARFDie CUDie = DCU.getUnitDIE(false);
  assert(CUDie);
  ArrayRef<char> HeaderData;
  if (DwarfVersion >= 5) {
    // Copy 12 bytes which represents the 32-bit DWARF Header for DWARF5.
    if (DebugInfoData.size() < Dwarf5HeaderSize32Bit)
      return createStringError(inconvertibleErrorCode(),
                               "DebugInfoData is too small, it doesn't even "
                               "contain a 32-bit DWARF5 Header");

    HeaderData = DebugInfoData.take_front(Dwarf5HeaderSize32Bit);
  } else {
    // Copy 11 bytes which represents the 32-bit DWARF Header for DWARF4.
    if (DebugInfoData.size() < Dwarf4HeaderSize32Bit)
      return createStringError(inconvertibleErrorCode(),
                               "DebugInfoData is too small, it doesn't even "
                               "contain a 32-bit DWARF4 Header");

    HeaderData = DebugInfoData.take_front(Dwarf4HeaderSize32Bit);
  }
  Expected<DIETopLevelRef> Converted =
      DIEToCASConverter(DebugInfoData, Builder, IsLittleEndian, AddressSize)
          .convert(CUDie, HeaderData, AbbrevWriter);
  if (!Converted)
    return Converted.takeError();
  Builder.addNode(*Converted);
  return Error::success();
}

Error MCCASBuilder::splitDebugInfoAndAbbrevSections() {
  if (!DwarfSections.DebugInfo)
    return Error::success();

  const MCSection::FragmentListType &FragmentList =
      DwarfSections.DebugInfo->getFragmentList();
  Expected<SmallVector<char, 0>> DebugInfoData =
      mergeMCFragmentContents(FragmentList);
  if (!DebugInfoData)
    return DebugInfoData.takeError();

  Expected<CUSplit> SplitInfo = splitDebugInfoSectionData(*DebugInfoData);
  if (!SplitInfo)
    return SplitInfo.takeError();

  const MCSection::FragmentListType &AbbrevFragmentList =
      DwarfSections.Abbrev->getFragmentList();

  Expected<SmallVector<char, 0>> FullAbbrevData =
      mergeMCFragmentContents(AbbrevFragmentList);

  if (!FullAbbrevData)
    return FullAbbrevData.takeError();

  const MCSection::FragmentListType &StringOffsetsFragmentList =
      DwarfSections.StrOffsets->getFragmentList();

  Expected<SmallVector<char, 0>> FullStringOffsetsData =
      mergeMCFragmentContents(StringOffsetsFragmentList);

  if (!FullStringOffsetsData)
    return FullStringOffsetsData.takeError();

  InMemoryCASDWARFObject CASObj(*FullAbbrevData, *FullStringOffsetsData,
                                Asm.getBackend().Endian ==
                                    support::endianness::little,
                                ObjectWriter.getAddressSize());
  auto DWARFObj = std::make_unique<InMemoryCASDWARFObject>(CASObj);
  auto DWARFContextHolder = std::make_unique<DWARFContext>(std::move(DWARFObj));
  auto *DWARFCtx = DWARFContextHolder.get();

  AbbrevSetWriter AbbrevWriter;
  for (auto [CUData, AbbrevOffset, DwarfVersion] :
       llvm::zip(SplitInfo->SplitCUData, SplitInfo->AbbrevOffsets,
                 SplitInfo->DwarfVersions)) {
    if (auto E = CASObj.partitionCUData(CUData, AbbrevOffset, DWARFCtx, *this,
                                        AbbrevWriter, DwarfVersion))
      return E;
  }
  return Error::success();
}

inline void copyData(SmallVector<char, 0> &Data, StringRef DebugLineStrRef,
                     uint64_t &CurrOffset, DWARFDataExtractor::Cursor &Cursor) {
  Data.append(DebugLineStrRef.data() + CurrOffset,
              DebugLineStrRef.data() + Cursor.tell());
  CurrOffset = Cursor.tell();
}

Expected<uint64_t>
MCCASBuilder::createOptimizedLineSection(StringRef DebugLineStrRef) {
  DWARFDataExtractor LineTableDataReader(
      DebugLineStrRef, Asm.getBackend().Endian, ObjectWriter.getAddressSize());
  auto Prologue = parseLineTableHeaderAndSkip(LineTableDataReader);
  if (!Prologue)
    return Prologue.takeError();
  SmallVector<char, 0> DistinctData;
  // Copy line table prologue into the DistinctData buffer.
  DistinctData.append(DebugLineStrRef.data(),
                      DebugLineStrRef.data() + Prologue->Offset);
  SmallVector<DebugLineRef, 0> LineTableVector;
  SmallVector<char, 0> LineTableData;
  uint64_t *OffsetPtr = &Prologue->Offset;
  uint64_t End =
      Prologue->Length + (Prologue->Format == dwarf::DWARF32 ? 4 : 8);
  while (*OffsetPtr < End) {
    DWARFDataExtractor::Cursor Cursor(*OffsetPtr);
    auto Opcode = LineTableDataReader.getU8(Cursor);
    LineTableData.push_back(Opcode);
    if (Opcode == 0) {
      // Extended Opcodes always start with a zero opcode followed by
      // a uleb128 length so unknown opcodes can be skipped.
      uint64_t CurrOffset = Cursor.tell();
      uint64_t Len = LineTableDataReader.getULEB128(Cursor);
      if (Len == 0)
        return createStringError(inconvertibleErrorCode(),
                                 "0 Length for an extended opcode is wrong");
      copyData(LineTableData, DebugLineStrRef, CurrOffset, Cursor);

      uint8_t SubOpcode = LineTableDataReader.getU8(Cursor);
      LineTableData.push_back(SubOpcode);
      bool IsEndSequence = false;
      bool IsRelocation = false;
      CurrOffset = Cursor.tell();
      auto Err = handleExtendedOpcodesForLineTable(LineTableDataReader, Cursor,
                                                   SubOpcode, Len,
                                                   IsEndSequence, IsRelocation);
      if (Err)
        return std::move(Err);
      if (IsRelocation) {
        // Move cursor to end of relocation and copy.
        LineTableDataReader.getRelocatedAddress(Cursor);
        copyData(DistinctData, DebugLineStrRef, CurrOffset, Cursor);
      } else
        copyData(LineTableData, DebugLineStrRef, CurrOffset, Cursor);

      if (IsEndSequence) {
        // The current Opcode is a DW_LNE_end_sequence. It takes no operand,
        // create a cas block here.
        auto LineTable =
            DebugLineRef::create(*this, toStringRef(LineTableData));
        if (!LineTable)
          return LineTable.takeError();
        LineTableVector.push_back(*LineTable);
        LineTableData.clear();
      }
    } else if (Opcode < Prologue->OpcodeBase) {
      bool IsSetFile = false;
      bool IsRelocation = false;
      uint64_t CurrOffset = Cursor.tell();
      auto Err = handleStandardOpcodesForLineTable(
          LineTableDataReader, Cursor, Opcode, IsSetFile, IsRelocation);
      if (Err)
        return std::move(Err);
      if (IsRelocation) {
        // Move cursor to end of relocation and copy.
        LineTableDataReader.getRelocatedValue(Cursor, 2);
        copyData(DistinctData, DebugLineStrRef, CurrOffset, Cursor);
      } else
        copyData(LineTableData, DebugLineStrRef, CurrOffset, Cursor);

      if (IsSetFile) {
        // The current Opcode is a DW_LNS_set_file. Store file numbers in the
        // distinct data.
        uint64_t CurrOffset = Cursor.tell();
        LineTableDataReader.getULEB128(Cursor);
        // The file number doesn't dedupe, so store that in the DistinctData.
        copyData(DistinctData, DebugLineStrRef, CurrOffset, Cursor);
      }
    } else {
      // Special Opcodes. Do nothing, move on.
    }
    if (!Cursor)
      return Cursor.takeError();
    *OffsetPtr = Cursor.tell();
  }

  // Create DistinctDebugLineRef.
  auto DistinctRef =
      DistinctDebugLineRef::create(*this, toStringRef(DistinctData));
  if (!DistinctRef)
    return DistinctRef.takeError();

  // Add Nodes in order. DistinctDebugLineRef first, then the DebugLineRefs,
  // then a PaddingRef if needed.
  addNode(*DistinctRef);
  for (auto &Node : LineTableVector)
    addNode(Node);
  return *OffsetPtr;
}

Error MCCASBuilder::createLineSection() {
  if (!DwarfSections.Line)
    return Error::success();

  Expected<SmallVector<char, 0>> DebugLineData =
      mergeMCFragmentContents(DwarfSections.Line->getFragmentList(), true);
  if (!DebugLineData)
    return DebugLineData.takeError();

  startSection(DwarfSections.Line);

  if (DebugInfoUnopt) {
    auto DbgLineUnoptRef =
        DebugLineUnoptRef::create(*this, toStringRef(*DebugLineData));
    if (!DbgLineUnoptRef)
      return DbgLineUnoptRef.takeError();
    addNode(*DbgLineUnoptRef);
  } else {
    StringRef DebugLineStrRef(DebugLineData->data(), DebugLineData->size());
    while (DebugLineStrRef.size()) {
      auto BytesWritten = createOptimizedLineSection(DebugLineStrRef);
      if (!BytesWritten)
        return BytesWritten.takeError();
      DebugLineStrRef = DebugLineStrRef.drop_front(*BytesWritten);
    }
  }

  if (auto E = createPaddingRef(DwarfSections.Line))
    return E;
  return finalizeSection<DebugLineSectionRef>();
}

Error MCCASBuilder::createDebugStrSection() {

  auto DebugStringRefs = createDebugStringRefs();
  if (!DebugStringRefs)
    return DebugStringRefs.takeError();

  startSection(DwarfSections.Str);
  for (auto DebugStringRef : *DebugStringRefs)
    addNode(DebugStringRef);
  if (auto E = createPaddingRef(DwarfSections.Str))
    return E;
  return finalizeSection<DebugStringSectionRef>();
}

Expected<SmallVector<DebugStrRef, 0>> MCCASBuilder::createDebugStringRefs() {
  if (!DwarfSections.Str || !DwarfSections.Str->getFragmentList().size())
    return SmallVector<DebugStrRef, 0>();

  assert(DwarfSections.Str->getFragmentList().size() == 1 &&
         "One fragment in debug str section");

  SmallVector<DebugStrRef, 0> DebugStringRefs;
  ArrayRef<char> DebugStrData =
      cast<MCDataFragment>(*DwarfSections.Str->begin()).getContents();
  StringRef S(DebugStrData.data(), DebugStrData.size());
  if (auto E = createStringSection(S, [&](StringRef S) -> Error {
        auto Sym = DebugStrRef::create(*this, S);
        if (!Sym)
          return Sym.takeError();
        DebugStringRefs.push_back(*Sym);
        return Error::success();
      }))
    return std::move(E);
  return DebugStringRefs;
}

template <typename SectionTy>
std::optional<Expected<SectionTy>>
MCCASBuilder::createGenericDebugRef(MCSection *Section) {
  if (!Section || !Section->getFragmentList().size())
    return std::nullopt;

  auto DebugCASData =
      mergeMCFragmentContents(Section->getFragmentList(), false);

  if (!DebugCASData)
    return DebugCASData.takeError();

  StringRef S(DebugCASData->data(), DebugCASData->size());

  auto DebugCASRef = SectionTy::create(*this, S);
  if (!DebugCASRef)
    return DebugCASRef.takeError();

  return *DebugCASRef;
}

std::optional<Expected<DebugStrOffsetsRef>>
MCCASBuilder::createDebugStrOffsetsRef() {

  if (!DwarfSections.StrOffsets ||
      !DwarfSections.StrOffsets->getFragmentList().size())
    return std::nullopt;

  auto DebugStrOffsetsData = mergeMCFragmentContents(
      DwarfSections.StrOffsets->getFragmentList(), false);

  if (!DebugStrOffsetsData)
    return DebugStrOffsetsData.takeError();

#if LLVM_ENABLE_ZLIB
  SmallVector<uint8_t> CompressedBuff;
  compression::zlib::compress(
      arrayRefFromStringRef(toStringRef(*DebugStrOffsetsData)), CompressedBuff);
  // Reserve 8 bytes for ULEB to store the size of the uncompressed data.
  CompressedBuff.append(8, 0);
  encodeULEB128(DebugStrOffsetsData->size(), CompressedBuff.end() - 8,
                8 /*Pad to*/);
  auto DbgStrOffsetsRef =
      DebugStrOffsetsRef::create(*this, toStringRef(CompressedBuff));
  if (!DbgStrOffsetsRef)
    return DbgStrOffsetsRef.takeError();
  return *DbgStrOffsetsRef;
#else
  auto DbgStrOffsetsRef =
      DebugStrOffsetsRef::create(*this, toStringRef(*DebugStrOffsetsData));
  if (!DbgStrOffsetsRef)
    return DbgStrOffsetsRef.takeError();
  return *DbgStrOffsetsRef;
#endif
}

Error MCCASBuilder::createDebugStrOffsetsSection() {

  auto MaybeDebugStringOffsetsRef = createDebugStrOffsetsRef();
  if (!MaybeDebugStringOffsetsRef)
    return Error::success();

  if (!*MaybeDebugStringOffsetsRef)
    return MaybeDebugStringOffsetsRef->takeError();

  startSection(DwarfSections.StrOffsets);
  addNode(**MaybeDebugStringOffsetsRef);
  if (auto E = createPaddingRef(DwarfSections.StrOffsets))
    return E;
  return finalizeSection<DebugStringOffsetsSectionRef>();
}

Error MCCASBuilder::createDebugLocSection() {

  auto MaybeDebugLocRef = createGenericDebugRef<DebugLocRef>(DwarfSections.Loc);
  if (!MaybeDebugLocRef)
    return Error::success();

  if (!*MaybeDebugLocRef)
    return MaybeDebugLocRef->takeError();

  startSection(DwarfSections.Loc);
  addNode(**MaybeDebugLocRef);
  if (auto E = createPaddingRef(DwarfSections.Loc))
    return E;
  return finalizeSection<DebugLocSectionRef>();
}

Error MCCASBuilder::createDebugLoclistsSection() {

  auto MaybeDebugLoclistsRef =
      createGenericDebugRef<DebugLoclistsRef>(DwarfSections.Loclists);
  if (!MaybeDebugLoclistsRef)
    return Error::success();

  if (!*MaybeDebugLoclistsRef)
    return MaybeDebugLoclistsRef->takeError();

  startSection(DwarfSections.Loclists);
  addNode(**MaybeDebugLoclistsRef);
  if (auto E = createPaddingRef(DwarfSections.Loclists))
    return E;
  return finalizeSection<DebugLoclistsSectionRef>();
}

Error MCCASBuilder::createDebugRangesSection() {

  auto MaybeDebugRangesRef =
      createGenericDebugRef<DebugRangesRef>(DwarfSections.Ranges);
  if (!MaybeDebugRangesRef)
    return Error::success();

  if (!*MaybeDebugRangesRef)
    return MaybeDebugRangesRef->takeError();

  startSection(DwarfSections.Ranges);
  addNode(**MaybeDebugRangesRef);
  if (auto E = createPaddingRef(DwarfSections.Ranges))
    return E;
  return finalizeSection<DebugRangesSectionRef>();
}

Error MCCASBuilder::createDebugRangelistsSection() {

  auto MaybeDebugRangelistsRef =
      createGenericDebugRef<DebugRangelistsRef>(DwarfSections.Rangelists);
  if (!MaybeDebugRangelistsRef)
    return Error::success();

  if (!*MaybeDebugRangelistsRef)
    return MaybeDebugRangelistsRef->takeError();

  startSection(DwarfSections.Rangelists);
  addNode(**MaybeDebugRangelistsRef);
  if (auto E = createPaddingRef(DwarfSections.Rangelists))
    return E;
  return finalizeSection<DebugRangelistsSectionRef>();
}

Error MCCASBuilder::createDebugLineStrSection() {

  auto MaybeDebugLineStrRef =
      createGenericDebugRef<DebugLineStrRef>(DwarfSections.LineStr);
  if (!MaybeDebugLineStrRef)
    return Error::success();

  if (!*MaybeDebugLineStrRef)
    return MaybeDebugLineStrRef->takeError();

  startSection(DwarfSections.LineStr);
  addNode(**MaybeDebugLineStrRef);
  if (auto E = createPaddingRef(DwarfSections.LineStr))
    return E;
  return finalizeSection<DebugLineStrSectionRef>();
}

Error MCCASBuilder::createDebugNamesSection() {

  auto MaybeDebugNamesRef =
      createGenericDebugRef<DebugNamesRef>(DwarfSections.Names);
  if (!MaybeDebugNamesRef)
    return Error::success();

  if (!*MaybeDebugNamesRef)
    return MaybeDebugNamesRef->takeError();

  startSection(DwarfSections.Names);
  addNode(**MaybeDebugNamesRef);
  if (auto E = createPaddingRef(DwarfSections.Names))
    return E;
  return finalizeSection<DebugNamesSectionRef>();
}

Error MCCASBuilder::createAppleNamesSection() {

  auto MaybeAppleNamesRef =
      createGenericDebugRef<AppleNamesRef>(DwarfSections.AppleNames);
  if (!MaybeAppleNamesRef)
    return Error::success();

  if (!*MaybeAppleNamesRef)
    return MaybeAppleNamesRef->takeError();

  startSection(DwarfSections.AppleNames);
  addNode(**MaybeAppleNamesRef);
  if (auto E = createPaddingRef(DwarfSections.AppleNames))
    return E;
  return finalizeSection<AppleNamesSectionRef>();
}

Error MCCASBuilder::createAppleTypesSection() {

  auto MaybeAppleTypesRef =
      createGenericDebugRef<AppleTypesRef>(DwarfSections.AppleTypes);
  if (!MaybeAppleTypesRef)
    return Error::success();

  if (!*MaybeAppleTypesRef)
    return MaybeAppleTypesRef->takeError();

  startSection(DwarfSections.AppleTypes);
  addNode(**MaybeAppleTypesRef);
  if (auto E = createPaddingRef(DwarfSections.AppleTypes))
    return E;
  return finalizeSection<AppleTypesSectionRef>();
}

Error MCCASBuilder::createAppleNamespaceSection() {

  auto MaybeAppleNamespaceRef =
      createGenericDebugRef<AppleNamespaceRef>(DwarfSections.AppleNamespace);
  if (!MaybeAppleNamespaceRef)
    return Error::success();

  if (!*MaybeAppleNamespaceRef)
    return MaybeAppleNamespaceRef->takeError();

  startSection(DwarfSections.AppleNamespace);
  addNode(**MaybeAppleNamespaceRef);
  if (auto E = createPaddingRef(DwarfSections.AppleNamespace))
    return E;
  return finalizeSection<AppleNamespaceSectionRef>();
}

Error MCCASBuilder::createAppleObjCSection() {

  auto MaybeAppleObjCRef =
      createGenericDebugRef<AppleObjCRef>(DwarfSections.AppleObjC);
  if (!MaybeAppleObjCRef)
    return Error::success();

  if (!*MaybeAppleObjCRef)
    return MaybeAppleObjCRef->takeError();

  startSection(DwarfSections.AppleObjC);
  addNode(**MaybeAppleObjCRef);
  if (auto E = createPaddingRef(DwarfSections.AppleObjC))
    return E;
  return finalizeSection<AppleObjCSectionRef>();
}

static ArrayRef<char> getFragmentContents(const MCFragment &Fragment) {
  switch (Fragment.getKind()) {
#define MCFRAGMENT_NODE_REF(MCFragmentName, MCEnumName, MCEnumIdentifier)      \
  case MCFragment::MCEnumName: {                                               \
    const MCFragmentName &SF = cast<MCFragmentName>(Fragment);                 \
    return SF.getContents();                                                   \
  }
#define MCFRAGMENT_ENCODED_FRAGMENT_ONLY
#include "llvm/MCCAS/MCCASObjectV1.def"
  case MCFragment::FT_CVInlineLines: {
    const MCCVInlineLineTableFragment &SF =
        cast<MCCVInlineLineTableFragment>(Fragment);
    return SF.getContents();
  }
  case MCFragment::FT_LEB: {
    const MCLEBFragment &SF = cast<MCLEBFragment>(Fragment);
    return SF.getContents();
  }
  default:
    return ArrayRef<char>();
  }
}

static unsigned getRelocationSize(const MachO::any_relocation_info &RE,
                                  bool IsLittleEndian) {
  if (IsLittleEndian)
    return 1 << ((RE.r_word1 >> 25) & 3);
  return 1 << ((RE.r_word1 >> 5) & 3);
}

static uint32_t getRelocationOffset(const MachO::any_relocation_info &RE) {
  return RE.r_word0;
}

/// This helper function is used to partition a Fragment into 2 parts, the \p
/// FinalFragmentContents will contain the contents of the Fragment that will
/// deduplicate and will be stored as part of a *FragmentRef or a
/// MergedFragmentRef, the \p Addends stores all the relocation
/// addends that will not deduplicate in the CAS and must be stored separately,
/// there is one AddendRef per section in the CAS. Depending on the situation,
/// the \p RelocationBuffer may have the relocations for the entire section,
/// thereforem there may not be a way to know whether a relocation belongs to
/// the current fragment being processed. The \p RelocationBufferIndex is an out
/// parameter and is the index into the \p RelocationBuffer, which is used to
/// access the current relocation that has to be partitioned.
static void
partitionFragment(const MCAsmLayout &Layout, SmallVector<char, 0> &Addends,
                  SmallVector<char, 0> &FinalFragmentContents,
                  ArrayRef<MachO::any_relocation_info> RelocationBuffer,
                  const MCFragment &Fragment, uint64_t &RelocationBufferIndex,
                  bool IsLittleEndian) {
  auto FragmentContents = getFragmentContents(Fragment);
  /// FragmentIndex: It denotes the index into the FragmentContents that is used
  /// to copy the data that deduplicates in the \p FinalFragmentContents.
  uint64_t FragmentIndex = 0;
  /// PrevOffset: A relocation can sometimes be divided into multiple parts, all
  /// of them share the same offset, but describe only one Addend, if we already
  /// copied the addend out of the FragmentContents at a particular offset, we
  /// should skip all relocations that matches the same offset.
  int64_t PrevOffset = -1;
  // Relocations are stored in the Section.
  for (; RelocationBufferIndex < RelocationBuffer.size();
       RelocationBufferIndex++) {
    auto Reloc = RelocationBuffer[RelocationBufferIndex];
    uint32_t RelocOffset = getRelocationOffset(Reloc);
    if (PrevOffset == RelocOffset)
      continue;
    uint64_t FragmentOffset = Layout.getFragmentOffset(&Fragment);
    if (RelocOffset < FragmentOffset + FragmentContents.size()) {
      /// RelocOffsetInFragment: This is used to denote the offset of the
      /// relocation in the current Fragment. Relocation offsets are always from
      /// the start of the section, we need to normalize this value to start at
      /// the start of the Fragment instead.
      uint32_t RelocOffsetInFragment = RelocOffset - FragmentOffset;
      // Copy contents of fragment upto relocation addend data in the
      // FinalFragmentContents.
      FinalFragmentContents.append(FragmentContents.data() + FragmentIndex,
                                   FragmentContents.data() +
                                       RelocOffsetInFragment);
      // Addend belongs to the current fragment, copy the addend into the
      // Addend vector.
      Addends.append(FragmentContents.data() + RelocOffsetInFragment,
                     FragmentContents.data() + RelocOffsetInFragment +
                         getRelocationSize(Reloc, IsLittleEndian));
      FragmentIndex =
          RelocOffsetInFragment + getRelocationSize(Reloc, IsLittleEndian);
      PrevOffset = RelocOffset;
    } else
      break;
  }
  // Copy any leftover fragment contents into the FinalFragmentContents.
  FinalFragmentContents.append(FragmentContents.data() + FragmentIndex,
                               FragmentContents.data() +
                                   FragmentContents.size());
}

Error MCCASBuilder::buildFragments() {
  startGroup();

  for (const MCSection &Sec : Asm) {
    if (Sec.isVirtualSection() || Sec.getFragmentList().empty())
      continue;

    // Handle Debug Info sections separately.
    if (&Sec == DwarfSections.DebugInfo) {
      if (auto E = createDebugInfoSection())
        return E;
      continue;
    }

    // Handle Debug Abbrev sections separately.
    if (&Sec == DwarfSections.Abbrev) {
      if (auto E = createDebugAbbrevSection())
        return E;
      continue;
    }

    // Handle Debug Line sections separately.
    if (&Sec == DwarfSections.Line) {
      if (auto E = createLineSection())
        return E;
      continue;
    }

    // Handle Debug Str sections separately.
    if (&Sec == DwarfSections.Str) {
      if (auto E = createDebugStrSection())
        return E;
      continue;
    }

    // Handle Debug Str Offsets sections separately.
    if (&Sec == DwarfSections.StrOffsets) {
      if (auto E = createDebugStrOffsetsSection())
        return E;
      continue;
    }

    // Handle Debug Loc sections separately.
    if (&Sec == DwarfSections.Loc) {
      if (auto E = createDebugLocSection())
        return E;
      continue;
    }

    // Handle Debug Loclists sections separately.
    if (&Sec == DwarfSections.Loclists) {
      if (auto E = createDebugLoclistsSection())
        return E;
      continue;
    }

    // Handle Debug Ranges sections separately.
    if (&Sec == DwarfSections.Ranges) {
      if (auto E = createDebugRangesSection())
        return E;
      continue;
    }

    // Handle Debug Rangelists sections separately.
    if (&Sec == DwarfSections.Rangelists) {
      if (auto E = createDebugRangelistsSection())
        return E;
      continue;
    }

    // Handle Debug LineStr sections separately.
    if (&Sec == DwarfSections.LineStr) {
      if (auto E = createDebugLineStrSection())
        return E;
      continue;
    }

    // Handle Debug Names sections separately.
    if (&Sec == DwarfSections.Names) {
      if (auto E = createDebugNamesSection())
        return E;
      continue;
    }

    // Handle Debug AppleNames sections separately.
    if (&Sec == DwarfSections.AppleNames) {
      if (auto E = createAppleNamesSection())
        return E;
      continue;
    }

    // Handle Debug AppleTypes sections separately.
    if (&Sec == DwarfSections.AppleTypes) {
      if (auto E = createAppleTypesSection())
        return E;
      continue;
    }

    // Handle Debug AppleNamespace sections separately.
    if (&Sec == DwarfSections.AppleNamespace) {
      if (auto E = createAppleNamespaceSection())
        return E;
      continue;
    }

    // Handle Debug AppleObjC sections separately.
    if (&Sec == DwarfSections.AppleObjC) {
      if (auto E = createAppleObjCSection())
        return E;
      continue;
    }

    // Start Subsection for one section.
    startSection(&Sec);

    // Start subsection for first Atom.
    startAtom(Sec.getFragmentList().front().getAtom());

    SmallVector<char, 0> Addends;
    ArrayRef<MachO::any_relocation_info> RelocationBuffer;
    MCDataFragmentMerger Merger(*this, &Sec);
    uint64_t RelocationBufferIndex = 0;
    for (const MCFragment &F : Sec) {
      auto Relocs = RelMap.find(&F);
      if (RelocLocation == Atom) {
        if (Relocs != RelMap.end()) {
          AtomRelocs.append(Relocs->second.begin(), Relocs->second.end());
          // Reset RelocationBufferIndex if Relocations exist per Fragment. This
          // is done because if the relocations are stored in the RelMap, and
          // not with the SectionContents, we need to reset the
          // RelocationBufferIndex to start at the beginning of the Fragments
          // relocation buffer.
          RelocationBufferIndex = 0;
        }
      }

      // Relocations are in the RelMap or in the SectionRelocs. If they are in
      // the RelMap, they are accessible per fragment. Choose the correct buffer
      // where they are stored. Initialize RelocationBuffer to an empty
      // ArrayRef, if no Relocations are present.
      if (Relocs != RelMap.end())
        RelocationBuffer = Relocs->second;
      else if (SectionRelocs.empty())
        RelocationBuffer = ArrayRef<MachO::any_relocation_info>();
      else
        RelocationBuffer = SectionRelocs;

      auto Size = Asm.computeFragmentSize(Layout, F);
      // Don't need to encode the fragment if it doesn't contribute anything.
      if (!Size)
        continue;

      SmallVector<char, 0> FinalFragmentContents;
      // Set the RelocationBuffer to be an empty ArrayRef, and the
      // RelocationBufferIndex to zero if the architecture is 32-bit, because we
      // do not support relocation partitioning on 32-bit platforms. With this,
      // partitionFragment will put all the fragment contents in the
      // FinalFragmentContents, and the Addends buffer will be empty.
      if (ObjectWriter.getAddressSize() == 4) {
        RelocationBuffer = ArrayRef<MachO::any_relocation_info>();
        RelocationBufferIndex = 0;
      }
      partitionFragment(Layout, Addends, FinalFragmentContents,
                        RelocationBuffer, F, RelocationBufferIndex,
                        ObjectWriter.Target.isLittleEndian());

      if (auto E = Merger.tryMerge(F, Size, FinalFragmentContents))
        return E;
    }
    if (auto E = Merger.flush())
      return E;

    // End last subsection for late Atom.
    if (auto E = finalizeAtom())
      return E;

    if (auto E = createPaddingRef(&Sec))
      return E;

    // Do not create an AddendsRef if there were no relocations in this section.
    if (!Addends.empty()) {
      auto AddendRef = AddendsRef::create(*this, toStringRef(Addends));
      if (!AddendRef)
        return AddendRef.takeError();
      addNode(*AddendRef);
    }

    if (auto E = finalizeSection())
      return E;
  }
  return finalizeGroup();
}

Error MCCASBuilder::buildRelocations() {
  ObjectWriter.resetBuffer();
  if (ObjectWriter.Mode == CASBackendMode::Verify ||
      RelocLocation == CompileUnit)
    ObjectWriter.writeRelocations(Asm, Layout);

  if (RelocLocation == CompileUnit) {
    auto Relocs = RelocationsRef::create(*this, ObjectWriter.getContent());
    if (!Relocs)
      return Relocs.takeError();

    addNode(*Relocs);
  }

  return Error::success();
}

Error MCCASBuilder::buildDataInCodeRegion() {
  ObjectWriter.resetBuffer();
  ObjectWriter.writeDataInCodeRegion(Asm, Layout);
  auto Data = DataInCodeRef::create(*this, ObjectWriter.getContent());
  if (!Data)
    return Data.takeError();

  addNode(*Data);
  return Error::success();
}

Error MCCASBuilder::buildSymbolTable() {
  ObjectWriter.resetBuffer();
  ObjectWriter.writeSymbolTable(Asm, Layout);
  StringRef S = ObjectWriter.getContent();
  std::vector<cas::ObjectRef> CStrings;
  if (auto E = createStringSection(S, [&](StringRef S) -> Error {
        auto Sym = CStringRef::create(*this, S);
        if (!Sym)
          return Sym.takeError();
        CStrings.push_back(Sym->getRef());
        return Error::success();
      }))
    return E;

  auto Ref = SymbolTableRef::create(*this, CStrings);
  if (!Ref)
    return Ref.takeError();
  addNode(*Ref);

  return Error::success();
}

void MCCASBuilder::startGroup() {
  assert(GroupContext.empty() && "GroupContext is not empty");
  CurrentContext = &GroupContext;
}

Error MCCASBuilder::finalizeGroup() {
  auto Ref = GroupRef::create(*this, GroupContext);
  if (!Ref)
    return Ref.takeError();
  GroupContext.clear();
  CurrentContext = &Sections;
  addNode(*Ref);
  return Error::success();
}

void MCCASBuilder::startSection(const MCSection *Sec) {
  assert(SectionContext.empty() && !CurrentSection && RelMap.empty() &&
         SectionRelocs.empty() && "SectionContext is not empty");

  CurrentSection = Sec;
  CurrentContext = &SectionContext;

  if (RelocLocation == Atom) {
    // Build a map for lookup.
    for (auto R : ObjectWriter.getRelocations()[Sec]) {
      // For the Dwarf Sections, just append the relocations to the
      // SectionRelocs. No Atoms are considered for this section.
      if (R.F && Sec != DwarfSections.Line && Sec != DwarfSections.DebugInfo &&
          Sec != DwarfSections.Abbrev && Sec != DwarfSections.StrOffsets &&
          Sec != DwarfSections.Loclists && Sec != DwarfSections.Ranges &&
          Sec != DwarfSections.Rangelists && Sec != DwarfSections.LineStr &&
          Sec != DwarfSections.Names && Sec != DwarfSections.AppleNames &&
          Sec != DwarfSections.AppleTypes &&
          Sec != DwarfSections.AppleNamespace && Sec != DwarfSections.AppleObjC)
        RelMap[R.F].push_back(R.MRE);
      else
        // If the fragment is nullptr, it should a section with only relocation
        // in section. Encode in section.
        // DebugInfo sections are also encoded in a single section.
        SectionRelocs.push_back(R.MRE);
    }
  }

  if (RelocLocation == Section) {
    for (auto R : ObjectWriter.getRelocations()[Sec])
      SectionRelocs.push_back(R.MRE);
  }
}

template <typename SectionRefTy>
Error MCCASBuilder::finalizeSection() {
  auto Ref = SectionRefTy::create(*this, SectionContext);
  if (!Ref)
    return Ref.takeError();

  SectionContext.clear();
  SectionRelocs.clear();
  RelMap.clear();
  CurrentSection = nullptr;
  CurrentContext = &GroupContext;
  addNode(*Ref);

  return Error::success();
}

void MCCASBuilder::startAtom(const MCSymbol *Atom) {
  assert(AtomContext.empty() && AtomRelocs.empty() && !CurrentAtom &&
         "AtomContext is not empty");

  CurrentAtom = Atom;
  CurrentContext = &AtomContext;
}

Error MCCASBuilder::finalizeAtom() {
  auto Ref = AtomRef::create(*this, AtomContext);
  if (!Ref)
    return Ref.takeError();

  AtomContext.clear();
  AtomRelocs.clear();
  CurrentAtom = nullptr;
  CurrentContext = &SectionContext;
  addNode(*Ref);

  return Error::success();
}

void MCCASBuilder::addNode(cas::ObjectProxy Node) {
  CurrentContext->push_back(Node.getRef());
}

Expected<MCAssemblerRef> MCAssemblerRef::create(const MCSchema &Schema,
                                                MachOCASWriter &ObjectWriter,
                                                MCAssembler &Asm,
                                                const MCAsmLayout &Layout,
                                                raw_ostream *DebugOS) {
  MCCASBuilder Builder(Schema, ObjectWriter, Asm, Layout, DebugOS);

  if (auto E = Builder.prepare())
    return std::move(E);

  if (auto E = Builder.buildMachOHeader())
    return std::move(E);

  if (auto E = Builder.buildFragments())
    return std::move(E);

  // Only need to do this for verify mode so we compare the output byte by
  // byte.
  if (ObjectWriter.Mode == CASBackendMode::Verify) {
    ObjectWriter.writeSectionData(Asm, Layout);
  }

  if (auto E = Builder.buildRelocations())
    return std::move(E);

  if (auto E = Builder.buildDataInCodeRegion())
    return std::move(E);

  if (auto E = Builder.buildSymbolTable())
    return std::move(E);

  auto B = Builder::startRootNode(Schema, KindString);
  if (!B)
    return B.takeError();

  // Put Header, Relocations, SymbolTable, etc. in the front.
  B->Refs.append(Builder.Sections.begin(), Builder.Sections.end());

  std::string NormalizedTriple = ObjectWriter.Target.normalize();
  writeVBR8(uint32_t(NormalizedTriple.size()), B->Data);
  B->Data.append(NormalizedTriple);

  return get(B->build());
}

template <typename T>
static Expected<T> findSectionFromAsm(const MCAssemblerRef &Asm) {
  for (unsigned I = 1; I < Asm.getNumReferences(); ++I) {
    auto Node = MCObjectProxy::get(
        Asm.getSchema(), Asm.getSchema().CAS.getProxy(Asm.getReference(I)));
    if (!Node)
      return Node.takeError();
    if (auto Ref = T::Cast(*Node))
      return *Ref;
  }

  return createStringError(inconvertibleErrorCode(),
                           "cannot locate the requested section");
}

template <typename T>
static Expected<uint64_t> materializeData(raw_ostream &OS,
                                          const MCAssemblerRef &Asm) {
  auto Node = findSectionFromAsm<T>(Asm);
  if (!Node)
    return Node.takeError();

  return Node->materialize(OS);
}

Error MCAssemblerRef::materialize(raw_ostream &OS) const {
  // Read the triple first.
  StringRef Remaining = getData();
  uint32_t NormalizedTripleSize;
  if (auto E = consumeVBR8(Remaining, NormalizedTripleSize))
    return E;
  auto TripleStr = consumeDataOfSize(Remaining, NormalizedTripleSize);
  if (!TripleStr)
    return TripleStr.takeError();
  Triple Target(*TripleStr);

  MCCASReader Reader(OS, Target, getSchema());
  uint64_t Written = 0;
  // MachOHeader.
  auto HeaderSize = materializeData<HeaderRef>(OS, *this);
  if (!HeaderSize)
    return HeaderSize.takeError();
  Written += *HeaderSize;

  // SectionData.
  auto SectionDataRef = findSectionFromAsm<GroupRef>(*this);
  if (!SectionDataRef)
    return SectionDataRef.takeError();
  auto SectionDataSize = SectionDataRef->materialize(Reader);
  if (!SectionDataSize)
    return SectionDataSize.takeError();
  Written += *SectionDataSize;

  // Add padding to pointer size.
  auto SectionDataPad =
      offsetToAlignment(Written, Target.isArch64Bit() ? Align(8) : Align(4));
  OS.write_zeros(SectionDataPad);

  for (auto &Sec : Reader.Relocations) {
    for (auto &Entry : llvm::reverse(Sec)) {
      support::endian::write<uint32_t>(OS, Entry.r_word0, Reader.getEndian());
      support::endian::write<uint32_t>(OS, Entry.r_word1, Reader.getEndian());
    }
  }

  if (auto Relocations = findSectionFromAsm<RelocationsRef>(*this)) {
    auto RelocSize = Relocations->materialize(OS);
    if (!RelocSize)
      return RelocSize.takeError();
  } else
    consumeError(Relocations.takeError()); // Relocations can be missing.

  auto DCOrErr = materializeData<DataInCodeRef>(OS, *this);
  if (!DCOrErr)
    return DCOrErr.takeError();

  auto SymTableRef = findSectionFromAsm<SymbolTableRef>(*this);
  if (!SymTableRef)
    return SymTableRef.takeError();
  auto SymbolTableSize = SymTableRef->materialize(Reader);
  if (!SymbolTableSize)
    return SymbolTableSize.takeError();

  return Error::success();
}

MCCASReader::MCCASReader(raw_ostream &OS, const Triple &Target,
                         const MCSchema &Schema)
    : OS(OS), Target(Target), Schema(Schema) {}

Expected<uint64_t> MCCASReader::materializeGroup(cas::ObjectRef ID) {
  auto Node = MCObjectProxy::get(Schema, Schema.CAS.getProxy(ID));
  if (!Node)
    return Node.takeError();

  // Group can have sections, symbol table strs.
  if (auto F = SectionRef::Cast(*Node))
    return F->materialize(*this);
  if (auto F = DebugStringSectionRef::Cast(*Node))
    return F->materialize(*this);
  if (auto F = DebugStringOffsetsSectionRef::Cast(*Node))
    return F->materialize(*this);
  if (auto F = DebugLocSectionRef::Cast(*Node))
    return F->materialize(*this);
  if (auto F = DebugLoclistsSectionRef::Cast(*Node))
    return F->materialize(*this);
  if (auto F = DebugRangesSectionRef::Cast(*Node))
    return F->materialize(*this);
  if (auto F = DebugRangelistsSectionRef::Cast(*Node))
    return F->materialize(*this);
  if (auto F = DebugLineStrSectionRef::Cast(*Node))
    return F->materialize(*this);
  if (auto F = DebugNamesSectionRef::Cast(*Node))
    return F->materialize(*this);
  if (auto F = AppleNamesSectionRef::Cast(*Node))
    return F->materialize(*this);
  if (auto F = AppleTypesSectionRef::Cast(*Node))
    return F->materialize(*this);
  if (auto F = AppleNamespaceSectionRef::Cast(*Node))
    return F->materialize(*this);
  if (auto F = AppleObjCSectionRef::Cast(*Node))
    return F->materialize(*this);
  if (auto F = CStringRef::Cast(*Node)) {
    auto Size = F->materialize(OS);
    if (!Size)
      return Size.takeError();
    // Write null between strings.
    OS.write_zeros(1);
    return *Size + 1;
  }
  if (auto F = DebugInfoSectionRef::Cast(*Node))
    return materializeDebugInfoFromTagImpl(*this, *F);
  if (auto F = DebugLineSectionRef::Cast(*Node))
    return F->materialize(*this);
  return createStringError(inconvertibleErrorCode(),
                           "unsupported CAS node for group");
}

Expected<uint64_t>
MCCASReader::materializeDebugAbbrevUnopt(ArrayRef<cas::ObjectRef> Refs) {

  SmallVector<char, 0> DebugAbbrevSection;
  bool DebugAbbrevUnoptRefSeen = false;
  for (auto Ref : Refs) {
    auto Obj = getObjectProxy(Ref);
    if (!Obj)
      return Obj.takeError();
    if (auto F = DebugAbbrevUnoptRef::Cast(*Obj)) {
      DebugAbbrevUnoptRefSeen = true;
      append_range(DebugAbbrevSection, F->getData());
      continue;
    }
    if (auto F = PaddingRef::Cast(*Obj)) {
      if (!DebugAbbrevUnoptRefSeen)
        return 0;
      raw_svector_ostream OS(DebugAbbrevSection);
      auto Size = F->materialize(OS);
      if (!Size)
        return Size.takeError();
      continue;
    }
    llvm_unreachable("Incorrect CAS Object in DebugAbbrevSection");
  }
  OS << DebugAbbrevSection;
  return DebugAbbrevSection.size();
}

Expected<uint64_t> MCCASReader::materializeSection(cas::ObjectRef ID,
                                                   raw_ostream *Stream) {
  auto Node = MCObjectProxy::get(Schema, Schema.CAS.getProxy(ID));
  if (!Node)
    return Node.takeError();

  // Section can have atoms, padding, debug_strs.
  if (auto F = AtomRef::Cast(*Node))
    return F->materialize(*this, Stream);
  if (auto F = PaddingRef::Cast(*Node))
    return F->materialize(*Stream);
  if (auto F = DebugStrRef::Cast(*Node)) {
    auto Size = F->materialize(*Stream);
    if (!Size)
      return Size.takeError();
    // Write null between strings.
    Stream->write_zeros(1);
    return *Size + 1;
  }
  if (auto F = DebugStrOffsetsRef::Cast(*Node))
    return F->materialize(*Stream);
  if (auto F = DebugLocRef::Cast(*Node))
    return F->materialize(*Stream);
  if (auto F = DebugLoclistsRef::Cast(*Node))
    return F->materialize(*Stream);
  if (auto F = DebugRangesRef::Cast(*Node))
    return F->materialize(*Stream);
  if (auto F = DebugRangelistsRef::Cast(*Node))
    return F->materialize(*Stream);
  if (auto F = DebugLineStrRef::Cast(*Node))
    return F->materialize(*Stream);
  if (auto F = DebugNamesRef::Cast(*Node))
    return F->materialize(*Stream);
  if (auto F = AppleNamesRef::Cast(*Node))
    return F->materialize(*Stream);
  if (auto F = AppleTypesRef::Cast(*Node))
    return F->materialize(*Stream);
  if (auto F = AppleNamespaceRef::Cast(*Node))
    return F->materialize(*Stream);
  if (auto F = AppleObjCRef::Cast(*Node))
    return F->materialize(*Stream);
  if (auto F = AddendsRef::Cast(*Node))
    // AddendsRef is already handled when materializing Atoms, skip.
    return 0;
  return createStringError(inconvertibleErrorCode(),
                           "unsupported CAS node for atom");
}

/// This helper function reconstructs the current Section as it was before the
/// CAS was created. In the CAS, each section is split into multiple
/// *FragmentRef or MergedFragmentRef blocks, and an AddendsRef block that
/// contains the relocation addends for that section. The \p SectionBuffer is an
/// out parameter that will contain the contents of the entire section after it
/// is properly reconstructed. The \p FragmentBuffer contains the contents of
/// all the Fragments for that section.
Expected<uint64_t>
MCCASReader::reconstructSection(SmallVectorImpl<char> &SectionBuffer,
                                ArrayRef<char> FragmentBuffer) {
  /// FragmentIndex: It denotes the index into the \p FragmentBuffer that is
  /// used to copy the Fragment contents into the \p SectionBuffer.
  uint64_t FragmentIndex = 0;
  /// PrevOffset: A relocation can sometimes be divided into multiple parts, all
  /// of them share the same offset, but describe only one Addend, if we already
  /// copied the addend out of the Addends at a particular offset, we should
  /// skip all relocations that matches the same offset.
  int64_t PrevOffset = -1;
  /// If the \p Addends buffer is empty, there was no AddendsRef for this
  /// section, this is either because no \p Relocations exist in this section,
  /// or this is 32-bit architecture, where we do not support relocation
  /// partitioning.
  if (!Addends.empty()) {
    for (auto Reloc : Relocations.back()) {
      auto RelocationOffsetInSection = getRelocationOffset(Reloc);
      if (PrevOffset == RelocationOffsetInSection)
        continue;
      auto RelocationSize =
          getRelocationSize(Reloc, getEndian() == support::little);
      /// NumOfBytesToReloc: This denotes the number of bytes needed to be
      /// copied into the \p SectionBuffer before we copy the next addend.
      auto NumOfBytesToReloc = RelocationOffsetInSection - SectionBuffer.size();
      // Copy the contents of the fragment till the next relocation.
      SectionBuffer.append(FragmentBuffer.begin() + FragmentIndex,
                           FragmentBuffer.begin() + FragmentIndex +
                               NumOfBytesToReloc);
      FragmentIndex += NumOfBytesToReloc;
      // Copy the relocation addend.
      SectionBuffer.append(Addends.begin() + AddendBufferIndex,
                           Addends.begin() + AddendBufferIndex +
                               RelocationSize);
      AddendBufferIndex += RelocationSize;
      PrevOffset = RelocationOffsetInSection;
    }
  }
  // Copy any remaining bytes of the fragment into the SectionBuffer.
  SectionBuffer.append(FragmentBuffer.begin() + FragmentIndex,
                       FragmentBuffer.end());
  assert(AddendBufferIndex == Addends.size() &&
         "All addends for section not copied into final section buffer");
  return AddendBufferIndex;
}

Expected<uint64_t> MCCASReader::materializeAtom(cas::ObjectRef ID,
                                                raw_ostream *Stream) {
  auto Node = MCObjectProxy::get(Schema, Schema.CAS.getProxy(ID));
  if (!Node)
    return Node.takeError();

#define MCFRAGMENT_NODE_REF(MCFragmentName, MCEnumName, MCEnumIdentifier)      \
  if (auto F = MCFragmentName##Ref::Cast(*Node))                               \
    return F->materialize(*this, Stream);
#include "llvm/MCCAS/MCCASObjectV1.def"
  if (auto F = PaddingRef::Cast(*Node))
    return F->materialize(*Stream);
  if (auto F = MergedFragmentRef::Cast(*Node))
    return F->materialize(*Stream);

  return createStringError(inconvertibleErrorCode(),
                           "unsupported CAS node for fragment");
}

/// If the AddendsRef exists in the current section, copy its contents into the
/// Addends buffer.
Error MCCASReader::checkIfAddendRefExistsAndCopy(
    ArrayRef<cas::ObjectRef> Refs) {
  auto ID = Refs.back();
  auto Node = getObjectProxy(ID);
  if (!Node)
    return Node.takeError();

  if (auto F = AddendsRef::Cast(*Node))
    Addends.append(F->getData().begin(), F->getData().end());
  return Error::success();
}

Expected<DIEAbbrevSetRef>
DIEAbbrevSetRef::create(MCCASBuilder &MB, ArrayRef<cas::ObjectRef> Abbrevs) {
  Expected<Builder> B = Builder::startNode(MB.Schema, KindString);
  if (!B)
    return B.takeError();
  append_range(B->Refs, Abbrevs);
  return get(B->build());
}

Expected<DIETopLevelRef>
DIETopLevelRef::create(MCCASBuilder &MB, ArrayRef<cas::ObjectRef> Children) {
  Expected<Builder> B = Builder::startNode(MB.Schema, KindString);
  if (!B)
    return B.takeError();
  append_range(B->Refs, Children);
  return get(B->build());
}

Expected<DIEDedupeTopLevelRef>
DIEDedupeTopLevelRef::create(MCCASBuilder &MB,
                             ArrayRef<cas::ObjectRef> Children) {
  Expected<Builder> B = Builder::startNode(MB.Schema, KindString);
  if (!B)
    return B.takeError();
  append_range(B->Refs, Children);
  return get(B->build());
}

// Returns true if DIE should be placed in a separate CAS block.
static bool shouldCreateSeparateBlockFor(DWARFDie &DIE) {
  dwarf::Tag Tag = DIE.getTag();

  if (Tag == dwarf::Tag::DW_TAG_subprogram) {
    // Only split on subprogram definitions, so look for low_pc.
    for (const DWARFAttribute &AttrValue : DIE.attributes())
      if (AttrValue.Attr == dwarf::Attribute::DW_AT_low_pc)
        return true;
    return false;
  }

  if (Tag == dwarf::Tag::DW_TAG_enumeration_type)
    return true;

  if (Tag == dwarf::Tag::DW_TAG_structure_type ||
      Tag == dwarf::Tag::DW_TAG_class_type) {
    // Don't split on declarations, as these are short
    for (const DWARFAttribute &AttrValue : DIE.attributes())
      if (AttrValue.Attr == dwarf::Attribute::DW_AT_declaration)
        return false;
    return true;
  }

  return false;
}

static void writeDIEAttrs(DWARFDie &DIE, ArrayRef<char> DebugInfoData,
                          DIEDataWriter &DIEWriter,
                          DistinctDataWriter &DistinctWriter,
                          bool IsLittleEndian, uint8_t AddressSize) {
  for (const DWARFAttribute &AttrValue : DIE.attributes()) {
    dwarf::Attribute Attr = AttrValue.Attr;
    dwarf::Form Form = AttrValue.Value.getForm();
    ArrayRef<char> FormData =
        DebugInfoData.slice(AttrValue.Offset, AttrValue.ByteSize);
    auto &WriterToUse = doesntDedup(Form, Attr)
                            ? static_cast<DataWriter &>(DistinctWriter)
                            : DIEWriter;
    if (Form == dwarf::Form::DW_FORM_ref4 || Form == dwarf::Form::DW_FORM_strp)
      convertFourByteFormDataToULEB(FormData, WriterToUse, IsLittleEndian,
                                    AddressSize);
    else
      WriterToUse.writeData(FormData);
  }
}

static void
pushNewDIEWriter(SmallVectorImpl<std::unique_ptr<DIEDataWriter>> &DIEWriters) {
  auto DIEWriter = std::make_unique<DIEDataWriter>();
  DIEWriters.push_back(std::move(DIEWriter));
}

/// Creates an abbreviation for DIE using AbbrevWriter.
/// Stores the contents of the DIE using DistinctWriter and DIEWriter following
/// the format:
///   [abbreviation_index, raw_data?]+
/// * abbreviation_index is always written with DistinctWriter.
/// * raw_data, when present, may be written to either DistinctWriter or
/// DIEWriter, depending on deduplication choices made.
/// * If abbreviation_index is getEndOfDIESiblingsMarker(), raw_data is empty and
/// this denotes the end of a sequence of sibling DIEs.
/// * If abbreviation_index is getDIEInAnotherBlockMarker(), raw_data is empty
/// and this denotes a DIE placed in a child CAS block.
/// * Otherwise, abbreviation_index is an index into the list of references of a
/// DIEAbbrevSetRef block. In this case, raw_data should be interpreted
/// according to the corresponding DIEAbbrevRefs block.
Error DIEToCASConverter::convertImpl(
    DWARFDie DIE, DistinctDataWriter &DistinctWriter,
    AbbrevSetWriter &AbbrevWriter,
    SmallVectorImpl<std::unique_ptr<DIEDataWriter>> &DIEWriters) {
  SmallVector<ParentAndChildDIE> DIEStack;
  pushNewDIEWriter(DIEWriters);
  DIEStack.push_back({DIE, false, *DIEWriters.back(), std::nullopt});
  while (!DIEStack.empty()) {
    auto ParentAndChild = DIEStack.pop_back_val();
    DWARFDie CurrDIE = ParentAndChild.Parent;

    if (!ParentAndChild.ParentAlreadyWritten) {
      Expected<unsigned> MaybeAbbrevIndex =
          AbbrevWriter.createAbbrevEntry(CurrDIE, CASBuilder);
      if (!MaybeAbbrevIndex)
        return MaybeAbbrevIndex.takeError();

      DistinctWriter.writeULEB128(encodeAbbrevIndex(*MaybeAbbrevIndex));
      writeDIEAttrs(CurrDIE, DebugInfoData, ParentAndChild.Writer,
                    DistinctWriter, IsLittleEndian, AddressSize);
    }

    DWARFDie Child = ParentAndChild.Child ? ParentAndChild.Child->getSibling()
                                          : CurrDIE.getFirstChild();
    if (Child) {
      dwarf::Tag ChildTag = Child.getTag();
      if (ChildTag == dwarf::Tag::DW_TAG_null)
        DistinctWriter.writeULEB128(getEndOfDIESiblingsMarker());
      else if (shouldCreateSeparateBlockFor(Child)) {
        DistinctWriter.writeULEB128(getDIEInAnotherBlockMarker());
        DIEStack.push_back({CurrDIE, true, ParentAndChild.Writer, Child});
        pushNewDIEWriter(DIEWriters);
        DIEStack.push_back({Child, false, *DIEWriters.back(), std::nullopt});
      } else {
        DIEStack.push_back({CurrDIE, true, ParentAndChild.Writer, Child});
        DIEStack.push_back({Child, false, ParentAndChild.Writer, std::nullopt});
      }
    }
  }
  return Error::success();
}

Expected<DIETopLevelRef>
DIEToCASConverter::convert(DWARFDie DIE, ArrayRef<char> HeaderData,
                           AbbrevSetWriter &AbbrevWriter) {
  DistinctDataWriter DistinctWriter;
  DistinctWriter.writeData(HeaderData);
  SmallVector<std::unique_ptr<DIEDataWriter>> DIEWriters;
  if (Error E = convertImpl(DIE, DistinctWriter, AbbrevWriter, DIEWriters))
    return std::move(E);

  Expected<DIEAbbrevSetRef> MaybeAbbrevSet =
      AbbrevWriter.endAbbrevSet(CASBuilder);
  if (!MaybeAbbrevSet)
    return MaybeAbbrevSet.takeError();
  Expected<DIEDistinctDataRef> MaybeDistinct =
      DistinctWriter.getCASNode(CASBuilder);
  if (!MaybeDistinct)
    return MaybeDistinct.takeError();

  SmallVector<cas::ObjectRef> DIERefs;
  DIERefs.reserve(DIEWriters.size());
  for (auto &Writer : DIEWriters) {
    Expected<DIEDataRef> DIERef = Writer->getCASNode(CASBuilder);
    if (!DIERef)
      return DIERef.takeError();
    DIERefs.push_back(DIERef->getRef());
  }

  auto TopDIERef = DIEDedupeTopLevelRef::create(CASBuilder, DIERefs);
  if (!TopDIERef)
    return TopDIERef.takeError();
  SmallVector<cas::ObjectRef, 3> Refs{
      TopDIERef->getRef(), MaybeAbbrevSet->getRef(), MaybeDistinct->getRef()};
  return DIETopLevelRef::create(CASBuilder, Refs);
}

Expected<LoadedDIETopLevel>
mccasformats::v1::loadDIETopLevel(DIETopLevelRef TopLevelRef) {
  if (TopLevelRef.getNumReferences() != 3)
    return createStringError(
        inconvertibleErrorCode(),
        "TopLevelRef is expected to have three references");

  const MCSchema &Schema = TopLevelRef.getSchema();
  Expected<DIEDedupeTopLevelRef> RootDIE =
      DIEDedupeTopLevelRef::get(Schema, TopLevelRef.getReference(0));
  Expected<DIEAbbrevSetRef> AbbrevSet =
      DIEAbbrevSetRef::get(Schema, TopLevelRef.getReference(1));
  Expected<DIEDistinctDataRef> DistinctData =
      DIEDistinctDataRef::get(Schema, TopLevelRef.getReference(2));
  if (!RootDIE)
    return RootDIE.takeError();
  if (!AbbrevSet)
    return AbbrevSet.takeError();
  if (!DistinctData)
    return DistinctData.takeError();

  auto MaybeAbbrevEntries = loadAllRefs<DIEAbbrevRef>(*AbbrevSet);
  if (!MaybeAbbrevEntries)
    return MaybeAbbrevEntries.takeError();
  SmallVector<StringRef, 0> AbbrevData(map_range(
      *MaybeAbbrevEntries, [](DIEAbbrevRef Ref) { return Ref.getData(); }));
  return LoadedDIETopLevel{std::move(AbbrevData), *DistinctData,
                           *RootDIE};
}

struct DIEVisitor {

  struct AbbrevContent {
    dwarf::Attribute Attr;
    dwarf::Form Form;
    bool FormInDistinctData;
    std::optional<uint8_t> FormSize;
  };

  struct AbbrevEntry {
    dwarf::Tag Tag;
    bool HasChildren;
    SmallVector<AbbrevContent> AbbrevContents;
  };

  Error visitDIERef(DIEDedupeTopLevelRef Ref);
  Error visitDIERef(ArrayRef<DIEDataRef> &DIEChildrenStack);
  Error visitDIEAttrs(DataExtractor &Extractor, DataExtractor::Cursor &Cursor,
                      StringRef DIEData, ArrayRef<AbbrevContent> DIEContents);
  Error materializeAbbrevDIE(unsigned AbbrevIdx);

  uint16_t DwarfVersion;
  SmallVector<AbbrevEntry> AbbrevEntryCache;
  ArrayRef<StringRef> AbbrevEntries;
  DataExtractor DistinctExtractor;
  DataExtractor::Cursor DistinctCursor;
  StringRef DistinctData;

  std::function<void(StringRef)> HeaderCallback;
  std::function<void(dwarf::Tag, uint64_t)> StartTagCallback;
  std::function<void(dwarf::Attribute, dwarf::Form, StringRef, bool)>
      AttrCallback;
  std::function<void(bool)> EndTagCallback;
  std::function<void(StringRef)> NewBlockCallback;
};

Error DIEVisitor::visitDIEAttrs(DataExtractor &Extractor,
                                DataExtractor::Cursor &Cursor,
                                StringRef DIEData,
                                ArrayRef<AbbrevContent> DIEContents) {
  constexpr auto IsLittleEndian = true;
  auto FormParams = dwarf::FormParams{DwarfVersion, Extractor.getAddressSize(),
                                      dwarf::DwarfFormat::DWARF32};

  for (auto Contents : DIEContents) {
    bool DataInDistinct = Contents.FormInDistinctData;
    auto &ExtractorForData = DataInDistinct ? DistinctExtractor : Extractor;
    auto &CursorForData = DataInDistinct ? DistinctCursor : Cursor;
    StringRef DataToUse = DataInDistinct ? DistinctData : DIEData;
    Expected<uint64_t> FormSize =
        Contents.FormSize ? *Contents.FormSize
                          : getFormSize(Contents.Form, FormParams, DataToUse,
                                        CursorForData.tell(), IsLittleEndian,
                                        Extractor.getAddressSize());
    if (!FormSize)
      return FormSize.takeError();

    StringRef RawBytes;
    if (*FormSize)
      RawBytes = ExtractorForData.getBytes(CursorForData, *FormSize);
    if (!CursorForData)
      return CursorForData.takeError();
    AttrCallback(Contents.Attr, Contents.Form, RawBytes, DataInDistinct);
  }
  return Error::success();
}

static Expected<uint64_t> readAbbrevIdx(DataExtractor &Extractor,
                                        DataExtractor::Cursor &Cursor) {
  uint64_t Idx = Extractor.getULEB128(Cursor);
  if (!Cursor)
    return Cursor.takeError();
  return Idx;
}

static AbbrevEntryReader getAbbrevEntryReader(ArrayRef<StringRef> AbbrevEntries,
                                              unsigned AbbrevIdx,
                                              bool IsLittleEndian,
                                              uint8_t AddressSize) {
  StringRef AbbrevData =
      AbbrevEntries[decodeAbbrevIndexAsAbbrevSetIdx(AbbrevIdx)];
  return AbbrevEntryReader(AbbrevData, IsLittleEndian, AddressSize);
}

static std::optional<uint8_t> getNonULEBFormSize(dwarf::Form Form,
                                                 dwarf::FormParams FP) {
  switch (Form) {
  case dwarf::DW_FORM_addr:
    return FP.AddrSize;
  case dwarf::DW_FORM_ref_addr:
    return FP.getRefAddrByteSize();
  case dwarf::DW_FORM_exprloc:
  case dwarf::DW_FORM_block:
  case dwarf::DW_FORM_block1:
  case dwarf::DW_FORM_block2:
  case dwarf::DW_FORM_block4:
  case dwarf::DW_FORM_sdata:
  case dwarf::DW_FORM_udata:
  case dwarf::DW_FORM_ref_udata:
  case dwarf::DW_FORM_ref4_cas:
  case dwarf::DW_FORM_strp_cas:
  case dwarf::DW_FORM_rnglistx:
  case dwarf::DW_FORM_loclistx:
  case dwarf::DW_FORM_GNU_addr_index:
  case dwarf::DW_FORM_GNU_str_index:
  case dwarf::DW_FORM_addrx:
  case dwarf::DW_FORM_strx:
  case dwarf::DW_FORM_LLVM_addrx_offset:
  case dwarf::DW_FORM_string:
  case dwarf::DW_FORM_indirect:
    return std::nullopt;

  case dwarf::DW_FORM_implicit_const:
  case dwarf::DW_FORM_flag_present:
    return 0;
  case dwarf::DW_FORM_data1:
  case dwarf::DW_FORM_ref1:
  case dwarf::DW_FORM_flag:
  case dwarf::DW_FORM_strx1:
  case dwarf::DW_FORM_addrx1:
    return 1;
  case dwarf::DW_FORM_data2:
  case dwarf::DW_FORM_ref2:
  case dwarf::DW_FORM_strx2:
  case dwarf::DW_FORM_addrx2:
    return 2;
  case dwarf::DW_FORM_strx3:
    return 3;
  case dwarf::DW_FORM_data4:
  case dwarf::DW_FORM_ref4:
  case dwarf::DW_FORM_ref_sup4:
  case dwarf::DW_FORM_strx4:
  case dwarf::DW_FORM_addrx4:
    return 4;
  case dwarf::DW_FORM_ref_sig8:
  case dwarf::DW_FORM_data8:
  case dwarf::DW_FORM_ref8:
  case dwarf::DW_FORM_ref_sup8:
    return 8;
  case dwarf::DW_FORM_data16:
    return 16;
  case dwarf::DW_FORM_strp:
  case dwarf::DW_FORM_sec_offset:
  case dwarf::DW_FORM_GNU_ref_alt:
  case dwarf::DW_FORM_GNU_strp_alt:
  case dwarf::DW_FORM_line_strp:
  case dwarf::DW_FORM_strp_sup:
    return FP.getDwarfOffsetByteSize();
  case dwarf::DW_FORM_addrx3:
  case dwarf::DW_FORM_lo_user:
    llvm_unreachable("usupported form");
    break;
  }
}

Error DIEVisitor::materializeAbbrevDIE(unsigned AbbrevIdx) {
  auto FormParams =
      dwarf::FormParams{DwarfVersion, DistinctExtractor.getAddressSize(),
                        dwarf::DwarfFormat::DWARF32};

  AbbrevEntryReader AbbrevReader = getAbbrevEntryReader(
      AbbrevEntries, AbbrevIdx, DistinctExtractor.isLittleEndian(),
      DistinctExtractor.getAddressSize());
  Expected<dwarf::Tag> MaybeTag = AbbrevReader.readTag();
  if (!MaybeTag)
    return MaybeTag.takeError();

  Expected<bool> MaybeHasChildren = AbbrevReader.readHasChildren();
  if (!MaybeHasChildren)
    return MaybeHasChildren.takeError();

  SmallVector<AbbrevContent> AbbrevVector;
  while (true) {
    Expected<dwarf::Attribute> Attr = AbbrevReader.readAttr();
    if (!Attr)
      return Attr.takeError();
    if (*Attr == getEndOfAttributesMarker())
      break;

    Expected<dwarf::Form> Form = AbbrevReader.readForm();
    if (!Form)
      return Form.takeError();
    AbbrevVector.push_back({*Attr, *Form, doesntDedup(*Form, *Attr),
                            getNonULEBFormSize(*Form, FormParams)});
  }
  AbbrevEntryCache.push_back(
      {*MaybeTag, *MaybeHasChildren, std::move(AbbrevVector)});
  return Error::success();
}

/// Restores the state of the \p Reader and \p Data
/// arguments to a previous state. The algorithm in visitDIERefs is an iterative
/// implementation of a Depth First Search, and this function is used to
/// simulate a return from a recursive callback, by restoring the locals to a
/// previous stack frame.
static void popStack(DataExtractor &Extractor, DataExtractor::Cursor &Cursor,
                     StringRef &Data,
                     std::stack<std::pair<StringRef, unsigned>> &StackOfNodes,
                     uint8_t AddressSize) {
  auto DataAndOffset = StackOfNodes.top();
  Extractor = DataExtractor(DataAndOffset.first, Extractor.isLittleEndian(),
                            AddressSize);
  Data = DataAndOffset.first;
  Cursor.seek(DataAndOffset.second);
  StackOfNodes.pop();
}

// Visit DIERef CAS objects and materialize them.
Error DIEVisitor::visitDIERef(ArrayRef<DIEDataRef> &DIEChildrenStack) {

  for (unsigned I = 0; I < AbbrevEntries.size(); I++)
    if (Error E = materializeAbbrevDIE(encodeAbbrevIndex(I)))
      return E;

  std::stack<std::pair<StringRef, unsigned>> StackOfNodes;
  auto Data = DIEChildrenStack.empty() ? StringRef()
                                       : DIEChildrenStack.front().getData();
  DataExtractor Extractor(Data, DistinctExtractor.isLittleEndian(),
                          DistinctExtractor.getAddressSize());
  DataExtractor::Cursor Cursor(0);

  while (!DistinctExtractor.eof(DistinctCursor)) {

    Expected<uint64_t> MaybeAbbrevIdx =
        readAbbrevIdx(DistinctExtractor, DistinctCursor);
    if (!MaybeAbbrevIdx)
      return MaybeAbbrevIdx.takeError();
    auto AbbrevIdx = *MaybeAbbrevIdx;

    // If we see a EndOfDIESiblingsMarker, we know that this sequence of
    // Children has no more siblings and we need to pop the StackOfNodes and
    // continue materialization of the parent's siblings that may exist.
    if (AbbrevIdx == getEndOfDIESiblingsMarker()) {
      EndTagCallback(true /*HadChildren*/);
      if (!StackOfNodes.empty() && Extractor.eof(Cursor))
        popStack(Extractor, Cursor, Data, StackOfNodes,
                 DistinctExtractor.getAddressSize());
      continue;
    }

    // If we see a DIEInAnotherBlockMarker, we know that the next DIE is in
    // another CAS Block, we have to push the current CAS Object on the stack,
    // and materialize the next DIE from the DIEChildrenStack.
    if (AbbrevIdx == getDIEInAnotherBlockMarker()) {
      StackOfNodes.push(std::make_pair(Data, Cursor.tell()));
      DIEChildrenStack = DIEChildrenStack.drop_front();
      Data = DIEChildrenStack.front().getData();
      NewBlockCallback(DIEChildrenStack.front().getID().toString());
      Extractor = DataExtractor(Data, DistinctExtractor.isLittleEndian(),
                                DistinctExtractor.getAddressSize());
      Cursor.seek(0);
      continue;
    }

    // If we have a legitimate AbbrevIdx, materialize the current DIE.
    auto &AbbrevEntryCacheVal =
        AbbrevEntryCache[decodeAbbrevIndexAsAbbrevSetIdx(AbbrevIdx)];
    StartTagCallback(AbbrevEntryCacheVal.Tag, AbbrevIdx);

    if (auto E = visitDIEAttrs(Extractor, Cursor, Data,
                               AbbrevEntryCacheVal.AbbrevContents))
      return E;

    // If the current DIE doesn't have any children, the current CAS Object will
    // not contain any more data, pop the stack to continue materializing its
    // parent's siblings that may exist.
    if (!AbbrevEntryCacheVal.HasChildren) {
      if (!StackOfNodes.empty() && Extractor.eof(Cursor))
        popStack(Extractor, Cursor, Data, StackOfNodes,
                 DistinctExtractor.getAddressSize());
      EndTagCallback(false /*HadChildren*/);
    }
  }
  return Error::success();
}

Error DIEVisitor::visitDIERef(DIEDedupeTopLevelRef StartDIERef) {

  auto Offset = DistinctCursor.tell();
  Expected<uint64_t> MaybeAbbrevIdx =
      readAbbrevIdx(DistinctExtractor, DistinctCursor);
  if (!MaybeAbbrevIdx)
    return MaybeAbbrevIdx.takeError();
  auto AbbrevIdx = *MaybeAbbrevIdx;
  // The tag of a fresh block must be meaningful, otherwise we wouldn't have
  // made a new block.
  assert(AbbrevIdx != getEndOfDIESiblingsMarker() &&
         AbbrevIdx != getDIEInAnotherBlockMarker());

  DistinctCursor.seek(Offset);

  NewBlockCallback(StartDIERef.getID().toString());

  Expected<SmallVector<DIEDataRef>> MaybeChildren =
      loadAllRefs<DIEDataRef>(StartDIERef);
  if (!MaybeChildren)
    return MaybeChildren.takeError();
  ArrayRef<DIEDataRef> Children = *MaybeChildren;

  return visitDIERef(Children);
}

Error mccasformats::v1::visitDebugInfo(
    SmallVectorImpl<StringRef> &TotAbbrevEntries,
    Expected<DIETopLevelRef> MaybeTopLevelRef,
    std::function<void(StringRef)> HeaderCallback,
    std::function<void(dwarf::Tag, uint64_t)> StartTagCallback,
    std::function<void(dwarf::Attribute, dwarf::Form, StringRef, bool)>
        AttrCallback,
    std::function<void(bool)> EndTagCallback, bool IsLittleEndian,
    uint8_t AddressSize, std::function<void(StringRef)> NewBlockCallback) {

  Expected<LoadedDIETopLevel> LoadedTopRef =
      loadDIETopLevel(std::move(MaybeTopLevelRef));
  if (!LoadedTopRef)
    return LoadedTopRef.takeError();

  StringRef DistinctData = LoadedTopRef->DistinctData.getData();
#if LLVM_ENABLE_ZLIB
  ArrayRef<uint8_t> BuffRef = arrayRefFromStringRef(DistinctData);
  auto UncompressedSize = decodeULEB128(BuffRef.data() + BuffRef.size() - 8);
  BuffRef = BuffRef.drop_back(8);
  SmallVector<uint8_t> OutBuff;
  if (auto E =
          compression::zlib::decompress(BuffRef, OutBuff, UncompressedSize))
    return E;
  DistinctData = toStringRef(OutBuff);
#endif
  DataExtractor DistinctExtractor(DistinctData, IsLittleEndian, AddressSize);
  DataExtractor::Cursor DistinctCursor(0);

  auto Size = getSizeFromDwarfHeader(DistinctExtractor, DistinctCursor);
  if (!Size)
    return Size.takeError();

  // 2-byte Dwarf version identifier.
  uint16_t DwarfVersion = DistinctExtractor.getU16(DistinctCursor);
  DistinctCursor.seek(0);

  StringRef HeaderData = DistinctExtractor.getBytes(
      DistinctCursor,
      DwarfVersion >= 5 ? Dwarf5HeaderSize32Bit : Dwarf4HeaderSize32Bit);
  if (!DistinctCursor)
    return DistinctCursor.takeError();
  HeaderCallback(HeaderData);

  append_range(TotAbbrevEntries, LoadedTopRef->AbbrevEntries);
  DIEVisitor Visitor{DwarfVersion,
                     {},
                     TotAbbrevEntries,
                     DistinctExtractor,
                     DataExtractor::Cursor(DistinctCursor.tell()),
                     DistinctData,
                     HeaderCallback,
                     StartTagCallback,
                     AttrCallback,
                     EndTagCallback,
                     NewBlockCallback};
  return Visitor.visitDIERef(LoadedTopRef->RootDIE);
}