File: SwiftLanguageRuntime.cpp

package info (click to toggle)
swiftlang 6.0.3-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,519,992 kB
  • sloc: cpp: 9,107,863; ansic: 2,040,022; asm: 1,135,751; python: 296,500; objc: 82,456; f90: 60,502; lisp: 34,951; pascal: 19,946; sh: 18,133; perl: 7,482; ml: 4,937; javascript: 4,117; makefile: 3,840; awk: 3,535; xml: 914; fortran: 619; cs: 573; ruby: 573
file content (2918 lines) | stat: -rw-r--r-- 105,826 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
//===-- SwiftLanguageRuntime.cpp ------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//

#include "SwiftLanguageRuntime.h"
#include "Plugins/LanguageRuntime/Swift/LLDBMemoryReader.h"
#include "ReflectionContextInterface.h"
#include "SwiftLanguageRuntimeImpl.h"
#include "SwiftMetadataCache.h"

#include "Plugins/ExpressionParser/Swift/SwiftPersistentExpressionState.h"
#include "Plugins/Process/Utility/RegisterContext_x86.h"
#include "Plugins/TypeSystem/Clang/TypeSystemClang.h"
#include "Utility/ARM64_DWARF_Registers.h"
#include "lldb/Breakpoint/StoppointCallbackContext.h"
#include "lldb/Core/Debugger.h"
#include "lldb/Core/JITSection.h"
#include "lldb/Core/PluginManager.h"
#include "lldb/Core/Progress.h"
#include "lldb/Core/Section.h"
#include "lldb/Core/ValueObject.h"
#include "lldb/Core/ValueObjectCast.h"
#include "lldb/Core/ValueObjectConstResult.h"
#include "lldb/Core/ValueObjectVariable.h"
#include "lldb/DataFormatters/StringPrinter.h"
#include "lldb/Host/OptionParser.h"
#include "lldb/Host/SafeMachO.h"
#include "lldb/Interpreter/CommandInterpreter.h"
#include "lldb/Interpreter/CommandObject.h"
#include "lldb/Interpreter/CommandObjectMultiword.h"
#include "lldb/Interpreter/CommandReturnObject.h"
#include "lldb/Symbol/Function.h"
#include "lldb/Symbol/VariableList.h"
#include "lldb/Target/RegisterContext.h"
#include "lldb/Utility/LLDBLog.h"
#include "lldb/Utility/Log.h"
#include "lldb/Utility/OptionParsing.h"
#include "lldb/Utility/Timer.h"

#include "lldb/lldb-enumerations.h"
#include "swift/AST/ASTMangler.h"
#include "swift/Demangling/Demangle.h"
#include "swift/RemoteInspection/ReflectionContext.h"
#include "swift/RemoteAST/RemoteAST.h"

#include "clang/AST/ASTContext.h"
#include "clang/AST/DeclCXX.h"

#include "llvm/ADT/StringRef.h"
#include "llvm/BinaryFormat/Dwarf.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/Memory.h"

// FIXME: we should not need this
#include "Plugins/Language/Swift/SwiftFormatters.h"
#include "Plugins/Language/Swift/SwiftRuntimeFailureRecognizer.h"

using namespace lldb;
using namespace lldb_private;

LLDB_PLUGIN_DEFINE(SwiftLanguageRuntime)

namespace lldb_private {
char SwiftLanguageRuntime::ID = 0;

extern "C" unsigned long long _swift_classIsSwiftMask = 0;

const char *SwiftLanguageRuntime::GetErrorBackstopName() {
  return "swift_errorInMain";
}

const char *SwiftLanguageRuntime::GetStandardLibraryBaseName() {
  return "swiftCore";
}

static ConstString GetStandardLibraryName(Process &process) {
  // This result needs to be stored in the constructor.
  PlatformSP platform_sp(process.GetTarget().GetPlatform());
  if (platform_sp)
    return platform_sp->GetFullNameForDylib(
        ConstString(SwiftLanguageRuntime::GetStandardLibraryBaseName()));
  return {};
}

ConstString SwiftLanguageRuntime::GetStandardLibraryName() {
  return ::GetStandardLibraryName(*m_process);
}

static bool IsModuleSwiftRuntime(lldb_private::Process &process,
                                 lldb_private::Module &module) {
  return module.GetFileSpec().GetFilename() == GetStandardLibraryName(process);
}

AppleObjCRuntimeV2 *
SwiftLanguageRuntime::GetObjCRuntime(lldb_private::Process &process) {
  if (auto objc_runtime = ObjCLanguageRuntime::Get(process)) {
    if (objc_runtime->GetPluginName() ==
        AppleObjCRuntimeV2::GetPluginNameStatic())
      return (AppleObjCRuntimeV2 *)objc_runtime;
  }
  return nullptr;
}

AppleObjCRuntimeV2 *SwiftLanguageRuntime::GetObjCRuntime() {
  return GetObjCRuntime(*m_process);
}

enum class RuntimeKind { Swift, ObjC };

/// Detect a statically linked Swift runtime by looking for a well-known symbol.
static bool IsStaticSwiftRuntime(Module &image) {
  static ConstString swift_reflection_version_sym("swift_release");
  return image.FindFirstSymbolWithNameAndType(swift_reflection_version_sym);
}

/// \return the Swift or Objective-C runtime found in the loaded images.
static ModuleSP findRuntime(Process &process, RuntimeKind runtime_kind) {
  AppleObjCRuntimeV2 *objc_runtime = nullptr;
  if (runtime_kind == RuntimeKind::ObjC) {
    objc_runtime = SwiftLanguageRuntime::GetObjCRuntime(process);
    if (!objc_runtime)
      return {};
  }

  ModuleSP runtime_image;
  process.GetTarget().GetImages().ForEach([&](const ModuleSP &image) {
    if (runtime_kind == RuntimeKind::Swift && image &&
        IsModuleSwiftRuntime(process, *image)) {
      runtime_image = image;
      return false;
    }
    if (runtime_kind == RuntimeKind::ObjC &&
        objc_runtime->IsModuleObjCLibrary(image)) {
      runtime_image = image;
      return false;
    }
    return true;
  });

  if (!runtime_image && runtime_kind == RuntimeKind::Swift) {
    // Do a more expensive search for a statically linked Swift runtime.
    process.GetTarget().GetImages().ForEach([&](const ModuleSP &image) {
      if (image && IsStaticSwiftRuntime(*image)) {
        runtime_image = image;
        return false;
      }
      return true;
    });
  }
  return runtime_image;
}

static std::optional<lldb::addr_t>
FindSymbolForSwiftObject(Process &process, RuntimeKind runtime_kind,
                         StringRef object, const SymbolType sym_type) {
  ModuleSP image = findRuntime(process, runtime_kind);
  Target &target = process.GetTarget();
  if (!image) {
    // Don't diagnose a missing Objective-C runtime on platforms that
    // don't have one.
    if (runtime_kind == RuntimeKind::ObjC) {
      auto *obj_file = target.GetExecutableModule()->GetObjectFile();
      bool have_objc_interop =
          obj_file && obj_file->GetPluginName().equals("mach-o");
      if (!have_objc_interop)
        return {};
    }
    target.GetDebugger().GetAsyncErrorStream()->Printf(
        "Couldn't find the %s runtime library in loaded images.\n",
        (runtime_kind == RuntimeKind::Swift) ? "Swift" : "Objective-C");
    return {};
  }

  SymbolContextList sc_list;
  image->FindSymbolsWithNameAndType(ConstString(object), sym_type, sc_list);
  if (sc_list.GetSize() != 1)
    return {};

  SymbolContext SwiftObject_Class;
  if (!sc_list.GetContextAtIndex(0, SwiftObject_Class))
    return {};
  if (!SwiftObject_Class.symbol)
    return {};
  lldb::addr_t addr =
      SwiftObject_Class.symbol->GetAddress().GetLoadAddress(&target);
  if (addr && addr != LLDB_INVALID_ADDRESS)
    return addr;

  return {};
}

static lldb::BreakpointResolverSP
CreateExceptionResolver(const lldb::BreakpointSP &bkpt, bool catch_bp, bool throw_bp) {
  BreakpointResolverSP resolver_sp;

  if (throw_bp)
    resolver_sp.reset(new BreakpointResolverName(
        bkpt, "swift_willThrow", eFunctionNameTypeBase, eLanguageTypeUnknown,
        Breakpoint::Exact, 0, eLazyBoolNo));
  // FIXME: We don't do catch breakpoints for ObjC yet.
  // Should there be some way for the runtime to specify what it can do in this
  // regard?
  return resolver_sp;
}

/// Simple Swift programs may not actually depend on the Swift runtime
/// library (libswiftCore.dylib), but if it is missing, what we can do
/// is limited. This implementation represents that case.
class SwiftLanguageRuntimeStub {
  Process &m_process;

public:
  SwiftLanguageRuntimeStub(Process &process) : m_process(process) {}

#define STUB_LOG()                                                             \
  do {                                                                         \
    LLDB_LOGF(GetLog(LLDBLog::Expressions | LLDBLog::Types),                   \
              "Swift language runtime isn't available because %s is not "      \
              "loaded in the process.",                                        \
              GetStandardLibraryName(m_process).AsCString());                  \
    assert(false && "called into swift language runtime stub");                \
  } while (0)

  ThreadSafeReflectionContext GetReflectionContext() {
    STUB_LOG();
    return ThreadSafeReflectionContext();
  }

  bool GetDynamicTypeAndAddress(ValueObject &in_value,
                                lldb::DynamicValueType use_dynamic,
                                TypeAndOrName &class_type_or_name,
                                Address &address,
                                Value::ValueType &value_type) {
    STUB_LOG();
    return false;
  }

  TypeAndOrName FixUpDynamicType(const TypeAndOrName &type_and_or_name,
                                 ValueObject &static_value) {
    STUB_LOG();
    return {};
  }

  bool IsTaggedPointer(lldb::addr_t addr, CompilerType type) {
    STUB_LOG();
    return false;
  }

  std::pair<lldb::addr_t, bool> FixupPointerValue(lldb::addr_t addr,
                                                  CompilerType type) {
    STUB_LOG();
    return {addr, false};
  }

  lldb::addr_t FixupAddress(lldb::addr_t addr, CompilerType type,
                            Status &error) {
    STUB_LOG();
    return addr;
  }

  CompilerType GetTypeFromMetadata(TypeSystemSwift &tss, Address addr) {
    STUB_LOG();
    return {};
  }

  void SymbolsDidLoad(const ModuleList &module_list) {}
  void ModulesDidLoad(const ModuleList &module_list) {}

  bool IsStoredInlineInBuffer(CompilerType type) {
    STUB_LOG();
    return false;
  }

  void DumpTyperef(CompilerType type, TypeSystemSwiftTypeRef *module_holder,
                   Stream *s) {
    STUB_LOG();
  }

  std::optional<uint64_t> GetMemberVariableOffset(CompilerType instance_type,
                                                   ValueObject *instance,
                                                   llvm::StringRef member_name,
                                                   Status *error) {
    STUB_LOG();
    return {};
  }

  llvm::Expected<uint32_t> GetNumChildren(CompilerType type,
                                          ExecutionContextScope *exe_scopej) {
    STUB_LOG();
    return 0;
  }

  std::optional<std::string> GetEnumCaseName(CompilerType type,
                                              const DataExtractor &data,
                                              ExecutionContext *exe_ctx) {
    STUB_LOG();
    return {};
  }

  std::pair<SwiftLanguageRuntime::LookupResult, std::optional<size_t>>
  GetIndexOfChildMemberWithName(CompilerType type, llvm::StringRef name,
                                ExecutionContext *exe_ctx,
                                bool omit_empty_base_classes,
                                std::vector<uint32_t> &child_indexes) {
    STUB_LOG();
    return {};
  }

  CompilerType GetChildCompilerTypeAtIndex(
      CompilerType type, size_t idx, bool transparent_pointers,
      bool omit_empty_base_classes, bool ignore_array_bounds,
      std::string &child_name, uint32_t &child_byte_size,
      int32_t &child_byte_offset, uint32_t &child_bitfield_bit_size,
      uint32_t &child_bitfield_bit_offset, bool &child_is_base_class,
      bool &child_is_deref_of_parent, ValueObject *valobj,
      uint64_t &language_flags) {
    STUB_LOG();
    return {};
  }

  std::optional<unsigned> GetNumFields(CompilerType type,
                                        ExecutionContext *exe_ctx) {
    STUB_LOG();
    return {};
  }

  llvm::Error GetObjectDescription(Stream &str, ValueObject &object) {
    STUB_LOG();
    return llvm::createStringError("Swift runtime not initialized");
  }

  void AddToLibraryNegativeCache(llvm::StringRef library_name) {}

  bool IsInLibraryNegativeCache(llvm::StringRef library_name) {
    return false;
  }

  void ReleaseAssociatedRemoteASTContext(swift::ASTContext *ctx) {}

  CompilerType BindGenericTypeParameters(StackFrame &stack_frame,
                                         CompilerType base_type) {
    STUB_LOG();
    return {};
  }

  CompilerType BindGenericTypeParameters(
      CompilerType unbound_type,
      std::function<CompilerType(unsigned, unsigned)> type_finder) {
    STUB_LOG();
    return {};
  }

  CompilerType GetConcreteType(ExecutionContextScope *exe_scope,
                               ConstString abstract_type_name) {
    STUB_LOG();
    return {};
  }

  std::optional<uint64_t> GetBitSize(CompilerType type,
                                      ExecutionContextScope *exe_scope) {
    STUB_LOG();
    return {};
  }

  std::optional<uint64_t> GetByteStride(CompilerType type) {
    STUB_LOG();
    return {};
  }

  std::optional<size_t> GetBitAlignment(CompilerType type,
                                         ExecutionContextScope *exe_scope) {
    STUB_LOG();
    return {};
  }

  bool IsValidErrorValue(ValueObject &in_value) {
    STUB_LOG();
    return {};
  }

