llvm.org GIT mirror llvm / b6b924e lib / Demangle / MicrosoftDemangle.cpp
b6b924e

Tree @b6b924e (Download .tar.gz)

MicrosoftDemangle.cpp @b6b924eraw · history · blame

   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
//===- MicrosoftDemangle.cpp ----------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines a demangler for MSVC-style mangled symbols.
//
// This file has no dependencies on the rest of LLVM so that it can be
// easily reused in other programs such as libcxxabi.
//
//===----------------------------------------------------------------------===//

#include "llvm/Demangle/Demangle.h"

#include "llvm/Demangle/Compiler.h"
#include "llvm/Demangle/StringView.h"
#include "llvm/Demangle/Utility.h"

#include <array>
#include <cctype>
#include <cstdio>
#include <tuple>

// This memory allocator is extremely fast, but it doesn't call dtors
// for allocated objects. That means you can't use STL containers
// (such as std::vector) with this allocator. But it pays off --
// the demangler is 3x faster with this allocator compared to one with
// STL containers.
namespace {
  constexpr size_t AllocUnit = 4096;

class ArenaAllocator {
  struct AllocatorNode {
    uint8_t *Buf = nullptr;
    size_t Used = 0;
    size_t Capacity = 0;
    AllocatorNode *Next = nullptr;
  };

  void addNode(size_t Capacity) {
    AllocatorNode *NewHead = new AllocatorNode;
    NewHead->Buf = new uint8_t[Capacity];
    NewHead->Next = Head;
    NewHead->Capacity = Capacity;
    Head = NewHead;
    NewHead->Used = 0;
  }

public:
  ArenaAllocator() { addNode(AllocUnit); }

  ~ArenaAllocator() {
    while (Head) {
      assert(Head->Buf);
      delete[] Head->Buf;
      AllocatorNode *Next = Head->Next;
      delete Head;
      Head = Next;
    }
  }

  char *allocUnalignedBuffer(size_t Length) {
    uint8_t *Buf = Head->Buf + Head->Used;

    Head->Used += Length;
    if (Head->Used > Head->Capacity) {
      // It's possible we need a buffer which is larger than our default unit
      // size, so we need to be careful to add a node with capacity that is at
      // least as large as what we need.
      addNode(std::max(AllocUnit, Length));
      Head->Used = Length;
      Buf = Head->Buf;
    }

    return reinterpret_cast<char *>(Buf);
  }

  template <typename T, typename... Args> T *alloc(Args &&... ConstructorArgs) {

    size_t Size = sizeof(T);
    assert(Head && Head->Buf);

    size_t P = (size_t)Head->Buf + Head->Used;
    uintptr_t AlignedP =
        (((size_t)P + alignof(T) - 1) & ~(size_t)(alignof(T) - 1));
    uint8_t *PP = (uint8_t *)AlignedP;
    size_t Adjustment = AlignedP - P;

    Head->Used += Size + Adjustment;
    if (Head->Used < Head->Capacity)
      return new (PP) T(std::forward<Args>(ConstructorArgs)...);

    addNode(AllocUnit);
    Head->Used = Size;
    return new (Head->Buf) T(std::forward<Args>(ConstructorArgs)...);
  }

private:
  AllocatorNode *Head = nullptr;
};
} // namespace

static bool startsWithDigit(StringView S) {
  return !S.empty() && std::isdigit(S.front());
}

// Writes a space if the last token does not end with a punctuation.
static void outputSpaceIfNecessary(OutputStream &OS) {
  if (OS.empty())
    return;

  char C = OS.back();
  if (isalnum(C) || C == '>')
    OS << " ";
}

// Storage classes
enum Qualifiers : uint8_t {
  Q_None = 0,
  Q_Const = 1 << 0,
  Q_Volatile = 1 << 1,
  Q_Far = 1 << 2,
  Q_Huge = 1 << 3,
  Q_Unaligned = 1 << 4,
  Q_Restrict = 1 << 5,
  Q_Pointer64 = 1 << 6
};

enum class StorageClass : uint8_t {
  None,
  PrivateStatic,
  ProtectedStatic,
  PublicStatic,
  Global,
  FunctionLocalStatic,
};

enum class QualifierMangleMode { Drop, Mangle, Result };

enum class PointerAffinity { Pointer, Reference, RValueReference };

// Calling conventions
enum class CallingConv : uint8_t {
  None,
  Cdecl,
  Pascal,
  Thiscall,
  Stdcall,
  Fastcall,
  Clrcall,
  Eabi,
  Vectorcall,
  Regcall,
};

enum class ReferenceKind : uint8_t { None, LValueRef, RValueRef };

// Types
enum class PrimTy : uint8_t {
  Unknown,
  None,
  Function,
  Ptr,
  MemberPtr,
  Array,

  Struct,
  Union,
  Class,
  Enum,

  Void,
  Bool,
  Char,
  Schar,
  Uchar,
  Char16,
  Char32,
  Short,
  Ushort,
  Int,
  Uint,
  Long,
  Ulong,
  Int64,
  Uint64,
  Wchar,
  Float,
  Double,
  Ldouble,
  Nullptr,
  Vftable,
  Vbtable,
  LocalStaticGuard
};

enum class OperatorTy : uint8_t {
  Ctor,                    // ?0 # Foo::Foo()
  Dtor,                    // ?1 # Foo::~Foo()
  New,                     // ?2 # operator new
  Delete,                  // ?3 # operator delete
  Assign,                  // ?4 # operator=
  RightShift,              // ?5 # operator>>
  LeftShift,               // ?6 # operator<<
  LogicalNot,              // ?7 # operator!
  Equals,                  // ?8 # operator==
  NotEquals,               // ?9 # operator!=
  ArraySubscript,          // ?A # operator[]
  Conversion,              // ?B # Foo::operator <type>()
  Pointer,                 // ?C # operator->
  Dereference,             // ?D # operator*
  Increment,               // ?E # operator++
  Decrement,               // ?F # operator--
  Minus,                   // ?G # operator-
  Plus,                    // ?H # operator+
  BitwiseAnd,              // ?I # operator&
  MemberPointer,           // ?J # operator->*
  Divide,                  // ?K # operator/
  Modulus,                 // ?L # operator%
  LessThan,                // ?M operator<
  LessThanEqual,           // ?N operator<=
  GreaterThan,             // ?O operator>
  GreaterThanEqual,        // ?P operator>=
  Comma,                   // ?Q operator,
  Parens,                  // ?R operator()
  BitwiseNot,              // ?S operator~
  BitwiseXor,              // ?T operator^
  BitwiseOr,               // ?U operator|
  LogicalAnd,              // ?V operator&&
  LogicalOr,               // ?W operator||
  TimesEqual,              // ?X operator*=
  PlusEqual,               // ?Y operator+=
  MinusEqual,              // ?Z operator-=
  DivEqual,                // ?_0 operator/=
  ModEqual,                // ?_1 operator%=
  RshEqual,                // ?_2 operator>>=
  LshEqual,                // ?_3 operator<<=
  BitwiseAndEqual,         // ?_4 operator&=
  BitwiseOrEqual,          // ?_5 operator|=
  BitwiseXorEqual,         // ?_6 operator^=
  Vftable,                 // ?_7 # vftable
  Vbtable,                 // ?_8 # vbtable
  Vcall,                   // ?_9 # vcall
  Typeof,                  // ?_A # typeof
  LocalStaticGuard,        // ?_B # local static guard
  StringLiteral,           // ?_C # string literal
  VbaseDtor,               // ?_D # vbase destructor
  VecDelDtor,              // ?_E # vector deleting destructor
  DefaultCtorClosure,      // ?_F # default constructor closure
  ScalarDelDtor,           // ?_G # scalar deleting destructor
  VecCtorIter,             // ?_H # vector constructor iterator
  VecDtorIter,             // ?_I # vector destructor iterator
  VecVbaseCtorIter,        // ?_J # vector vbase constructor iterator
  VdispMap,                // ?_K # virtual displacement map
  EHVecCtorIter,           // ?_L # eh vector constructor iterator
  EHVecDtorIter,           // ?_M # eh vector destructor iterator
  EHVecVbaseCtorIter,      // ?_N # eh vector vbase constructor iterator
  CopyCtorClosure,         // ?_O # copy constructor closure
  UdtReturning,            // ?_P<name> # udt returning <name>
  Unknown,                 // ?_Q # <unknown>
  RttiTypeDescriptor,      // ?_R0 # RTTI Type Descriptor
  RttiBaseClassDescriptor, // ?_R1 # RTTI Base Class Descriptor at (a,b,c,d)
  RttiBaseClassArray,      // ?_R2 # RTTI Base Class Array
  RttiClassHierarchyDescriptor, // ?_R3 # RTTI Class Hierarchy Descriptor
  RttiCompleteObjLocator,       // ?_R4 # RTTI Complete Object Locator
  LocalVftable,                 // ?_S # local vftable
  LocalVftableCtorClosure,      // ?_T # local vftable constructor closure
  ArrayNew,                     // ?_U operator new[]
  ArrayDelete,                  // ?_V operator delete[]
  LiteralOperator,              // ?__K operator ""_name
  CoAwait,                      // ?__L co_await
  Spaceship,                    // operator<=>
};

// A map to translate from operator prefix to operator type.
struct OperatorMapEntry {
  StringView Prefix;
  StringView Name;
  OperatorTy Operator;
};

// The entries here must be in the same order as the enumeration so that it can
// be indexed by enum value.
OperatorMapEntry OperatorMap[] = {
    {"0", " <ctor>", OperatorTy::Ctor},
    {"1", " <dtor>", OperatorTy::Dtor},
    {"2", "operator new", OperatorTy::New},
    {"3", "operator delete", OperatorTy::Delete},
    {"4", "operator=", OperatorTy::Assign},
    {"5", "operator>>", OperatorTy::RightShift},
    {"6", "operator<<", OperatorTy::LeftShift},
    {"7", "operator!", OperatorTy::LogicalNot},
    {"8", "operator==", OperatorTy::Equals},
    {"9", "operator!=", OperatorTy::NotEquals},
    {"A", "operator[]", OperatorTy::ArraySubscript},
    {"B", "operator <conversion>", OperatorTy::Conversion},
    {"C", "operator->", OperatorTy::Pointer},
    {"D", "operator*", OperatorTy::Dereference},
    {"E", "operator++", OperatorTy::Increment},
    {"F", "operator--", OperatorTy::Decrement},
    {"G", "operator-", OperatorTy::Minus},
    {"H", "operator+", OperatorTy::Plus},
    {"I", "operator&", OperatorTy::BitwiseAnd},
    {"J", "operator->*", OperatorTy::MemberPointer},
    {"K", "operator/", OperatorTy::Divide},
    {"L", "operator%", OperatorTy::Modulus},
    {"M", "operator<", OperatorTy::LessThan},
    {"N", "operator<=", OperatorTy::LessThanEqual},
    {"O", "operator>", OperatorTy::GreaterThan},
    {"P", "operator>=", OperatorTy::GreaterThanEqual},
    {"Q", "operator,", OperatorTy::Comma},
    {"R", "operator()", OperatorTy::Parens},
    {"S", "operator~", OperatorTy::BitwiseNot},
    {"T", "operator^", OperatorTy::BitwiseXor},
    {"U", "operator|", OperatorTy::BitwiseOr},
    {"V", "operator&&", OperatorTy::LogicalAnd},
    {"W", "operator||", OperatorTy::LogicalOr},
    {"X", "operator*=", OperatorTy::TimesEqual},
    {"Y", "operator+=", OperatorTy::PlusEqual},
    {"Z", "operator-=", OperatorTy::MinusEqual},
    {"_0", "operator/=", OperatorTy::DivEqual},
    {"_1", "operator%=", OperatorTy::ModEqual},
    {"_2", "operator>>=", OperatorTy::RshEqual},
    {"_3", "operator<<=", OperatorTy::LshEqual},
    {"_4", "operator&=", OperatorTy::BitwiseAndEqual},
    {"_5", "operator|=", OperatorTy::BitwiseOrEqual},
    {"_6", "operator^=", OperatorTy::BitwiseXorEqual},
    {"_7", "`vftable'", OperatorTy::Vftable},
    {"_8", "`vbtable'", OperatorTy::Vbtable},
    {"_9", "`vcall'", OperatorTy::Vcall},
    {"_A", "`typeof'", OperatorTy::Typeof},
    {"_B", "`local static guard'", OperatorTy::LocalStaticGuard},
    {"_C", "`string'", OperatorTy::StringLiteral},
    {"_D", "`vbase dtor'", OperatorTy::VbaseDtor},
    {"_E", "`vector deleting dtor'", OperatorTy::VecDelDtor},
    {"_F", "`default ctor closure'", OperatorTy::DefaultCtorClosure},
    {"_G", "`scalar deleting dtor'", OperatorTy::ScalarDelDtor},
    {"_H", "`vector ctor iterator'", OperatorTy::VecCtorIter},
    {"_I", "`vector dtor iterator'", OperatorTy::VecDtorIter},
    {"_J", "`vector vbase ctor iterator'", OperatorTy::VecVbaseCtorIter},
    {"_K", "`virtual displacement map'", OperatorTy::VdispMap},
    {"_L", "`eh vector ctor iterator'", OperatorTy::EHVecCtorIter},
    {"_M", "`eh vector dtor iterator'", OperatorTy::EHVecDtorIter},
    {"_N", "`eh vector vbase ctor iterator'", OperatorTy::EHVecVbaseCtorIter},
    {"_O", "`copy ctor closure'", OperatorTy::CopyCtorClosure},
    {"_P", "`udt returning'", OperatorTy::UdtReturning},
    {"_Q", "`unknown'", OperatorTy::Unknown},
    {"_R0", "`RTTI Type Descriptor'", OperatorTy::RttiTypeDescriptor},
    {"_R1", "RTTI Base Class Descriptor", OperatorTy::RttiBaseClassDescriptor},
    {"_R2", "`RTTI Base Class Array'", OperatorTy::RttiBaseClassArray},
    {"_R3", "`RTTI Class Hierarchy Descriptor'",
     OperatorTy::RttiClassHierarchyDescriptor},
    {"_R4", "`RTTI Complete Object Locator'",
     OperatorTy::RttiCompleteObjLocator},
    {"_S", "`local vftable'", OperatorTy::LocalVftable},
    {"_T", "`local vftable ctor closure'", OperatorTy::LocalVftableCtorClosure},
    {"_U", "operator new[]", OperatorTy::ArrayNew},
    {"_V", "operator delete[]", OperatorTy::ArrayDelete},
    {"__K", "operator \"\"", OperatorTy::LiteralOperator},
    {"__L", "co_await", OperatorTy::CoAwait},
};

