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
|
//===- DebugInfo.cpp - Debug Information Helper Classes -------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file implements the helper classes used to build and interpret debug
// information in LLVM IR form.
//
//===----------------------------------------------------------------------===//
#include "llvm-c/DebugInfo.h"
#include "LLVMContextImpl.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/DenseSet.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/IR/BasicBlock.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DIBuilder.h"
#include "llvm/IR/DebugInfo.h"
#include "llvm/IR/DebugInfoMetadata.h"
#include "llvm/IR/DebugLoc.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/GVMaterializer.h"
#include "llvm/IR/Instruction.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Metadata.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/PassManager.h"
#include "llvm/Support/Casting.h"
#include <algorithm>
#include <cassert>
#include <optional>
#include <utility>
using namespace llvm;
using namespace llvm::at;
using namespace llvm::dwarf;
/// Finds all intrinsics declaring local variables as living in the memory that
/// 'V' points to. This may include a mix of dbg.declare and
/// dbg.addr intrinsics.
TinyPtrVector<DbgVariableIntrinsic *> llvm::FindDbgAddrUses(Value *V) {
// This function is hot. Check whether the value has any metadata to avoid a
// DenseMap lookup.
if (!V->isUsedByMetadata())
return {};
auto *L = LocalAsMetadata::getIfExists(V);
if (!L)
return {};
auto *MDV = MetadataAsValue::getIfExists(V->getContext(), L);
if (!MDV)
return {};
TinyPtrVector<DbgVariableIntrinsic *> Declares;
for (User *U : MDV->users()) {
if (auto *DII = dyn_cast<DbgVariableIntrinsic>(U))
if (DII->isAddressOfVariable())
Declares.push_back(DII);
}
return Declares;
}
TinyPtrVector<DbgDeclareInst *> llvm::FindDbgDeclareUses(Value *V) {
TinyPtrVector<DbgDeclareInst *> DDIs;
for (DbgVariableIntrinsic *DVI : FindDbgAddrUses(V))
if (auto *DDI = dyn_cast<DbgDeclareInst>(DVI))
DDIs.push_back(DDI);
return DDIs;
}
void llvm::findDbgValues(SmallVectorImpl<DbgValueInst *> &DbgValues, Value *V) {
// This function is hot. Check whether the value has any metadata to avoid a
// DenseMap lookup.
if (!V->isUsedByMetadata())
return;
// TODO: If this value appears multiple times in a DIArgList, we should still
// only add the owning DbgValueInst once; use this set to track ArgListUsers.
// This behaviour can be removed when we can automatically remove duplicates.
SmallPtrSet<DbgValueInst *, 4> EncounteredDbgValues;
if (auto *L = LocalAsMetadata::getIfExists(V)) {
if (auto *MDV = MetadataAsValue::getIfExists(V->getContext(), L)) {
for (User *U : MDV->users())
if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(U))
DbgValues.push_back(DVI);
}
for (Metadata *AL : L->getAllArgListUsers()) {
if (auto *MDV = MetadataAsValue::getIfExists(V->getContext(), AL)) {
for (User *U : MDV->users())
if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(U))
if (EncounteredDbgValues.insert(DVI).second)
DbgValues.push_back(DVI);
}
}
}
}
void llvm::findDbgUsers(SmallVectorImpl<DbgVariableIntrinsic *> &DbgUsers,
Value *V) {
// This function is hot. Check whether the value has any metadata to avoid a
// DenseMap lookup.
if (!V->isUsedByMetadata())
return;
// TODO: If this value appears multiple times in a DIArgList, we should still
// only add the owning DbgValueInst once; use this set to track ArgListUsers.
// This behaviour can be removed when we can automatically remove duplicates.
SmallPtrSet<DbgVariableIntrinsic *, 4> EncounteredDbgValues;
if (auto *L = LocalAsMetadata::getIfExists(V)) {
if (auto *MDV = MetadataAsValue::getIfExists(V->getContext(), L)) {
for (User *U : MDV->users())
if (DbgVariableIntrinsic *DII = dyn_cast<DbgVariableIntrinsic>(U))
DbgUsers.push_back(DII);
}
for (Metadata *AL : L->getAllArgListUsers()) {
if (auto *MDV = MetadataAsValue::getIfExists(V->getContext(), AL)) {
for (User *U : MDV->users())
if (DbgVariableIntrinsic *DII = dyn_cast<DbgVariableIntrinsic>(U))
if (EncounteredDbgValues.insert(DII).second)
DbgUsers.push_back(DII);
}
}
}
}
DISubprogram *llvm::getDISubprogram(const MDNode *Scope) {
if (auto *LocalScope = dyn_cast_or_null<DILocalScope>(Scope))
return LocalScope->getSubprogram();
return nullptr;
}
DebugLoc llvm::getDebugValueLoc(DbgVariableIntrinsic *DII) {
// Original dbg.declare must have a location.
const DebugLoc &DeclareLoc = DII->getDebugLoc();
MDNode *Scope = DeclareLoc.getScope();
DILocation *InlinedAt = DeclareLoc.getInlinedAt();
// Because no machine insts can come from debug intrinsics, only the scope
// and inlinedAt is significant. Zero line numbers are used in case this
// DebugLoc leaks into any adjacent instructions. Produce an unknown location
// with the correct scope / inlinedAt fields.
return DILocation::get(DII->getContext(), 0, 0, Scope, InlinedAt);
}
//===----------------------------------------------------------------------===//
// DebugInfoFinder implementations.
//===----------------------------------------------------------------------===//
void DebugInfoFinder::reset() {
CUs.clear();
SPs.clear();
GVs.clear();
TYs.clear();
Scopes.clear();
NodesSeen.clear();
}
void DebugInfoFinder::processModule(const Module &M) {
for (auto *CU : M.debug_compile_units())
processCompileUnit(CU);
for (auto &F : M.functions()) {
if (auto *SP = cast_or_null<DISubprogram>(F.getSubprogram()))
processSubprogram(SP);
// There could be subprograms from inlined functions referenced from
// instructions only. Walk the function to find them.
for (const BasicBlock &BB : F)
for (const Instruction &I : BB)
processInstruction(M, I);
}
}
void DebugInfoFinder::processCompileUnit(DICompileUnit *CU) {
if (!addCompileUnit(CU))
return;
for (auto *DIG : CU->getGlobalVariables()) {
if (!addGlobalVariable(DIG))
continue;
auto *GV = DIG->getVariable();
processScope(GV->getScope());
processType(GV->getType());
}
for (auto *ET : CU->getEnumTypes())
processType(ET);
for (auto *RT : CU->getRetainedTypes())
if (auto *T = dyn_cast<DIType>(RT))
processType(T);
else
processSubprogram(cast<DISubprogram>(RT));
for (auto *Import : CU->getImportedEntities()) {
auto *Entity = Import->getEntity();
if (auto *T = dyn_cast<DIType>(Entity))
processType(T);
else if (auto *SP = dyn_cast<DISubprogram>(Entity))
processSubprogram(SP);
else if (auto *NS = dyn_cast<DINamespace>(Entity))
processScope(NS->getScope());
else if (auto *M = dyn_cast<DIModule>(Entity))
processScope(M->getScope());
}
}
void DebugInfoFinder::processInstruction(const Module &M,
const Instruction &I) {
if (auto *DVI = dyn_cast<DbgVariableIntrinsic>(&I))
processVariable(M, *DVI);
if (auto DbgLoc = I.getDebugLoc())
processLocation(M, DbgLoc.get());
}
void DebugInfoFinder::processLocation(const Module &M, const DILocation *Loc) {
if (!Loc)
return;
processScope(Loc->getScope());
processLocation(M, Loc->getInlinedAt());
}
void DebugInfoFinder::processType(DIType *DT) {
if (!addType(DT))
return;
processScope(DT->getScope());
if (auto *ST = dyn_cast<DISubroutineType>(DT)) {
for (DIType *Ref : ST->getTypeArray())
processType(Ref);
return;
}
if (auto *DCT = dyn_cast<DICompositeType>(DT)) {
processType(DCT->getBaseType());
for (Metadata *D : DCT->getElements()) {
if (auto *T = dyn_cast<DIType>(D))
processType(T);
else if (auto *SP = dyn_cast<DISubprogram>(D))
processSubprogram(SP);
}
return;
}
if (auto *DDT = dyn_cast<DIDerivedType>(DT)) {
processType(DDT->getBaseType());
}
}
void DebugInfoFinder::processScope(DIScope *Scope) {
if (!Scope)
return;
if (auto *Ty = dyn_cast<DIType>(Scope)) {
processType(Ty);
return;
}
if (auto *CU = dyn_cast<DICompileUnit>(Scope)) {
addCompileUnit(CU);
return;
}
if (auto *SP = dyn_cast<DISubprogram>(Scope)) {
processSubprogram(SP);
return;
}
if (!addScope(Scope))
return;
if (auto *LB = dyn_cast<DILexicalBlockBase>(Scope)) {
processScope(LB->getScope());
} else if (auto *NS = dyn_cast<DINamespace>(Scope)) {
processScope(NS->getScope());
} else if (auto *M = dyn_cast<DIModule>(Scope)) {
processScope(M->getScope());
}
}
void DebugInfoFinder::processSubprogram(DISubprogram *SP) {
if (!addSubprogram(SP))
return;
processScope(SP->getScope());
// Some of the users, e.g. CloneFunctionInto / CloneModule, need to set up a
// ValueMap containing identity mappings for all of the DICompileUnit's, not
// just DISubprogram's, referenced from anywhere within the Function being
// cloned prior to calling MapMetadata / RemapInstruction to avoid their
// duplication later as DICompileUnit's are also directly referenced by
// llvm.dbg.cu list. Thefore we need to collect DICompileUnit's here as well.
// Also, DICompileUnit's may reference DISubprogram's too and therefore need
// to be at least looked through.
processCompileUnit(SP->getUnit());
processType(SP->getType());
for (auto *Element : SP->getTemplateParams()) {
if (auto *TType = dyn_cast<DITemplateTypeParameter>(Element)) {
processType(TType->getType());
} else if (auto *TVal = dyn_cast<DITemplateValueParameter>(Element)) {
processType(TVal->getType());
}
}
}
void DebugInfoFinder::processVariable(const Module &M,
const DbgVariableIntrinsic &DVI) {
auto *N = dyn_cast<MDNode>(DVI.getVariable());
if (!N)
return;
auto *DV = dyn_cast<DILocalVariable>(N);
if (!DV)
return;
if (!NodesSeen.insert(DV).second)
return;
processScope(DV->getScope());
processType(DV->getType());
}
bool DebugInfoFinder::addType(DIType *DT) {
if (!DT)
return false;
if (!NodesSeen.insert(DT).second)
return false;
TYs.push_back(const_cast<DIType *>(DT));
return true;
}
bool DebugInfoFinder::addCompileUnit(DICompileUnit *CU) {
if (!CU)
return false;
if (!NodesSeen.insert(CU).second)
return false;
CUs.push_back(CU);
return true;
}
bool DebugInfoFinder::addGlobalVariable(DIGlobalVariableExpression *DIG) {
if (!NodesSeen.insert(DIG).second)
return false;
GVs.push_back(DIG);
return true;
}
bool DebugInfoFinder::addSubprogram(DISubprogram *SP) {
if (!SP)
return false;
if (!NodesSeen.insert(SP).second)
return false;
SPs.push_back(SP);
return true;
}
bool DebugInfoFinder::addScope(DIScope *Scope) {
if (!Scope)
return false;
// FIXME: Ocaml binding generates a scope with no content, we treat it
// as null for now.
if (Scope->getNumOperands() == 0)
return false;
if (!NodesSeen.insert(Scope).second)
return false;
Scopes.push_back(Scope);
return true;
}
static MDNode *updateLoopMetadataDebugLocationsImpl(
MDNode *OrigLoopID, function_ref<Metadata *(Metadata *)> Updater) {
assert(OrigLoopID && OrigLoopID->getNumOperands() > 0 &&
"Loop ID needs at least one operand");
assert(OrigLoopID && OrigLoopID->getOperand(0).get() == OrigLoopID &&
"Loop ID should refer to itself");
// Save space for the self-referential LoopID.
SmallVector<Metadata *, 4> MDs = {nullptr};
for (unsigned i = 1; i < OrigLoopID->getNumOperands(); ++i) {
Metadata *MD = OrigLoopID->getOperand(i);
if (!MD)
MDs.push_back(nullptr);
else if (Metadata *NewMD = Updater(MD))
MDs.push_back(NewMD);
}
MDNode *NewLoopID = MDNode::getDistinct(OrigLoopID->getContext(), MDs);
// Insert the self-referential LoopID.
NewLoopID->replaceOperandWith(0, NewLoopID);
return NewLoopID;
}
void llvm::updateLoopMetadataDebugLocations(
Instruction &I, function_ref<Metadata *(Metadata *)> Updater) {
MDNode *OrigLoopID = I.getMetadata(LLVMContext::MD_loop);
if (!OrigLoopID)
return;
MDNode *NewLoopID = updateLoopMetadataDebugLocationsImpl(OrigLoopID, Updater);
I.setMetadata(LLVMContext::MD_loop, NewLoopID);
}
/// Return true if a node is a DILocation or if a DILocation is
/// indirectly referenced by one of the node's children.
static bool isDILocationReachable(SmallPtrSetImpl<Metadata *> &Visited,
SmallPtrSetImpl<Metadata *> &Reachable,
Metadata *MD) {
MDNode *N = dyn_cast_or_null<MDNode>(MD);
if (!N)
return false;
if (isa<DILocation>(N) || Reachable.count(N))
return true;
if (!Visited.insert(N).second)
return false;
for (auto &OpIt : N->operands()) {
Metadata *Op = OpIt.get();
if (isDILocationReachable(Visited, Reachable, Op)) {
Reachable.insert(N);
return true;
}
}
return false;
}
static MDNode *stripDebugLocFromLoopID(MDNode *N) {
assert(!N->operands().empty() && "Missing self reference?");
SmallPtrSet<Metadata *, 8> Visited, DILocationReachable;
// If we already visited N, there is nothing to do.
if (!Visited.insert(N).second)
return N;
// If there is no debug location, we do not have to rewrite this
// MDNode. This loop also initializes DILocationReachable, later
// needed by updateLoopMetadataDebugLocationsImpl; the use of
// count_if avoids an early exit.
if (!std::count_if(N->op_begin() + 1, N->op_end(),
[&Visited, &DILocationReachable](const MDOperand &Op) {
return isDILocationReachable(
Visited, DILocationReachable, Op.get());
}))
return N;
// If there is only the debug location without any actual loop metadata, we
// can remove the metadata.
if (llvm::all_of(llvm::drop_begin(N->operands()),
[&Visited, &DILocationReachable](const MDOperand &Op) {
return isDILocationReachable(Visited, DILocationReachable,
Op.get());
}))
return nullptr;
return updateLoopMetadataDebugLocationsImpl(
N, [&DILocationReachable](Metadata *MD) -> Metadata * {
if (isa<DILocation>(MD) || DILocationReachable.count(MD))
return nullptr;
return MD;
});
}
bool llvm::stripDebugInfo(Function &F) {
bool Changed = false;
if (F.hasMetadata(LLVMContext::MD_dbg)) {
Changed = true;
F.setSubprogram(nullptr);
}
DenseMap<MDNode *, MDNode *> LoopIDsMap;
for (BasicBlock &BB : F) {
for (Instruction &I : llvm::make_early_inc_range(BB)) {
if (isa<DbgInfoIntrinsic>(&I)) {
I.eraseFromParent();
Changed = true;
continue;
}
if (I.getDebugLoc()) {
Changed = true;
I.setDebugLoc(DebugLoc());
}
if (auto *LoopID = I.getMetadata(LLVMContext::MD_loop)) {
auto *NewLoopID = LoopIDsMap.lookup(LoopID);
if (!NewLoopID)
NewLoopID = LoopIDsMap[LoopID] = stripDebugLocFromLoopID(LoopID);
if (NewLoopID != LoopID)
I.setMetadata(LLVMContext::MD_loop, NewLoopID);
}
// Strip other attachments that are or use debug info.
if (I.hasMetadataOtherThanDebugLoc()) {
// Heapallocsites point into the DIType system.
I.setMetadata("heapallocsite", nullptr);
// DIAssignID are debug info metadata primitives.
I.setMetadata(LLVMContext::MD_DIAssignID, nullptr);
}
}
}
return Changed;
}
bool llvm::StripDebugInfo(Module &M) {
bool Changed = false;
for (NamedMDNode &NMD : llvm::make_early_inc_range(M.named_metadata())) {
// We're stripping debug info, and without them, coverage information
// doesn't quite make sense.
if (NMD.getName().startswith("llvm.dbg.") ||
NMD.getName() == "llvm.gcov") {
NMD.eraseFromParent();
Changed = true;
}
}
for (Function &F : M)
Changed |= stripDebugInfo(F);
for (auto &GV : M.globals()) {
Changed |= GV.eraseMetadata(LLVMContext::MD_dbg);
}
if (GVMaterializer *Materializer = M.getMaterializer())
Materializer->setStripDebugInfo();
return Changed;
}
namespace {
/// Helper class to downgrade -g metadata to -gline-tables-only metadata.
class DebugTypeInfoRemoval {
DenseMap<Metadata *, Metadata *> Replacements;
public:
/// The (void)() type.
MDNode *EmptySubroutineType;
private:
/// Remember what linkage name we originally had before stripping. If we end
/// up making two subprograms identical who originally had different linkage
/// names, then we need to make one of them distinct, to avoid them getting
/// uniqued. Maps the new node to the old linkage name.
DenseMap<DISubprogram *, StringRef> NewToLinkageName;
// TODO: Remember the distinct subprogram we created for a given linkage name,
// so that we can continue to unique whenever possible. Map <newly created
// node, old linkage name> to the first (possibly distinct) mdsubprogram
// created for that combination. This is not strictly needed for correctness,
// but can cut down on the number of MDNodes and let us diff cleanly with the
// output of -gline-tables-only.
public:
DebugTypeInfoRemoval(LLVMContext &C)
: EmptySubroutineType(DISubroutineType::get(C, DINode::FlagZero, 0,
MDNode::get(C, {}))) {}
Metadata *map(Metadata *M) {
if (!M)
return nullptr;
auto Replacement = Replacements.find(M);
if (Replacement != Replacements.end())
return Replacement->second;
return M;
}
MDNode *mapNode(Metadata *N) { return dyn_cast_or_null<MDNode>(map(N)); }
/// Recursively remap N and all its referenced children. Does a DF post-order
/// traversal, so as to remap bottoms up.
void traverseAndRemap(MDNode *N) { traverse(N); }
private:
// Create a new DISubprogram, to replace the one given.
DISubprogram *getReplacementSubprogram(DISubprogram *MDS) {
auto *FileAndScope = cast_or_null<DIFile>(map(MDS->getFile()));
StringRef LinkageName = MDS->getName().empty() ? MDS->getLinkageName() : "";
DISubprogram *Declaration = nullptr;
auto *Type = cast_or_null<DISubroutineType>(map(MDS->getType()));
DIType *ContainingType =
cast_or_null<DIType>(map(MDS->getContainingType()));
auto *Unit = cast_or_null<DICompileUnit>(map(MDS->getUnit()));
auto Variables = nullptr;
auto TemplateParams = nullptr;
// Make a distinct DISubprogram, for situations that warrent it.
auto distinctMDSubprogram = [&]() {
return DISubprogram::getDistinct(
MDS->getContext(), FileAndScope, MDS->getName(), LinkageName,
FileAndScope, MDS->getLine(), Type, MDS->getScopeLine(),
ContainingType, MDS->getVirtualIndex(), MDS->getThisAdjustment(),
MDS->getFlags(), MDS->getSPFlags(), Unit, TemplateParams, Declaration,
Variables);
};
if (MDS->isDistinct())
return distinctMDSubprogram();
auto *NewMDS = DISubprogram::get(
MDS->getContext(), FileAndScope, MDS->getName(), LinkageName,
FileAndScope, MDS->getLine(), Type, MDS->getScopeLine(), ContainingType,
MDS->getVirtualIndex(), MDS->getThisAdjustment(), MDS->getFlags(),
MDS->getSPFlags(), Unit, TemplateParams, Declaration, Variables);
StringRef OldLinkageName = MDS->getLinkageName();
// See if we need to make a distinct one.
auto OrigLinkage = NewToLinkageName.find(NewMDS);
if (OrigLinkage != NewToLinkageName.end()) {
if (OrigLinkage->second == OldLinkageName)
// We're good.
return NewMDS;
// Otherwise, need to make a distinct one.
// TODO: Query the map to see if we already have one.
return distinctMDSubprogram();
}
NewToLinkageName.insert({NewMDS, MDS->getLinkageName()});
return NewMDS;
}
/// Create a new compile unit, to replace the one given
DICompileUnit *getReplacementCU(DICompileUnit *CU) {
// Drop skeleton CUs.
if (CU->getDWOId())
return nullptr;
auto *File = cast_or_null<DIFile>(map(CU->getFile()));
MDTuple *EnumTypes = nullptr;
MDTuple *RetainedTypes = nullptr;
MDTuple *GlobalVariables = nullptr;
MDTuple *ImportedEntities = nullptr;
return DICompileUnit::getDistinct(
CU->getContext(), CU->getSourceLanguage(), File, CU->getProducer(),
CU->isOptimized(), CU->getFlags(), CU->getRuntimeVersion(),
CU->getSplitDebugFilename(), DICompileUnit::LineTablesOnly, EnumTypes,
RetainedTypes, GlobalVariables, ImportedEntities, CU->getMacros(),
CU->getDWOId(), CU->getSplitDebugInlining(),
CU->getDebugInfoForProfiling(), CU->getNameTableKind(),
CU->getRangesBaseAddress(), CU->getSysRoot(), CU->getSDK());
}
DILocation *getReplacementMDLocation(DILocation *MLD) {
auto *Scope = map(MLD->getScope());
auto *InlinedAt = map(MLD->getInlinedAt());
if (MLD->isDistinct())
return DILocation::getDistinct(MLD->getContext(), MLD->getLine(),
MLD->getColumn(), Scope, InlinedAt);
return DILocation::get(MLD->getContext(), MLD->getLine(), MLD->getColumn(),
Scope, InlinedAt);
}
/// Create a new generic MDNode, to replace the one given
MDNode *getReplacementMDNode(MDNode *N) {
SmallVector<Metadata *, 8> Ops;
Ops.reserve(N->getNumOperands());
for (auto &I : N->operands())
if (I)
Ops.push_back(map(I));
auto *Ret = MDNode::get(N->getContext(), Ops);
return Ret;
}
/// Attempt to re-map N to a newly created node.
void remap(MDNode *N) {
if (Replacements.count(N))
return;
auto doRemap = [&](MDNode *N) -> MDNode * {
if (!N)
return nullptr;
if (auto *MDSub = dyn_cast<DISubprogram>(N)) {
remap(MDSub->getUnit());
return getReplacementSubprogram(MDSub);
}
if (isa<DISubroutineType>(N))
return EmptySubroutineType;
if (auto *CU = dyn_cast<DICompileUnit>(N))
return getReplacementCU(CU);
if (isa<DIFile>(N))
return N;
if (auto *MDLB = dyn_cast<DILexicalBlockBase>(N))
// Remap to our referenced scope (recursively).
return mapNode(MDLB->getScope());
if (auto *MLD = dyn_cast<DILocation>(N))
return getReplacementMDLocation(MLD);
// Otherwise, if we see these, just drop them now. Not strictly necessary,
// but this speeds things up a little.
if (isa<DINode>(N))
return nullptr;
return getReplacementMDNode(N);
};
Replacements[N] = doRemap(N);
}
/// Do the remapping traversal.
void traverse(MDNode *);
};
} // end anonymous namespace
void DebugTypeInfoRemoval::traverse(MDNode *N) {
if (!N || Replacements.count(N))
return;
// To avoid cycles, as well as for efficiency sake, we will sometimes prune
// parts of the graph.
auto prune = [](MDNode *Parent, MDNode *Child) {
if (auto *MDS = dyn_cast<DISubprogram>(Parent))
return Child == MDS->getRetainedNodes().get();
return false;
};
SmallVector<MDNode *, 16> ToVisit;
DenseSet<MDNode *> Opened;
// Visit each node starting at N in post order, and map them.
ToVisit.push_back(N);
while (!ToVisit.empty()) {
auto *N = ToVisit.back();
if (!Opened.insert(N).second) {
// Close it.
remap(N);
ToVisit.pop_back();
continue;
}
for (auto &I : N->operands())
if (auto *MDN = dyn_cast_or_null<MDNode>(I))
if (!Opened.count(MDN) && !Replacements.count(MDN) && !prune(N, MDN) &&
!isa<DICompileUnit>(MDN))
ToVisit.push_back(MDN);
}
}
bool llvm::stripNonLineTableDebugInfo(Module &M) {
bool Changed = false;
// First off, delete the debug intrinsics.
auto RemoveUses = [&](StringRef Name) {
if (auto *DbgVal = M.getFunction(Name)) {
while (!DbgVal->use_empty())
cast<Instruction>(DbgVal->user_back())->eraseFromParent();
DbgVal->eraseFromParent();
Changed = true;
}
};
RemoveUses("llvm.dbg.addr");
RemoveUses("llvm.dbg.declare");
RemoveUses("llvm.dbg.label");
RemoveUses("llvm.dbg.value");
// Delete non-CU debug info named metadata nodes.
for (auto NMI = M.named_metadata_begin(), NME = M.named_metadata_end();
NMI != NME;) {
NamedMDNode *NMD = &*NMI;
++NMI;
// Specifically keep dbg.cu around.
if (NMD->getName() == "llvm.dbg.cu")
continue;
}
// Drop all dbg attachments from global variables.
for (auto &GV : M.globals())
GV.eraseMetadata(LLVMContext::MD_dbg);
DebugTypeInfoRemoval Mapper(M.getContext());
auto remap = [&](MDNode *Node) -> MDNode * {
if (!Node)
return nullptr;
Mapper.traverseAndRemap(Node);
auto *NewNode = Mapper.mapNode(Node);
Changed |= Node != NewNode;
Node = NewNode;
return NewNode;
};
// Rewrite the DebugLocs to be equivalent to what
// -gline-tables-only would have created.
for (auto &F : M) {
if (auto *SP = F.getSubprogram()) {
Mapper.traverseAndRemap(SP);
auto *NewSP = cast<DISubprogram>(Mapper.mapNode(SP));
Changed |= SP != NewSP;
F.setSubprogram(NewSP);
}
for (auto &BB : F) {
for (auto &I : BB) {
auto remapDebugLoc = [&](const DebugLoc &DL) -> DebugLoc {
auto *Scope = DL.getScope();
MDNode *InlinedAt = DL.getInlinedAt();
Scope = remap(Scope);
InlinedAt = remap(InlinedAt);
return DILocation::get(M.getContext(), DL.getLine(), DL.getCol(),
Scope, InlinedAt);
};
if (I.getDebugLoc() != DebugLoc())
I.setDebugLoc(remapDebugLoc(I.getDebugLoc()));
// Remap DILocations in llvm.loop attachments.
updateLoopMetadataDebugLocations(I, [&](Metadata *MD) -> Metadata * {
if (auto *Loc = dyn_cast_or_null<DILocation>(MD))
return remapDebugLoc(Loc).get();
return MD;
});
// Strip heapallocsite attachments, they point into the DIType system.
if (I.hasMetadataOtherThanDebugLoc())
I.setMetadata("heapallocsite", nullptr);
}
}
}
// Create a new llvm.dbg.cu, which is equivalent to the one
// -gline-tables-only would have created.
for (auto &NMD : M.getNamedMDList()) {
SmallVector<MDNode *, 8> Ops;
for (MDNode *Op : NMD.operands())
Ops.push_back(remap(Op));
if (!Changed)
continue;
NMD.clearOperands();
for (auto *Op : Ops)
if (Op)
NMD.addOperand(Op);
}
return Changed;
}
unsigned llvm::getDebugMetadataVersionFromModule(const Module &M) {
if (auto *Val = mdconst::dyn_extract_or_null<ConstantInt>(
M.getModuleFlag("Debug Info Version")))
return Val->getZExtValue();
return 0;
}
void Instruction::applyMergedLocation(const DILocation *LocA,
const DILocation *LocB) {
setDebugLoc(DILocation::getMergedLocation(LocA, LocB));
}
void Instruction::mergeDIAssignID(
ArrayRef<const Instruction *> SourceInstructions) {
// Replace all uses (and attachments) of all the DIAssignIDs
// on SourceInstructions with a single merged value.
assert(getFunction() && "Uninserted instruction merged");
// Collect up the DIAssignID tags.
SmallVector<DIAssignID *, 4> IDs;
for (const Instruction *I : SourceInstructions) {
if (auto *MD = I->getMetadata(LLVMContext::MD_DIAssignID))
IDs.push_back(cast<DIAssignID>(MD));
assert(getFunction() == I->getFunction() &&
"Merging with instruction from another function not allowed");
}
// Add this instruction's DIAssignID too, if it has one.
if (auto *MD = getMetadata(LLVMContext::MD_DIAssignID))
IDs.push_back(cast<DIAssignID>(MD));
if (IDs.empty())
return; // No DIAssignID tags to process.
DIAssignID *MergeID = IDs[0];
for (auto It = std::next(IDs.begin()), End = IDs.end(); It != End; ++It) {
if (*It != MergeID)
at::RAUW(*It, MergeID);
}
setMetadata(LLVMContext::MD_DIAssignID, MergeID);
}
void Instruction::updateLocationAfterHoist() { dropLocation(); }
void Instruction::dropLocation() {
const DebugLoc &DL = getDebugLoc();
if (!DL)
return;
// If this isn't a call, drop the location to allow a location from a
// preceding instruction to propagate.
bool MayLowerToCall = false;
if (isa<CallBase>(this)) {
auto *II = dyn_cast<IntrinsicInst>(this);
MayLowerToCall =
!II || IntrinsicInst::mayLowerToFunctionCall(II->getIntrinsicID());
}
if (!MayLowerToCall) {
setDebugLoc(DebugLoc());
return;
}
// Set a line 0 location for calls to preserve scope information in case
// inlining occurs.
DISubprogram *SP = getFunction()->getSubprogram();
if (SP)
// If a function scope is available, set it on the line 0 location. When
// hoisting a call to a predecessor block, using the function scope avoids
// making it look like the callee was reached earlier than it should be.
setDebugLoc(DILocation::get(getContext(), 0, 0, SP));
else
// The parent function has no scope. Go ahead and drop the location. If
// the parent function is inlined, and the callee has a subprogram, the
// inliner will attach a location to the call.
//
// One alternative is to set a line 0 location with the existing scope and
// inlinedAt info. The location might be sensitive to when inlining occurs.
setDebugLoc(DebugLoc());
}
//===----------------------------------------------------------------------===//
// LLVM C API implementations.
//===----------------------------------------------------------------------===//
static unsigned map_from_llvmDWARFsourcelanguage(LLVMDWARFSourceLanguage lang) {
switch (lang) {
#define HANDLE_DW_LANG(ID, NAME, LOWER_BOUND, VERSION, VENDOR) \
case LLVMDWARFSourceLanguage##NAME: \
return ID;
#include "llvm/BinaryFormat/Dwarf.def"
#undef HANDLE_DW_LANG
}
llvm_unreachable("Unhandled Tag");
}
template <typename DIT> DIT *unwrapDI(LLVMMetadataRef Ref) {
return (DIT *)(Ref ? unwrap<MDNode>(Ref) : nullptr);
}
static DINode::DIFlags map_from_llvmDIFlags(LLVMDIFlags Flags) {
return static_cast<DINode::DIFlags>(Flags);
}
static LLVMDIFlags map_to_llvmDIFlags(DINode::DIFlags Flags) {
return static_cast<LLVMDIFlags>(Flags);
}
static DISubprogram::DISPFlags
pack_into_DISPFlags(bool IsLocalToUnit, bool IsDefinition, bool IsOptimized) {
return DISubprogram::toSPFlags(IsLocalToUnit, IsDefinition, IsOptimized);
}
unsigned LLVMDebugMetadataVersion() {
return DEBUG_METADATA_VERSION;
}
LLVMDIBuilderRef LLVMCreateDIBuilderDisallowUnresolved(LLVMModuleRef M) {
return wrap(new DIBuilder(*unwrap(M), false));
}
LLVMDIBuilderRef LLVMCreateDIBuilder(LLVMModuleRef M) {
return wrap(new DIBuilder(*unwrap(M)));
}
unsigned LLVMGetModuleDebugMetadataVersion(LLVMModuleRef M) {
return getDebugMetadataVersionFromModule(*unwrap(M));
}
LLVMBool LLVMStripModuleDebugInfo(LLVMModuleRef M) {
return StripDebugInfo(*unwrap(M));
}
void LLVMDisposeDIBuilder(LLVMDIBuilderRef Builder) {
delete unwrap(Builder);
}
void LLVMDIBuilderFinalize(LLVMDIBuilderRef Builder) {
unwrap(Builder)->finalize();
}
void LLVMDIBuilderFinalizeSubprogram(LLVMDIBuilderRef Builder,
LLVMMetadataRef subprogram) {
unwrap(Builder)->finalizeSubprogram(unwrapDI<DISubprogram>(subprogram));
}
LLVMMetadataRef LLVMDIBuilderCreateCompileUnit(
LLVMDIBuilderRef Builder, LLVMDWARFSourceLanguage Lang,
LLVMMetadataRef FileRef, const char *Producer, size_t ProducerLen,
LLVMBool isOptimized, const char *Flags, size_t FlagsLen,
unsigned RuntimeVer, const char *SplitName, size_t SplitNameLen,
LLVMDWARFEmissionKind Kind, unsigned DWOId, LLVMBool SplitDebugInlining,
LLVMBool DebugInfoForProfiling, const char *SysRoot, size_t SysRootLen,
const char *SDK, size_t SDKLen) {
auto File = unwrapDI<DIFile>(FileRef);
return wrap(unwrap(Builder)->createCompileUnit(
map_from_llvmDWARFsourcelanguage(Lang), File,
StringRef(Producer, ProducerLen), isOptimized, StringRef(Flags, FlagsLen),
RuntimeVer, StringRef(SplitName, SplitNameLen),
static_cast<DICompileUnit::DebugEmissionKind>(Kind), DWOId,
SplitDebugInlining, DebugInfoForProfiling,
DICompileUnit::DebugNameTableKind::Default, false,
StringRef(SysRoot, SysRootLen), StringRef(SDK, SDKLen)));
}
LLVMMetadataRef
LLVMDIBuilderCreateFile(LLVMDIBuilderRef Builder, const char *Filename,
size_t FilenameLen, const char *Directory,
size_t DirectoryLen) {
return wrap(unwrap(Builder)->createFile(StringRef(Filename, FilenameLen),
StringRef(Directory, DirectoryLen)));
}
LLVMMetadataRef
LLVMDIBuilderCreateModule(LLVMDIBuilderRef Builder, LLVMMetadataRef ParentScope,
const char *Name, size_t NameLen,
const char *ConfigMacros, size_t ConfigMacrosLen,
const char *IncludePath, size_t IncludePathLen,
const char *APINotesFile, size_t APINotesFileLen) {
return wrap(unwrap(Builder)->createModule(
unwrapDI<DIScope>(ParentScope), StringRef(Name, NameLen),
StringRef(ConfigMacros, ConfigMacrosLen),
StringRef(IncludePath, IncludePathLen),
StringRef(APINotesFile, APINotesFileLen)));
}
LLVMMetadataRef LLVMDIBuilderCreateNameSpace(LLVMDIBuilderRef Builder,
LLVMMetadataRef ParentScope,
const char *Name, size_t NameLen,
LLVMBool ExportSymbols) {
return wrap(unwrap(Builder)->createNameSpace(
unwrapDI<DIScope>(ParentScope), StringRef(Name, NameLen), ExportSymbols));
}
LLVMMetadataRef LLVMDIBuilderCreateFunction(
LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
size_t NameLen, const char *LinkageName, size_t LinkageNameLen,
LLVMMetadataRef File, unsigned LineNo, LLVMMetadataRef Ty,
LLVMBool IsLocalToUnit, LLVMBool IsDefinition,
unsigned ScopeLine, LLVMDIFlags Flags, LLVMBool IsOptimized) {
return wrap(unwrap(Builder)->createFunction(
unwrapDI<DIScope>(Scope), {Name, NameLen}, {LinkageName, LinkageNameLen},
unwrapDI<DIFile>(File), LineNo, unwrapDI<DISubroutineType>(Ty), ScopeLine,
map_from_llvmDIFlags(Flags),
pack_into_DISPFlags(IsLocalToUnit, IsDefinition, IsOptimized), nullptr,
nullptr, nullptr));
}
LLVMMetadataRef LLVMDIBuilderCreateLexicalBlock(
LLVMDIBuilderRef Builder, LLVMMetadataRef Scope,
LLVMMetadataRef File, unsigned Line, unsigned Col) {
return wrap(unwrap(Builder)->createLexicalBlock(unwrapDI<DIScope>(Scope),
unwrapDI<DIFile>(File),
Line, Col));
}
LLVMMetadataRef
LLVMDIBuilderCreateLexicalBlockFile(LLVMDIBuilderRef Builder,
LLVMMetadataRef Scope,
LLVMMetadataRef File,
unsigned Discriminator) {
return wrap(unwrap(Builder)->createLexicalBlockFile(unwrapDI<DIScope>(Scope),
unwrapDI<DIFile>(File),
Discriminator));
}
LLVMMetadataRef
LLVMDIBuilderCreateImportedModuleFromNamespace(LLVMDIBuilderRef Builder,
LLVMMetadataRef Scope,
LLVMMetadataRef NS,
LLVMMetadataRef File,
unsigned Line) {
return wrap(unwrap(Builder)->createImportedModule(unwrapDI<DIScope>(Scope),
unwrapDI<DINamespace>(NS),
unwrapDI<DIFile>(File),
Line));
}
LLVMMetadataRef LLVMDIBuilderCreateImportedModuleFromAlias(
LLVMDIBuilderRef Builder, LLVMMetadataRef Scope,
LLVMMetadataRef ImportedEntity, LLVMMetadataRef File, unsigned Line,
LLVMMetadataRef *Elements, unsigned NumElements) {
auto Elts =
(NumElements > 0)
? unwrap(Builder)->getOrCreateArray({unwrap(Elements), NumElements})
: nullptr;
return wrap(unwrap(Builder)->createImportedModule(
unwrapDI<DIScope>(Scope), unwrapDI<DIImportedEntity>(ImportedEntity),
unwrapDI<DIFile>(File), Line, Elts));
}
LLVMMetadataRef LLVMDIBuilderCreateImportedModuleFromModule(
LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, LLVMMetadataRef M,
LLVMMetadataRef File, unsigned Line, LLVMMetadataRef *Elements,
unsigned NumElements) {
auto Elts =
(NumElements > 0)
? unwrap(Builder)->getOrCreateArray({unwrap(Elements), NumElements})
: nullptr;
return wrap(unwrap(Builder)->createImportedModule(
unwrapDI<DIScope>(Scope), unwrapDI<DIModule>(M), unwrapDI<DIFile>(File),
Line, Elts));
}
LLVMMetadataRef LLVMDIBuilderCreateImportedDeclaration(
LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, LLVMMetadataRef Decl,
LLVMMetadataRef File, unsigned Line, const char *Name, size_t NameLen,
LLVMMetadataRef *Elements, unsigned NumElements) {
auto Elts =
(NumElements > 0)
? unwrap(Builder)->getOrCreateArray({unwrap(Elements), NumElements})
: nullptr;
return wrap(unwrap(Builder)->createImportedDeclaration(
unwrapDI<DIScope>(Scope), unwrapDI<DINode>(Decl), unwrapDI<DIFile>(File),
Line, {Name, NameLen}, Elts));
}
LLVMMetadataRef
LLVMDIBuilderCreateDebugLocation(LLVMContextRef Ctx, unsigned Line,
unsigned Column, LLVMMetadataRef Scope,
LLVMMetadataRef InlinedAt) {
return wrap(DILocation::get(*unwrap(Ctx), Line, Column, unwrap(Scope),
unwrap(InlinedAt)));
}
unsigned LLVMDILocationGetLine(LLVMMetadataRef Location) {
return unwrapDI<DILocation>(Location)->getLine();
}
unsigned LLVMDILocationGetColumn(LLVMMetadataRef Location) {
return unwrapDI<DILocation>(Location)->getColumn();
}
LLVMMetadataRef LLVMDILocationGetScope(LLVMMetadataRef Location) {
return wrap(unwrapDI<DILocation>(Location)->getScope());
}
LLVMMetadataRef LLVMDILocationGetInlinedAt(LLVMMetadataRef Location) {
return wrap(unwrapDI<DILocation>(Location)->getInlinedAt());
}
LLVMMetadataRef LLVMDIScopeGetFile(LLVMMetadataRef Scope) {
return wrap(unwrapDI<DIScope>(Scope)->getFile());
}
const char *LLVMDIFileGetDirectory(LLVMMetadataRef File, unsigned *Len) {
auto Dir = unwrapDI<DIFile>(File)->getDirectory();
*Len = Dir.size();
return Dir.data();
}
const char *LLVMDIFileGetFilename(LLVMMetadataRef File, unsigned *Len) {
auto Name = unwrapDI<DIFile>(File)->getFilename();
*Len = Name.size();
return Name.data();
}
const char *LLVMDIFileGetSource(LLVMMetadataRef File, unsigned *Len) {
if (auto Src = unwrapDI<DIFile>(File)->getSource()) {
*Len = Src->size();
return Src->data();
}
*Len = 0;
return "";
}
LLVMMetadataRef LLVMDIBuilderCreateMacro(LLVMDIBuilderRef Builder,
LLVMMetadataRef ParentMacroFile,
unsigned Line,
LLVMDWARFMacinfoRecordType RecordType,
const char *Name, size_t NameLen,
const char *Value, size_t ValueLen) {
return wrap(
unwrap(Builder)->createMacro(unwrapDI<DIMacroFile>(ParentMacroFile), Line,
static_cast<MacinfoRecordType>(RecordType),
{Name, NameLen}, {Value, ValueLen}));
}
LLVMMetadataRef
LLVMDIBuilderCreateTempMacroFile(LLVMDIBuilderRef Builder,
LLVMMetadataRef ParentMacroFile, unsigned Line,
LLVMMetadataRef File) {
return wrap(unwrap(Builder)->createTempMacroFile(
unwrapDI<DIMacroFile>(ParentMacroFile), Line, unwrapDI<DIFile>(File)));
}
LLVMMetadataRef LLVMDIBuilderCreateEnumerator(LLVMDIBuilderRef Builder,
const char *Name, size_t NameLen,
int64_t Value,
LLVMBool IsUnsigned) {
return wrap(unwrap(Builder)->createEnumerator({Name, NameLen}, Value,
IsUnsigned != 0));
}
LLVMMetadataRef LLVMDIBuilderCreateEnumerationType(
LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
size_t NameLen, LLVMMetadataRef File, unsigned LineNumber,
uint64_t SizeInBits, uint32_t AlignInBits, LLVMMetadataRef *Elements,
unsigned NumElements, LLVMMetadataRef ClassTy) {
auto Elts = unwrap(Builder)->getOrCreateArray({unwrap(Elements),
NumElements});
return wrap(unwrap(Builder)->createEnumerationType(
unwrapDI<DIScope>(Scope), {Name, NameLen}, unwrapDI<DIFile>(File),
LineNumber, SizeInBits, AlignInBits, Elts, unwrapDI<DIType>(ClassTy)));
}
LLVMMetadataRef LLVMDIBuilderCreateUnionType(
LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
size_t NameLen, LLVMMetadataRef File, unsigned LineNumber,
uint64_t SizeInBits, uint32_t AlignInBits, LLVMDIFlags Flags,
LLVMMetadataRef *Elements, unsigned NumElements, unsigned RunTimeLang,
const char *UniqueId, size_t UniqueIdLen) {
auto Elts = unwrap(Builder)->getOrCreateArray({unwrap(Elements),
NumElements});
return wrap(unwrap(Builder)->createUnionType(
unwrapDI<DIScope>(Scope), {Name, NameLen}, unwrapDI<DIFile>(File),
LineNumber, SizeInBits, AlignInBits, map_from_llvmDIFlags(Flags),
Elts, RunTimeLang, {UniqueId, UniqueIdLen}));
}
LLVMMetadataRef
LLVMDIBuilderCreateArrayType(LLVMDIBuilderRef Builder, uint64_t Size,
uint32_t AlignInBits, LLVMMetadataRef Ty,
LLVMMetadataRef *Subscripts,
unsigned NumSubscripts) {
auto Subs = unwrap(Builder)->getOrCreateArray({unwrap(Subscripts),
NumSubscripts});
return wrap(unwrap(Builder)->createArrayType(Size, AlignInBits,
unwrapDI<DIType>(Ty), Subs));
}
LLVMMetadataRef
LLVMDIBuilderCreateVectorType(LLVMDIBuilderRef Builder, uint64_t Size,
uint32_t AlignInBits, LLVMMetadataRef Ty,
LLVMMetadataRef *Subscripts,
unsigned NumSubscripts) {
auto Subs = unwrap(Builder)->getOrCreateArray({unwrap(Subscripts),
NumSubscripts});
return wrap(unwrap(Builder)->createVectorType(Size, AlignInBits,
unwrapDI<DIType>(Ty), Subs));
}
LLVMMetadataRef
LLVMDIBuilderCreateBasicType(LLVMDIBuilderRef Builder, const char *Name,
size_t NameLen, uint64_t SizeInBits,
LLVMDWARFTypeEncoding Encoding,
LLVMDIFlags Flags) {
return wrap(unwrap(Builder)->createBasicType({Name, NameLen},
SizeInBits, Encoding,
map_from_llvmDIFlags(Flags)));
}
LLVMMetadataRef LLVMDIBuilderCreatePointerType(
LLVMDIBuilderRef Builder, LLVMMetadataRef PointeeTy,
uint64_t SizeInBits, uint32_t AlignInBits, unsigned AddressSpace,
const char *Name, size_t NameLen) {
return wrap(unwrap(Builder)->createPointerType(unwrapDI<DIType>(PointeeTy),
SizeInBits, AlignInBits,
AddressSpace, {Name, NameLen}));
}
LLVMMetadataRef LLVMDIBuilderCreateStructType(
LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
size_t NameLen, LLVMMetadataRef File, unsigned LineNumber,
uint64_t SizeInBits, uint32_t AlignInBits, LLVMDIFlags Flags,
LLVMMetadataRef DerivedFrom, LLVMMetadataRef *Elements,
unsigned NumElements, unsigned RunTimeLang, LLVMMetadataRef VTableHolder,
const char *UniqueId, size_t UniqueIdLen) {
auto Elts = unwrap(Builder)->getOrCreateArray({unwrap(Elements),
NumElements});
return wrap(unwrap(Builder)->createStructType(
unwrapDI<DIScope>(Scope), {Name, NameLen}, unwrapDI<DIFile>(File),
LineNumber, SizeInBits, AlignInBits, map_from_llvmDIFlags(Flags),
unwrapDI<DIType>(DerivedFrom), Elts, RunTimeLang,
unwrapDI<DIType>(VTableHolder), {UniqueId, UniqueIdLen}));
}
LLVMMetadataRef LLVMDIBuilderCreateMemberType(
LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
size_t NameLen, LLVMMetadataRef File, unsigned LineNo, uint64_t SizeInBits,
uint32_t AlignInBits, uint64_t OffsetInBits, LLVMDIFlags Flags,
LLVMMetadataRef Ty) {
return wrap(unwrap(Builder)->createMemberType(unwrapDI<DIScope>(Scope),
{Name, NameLen}, unwrapDI<DIFile>(File), LineNo, SizeInBits, AlignInBits,
OffsetInBits, map_from_llvmDIFlags(Flags), unwrapDI<DIType>(Ty)));
}
LLVMMetadataRef
LLVMDIBuilderCreateUnspecifiedType(LLVMDIBuilderRef Builder, const char *Name,
size_t NameLen) {
return wrap(unwrap(Builder)->createUnspecifiedType({Name, NameLen}));
}
LLVMMetadataRef
LLVMDIBuilderCreateStaticMemberType(
LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
size_t NameLen, LLVMMetadataRef File, unsigned LineNumber,
LLVMMetadataRef Type, LLVMDIFlags Flags, LLVMValueRef ConstantVal,
uint32_t AlignInBits) {
return wrap(unwrap(Builder)->createStaticMemberType(
unwrapDI<DIScope>(Scope), {Name, NameLen},
unwrapDI<DIFile>(File), LineNumber, unwrapDI<DIType>(Type),
map_from_llvmDIFlags(Flags), unwrap<Constant>(ConstantVal),
AlignInBits));
}
LLVMMetadataRef
LLVMDIBuilderCreateObjCIVar(LLVMDIBuilderRef Builder,
const char *Name, size_t NameLen,
LLVMMetadataRef File, unsigned LineNo,
uint64_t SizeInBits, uint32_t AlignInBits,
uint64_t OffsetInBits, LLVMDIFlags Flags,
LLVMMetadataRef Ty, LLVMMetadataRef PropertyNode) {
return wrap(unwrap(Builder)->createObjCIVar(
{Name, NameLen}, unwrapDI<DIFile>(File), LineNo,
SizeInBits, AlignInBits, OffsetInBits,
map_from_llvmDIFlags(Flags), unwrapDI<DIType>(Ty),
unwrapDI<MDNode>(PropertyNode)));
}
LLVMMetadataRef
LLVMDIBuilderCreateObjCProperty(LLVMDIBuilderRef Builder,
const char *Name, size_t NameLen,
LLVMMetadataRef File, unsigned LineNo,
const char *GetterName, size_t GetterNameLen,
const char *SetterName, size_t SetterNameLen,
unsigned PropertyAttributes,
LLVMMetadataRef Ty) {
return wrap(unwrap(Builder)->createObjCProperty(
{Name, NameLen}, unwrapDI<DIFile>(File), LineNo,
{GetterName, GetterNameLen}, {SetterName, SetterNameLen},
PropertyAttributes, unwrapDI<DIType>(Ty)));
}
LLVMMetadataRef
LLVMDIBuilderCreateObjectPointerType(LLVMDIBuilderRef Builder,
LLVMMetadataRef Type) {
return wrap(unwrap(Builder)->createObjectPointerType(unwrapDI<DIType>(Type)));
}
LLVMMetadataRef
LLVMDIBuilderCreateTypedef(LLVMDIBuilderRef Builder, LLVMMetadataRef Type,
const char *Name, size_t NameLen,
LLVMMetadataRef File, unsigned LineNo,
LLVMMetadataRef Scope, uint32_t AlignInBits) {
return wrap(unwrap(Builder)->createTypedef(
unwrapDI<DIType>(Type), {Name, NameLen}, unwrapDI<DIFile>(File), LineNo,
unwrapDI<DIScope>(Scope), AlignInBits));
}
LLVMMetadataRef
LLVMDIBuilderCreateInheritance(LLVMDIBuilderRef Builder,
LLVMMetadataRef Ty, LLVMMetadataRef BaseTy,
uint64_t BaseOffset, uint32_t VBPtrOffset,
LLVMDIFlags Flags) {
return wrap(unwrap(Builder)->createInheritance(
unwrapDI<DIType>(Ty), unwrapDI<DIType>(BaseTy),
BaseOffset, VBPtrOffset, map_from_llvmDIFlags(Flags)));
}
LLVMMetadataRef
LLVMDIBuilderCreateForwardDecl(
LLVMDIBuilderRef Builder, unsigned Tag, const char *Name,
size_t NameLen, LLVMMetadataRef Scope, LLVMMetadataRef File, unsigned Line,
unsigned RuntimeLang, uint64_t SizeInBits, uint32_t AlignInBits,
const char *UniqueIdentifier, size_t UniqueIdentifierLen) {
return wrap(unwrap(Builder)->createForwardDecl(
Tag, {Name, NameLen}, unwrapDI<DIScope>(Scope),
unwrapDI<DIFile>(File), Line, RuntimeLang, SizeInBits,
AlignInBits, {UniqueIdentifier, UniqueIdentifierLen}));
}
LLVMMetadataRef
LLVMDIBuilderCreateReplaceableCompositeType(
LLVMDIBuilderRef Builder, unsigned Tag, const char *Name,
size_t NameLen, LLVMMetadataRef Scope, LLVMMetadataRef File, unsigned Line,
unsigned RuntimeLang, uint64_t SizeInBits, uint32_t AlignInBits,
LLVMDIFlags Flags, const char *UniqueIdentifier,
size_t UniqueIdentifierLen) {
return wrap(unwrap(Builder)->createReplaceableCompositeType(
Tag, {Name, NameLen}, unwrapDI<DIScope>(Scope),
unwrapDI<DIFile>(File), Line, RuntimeLang, SizeInBits,
AlignInBits, map_from_llvmDIFlags(Flags),
{UniqueIdentifier, UniqueIdentifierLen}));
}
LLVMMetadataRef
LLVMDIBuilderCreateQualifiedType(LLVMDIBuilderRef Builder, unsigned Tag,
LLVMMetadataRef Type) {
return wrap(unwrap(Builder)->createQualifiedType(Tag,
unwrapDI<DIType>(Type)));
}
LLVMMetadataRef
LLVMDIBuilderCreateReferenceType(LLVMDIBuilderRef Builder, unsigned Tag,
LLVMMetadataRef Type) {
return wrap(unwrap(Builder)->createReferenceType(Tag,
unwrapDI<DIType>(Type)));
}
LLVMMetadataRef
LLVMDIBuilderCreateNullPtrType(LLVMDIBuilderRef Builder) {
return wrap(unwrap(Builder)->createNullPtrType());
}
LLVMMetadataRef
LLVMDIBuilderCreateMemberPointerType(LLVMDIBuilderRef Builder,
LLVMMetadataRef PointeeType,
LLVMMetadataRef ClassType,
uint64_t SizeInBits,
uint32_t AlignInBits,
LLVMDIFlags Flags) {
return wrap(unwrap(Builder)->createMemberPointerType(
unwrapDI<DIType>(PointeeType),
unwrapDI<DIType>(ClassType), AlignInBits, SizeInBits,
map_from_llvmDIFlags(Flags)));
}
LLVMMetadataRef
LLVMDIBuilderCreateBitFieldMemberType(LLVMDIBuilderRef Builder,
LLVMMetadataRef Scope,
const char *Name, size_t NameLen,
LLVMMetadataRef File, unsigned LineNumber,
uint64_t SizeInBits,
uint64_t OffsetInBits,
uint64_t StorageOffsetInBits,
LLVMDIFlags Flags, LLVMMetadataRef Type) {
return wrap(unwrap(Builder)->createBitFieldMemberType(
unwrapDI<DIScope>(Scope), {Name, NameLen},
unwrapDI<DIFile>(File), LineNumber,
SizeInBits, OffsetInBits, StorageOffsetInBits,
map_from_llvmDIFlags(Flags), unwrapDI<DIType>(Type)));
}
LLVMMetadataRef LLVMDIBuilderCreateClassType(LLVMDIBuilderRef Builder,
LLVMMetadataRef Scope, const char *Name, size_t NameLen,
LLVMMetadataRef File, unsigned LineNumber, uint64_t SizeInBits,
uint32_t AlignInBits, uint64_t OffsetInBits, LLVMDIFlags Flags,
LLVMMetadataRef DerivedFrom,
LLVMMetadataRef *Elements, unsigned NumElements,
LLVMMetadataRef VTableHolder, LLVMMetadataRef TemplateParamsNode,
const char *UniqueIdentifier, size_t UniqueIdentifierLen) {
auto Elts = unwrap(Builder)->getOrCreateArray({unwrap(Elements),
NumElements});
return wrap(unwrap(Builder)->createClassType(
unwrapDI<DIScope>(Scope), {Name, NameLen},
unwrapDI<DIFile>(File), LineNumber,
SizeInBits, AlignInBits, OffsetInBits,
map_from_llvmDIFlags(Flags), unwrapDI<DIType>(DerivedFrom),
Elts, unwrapDI<DIType>(VTableHolder),
unwrapDI<MDNode>(TemplateParamsNode),
{UniqueIdentifier, UniqueIdentifierLen}));
}
LLVMMetadataRef
LLVMDIBuilderCreateArtificialType(LLVMDIBuilderRef Builder,
LLVMMetadataRef Type) {
return wrap(unwrap(Builder)->createArtificialType(unwrapDI<DIType>(Type)));
}
const char *LLVMDITypeGetName(LLVMMetadataRef DType, size_t *Length) {
StringRef Str = unwrap<DIType>(DType)->getName();
*Length = Str.size();
return Str.data();
}
uint64_t LLVMDITypeGetSizeInBits(LLVMMetadataRef DType) {
return unwrapDI<DIType>(DType)->getSizeInBits();
}
uint64_t LLVMDITypeGetOffsetInBits(LLVMMetadataRef DType) {
return unwrapDI<DIType>(DType)->getOffsetInBits();
}
uint32_t LLVMDITypeGetAlignInBits(LLVMMetadataRef DType) {
return unwrapDI<DIType>(DType)->getAlignInBits();
}
unsigned LLVMDITypeGetLine(LLVMMetadataRef DType) {
return unwrapDI<DIType>(DType)->getLine();
}
LLVMDIFlags LLVMDITypeGetFlags(LLVMMetadataRef DType) {
return map_to_llvmDIFlags(unwrapDI<DIType>(DType)->getFlags());
}
LLVMMetadataRef LLVMDIBuilderGetOrCreateTypeArray(LLVMDIBuilderRef Builder,
LLVMMetadataRef *Types,
size_t Length) {
return wrap(
unwrap(Builder)->getOrCreateTypeArray({unwrap(Types), Length}).get());
}
LLVMMetadataRef
LLVMDIBuilderCreateSubroutineType(LLVMDIBuilderRef Builder,
LLVMMetadataRef File,
LLVMMetadataRef *ParameterTypes,
unsigned NumParameterTypes,
LLVMDIFlags Flags) {
auto Elts = unwrap(Builder)->getOrCreateTypeArray({unwrap(ParameterTypes),
NumParameterTypes});
return wrap(unwrap(Builder)->createSubroutineType(
Elts, map_from_llvmDIFlags(Flags)));
}
LLVMMetadataRef LLVMDIBuilderCreateExpression(LLVMDIBuilderRef Builder,
uint64_t *Addr, size_t Length) {
return wrap(
unwrap(Builder)->createExpression(ArrayRef<uint64_t>(Addr, Length)));
}
LLVMMetadataRef
LLVMDIBuilderCreateConstantValueExpression(LLVMDIBuilderRef Builder,
uint64_t Value) {
return wrap(unwrap(Builder)->createConstantValueExpression(Value));
}
LLVMMetadataRef LLVMDIBuilderCreateGlobalVariableExpression(
LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
size_t NameLen, const char *Linkage, size_t LinkLen, LLVMMetadataRef File,
unsigned LineNo, LLVMMetadataRef Ty, LLVMBool LocalToUnit,
LLVMMetadataRef Expr, LLVMMetadataRef Decl, uint32_t AlignInBits) {
return wrap(unwrap(Builder)->createGlobalVariableExpression(
unwrapDI<DIScope>(Scope), {Name, NameLen}, {Linkage, LinkLen},
unwrapDI<DIFile>(File), LineNo, unwrapDI<DIType>(Ty), LocalToUnit,
true, unwrap<DIExpression>(Expr), unwrapDI<MDNode>(Decl),
nullptr, AlignInBits));
}
LLVMMetadataRef LLVMDIGlobalVariableExpressionGetVariable(LLVMMetadataRef GVE) {
return wrap(unwrapDI<DIGlobalVariableExpression>(GVE)->getVariable());
}
LLVMMetadataRef LLVMDIGlobalVariableExpressionGetExpression(
LLVMMetadataRef GVE) {
return wrap(unwrapDI<DIGlobalVariableExpression>(GVE)->getExpression());
}
LLVMMetadataRef LLVMDIVariableGetFile(LLVMMetadataRef Var) {
return wrap(unwrapDI<DIVariable>(Var)->getFile());
}
LLVMMetadataRef LLVMDIVariableGetScope(LLVMMetadataRef Var) {
return wrap(unwrapDI<DIVariable>(Var)->getScope());
}
unsigned LLVMDIVariableGetLine(LLVMMetadataRef Var) {
return unwrapDI<DIVariable>(Var)->getLine();
}
LLVMMetadataRef LLVMTemporaryMDNode(LLVMContextRef Ctx, LLVMMetadataRef *Data,
size_t Count) {
return wrap(
MDTuple::getTemporary(*unwrap(Ctx), {unwrap(Data), Count}).release());
}
void LLVMDisposeTemporaryMDNode(LLVMMetadataRef TempNode) {
MDNode::deleteTemporary(unwrapDI<MDNode>(TempNode));
}
void LLVMMetadataReplaceAllUsesWith(LLVMMetadataRef TargetMetadata,
LLVMMetadataRef Replacement) {
auto *Node = unwrapDI<MDNode>(TargetMetadata);
Node->replaceAllUsesWith(unwrap(Replacement));
MDNode::deleteTemporary(Node);
}
LLVMMetadataRef LLVMDIBuilderCreateTempGlobalVariableFwdDecl(
LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
size_t NameLen, const char *Linkage, size_t LnkLen, LLVMMetadataRef File,
unsigned LineNo, LLVMMetadataRef Ty, LLVMBool LocalToUnit,
LLVMMetadataRef Decl, uint32_t AlignInBits) {
return wrap(unwrap(Builder)->createTempGlobalVariableFwdDecl(
unwrapDI<DIScope>(Scope), {Name, NameLen}, {Linkage, LnkLen},
unwrapDI<DIFile>(File), LineNo, unwrapDI<DIType>(Ty), LocalToUnit,
unwrapDI<MDNode>(Decl), nullptr, AlignInBits));
}
LLVMValueRef
LLVMDIBuilderInsertDeclareBefore(LLVMDIBuilderRef Builder, LLVMValueRef Storage,
LLVMMetadataRef VarInfo, LLVMMetadataRef Expr,
LLVMMetadataRef DL, LLVMValueRef Instr) {
return wrap(unwrap(Builder)->insertDeclare(
unwrap(Storage), unwrap<DILocalVariable>(VarInfo),
unwrap<DIExpression>(Expr), unwrap<DILocation>(DL),
unwrap<Instruction>(Instr)));
}
LLVMValueRef LLVMDIBuilderInsertDeclareAtEnd(
LLVMDIBuilderRef Builder, LLVMValueRef Storage, LLVMMetadataRef VarInfo,
LLVMMetadataRef Expr, LLVMMetadataRef DL, LLVMBasicBlockRef Block) {
return wrap(unwrap(Builder)->insertDeclare(
unwrap(Storage), unwrap<DILocalVariable>(VarInfo),
unwrap<DIExpression>(Expr), unwrap<DILocation>(DL),
unwrap(Block)));
}
LLVMValueRef LLVMDIBuilderInsertDbgValueBefore(LLVMDIBuilderRef Builder,
LLVMValueRef Val,
LLVMMetadataRef VarInfo,
LLVMMetadataRef Expr,
LLVMMetadataRef DebugLoc,
LLVMValueRef Instr) {
return wrap(unwrap(Builder)->insertDbgValueIntrinsic(
unwrap(Val), unwrap<DILocalVariable>(VarInfo),
unwrap<DIExpression>(Expr), unwrap<DILocation>(DebugLoc),
unwrap<Instruction>(Instr)));
}
LLVMValueRef LLVMDIBuilderInsertDbgValueAtEnd(LLVMDIBuilderRef Builder,
LLVMValueRef Val,
LLVMMetadataRef VarInfo,
LLVMMetadataRef Expr,
LLVMMetadataRef DebugLoc,
LLVMBasicBlockRef Block) {
return wrap(unwrap(Builder)->insertDbgValueIntrinsic(
unwrap(Val), unwrap<DILocalVariable>(VarInfo),
unwrap<DIExpression>(Expr), unwrap<DILocation>(DebugLoc),
unwrap(Block)));
}
LLVMMetadataRef LLVMDIBuilderCreateAutoVariable(
LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
size_t NameLen, LLVMMetadataRef File, unsigned LineNo, LLVMMetadataRef Ty,
LLVMBool AlwaysPreserve, LLVMDIFlags Flags, uint32_t AlignInBits) {
return wrap(unwrap(Builder)->createAutoVariable(
unwrap<DIScope>(Scope), {Name, NameLen}, unwrap<DIFile>(File),
LineNo, unwrap<DIType>(Ty), AlwaysPreserve,
map_from_llvmDIFlags(Flags), AlignInBits));
}
LLVMMetadataRef LLVMDIBuilderCreateParameterVariable(
LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
size_t NameLen, unsigned ArgNo, LLVMMetadataRef File, unsigned LineNo,
LLVMMetadataRef Ty, LLVMBool AlwaysPreserve, LLVMDIFlags Flags) {
return wrap(unwrap(Builder)->createParameterVariable(
unwrap<DIScope>(Scope), {Name, NameLen}, ArgNo, unwrap<DIFile>(File),
LineNo, unwrap<DIType>(Ty), AlwaysPreserve,
map_from_llvmDIFlags(Flags)));
}
LLVMMetadataRef LLVMDIBuilderGetOrCreateSubrange(LLVMDIBuilderRef Builder,
int64_t Lo, int64_t Count) {
return wrap(unwrap(Builder)->getOrCreateSubrange(Lo, Count));
}
LLVMMetadataRef LLVMDIBuilderGetOrCreateArray(LLVMDIBuilderRef Builder,
LLVMMetadataRef *Data,
size_t Length) {
Metadata **DataValue = unwrap(Data);
return wrap(unwrap(Builder)->getOrCreateArray({DataValue, Length}).get());
}
LLVMMetadataRef LLVMGetSubprogram(LLVMValueRef Func) {
return wrap(unwrap<Function>(Func)->getSubprogram());
}
void LLVMSetSubprogram(LLVMValueRef Func, LLVMMetadataRef SP) {
unwrap<Function>(Func)->setSubprogram(unwrap<DISubprogram>(SP));
}
unsigned LLVMDISubprogramGetLine(LLVMMetadataRef Subprogram) {
return unwrapDI<DISubprogram>(Subprogram)->getLine();
}
LLVMMetadataRef LLVMInstructionGetDebugLoc(LLVMValueRef Inst) {
return wrap(unwrap<Instruction>(Inst)->getDebugLoc().getAsMDNode());
}
void LLVMInstructionSetDebugLoc(LLVMValueRef Inst, LLVMMetadataRef Loc) {
if (Loc)
unwrap<Instruction>(Inst)->setDebugLoc(DebugLoc(unwrap<MDNode>(Loc)));
else
unwrap<Instruction>(Inst)->setDebugLoc(DebugLoc());
}
LLVMMetadataKind LLVMGetMetadataKind(LLVMMetadataRef Metadata) {
switch(unwrap(Metadata)->getMetadataID()) {
#define HANDLE_METADATA_LEAF(CLASS) \
case Metadata::CLASS##Kind: \
return (LLVMMetadataKind)LLVM##CLASS##MetadataKind;
#include "llvm/IR/Metadata.def"
default:
return (LLVMMetadataKind)LLVMGenericDINodeMetadataKind;
}
}
AssignmentInstRange at::getAssignmentInsts(DIAssignID *ID) {
assert(ID && "Expected non-null ID");
LLVMContext &Ctx = ID->getContext();
auto &Map = Ctx.pImpl->AssignmentIDToInstrs;
auto MapIt = Map.find(ID);
if (MapIt == Map.end())
return make_range(nullptr, nullptr);
return make_range(MapIt->second.begin(), MapIt->second.end());
}
AssignmentMarkerRange at::getAssignmentMarkers(DIAssignID *ID) {
assert(ID && "Expected non-null ID");
LLVMContext &Ctx = ID->getContext();
auto *IDAsValue = MetadataAsValue::getIfExists(Ctx, ID);
// The ID is only used wrapped in MetadataAsValue(ID), so lets check that
// one of those already exists first.
if (!IDAsValue)
return make_range(Value::user_iterator(), Value::user_iterator());
return make_range(IDAsValue->user_begin(), IDAsValue->user_end());
}
void at::deleteAssignmentMarkers(const Instruction *Inst) {
auto Range = getAssignmentMarkers(Inst);
if (Range.empty())
return;
SmallVector<DbgAssignIntrinsic *> ToDelete(Range.begin(), Range.end());
for (auto *DAI : ToDelete)
DAI->eraseFromParent();
}
void at::RAUW(DIAssignID *Old, DIAssignID *New) {
// Replace MetadataAsValue uses.
if (auto *OldIDAsValue =
MetadataAsValue::getIfExists(Old->getContext(), Old)) {
auto *NewIDAsValue = MetadataAsValue::get(Old->getContext(), New);
OldIDAsValue->replaceAllUsesWith(NewIDAsValue);
}
// Replace attachments.
AssignmentInstRange InstRange = getAssignmentInsts(Old);
// Use intermediate storage for the instruction ptrs because the
// getAssignmentInsts range iterators will be invalidated by adding and
// removing DIAssignID attachments.
SmallVector<Instruction *> InstVec(InstRange.begin(), InstRange.end());
for (auto *I : InstVec)
I->setMetadata(LLVMContext::MD_DIAssignID, New);
}
void at::deleteAll(Function *F) {
SmallVector<DbgAssignIntrinsic *, 12> ToDelete;
for (BasicBlock &BB : *F) {
for (Instruction &I : BB) {
if (auto *DAI = dyn_cast<DbgAssignIntrinsic>(&I))
ToDelete.push_back(DAI);
else
I.setMetadata(LLVMContext::MD_DIAssignID, nullptr);
}
}
for (auto *DAI : ToDelete)
DAI->eraseFromParent();
}
/// Collect constant properies (base, size, offset) of \p StoreDest.
/// Return std::nullopt if any properties are not constants.
static std::optional<AssignmentInfo>
getAssignmentInfoImpl(const DataLayout &DL, const Value *StoreDest,
uint64_t SizeInBits) {
APInt GEPOffset(DL.getIndexTypeSizeInBits(StoreDest->getType()), 0);
const Value *Base = StoreDest->stripAndAccumulateConstantOffsets(
DL, GEPOffset, /*AllowNonInbounds*/ true);
uint64_t OffsetInBytes = GEPOffset.getLimitedValue();
// Check for overflow.
if (OffsetInBytes == UINT64_MAX)
return std::nullopt;
if (const auto *Alloca = dyn_cast<AllocaInst>(Base))
return AssignmentInfo(DL, Alloca, OffsetInBytes * 8, SizeInBits);
return std::nullopt;
}
std::optional<AssignmentInfo> at::getAssignmentInfo(const DataLayout &DL,
const MemIntrinsic *I) {
const Value *StoreDest = I->getRawDest();
// Assume 8 bit bytes.
auto *ConstLengthInBytes = dyn_cast<ConstantInt>(I->getLength());
if (!ConstLengthInBytes)
// We can't use a non-const size, bail.
return std::nullopt;
uint64_t SizeInBits = 8 * ConstLengthInBytes->getZExtValue();
return getAssignmentInfoImpl(DL, StoreDest, SizeInBits);
}
std::optional<AssignmentInfo> at::getAssignmentInfo(const DataLayout &DL,
const StoreInst *SI) {
const Value *StoreDest = SI->getPointerOperand();
uint64_t SizeInBits = DL.getTypeSizeInBits(SI->getValueOperand()->getType());
return getAssignmentInfoImpl(DL, StoreDest, SizeInBits);
}
std::optional<AssignmentInfo> at::getAssignmentInfo(const DataLayout &DL,
const AllocaInst *AI) {
uint64_t SizeInBits = DL.getTypeSizeInBits(AI->getAllocatedType());
return getAssignmentInfoImpl(DL, AI, SizeInBits);
}
static CallInst *emitDbgAssign(AssignmentInfo Info, Value *Val, Value *Dest,
Instruction &StoreLikeInst,
const VarRecord &VarRec, DIBuilder &DIB) {
auto *ID = StoreLikeInst.getMetadata(LLVMContext::MD_DIAssignID);
assert(ID && "Store instruction must have DIAssignID metadata");
(void)ID;
DIExpression *Expr =
DIExpression::get(StoreLikeInst.getContext(), std::nullopt);
if (!Info.StoreToWholeAlloca) {
auto R = DIExpression::createFragmentExpression(Expr, Info.OffsetInBits,
Info.SizeInBits);
assert(R.has_value() && "failed to create fragment expression");
Expr = *R;
}
DIExpression *AddrExpr =
DIExpression::get(StoreLikeInst.getContext(), std::nullopt);
return DIB.insertDbgAssign(&StoreLikeInst, Val, VarRec.Var, Expr, Dest,
AddrExpr, VarRec.DL);
}
#undef DEBUG_TYPE // Silence redefinition warning (from ConstantsContext.h).
#define DEBUG_TYPE "assignment-tracking"
void at::trackAssignments(Function::iterator Start, Function::iterator End,
const StorageToVarsMap &Vars, const DataLayout &DL,
bool DebugPrints) {
// Early-exit if there are no interesting variables.
if (Vars.empty())
return;
auto &Ctx = Start->getContext();
auto &Module = *Start->getModule();
// Undef type doesn't matter, so long as it isn't void. Let's just use i1.
auto *Undef = UndefValue::get(Type::getInt1Ty(Ctx));
DIBuilder DIB(Module, /*AllowUnresolved*/ false);
// Scan the instructions looking for stores to local variables' storage.
LLVM_DEBUG(errs() << "# Scanning instructions\n");
for (auto BBI = Start; BBI != End; ++BBI) {
for (Instruction &I : *BBI) {
std::optional<AssignmentInfo> Info;
Value *ValueComponent = nullptr;
Value *DestComponent = nullptr;
if (auto *AI = dyn_cast<AllocaInst>(&I)) {
// We want to track the variable's stack home from its alloca's
// position onwards so we treat it as an assignment (where the stored
// value is Undef).
Info = getAssignmentInfo(DL, AI);
ValueComponent = Undef;
DestComponent = AI;
} else if (auto *SI = dyn_cast<StoreInst>(&I)) {
Info = getAssignmentInfo(DL, SI);
ValueComponent = SI->getValueOperand();
DestComponent = SI->getPointerOperand();
} else if (auto *MI = dyn_cast<MemTransferInst>(&I)) {
Info = getAssignmentInfo(DL, MI);
// May not be able to represent this value easily.
ValueComponent = Undef;
DestComponent = MI->getOperand(0);
} else if (auto *MI = dyn_cast<MemSetInst>(&I)) {
Info = getAssignmentInfo(DL, MI);
// If we're zero-initing we can state the assigned value is zero,
// otherwise use undef.
auto *ConstValue = dyn_cast<ConstantInt>(MI->getOperand(1));
if (ConstValue && ConstValue->isZero())
ValueComponent = ConstValue;
else
ValueComponent = Undef;
DestComponent = MI->getOperand(0);
} else {
// Not a store-like instruction.
continue;
}
assert(ValueComponent && DestComponent);
LLVM_DEBUG(errs() << "SCAN: Found store-like: " << I << "\n");
// Check if getAssignmentInfo failed to understand this store.
if (!Info.has_value()) {
LLVM_DEBUG(
errs()
<< " | SKIP: Untrackable store (e.g. through non-const gep)\n");
continue;
}
LLVM_DEBUG(errs() << " | BASE: " << *Info->Base << "\n");
// Check if the store destination is a local variable with debug info.
auto LocalIt = Vars.find(Info->Base);
if (LocalIt == Vars.end()) {
LLVM_DEBUG(
errs()
<< " | SKIP: Base address not associated with local variable\n");
continue;
}
DIAssignID *ID =
cast_or_null<DIAssignID>(I.getMetadata(LLVMContext::MD_DIAssignID));
if (!ID) {
ID = DIAssignID::getDistinct(Ctx);
I.setMetadata(LLVMContext::MD_DIAssignID, ID);
}
for (const VarRecord &R : LocalIt->second) {
auto *Assign =
emitDbgAssign(*Info, ValueComponent, DestComponent, I, R, DIB);
(void)Assign;
LLVM_DEBUG(errs() << " > INSERT: " << *Assign << "\n");
}
}
}
}
void AssignmentTrackingPass::runOnFunction(Function &F) {
// Collect a map of {backing storage : dbg.declares} (currently "backing
// storage" is limited to Allocas). We'll use this to find dbg.declares to
// delete after running `trackAssignments`.
DenseMap<const AllocaInst *, SmallPtrSet<DbgDeclareInst *, 2>> DbgDeclares;
// Create another similar map of {storage : variables} that we'll pass to
// trackAssignments.
StorageToVarsMap Vars;
for (auto &BB : F) {
for (auto &I : BB) {
DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(&I);
if (!DDI)
continue;
// FIXME: trackAssignments doesn't let you specify any modifiers to the
// variable (e.g. fragment) or location (e.g. offset), so we have to
// leave dbg.declares with non-empty expressions in place.
if (DDI->getExpression()->getNumElements() != 0)
continue;
if (AllocaInst *Alloca =
dyn_cast<AllocaInst>(DDI->getAddress()->stripPointerCasts())) {
DbgDeclares[Alloca].insert(DDI);
Vars[Alloca].insert(VarRecord(DDI));
}
}
}
auto DL = std::make_unique<DataLayout>(F.getParent());
// FIXME: Locals can be backed by caller allocas (sret, byval).
// Note: trackAssignments doesn't respect dbg.declare's IR positions (as it
// doesn't "understand" dbg.declares). However, this doesn't appear to break
// any rules given this description of dbg.declare from
// llvm/docs/SourceLevelDebugging.rst:
//
// It is not control-dependent, meaning that if a call to llvm.dbg.declare
// exists and has a valid location argument, that address is considered to
// be the true home of the variable across its entire lifetime.
trackAssignments(F.begin(), F.end(), Vars, *DL);
// Delete dbg.declares for variables now tracked with assignment tracking.
for (auto &P : DbgDeclares) {
const AllocaInst *Alloca = P.first;
auto Markers = at::getAssignmentMarkers(Alloca);
(void)Markers;
for (DbgDeclareInst *DDI : P.second) {
// Assert that the alloca that DDI uses is now linked to a dbg.assign
// describing the same variable (i.e. check that this dbg.declare
// has been replaced by a dbg.assign).
assert(llvm::any_of(Markers, [DDI](DbgAssignIntrinsic *DAI) {
return DebugVariable(DAI) == DebugVariable(DDI);
}));
// Delete DDI because the variable location is now tracked using
// assignment tracking.
DDI->eraseFromParent();
}
}
}
static const char *AssignmentTrackingModuleFlag =
"debug-info-assignment-tracking";
static void setAssignmentTrackingModuleFlag(Module &M) {
M.setModuleFlag(Module::ModFlagBehavior::Max, AssignmentTrackingModuleFlag,
ConstantAsMetadata::get(
ConstantInt::get(Type::getInt1Ty(M.getContext()), 1)));
}
static bool getAssignmentTrackingModuleFlag(const Module &M) {
Metadata *Value = M.getModuleFlag(AssignmentTrackingModuleFlag);
return Value && !cast<ConstantAsMetadata>(Value)->getValue()->isZeroValue();
}
bool llvm::isAssignmentTrackingEnabled(const Module &M) {
return getAssignmentTrackingModuleFlag(M);
}
PreservedAnalyses AssignmentTrackingPass::run(Function &F,
FunctionAnalysisManager &AM) {
runOnFunction(F);
// Record that this module uses assignment tracking. It doesn't matter that
// some functons in the module may not use it - the debug info in those
// functions will still be handled properly.
setAssignmentTrackingModuleFlag(*F.getParent());
// Q: Can we return a less conservative set than just CFGAnalyses? Can we
// return PreservedAnalyses::all()?
PreservedAnalyses PA;
PA.preserveSet<CFGAnalyses>();
return PA;
}
PreservedAnalyses AssignmentTrackingPass::run(Module &M,
ModuleAnalysisManager &AM) {
for (auto &F : M)
runOnFunction(F);
// Record that this module uses assignment tracking.
setAssignmentTrackingModuleFlag(M);
// Q: Can we return a less conservative set than just CFGAnalyses? Can we
// return PreservedAnalyses::all()?
PreservedAnalyses PA;
PA.preserveSet<CFGAnalyses>();
return PA;
}
#undef DEBUG_TYPE
|