  lldb::SyntheticChildrenSP
  GetBridgedSyntheticChildProvider(ValueObject &valobj) {
    STUB_LOG();
    return {};
  }

  void WillStartExecutingUserExpression(bool runs_in_playground_or_repl) {
    if (!runs_in_playground_or_repl)
      STUB_LOG();
  }

  void DidFinishExecutingUserExpression(bool runs_in_playground_or_repl) {
    if (!runs_in_playground_or_repl)
      STUB_LOG();
  }

  bool IsABIStable() {
    STUB_LOG();

    // Pick a sensible default.
    return m_process.GetTarget().GetArchitecture().GetTriple().isOSDarwin()
               ? true
               : false;
  }

  SwiftLanguageRuntimeStub(const SwiftLanguageRuntimeStub &) = delete;
  const SwiftLanguageRuntimeStub &
  operator=(const SwiftLanguageRuntimeStub &) = delete;
};

static std::unique_ptr<swift::SwiftObjectFileFormat>
GetObjectFileFormat(llvm::Triple::ObjectFormatType obj_format_type) {
  std::unique_ptr<swift::SwiftObjectFileFormat> obj_file_format;
  switch (obj_format_type) {
  case llvm::Triple::MachO:
    obj_file_format = std::make_unique<swift::SwiftObjectFileFormatMachO>();
    break;
  case llvm::Triple::ELF:
    obj_file_format = std::make_unique<swift::SwiftObjectFileFormatELF>();
    break;
  case llvm::Triple::COFF:
    obj_file_format = std::make_unique<swift::SwiftObjectFileFormatCOFF>();
    break;
  default:
    if (Log *log = GetLog(LLDBLog::Types))
      log->Printf("%s: Could not find out swift reflection section names for "
                  "object format type.",
                  __FUNCTION__);
  }
  return obj_file_format;
}

static bool HasReflectionInfo(ObjectFile *obj_file) {
  if (!obj_file)
    return false;

  auto findSectionInObject = [&](StringRef name) {
    ConstString section_name(name);
    SectionSP section_sp =
        obj_file->GetSectionList()->FindSectionByName(section_name);
    if (section_sp)
      return true;
    return false;
  };

  const auto obj_format_type =
      obj_file->GetArchitecture().GetTriple().getObjectFormat();
  auto obj_file_format_up = GetObjectFileFormat(obj_format_type);
  if (!obj_file_format_up)
    return false;

  StringRef field_md =
      obj_file_format_up->getSectionName(swift::ReflectionSectionKind::fieldmd);
  StringRef assocty =
      obj_file_format_up->getSectionName(swift::ReflectionSectionKind::assocty);
  StringRef builtin =
      obj_file_format_up->getSectionName(swift::ReflectionSectionKind::builtin);
  StringRef capture =
      obj_file_format_up->getSectionName(swift::ReflectionSectionKind::capture);
  StringRef typeref =
      obj_file_format_up->getSectionName(swift::ReflectionSectionKind::typeref);
  StringRef reflstr =
      obj_file_format_up->getSectionName(swift::ReflectionSectionKind::reflstr);

  bool hasReflectionSection =
      findSectionInObject(field_md) || findSectionInObject(assocty) ||
      findSectionInObject(builtin) || findSectionInObject(capture) ||
      findSectionInObject(typeref) || findSectionInObject(reflstr);
  return hasReflectionSection;
}

ThreadSafeReflectionContext
SwiftLanguageRuntimeImpl::GetReflectionContext() {
  m_reflection_ctx_mutex.lock();
  SetupReflection();
  // SetupReflection can potentially fail.
  if (m_initialized_reflection_ctx)
    ProcessModulesToAdd();
  return {m_reflection_ctx.get(), m_reflection_ctx_mutex};
}

void SwiftLanguageRuntimeImpl::ProcessModulesToAdd() {
  // A snapshot of the modules to be processed. This is necessary because
  // AddModuleToReflectionContext may recursively call into this function again.
  ModuleList modules_to_add_snapshot;
  modules_to_add_snapshot.Swap(m_modules_to_add);

  if (modules_to_add_snapshot.IsEmpty())
    return;

  auto &target = m_process.GetTarget();
  auto exe_module = target.GetExecutableModule();
  Progress progress("Setting up Swift reflection", {}, modules_to_add_snapshot.GetSize());
  size_t completion = 0;

  // Add all defered modules to reflection context that were added to
  // the target since this SwiftLanguageRuntime was created.
  modules_to_add_snapshot.ForEach([&](const ModuleSP &module_sp) -> bool {
    AddModuleToReflectionContext(module_sp);
    progress.Increment(++completion,
                       module_sp->GetFileSpec().GetFilename().AsCString());
    return true;
  });
}

SwiftMetadataCache *
SwiftLanguageRuntimeImpl::GetSwiftMetadataCache() {
  if (!m_swift_metadata_cache.is_enabled())
    return {};
  return &m_swift_metadata_cache;
}

void SwiftLanguageRuntimeImpl::SetupReflection() {
  LLDB_SCOPED_TIMER();


  std::lock_guard<std::recursive_mutex> lock(m_reflection_ctx_mutex);
  if (m_initialized_reflection_ctx)
    return;

  // The global ABI bit is read by the Swift runtime library.
  SetupABIBit();

  auto &target = m_process.GetTarget();
  auto exe_module = target.GetExecutableModule();

  auto *log = GetLog(LLDBLog::Types);
  if (!exe_module) {
    LLDB_LOGF(log, "%s: Failed to get executable module",
              LLVM_PRETTY_FUNCTION);
    m_initialized_reflection_ctx = false;
    return;
  }

  bool objc_interop = (bool)findRuntime(m_process, RuntimeKind::ObjC);
  const char *objc_interop_msg =
      objc_interop ? "with Objective-C interopability" : "Swift only";

  auto &triple = exe_module->GetArchitecture().GetTriple();
  uint32_t ptr_size = m_process.GetAddressByteSize();
  LLDB_LOG(log, "Initializing a {0}-bit reflection context ({1}) for \"{2}\"",
           ptr_size * 8, triple.str(), objc_interop_msg);
  if (ptr_size == 4 || ptr_size == 8)
    m_reflection_ctx = ReflectionContextInterface::CreateReflectionContext(
        ptr_size, this->GetMemoryReader(), objc_interop,
        GetSwiftMetadataCache());
  if (!m_reflection_ctx)
    LLDB_LOG(log, "Could not initialize reflection context for \"{0}\"",
             triple.str());
  // We set m_initialized_reflection_ctx to true here because
  // AddModuleToReflectionContext can potentially call into SetupReflection
  // again (which will early exit). This is safe to do since every other thread
  // using reflection context will have to wait until all the modules are added,
  // since the thread performing the initialization locked the mutex.
  m_initialized_reflection_ctx = true;
}

bool SwiftLanguageRuntimeImpl::IsABIStable() {
  GetReflectionContext();
  return _swift_classIsSwiftMask == 2;
}

void SwiftLanguageRuntimeImpl::SetupSwiftError() {
  m_SwiftNativeNSErrorISA =
      FindSymbolForSwiftObject(m_process, RuntimeKind::Swift,
                               "__SwiftNativeNSError", eSymbolTypeObjCClass);
}

std::optional<lldb::addr_t>
SwiftLanguageRuntimeImpl::GetSwiftNativeNSErrorISA() {
  return m_SwiftNativeNSErrorISA;
}

void SwiftLanguageRuntimeImpl::SetupExclusivity() {
  m_dynamic_exclusivity_flag_addr = FindSymbolForSwiftObject(
      m_process, RuntimeKind::Swift, "_swift_disableExclusivityChecking",
      eSymbolTypeData);
  Log *log(GetLog(LLDBLog::Expressions));
  if (log)
    log->Printf(
        "SwiftLanguageRuntime: _swift_disableExclusivityChecking = %llu",
        m_dynamic_exclusivity_flag_addr ? *m_dynamic_exclusivity_flag_addr : 0);
}

std::optional<lldb::addr_t>
SwiftLanguageRuntimeImpl::GetDynamicExclusivityFlagAddr() {
  return m_dynamic_exclusivity_flag_addr;
}

void SwiftLanguageRuntimeImpl::SetupABIBit() {
  if (FindSymbolForSwiftObject(m_process, RuntimeKind::ObjC,
                               "objc_debug_swift_stable_abi_bit",
                               eSymbolTypeAny))
    _swift_classIsSwiftMask = 2;
  else
    _swift_classIsSwiftMask = 1;
}

SwiftLanguageRuntimeImpl::SwiftLanguageRuntimeImpl(Process &process)
    : m_process(process) {
  // The global ABI bit is read by the Swift runtime library.
  SetupExclusivity();
  SetupSwiftError();
  Target &target = m_process.GetTarget();
  m_modules_to_add.Append(target.GetImages());
  RegisterSwiftRuntimeFailureRecognizer(m_process);
}

LanguageRuntime *
SwiftLanguageRuntime::CreateInstance(Process *process,
                                     lldb::LanguageType language) {
  if ((language != eLanguageTypeSwift) || !process)
    return nullptr;
  return new SwiftLanguageRuntime(process);
}

SwiftLanguageRuntime::SwiftLanguageRuntime(Process *process)
    : LanguageRuntime(process) {
  // It's not possible to bring up a full SwiftLanguageRuntime if the Swift
  // runtime library hasn't been loaded yet.
  if (findRuntime(*process, RuntimeKind::Swift))
    m_impl = std::make_unique<SwiftLanguageRuntimeImpl>(*process);
  else
    m_stub = std::make_unique<SwiftLanguageRuntimeStub>(*process);
}

void SwiftLanguageRuntime::ModulesDidLoad(const ModuleList &module_list) {
  assert(m_process && "modules loaded without process");
  if (m_impl) {
    m_impl->ModulesDidLoad(module_list);
    return;
  }

  bool did_load_runtime = false;
  module_list.ForEach([&](const ModuleSP &module_sp) -> bool {
    did_load_runtime |= IsModuleSwiftRuntime(*m_process, *module_sp) ||
                        IsStaticSwiftRuntime(*module_sp);
    return !did_load_runtime;
  });
  if (did_load_runtime) {
    m_impl = std::make_unique<SwiftLanguageRuntimeImpl>(*m_process);
    m_impl->ModulesDidLoad(module_list);
  }
}

static llvm::SmallVector<llvm::StringRef, 1>
GetLikelySwiftImageNamesForModule(ModuleSP module) {
  if (!module || !module->GetFileSpec())
    return {};

  auto name =
      module->GetFileSpec().GetFileNameStrippingExtension().GetStringRef();
  if (name == "libswiftCore")
    name = "Swift";
  if (name.startswith("libswift"))
    name = name.drop_front(8);
  if (name.startswith("lib"))
    name = name.drop_front(3);
  return {name};
}

bool SwiftLanguageRuntimeImpl::AddJitObjectFileToReflectionContext(
    ObjectFile &obj_file, llvm::Triple::ObjectFormatType obj_format_type,
      llvm::SmallVector<llvm::StringRef, 1> likely_module_names) {
  assert(obj_file.GetType() == ObjectFile::eTypeJIT &&
         "Not a JIT object file!");
  auto obj_file_format = GetObjectFileFormat(obj_format_type);

  if (!obj_file_format)
    return false;

  auto reflection_info_id = m_reflection_ctx->AddImage(
      [&](swift::ReflectionSectionKind section_kind)
          -> std::pair<swift::remote::RemoteRef<void>, uint64_t> {
        auto section_name = obj_file_format->getSectionName(section_kind);
        for (auto section : *obj_file.GetSectionList()) {
          JITSection *jit_section = llvm::dyn_cast<JITSection>(section.get());
          if (jit_section && section->GetName().AsCString() == section_name) {
            DataExtractor extractor;
            auto section_size = section->GetSectionData(extractor);
            if (!section_size)
              return {};
            auto size = jit_section->getNonJitSize();
            auto data = extractor.GetData();
            if (section_size < size || !data.begin())
              return {};

            auto *Buf = malloc(size);
            std::memcpy(Buf, data.begin(), size);
            swift::remote::RemoteRef<void> remote_ref(section->GetFileAddress(),
                                                      Buf);

            return {remote_ref, size};
          }
        }
        return {};
      },
      likely_module_names);
  // We don't care to cache modules generated by the jit, because they will
  // only be used by the current process.
  return reflection_info_id.has_value();
}

std::optional<uint32_t>
SwiftLanguageRuntimeImpl::AddObjectFileToReflectionContext(
    ModuleSP module,
    llvm::SmallVector<llvm::StringRef, 1> likely_module_names) {
  auto obj_format_type =
      module->GetArchitecture().GetTriple().getObjectFormat();

  auto obj_file_format = GetObjectFileFormat(obj_format_type);
  if (!obj_file_format)
    return {};

  bool should_register_with_symbol_obj_file = [&]() -> bool {
    if (!m_process.GetTarget().GetSwiftReadMetadataFromDSYM())
      return false;
    auto *symbol_file = module->GetSymbolFile();
    if (!symbol_file)
      return false;
    auto *sym_obj_file = symbol_file->GetObjectFile();
    if (!sym_obj_file)
      return false;

    std::optional<llvm::StringRef> maybe_segment_name =
        obj_file_format->getSymbolRichSegmentName();
    if (!maybe_segment_name)
      return false;

    llvm::StringRef segment_name = *maybe_segment_name;

    auto *section_list = sym_obj_file->GetSectionList();
    auto segment_iter = llvm::find_if(*section_list, [&](auto segment) {
      return segment->GetName() == segment_name.begin();
    });

    if (segment_iter == section_list->end())
      return false;

    auto *segment = segment_iter->get();

    auto section_iter =
        llvm::find_if(segment->GetChildren(), [&](auto section) {
          return obj_file_format->sectionContainsReflectionData(
              section->GetName().GetStringRef());
        });
    return section_iter != segment->GetChildren().end();
  }();

  std::optional<llvm::StringRef> maybe_segment_name;
  std::optional<llvm::StringRef> maybe_secondary_segment_name;
  ObjectFile *object_file;
  if (should_register_with_symbol_obj_file) {
    maybe_segment_name = obj_file_format->getSymbolRichSegmentName();
    maybe_secondary_segment_name = obj_file_format->getSegmentName();
    object_file = module->GetSymbolFile()->GetObjectFile();
  } else {
    maybe_segment_name = obj_file_format->getSegmentName();
    object_file = module->GetObjectFile();
  }

  if (!maybe_segment_name)
    return {};

  llvm::StringRef segment_name = *maybe_segment_name;

  auto lldb_memory_reader = GetMemoryReader();
  auto maybe_start_and_end = lldb_memory_reader->addModuleToAddressMap(
      module, should_register_with_symbol_obj_file);
  if (!maybe_start_and_end)
    return {};

  uint64_t start_address, end_address;
  std::tie(start_address, end_address) = *maybe_start_and_end;

  auto *section_list = object_file->GetSectionList();
  if (section_list->GetSize() == 0)
    return false;

  auto segment_iter = llvm::find_if(*section_list, [&](auto segment) {
    return segment->GetName() == segment_name.begin();
  });

  if (segment_iter == section_list->end())
    return {};

  auto *segment = segment_iter->get();
  Section *maybe_secondary_segment = nullptr;
  if (maybe_secondary_segment_name) {
    auto secondary_segment_name = *maybe_secondary_segment_name;
    auto segment_iter = llvm::find_if(*section_list, [&](auto segment) {
      return segment->GetName() == secondary_segment_name.begin();
    });

    if (segment_iter != section_list->end())
      maybe_secondary_segment = segment_iter->get();
  }
  auto find_section_with_kind = [&](Section *segment,
                                    swift::ReflectionSectionKind section_kind)
      -> std::pair<swift::remote::RemoteRef<void>, uint64_t> {
    if (!segment)
      return {};

    auto section_name = obj_file_format->getSectionName(section_kind);
    for (auto section : segment->GetChildren()) {
      // Iterate over the sections until we find the reflection section we
      // need.
      if (section->GetName().AsCString() == section_name) {
        DataExtractor extractor;
        auto size = section->GetSectionData(extractor);
        auto data = extractor.GetData();
        size = section->GetFileSize();
        if (!data.begin())
          return {};

        // Alloc a buffer and copy over the reflection section's contents.
        // This buffer will be owned by reflection context.
        auto *Buf = malloc(size);
        std::memcpy(Buf, data.begin(), size);

        // The section's address is the start address for this image
        // added with the section's virtual address subtracting the start of the
        // module's address. We need to use the virtual address instead of the
        // file offset because the offsets encoded in the reflection section are
        // calculated in the virtual address space.
        auto address = start_address + section->GetFileAddress() -
                       section_list->GetSectionAtIndex(0)->GetFileAddress();
        assert(address <= end_address && "Address outside of range!");

        swift::remote::RemoteRef<void> remote_ref(address, Buf);
        return {remote_ref, size};
      }
    }
    return {};
  };

  return m_reflection_ctx->AddImage(
      [&](swift::ReflectionSectionKind section_kind)
          -> std::pair<swift::remote::RemoteRef<void>, uint64_t> {
        auto pair = find_section_with_kind(segment, section_kind);
        if (pair.first)
          return pair;
        return find_section_with_kind(maybe_secondary_segment, section_kind);
      },
      likely_module_names);
}

bool SwiftLanguageRuntimeImpl::AddModuleToReflectionContext(
    const lldb::ModuleSP &module_sp) {
  // This function is called from within SetupReflection so it cannot
  // call GetReflectionContext().
  assert(m_initialized_reflection_ctx);
  if (!m_reflection_ctx)
    return false;
  if (!module_sp)
    return false;
  auto *obj_file = module_sp->GetObjectFile();
  if (!obj_file)
    return false;
  auto &target = m_process.GetTarget();
  Address start_address = obj_file->GetBaseAddress();
  auto load_ptr = static_cast<uintptr_t>(
      start_address.GetLoadAddress(&target));
  auto likely_module_names = GetLikelySwiftImageNamesForModule(module_sp);
  if (obj_file->GetType() == ObjectFile::eTypeJIT) {
    auto object_format_type =
        module_sp->GetArchitecture().GetTriple().getObjectFormat();
    return AddJitObjectFileToReflectionContext(*obj_file, object_format_type,
                                               likely_module_names);
  }

  if (load_ptr == 0 || load_ptr == LLDB_INVALID_ADDRESS) {
    if (obj_file->GetType() != ObjectFile::eTypeJIT)
      LLDB_LOG(GetLog(LLDBLog::Types),
               "{0}: failed to get start address for \"{1}\".", __FUNCTION__,
               module_sp->GetObjectName()
                   ? module_sp->GetObjectName()
                   : obj_file->GetFileSpec().GetFilename());
    return false;
  }
  bool found = HasReflectionInfo(obj_file);
  LLDB_LOG(GetLog(LLDBLog::Types), "{0} reflection metadata in \"{1}\"",
           found ? "Adding" : "No",
           module_sp->GetObjectName() ? module_sp->GetObjectName()
                                      : obj_file->GetFileSpec().GetFilename());
  if (!found)
    return true;

  auto read_from_file_cache =
      GetMemoryReader()->readMetadataFromFileCacheEnabled();

  std::optional<uint32_t> info_id;
  // When dealing with ELF, we need to pass in the contents of the on-disk
  // file, since the Section Header Table is not present in the child process
  if (obj_file->GetPluginName().equals("elf")) {
    DataExtractor extractor;
    auto size = obj_file->GetData(0, obj_file->GetByteSize(), extractor);
    const uint8_t *file_data = extractor.GetDataStart();
    llvm::sys::MemoryBlock file_buffer((void *)file_data, size);
    info_id = m_reflection_ctx->ReadELF(
        swift::remote::RemoteAddress(load_ptr),
        std::optional<llvm::sys::MemoryBlock>(file_buffer),
        likely_module_names);
  } else if (read_from_file_cache &&
             obj_file->GetPluginName().equals("mach-o")) {
    info_id = AddObjectFileToReflectionContext(module_sp, likely_module_names);
    if (!info_id)
      info_id = m_reflection_ctx->AddImage(swift::remote::RemoteAddress(load_ptr),
                                 likely_module_names);
  } else {
    info_id = m_reflection_ctx->AddImage(swift::remote::RemoteAddress(load_ptr),
                               likely_module_names);
  }

  if (!info_id) {
    LLDB_LOG(GetLog(LLDBLog::Types),
             "Error while loading reflection metadata in \"{0}\"",
             module_sp->GetObjectName());
    return false;
  }

  if (auto *swift_metadata_cache = GetSwiftMetadataCache())
      swift_metadata_cache->registerModuleWithReflectionInfoID(module_sp,
                                                               *info_id);

  return true;
}

void SwiftLanguageRuntimeImpl::ModulesDidLoad(const ModuleList &module_list) {
  // The modules will be lazily processed on the next call to
  // GetReflectionContext.
  m_modules_to_add.AppendIfNeeded(module_list);
}

std::string
SwiftLanguageRuntimeImpl::GetObjectDescriptionExpr_Result(ValueObject &object) {
  Log *log(GetLog(LLDBLog::DataFormatters | LLDBLog::Expressions));
  std::string expr_string
      = llvm::formatv("Swift._DebuggerSupport.stringForPrintObject({0})",
                      object.GetName().GetCString()).str();
  if (log)
    log->Printf("[GetObjectDescriptionExpr_Result] expression: %s",
                expr_string.c_str());
  return expr_string;
}

std::string
SwiftLanguageRuntimeImpl::GetObjectDescriptionExpr_Ref(ValueObject &object) {
  Log *log(GetLog(LLDBLog::DataFormatters | LLDBLog::Expressions));

  StreamString expr_string;
  std::string expr_str
      = llvm::formatv("Swift._DebuggerSupport.stringForPrintObject(Swift."
                      "unsafeBitCast({0:x}, to: AnyObject.self))",
                      object.GetValueAsUnsigned(0)).str();

  if (log)
    log->Printf("[GetObjectDescriptionExpr_Result] expression: %s",
                expr_string.GetData());
  return expr_str;
}

static const ExecutionContextRef *GetSwiftExeCtx(ValueObject &valobj) {
  return (valobj.GetPreferredDisplayLanguage() == eLanguageTypeSwift)
             ? &valobj.GetExecutionContextRef()
             : nullptr;
}

std::string
SwiftLanguageRuntimeImpl::GetObjectDescriptionExpr_Copy(ValueObject &object,
    lldb::addr_t &copy_location)
{
  Log *log(GetLog(LLDBLog::DataFormatters | LLDBLog::Expressions));

  ValueObjectSP static_sp(object.GetStaticValue());

  CompilerType static_type(static_sp->GetCompilerType());
  if (auto non_reference_type = static_type.GetNonReferenceType())
    static_type = non_reference_type;

  // If we are in a generic context, here the static type of the object
  // might end up being generic (i.e. <T>). We want to make sure that
  // we correctly map the type into context before asking questions or
  // printing, as IRGen requires a fully realized type to work on.
  StackFrameSP frame_sp = object.GetFrameSP();
  if (!frame_sp)
      frame_sp
          = m_process.GetThreadList().GetSelectedThread()
              ->GetSelectedFrame(DoNoSelectMostRelevantFrame);

  auto swift_ast_ctx =
      static_type.GetTypeSystem().dyn_cast_or_null<TypeSystemSwift>();
  if (swift_ast_ctx) {
    SwiftScratchContextLock lock(GetSwiftExeCtx(object));
    static_type = BindGenericTypeParameters(*frame_sp, static_type);
  }

  auto stride = 0;
  auto opt_stride = static_type.GetByteStride(frame_sp.get());
  if (opt_stride)
    stride = *opt_stride;

  Status error;
  copy_location = m_process.AllocateMemory(
      stride, ePermissionsReadable | ePermissionsWritable, error);
  if (copy_location == LLDB_INVALID_ADDRESS) {
    if (log)
      log->Printf("[GetObjectDescriptionExpr_Copy] copy_location invalid");
    return {};
  }

  DataExtractor data_extractor;
  if (0 == static_sp->GetData(data_extractor, error)) {
    if (log)
      log->Printf("[GetObjectDescriptionExpr_Copy] data extraction failed");
    return {};
  }

  if (0 == m_process.WriteMemory(copy_location, data_extractor.GetDataStart(),
                               data_extractor.GetByteSize(), error)) {
    if (log)
      log->Printf("[GetObjectDescriptionExpr_Copy] memory copy failed");
    return {};
  }

  std::string expr_string
      = llvm::formatv("Swift._DebuggerSupport.stringForPrintObject(Swift."
                      "UnsafePointer<{0}>(bitPattern: {1:x})!.pointee)",
                      static_type.GetTypeName().GetCString(), copy_location).str();
  if (log)
    log->Printf("[GetObjectDescriptionExpr_Copy] expression: %s",
                expr_string.c_str());

  return expr_string;
}

llvm::Error SwiftLanguageRuntimeImpl::RunObjectDescriptionExpr(
    ValueObject &object, std::string &expr_string, Stream &result) {
  Log *log(GetLog(LLDBLog::DataFormatters | LLDBLog::Expressions));
  ValueObjectSP result_sp;
  EvaluateExpressionOptions eval_options;
  eval_options.SetLanguage(lldb::eLanguageTypeSwift);
  eval_options.SetSuppressPersistentResult(true);
  eval_options.SetGenerateDebugInfo(true);
  eval_options.SetTimeout(m_process.GetUtilityExpressionTimeout());

  StackFrameSP frame_sp = object.GetFrameSP();
  if (!frame_sp)
    frame_sp
        = m_process.GetThreadList().GetSelectedThread()
            ->GetSelectedFrame(DoNoSelectMostRelevantFrame);
  if (!frame_sp)
    return llvm::createStringError("no execution context to run expression in");
  auto eval_result = m_process.GetTarget().EvaluateExpression(
      expr_string,
      frame_sp.get(),
      result_sp, eval_options);

  if (log) {
    const char *eval_result_str
        = m_process.ExecutionResultAsCString(eval_result);
    log->Printf("[RunObjectDescriptionExpr] %s", eval_result_str);
  }

  // Sanity check the result of the expression before moving forward
  if (!result_sp) {
    if (log)
      log->Printf(
          "[RunObjectDescriptionExpr] expression generated no result");

    return llvm::createStringError("expression produced no result");
  }
  if (result_sp->GetError().Fail()) {
    if (log)
      log->Printf(
          "[RunObjectDescriptionExpr] expression generated error: %s",
          result_sp->GetError().AsCString());

    return result_sp->GetError().ToError();
  }
  if (!result_sp->GetCompilerType().IsValid()) {
    if (log)
      log->Printf("[RunObjectDescriptionExpr] expression generated "
                  "invalid type");

    return llvm::createStringError("expression produced invalid result type");
  }

  formatters::StringPrinter::ReadStringAndDumpToStreamOptions dump_options;
  dump_options.SetEscapeNonPrintables(false);
  dump_options.SetQuote('\0');
  dump_options.SetPrefixToken(nullptr);
  if (formatters::swift::String_SummaryProvider(
          *result_sp.get(), result,
          TypeSummaryOptions()
              .SetLanguage(lldb::eLanguageTypeSwift)
              .SetCapping(eTypeSummaryUncapped),
          dump_options)) {
    if (log)
      log->Printf("[RunObjectDescriptionExpr] expression completed "
                  "successfully");
    return llvm::Error::success();
  }
  if (log)
    log->Printf("[RunObjectDescriptionExpr] expression generated "
                "invalid string data");

  return llvm::createStringError("expression produced unprintable string");
}

static bool IsVariable(ValueObject &object) {
  if (object.IsSynthetic())
    return IsVariable(*object.GetNonSyntheticValue());

  return bool(object.GetVariable());
}

static bool IsSwiftResultVariable(ConstString name) {
  if (name) {
    llvm::StringRef name_sr(name.GetStringRef());
    if (name_sr.size() > 2 &&
        (name_sr.startswith("$R") || name_sr.startswith("$E")) &&
        ::isdigit(name_sr[2]))
      return true;
  }
  return false;
}

static bool IsSwiftReferenceType(ValueObject &object) {
  CompilerType object_type(object.GetCompilerType());
  if (object_type.GetTypeSystem().isa_and_nonnull<TypeSystemSwift>()) {
    Flags type_flags(object_type.GetTypeInfo());
    if (type_flags.AllSet(eTypeIsClass | eTypeHasValue |
                          eTypeInstanceIsPointer))
      return true;
  }
  return false;
}

llvm::Error
SwiftLanguageRuntimeImpl::GetObjectDescription(Stream &str,
                                               ValueObject &object) {
  if (object.IsUninitializedReference())
    return llvm::createStringError("<uninitialized>");

  std::string expr_string;

  if (::IsVariable(object) || ::IsSwiftResultVariable(object.GetName())) {
    // if the object is a Swift variable, it has two properties:
    // a) its name is something we can refer to in expressions for free
    // b) its type may be something we can't actually talk about in expressions
    // so, just use the result variable's name in the expression and be done
    // with it
    expr_string = GetObjectDescriptionExpr_Result(object);
  } else if (::IsSwiftReferenceType(object)) {
    // if this is a Swift class, it has two properties:
    // a) we do not need its type name, AnyObject is just as good
    // b) its value is something we can directly use to refer to it
    // so, just use the ValueObject's pointer-value and be done with it
    expr_string = GetObjectDescriptionExpr_Ref(object);
  }
  if (!expr_string.empty()) {
    StreamString probe_stream;
    auto error = RunObjectDescriptionExpr(object, expr_string, probe_stream);
    if (error)
      return error;
    str.Printf("%s", probe_stream.GetData());
    return llvm::Error::success();
  }
  // In general, don't try to use the name of the ValueObject as it might end up
  // referring to the wrong thing.  Instead, copy the object data into the
  // target and call object description on the copy.
  lldb::addr_t copy_location = LLDB_INVALID_ADDRESS;
  expr_string = GetObjectDescriptionExpr_Copy(object, copy_location);
  if (copy_location == LLDB_INVALID_ADDRESS) {
    return llvm::createStringError(
        "Failed to allocate memory for copy object.");
  }

  auto cleanup = llvm::make_scope_exit(
      [&]() { m_process.DeallocateMemory(copy_location); });

  if (expr_string.empty())
    return llvm::createStringError("no object description");
  return RunObjectDescriptionExpr(object, expr_string, str);
}

StructuredDataImpl *
SwiftLanguageRuntime::GetLanguageSpecificData(StackFrame &frame) {
  auto sc = frame.GetSymbolContext(eSymbolContextFunction);
  if (!sc.function)
    return nullptr;

  auto dict_sp = std::make_shared<StructuredData::Dictionary>();
  auto symbol = sc.function->GetMangled().GetMangledName().GetStringRef();
  auto is_async = SwiftLanguageRuntime::IsAnySwiftAsyncFunctionSymbol(symbol);
  dict_sp->AddBooleanItem("IsSwiftAsyncFunction", is_async);

  auto *data = new StructuredDataImpl;
  data->SetObjectSP(dict_sp);
  return data;
}

void SwiftLanguageRuntime::FindFunctionPointersInCall(
    StackFrame &frame, std::vector<Address> &addresses, bool debug_only,
    bool resolve_thunks) {
  // Extract the mangled name from the stack frame, and realize the
  // function type in the Target's SwiftASTContext.  Then walk the
  // arguments looking for function pointers.  If we find one in the
  // FIRST argument, we can fetch the pointer value and return that.
  // FIXME: when we can ask swift/llvm for the location of function
  // arguments, then we can do this for all the function pointer
  // arguments we find.

  SymbolContext sc = frame.GetSymbolContext(eSymbolContextSymbol);
  if (sc.symbol) {
    Mangled mangled_name = sc.symbol->GetMangled();
    if (mangled_name.GuessLanguage() == lldb::eLanguageTypeSwift) {
      Status error;
      Target &target = frame.GetThread()->GetProcess()->GetTarget();
      ExecutionContext exe_ctx(frame);
      std::optional<SwiftScratchContextReader> maybe_swift_ast =
          target.GetSwiftScratchContext(error, frame);
      auto scratch_ctx = maybe_swift_ast->get();
      if (scratch_ctx) {
        if (SwiftASTContext *swift_ast = scratch_ctx->GetSwiftASTContext(&sc)) {
        CompilerType function_type = swift_ast->GetTypeFromMangledTypename(
            mangled_name.GetMangledName());
        if (error.Success()) {
          if (function_type.IsFunctionType()) {
            // FIXME: For now we only check the first argument since
            // we don't know how to find the values of arguments
            // further in the argument list.
            //
            // int num_arguments = function_type.GetFunctionArgumentCount();
            // for (int i = 0; i < num_arguments; i++)

            for (int i = 0; i < 1; i++) {
              CompilerType argument_type =
                  function_type.GetFunctionArgumentTypeAtIndex(i);
              if (argument_type.IsFunctionPointerType()) {
                // We found a function pointer argument.  Try to track
                // down its value.  This is a hack for now, we really
                // should ask swift/llvm how to find the argument(s)
                // given the Swift decl for this function, and then
                // look those up in the frame.

                ABISP abi_sp(frame.GetThread()->GetProcess()->GetABI());
                ValueList argument_values;
                Value input_value;
                auto clang_ctx = ScratchTypeSystemClang::GetForTarget(target);
                if (!clang_ctx)
                  continue;

                CompilerType clang_void_ptr_type =
                    clang_ctx->GetBasicType(eBasicTypeVoid).GetPointerType();

                input_value.SetValueType(Value::ValueType::Scalar);
                input_value.SetCompilerType(clang_void_ptr_type);
                argument_values.PushValue(input_value);

                bool success = abi_sp->GetArgumentValues(
                    *(frame.GetThread().get()), argument_values);
                if (success) {
                  // Now get a pointer value from the zeroth argument.
                  Status error;
                  DataExtractor data;
                  ExecutionContext exe_ctx;
                  frame.CalculateExecutionContext(exe_ctx);
                  error = argument_values.GetValueAtIndex(0)->GetValueAsData(
                      &exe_ctx, data, NULL);
                  lldb::offset_t offset = 0;
                  lldb::addr_t fn_ptr_addr = data.GetAddress(&offset);
                  Address fn_ptr_address;
                  fn_ptr_address.SetLoadAddress(fn_ptr_addr, &target);
                  // Now check to see if this has debug info:
                  bool add_it = true;

                  if (resolve_thunks) {
                    SymbolContext sc;
                    fn_ptr_address.CalculateSymbolContext(
                        &sc, eSymbolContextEverything);
                    if (sc.comp_unit && sc.symbol) {
                      ConstString symbol_name =
                          sc.symbol->GetMangled().GetMangledName();
                      if (symbol_name) {
                        SymbolContext target_context;
                        if (GetTargetOfPartialApply(sc, symbol_name,
                                                    target_context)) {
                          if (target_context.symbol)
                            fn_ptr_address =
                                target_context.symbol->GetAddress();
                          else if (target_context.function)
                            fn_ptr_address =
                                target_context.function->GetAddressRange()
                                    .GetBaseAddress();
                        }
                      }
                    }
                  }

                  if (debug_only) {
                    LineEntry line_entry;
                    fn_ptr_address.CalculateSymbolContextLineEntry(line_entry);
                    if (!line_entry.IsValid())
                      add_it = false;
                  }
                  if (add_it)
                    addresses.push_back(fn_ptr_address);
                }
              }
            }
          }
        }
      }
      }
    }
  }
}

//------------------------------------------------------------------
// Exception breakpoint Precondition class for Swift:
//------------------------------------------------------------------
void SwiftLanguageRuntimeImpl::SwiftExceptionPrecondition::AddTypeName(
    const char *class_name) {
  m_type_names.insert(class_name);
}

void SwiftLanguageRuntimeImpl::SwiftExceptionPrecondition::AddEnumSpec(
    const char *enum_name, const char *element_name) {
  std::unordered_map<std::string, std::vector<std::string>>::value_type
      new_value(enum_name, std::vector<std::string>());
  auto result = m_enum_spec.emplace(new_value);
  result.first->second.push_back(element_name);
}

SwiftLanguageRuntimeImpl::SwiftExceptionPrecondition::
    SwiftExceptionPrecondition() {}

ValueObjectSP SwiftLanguageRuntime::CalculateErrorValueObjectFromValue(
    Value &value, ConstString name, bool persistent) {
  if (!m_process)
    return {};
  ValueObjectSP error_valobj_sp;
  auto type_system_or_err =
      m_process->GetTarget().GetScratchTypeSystemForLanguage(
          eLanguageTypeSwift);
  if (!type_system_or_err)
    return error_valobj_sp;

  auto *ast_context =
      llvm::dyn_cast_or_null<TypeSystemSwift>(type_system_or_err->get());
  if (!ast_context)
    return error_valobj_sp;

  CompilerType swift_error_proto_type = ast_context->GetErrorType();
  value.SetCompilerType(swift_error_proto_type);

  error_valobj_sp = ValueObjectConstResult::Create(m_process, value, name);

  if (error_valobj_sp && error_valobj_sp->GetError().Success()) {
    error_valobj_sp = error_valobj_sp->GetQualifiedRepresentationIfAvailable(
        lldb::eDynamicCanRunTarget, true);
    if (!IsValidErrorValue(*(error_valobj_sp.get()))) {
      error_valobj_sp.reset();
    }
  }

  if (persistent && error_valobj_sp) {
    ExecutionContext ctx =
        error_valobj_sp->GetExecutionContextRef().Lock(false);
    auto *exe_scope = ctx.GetBestExecutionContextScope();
    if (!exe_scope)
      return error_valobj_sp;
    Target &target = m_process->GetTarget();
    auto *persistent_state =
        target.GetSwiftPersistentExpressionState(*exe_scope);

    ConstString persistent_variable_name(
        persistent_state->GetNextPersistentVariableName(/*is_error*/ true));

    lldb::ValueObjectSP const_valobj_sp;

    // Check in case our value is already a constant value
    if (error_valobj_sp->GetIsConstant()) {
      const_valobj_sp = error_valobj_sp;
      const_valobj_sp->SetName(persistent_variable_name);
    } else
      const_valobj_sp =
          error_valobj_sp->CreateConstantValue(persistent_variable_name);

    lldb::ValueObjectSP live_valobj_sp = error_valobj_sp;

    error_valobj_sp = const_valobj_sp;

    ExpressionVariableSP clang_expr_variable_sp(
        persistent_state->CreatePersistentVariable(error_valobj_sp));
    clang_expr_variable_sp->m_live_sp = live_valobj_sp;
    clang_expr_variable_sp->m_flags |=
        ClangExpressionVariable::EVIsProgramReference;

    error_valobj_sp = clang_expr_variable_sp->GetValueObject();
  }
  return error_valobj_sp;
}

ValueObjectSP
SwiftLanguageRuntime::CalculateErrorValue(StackFrameSP frame_sp,
                                          ConstString variable_name) {
  ProcessSP process_sp(frame_sp->GetThread()->GetProcess());
  Status error;
  Target *target = frame_sp->CalculateTarget().get();
  ValueObjectSP error_valobj_sp;

  auto *runtime = Get(process_sp);
  if (!runtime)
    return error_valobj_sp;

  std::optional<Value> arg0 =
      runtime->GetErrorReturnLocationAfterReturn(frame_sp);
  if (!arg0)
    return error_valobj_sp;

  ExecutionContext exe_ctx;
  frame_sp->CalculateExecutionContext(exe_ctx);

  auto *exe_scope = exe_ctx.GetBestExecutionContextScope();
  if (!exe_scope)
    return error_valobj_sp;

  std::optional<SwiftScratchContextReader> maybe_scratch_context =
      target->GetSwiftScratchContext(error, *frame_sp);
  if (!maybe_scratch_context || error.Fail())
    return error_valobj_sp;
  auto scratch_ctx = maybe_scratch_context->get();
  if (!scratch_ctx)
    return error_valobj_sp;

  auto buffer_up =
      std::make_unique<DataBufferHeap>(arg0->GetScalar().GetByteSize(), 0);
  arg0->GetScalar().GetBytes(buffer_up->GetData());
  lldb::DataBufferSP buffer(std::move(buffer_up));

  CompilerType swift_error_proto_type = scratch_ctx->GetErrorType();
  if (!swift_error_proto_type.IsValid())
    return error_valobj_sp;

  error_valobj_sp = ValueObjectConstResult::Create(
      exe_scope, swift_error_proto_type, variable_name, buffer,
      endian::InlHostByteOrder(), exe_ctx.GetAddressByteSize());
  if (error_valobj_sp->GetError().Fail())
    return error_valobj_sp;

  error_valobj_sp = error_valobj_sp->GetQualifiedRepresentationIfAvailable(
      lldb::eDynamicCanRunTarget, true);
  return error_valobj_sp;
}

void SwiftLanguageRuntime::RegisterGlobalError(Target &target, ConstString name,
                                               lldb::addr_t addr) {
  auto type_system_or_err =
      target.GetScratchTypeSystemForLanguage(eLanguageTypeSwift);
  if (!type_system_or_err) {
    llvm::consumeError(type_system_or_err.takeError());
    return;
  }

  auto *swift_ast_ctx = llvm::dyn_cast_or_null<SwiftASTContextForExpressions>(
      type_system_or_err->get());
  if (swift_ast_ctx && !swift_ast_ctx->HasFatalErrors()) {
    std::string module_name = "$__lldb_module_for_";
    module_name.append(&name.GetCString()[1]);
    SourceModule module_info;
    module_info.path.push_back(ConstString(module_name));

    Status module_creation_error;
    swift::ModuleDecl *module_decl =
        swift_ast_ctx->CreateModule(module_info, module_creation_error,
                                    /*importInfo*/ {});

    if (module_creation_error.Success() && module_decl) {
      const bool is_static = false;
      const auto introducer = swift::VarDecl::Introducer::Let;

      swift::VarDecl *var_decl = new (*swift_ast_ctx->GetASTContext())
          swift::VarDecl(is_static, introducer, swift::SourceLoc(),
                         swift_ast_ctx->GetIdentifier(name.GetCString()),
                         module_decl);
      var_decl->setInterfaceType(
          llvm::expectedToStdOptional(
              swift_ast_ctx->GetSwiftType(swift_ast_ctx->GetErrorType()))
              .value_or(swift::Type()));
      var_decl->setDebuggerVar(true);

      SwiftPersistentExpressionState *persistent_state =
          llvm::cast<SwiftPersistentExpressionState>(
              target.GetPersistentExpressionStateForLanguage(
                  lldb::eLanguageTypeSwift));
      if (!persistent_state)
        return;

      persistent_state->RegisterSwiftPersistentDecl({swift_ast_ctx, var_decl});

      ConstString mangled_name;

      {
        swift::Mangle::ASTMangler mangler(true);
        mangled_name = ConstString(mangler.mangleGlobalVariableFull(var_decl));
      }

      lldb::addr_t symbol_addr;

      {
        ProcessSP process_sp(target.GetProcessSP());
        Status alloc_error;

        symbol_addr = process_sp->AllocateMemory(
            process_sp->GetAddressByteSize(),
            lldb::ePermissionsWritable | lldb::ePermissionsReadable,
            alloc_error);

        if (alloc_error.Success() && symbol_addr != LLDB_INVALID_ADDRESS) {
          Status write_error;
          process_sp->WritePointerToMemory(symbol_addr, addr, write_error);

          if (write_error.Success()) {
            persistent_state->RegisterSymbol(mangled_name, symbol_addr);
          }
        }
      }
    }
  }
}

lldb::BreakpointPreconditionSP
SwiftLanguageRuntimeImpl::GetBreakpointExceptionPrecondition(
    LanguageType language, bool throw_bp) {
  if (language != eLanguageTypeSwift)
    return lldb::BreakpointPreconditionSP();
  if (!throw_bp)
    return lldb::BreakpointPreconditionSP();
  BreakpointPreconditionSP precondition_sp(
      new SwiftLanguageRuntimeImpl::SwiftExceptionPrecondition());
  return precondition_sp;
}

bool SwiftLanguageRuntimeImpl::SwiftExceptionPrecondition::EvaluatePrecondition(
    StoppointCallbackContext &context) {
  if (!m_type_names.empty()) {
    StackFrameSP frame_sp = context.exe_ctx_ref.GetFrameSP();
    if (!frame_sp)
      return true;

    ValueObjectSP error_valobj_sp = SwiftLanguageRuntime::CalculateErrorValue(
        frame_sp, ConstString("__swift_error_var"));
    if (!error_valobj_sp || error_valobj_sp->GetError().Fail())
      return true;

    // This shouldn't fail, since at worst it will return me the object I just
    // successfully got.
    std::string full_error_name(
        error_valobj_sp->GetCompilerType().GetTypeName().AsCString());
    size_t last_dot_pos = full_error_name.rfind('.');
    std::string type_name_base;
    if (last_dot_pos == std::string::npos)
      type_name_base = full_error_name;
    else {
      if (last_dot_pos + 1 <= full_error_name.size())
        type_name_base =
            full_error_name.substr(last_dot_pos + 1, full_error_name.size());
    }

    // The type name will be the module and then the type.  If the match name
    // has a dot, we require a complete
    // match against the type, if the type name has no dot, we match it against
    // the base.

    for (std::string name : m_type_names) {
      if (name.rfind('.') != std::string::npos) {
        if (name == full_error_name)
          return true;
      } else {
        if (name == type_name_base)
          return true;
      }
    }
    return false;
  }
  return true;
}

void SwiftLanguageRuntimeImpl::SwiftExceptionPrecondition::GetDescription(
    Stream &stream, lldb::DescriptionLevel level) {
  if (level == eDescriptionLevelFull || level == eDescriptionLevelVerbose) {
    if (m_type_names.size() > 0) {
      stream.Printf("\nType Filters:");
      for (std::string name : m_type_names) {
        stream.Printf(" %s", name.c_str());
      }
      stream.Printf("\n");
    }
  }
}

Status
SwiftLanguageRuntimeImpl::SwiftExceptionPrecondition::ConfigurePrecondition(
    Args &args) {
  Status error;
  std::vector<std::string> object_typenames;
  OptionParsing::GetOptionValuesAsStrings(args, "exception-typename",
                                          object_typenames);
  for (auto type_name : object_typenames)
    AddTypeName(type_name.c_str());
  return error;
}

void SwiftLanguageRuntimeImpl::AddToLibraryNegativeCache(
    StringRef library_name) {
  std::lock_guard<std::mutex> locker(m_negative_cache_mutex);
  m_library_negative_cache.insert(library_name);
}

bool SwiftLanguageRuntimeImpl::IsInLibraryNegativeCache(
    StringRef library_name) {
  std::lock_guard<std::mutex> locker(m_negative_cache_mutex);
  return m_library_negative_cache.count(library_name) == 1;
}

class ProjectionSyntheticChildren : public SyntheticChildren {
public:
  struct FieldProjection {
    ConstString name;
    CompilerType type;
    int32_t byte_offset;