// Function classes
enum FuncClass : uint16_t {
  None = 0,
  Public = 1 << 0,
  Protected = 1 << 1,
  Private = 1 << 2,
  Global = 1 << 3,
  Static = 1 << 4,
  Virtual = 1 << 5,
  Far = 1 << 6,
  ExternC = 1 << 7,
  NoPrototype = 1 << 8,
  VirtualThisAdjust = 1 << 9,
  VirtualThisAdjustEx = 1 << 10,
  StaticThisAdjust = 1 << 11
};

enum NameBackrefBehavior : uint8_t {
  NBB_None = 0,          // don't save any names as backrefs.
  NBB_Template = 1 << 0, // save template instanations.
  NBB_Simple = 1 << 1,   // save simple names.
};

enum class SymbolCategory {
  Unknown,
  NamedFunction,
  NamedVariable,
  UnnamedFunction,
  UnnamedVariable,
  SpecialOperator
};

namespace {

struct Type;
struct Name;

struct FunctionParams {
  bool IsVariadic = false;

  Type *Current = nullptr;

  FunctionParams *Next = nullptr;
};

struct TemplateParams {
  bool IsTemplateTemplate = false;
  bool IsAliasTemplate = false;
  bool IsIntegerLiteral = false;
  bool IntegerLiteralIsNegative = false;
  bool IsEmptyParameterPack = false;
  bool PointerToSymbol = false;
  bool NullptrLiteral = false;
  bool DataMemberPointer = false;
  bool ReferenceToSymbol = false;

  int ThunkOffsetCount = 0;
  std::array<int64_t, 3> ThunkOffsets;

  // If IsIntegerLiteral is true, this is a non-type template parameter
  // whose value is contained in this field.
  uint64_t IntegralValue = 0;

  // Type can be null if this is a template template parameter.  In that case
  // only Name will be valid.
  Type *ParamType = nullptr;

  // Name can be valid if this is a template template parameter (see above) or
  // this is a function declaration (e.g. foo<&SomeFunc>).  In the latter case
  // Name contains the name of the function and Type contains the signature.
  Name *ParamName = nullptr;

  TemplateParams *Next = nullptr;
};

// The type class. Mangled symbols are first parsed and converted to
// this type and then converted to string.
struct Type {
  virtual ~Type() {}

  virtual Type *clone(ArenaAllocator &Arena) const;

  // Write the "first half" of a given type.  This is a static functions to
  // give the code a chance to do processing that is common to a subset of
  // subclasses
  static void outputPre(OutputStream &OS, Type &Ty);

  // Write the "second half" of a given type.  This is a static functions to
  // give the code a chance to do processing that is common to a subset of
  // subclasses
  static void outputPost(OutputStream &OS, Type &Ty);

  virtual void outputPre(OutputStream &OS);
  virtual void outputPost(OutputStream &OS);

  // Primitive type such as Int.
  PrimTy Prim = PrimTy::Unknown;

  Qualifiers Quals = Q_None;
  StorageClass Storage = StorageClass::None; // storage class
};

// Represents an identifier which may be a template.
struct Name {
  virtual ~Name() = default;

  bool IsTemplateInstantiation = false;
  bool IsOperator = false;
  bool IsBackReference = false;

  bool isStringLiteralOperatorInfo() const;

  // Name read from an MangledName string.
  StringView Str;

  // Template parameters. Only valid if IsTemplateInstantiation is true.
  TemplateParams *TParams = nullptr;

  // Nested BackReferences (e.g. "A::B::C") are represented as a linked list.
  Name *Next = nullptr;
};

struct OperatorInfo : public Name {
  explicit OperatorInfo(const OperatorMapEntry &Info) : Info(&Info) {
    this->IsOperator = true;
  }
  explicit OperatorInfo(OperatorTy OpType)
      : OperatorInfo(OperatorMap[(int)OpType]) {}

  const OperatorMapEntry *Info = nullptr;
};

struct StringLiteral : public OperatorInfo {
  StringLiteral() : OperatorInfo(OperatorTy::StringLiteral) {}

  PrimTy CharType;
  bool IsTruncated = false;
};

struct RttiBaseClassDescriptor : public OperatorInfo {
  RttiBaseClassDescriptor()
      : OperatorInfo(OperatorTy::RttiBaseClassDescriptor) {}

  uint32_t NVOffset = 0;
  int32_t VBPtrOffset = 0;
  uint32_t VBTableOffset = 0;
  uint32_t Flags = 0;
};

struct LocalStaticGuardVariable : public OperatorInfo {
  LocalStaticGuardVariable() : OperatorInfo(OperatorTy::LocalStaticGuard) {}

  uint32_t ScopeIndex = 0;
  bool IsVisible = false;
};

struct VirtualMemberPtrThunk : public OperatorInfo {
  VirtualMemberPtrThunk() : OperatorInfo(OperatorTy::Vcall) {}

  uint64_t OffsetInVTable = 0;
  CallingConv CC = CallingConv::Cdecl;
};

struct PointerType : public Type {
  Type *clone(ArenaAllocator &Arena) const override;
  void outputPre(OutputStream &OS) override;
  void outputPost(OutputStream &OS) override;

  PointerAffinity Affinity;

  // Represents a type X in "a pointer to X", "a reference to X",
  // "an array of X", or "a function returning X".
  Type *Pointee = nullptr;
};

struct MemberPointerType : public Type {
  Type *clone(ArenaAllocator &Arena) const override;
  void outputPre(OutputStream &OS) override;
  void outputPost(OutputStream &OS) override;

  Name *MemberName = nullptr;

  // Represents a type X in "a pointer to X", "a reference to X",
  // "an array of X", or "a function returning X".
  Type *Pointee = nullptr;
};

struct FunctionType : public Type {
  struct ThisAdjustor {
    uint32_t StaticOffset = 0;
    int32_t VBPtrOffset = 0;
    int32_t VBOffsetOffset = 0;
    int32_t VtordispOffset = 0;
  };

  Type *clone(ArenaAllocator &Arena) const override;
  void outputPre(OutputStream &OS) override;
  void outputPost(OutputStream &OS) override;

  // True if this FunctionType instance is the Pointee of a PointerType or
  // MemberPointerType.
  bool IsFunctionPointer = false;
  bool IsThunk = false;

  Type *ReturnType = nullptr;
  // If this is a reference, the type of reference.
  ReferenceKind RefKind;

  CallingConv CallConvention;
  FuncClass FunctionClass;

  // Valid if IsThunk is true.
  ThisAdjustor *ThisAdjust = nullptr;

  FunctionParams Params;
};

struct UdtType : public Type {
  Type *clone(ArenaAllocator &Arena) const override;
  void outputPre(OutputStream &OS) override;

  Name *UdtName = nullptr;
};

struct ArrayDimension {
  uint64_t Dim = 0;
  ArrayDimension *Next = nullptr;
};

struct ArrayType : public Type {
  Type *clone(ArenaAllocator &Arena) const override;
  void outputPre(OutputStream &OS) override;
  void outputPost(OutputStream &OS) override;

  // Either NextDimension or ElementType will be valid.
  ArrayDimension *Dims = nullptr;

  Type *ElementType = nullptr;
};

} // namespace

static bool isMemberPointer(StringView MangledName) {
  switch (MangledName.popFront()) {
  case '$':
    // This is probably an rvalue reference (e.g. $$Q), and you cannot have an
    // rvalue reference to a member.
    return false;
  case 'A':
    // 'A' indicates a reference, and you cannot have a reference to a member
    // function or member.
    return false;
  case 'P':
  case 'Q':
  case 'R':
  case 'S':
    // These 4 values indicate some kind of pointer, but we still don't know
    // what.
    break;
  default:
    assert(false && "Ty is not a pointer type!");
  }

  // If it starts with a number, then 6 indicates a non-member function
  // pointer, and 8 indicates a member function pointer.
  if (startsWithDigit(MangledName)) {
    assert(MangledName[0] == '6' || MangledName[0] == '8');
    return (MangledName[0] == '8');
  }

  // Remove ext qualifiers since those can appear on either type and are
  // therefore not indicative.
  MangledName.consumeFront('E'); // 64-bit
  MangledName.consumeFront('I'); // restrict
  MangledName.consumeFront('F'); // unaligned

  assert(!MangledName.empty());

  // The next value should be either ABCD (non-member) or QRST (member).
  switch (MangledName.front()) {
  case 'A':
  case 'B':
  case 'C':
  case 'D':
    return false;
  case 'Q':
  case 'R':
  case 'S':
  case 'T':
    return true;
  default:
    assert(false);
  }
  return false;
}

static void outputCallingConvention(OutputStream &OS, CallingConv CC) {
  outputSpaceIfNecessary(OS);

  switch (CC) {
  case CallingConv::Cdecl:
    OS << "__cdecl";
    break;
  case CallingConv::Fastcall:
    OS << "__fastcall";
    break;
  case CallingConv::Pascal:
    OS << "__pascal";
    break;
  case CallingConv::Regcall:
    OS << "__regcall";
    break;
  case CallingConv::Stdcall:
    OS << "__stdcall";
    break;
  case CallingConv::Thiscall:
    OS << "__thiscall";
    break;
  case CallingConv::Eabi:
    OS << "__eabi";
    break;
  case CallingConv::Vectorcall:
    OS << "__vectorcall";
    break;
  case CallingConv::Clrcall:
    OS << "__clrcall";
    break;
  default:
    break;
  }
}

static bool startsWithLocalScopePattern(StringView S) {
  if (!S.consumeFront('?'))
    return false;
  if (S.size() < 2)
    return false;

  size_t End = S.find('?');
  if (End == StringView::npos)
    return false;
  StringView Candidate = S.substr(0, End);
  if (Candidate.empty())
    return false;

  // \?[0-9]\?
  // ?@? is the discriminator 0.
  if (Candidate.size() == 1)
    return Candidate[0] == '@' || (Candidate[0] >= '0' && Candidate[0] <= '9');

  // If it's not 0-9, then it's an encoded number terminated with an @
  if (Candidate.back() != '@')
    return false;
  Candidate = Candidate.dropBack();

  // An encoded number starts with B-P and all subsequent digits are in A-P.
  // Note that the reason the first digit cannot be A is two fold.  First, it
  // would create an ambiguity with ?A which delimits the beginning of an
  // anonymous namespace.  Second, A represents 0, and you don't start a multi
  // digit number with a leading 0.  Presumably the anonymous namespace
  // ambiguity is also why single digit encoded numbers use 0-9 rather than A-J.
  if (Candidate[0] < 'B' || Candidate[0] > 'P')
    return false;
  Candidate = Candidate.dropFront();
  while (!Candidate.empty()) {
    if (Candidate[0] < 'A' || Candidate[0] > 'P')
      return false;
    Candidate = Candidate.dropFront();
  }

  return true;
}

// Write a function or template parameter list.
static void outputParameterList(OutputStream &OS,
                                const FunctionParams &Params) {
  if (!Params.Current) {
    OS << "void";
    return;
  }

  const FunctionParams *Head = &Params;
  while (Head) {
    Type::outputPre(OS, *Head->Current);
    Type::outputPost(OS, *Head->Current);

    Head = Head->Next;

    if (Head)
      OS << ", ";
  }
}