    FieldProjection(CompilerType parent_type, ExecutionContext *exe_ctx,
                    size_t idx, ValueObject *valobj) {
      const bool transparent_pointers = false;
      const bool omit_empty_base_classes = true;
      const bool ignore_array_bounds = false;
      bool child_is_base_class = false;
      bool child_is_deref_of_parent = false;
      std::string child_name;

      uint32_t child_byte_size;
      uint32_t child_bitfield_bit_size;
      uint32_t child_bitfield_bit_offset;
      uint64_t language_flags;

      auto type_or_err = parent_type.GetChildCompilerTypeAtIndex(
          exe_ctx, idx, transparent_pointers, omit_empty_base_classes,
          ignore_array_bounds, child_name, child_byte_size, byte_offset,
          child_bitfield_bit_size, child_bitfield_bit_offset,
          child_is_base_class, child_is_deref_of_parent, valobj,
          language_flags);
      if (!type_or_err)
        LLDB_LOG_ERROR(GetLog(LLDBLog::Types), type_or_err.takeError(),
                       "could not find child #{1}: {0}", idx);
      else
        type = *type_or_err;

      if (child_is_base_class)
        type.Clear(); // invalidate - base classes are dealt with outside of the
                      // projection
      else
        name.SetCStringWithLength(child_name.c_str(), child_name.size());
    }

    bool IsValid() { return !name.IsEmpty() && type.IsValid(); }

    explicit operator bool() { return IsValid(); }
  };

  struct TypeProjection {
    std::vector<FieldProjection> field_projections;
    ConstString type_name;
  };

  typedef std::unique_ptr<TypeProjection> TypeProjectionUP;

  bool IsScripted() override { return false; }

  std::string GetDescription() override {
    return "projection synthetic children";
  }

  ProjectionSyntheticChildren(const Flags &flags, TypeProjectionUP &&projection)
      : SyntheticChildren(flags), m_projection(std::move(projection)) {}

protected:
  TypeProjectionUP m_projection;

  class ProjectionFrontEndProvider : public SyntheticChildrenFrontEnd {
  public:
    ProjectionFrontEndProvider(ValueObject &backend,
                               TypeProjectionUP &projection)
        : SyntheticChildrenFrontEnd(backend), m_num_bases(0),
          m_projection(projection.get()) {
      lldbassert(m_projection && "need a valid projection");
      CompilerType type(backend.GetCompilerType());
      m_num_bases = type.GetNumDirectBaseClasses();
    }

    llvm::Expected<uint32_t> CalculateNumChildren() override {
      return m_projection->field_projections.size() + m_num_bases;
    }

    lldb::ValueObjectSP GetChildAtIndex(uint32_t idx) override {
      if (idx < m_num_bases) {
        if (ValueObjectSP base_object_sp =
                m_backend.GetChildAtIndex(idx, true)) {
          CompilerType base_type(base_object_sp->GetCompilerType());
          ConstString base_type_name(base_type.GetTypeName());
          if (base_type_name.IsEmpty() ||
              !SwiftLanguageRuntime::IsSwiftClassName(
                  base_type_name.GetCString()))
            return base_object_sp;
          base_object_sp = m_backend.GetSyntheticBase(
              0, base_type, true,
              Mangled(base_type_name)
                  .GetDemangledName());
          return base_object_sp;
        } else
          return nullptr;
      }
      idx -= m_num_bases;
      if (idx < m_projection->field_projections.size()) {
        auto &projection(m_projection->field_projections.at(idx));
        return m_backend.GetSyntheticChildAtOffset(
            projection.byte_offset, projection.type, true, projection.name);
      }
      return nullptr;
    }