static void outputStringLiteral(OutputStream &OS, const StringLiteral &Str) {
  switch (Str.CharType) {
  case PrimTy::Wchar:
    OS << "const wchar_t * {L\"";
    break;
  case PrimTy::Char:
    OS << "const char * {\"";
    break;
  case PrimTy::Char16:
    OS << "const char16_t * {u\"";
    break;
  case PrimTy::Char32:
    OS << "const char32_t * {U\"";
    break;
  default:
    LLVM_BUILTIN_UNREACHABLE;
  }
  OS << Str.Str << "\"";
  if (Str.IsTruncated)
    OS << "...";
  OS << "}";
}

static void outputName(OutputStream &OS, const Name *TheName, const Type *Ty);

static void outputParameterList(OutputStream &OS,
                                const TemplateParams &Params) {
  if (Params.IsEmptyParameterPack) {
    OS << "<>";
    return;
  }

  OS << "<";
  const TemplateParams *Head = &Params;
  while (Head) {
    // Type can be null if this is a template template parameter,
    // and Name can be null if this is a simple type.

    if (Head->IsIntegerLiteral) {
      if (Head->IntegerLiteralIsNegative)
        OS << '-';
      OS << Head->IntegralValue;
    } else if (Head->PointerToSymbol || Head->ReferenceToSymbol) {
      if (Head->NullptrLiteral)
        OS << "nullptr";
      else {
        if (Head->ThunkOffsetCount > 0)
          OS << "{";
        else if (Head->PointerToSymbol)
          OS << "&";
        if (Head->ParamType)
          Type::outputPre(OS, *Head->ParamType);
        outputName(OS, Head->ParamName, Head->ParamType);
        if (Head->ParamType)
          Type::outputPost(OS, *Head->ParamType);
        if (Head->ThunkOffsetCount > 0) {
          for (int I = 0; I < Head->ThunkOffsetCount; ++I) {
            OS << ", " << Head->ThunkOffsets[I];
          }
          OS << "}";
        }
      }
    } else if (Head->DataMemberPointer) {
      OS << "{" << Head->ThunkOffsets[0];
      for (int I = 1; I < Head->ThunkOffsetCount; ++I)
        OS << ", " << Head->ThunkOffsets[I];
      OS << "}";
    } else if (Head->ParamType) {
      // simple type.
      Type::outputPre(OS, *Head->ParamType);
      Type::outputPost(OS, *Head->ParamType);
    } else {
      // Template alias.
      outputName(OS, Head->ParamName, Head->ParamType);
    }

    Head = Head->Next;

    if (Head)
      OS << ", ";
  }
  OS << ">";
}

static void outputQualifiers(OutputStream &OS, Qualifiers Q) {
  if (Q & Q_Const) {
    outputSpaceIfNecessary(OS);
    OS << "const";
  }

  if (Q & Q_Volatile) {
    outputSpaceIfNecessary(OS);
    OS << "volatile";
  }

  if (Q & Q_Restrict) {
    outputSpaceIfNecessary(OS);
    OS << "__restrict";
  }
}

static void outputNameComponent(OutputStream &OS, const Name &N) {
  OS << N.Str;

  if (N.IsTemplateInstantiation && N.TParams)
    outputParameterList(OS, *N.TParams);
}

static const OperatorInfo *lastComponentAsOperator(const Name *TheName) {
  if (!TheName)
    return nullptr;
  while (TheName->Next)
    TheName = TheName->Next;
  if (TheName->IsOperator)
    return static_cast<const OperatorInfo *>(TheName);
  return nullptr;
}

static void outputName(OutputStream &OS, const Name *TheName, const Type *Ty) {
  if (!TheName)
    return;

  outputSpaceIfNecessary(OS);

  const OperatorInfo *Operator = lastComponentAsOperator(TheName);
  const VirtualMemberPtrThunk *Thunk = nullptr;
  if (Operator) {
    if (Operator->Info->Operator == OperatorTy::Vcall) {
      Thunk = static_cast<const VirtualMemberPtrThunk *>(Operator);
      OS << "[thunk]: ";
      outputCallingConvention(OS, Thunk->CC);
      OS << " ";
    }
  }

  const Name *Previous = nullptr;
  // Print out namespaces or outer class BackReferences.
  for (; TheName->Next; TheName = TheName->Next) {
    Previous = TheName;
    outputNameComponent(OS, *TheName);
    OS << "::";
  }

  // Print out a regular name.
  if (!TheName->IsOperator) {
    outputNameComponent(OS, *TheName);
    return;
  }


  // Print out ctor or dtor.
  switch (Operator->Info->Operator) {
  case OperatorTy::Dtor:
    OS << "~";
    LLVM_FALLTHROUGH;
  case OperatorTy::Ctor:
    outputNameComponent(OS, *Previous);
    break;
  case OperatorTy::Conversion:
    OS << "operator";
    if (TheName->IsTemplateInstantiation && TheName->TParams)
      outputParameterList(OS, *TheName->TParams);
    OS << " ";
    if (Ty) {
      const FunctionType *FTy = static_cast<const FunctionType *>(Ty);
      Type::outputPre(OS, *FTy->ReturnType);
      Type::outputPost(OS, *FTy->ReturnType);
    } else {
      OS << "<conversion>";
    }
    break;
  case OperatorTy::LiteralOperator:
    OS << Operator->Info->Name;
    outputNameComponent(OS, *TheName);
    break;
  case OperatorTy::RttiBaseClassDescriptor: {
    const RttiBaseClassDescriptor &BCD =
        static_cast<const RttiBaseClassDescriptor &>(*Operator);
    OS << "`" << Operator->Info->Name << " at (";
    OS << BCD.NVOffset << ", " << BCD.VBPtrOffset << ", " << BCD.VBTableOffset
       << ", " << BCD.Flags;
    OS << ")'";
    break;
  }
  case OperatorTy::Vcall: {
    OS << "`vcall'{";
    OS << Thunk->OffsetInVTable << ", {flat}}";
    break;
  }

  case OperatorTy::LocalStaticGuard: {
    const LocalStaticGuardVariable &LSG =
        static_cast<const LocalStaticGuardVariable &>(*Operator);
    OS << Operator->Info->Name;
    if (LSG.ScopeIndex > 0)
      OS << "{" << LSG.ScopeIndex << "}";
    break;
  }
  default:
    OS << Operator->Info->Name;
    if (Operator->IsTemplateInstantiation)
      outputParameterList(OS, *Operator->TParams);
    break;
  }
}

static void outputSpecialOperator(OutputStream &OS, const Name *OuterName) {
  assert(OuterName);
  // The last component should be an operator.
  const OperatorInfo *Operator = lastComponentAsOperator(OuterName);

  assert(Operator->IsOperator);
  const OperatorInfo &Oper = static_cast<const OperatorInfo &>(*Operator);
  switch (Oper.Info->Operator) {
  case OperatorTy::StringLiteral: {
    const StringLiteral &SL = static_cast<const StringLiteral &>(Oper);
    outputStringLiteral(OS, SL);
    break;
  }
  case OperatorTy::Vcall: {
    const VirtualMemberPtrThunk &Thunk =
        static_cast<const VirtualMemberPtrThunk &>(Oper);
    OS << "[thunk]: ";
    outputCallingConvention(OS, Thunk.CC);
    OS << " ";
    // Print out namespaces or outer class BackReferences.
    const Name *N = OuterName;
    for (; N->Next; N = N->Next) {
      outputNameComponent(OS, *N);
      OS << "::";
    }
    OS << "`vcall'{";
    OS << Thunk.OffsetInVTable << ", {flat}}";
    break;
  }
  default:
    // There are no other special operator categories.
    LLVM_BUILTIN_UNREACHABLE;
  }
}

namespace {

bool Name::isStringLiteralOperatorInfo() const {
  if (!IsOperator)
    return false;
  const OperatorInfo &O = static_cast<const OperatorInfo &>(*this);
  return O.Info->Operator == OperatorTy::StringLiteral;
}

Type *Type::clone(ArenaAllocator &Arena) const {
  return Arena.alloc<Type>(*this);
}

// Write the "first half" of a given type.
void Type::outputPre(OutputStream &OS, Type &Ty) {
  // Function types require custom handling of const and static so we
  // handle them separately.  All other types use the same decoration
  // for these modifiers, so handle them here in common code.
  if (Ty.Prim == PrimTy::Function) {
    Ty.outputPre(OS);
    return;
  }

  switch (Ty.Storage) {
  case StorageClass::PrivateStatic:
  case StorageClass::PublicStatic:
  case StorageClass::ProtectedStatic:
    OS << "static ";
  default:
    break;
  }
  Ty.outputPre(OS);

  outputQualifiers(OS, Ty.Quals);
}

// Write the "second half" of a given type.
void Type::outputPost(OutputStream &OS, Type &Ty) { Ty.outputPost(OS); }

void Type::outputPre(OutputStream &OS) {
  switch (Prim) {
  case PrimTy::Void:
    OS << "void";
    break;
  case PrimTy::Bool:
    OS << "bool";
    break;
  case PrimTy::Char:
    OS << "char";
    break;
  case PrimTy::Schar:
    OS << "signed char";
    break;
  case PrimTy::Uchar:
    OS << "unsigned char";
    break;
  case PrimTy::Char16:
    OS << "char16_t";
    break;
  case PrimTy::Char32:
    OS << "char32_t";
    break;
  case PrimTy::Short:
    OS << "short";
    break;
  case PrimTy::Ushort:
    OS << "unsigned short";
    break;
  case PrimTy::Int:
    OS << "int";
    break;
  case PrimTy::Uint:
    OS << "unsigned int";
    break;
  case PrimTy::Long:
    OS << "long";
    break;
  case PrimTy::Ulong:
    OS << "unsigned long";
    break;
  case PrimTy::Int64:
    OS << "__int64";
    break;
  case PrimTy::Uint64:
    OS << "unsigned __int64";
    break;
  case PrimTy::Wchar:
    OS << "wchar_t";
    break;
  case PrimTy::Float:
    OS << "float";
    break;
  case PrimTy::Double:
    OS << "double";
    break;
  case PrimTy::Ldouble:
    OS << "long double";
    break;
  case PrimTy::Nullptr:
    OS << "std::nullptr_t";
    break;
  case PrimTy::Vbtable:
  case PrimTy::Vftable:
    break;
  default:
    assert(false && "Invalid primitive type!");
  }
}
void Type::outputPost(OutputStream &OS) {}

Type *PointerType::clone(ArenaAllocator &Arena) const {
  return Arena.alloc<PointerType>(*this);
}

static void outputPointerIndicator(OutputStream &OS, PointerAffinity Affinity,
                                   const Name *MemberName,
                                   const Type *Pointee) {
  // "[]" and "()" (for function parameters) take precedence over "*",
  // so "int *x(int)" means "x is a function returning int *". We need
  // parentheses to supercede the default precedence. (e.g. we want to
  // emit something like "int (*x)(int)".)
  if (Pointee->Prim == PrimTy::Function || Pointee->Prim == PrimTy::Array) {
    OS << "(";
    if (Pointee->Prim == PrimTy::Function) {
      const FunctionType *FTy = static_cast<const FunctionType *>(Pointee);
      assert(FTy->IsFunctionPointer);
      outputCallingConvention(OS, FTy->CallConvention);
      OS << " ";
    }
  }

  if (MemberName) {
    outputName(OS, MemberName, Pointee);
    OS << "::";
  }

  if (Affinity == PointerAffinity::Pointer)
    OS << "*";
  else if (Affinity == PointerAffinity::Reference)
    OS << "&";
  else
    OS << "&&";
}

void PointerType::outputPre(OutputStream &OS) {
  Type::outputPre(OS, *Pointee);

  outputSpaceIfNecessary(OS);

  if (Quals & Q_Unaligned)
    OS << "__unaligned ";

  outputPointerIndicator(OS, Affinity, nullptr, Pointee);

  // FIXME: We should output this, but it requires updating lots of tests.
  // if (Ty.Quals & Q_Pointer64)
  //  OS << " __ptr64";
}

void PointerType::outputPost(OutputStream &OS) {
  if (Pointee->Prim == PrimTy::Function || Pointee->Prim == PrimTy::Array)
    OS << ")";

  Type::outputPost(OS, *Pointee);
}

Type *MemberPointerType::clone(ArenaAllocator &Arena) const {
  return Arena.alloc<MemberPointerType>(*this);
}

void MemberPointerType::outputPre(OutputStream &OS) {
  Type::outputPre(OS, *Pointee);

  outputSpaceIfNecessary(OS);

  outputPointerIndicator(OS, PointerAffinity::Pointer, MemberName, Pointee);

  // FIXME: We should output this, but it requires updating lots of tests.
  // if (Ty.Quals & Q_Pointer64)
  //  OS << " __ptr64";
}

void MemberPointerType::outputPost(OutputStream &OS) {
  if (Pointee->Prim == PrimTy::Function || Pointee->Prim == PrimTy::Array)
    OS << ")";

  Type::outputPost(OS, *Pointee);
}

Type *FunctionType::clone(ArenaAllocator &Arena) const {
  return Arena.alloc<FunctionType>(*this);
}

void FunctionType::outputPre(OutputStream &OS) {
  if ((FunctionClass & StaticThisAdjust) || (FunctionClass & VirtualThisAdjust))
    OS << "[thunk]: ";

  if (!(FunctionClass & Global)) {
    if (FunctionClass & Static)
      OS << "static ";
  }
  if (FunctionClass & ExternC)
    OS << "extern \"C\" ";

  if (FunctionClass & Virtual)
    OS << "virtual ";

  if (ReturnType) {
    Type::outputPre(OS, *ReturnType);
    OS << " ";
  }

  // Function pointers print the calling convention as void (__cdecl *)(params)
  // rather than void __cdecl (*)(params).  So we need to let the PointerType
  // class handle this.
  if (!IsFunctionPointer)
    outputCallingConvention(OS, CallConvention);
}

void FunctionType::outputPost(OutputStream &OS) {
  // extern "C" functions don't have a prototype.
  if (FunctionClass & NoPrototype)
    return;

  if (FunctionClass & StaticThisAdjust) {
    OS << "`adjustor{" << ThisAdjust->StaticOffset << "}'";
  } else if (FunctionClass & VirtualThisAdjust) {
    if (FunctionClass & VirtualThisAdjustEx) {
      OS << "`vtordispex{" << ThisAdjust->VBPtrOffset << ", "
         << ThisAdjust->VBOffsetOffset << ", " << ThisAdjust->VtordispOffset
         << ", " << ThisAdjust->StaticOffset << "}'";
    } else {
      OS << "`vtordisp{" << ThisAdjust->VtordispOffset << ", "
         << ThisAdjust->StaticOffset << "}'";
    }
  }

  OS << "(";
  outputParameterList(OS, Params);
  OS << ")";
  if (Quals & Q_Const)
    OS << " const";
  if (Quals & Q_Volatile)
    OS << " volatile";
  if (Quals & Q_Restrict)
    OS << " __restrict";
  if (Quals & Q_Unaligned)
    OS << " __unaligned";

  if (RefKind == ReferenceKind::LValueRef)
    OS << " &";
  else if (RefKind == ReferenceKind::RValueRef)
    OS << " &&";

  if (ReturnType)
    Type::outputPost(OS, *ReturnType);
  return;
}

Type *UdtType::clone(ArenaAllocator &Arena) const {
  return Arena.alloc<UdtType>(*this);
}

void UdtType::outputPre(OutputStream &OS) {
  switch (Prim) {
  case PrimTy::Class:
    OS << "class ";
    break;
  case PrimTy::Struct:
    OS << "struct ";
    break;
  case PrimTy::Union:
    OS << "union ";
    break;
  case PrimTy::Enum:
    OS << "enum ";
    break;
  default:
    assert(false && "Not a udt type!");
  }

  outputName(OS, UdtName, this);
}

Type *ArrayType::clone(ArenaAllocator &Arena) const {
  return Arena.alloc<ArrayType>(*this);
}

void ArrayType::outputPre(OutputStream &OS) {
  Type::outputPre(OS, *ElementType);
}

void ArrayType::outputPost(OutputStream &OS) {
  ArrayDimension *D = Dims;
  while (D) {
    OS << "[";
    if (D->Dim > 0)
      OS << D->Dim;
    OS << "]";
    D = D->Next;
  }

  Type::outputPost(OS, *ElementType);
}

struct Symbol {
  SymbolCategory Category;