    size_t GetIndexOfChildWithName(ConstString name) override {
      for (size_t idx = 0; idx < m_projection->field_projections.size();
           idx++) {
        if (m_projection->field_projections.at(idx).name == name)
          return idx;
      }
      return UINT32_MAX;
    }

    lldb::ChildCacheState Update() override {
      return ChildCacheState::eRefetch;
    }

    bool MightHaveChildren() override { return true; }

    ConstString GetSyntheticTypeName() override {
      return m_projection->type_name;
    }

  private:
    size_t m_num_bases;
    TypeProjectionUP::element_type *m_projection;
  };

public:
  SyntheticChildrenFrontEnd::AutoPointer
  GetFrontEnd(ValueObject &backend) override {
    return SyntheticChildrenFrontEnd::AutoPointer(
        new ProjectionFrontEndProvider(backend, m_projection));
  }
};

lldb::SyntheticChildrenSP
SwiftLanguageRuntimeImpl::GetBridgedSyntheticChildProvider(
    ValueObject &valobj) {
  ConstString type_name = valobj.GetCompilerType().GetTypeName();

  if (!type_name.IsEmpty()) {
    auto iter = m_bridged_synthetics_map.find(type_name.AsCString()),
         end = m_bridged_synthetics_map.end();
    if (iter != end)
      return iter->second;
  }

  ProjectionSyntheticChildren::TypeProjectionUP type_projection(
      new ProjectionSyntheticChildren::TypeProjectionUP::element_type());

  if (auto maybe_swift_ast_ctx = valobj.GetSwiftScratchContext()) {
    CompilerType swift_type =
        maybe_swift_ast_ctx->get()->GetTypeFromMangledTypename(type_name);

    if (swift_type.IsValid()) {
      ExecutionContext exe_ctx(m_process);
      bool any_projected = false;
      for (size_t idx = 0, e = llvm::expectedToStdOptional(
                                   swift_type.GetNumChildren(true, &exe_ctx))
                                   .value_or(0);
           idx < e; idx++) {
        // if a projection fails, keep going - we have offsets here, so it
        // should be OK to skip some members
        if (auto projection = ProjectionSyntheticChildren::FieldProjection(
                swift_type, &exe_ctx, idx, &valobj)) {
          any_projected = true;
          type_projection->field_projections.push_back(projection);
        }
      }

      if (any_projected) {
        type_projection->type_name = swift_type.GetDisplayTypeName();
        SyntheticChildrenSP synth_sp =
            SyntheticChildrenSP(new ProjectionSyntheticChildren(
                SyntheticChildren::Flags(), std::move(type_projection)));
        m_bridged_synthetics_map.insert({type_name.AsCString(), synth_sp});
        return synth_sp;
      }
    }
  }

  return nullptr;
}

std::optional<std::pair<lldb::ValueObjectSP, bool>>
SwiftLanguageRuntime::ExtractSwiftValueObjectFromCxxWrapper(
    ValueObject &valobj) {
  ValueObjectSP swift_valobj;

  // There are three flavors of C++ wrapper classes:
  // - Reference types wrappers, which have no ivars, and have one super class
  // which contains an opaque pointer to the Swift instance.
  // - Value type wrappers which has one ivar, an opaque pointer to the Swift
  // instance.
  // - Value type wrappers, which has one ivar, a single char array with the
  // swift value embedded directly in it.
  // In all cases the value object should have exactly one child.
  if (valobj.GetNumChildrenIgnoringErrors() != 1)
    return {};

  auto child_valobj = valobj.GetChildAtIndex(0, true);
  auto child_type = child_valobj->GetCompilerType();
  auto child_name = child_type.GetMangledTypeName();

  // If this is a reference wrapper, the first child is actually the super
  // class.
  if (child_name == "swift::_impl::RefCountedClass") {
    // The super class should have exactly one ivar, the opaque pointer that
    // points to the Swift instance.
    if (child_valobj->GetNumChildrenIgnoringErrors() != 1)
      return {};

    auto opaque_ptr_valobj = child_valobj->GetChildAtIndex(0, true);

    // This is a Swift class type, which is a reference, so no need to wrap the
    // corresponding Swift type behind a pointer.
    return {{opaque_ptr_valobj, false}};
  }

  if (child_name == "swift::_impl::OpaqueStorage") {
    if (child_valobj->GetNumChildrenIgnoringErrors() != 1)
      return {};

    auto opaque_ptr_valobj = child_valobj->GetChildAtIndex(0, true);
    // This is a Swift value stored behind a pointer.
    return {{opaque_ptr_valobj, true}};
  }

  CompilerType element_type;
  if (child_type.IsArrayType(&element_type))
    if (element_type.IsCharType())
      // This is an Swift value type inlined directly into the C++ type as a
      // char[n].
      return {{valobj.GetSP(), false}};
  return {};
}

void SwiftLanguageRuntimeImpl::WillStartExecutingUserExpression(
    bool runs_in_playground_or_repl) {
  if (runs_in_playground_or_repl)
    return;

  std::lock_guard<std::mutex> lock(m_active_user_expr_mutex);
  Log *log(GetLog(LLDBLog::Expressions));
  LLDB_LOG(log,
           "SwiftLanguageRuntime: starting user expression. "
           "Number active: %u",
           m_active_user_expr_count + 1);
  if (m_active_user_expr_count++ > 0)
    return;

  auto dynamic_exlusivity_flag_addr = GetDynamicExclusivityFlagAddr();
  if (!dynamic_exlusivity_flag_addr) {
    LLDB_LOG(log, "Failed to get address of disableExclusivityChecking flag");
    return;
  }

  // We're executing the first user expression. Toggle the flag.
  auto type_system_or_err =
      m_process.GetTarget().GetScratchTypeSystemForLanguage(
          eLanguageTypeC_plus_plus);
  if (!type_system_or_err) {
    LLDB_LOG_ERROR(
        log, type_system_or_err.takeError(),
        "SwiftLanguageRuntime: Unable to get pointer to type system");
    return;
  }

  auto ts = *type_system_or_err;
  if (!ts) {
    LLDB_LOG(log, "type system no longer live");
    return;
  }
  ConstString BoolName("bool");
  std::optional<uint64_t> bool_size =
      ts->GetBuiltinTypeByName(BoolName).GetByteSize(nullptr);
  if (!bool_size)
    return;

  Status error;
  Scalar original_value;
  m_process.ReadScalarIntegerFromMemory(
      *dynamic_exlusivity_flag_addr, *bool_size, false, original_value, error);

  m_original_dynamic_exclusivity_flag_state = original_value.UInt() != 0;
  if (error.Fail()) {
    LLDB_LOG(log,
             "SwiftLanguageRuntime: Unable to read disableExclusivityChecking "
             "flag state: %s",
             error.AsCString());
    return;
  }

  Scalar new_value(1U);
  m_process.WriteScalarToMemory(*m_dynamic_exclusivity_flag_addr, new_value,
                                *bool_size, error);
  if (error.Fail()) {
    LLDB_LOG(log,
             "SwiftLanguageRuntime: Unable to set disableExclusivityChecking "
             "flag state: %s",
             error.AsCString());
    return;
  }

  LLDB_LOG(log,
           "SwiftLanguageRuntime: Changed disableExclusivityChecking flag "
           "state from %u to 1",
           m_original_dynamic_exclusivity_flag_state);
}

void SwiftLanguageRuntimeImpl::DidFinishExecutingUserExpression(
    bool runs_in_playground_or_repl) {
  if (runs_in_playground_or_repl)
    return;

  std::lock_guard<std::mutex> lock(m_active_user_expr_mutex);
  Log *log(GetLog(LLDBLog::Expressions));

  --m_active_user_expr_count;
  LLDB_LOG(log,
           "SwiftLanguageRuntime: finished user expression. "
           "Number active: %u",
           m_active_user_expr_count);

  if (m_active_user_expr_count > 0)
    return;

  auto dynamic_exlusivity_flag_addr = GetDynamicExclusivityFlagAddr();
  if (!dynamic_exlusivity_flag_addr) {
    LLDB_LOG(log, "Failed to get address of disableExclusivityChecking flag");
    return;
  }

  auto type_system_or_err =
      m_process.GetTarget().GetScratchTypeSystemForLanguage(
          eLanguageTypeC_plus_plus);
  if (!type_system_or_err) {
    LLDB_LOG_ERROR(
        log, type_system_or_err.takeError(),
        "SwiftLanguageRuntime: Unable to get pointer to type system");
    return;
  }

  auto ts = *type_system_or_err;
  if (!ts) {
    LLDB_LOG(log, "type system no longer live");
    return;
  }
  ConstString BoolName("bool");
  std::optional<uint64_t> bool_size =
      ts->GetBuiltinTypeByName(BoolName).GetByteSize(nullptr);
  if (!bool_size)
    return;

  Status error;
  Scalar original_value(m_original_dynamic_exclusivity_flag_state ? 1U : 0U);
  m_process.WriteScalarToMemory(*dynamic_exlusivity_flag_addr, original_value,
                                *bool_size, error);
  if (error.Fail()) {
    LLDB_LOG(log,
             "SwiftLanguageRuntime: Unable to reset "
             "disableExclusivityChecking flag state: %s",
             error.AsCString());
    return;
  }
  if (log)
    LLDB_LOG(log,
             "SwiftLanguageRuntime: Changed "
             "disableExclusivityChecking flag state back to %u",
             m_original_dynamic_exclusivity_flag_state);
}

std::optional<Value> SwiftLanguageRuntime::GetErrorReturnLocationAfterReturn(
    lldb::StackFrameSP frame_sp) {
  std::optional<Value> error_val;

  llvm::StringRef error_reg_name;
  ArchSpec arch_spec(GetTargetRef().GetArchitecture());
  switch (arch_spec.GetMachine()) {
  case llvm::Triple::ArchType::arm:
    error_reg_name = "r6";
    break;
  case llvm::Triple::ArchType::aarch64:
    error_reg_name = "x21";
    break;
  case llvm::Triple::ArchType::x86_64:
    error_reg_name = "r12";
    break;
  default:
    break;
  }

  if (error_reg_name.empty())
    return error_val;

  RegisterContextSP reg_ctx = frame_sp->GetRegisterContext();
  const RegisterInfo *reg_info = reg_ctx->GetRegisterInfoByName(error_reg_name);
  lldbassert(reg_info &&
             "didn't get the right register name for swift error register");
  if (!reg_info)
    return error_val;

  RegisterValue reg_value;
  if (!reg_ctx->ReadRegister(reg_info, reg_value)) {
    // Do some logging here.
    return error_val;
  }

  lldb::addr_t error_addr = reg_value.GetAsUInt64();
  if (error_addr == 0)
    return error_val;

  Value val;
  if (reg_value.GetScalarValue(val.GetScalar())) {
    val.SetValueType(Value::ValueType::Scalar);
    val.SetContext(Value::ContextType::RegisterInfo,
                   const_cast<RegisterInfo *>(reg_info));
    error_val = val;
  }
  return error_val;
}

std::optional<Value> SwiftLanguageRuntime::GetErrorReturnLocationBeforeReturn(
    lldb::StackFrameSP frame_sp, bool &need_to_check_after_return) {
  std::optional<Value> error_val;

  if (!frame_sp) {
    need_to_check_after_return = false;
    return error_val;
  }

  // For Architectures where the error isn't returned in a register,
  // there's a magic variable that points to the value.  Check that first:

  ConstString error_location_name("$error");
  VariableListSP variables_sp = frame_sp->GetInScopeVariableList(false);
  VariableSP error_loc_var_sp = variables_sp->FindVariable(
      error_location_name, eValueTypeVariableArgument);
  if (error_loc_var_sp) {
    need_to_check_after_return = false;

    ValueObjectSP error_loc_val_sp = frame_sp->GetValueObjectForFrameVariable(
        error_loc_var_sp, eNoDynamicValues);
    if (error_loc_val_sp && error_loc_val_sp->GetError().Success())
      error_val = error_loc_val_sp->GetValue();

    return error_val;
  }

  // Otherwise, see if we know which register it lives in from the calling
  // convention. This should probably go in the ABI plugin not here, but the
  // Swift ABI can change with swiftlang versions and that would make it awkward
  // in the ABI.

  Function *func = frame_sp->GetSymbolContext(eSymbolContextFunction).function;
  if (!func) {
    need_to_check_after_return = false;
    return error_val;
  }

  need_to_check_after_return = func->CanThrow();
  return error_val;
}

lldb::BreakpointResolverSP
SwiftLanguageRuntime::CreateExceptionResolver(const lldb::BreakpointSP &bkpt, bool catch_bp,
                                              bool throw_bp) {
  return ::CreateExceptionResolver(bkpt, catch_bp, throw_bp);
}

static OptionDefinition g_swift_demangle_options[] = {
    // clang-format off
  {LLDB_OPT_SET_1, false, "expand", 'e', OptionParser::eNoArgument, nullptr, {}, 0, eArgTypeNone, "Whether LLDB should print the demangled tree"},
    // clang-format on
};

class CommandObjectSwift_Demangle : public CommandObjectParsed {
public:
  CommandObjectSwift_Demangle(CommandInterpreter &interpreter)
      : CommandObjectParsed(interpreter, "demangle",
                            "Demangle a Swift mangled name",
                            "language swift demangle"),
        m_options() {
    CommandArgumentData mangled_name_arg{eArgTypeSymbol};
    m_arguments.push_back({mangled_name_arg});
  }