  Qualifiers SymbolQuals = Q_None;
  Name *SymbolName = nullptr;
  Type *SymbolType = nullptr;
};

} // namespace

namespace {

struct BackrefContext {
  static constexpr size_t Max = 10;

  Type *FunctionParams[Max];
  size_t FunctionParamCount = 0;

  // The first 10 BackReferences in a mangled name can be back-referenced by
  // special name @[0-9]. This is a storage for the first 10 BackReferences.
  StringView Names[Max];
  size_t NamesCount = 0;
};

// Demangler class takes the main role in demangling symbols.
// It has a set of functions to parse mangled symbols into Type instances.
// It also has a set of functions to cnovert Type instances to strings.
class Demangler {
public:
  Demangler() = default;
  virtual ~Demangler() = default;

  // You are supposed to call parse() first and then check if error is true.  If
  // it is false, call output() to write the formatted name to the given stream.
  Symbol *parse(StringView &MangledName);
  Symbol *parseOperator(StringView &MangledName);

  void output(const Symbol *S, OutputStream &OS);

  // True if an error occurred.
  bool Error = false;

  void dumpBackReferences();

private:
  std::pair<SymbolCategory, Type *>
  demangleSymbolCategoryAndType(StringView &MangledName);

  Type *demangleVariableEncoding(StringView &MangledName, StorageClass SC);
  Type *demangleFunctionEncoding(StringView &MangledName);
  uint64_t demangleThunkThisAdjust(StringView &MangledName);

  Qualifiers demanglePointerExtQualifiers(StringView &MangledName);

  // Parser functions. This is a recursive-descent parser.
  Type *demangleType(StringView &MangledName, QualifierMangleMode QMM);
  Type *demangleBasicType(StringView &MangledName);
  UdtType *demangleClassType(StringView &MangledName);
  PointerType *demanglePointerType(StringView &MangledName);
  MemberPointerType *demangleMemberPointerType(StringView &MangledName);
  FunctionType *demangleFunctionType(StringView &MangledName, bool HasThisQuals,
                                     bool IsFunctionPointer);

  ArrayType *demangleArrayType(StringView &MangledName);

  TemplateParams *demangleTemplateParameterList(StringView &MangledName);
  FunctionParams demangleFunctionParameterList(StringView &MangledName);

  std::pair<uint64_t, bool> demangleNumber(StringView &MangledName);
  uint64_t demangleUnsigned(StringView &MangledName);
  int64_t demangleSigned(StringView &MangledName);

  void memorizeString(StringView s);

  /// Allocate a copy of \p Borrowed into memory that we own.
  StringView copyString(StringView Borrowed);

  Name *demangleFullyQualifiedTypeName(StringView &MangledName);
  Name *demangleFullyQualifiedSymbolName(StringView &MangledName);

  Name *demangleUnqualifiedTypeName(StringView &MangledName, bool Memorize);
  Name *demangleUnqualifiedSymbolName(StringView &MangledName,
                                      NameBackrefBehavior NBB);

  Name *demangleNameScopeChain(StringView &MangledName, Name *UnqualifiedName);
  Name *demangleNameScopePiece(StringView &MangledName);

  Name *demangleBackRefName(StringView &MangledName);
  Name *demangleTemplateInstantiationName(StringView &MangledName,
                                          NameBackrefBehavior NBB);
  std::pair<OperatorTy, Name *> demangleOperatorName(StringView &MangledName,
                                                     bool FullyQualified);
  Name *demangleSimpleName(StringView &MangledName, bool Memorize);
  Name *demangleAnonymousNamespaceName(StringView &MangledName);
  Name *demangleLocallyScopedNamePiece(StringView &MangledName);
  StringLiteral *demangleStringLiteral(StringView &MangledName);

  StringView demangleSimpleString(StringView &MangledName, bool Memorize);

  FuncClass demangleFunctionClass(StringView &MangledName);
  CallingConv demangleCallingConvention(StringView &MangledName);
  StorageClass demangleVariableStorageClass(StringView &MangledName);
  ReferenceKind demangleReferenceKind(StringView &MangledName);
  void demangleThrowSpecification(StringView &MangledName);
  wchar_t demangleWcharLiteral(StringView &MangledName);
  uint8_t demangleCharLiteral(StringView &MangledName);

  std::pair<Qualifiers, bool> demangleQualifiers(StringView &MangledName);

  // Memory allocator.
  ArenaAllocator Arena;

  // A single type uses one global back-ref table for all function params.
  // This means back-refs can even go "into" other types.  Examples:
  //
  //  // Second int* is a back-ref to first.
  //  void foo(int *, int*);
  //
  //  // Second int* is not a back-ref to first (first is not a function param).
  //  int* foo(int*);
  //
  //  // Second int* is a back-ref to first (ALL function types share the same
  //  // back-ref map.
  //  using F = void(*)(int*);
  //  F G(int *);
  BackrefContext Backrefs;
};
} // namespace

StringView Demangler::copyString(StringView Borrowed) {
  char *Stable = Arena.allocUnalignedBuffer(Borrowed.size() + 1);
  std::strcpy(Stable, Borrowed.begin());

  return {Stable, Borrowed.size()};
}

Symbol *Demangler::parseOperator(StringView &MangledName) {
  Symbol *S = Arena.alloc<Symbol>();

  bool IsMember = false;
  OperatorTy OTy;
  std::tie(OTy, S->SymbolName) = demangleOperatorName(MangledName, true);
  switch (OTy) {
  case OperatorTy::StringLiteral:
    S->Category = SymbolCategory::SpecialOperator;
    break;
  case OperatorTy::Vcall:
    S->Category = SymbolCategory::UnnamedFunction;
    break;
  case OperatorTy::LocalStaticGuard:
    S->Category = SymbolCategory::UnnamedVariable;
    break;
  case OperatorTy::Vftable:                // Foo@@6B@
  case OperatorTy::LocalVftable:           // Foo@@6B@
  case OperatorTy::RttiCompleteObjLocator: // Foo@@6B@
  case OperatorTy::Vbtable:                // Foo@@7B@
    S->Category = SymbolCategory::UnnamedVariable;
    switch (MangledName.popFront()) {
    case '6':
    case '7':
      std::tie(S->SymbolQuals, IsMember) = demangleQualifiers(MangledName);
      if (!MangledName.consumeFront('@'))
        Error = true;
      break;
    default:
      Error = true;
      break;
    }
    break;
  case OperatorTy::RttiTypeDescriptor: // <type>@@8
    S->Category = SymbolCategory::UnnamedVariable;
    S->SymbolType = demangleType(MangledName, QualifierMangleMode::Result);
    if (Error)
      break;
    if (!MangledName.consumeFront("@8"))
      Error = true;
    if (!MangledName.empty())
      Error = true;
    break;
  default:
    if (!Error)
      std::tie(S->Category, S->SymbolType) =
          demangleSymbolCategoryAndType(MangledName);
    break;
  }

  return (Error) ? nullptr : S;
}

std::pair<SymbolCategory, Type *>
Demangler::demangleSymbolCategoryAndType(StringView &MangledName) {
  // Read a variable.
  switch (MangledName.front()) {
  case '0':
  case '1':
  case '2':
  case '3':
  case '4':
    return std::make_pair(
        SymbolCategory::NamedVariable,
        demangleVariableEncoding(MangledName,
                                 demangleVariableStorageClass(MangledName)));
  case '8':
    MangledName.consumeFront('8');
    return std::pair<SymbolCategory, Type *>(SymbolCategory::UnnamedVariable,
                                             nullptr);
  }
  return std::make_pair(SymbolCategory::NamedFunction,
                        demangleFunctionEncoding(MangledName));
}

// Parser entry point.
Symbol *Demangler::parse(StringView &MangledName) {
  // We can't demangle MD5 names, just output them as-is.
  // Also, MSVC-style mangled symbols must start with '?'.
  if (MangledName.startsWith("??@") || !MangledName.startsWith('?')) {
    Symbol *S = Arena.alloc<Symbol>();
    S->Category = SymbolCategory::Unknown;
    S->SymbolName = Arena.alloc<Name>();
    S->SymbolName->Str = MangledName;
    S->SymbolType = nullptr;
    MangledName = StringView();
    return S;
  }

  MangledName.consumeFront('?');

  // ?$ is a template instantiation, but all other names that start with ? are
  // operators / special names.
  if (MangledName.startsWith('?') && !MangledName.startsWith("?$"))
    return parseOperator(MangledName);

  Symbol *S = Arena.alloc<Symbol>();
  // What follows is a main symbol name. This may include namespaces or class
  // back references.
  S->SymbolName = demangleFullyQualifiedSymbolName(MangledName);
  if (Error)
    return nullptr;

  std::tie(S->Category, S->SymbolType) =
      demangleSymbolCategoryAndType(MangledName);

  if (Error)
    return nullptr;

  return S;
}

// <type-encoding> ::= <storage-class> <variable-type>
// <storage-class> ::= 0  # private static member
//                 ::= 1  # protected static member
//                 ::= 2  # public static member
//                 ::= 3  # global
//                 ::= 4  # static local

Type *Demangler::demangleVariableEncoding(StringView &MangledName,
                                          StorageClass SC) {
  Type *Ty = demangleType(MangledName, QualifierMangleMode::Drop);

  Ty->Storage = SC;

  // <variable-type> ::= <type> <cvr-qualifiers>
  //                 ::= <type> <pointee-cvr-qualifiers> # pointers, references
  switch (Ty->Prim) {
  case PrimTy::Ptr:
  case PrimTy::MemberPtr: {
    Qualifiers ExtraChildQuals = Q_None;
    Ty->Quals =
        Qualifiers(Ty->Quals | demanglePointerExtQualifiers(MangledName));

    bool IsMember = false;
    std::tie(ExtraChildQuals, IsMember) = demangleQualifiers(MangledName);

    if (Ty->Prim == PrimTy::MemberPtr) {
      assert(IsMember);
      Name *BackRefName = demangleFullyQualifiedTypeName(MangledName);
      (void)BackRefName;
      MemberPointerType *MPTy = static_cast<MemberPointerType *>(Ty);
      MPTy->Pointee->Quals = Qualifiers(MPTy->Pointee->Quals | ExtraChildQuals);
    } else {
      PointerType *PTy = static_cast<PointerType *>(Ty);
      PTy->Pointee->Quals = Qualifiers(PTy->Pointee->Quals | ExtraChildQuals);
    }

    break;
  }
  default:
    Ty->Quals = demangleQualifiers(MangledName).first;
    break;
  }

  return Ty;
}

// Sometimes numbers are encoded in mangled symbols. For example,
// "int (*x)[20]" is a valid C type (x is a pointer to an array of
// length 20), so we need some way to embed numbers as part of symbols.
// This function parses it.
//
// <number>               ::= [?] <non-negative integer>
//
// <non-negative integer> ::= <decimal digit> # when 1 <= Number <= 10
//                        ::= <hex digit>+ @  # when Numbrer == 0 or >= 10
//
// <hex-digit>            ::= [A-P]           # A = 0, B = 1, ...
std::pair<uint64_t, bool> Demangler::demangleNumber(StringView &MangledName) {
  bool IsNegative = MangledName.consumeFront('?');

  if (startsWithDigit(MangledName)) {
    uint64_t Ret = MangledName[0] - '0' + 1;
    MangledName = MangledName.dropFront(1);
    return {Ret, IsNegative};
  }

  uint64_t Ret = 0;
  for (size_t i = 0; i < MangledName.size(); ++i) {
    char C = MangledName[i];
    if (C == '@') {
      MangledName = MangledName.dropFront(i + 1);
      return {Ret, IsNegative};
    }
    if ('A' <= C && C <= 'P') {
      Ret = (Ret << 4) + (C - 'A');
      continue;
    }
    break;
  }

  Error = true;
  return {0ULL, false};
}

uint64_t Demangler::demangleUnsigned(StringView &MangledName) {
  bool IsNegative = false;
  uint64_t Number = 0;
  std::tie(Number, IsNegative) = demangleNumber(MangledName);
  if (IsNegative)
    Error = true;
  return Number;
}

int64_t Demangler::demangleSigned(StringView &MangledName) {
  bool IsNegative = false;
  uint64_t Number = 0;
  std::tie(Number, IsNegative) = demangleNumber(MangledName);
  if (Number > INT64_MAX)
    Error = true;
  int64_t I = static_cast<int64_t>(Number);
  return IsNegative ? -I : I;
}

// First 10 strings can be referenced by special BackReferences ?0, ?1, ..., ?9.
// Memorize it.
void Demangler::memorizeString(StringView S) {
  if (Backrefs.NamesCount >= BackrefContext::Max)
    return;
  for (size_t i = 0; i < Backrefs.NamesCount; ++i)
    if (S == Backrefs.Names[i])
      return;
  Backrefs.Names[Backrefs.NamesCount++] = S;
}

Name *Demangler::demangleBackRefName(StringView &MangledName) {
  assert(startsWithDigit(MangledName));

  size_t I = MangledName[0] - '0';
  if (I >= Backrefs.NamesCount) {
    Error = true;
    return nullptr;
  }

  MangledName = MangledName.dropFront();
  Name *Node = Arena.alloc<Name>();
  Node->Str = Backrefs.Names[I];
  return Node;
}

Name *Demangler::demangleTemplateInstantiationName(StringView &MangledName,
                                                   NameBackrefBehavior NBB) {
  assert(MangledName.startsWith("?$"));
  MangledName.consumeFront("?$");

  BackrefContext OuterContext;
  std::swap(OuterContext, Backrefs);

  Name *Node = demangleUnqualifiedSymbolName(MangledName, NBB_Simple);
  if (!Error)
    Node->TParams = demangleTemplateParameterList(MangledName);

  std::swap(OuterContext, Backrefs);
  if (Error)
    return nullptr;

  Node->IsTemplateInstantiation = true;

  if (NBB & NBB_Template) {
    // Render this class template name into a string buffer so that we can
    // memorize it for the purpose of back-referencing.
    OutputStream OS = OutputStream::create(nullptr, nullptr, 1024);
    outputName(OS, Node, nullptr);
    OS << '\0';
    char *Name = OS.getBuffer();

    StringView Owned = copyString(Name);
    memorizeString(Owned);
    std::free(Name);
  }

  return Node;
}

std::pair<OperatorTy, Name *>
Demangler::demangleOperatorName(StringView &MangledName, bool FullyQualified) {
  assert(MangledName.startsWith('?'));
  MangledName.consumeFront('?');

  const OperatorMapEntry *Entry = nullptr;
  for (const auto &MapEntry : OperatorMap) {
    if (!MangledName.consumeFront(MapEntry.Prefix))
      continue;
    Entry = &MapEntry;
    break;
  }
  if (!Entry) {
    Error = true;
    return std::make_pair(OperatorTy::Unknown, nullptr);
  }

  Name *N = nullptr;
  switch (Entry->Operator) {
  case OperatorTy::Vftable:                // Foo@@6B@
  case OperatorTy::LocalVftable:           // Foo@@6B@
  case OperatorTy::RttiCompleteObjLocator: // Foo@@6B@
  case OperatorTy::Vbtable: {              // Foo@@7B@
    OperatorInfo *Oper = Arena.alloc<OperatorInfo>(*Entry);
    N = (FullyQualified) ? demangleNameScopeChain(MangledName, Oper) : Oper;
    break;
  }

  case OperatorTy::StringLiteral:
    N = demangleStringLiteral(MangledName);
    break;
  case OperatorTy::LiteralOperator:
    N = Arena.alloc<OperatorInfo>(*Entry);
    N->Str = demangleSimpleString(MangledName, false);
    if (!MangledName.consumeFront('@'))
      Error = true;
    break;
  case OperatorTy::RttiBaseClassDescriptor: {
    RttiBaseClassDescriptor *Temp = Arena.alloc<RttiBaseClassDescriptor>();
    Temp->NVOffset = demangleUnsigned(MangledName);
    Temp->VBPtrOffset = demangleSigned(MangledName);
    Temp->VBTableOffset = demangleUnsigned(MangledName);
    Temp->Flags = demangleUnsigned(MangledName);
    N = (FullyQualified) ? demangleNameScopeChain(MangledName, Temp) : Temp;
    break;
  }
  case OperatorTy::Vcall: {
    VirtualMemberPtrThunk *Temp = Arena.alloc<VirtualMemberPtrThunk>();
    N = demangleNameScopeChain(MangledName, Temp);
    if (Error)
      break;
    if (!MangledName.consumeFront("$B"))
      Error = true;
    Temp->OffsetInVTable = demangleUnsigned(MangledName);
    if (!MangledName.consumeFront('A'))
      Error = true;
    Temp->CC = demangleCallingConvention(MangledName);
    break;
  }
  case OperatorTy::RttiTypeDescriptor:
    // This one is just followed by a type, not a name scope.
    N = Arena.alloc<OperatorInfo>(*Entry);
    break;
  case OperatorTy::LocalStaticGuard: {
    LocalStaticGuardVariable *Temp = Arena.alloc<LocalStaticGuardVariable>();
    N = (FullyQualified) ? demangleNameScopeChain(MangledName, Temp) : Temp;
    if (MangledName.consumeFront("4IA"))
      Temp->IsVisible = false;
    else if (MangledName.consumeFront("5"))
      Temp->IsVisible = true;
    else
      Error = true;
    if (!MangledName.empty())
      Temp->ScopeIndex = demangleUnsigned(MangledName);
    break;
  }
  default:
    N = Arena.alloc<OperatorInfo>(*Entry);
    N = (FullyQualified) ? demangleNameScopeChain(MangledName, N) : N;
    break;
  }
  if (Error)
    return std::make_pair(OperatorTy::Unknown, nullptr);

  return std::make_pair(Entry->Operator, N);
}

Name *Demangler::demangleSimpleName(StringView &MangledName, bool Memorize) {
  StringView S = demangleSimpleString(MangledName, Memorize);
  if (Error)
    return nullptr;

  Name *Node = Arena.alloc<Name>();
  Node->Str = S;
  return Node;
}

static bool isRebasedHexDigit(char C) { return (C >= 'A' && C <= 'P'); }

static uint8_t rebasedHexDigitToNumber(char C) {
  assert(isRebasedHexDigit(C));
  return (C <= 'J') ? (C - 'A') : (10 + C - 'K');
}

uint8_t Demangler::demangleCharLiteral(StringView &MangledName) {
  if (!MangledName.startsWith('?'))
    return MangledName.popFront();

  MangledName = MangledName.dropFront();
  if (MangledName.empty())
    goto CharLiteralError;

  if (MangledName.consumeFront('$')) {
    // Two hex digits
    if (MangledName.size() < 2)
      goto CharLiteralError;
    StringView Nibbles = MangledName.substr(0, 2);
    if (!isRebasedHexDigit(Nibbles[0]) || !isRebasedHexDigit(Nibbles[1]))
      goto CharLiteralError;
    // Don't append the null terminator.
    uint8_t C1 = rebasedHexDigitToNumber(Nibbles[0]);
    uint8_t C2 = rebasedHexDigitToNumber(Nibbles[1]);
    MangledName = MangledName.dropFront(2);
    return (C1 << 4) | C2;
  }

  if (startsWithDigit(MangledName)) {
    const char *Lookup = ",/\\:. \n\t'-";
    char C = Lookup[MangledName[0] - '0'];
    MangledName = MangledName.dropFront();
    return C;
  }

  if (MangledName[0] >= 'a' && MangledName[0] <= 'z') {
    char Lookup[26] = {'\xE1', '\xE2', '\xE3', '\xE4', '\xE5', '\xE6', '\xE7',
                       '\xE8', '\xE9', '\xEA', '\xEB', '\xEC', '\xED', '\xEE',
                       '\xEF', '\xF0', '\xF1', '\xF2', '\xF3', '\xF4', '\xF5',
                       '\xF6', '\xF7', '\xF8', '\xF9', '\xFA'};
    char C = Lookup[MangledName[0] - 'a'];
    MangledName = MangledName.dropFront();
    return C;
  }

  if (MangledName[0] >= 'A' && MangledName[0] <= 'Z') {
    char Lookup[26] = {'\xC1', '\xC2', '\xC3', '\xC4', '\xC5', '\xC6', '\xC7',
                       '\xC8', '\xC9', '\xCA', '\xCB', '\xCC', '\xCD', '\xCE',
                       '\xCF', '\xD0', '\xD1', '\xD2', '\xD3', '\xD4', '\xD5',
                       '\xD6', '\xD7', '\xD8', '\xD9', '\xDA'};
    char C = Lookup[MangledName[0] - 'A'];
    MangledName = MangledName.dropFront();
    return C;
  }

CharLiteralError:
  Error = true;
  return '\0';
}

wchar_t Demangler::demangleWcharLiteral(StringView &MangledName) {
  uint8_t C1, C2;

  C1 = demangleCharLiteral(MangledName);
  if (Error)
    goto WCharLiteralError;
  C2 = demangleCharLiteral(MangledName);
  if (Error)
    goto WCharLiteralError;

  return ((wchar_t)C1 << 8) | (wchar_t)C2;

WCharLiteralError:
  Error = true;
  return L'\0';
}

static void writeHexDigit(char *Buffer, uint8_t Digit) {
  assert(Digit <= 15);
  *Buffer = (Digit < 10) ? ('0' + Digit) : ('A' + Digit - 10);
}

static void outputHex(OutputStream &OS, unsigned C) {
  if (C == 0) {
    OS << "\\x00";
    return;
  }
  // It's easier to do the math if we can work from right to left, but we need
  // to print the numbers from left to right.  So render this into a temporary
  // buffer first, then output the temporary buffer.  Each byte is of the form
  // \xAB, which means that each byte needs 4 characters.  Since there are at
  // most 4 bytes, we need a 4*4+1 = 17 character temporary buffer.
  char TempBuffer[17];

  ::memset(TempBuffer, 0, sizeof(TempBuffer));
  constexpr int MaxPos = 15;

  int Pos = MaxPos - 1;
  while (C != 0) {
    for (int I = 0; I < 2; ++I) {
      writeHexDigit(&TempBuffer[Pos--], C % 16);
      C /= 16;
    }
    TempBuffer[Pos--] = 'x';
    TempBuffer[Pos--] = '\\';
    assert(Pos >= 0);
  }
  OS << StringView(&TempBuffer[Pos + 1]);
}