  ~CommandObjectSwift_Demangle() {}

  Options *GetOptions() override { return &m_options; }

  class CommandOptions : public Options {
  public:
    CommandOptions() : Options(), m_expand(false, false) {
      OptionParsingStarting(nullptr);
    }

    virtual ~CommandOptions() {}

    Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
                          ExecutionContext *execution_context) override {
      Status error;
      const int short_option = m_getopt_table[option_idx].val;
      switch (short_option) {
      case 'e':
        m_expand.SetCurrentValue(true);
        break;

      default:
        error.SetErrorStringWithFormat("invalid short option character '%c'",
                                       short_option);
        break;
      }

      return error;
    }

    void OptionParsingStarting(ExecutionContext *execution_context) override {
      m_expand.Clear();
    }

    llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
      return llvm::ArrayRef(g_swift_demangle_options);
    }

    // Options table: Required for subclasses of Options.

    OptionValueBoolean m_expand;
  };

protected:
  void DoExecute(Args &command, CommandReturnObject &result) override {
    for (size_t i = 0; i < command.GetArgumentCount(); i++) {
      StringRef name = command.GetArgumentAtIndex(i);
      if (!name.empty()) {
        Context ctx;
        NodePointer node_ptr = nullptr;
        // Match the behavior of swift-demangle and accept Swift symbols without
        // the leading `$`. This makes symbol copy & paste more convenient.
        if (name.startswith("S") || name.startswith("s")) {
          std::string correctedName = std::string("$") + name.str();
          node_ptr =
              SwiftLanguageRuntime::DemangleSymbolAsNode(correctedName, ctx);
        } else {
          node_ptr = SwiftLanguageRuntime::DemangleSymbolAsNode(name, ctx);
        }
        if (node_ptr) {
          if (m_options.m_expand)
            result.GetOutputStream().PutCString(getNodeTreeAsString(node_ptr));
          result.GetOutputStream().Printf(
              "%s ---> %s\n", name.data(),
              swift::Demangle::nodeToString(node_ptr).c_str());
        }
      }
    }
    result.SetStatus(lldb::eReturnStatusSuccessFinishResult);
  }

  CommandOptions m_options;
};

class CommandObjectSwift_RefCount : public CommandObjectRaw {
public:
  CommandObjectSwift_RefCount(CommandInterpreter &interpreter)
      : CommandObjectRaw(interpreter, "refcount",
                         "Inspect the reference count data for a Swift object",
                         "language swift refcount",
                         eCommandProcessMustBePaused | eCommandRequiresFrame) {}

  ~CommandObjectSwift_RefCount() {}

  Options *GetOptions() override { return nullptr; }

private:
  enum class ReferenceCountType {
    eReferenceStrong,
    eReferenceUnowned,
    eReferenceWeak,
  };

  std::optional<uint32_t> getReferenceCount(StringRef ObjName,
                                             ReferenceCountType Type,
                                             ExecutionContext &exe_ctx,
                                             StackFrameSP &Frame) {
    std::string Kind;
    switch (Type) {
    case ReferenceCountType::eReferenceStrong:
      Kind = "";
      break;
    case ReferenceCountType::eReferenceUnowned:
      Kind = "Unowned";
      break;
    case ReferenceCountType::eReferenceWeak:
      Kind = "Weak";
      break;
    }

    EvaluateExpressionOptions eval_options;
    eval_options.SetLanguage(lldb::eLanguageTypeSwift);
    eval_options.SetSuppressPersistentResult(true);
    ValueObjectSP result_valobj_sp;
    std::string Expr =
        (llvm::Twine("Swift._get") + Kind + llvm::Twine("RetainCount(") +
         ObjName + llvm::Twine(")"))
            .str();
    bool evalStatus = exe_ctx.GetTargetSP()->EvaluateExpression(
        Expr, Frame.get(), result_valobj_sp, eval_options);
    if (evalStatus != eExpressionCompleted)
      return std::nullopt;

    bool success = false;
    uint32_t count = result_valobj_sp->GetSyntheticValue()->GetValueAsUnsigned(
        UINT32_MAX, &success);
    if (!success)
      return std::nullopt;
    return count;
  }

protected:
  void DoExecute(llvm::StringRef command,
                 CommandReturnObject &result) override {
    StackFrameSP frame_sp(m_exe_ctx.GetFrameSP());
    EvaluateExpressionOptions options;
    options.SetLanguage(lldb::eLanguageTypeSwift);
    options.SetSuppressPersistentResult(true);
    ValueObjectSP result_valobj_sp;

    // We want to evaluate first the object we're trying to get the
    // refcount of, in order, to, e.g. see whether it's available.
    // So, given `language swift refcount patatino`, we try to
    // evaluate `expr patatino` and fail early in case there is
    // an error.
    bool evalStatus = m_exe_ctx.GetTargetSP()->EvaluateExpression(
        command, frame_sp.get(), result_valobj_sp, options);
    if (evalStatus != eExpressionCompleted) {
      result.SetStatus(lldb::eReturnStatusFailed);
      if (result_valobj_sp && result_valobj_sp->GetError().Fail())
        result.AppendError(result_valobj_sp->GetError().AsCString());
      return;
    }

    // At this point, we're sure we're grabbing in our hands a valid
    // object and we can ask questions about it. `refcounts` are only
    // defined on class objects, so we throw an error in case we're
    // trying to look at something else.
    result_valobj_sp = result_valobj_sp->GetQualifiedRepresentationIfAvailable(
        lldb::eDynamicCanRunTarget, true);
    CompilerType result_type(result_valobj_sp->GetCompilerType());
    if (!(result_type.GetTypeInfo() & lldb::eTypeInstanceIsPointer)) {
      result.AppendError("refcount only available for class types");
      result.SetStatus(lldb::eReturnStatusFailed);
      return;
    }

    // Ask swift debugger support in the compiler about the objects
    // reference counts, and return them to the user.
    std::optional<uint32_t> strong = getReferenceCount(
        command, ReferenceCountType::eReferenceStrong, m_exe_ctx, frame_sp);
    std::optional<uint32_t> unowned = getReferenceCount(
        command, ReferenceCountType::eReferenceUnowned, m_exe_ctx, frame_sp);
    std::optional<uint32_t> weak = getReferenceCount(
        command, ReferenceCountType::eReferenceWeak, m_exe_ctx, frame_sp);

    std::string unavailable = "<unavailable>";

    result.AppendMessageWithFormat(
        "refcount data: (strong = %s, unowned = %s, weak = %s)\n",
        strong ? std::to_string(*strong).c_str() : unavailable.c_str(),
        unowned ? std::to_string(*unowned).c_str() : unavailable.c_str(),
        weak ? std::to_string(*weak).c_str() : unavailable.c_str());
    result.SetStatus(lldb::eReturnStatusSuccessFinishResult);
  }
};