static void outputEscapedChar(OutputStream &OS, unsigned C) {
  switch (C) {
  case '\'': // single quote
    OS << "\\\'";
    return;
  case '\"': // double quote
    OS << "\\\"";
    return;
  case '\\': // backslash
    OS << "\\\\";
    return;
  case '\a': // bell
    OS << "\\a";
    return;
  case '\b': // backspace
    OS << "\\b";
    return;
  case '\f': // form feed
    OS << "\\f";
    return;
  case '\n': // new line
    OS << "\\n";
    return;
  case '\r': // carriage return
    OS << "\\r";
    return;
  case '\t': // tab
    OS << "\\t";
    return;
  case '\v': // vertical tab
    OS << "\\v";
    return;
  default:
    break;
  }

  if (C > 0x1F && C < 0x7F) {
    // Standard ascii char.
    OS << (char)C;
    return;
  }

  outputHex(OS, C);
}

unsigned countTrailingNullBytes(const uint8_t *StringBytes, int Length) {
  const uint8_t *End = StringBytes + Length - 1;
  unsigned Count = 0;
  while (Length > 0 && *End == 0) {
    --Length;
    --End;
    ++Count;
  }
  return Count;
}

unsigned countEmbeddedNulls(const uint8_t *StringBytes, unsigned Length) {
  unsigned Result = 0;
  for (unsigned I = 0; I < Length; ++I) {
    if (*StringBytes++ == 0)
      ++Result;
  }
  return Result;
}

unsigned guessCharByteSize(const uint8_t *StringBytes, unsigned NumChars,
                           unsigned NumBytes) {
  assert(NumBytes > 0);

  // If the number of bytes is odd, this is guaranteed to be a char string.
  if (NumBytes % 2 == 1)
    return 1;

  // All strings can encode at most 32 bytes of data.  If it's less than that,
  // then we encoded the entire string.  In this case we check for a 1-byte,
  // 2-byte, or 4-byte null terminator.
  if (NumBytes < 32) {
    unsigned TrailingNulls = countTrailingNullBytes(StringBytes, NumChars);
    if (TrailingNulls >= 4)
      return 4;
    if (TrailingNulls >= 2)
      return 2;
    return 1;
  }

  // The whole string was not able to be encoded.  Try to look at embedded null
  // terminators to guess.  The heuristic is that we count all embedded null
  // terminators.  If more than 2/3 are null, it's a char32.  If more than 1/3
  // are null, it's a char16.  Otherwise it's a char8.  This obviously isn't
  // perfect and is biased towards languages that have ascii alphabets, but this
  // was always going to be best effort since the encoding is lossy.
  unsigned Nulls = countEmbeddedNulls(StringBytes, NumChars);
  if (Nulls >= 2 * NumChars / 3)
    return 4;
  if (Nulls >= NumChars / 3)
    return 2;
  return 1;
}

static unsigned decodeMultiByteChar(const uint8_t *StringBytes,
                                    unsigned CharIndex, unsigned CharBytes) {
  assert(CharBytes == 1 || CharBytes == 2 || CharBytes == 4);
  unsigned Offset = CharIndex * CharBytes;
  unsigned Result = 0;
  StringBytes = StringBytes + Offset;
  for (unsigned I = 0; I < CharBytes; ++I) {
    unsigned C = static_cast<unsigned>(StringBytes[I]);
    Result |= C << (8 * I);
  }
  return Result;
}

StringLiteral *Demangler::demangleStringLiteral(StringView &MangledName) {
  // This function uses goto, so declare all variables up front.
  OutputStream OS;
  StringView CRC;
  uint64_t StringByteSize;
  bool IsWcharT = false;
  bool IsNegative = false;
  size_t CrcEndPos = 0;
  char *ResultBuffer = nullptr;

  StringLiteral *Result = Arena.alloc<StringLiteral>();

  // Prefix indicating the beginning of a string literal
  if (!MangledName.consumeFront("@_"))
    goto StringLiteralError;
  if (MangledName.empty())
    goto StringLiteralError;

  // Char Type (regular or wchar_t)
  switch (MangledName.popFront()) {
  case '1':
    IsWcharT = true;
    LLVM_FALLTHROUGH;
  case '0':
    break;
  default:
    goto StringLiteralError;
  }

  // Encoded Length
  std::tie(StringByteSize, IsNegative) = demangleNumber(MangledName);
  if (Error || IsNegative)
    goto StringLiteralError;

  // CRC 32 (always 8 characters plus a terminator)
  CrcEndPos = MangledName.find('@');
  if (CrcEndPos == StringView::npos)
    goto StringLiteralError;
  CRC = MangledName.substr(0, CrcEndPos);
  MangledName = MangledName.dropFront(CrcEndPos + 1);
  if (MangledName.empty())
    goto StringLiteralError;

  OS = OutputStream::create(nullptr, nullptr, 1024);
  if (IsWcharT) {
    Result->CharType = PrimTy::Wchar;
    if (StringByteSize > 64)
      Result->IsTruncated = true;

    while (!MangledName.consumeFront('@')) {
      assert(StringByteSize >= 2);
      wchar_t W = demangleWcharLiteral(MangledName);
      if (StringByteSize != 2 || Result->IsTruncated)
        outputEscapedChar(OS, W);
      StringByteSize -= 2;
      if (Error)
        goto StringLiteralError;
    }
  } else {
    if (StringByteSize > 32)
      Result->IsTruncated = true;

    constexpr unsigned MaxStringByteLength = 32;
    uint8_t StringBytes[MaxStringByteLength];

    unsigned BytesDecoded = 0;
    while (!MangledName.consumeFront('@')) {
      assert(StringByteSize >= 1);
      StringBytes[BytesDecoded++] = demangleCharLiteral(MangledName);
    }

    unsigned CharBytes =
        guessCharByteSize(StringBytes, BytesDecoded, StringByteSize);
    assert(StringByteSize % CharBytes == 0);
    switch (CharBytes) {
    case 1:
      Result->CharType = PrimTy::Char;
      break;
    case 2:
      Result->CharType = PrimTy::Char16;
      break;
    case 4:
      Result->CharType = PrimTy::Char32;
      break;
    default:
      LLVM_BUILTIN_UNREACHABLE;
    }
    const unsigned NumChars = BytesDecoded / CharBytes;
    for (unsigned CharIndex = 0; CharIndex < NumChars; ++CharIndex) {
      unsigned NextChar =
          decodeMultiByteChar(StringBytes, CharIndex, CharBytes);
      if (CharIndex + 1 < NumChars || Result->IsTruncated)
        outputEscapedChar(OS, NextChar);
    }
  }

  OS << '\0';
  ResultBuffer = OS.getBuffer();
  Result->Str = copyString(ResultBuffer);
  std::free(ResultBuffer);
  return Result;

StringLiteralError:
  Error = true;
  return nullptr;
}

StringView Demangler::demangleSimpleString(StringView &MangledName,
                                           bool Memorize) {
  StringView S;
  for (size_t i = 0; i < MangledName.size(); ++i) {
    if (MangledName[i] != '@')
      continue;
    S = MangledName.substr(0, i);
    MangledName = MangledName.dropFront(i + 1);

    if (Memorize)
      memorizeString(S);
    return S;
  }

  Error = true;
  return {};
}

Name *Demangler::demangleAnonymousNamespaceName(StringView &MangledName) {
  assert(MangledName.startsWith("?A"));
  MangledName.consumeFront("?A");

  Name *Node = Arena.alloc<Name>();
  Node->Str = "`anonymous namespace'";
  size_t EndPos = MangledName.find('@');
  if (EndPos == StringView::npos) {
    Error = true;
    return nullptr;
  }
  StringView NamespaceKey = MangledName.substr(0, EndPos);
  memorizeString(NamespaceKey);
  MangledName = MangledName.substr(EndPos + 1);
  return Node;
}

Name *Demangler::demangleLocallyScopedNamePiece(StringView &MangledName) {
  assert(startsWithLocalScopePattern(MangledName));

  Name *Node = Arena.alloc<Name>();
  MangledName.consumeFront('?');
  auto Number = demangleNumber(MangledName);
  assert(!Number.second);

  // One ? to terminate the number
  MangledName.consumeFront('?');

  assert(!Error);
  Symbol *Scope = parse(MangledName);
  if (Error)
    return nullptr;

  // Render the parent symbol's name into a buffer.
  OutputStream OS = OutputStream::create(nullptr, nullptr, 1024);
  OS << '`';
  output(Scope, OS);
  OS << '\'';
  OS << "::`" << Number.first << "'";
  OS << '\0';
  char *Result = OS.getBuffer();
  Node->Str = copyString(Result);
  std::free(Result);
  return Node;
}

// Parses a type name in the form of A@B@C@@ which represents C::B::A.
Name *Demangler::demangleFullyQualifiedTypeName(StringView &MangledName) {
  Name *TypeName = demangleUnqualifiedTypeName(MangledName, true);
  if (Error)
    return nullptr;
  assert(TypeName);

  Name *QualName = demangleNameScopeChain(MangledName, TypeName);
  if (Error)
    return nullptr;
  assert(QualName);
  return QualName;
}

// Parses a symbol name in the form of A@B@C@@ which represents C::B::A.
// Symbol names have slightly different rules regarding what can appear
// so we separate out the implementations for flexibility.
Name *Demangler::demangleFullyQualifiedSymbolName(StringView &MangledName) {
  // This is the final component of a symbol name (i.e. the leftmost component
  // of a mangled name.  Since the only possible template instantiation that
  // can appear in this context is a function template, and since those are
  // not saved for the purposes of name backreferences, only backref simple
  // names.
  Name *SymbolName = demangleUnqualifiedSymbolName(MangledName, NBB_Simple);
  if (Error)
    return nullptr;

  Name *QualName = demangleNameScopeChain(MangledName, SymbolName);
  if (Error)
    return nullptr;
  assert(QualName);
  return QualName;
}

Name *Demangler::demangleUnqualifiedTypeName(StringView &MangledName,
                                             bool Memorize) {
  // An inner-most name can be a back-reference, because a fully-qualified name
  // (e.g. Scope + Inner) can contain other fully qualified names inside of
  // them (for example template parameters), and these nested parameters can
  // refer to previously mangled types.
  if (startsWithDigit(MangledName))
    return demangleBackRefName(MangledName);

  if (MangledName.startsWith("?$"))
    return demangleTemplateInstantiationName(MangledName, NBB_Template);

  return demangleSimpleName(MangledName, Memorize);
}

Name *Demangler::demangleUnqualifiedSymbolName(StringView &MangledName,
                                               NameBackrefBehavior NBB) {
  if (startsWithDigit(MangledName))
    return demangleBackRefName(MangledName);
  if (MangledName.startsWith("?$"))
    return demangleTemplateInstantiationName(MangledName, NBB);
  if (MangledName.startsWith('?'))
    return demangleOperatorName(MangledName, false).second;
  return demangleSimpleName(MangledName, (NBB & NBB_Simple) != 0);
}

Name *Demangler::demangleNameScopePiece(StringView &MangledName) {
  if (startsWithDigit(MangledName))
    return demangleBackRefName(MangledName);

  if (MangledName.startsWith("?$"))
    return demangleTemplateInstantiationName(MangledName, NBB_Template);

  if (MangledName.startsWith("?A"))
    return demangleAnonymousNamespaceName(MangledName);

  if (startsWithLocalScopePattern(MangledName))
    return demangleLocallyScopedNamePiece(MangledName);

  return demangleSimpleName(MangledName, true);
}

Name *Demangler::demangleNameScopeChain(StringView &MangledName,
                                        Name *UnqualifiedName) {
  Name *Head = UnqualifiedName;

  while (!MangledName.consumeFront("@")) {
    if (MangledName.empty()) {
      Error = true;
      return nullptr;
    }

    assert(!Error);
    Name *Elem = demangleNameScopePiece(MangledName);
    if (Error)
      return nullptr;

    Elem->Next = Head;
    Head = Elem;
  }
  return Head;
}