class CommandObjectMultiwordSwift : public CommandObjectMultiword {
public:
  CommandObjectMultiwordSwift(CommandInterpreter &interpreter)
      : CommandObjectMultiword(
            interpreter, "swift",
            "A set of commands for operating on the Swift Language Runtime.",
            "swift <subcommand> [<subcommand-options>]") {
    LoadSubCommand("demangle", CommandObjectSP(new CommandObjectSwift_Demangle(
                                   interpreter)));
    LoadSubCommand("refcount", CommandObjectSP(new CommandObjectSwift_RefCount(
                                   interpreter)));
  }

  virtual ~CommandObjectMultiwordSwift() {}
};

void SwiftLanguageRuntime::Initialize() {
  PluginManager::RegisterPlugin(
      GetPluginNameStatic(), "Language runtime for the Swift language",
      CreateInstance,
      [](CommandInterpreter &interpreter) -> lldb::CommandObjectSP {
        return CommandObjectSP(new CommandObjectMultiwordSwift(interpreter));
      },
      SwiftLanguageRuntimeImpl::GetBreakpointExceptionPrecondition);
}

void SwiftLanguageRuntime::Terminate() {
  PluginManager::UnregisterPlugin(CreateInstance);
}

#define FORWARD(METHOD, ...)                                                   \
  assert(m_impl || m_stub);                                                    \
  return m_impl ? m_impl->METHOD(__VA_ARGS__) : m_stub->METHOD(__VA_ARGS__);

ThreadSafeReflectionContext
SwiftLanguageRuntime::GetReflectionContext() {
  // Hand written because the ternary operator prevents RVO when compiling with
  // MSVC.
  assert(m_impl || m_stub);
  if (m_impl)
    return m_impl->GetReflectionContext();
  return m_stub->GetReflectionContext();
}

void SwiftLanguageRuntime::SymbolsDidLoad(const ModuleList &module_list) {
  FORWARD(SymbolsDidLoad, module_list);
}

bool SwiftLanguageRuntime::GetDynamicTypeAndAddress(
    ValueObject &in_value, lldb::DynamicValueType use_dynamic,
    TypeAndOrName &class_type_or_name, Address &address,
    Value::ValueType &value_type) {
  FORWARD(GetDynamicTypeAndAddress, in_value, use_dynamic, class_type_or_name,
          address, value_type);
}

CompilerType SwiftLanguageRuntime::BindGenericTypeParameters(
    CompilerType unbound_type,
    std::function<CompilerType(unsigned, unsigned)> type_resolver) {
  FORWARD(BindGenericTypeParameters, unbound_type, type_resolver);
}

void SwiftLanguageRuntime::DumpTyperef(CompilerType type,
                                       TypeSystemSwiftTypeRef *module_holder,
                                       Stream *s) {
  FORWARD(DumpTyperef, type, module_holder, s);
}

TypeAndOrName
SwiftLanguageRuntime::FixUpDynamicType(const TypeAndOrName &type_and_or_name,
                                       ValueObject &static_value) {
  FORWARD(FixUpDynamicType, type_and_or_name, static_value);
}

bool SwiftLanguageRuntime::IsTaggedPointer(lldb::addr_t addr,
                                           CompilerType type) {
  FORWARD(IsTaggedPointer, addr, type);
}

std::pair<lldb::addr_t, bool>
SwiftLanguageRuntime::FixupPointerValue(lldb::addr_t addr, CompilerType type) {
  FORWARD(FixupPointerValue, addr, type);
}

lldb::addr_t SwiftLanguageRuntime::FixupAddress(lldb::addr_t addr,
                                                CompilerType type,
                                                Status &error) {
  FORWARD(FixupAddress, addr, type, error);
}

CompilerType SwiftLanguageRuntime::GetTypeFromMetadata(TypeSystemSwift &tss,
                                                       Address addr) {
  FORWARD(GetTypeFromMetadata, tss, addr);
}

bool SwiftLanguageRuntime::IsStoredInlineInBuffer(CompilerType type) {
  FORWARD(IsStoredInlineInBuffer, type);
}

std::optional<uint64_t> SwiftLanguageRuntime::GetMemberVariableOffset(
    CompilerType instance_type, ValueObject *instance,
    llvm::StringRef member_name, Status *error) {
  FORWARD(GetMemberVariableOffset, instance_type, instance, member_name, error);
}

llvm::Expected<uint32_t>
SwiftLanguageRuntime::GetNumChildren(CompilerType type,
                                     ExecutionContextScope *exe_scope) {
  FORWARD(GetNumChildren, type, exe_scope);
}

std::optional<std::string> SwiftLanguageRuntime::GetEnumCaseName(
    CompilerType type, const DataExtractor &data, ExecutionContext *exe_ctx) {
  FORWARD(GetEnumCaseName, type, data, exe_ctx);
}

std::pair<SwiftLanguageRuntime::LookupResult, std::optional<size_t>>
SwiftLanguageRuntime::GetIndexOfChildMemberWithName(
    CompilerType type, llvm::StringRef name, ExecutionContext *exe_ctx,
    bool omit_empty_base_classes, std::vector<uint32_t> &child_indexes) {
  FORWARD(GetIndexOfChildMemberWithName, type, name, exe_ctx,
          omit_empty_base_classes, child_indexes);
}

llvm::Expected<CompilerType> SwiftLanguageRuntime::GetChildCompilerTypeAtIndex(
    CompilerType type, size_t idx, bool transparent_pointers,
    bool omit_empty_base_classes, bool ignore_array_bounds,
    std::string &child_name, uint32_t &child_byte_size,
    int32_t &child_byte_offset, uint32_t &child_bitfield_bit_size,
    uint32_t &child_bitfield_bit_offset, bool &child_is_base_class,
    bool &child_is_deref_of_parent, ValueObject *valobj,
    uint64_t &language_flags) {
  FORWARD(GetChildCompilerTypeAtIndex, type, idx, transparent_pointers,
          omit_empty_base_classes, ignore_array_bounds, child_name,
          child_byte_size, child_byte_offset,
          child_bitfield_bit_size, child_bitfield_bit_offset,
          child_is_base_class, child_is_deref_of_parent, valobj,
          language_flags);
}

std::optional<unsigned>
SwiftLanguageRuntime::GetNumFields(CompilerType type,
                                   ExecutionContext *exe_ctx) {
  FORWARD(GetNumFields, type, exe_ctx);
}

llvm::Error SwiftLanguageRuntime::GetObjectDescription(Stream &str,
                                                       ValueObject &object) {
  FORWARD(GetObjectDescription, str, object);
}

void SwiftLanguageRuntime::AddToLibraryNegativeCache(
    llvm::StringRef library_name) {
  FORWARD(AddToLibraryNegativeCache, library_name);
}

bool SwiftLanguageRuntime::IsInLibraryNegativeCache(
    llvm::StringRef library_name) {
  FORWARD(IsInLibraryNegativeCache, library_name);
}

void SwiftLanguageRuntime::ReleaseAssociatedRemoteASTContext(
    swift::ASTContext *ctx) {
  FORWARD(ReleaseAssociatedRemoteASTContext, ctx);
}

CompilerType
SwiftLanguageRuntime::BindGenericTypeParameters(StackFrame &stack_frame,
                                                CompilerType base_type) {
  FORWARD(BindGenericTypeParameters, stack_frame, base_type);
}

CompilerType
SwiftLanguageRuntime::GetConcreteType(ExecutionContextScope *exe_scope,
                                      ConstString abstract_type_name) {
  FORWARD(GetConcreteType, exe_scope, abstract_type_name);
}

std::optional<uint64_t>
SwiftLanguageRuntime::GetBitSize(CompilerType type,
                                 ExecutionContextScope *exe_scope) {
  FORWARD(GetBitSize, type, exe_scope);
}

std::optional<uint64_t>
SwiftLanguageRuntime::GetByteStride(CompilerType type) {
  FORWARD(GetByteStride, type);
}

std::optional<size_t>
SwiftLanguageRuntime::GetBitAlignment(CompilerType type,
                                      ExecutionContextScope *exe_scope) {
  FORWARD(GetBitAlignment, type, exe_scope);
}

bool SwiftLanguageRuntime::IsValidErrorValue(ValueObject &in_value) {
  FORWARD(IsValidErrorValue, in_value);
}

lldb::SyntheticChildrenSP
SwiftLanguageRuntime::GetBridgedSyntheticChildProvider(ValueObject &valobj) {
  FORWARD(GetBridgedSyntheticChildProvider, valobj);
}

void SwiftLanguageRuntime::WillStartExecutingUserExpression(
    bool runs_in_playground_or_repl) {
  FORWARD(WillStartExecutingUserExpression, runs_in_playground_or_repl);
}

void SwiftLanguageRuntime::DidFinishExecutingUserExpression(
    bool runs_in_playground_or_repl) {
  FORWARD(DidFinishExecutingUserExpression, runs_in_playground_or_repl);
}

bool SwiftLanguageRuntime::IsABIStable() { FORWARD(IsABIStable); }

namespace {
/// The target specific register numbers used for async unwinding.
///
/// For UnwindPlans, these use eh_frame / dwarf register numbering.
struct AsyncUnwindRegisterNumbers {
  uint32_t async_ctx_regnum;
  uint32_t fp_regnum;
  uint32_t pc_regnum;
  /// A register to use as a marker to indicate how the async context is passed
  /// to the function (indirectly, or not). This needs to be communicated to the
  /// frames below us as they need to react differently. There is no good way to
  /// expose this, so we set another dummy register to communicate this state.
  uint32_t dummy_regnum;
};
} // namespace

static std::optional<AsyncUnwindRegisterNumbers>
GetAsyncUnwindRegisterNumbers(llvm::Triple::ArchType triple) {
  switch (triple) {
  case llvm::Triple::x86_64: {
    AsyncUnwindRegisterNumbers regnums;
    regnums.async_ctx_regnum = dwarf_r14_x86_64;
    regnums.fp_regnum = dwarf_rbp_x86_64;
    regnums.pc_regnum = dwarf_rip_x86_64;
    regnums.dummy_regnum = dwarf_r15_x86_64;
    return regnums;
  }
  case llvm::Triple::aarch64: {
    AsyncUnwindRegisterNumbers regnums;
    regnums.async_ctx_regnum = arm64_dwarf::x22;
    regnums.fp_regnum = arm64_dwarf::fp;
    regnums.pc_regnum = arm64_dwarf::pc;
    regnums.dummy_regnum = arm64_dwarf::x23;
    return regnums;
  }
  default:
    return {};
  }
}

lldb::addr_t SwiftLanguageRuntime::GetAsyncContext(RegisterContext *regctx) {
  if (!regctx)
    return LLDB_INVALID_ADDRESS;

  auto arch = regctx->CalculateTarget()->GetArchitecture();
  if (auto regnums = GetAsyncUnwindRegisterNumbers(arch.GetMachine())) {
    auto reg = regctx->ConvertRegisterKindToRegisterNumber(
        RegisterKind::eRegisterKindDWARF, regnums->async_ctx_regnum);
    return regctx->ReadRegisterAsUnsigned(reg, LLDB_INVALID_ADDRESS);
  }

  assert(false && "swift async supports only x86_64 and arm64");
  return LLDB_INVALID_ADDRESS;
}