FuncClass Demangler::demangleFunctionClass(StringView &MangledName) {
  SwapAndRestore<StringView> RestoreOnError(MangledName, MangledName);
  RestoreOnError.shouldRestore(false);

  switch (MangledName.popFront()) {
  case '9':
    return FuncClass(ExternC | NoPrototype);
  case 'A':
    return Private;
  case 'B':
    return FuncClass(Private | Far);
  case 'C':
    return FuncClass(Private | Static);
  case 'D':
    return FuncClass(Private | Static);
  case 'E':
    return FuncClass(Private | Virtual);
  case 'F':
    return FuncClass(Private | Virtual);
  case 'I':
    return FuncClass(Protected);
  case 'J':
    return FuncClass(Protected | Far);
  case 'K':
    return FuncClass(Protected | Static);
  case 'L':
    return FuncClass(Protected | Static | Far);
  case 'M':
    return FuncClass(Protected | Virtual);
  case 'N':
    return FuncClass(Protected | Virtual | Far);
  case 'O':
    return FuncClass(Protected | Virtual | StaticThisAdjust);
  case 'P':
    return FuncClass(Protected | Virtual | StaticThisAdjust | Far);
  case 'Q':
    return FuncClass(Public);
  case 'R':
    return FuncClass(Public | Far);
  case 'S':
    return FuncClass(Public | Static);
  case 'T':
    return FuncClass(Public | Static | Far);
  case 'U':
    return FuncClass(Public | Virtual);
  case 'V':
    return FuncClass(Public | Virtual | Far);
  case 'W':
    return FuncClass(Public | Virtual | StaticThisAdjust);
  case 'X':
    return FuncClass(Public | Virtual | StaticThisAdjust | Far);
  case 'Y':
    return FuncClass(Global);
  case 'Z':
    return FuncClass(Global | Far);
  case '$': {
    FuncClass VFlag = VirtualThisAdjust;
    if (MangledName.consumeFront('R'))
      VFlag = FuncClass(VFlag | VirtualThisAdjustEx);

    switch (MangledName.popFront()) {
    case '0':
      return FuncClass(Private | Virtual | VFlag);
    case '1':
      return FuncClass(Private | Virtual | VFlag | Far);
    case '2':
      return FuncClass(Protected | Virtual | VFlag);
    case '3':
      return FuncClass(Protected | Virtual | VFlag | Far);
    case '4':
      return FuncClass(Public | Virtual | VFlag);
    case '5':
      return FuncClass(Public | Virtual | VFlag | Far);
    }
  }
  }

  Error = true;
  RestoreOnError.shouldRestore(true);
  return Public;
}

CallingConv Demangler::demangleCallingConvention(StringView &MangledName) {
  switch (MangledName.popFront()) {
  case 'A':
  case 'B':
    return CallingConv::Cdecl;
  case 'C':
  case 'D':
    return CallingConv::Pascal;
  case 'E':
  case 'F':
    return CallingConv::Thiscall;
  case 'G':
  case 'H':
    return CallingConv::Stdcall;
  case 'I':
  case 'J':
    return CallingConv::Fastcall;
  case 'M':
  case 'N':
    return CallingConv::Clrcall;
  case 'O':
  case 'P':
    return CallingConv::Eabi;
  case 'Q':
    return CallingConv::Vectorcall;
  }

  return CallingConv::None;
}

StorageClass Demangler::demangleVariableStorageClass(StringView &MangledName) {
  assert(std::isdigit(MangledName.front()));

  switch (MangledName.popFront()) {
  case '0':
    return StorageClass::PrivateStatic;
  case '1':
    return StorageClass::ProtectedStatic;
  case '2':
    return StorageClass::PublicStatic;
  case '3':
    return StorageClass::Global;
  case '4':
    return StorageClass::FunctionLocalStatic;
  }
  Error = true;
  return StorageClass::None;
}

std::pair<Qualifiers, bool>
Demangler::demangleQualifiers(StringView &MangledName) {

  switch (MangledName.popFront()) {
  // Member qualifiers
  case 'Q':
    return std::make_pair(Q_None, true);
  case 'R':
    return std::make_pair(Q_Const, true);
  case 'S':
    return std::make_pair(Q_Volatile, true);
  case 'T':
    return std::make_pair(Qualifiers(Q_Const | Q_Volatile), true);
  // Non-Member qualifiers
  case 'A':
    return std::make_pair(Q_None, false);
  case 'B':
    return std::make_pair(Q_Const, false);
  case 'C':
    return std::make_pair(Q_Volatile, false);
  case 'D':
    return std::make_pair(Qualifiers(Q_Const | Q_Volatile), false);
  }
  Error = true;
  return std::make_pair(Q_None, false);
}

static bool isTagType(StringView S) {
  switch (S.front()) {
  case 'T': // union
  case 'U': // struct
  case 'V': // class
  case 'W': // enum
    return true;
  }
  return false;
}

static bool isPointerType(StringView S) {
  if (S.startsWith("$$Q")) // foo &&
    return true;

  switch (S.front()) {
  case 'A': // foo &
  case 'P': // foo *
  case 'Q': // foo *const
  case 'R': // foo *volatile
  case 'S': // foo *const volatile
    return true;
  }
  return false;
}

static bool isArrayType(StringView S) { return S[0] == 'Y'; }

static bool isFunctionType(StringView S) {
  return S.startsWith("$$A8@@") || S.startsWith("$$A6");
}

// <variable-type> ::= <type> <cvr-qualifiers>
//                 ::= <type> <pointee-cvr-qualifiers> # pointers, references
Type *Demangler::demangleType(StringView &MangledName,
                              QualifierMangleMode QMM) {
  Qualifiers Quals = Q_None;
  bool IsMember = false;
  bool IsMemberKnown = false;
  if (QMM == QualifierMangleMode::Mangle) {
    std::tie(Quals, IsMember) = demangleQualifiers(MangledName);
    IsMemberKnown = true;
  } else if (QMM == QualifierMangleMode::Result) {
    if (MangledName.consumeFront('?')) {
      std::tie(Quals, IsMember) = demangleQualifiers(MangledName);
      IsMemberKnown = true;
    }
  }

  Type *Ty = nullptr;
  if (isTagType(MangledName))
    Ty = demangleClassType(MangledName);
  else if (isPointerType(MangledName)) {
    if (!IsMemberKnown)
      IsMember = isMemberPointer(MangledName);

    if (IsMember)
      Ty = demangleMemberPointerType(MangledName);
    else
      Ty = demanglePointerType(MangledName);
  } else if (isArrayType(MangledName))
    Ty = demangleArrayType(MangledName);
  else if (isFunctionType(MangledName)) {
    if (MangledName.consumeFront("$$A8@@"))
      Ty = demangleFunctionType(MangledName, true, false);
    else {
      assert(MangledName.startsWith("$$A6"));
      MangledName.consumeFront("$$A6");
      Ty = demangleFunctionType(MangledName, false, false);
    }
  } else {
    Ty = demangleBasicType(MangledName);
    assert(Ty && !Error);
    if (!Ty || Error)
      return Ty;
  }

  Ty->Quals = Qualifiers(Ty->Quals | Quals);
  return Ty;
}

ReferenceKind Demangler::demangleReferenceKind(StringView &MangledName) {
  if (MangledName.consumeFront('G'))
    return ReferenceKind::LValueRef;
  else if (MangledName.consumeFront('H'))
    return ReferenceKind::RValueRef;
  return ReferenceKind::None;
}

void Demangler::demangleThrowSpecification(StringView &MangledName) {
  if (MangledName.consumeFront('Z'))
    return;

  Error = true;
}

FunctionType *Demangler::demangleFunctionType(StringView &MangledName,
                                              bool HasThisQuals,
                                              bool IsFunctionPointer) {
  FunctionType *FTy = Arena.alloc<FunctionType>();
  FTy->Prim = PrimTy::Function;
  FTy->IsFunctionPointer = IsFunctionPointer;

  if (HasThisQuals) {
    FTy->Quals = demanglePointerExtQualifiers(MangledName);
    FTy->RefKind = demangleReferenceKind(MangledName);
    FTy->Quals = Qualifiers(FTy->Quals | demangleQualifiers(MangledName).first);
  }

  // Fields that appear on both member and non-member functions.
  FTy->CallConvention = demangleCallingConvention(MangledName);

  // <return-type> ::= <type>
  //               ::= @ # structors (they have no declared return type)
  bool IsStructor = MangledName.consumeFront('@');
  if (!IsStructor)
    FTy->ReturnType = demangleType(MangledName, QualifierMangleMode::Result);

  FTy->Params = demangleFunctionParameterList(MangledName);

  demangleThrowSpecification(MangledName);

  return FTy;
}

Type *Demangler::demangleFunctionEncoding(StringView &MangledName) {
  FuncClass ExtraFlags = FuncClass::None;
  if (MangledName.consumeFront("$$J0"))
    ExtraFlags = FuncClass::ExternC;

  FuncClass FC = demangleFunctionClass(MangledName);
  FC = FuncClass(ExtraFlags | FC);

  FunctionType::ThisAdjustor *Adjustor = nullptr;
  if (FC & FuncClass::StaticThisAdjust) {
    Adjustor = Arena.alloc<FunctionType::ThisAdjustor>();
    Adjustor->StaticOffset = demangleSigned(MangledName);
  } else if (FC & FuncClass::VirtualThisAdjust) {
    Adjustor = Arena.alloc<FunctionType::ThisAdjustor>();
    if (FC & FuncClass::VirtualThisAdjustEx) {
      Adjustor->VBPtrOffset = demangleSigned(MangledName);
      Adjustor->VBOffsetOffset = demangleSigned(MangledName);
    }
    Adjustor->VtordispOffset = demangleSigned(MangledName);
    Adjustor->StaticOffset = demangleSigned(MangledName);
  }

  FunctionType *FTy = nullptr;
  if (FC & NoPrototype) {
    // This is an extern "C" function whose full signature hasn't been mangled.
    // This happens when we need to mangle a local symbol inside of an extern
    // "C" function.
    FTy = Arena.alloc<FunctionType>();
  } else {
    bool HasThisQuals = !(FC & (Global | Static));
    FTy = demangleFunctionType(MangledName, HasThisQuals, false);
  }
  FTy->ThisAdjust = Adjustor;
  FTy->FunctionClass = FC;

  return FTy;
}

// Reads a primitive type.
Type *Demangler::demangleBasicType(StringView &MangledName) {
  Type *Ty = Arena.alloc<Type>();

  if (MangledName.consumeFront("$$T")) {
    Ty->Prim = PrimTy::Nullptr;
    return Ty;
  }

  switch (MangledName.popFront()) {
  case 'X':
    Ty->Prim = PrimTy::Void;
    break;
  case 'D':
    Ty->Prim = PrimTy::Char;
    break;
  case 'C':
    Ty->Prim = PrimTy::Schar;
    break;
  case 'E':
    Ty->Prim = PrimTy::Uchar;
    break;
  case 'F':
    Ty->Prim = PrimTy::Short;
    break;
  case 'G':
    Ty->Prim = PrimTy::Ushort;
    break;
  case 'H':
    Ty->Prim = PrimTy::Int;
    break;
  case 'I':
    Ty->Prim = PrimTy::Uint;
    break;
  case 'J':
    Ty->Prim = PrimTy::Long;
    break;
  case 'K':
    Ty->Prim = PrimTy::Ulong;
    break;
  case 'M':
    Ty->Prim = PrimTy::Float;
    break;
  case 'N':
    Ty->Prim = PrimTy::Double;
    break;
  case 'O':
    Ty->Prim = PrimTy::Ldouble;
    break;
  case '_': {
    if (MangledName.empty()) {
      Error = true;
      return nullptr;
    }
    switch (MangledName.popFront()) {
    case 'N':
      Ty->Prim = PrimTy::Bool;
      break;
    case 'J':
      Ty->Prim = PrimTy::Int64;
      break;
    case 'K':
      Ty->Prim = PrimTy::Uint64;
      break;
    case 'W':
      Ty->Prim = PrimTy::Wchar;
      break;
    case 'S':
      Ty->Prim = PrimTy::Char16;
      break;
    case 'U':
      Ty->Prim = PrimTy::Char32;
      break;
    default:
      Error = true;
      return nullptr;
    }
    break;
  }
  default:
    Error = true;
    return nullptr;
  }
  return Ty;
}

UdtType *Demangler::demangleClassType(StringView &MangledName) {
  UdtType *UTy = Arena.alloc<UdtType>();

  switch (MangledName.popFront()) {
  case 'T':
    UTy->Prim = PrimTy::Union;
    break;
  case 'U':
    UTy->Prim = PrimTy::Struct;
    break;
  case 'V':
    UTy->Prim = PrimTy::Class;
    break;
  case 'W':
    if (MangledName.popFront() != '4') {
      Error = true;
      return nullptr;
    }
    UTy->Prim = PrimTy::Enum;
    break;
  default:
    assert(false);
  }

  UTy->UdtName = demangleFullyQualifiedTypeName(MangledName);
  return UTy;
}

static std::pair<Qualifiers, PointerAffinity>
demanglePointerCVQualifiers(StringView &MangledName) {
  if (MangledName.consumeFront("$$Q"))
    return std::make_pair(Q_None, PointerAffinity::RValueReference);

  switch (MangledName.popFront()) {
  case 'A':
    return std::make_pair(Q_None, PointerAffinity::Reference);
  case 'P':
    return std::make_pair(Q_None, PointerAffinity::Pointer);
  case 'Q':
    return std::make_pair(Q_Const, PointerAffinity::Pointer);
  case 'R':
    return std::make_pair(Q_Volatile, PointerAffinity::Pointer);
  case 'S':
    return std::make_pair(Qualifiers(Q_Const | Q_Volatile),
                          PointerAffinity::Pointer);
  default:
    assert(false && "Ty is not a pointer type!");
  }
  return std::make_pair(Q_None, PointerAffinity::Pointer);
}

// <pointer-type> ::= E? <pointer-cvr-qualifiers> <ext-qualifiers> <type>
//                       # the E is required for 64-bit non-static pointers
PointerType *Demangler::demanglePointerType(StringView &MangledName) {
  PointerType *Pointer = Arena.alloc<PointerType>();

  std::tie(Pointer->Quals, Pointer->Affinity) =
      demanglePointerCVQualifiers(MangledName);

  Pointer->Prim = PrimTy::Ptr;
  if (MangledName.consumeFront("6")) {
    Pointer->Pointee = demangleFunctionType(MangledName, false, true);
    return Pointer;
  }

  Qualifiers ExtQuals = demanglePointerExtQualifiers(MangledName);
  Pointer->Quals = Qualifiers(Pointer->Quals | ExtQuals);

  Pointer->Pointee = demangleType(MangledName, QualifierMangleMode::Mangle);
  return Pointer;
}

MemberPointerType *
Demangler::demangleMemberPointerType(StringView &MangledName) {
  MemberPointerType *Pointer = Arena.alloc<MemberPointerType>();
  Pointer->Prim = PrimTy::MemberPtr;

  PointerAffinity Affinity;
  std::tie(Pointer->Quals, Affinity) = demanglePointerCVQualifiers(MangledName);
  assert(Affinity == PointerAffinity::Pointer);

  Qualifiers ExtQuals = demanglePointerExtQualifiers(MangledName);
  Pointer->Quals = Qualifiers(Pointer->Quals | ExtQuals);

  if (MangledName.consumeFront("8")) {
    Pointer->MemberName = demangleFullyQualifiedSymbolName(MangledName);
    Pointer->Pointee = demangleFunctionType(MangledName, true, true);
  } else {
    Qualifiers PointeeQuals = Q_None;
    bool IsMember = false;
    std::tie(PointeeQuals, IsMember) = demangleQualifiers(MangledName);
    assert(IsMember);
    Pointer->MemberName = demangleFullyQualifiedSymbolName(MangledName);

    Pointer->Pointee = demangleType(MangledName, QualifierMangleMode::Drop);
    Pointer->Pointee->Quals = PointeeQuals;
  }

  return Pointer;
}

Qualifiers Demangler::demanglePointerExtQualifiers(StringView &MangledName) {
  Qualifiers Quals = Q_None;
  if (MangledName.consumeFront('E'))
    Quals = Qualifiers(Quals | Q_Pointer64);
  if (MangledName.consumeFront('I'))
    Quals = Qualifiers(Quals | Q_Restrict);
  if (MangledName.consumeFront('F'))
    Quals = Qualifiers(Quals | Q_Unaligned);

  return Quals;
}

ArrayType *Demangler::demangleArrayType(StringView &MangledName) {
  assert(MangledName.front() == 'Y');
  MangledName.popFront();

  uint64_t Rank = 0;
  bool IsNegative = false;
  std::tie(Rank, IsNegative) = demangleNumber(MangledName);
  if (IsNegative || Rank == 0) {
    Error = true;
    return nullptr;
  }

  ArrayType *ATy = Arena.alloc<ArrayType>();
  ATy->Prim = PrimTy::Array;
  ATy->Dims = Arena.alloc<ArrayDimension>();
  ArrayDimension *Dim = ATy->Dims;
  for (uint64_t I = 0; I < Rank; ++I) {
    std::tie(Dim->Dim, IsNegative) = demangleNumber(MangledName);
    if (IsNegative) {
      Error = true;
      return nullptr;
    }
    if (I + 1 < Rank) {
      Dim->Next = Arena.alloc<ArrayDimension>();
      Dim = Dim->Next;
    }
  }

  if (MangledName.consumeFront("$$C")) {
    bool IsMember = false;
    std::tie(ATy->Quals, IsMember) = demangleQualifiers(MangledName);
    if (IsMember) {
      Error = true;
      return nullptr;
    }
  }

  ATy->ElementType = demangleType(MangledName, QualifierMangleMode::Drop);
  return ATy;
}

// Reads a function or a template parameters.
FunctionParams
Demangler::demangleFunctionParameterList(StringView &MangledName) {
  // Empty parameter list.
  if (MangledName.consumeFront('X'))
    return {};

  FunctionParams *Head;
  FunctionParams **Current = &Head;
  while (!Error && !MangledName.startsWith('@') &&
         !MangledName.startsWith('Z')) {

    if (startsWithDigit(MangledName)) {
      size_t N = MangledName[0] - '0';
      if (N >= Backrefs.FunctionParamCount) {
        Error = true;
        return {};
      }
      MangledName = MangledName.dropFront();

      *Current = Arena.alloc<FunctionParams>();
      (*Current)->Current = Backrefs.FunctionParams[N]->clone(Arena);
      Current = &(*Current)->Next;
      continue;
    }

    size_t OldSize = MangledName.size();

    *Current = Arena.alloc<FunctionParams>();
    (*Current)->Current = demangleType(MangledName, QualifierMangleMode::Drop);

    size_t CharsConsumed = OldSize - MangledName.size();
    assert(CharsConsumed != 0);

    // Single-letter types are ignored for backreferences because memorizing
    // them doesn't save anything.
    if (Backrefs.FunctionParamCount <= 9 && CharsConsumed > 1)
      Backrefs.FunctionParams[Backrefs.FunctionParamCount++] =
          (*Current)->Current;

    Current = &(*Current)->Next;
  }

  if (Error)
    return {};

  // A non-empty parameter list is terminated by either 'Z' (variadic) parameter
  // list or '@' (non variadic).  Careful not to consume "@Z", as in that case
  // the following Z could be a throw specifier.
  if (MangledName.consumeFront('@'))
    return *Head;

  if (MangledName.consumeFront('Z')) {
    Head->IsVariadic = true;
    return *Head;
  }

  Error = true;
  return {};
}

TemplateParams *
Demangler::demangleTemplateParameterList(StringView &MangledName) {
  TemplateParams *Head;
  TemplateParams **Current = &Head;
  while (!Error && !MangledName.startsWith('@')) {
    // Template parameter lists don't participate in back-referencing.
    *Current = Arena.alloc<TemplateParams>();

    TemplateParams &TP = **Current;

    // Empty parameter pack.
    if (MangledName.consumeFront("$S") || MangledName.consumeFront("$$V") ||
        MangledName.consumeFront("$$$V")) {
      TP.IsEmptyParameterPack = true;
      break;
    }

    if (MangledName.consumeFront("$$Y")) {
      // Template alias
      TP.IsTemplateTemplate = true;
      TP.IsAliasTemplate = true;
      TP.ParamName = demangleFullyQualifiedTypeName(MangledName);
    } else if (MangledName.consumeFront("$$B")) {
      // Array
      TP.ParamType = demangleType(MangledName, QualifierMangleMode::Drop);
    } else if (MangledName.consumeFront("$$C")) {
      // Type has qualifiers.
      TP.ParamType = demangleType(MangledName, QualifierMangleMode::Mangle);
    } else if (MangledName.startsWith("$1") || MangledName.startsWith("$H") ||
               MangledName.startsWith("$I") || MangledName.startsWith("$J")) {
      MangledName = MangledName.dropFront();
      // 1 - single inheritance       <name>
      // H - multiple inheritance     <name> <number>
      // I - virtual inheritance      <name> <number> <number> <number>
      // J - unspecified inheritance  <name> <number> <number> <number>
      char InheritanceSpecifier = MangledName.popFront();
      // Pointer to member
      Symbol *S = MangledName.startsWith('?') ? parse(MangledName) : nullptr;
      switch (InheritanceSpecifier) {
      case 'J':
        TP.ThunkOffsets[TP.ThunkOffsetCount++] = demangleSigned(MangledName);
        LLVM_FALLTHROUGH;
      case 'I':
        TP.ThunkOffsets[TP.ThunkOffsetCount++] = demangleSigned(MangledName);
        LLVM_FALLTHROUGH;
      case 'H':
        TP.ThunkOffsets[TP.ThunkOffsetCount++] = demangleSigned(MangledName);
        LLVM_FALLTHROUGH;
      case '1':
        break;
      default:
        Error = true;
        break;
      }
      TP.PointerToSymbol = true;
      if (S) {
        TP.ParamName = S->SymbolName;
        TP.ParamType = S->SymbolType;
      } else
        TP.NullptrLiteral = true;
    } else if (MangledName.startsWith("$E?")) {
      MangledName.consumeFront("$E");
      // Reference to symbol
      Symbol *S = parse(MangledName);
      TP.ParamName = S->SymbolName;
      TP.ParamType = S->SymbolType;
      TP.ReferenceToSymbol = true;
    } else if (MangledName.startsWith("$F") || MangledName.startsWith("$G")) {
      // Data member pointer.
      MangledName = MangledName.dropFront();
      char InheritanceSpecifier = MangledName.popFront();

      switch (InheritanceSpecifier) {
      case 'G':
        TP.ThunkOffsets[TP.ThunkOffsetCount++] = demangleSigned(MangledName);
        LLVM_FALLTHROUGH;
      case 'F':
        TP.ThunkOffsets[TP.ThunkOffsetCount++] = demangleSigned(MangledName);
        TP.ThunkOffsets[TP.ThunkOffsetCount++] = demangleSigned(MangledName);
        LLVM_FALLTHROUGH;
      case '0':
        break;
      default:
        Error = true;
        break;
      }
      TP.DataMemberPointer = true;

    } else if (MangledName.consumeFront("$0")) {
      // Integral non-type template parameter
      bool IsNegative = false;
      uint64_t Value = 0;
      std::tie(Value, IsNegative) = demangleNumber(MangledName);

      TP.IsIntegerLiteral = true;
      TP.IntegerLiteralIsNegative = IsNegative;
      TP.IntegralValue = Value;
    } else {
      TP.ParamType = demangleType(MangledName, QualifierMangleMode::Drop);
    }
    if (Error)
      return nullptr;

    Current = &TP.Next;
  }

  if (Error)
    return nullptr;

  // Template parameter lists cannot be variadic, so it can only be terminated
  // by @.
  if (MangledName.consumeFront('@'))
    return Head;
  Error = true;
  return nullptr;
}

void Demangler::output(const Symbol *S, OutputStream &OS) {
  if (S->Category == SymbolCategory::Unknown) {
    outputName(OS, S->SymbolName, S->SymbolType);
    return;
  }

  if (S->Category == SymbolCategory::SpecialOperator) {
    outputSpecialOperator(OS, S->SymbolName);
    return;
  }

  // Converts an AST to a string.
  //
  // Converting an AST representing a C++ type to a string is tricky due
  // to the bad grammar of the C++ declaration inherited from C. You have
  // to construct a string from inside to outside. For example, if a type
  // X is a pointer to a function returning int, the order you create a
  // string becomes something like this:
  //
  //   (1) X is a pointer: *X
  //   (2) (1) is a function returning int: int (*X)()
  //
  // So you cannot construct a result just by appending strings to a result.
  //
  // To deal with this, we split the function into two. outputPre() writes
  // the "first half" of type declaration, and outputPost() writes the
  // "second half". For example, outputPre() writes a return type for a
  // function and outputPost() writes an parameter list.
  if (S->SymbolType) {
    Type::outputPre(OS, *S->SymbolType);
    outputName(OS, S->SymbolName, S->SymbolType);
    Type::outputPost(OS, *S->SymbolType);
  } else {
    outputQualifiers(OS, S->SymbolQuals);
    outputName(OS, S->SymbolName, nullptr);
  }
}

void Demangler::dumpBackReferences() {
  std::printf("%d function parameter backreferences\n",
              (int)Backrefs.FunctionParamCount);

  // Create an output stream so we can render each type.
  OutputStream OS = OutputStream::create(nullptr, 0, 1024);
  for (size_t I = 0; I < Backrefs.FunctionParamCount; ++I) {
    OS.setCurrentPosition(0);

    Type *T = Backrefs.FunctionParams[I];
    Type::outputPre(OS, *T);
    Type::outputPost(OS, *T);

    std::printf("  [%d] - %.*s\n", (int)I, (int)OS.getCurrentPosition(),
                OS.getBuffer());
  }
  std::free(OS.getBuffer());

  if (Backrefs.FunctionParamCount > 0)
    std::printf("\n");
  std::printf("%d name backreferences\n", (int)Backrefs.NamesCount);
  for (size_t I = 0; I < Backrefs.NamesCount; ++I) {
    std::printf("  [%d] - %.*s\n", (int)I, (int)Backrefs.Names[I].size(),
                Backrefs.Names[I].begin());
  }
  if (Backrefs.NamesCount > 0)
    std::printf("\n");
}

char *llvm::microsoftDemangle(const char *MangledName, char *Buf, size_t *N,
                              int *Status, MSDemangleFlags Flags) {
  Demangler D;
  StringView Name{MangledName};
  Symbol *S = D.parse(Name);

  if (Flags & MSDF_DumpBackrefs)
    D.dumpBackReferences();
  OutputStream OS = OutputStream::create(Buf, N, 1024);
  if (D.Error) {
    OS << MangledName;
    *Status = llvm::demangle_invalid_mangled_name;
  } else {
    D.output(S, OS);
    *Status = llvm::demangle_success;
  }

  OS << '\0';
  return OS.getBuffer();
}