// Examine the register state and detect the transition from a real
// stack frame to an AsyncContext frame, or a frame in the middle of
// the AsyncContext chain, and return an UnwindPlan for these situations.
UnwindPlanSP
SwiftLanguageRuntime::GetRuntimeUnwindPlan(ProcessSP process_sp,
                                           RegisterContext *regctx,
                                           bool &behaves_like_zeroth_frame) {
  LLDB_SCOPED_TIMER();

  Target &target(process_sp->GetTarget());
  auto arch = target.GetArchitecture();
  std::optional<AsyncUnwindRegisterNumbers> regnums =
      GetAsyncUnwindRegisterNumbers(arch.GetMachine());
  if (!regnums)
    return UnwindPlanSP();

  // If we can't fetch the fp reg, and we *can* fetch the async
  // context register, then we're in the middle of the AsyncContext
  // chain, return an UnwindPlan for that.
  addr_t fp = regctx->GetFP(LLDB_INVALID_ADDRESS);
  if (fp == LLDB_INVALID_ADDRESS) {
    if (GetAsyncContext(regctx) != LLDB_INVALID_ADDRESS)
      return GetFollowAsyncContextUnwindPlan(process_sp, regctx, arch,
                                             behaves_like_zeroth_frame);
    return UnwindPlanSP();
  }

  // If we're in the prologue of a function, don't provide a Swift async
  // unwind plan.  We can be tricked by unmodified caller-registers that
  // make this look like an async frame when this is a standard ABI function
  // call, and the parent is the async frame.
  // This assumes that the frame pointer register will be modified in the
  // prologue.
  Address pc;
  pc.SetLoadAddress(regctx->GetPC(), &target);
  SymbolContext sc;
  if (pc.IsValid())
    if (!pc.CalculateSymbolContext(&sc, eSymbolContextFunction |
                                            eSymbolContextSymbol))
      return UnwindPlanSP();

  Address func_start_addr;
  uint32_t prologue_size;
  ConstString mangled_name;
  if (sc.function) {
    func_start_addr = sc.function->GetAddressRange().GetBaseAddress();
    prologue_size = sc.function->GetPrologueByteSize();
    mangled_name = sc.function->GetMangled().GetMangledName();
  } else if (sc.symbol) {
    func_start_addr = sc.symbol->GetAddress();
    prologue_size = sc.symbol->GetPrologueByteSize();
    mangled_name = sc.symbol->GetMangled().GetMangledName();
  } else {
    return UnwindPlanSP();
  }

  AddressRange prologue_range(func_start_addr, prologue_size);
  bool in_prologue = (func_start_addr == pc ||
                      prologue_range.ContainsLoadAddress(pc, &target));

  if (in_prologue) {
    if (!IsAnySwiftAsyncFunctionSymbol(mangled_name.GetStringRef()))
      return UnwindPlanSP();
  } else {
    addr_t saved_fp = LLDB_INVALID_ADDRESS;
    Status error;
    if (!process_sp->ReadMemory(fp, &saved_fp, 8, error))
      return UnwindPlanSP();

    // Get the high nibble of the dreferenced fp; if the 60th bit is set,
    // this is the transition to a swift async AsyncContext chain.
    if ((saved_fp & (0xfULL << 60)) >> 60 != 1)
      return UnwindPlanSP();
  }

  // The coroutine funclets split from an async function have 2 different ABIs:
  //  - Async suspend partial functions and the first funclet get their async
  //    context directly in the async register.
  //  - Async await resume partial functions take their context indirectly, it
  //    needs to be dereferenced to get the actual function's context.
  // The debug info for locals reflects this difference, so our unwinding of the
  // context register needs to reflect it too.
  bool indirect_context =
      IsSwiftAsyncAwaitResumePartialFunctionSymbol(mangled_name.GetStringRef());

  UnwindPlan::RowSP row(new UnwindPlan::Row);
  const int32_t ptr_size = 8;
  row->SetOffset(0);

  // A DWARF Expression to set the CFA.
  //      pushes the frame pointer register - 8
  //      dereference

  // FIXME: Row::RegisterLocation::RestoreType doesn't have a
  // deref(reg-value + offset) yet, shortcut around it with
  // a dwarf expression for now.
  // The CFA of an async frame is the address of it's associated AsyncContext.
  // In an async frame currently on the stack, this address is stored right
  // before the saved frame pointer on the stack.
  static const uint8_t g_cfa_dwarf_expression_x86_64[] = {
      llvm::dwarf::DW_OP_breg6, // DW_OP_breg6, register 6 == rbp
      0x78,                     //    sleb128 -8 (ptrsize)
      llvm::dwarf::DW_OP_deref,
  };
  static const uint8_t g_cfa_dwarf_expression_arm64[] = {
      llvm::dwarf::DW_OP_breg29, // DW_OP_breg29, register 29 == fp
      0x78,                      //    sleb128 -8 (ptrsize)
      llvm::dwarf::DW_OP_deref,
  };

  constexpr unsigned expr_size = sizeof(g_cfa_dwarf_expression_arm64);

  static_assert(sizeof(g_cfa_dwarf_expression_x86_64) ==
                    sizeof(g_cfa_dwarf_expression_arm64),
                "Code relies on DWARF  expressions being the same size");

  const uint8_t *expr = nullptr;
  if (arch.GetMachine() == llvm::Triple::x86_64)
    expr = g_cfa_dwarf_expression_x86_64;
  else if (arch.GetMachine() == llvm::Triple::aarch64)
    expr = g_cfa_dwarf_expression_arm64;
  else
    llvm_unreachable("Unsupported architecture");

  if (in_prologue) {
    if (indirect_context)
      row->GetCFAValue().SetIsRegisterDereferenced(regnums->async_ctx_regnum);
    else
      row->GetCFAValue().SetIsRegisterPlusOffset(regnums->async_ctx_regnum, 0);
  } else {
    row->GetCFAValue().SetIsDWARFExpression(expr, expr_size);
  }

  if (indirect_context) {
    if (in_prologue) {
      row->SetRegisterLocationToSame(regnums->async_ctx_regnum, false);
    } else {
      // In a "resume" coroutine, the passed context argument needs to be
      // dereferenced once to get the context. This is reflected in the debug
      // info so we need to account for it and report am async register value
      // that needs to be dereferenced to get to the context.
      // Note that the size passed for the DWARF expression is the size of the
      // array minus one. This skips the last deref for this use.
      assert(expr[expr_size - 1] == llvm::dwarf::DW_OP_deref &&
             "Should skip a deref");
      row->SetRegisterLocationToIsDWARFExpression(regnums->async_ctx_regnum,
                                                  expr, expr_size - 1, false);
    }
  } else {
    // In the first part of a split async function, the context is passed
    // directly, so we can use the CFA value directly.
    row->SetRegisterLocationToIsCFAPlusOffset(regnums->async_ctx_regnum, 0,
                                              false);
    // The fact that we are in this case needs to be communicated to the frames
    // below us as they need to react differently. There is no good way to
    // expose this, so we set another dummy register to communicate this state.
    static const uint8_t g_dummy_dwarf_expression[] = {
        llvm::dwarf::DW_OP_const1u, 0
    };
    row->SetRegisterLocationToIsDWARFExpression(
        regnums->dummy_regnum, g_dummy_dwarf_expression,
        sizeof(g_dummy_dwarf_expression), false);
  }

  std::optional<addr_t> pc_after_prologue = [&]() -> std::optional<addr_t> {
    // In the prologue, use the async_reg as is, it has not been clobbered.
    if (in_prologue)
      return TrySkipVirtualParentProlog(GetAsyncContext(regctx), *process_sp,
                                        indirect_context);

    // Both ABIs (x86_64 and aarch64) guarantee the async reg is saved at:
    // *(fp - 8).
    Status error;
    addr_t async_reg_entry_value = LLDB_INVALID_ADDRESS;
    process_sp->ReadMemory(fp - ptr_size, &async_reg_entry_value, ptr_size,
                           error);
    if (error.Fail())
      return {};
    return TrySkipVirtualParentProlog(async_reg_entry_value, *process_sp,
                                      indirect_context);
  }();

  if (pc_after_prologue)
    row->SetRegisterLocationToIsConstant(regnums->pc_regnum, *pc_after_prologue,
                                         false);
  else
    row->SetRegisterLocationToAtCFAPlusOffset(regnums->pc_regnum, ptr_size,
                                              false);
  row->SetUnspecifiedRegistersAreUndefined(true);

  UnwindPlanSP plan = std::make_shared<UnwindPlan>(lldb::eRegisterKindDWARF);
  plan->AppendRow(row);
  plan->SetSourceName("Swift Transition-to-AsyncContext-Chain");
  plan->SetSourcedFromCompiler(eLazyBoolNo);
  plan->SetUnwindPlanValidAtAllInstructions(eLazyBoolYes);
  plan->SetUnwindPlanForSignalTrap(eLazyBoolYes);
  return plan;
}

UnwindPlanSP SwiftLanguageRuntime::GetFollowAsyncContextUnwindPlan(
    ProcessSP process_sp, RegisterContext *regctx, ArchSpec &arch,
    bool &behaves_like_zeroth_frame) {
  LLDB_SCOPED_TIMER();

  UnwindPlan::RowSP row(new UnwindPlan::Row);
  const int32_t ptr_size = 8;
  row->SetOffset(0);

  std::optional<AsyncUnwindRegisterNumbers> regnums =
      GetAsyncUnwindRegisterNumbers(arch.GetMachine());
  if (!regnums)
    return UnwindPlanSP();

  const bool is_indirect =
      regctx->ReadRegisterAsUnsigned(regnums->dummy_regnum, (uint64_t)-1ll) ==
      (uint64_t)-1ll;
  // In the general case, the async register setup by the frame above us
  // should be dereferenced twice to get our context, except when the frame
  // above us is an async frame on the OS stack that takes its context directly
  // (see discussion in GetRuntimeUnwindPlan()). The availability of
  // dummy_regnum is used as a marker for this situation.
  if (!is_indirect) {
    row->GetCFAValue().SetIsRegisterDereferenced(regnums->async_ctx_regnum);
    row->SetRegisterLocationToSame(regnums->async_ctx_regnum, false);
  } else {
    static const uint8_t async_dwarf_expression_x86_64[] = {
        llvm::dwarf::DW_OP_regx, dwarf_r14_x86_64, // DW_OP_regx, reg
        llvm::dwarf::DW_OP_deref,                  // DW_OP_deref
        llvm::dwarf::DW_OP_deref,                  // DW_OP_deref
    };
    static const uint8_t async_dwarf_expression_arm64[] = {
        llvm::dwarf::DW_OP_regx, arm64_dwarf::x22, // DW_OP_regx, reg
        llvm::dwarf::DW_OP_deref,                  // DW_OP_deref
        llvm::dwarf::DW_OP_deref,                  // DW_OP_deref
    };

    const unsigned expr_size = sizeof(async_dwarf_expression_x86_64);
    static_assert(sizeof(async_dwarf_expression_x86_64) ==
                      sizeof(async_dwarf_expression_arm64),
                  "Expressions of different sizes");

    const uint8_t *expression = nullptr;
    if (arch.GetMachine() == llvm::Triple::x86_64)
      expression = async_dwarf_expression_x86_64;
    else if (arch.GetMachine() == llvm::Triple::aarch64)
      expression = async_dwarf_expression_arm64;
    else
      llvm_unreachable("Unsupported architecture");

    // Note how the register location gets the same expression pointer with a
    // different size. We just skip the trailing deref for it.
    assert(expression[expr_size - 1] == llvm::dwarf::DW_OP_deref &&
           "Should skip a deref");
    row->GetCFAValue().SetIsDWARFExpression(expression, expr_size);
    row->SetRegisterLocationToIsDWARFExpression(
        regnums->async_ctx_regnum, expression, expr_size - 1, false);
  }

  // Suppose this is unwinding frame #2 of a call stack. The value given for
  // the async register has two possible values, depending on what frame #1
  // expects:
  // 1. The CFA of frame #1, direct ABI, dereferencing it once produces CFA of
  // Frame #2.
  // 2. The CFA of frame #0, indirect ABI, dereferencing it twice produces CFA
  // of Frame #2.
  const unsigned num_indirections = 1 + is_indirect;
  if (std::optional<addr_t> pc_after_prologue = TrySkipVirtualParentProlog(
          GetAsyncContext(regctx), *process_sp, num_indirections))
    row->SetRegisterLocationToIsConstant(regnums->pc_regnum, *pc_after_prologue,
                                         false);
  else
    row->SetRegisterLocationToAtCFAPlusOffset(regnums->pc_regnum, ptr_size,
                                              false);

  row->SetUnspecifiedRegistersAreUndefined(true);

  UnwindPlanSP plan = std::make_shared<UnwindPlan>(lldb::eRegisterKindDWARF);
  plan->AppendRow(row);
  plan->SetSourceName("Swift Following-AsyncContext-Chain");
  plan->SetSourcedFromCompiler(eLazyBoolNo);
  plan->SetUnwindPlanValidAtAllInstructions(eLazyBoolYes);
  plan->SetUnwindPlanForSignalTrap(eLazyBoolYes);
  behaves_like_zeroth_frame = true;
  return plan;
}

std::optional<lldb::addr_t> SwiftLanguageRuntime::TrySkipVirtualParentProlog(
    lldb::addr_t async_reg_val, Process &process, unsigned num_indirections) {
  assert(num_indirections <= 2 &&
         "more than two dereferences should not be needed");
  if (async_reg_val == LLDB_INVALID_ADDRESS || async_reg_val == 0)
    return {};

  const auto ptr_size = process.GetAddressByteSize();
  Status error;

  // Compute the CFA of this frame.
  addr_t cfa = async_reg_val;
  for (; num_indirections != 0; --num_indirections) {
    process.ReadMemory(cfa, &cfa, ptr_size, error);
    if (error.Fail())
      return {};
  }

  // The last funclet will have a zero CFA, we don't want to read that.
  if (cfa == 0)
    return {};

  // Get the PC of the parent frame, i.e. the continuation pointer, which is
  // the second field of the CFA.
  addr_t pc_location = cfa + ptr_size;
  addr_t pc_value = LLDB_INVALID_ADDRESS;
  process.ReadMemory(pc_location, &pc_value, ptr_size, error);
  if (error.Fail())
    return {};

  Address pc;
  Target &target = process.GetTarget();
  pc.SetLoadAddress(pc_value, &target);
  if (!pc.IsValid())
    return {};

  SymbolContext sc;
  if (!pc.CalculateSymbolContext(&sc,
                                 eSymbolContextFunction | eSymbolContextSymbol))
    return {};
  if (!sc.symbol && !sc.function)
    return {};

  auto prologue_size = sc.symbol ? sc.symbol->GetPrologueByteSize()
                                 : sc.function->GetPrologueByteSize();
  return pc_value + prologue_size;
}
} // namespace lldb_private