1 //===- DebugInfo.cpp - Debug Information Helper Classes -------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the helper classes used to build and interpret debug
10 // information in LLVM IR form.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm-c/DebugInfo.h"
15 #include "LLVMContextImpl.h"
16 #include "llvm/ADT/DenseMap.h"
17 #include "llvm/ADT/DenseSet.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/ADT/SmallPtrSet.h"
20 #include "llvm/ADT/SmallVector.h"
21 #include "llvm/ADT/StringRef.h"
22 #include "llvm/IR/BasicBlock.h"
23 #include "llvm/IR/Constants.h"
24 #include "llvm/IR/DIBuilder.h"
25 #include "llvm/IR/DebugInfo.h"
26 #include "llvm/IR/DebugInfoMetadata.h"
27 #include "llvm/IR/DebugLoc.h"
28 #include "llvm/IR/DebugProgramInstruction.h"
29 #include "llvm/IR/Function.h"
30 #include "llvm/IR/GVMaterializer.h"
31 #include "llvm/IR/Instruction.h"
32 #include "llvm/IR/IntrinsicInst.h"
33 #include "llvm/IR/LLVMContext.h"
34 #include "llvm/IR/Metadata.h"
35 #include "llvm/IR/Module.h"
36 #include "llvm/IR/PassManager.h"
37 #include "llvm/Support/Casting.h"
38 #include <algorithm>
39 #include <cassert>
40 #include <optional>
41 #include <utility>
42
43 using namespace llvm;
44 using namespace llvm::at;
45 using namespace llvm::dwarf;
46
findDbgDeclares(Value * V)47 TinyPtrVector<DbgDeclareInst *> llvm::findDbgDeclares(Value *V) {
48 // This function is hot. Check whether the value has any metadata to avoid a
49 // DenseMap lookup.
50 if (!V->isUsedByMetadata())
51 return {};
52 auto *L = LocalAsMetadata::getIfExists(V);
53 if (!L)
54 return {};
55 auto *MDV = MetadataAsValue::getIfExists(V->getContext(), L);
56 if (!MDV)
57 return {};
58
59 TinyPtrVector<DbgDeclareInst *> Declares;
60 for (User *U : MDV->users())
61 if (auto *DDI = dyn_cast<DbgDeclareInst>(U))
62 Declares.push_back(DDI);
63
64 return Declares;
65 }
findDVRDeclares(Value * V)66 TinyPtrVector<DbgVariableRecord *> llvm::findDVRDeclares(Value *V) {
67 // This function is hot. Check whether the value has any metadata to avoid a
68 // DenseMap lookup.
69 if (!V->isUsedByMetadata())
70 return {};
71 auto *L = LocalAsMetadata::getIfExists(V);
72 if (!L)
73 return {};
74
75 TinyPtrVector<DbgVariableRecord *> Declares;
76 for (DbgVariableRecord *DVR : L->getAllDbgVariableRecordUsers())
77 if (DVR->getType() == DbgVariableRecord::LocationType::Declare)
78 Declares.push_back(DVR);
79
80 return Declares;
81 }
82
83 template <typename IntrinsicT, bool DbgAssignAndValuesOnly>
84 static void
findDbgIntrinsics(SmallVectorImpl<IntrinsicT * > & Result,Value * V,SmallVectorImpl<DbgVariableRecord * > * DbgVariableRecords)85 findDbgIntrinsics(SmallVectorImpl<IntrinsicT *> &Result, Value *V,
86 SmallVectorImpl<DbgVariableRecord *> *DbgVariableRecords) {
87 // This function is hot. Check whether the value has any metadata to avoid a
88 // DenseMap lookup.
89 if (!V->isUsedByMetadata())
90 return;
91
92 LLVMContext &Ctx = V->getContext();
93 // TODO: If this value appears multiple times in a DIArgList, we should still
94 // only add the owning DbgValueInst once; use this set to track ArgListUsers.
95 // This behaviour can be removed when we can automatically remove duplicates.
96 // V will also appear twice in a dbg.assign if its used in the both the value
97 // and address components.
98 SmallPtrSet<IntrinsicT *, 4> EncounteredIntrinsics;
99 SmallPtrSet<DbgVariableRecord *, 4> EncounteredDbgVariableRecords;
100
101 /// Append IntrinsicT users of MetadataAsValue(MD).
102 auto AppendUsers = [&Ctx, &EncounteredIntrinsics,
103 &EncounteredDbgVariableRecords, &Result,
104 DbgVariableRecords](Metadata *MD) {
105 if (auto *MDV = MetadataAsValue::getIfExists(Ctx, MD)) {
106 for (User *U : MDV->users())
107 if (IntrinsicT *DVI = dyn_cast<IntrinsicT>(U))
108 if (EncounteredIntrinsics.insert(DVI).second)
109 Result.push_back(DVI);
110 }
111 if (!DbgVariableRecords)
112 return;
113 // Get DbgVariableRecords that use this as a single value.
114 if (LocalAsMetadata *L = dyn_cast<LocalAsMetadata>(MD)) {
115 for (DbgVariableRecord *DVR : L->getAllDbgVariableRecordUsers()) {
116 if (!DbgAssignAndValuesOnly || DVR->isDbgValue() || DVR->isDbgAssign())
117 if (EncounteredDbgVariableRecords.insert(DVR).second)
118 DbgVariableRecords->push_back(DVR);
119 }
120 }
121 };
122
123 if (auto *L = LocalAsMetadata::getIfExists(V)) {
124 AppendUsers(L);
125 for (Metadata *AL : L->getAllArgListUsers()) {
126 AppendUsers(AL);
127 if (!DbgVariableRecords)
128 continue;
129 DIArgList *DI = cast<DIArgList>(AL);
130 for (DbgVariableRecord *DVR : DI->getAllDbgVariableRecordUsers())
131 if (!DbgAssignAndValuesOnly || DVR->isDbgValue() || DVR->isDbgAssign())
132 if (EncounteredDbgVariableRecords.insert(DVR).second)
133 DbgVariableRecords->push_back(DVR);
134 }
135 }
136 }
137
findDbgValues(SmallVectorImpl<DbgValueInst * > & DbgValues,Value * V,SmallVectorImpl<DbgVariableRecord * > * DbgVariableRecords)138 void llvm::findDbgValues(
139 SmallVectorImpl<DbgValueInst *> &DbgValues, Value *V,
140 SmallVectorImpl<DbgVariableRecord *> *DbgVariableRecords) {
141 findDbgIntrinsics<DbgValueInst, /*DbgAssignAndValuesOnly=*/true>(
142 DbgValues, V, DbgVariableRecords);
143 }
144
findDbgUsers(SmallVectorImpl<DbgVariableIntrinsic * > & DbgUsers,Value * V,SmallVectorImpl<DbgVariableRecord * > * DbgVariableRecords)145 void llvm::findDbgUsers(
146 SmallVectorImpl<DbgVariableIntrinsic *> &DbgUsers, Value *V,
147 SmallVectorImpl<DbgVariableRecord *> *DbgVariableRecords) {
148 findDbgIntrinsics<DbgVariableIntrinsic, /*DbgAssignAndValuesOnly=*/false>(
149 DbgUsers, V, DbgVariableRecords);
150 }
151
getDISubprogram(const MDNode * Scope)152 DISubprogram *llvm::getDISubprogram(const MDNode *Scope) {
153 if (auto *LocalScope = dyn_cast_or_null<DILocalScope>(Scope))
154 return LocalScope->getSubprogram();
155 return nullptr;
156 }
157
getDebugValueLoc(DbgVariableIntrinsic * DII)158 DebugLoc llvm::getDebugValueLoc(DbgVariableIntrinsic *DII) {
159 // Original dbg.declare must have a location.
160 const DebugLoc &DeclareLoc = DII->getDebugLoc();
161 MDNode *Scope = DeclareLoc.getScope();
162 DILocation *InlinedAt = DeclareLoc.getInlinedAt();
163 // Because no machine insts can come from debug intrinsics, only the scope
164 // and inlinedAt is significant. Zero line numbers are used in case this
165 // DebugLoc leaks into any adjacent instructions. Produce an unknown location
166 // with the correct scope / inlinedAt fields.
167 return DILocation::get(DII->getContext(), 0, 0, Scope, InlinedAt);
168 }
169
getDebugValueLoc(DbgVariableRecord * DVR)170 DebugLoc llvm::getDebugValueLoc(DbgVariableRecord *DVR) {
171 // Original dbg.declare must have a location.
172 const DebugLoc &DeclareLoc = DVR->getDebugLoc();
173 MDNode *Scope = DeclareLoc.getScope();
174 DILocation *InlinedAt = DeclareLoc.getInlinedAt();
175 // Because no machine insts can come from debug intrinsics, only the scope
176 // and inlinedAt is significant. Zero line numbers are used in case this
177 // DebugLoc leaks into any adjacent instructions. Produce an unknown location
178 // with the correct scope / inlinedAt fields.
179 return DILocation::get(DVR->getContext(), 0, 0, Scope, InlinedAt);
180 }
181
182 //===----------------------------------------------------------------------===//
183 // DebugInfoFinder implementations.
184 //===----------------------------------------------------------------------===//
185
reset()186 void DebugInfoFinder::reset() {
187 CUs.clear();
188 SPs.clear();
189 GVs.clear();
190 TYs.clear();
191 Scopes.clear();
192 NodesSeen.clear();
193 }
194
processModule(const Module & M)195 void DebugInfoFinder::processModule(const Module &M) {
196 for (auto *CU : M.debug_compile_units())
197 processCompileUnit(CU);
198 for (auto &F : M.functions()) {
199 if (auto *SP = cast_or_null<DISubprogram>(F.getSubprogram()))
200 processSubprogram(SP);
201 // There could be subprograms from inlined functions referenced from
202 // instructions only. Walk the function to find them.
203 for (const BasicBlock &BB : F)
204 for (const Instruction &I : BB)
205 processInstruction(M, I);
206 }
207 }
208
processCompileUnit(DICompileUnit * CU)209 void DebugInfoFinder::processCompileUnit(DICompileUnit *CU) {
210 if (!addCompileUnit(CU))
211 return;
212 for (auto *DIG : CU->getGlobalVariables()) {
213 if (!addGlobalVariable(DIG))
214 continue;
215 auto *GV = DIG->getVariable();
216 processScope(GV->getScope());
217 processType(GV->getType());
218 }
219 for (auto *ET : CU->getEnumTypes())
220 processType(ET);
221 for (auto *RT : CU->getRetainedTypes())
222 if (auto *T = dyn_cast<DIType>(RT))
223 processType(T);
224 else
225 processSubprogram(cast<DISubprogram>(RT));
226 for (auto *Import : CU->getImportedEntities()) {
227 auto *Entity = Import->getEntity();
228 if (auto *T = dyn_cast<DIType>(Entity))
229 processType(T);
230 else if (auto *SP = dyn_cast<DISubprogram>(Entity))
231 processSubprogram(SP);
232 else if (auto *NS = dyn_cast<DINamespace>(Entity))
233 processScope(NS->getScope());
234 else if (auto *M = dyn_cast<DIModule>(Entity))
235 processScope(M->getScope());
236 }
237 }
238
processInstruction(const Module & M,const Instruction & I)239 void DebugInfoFinder::processInstruction(const Module &M,
240 const Instruction &I) {
241 if (auto *DVI = dyn_cast<DbgVariableIntrinsic>(&I))
242 processVariable(M, DVI->getVariable());
243
244 if (auto DbgLoc = I.getDebugLoc())
245 processLocation(M, DbgLoc.get());
246
247 for (const DbgRecord &DPR : I.getDbgRecordRange())
248 processDbgRecord(M, DPR);
249 }
250
processLocation(const Module & M,const DILocation * Loc)251 void DebugInfoFinder::processLocation(const Module &M, const DILocation *Loc) {
252 if (!Loc)
253 return;
254 processScope(Loc->getScope());
255 processLocation(M, Loc->getInlinedAt());
256 }
257
processDbgRecord(const Module & M,const DbgRecord & DR)258 void DebugInfoFinder::processDbgRecord(const Module &M, const DbgRecord &DR) {
259 if (const DbgVariableRecord *DVR = dyn_cast<const DbgVariableRecord>(&DR))
260 processVariable(M, DVR->getVariable());
261 processLocation(M, DR.getDebugLoc().get());
262 }
263
processType(DIType * DT)264 void DebugInfoFinder::processType(DIType *DT) {
265 if (!addType(DT))
266 return;
267 processScope(DT->getScope());
268 if (auto *ST = dyn_cast<DISubroutineType>(DT)) {
269 for (DIType *Ref : ST->getTypeArray())
270 processType(Ref);
271 return;
272 }
273 if (auto *DCT = dyn_cast<DICompositeType>(DT)) {
274 processType(DCT->getBaseType());
275 for (Metadata *D : DCT->getElements()) {
276 if (auto *T = dyn_cast<DIType>(D))
277 processType(T);
278 else if (auto *SP = dyn_cast<DISubprogram>(D))
279 processSubprogram(SP);
280 }
281 return;
282 }
283 if (auto *DDT = dyn_cast<DIDerivedType>(DT)) {
284 processType(DDT->getBaseType());
285 }
286 }
287
processScope(DIScope * Scope)288 void DebugInfoFinder::processScope(DIScope *Scope) {
289 if (!Scope)
290 return;
291 if (auto *Ty = dyn_cast<DIType>(Scope)) {
292 processType(Ty);
293 return;
294 }
295 if (auto *CU = dyn_cast<DICompileUnit>(Scope)) {
296 addCompileUnit(CU);
297 return;
298 }
299 if (auto *SP = dyn_cast<DISubprogram>(Scope)) {
300 processSubprogram(SP);
301 return;
302 }
303 if (!addScope(Scope))
304 return;
305 if (auto *LB = dyn_cast<DILexicalBlockBase>(Scope)) {
306 processScope(LB->getScope());
307 } else if (auto *NS = dyn_cast<DINamespace>(Scope)) {
308 processScope(NS->getScope());
309 } else if (auto *M = dyn_cast<DIModule>(Scope)) {
310 processScope(M->getScope());
311 }
312 }
313
processSubprogram(DISubprogram * SP)314 void DebugInfoFinder::processSubprogram(DISubprogram *SP) {
315 if (!addSubprogram(SP))
316 return;
317 processScope(SP->getScope());
318 // Some of the users, e.g. CloneFunctionInto / CloneModule, need to set up a
319 // ValueMap containing identity mappings for all of the DICompileUnit's, not
320 // just DISubprogram's, referenced from anywhere within the Function being
321 // cloned prior to calling MapMetadata / RemapInstruction to avoid their
322 // duplication later as DICompileUnit's are also directly referenced by
323 // llvm.dbg.cu list. Thefore we need to collect DICompileUnit's here as well.
324 // Also, DICompileUnit's may reference DISubprogram's too and therefore need
325 // to be at least looked through.
326 processCompileUnit(SP->getUnit());
327 processType(SP->getType());
328 for (auto *Element : SP->getTemplateParams()) {
329 if (auto *TType = dyn_cast<DITemplateTypeParameter>(Element)) {
330 processType(TType->getType());
331 } else if (auto *TVal = dyn_cast<DITemplateValueParameter>(Element)) {
332 processType(TVal->getType());
333 }
334 }
335 }
336
processVariable(const Module & M,const DILocalVariable * DV)337 void DebugInfoFinder::processVariable(const Module &M,
338 const DILocalVariable *DV) {
339 if (!NodesSeen.insert(DV).second)
340 return;
341 processScope(DV->getScope());
342 processType(DV->getType());
343 }
344
addType(DIType * DT)345 bool DebugInfoFinder::addType(DIType *DT) {
346 if (!DT)
347 return false;
348
349 if (!NodesSeen.insert(DT).second)
350 return false;
351
352 TYs.push_back(const_cast<DIType *>(DT));
353 return true;
354 }
355
addCompileUnit(DICompileUnit * CU)356 bool DebugInfoFinder::addCompileUnit(DICompileUnit *CU) {
357 if (!CU)
358 return false;
359 if (!NodesSeen.insert(CU).second)
360 return false;
361
362 CUs.push_back(CU);
363 return true;
364 }
365
addGlobalVariable(DIGlobalVariableExpression * DIG)366 bool DebugInfoFinder::addGlobalVariable(DIGlobalVariableExpression *DIG) {
367 if (!NodesSeen.insert(DIG).second)
368 return false;
369
370 GVs.push_back(DIG);
371 return true;
372 }
373
addSubprogram(DISubprogram * SP)374 bool DebugInfoFinder::addSubprogram(DISubprogram *SP) {
375 if (!SP)
376 return false;
377
378 if (!NodesSeen.insert(SP).second)
379 return false;
380
381 SPs.push_back(SP);
382 return true;
383 }
384
addScope(DIScope * Scope)385 bool DebugInfoFinder::addScope(DIScope *Scope) {
386 if (!Scope)
387 return false;
388 // FIXME: Ocaml binding generates a scope with no content, we treat it
389 // as null for now.
390 if (Scope->getNumOperands() == 0)
391 return false;
392 if (!NodesSeen.insert(Scope).second)
393 return false;
394 Scopes.push_back(Scope);
395 return true;
396 }
397
updateLoopMetadataDebugLocationsImpl(MDNode * OrigLoopID,function_ref<Metadata * (Metadata *)> Updater)398 static MDNode *updateLoopMetadataDebugLocationsImpl(
399 MDNode *OrigLoopID, function_ref<Metadata *(Metadata *)> Updater) {
400 assert(OrigLoopID && OrigLoopID->getNumOperands() > 0 &&
401 "Loop ID needs at least one operand");
402 assert(OrigLoopID && OrigLoopID->getOperand(0).get() == OrigLoopID &&
403 "Loop ID should refer to itself");
404
405 // Save space for the self-referential LoopID.
406 SmallVector<Metadata *, 4> MDs = {nullptr};
407
408 for (unsigned i = 1; i < OrigLoopID->getNumOperands(); ++i) {
409 Metadata *MD = OrigLoopID->getOperand(i);
410 if (!MD)
411 MDs.push_back(nullptr);
412 else if (Metadata *NewMD = Updater(MD))
413 MDs.push_back(NewMD);
414 }
415
416 MDNode *NewLoopID = MDNode::getDistinct(OrigLoopID->getContext(), MDs);
417 // Insert the self-referential LoopID.
418 NewLoopID->replaceOperandWith(0, NewLoopID);
419 return NewLoopID;
420 }
421
updateLoopMetadataDebugLocations(Instruction & I,function_ref<Metadata * (Metadata *)> Updater)422 void llvm::updateLoopMetadataDebugLocations(
423 Instruction &I, function_ref<Metadata *(Metadata *)> Updater) {
424 MDNode *OrigLoopID = I.getMetadata(LLVMContext::MD_loop);
425 if (!OrigLoopID)
426 return;
427 MDNode *NewLoopID = updateLoopMetadataDebugLocationsImpl(OrigLoopID, Updater);
428 I.setMetadata(LLVMContext::MD_loop, NewLoopID);
429 }
430
431 /// Return true if a node is a DILocation or if a DILocation is
432 /// indirectly referenced by one of the node's children.
isDILocationReachable(SmallPtrSetImpl<Metadata * > & Visited,SmallPtrSetImpl<Metadata * > & Reachable,Metadata * MD)433 static bool isDILocationReachable(SmallPtrSetImpl<Metadata *> &Visited,
434 SmallPtrSetImpl<Metadata *> &Reachable,
435 Metadata *MD) {
436 MDNode *N = dyn_cast_or_null<MDNode>(MD);
437 if (!N)
438 return false;
439 if (isa<DILocation>(N) || Reachable.count(N))
440 return true;
441 if (!Visited.insert(N).second)
442 return false;
443 for (auto &OpIt : N->operands()) {
444 Metadata *Op = OpIt.get();
445 if (isDILocationReachable(Visited, Reachable, Op)) {
446 // Don't return just yet as we want to visit all MD's children to
447 // initialize DILocationReachable in stripDebugLocFromLoopID
448 Reachable.insert(N);
449 }
450 }
451 return Reachable.count(N);
452 }
453
isAllDILocation(SmallPtrSetImpl<Metadata * > & Visited,SmallPtrSetImpl<Metadata * > & AllDILocation,const SmallPtrSetImpl<Metadata * > & DIReachable,Metadata * MD)454 static bool isAllDILocation(SmallPtrSetImpl<Metadata *> &Visited,
455 SmallPtrSetImpl<Metadata *> &AllDILocation,
456 const SmallPtrSetImpl<Metadata *> &DIReachable,
457 Metadata *MD) {
458 MDNode *N = dyn_cast_or_null<MDNode>(MD);
459 if (!N)
460 return false;
461 if (isa<DILocation>(N) || AllDILocation.count(N))
462 return true;
463 if (!DIReachable.count(N))
464 return false;
465 if (!Visited.insert(N).second)
466 return false;
467 for (auto &OpIt : N->operands()) {
468 Metadata *Op = OpIt.get();
469 if (Op == MD)
470 continue;
471 if (!isAllDILocation(Visited, AllDILocation, DIReachable, Op)) {
472 return false;
473 }
474 }
475 AllDILocation.insert(N);
476 return true;
477 }
478
479 static Metadata *
stripLoopMDLoc(const SmallPtrSetImpl<Metadata * > & AllDILocation,const SmallPtrSetImpl<Metadata * > & DIReachable,Metadata * MD)480 stripLoopMDLoc(const SmallPtrSetImpl<Metadata *> &AllDILocation,
481 const SmallPtrSetImpl<Metadata *> &DIReachable, Metadata *MD) {
482 if (isa<DILocation>(MD) || AllDILocation.count(MD))
483 return nullptr;
484
485 if (!DIReachable.count(MD))
486 return MD;
487
488 MDNode *N = dyn_cast_or_null<MDNode>(MD);
489 if (!N)
490 return MD;
491
492 SmallVector<Metadata *, 4> Args;
493 bool HasSelfRef = false;
494 for (unsigned i = 0; i < N->getNumOperands(); ++i) {
495 Metadata *A = N->getOperand(i);
496 if (!A) {
497 Args.push_back(nullptr);
498 } else if (A == MD) {
499 assert(i == 0 && "expected i==0 for self-reference");
500 HasSelfRef = true;
501 Args.push_back(nullptr);
502 } else if (Metadata *NewArg =
503 stripLoopMDLoc(AllDILocation, DIReachable, A)) {
504 Args.push_back(NewArg);
505 }
506 }
507 if (Args.empty() || (HasSelfRef && Args.size() == 1))
508 return nullptr;
509
510 MDNode *NewMD = N->isDistinct() ? MDNode::getDistinct(N->getContext(), Args)
511 : MDNode::get(N->getContext(), Args);
512 if (HasSelfRef)
513 NewMD->replaceOperandWith(0, NewMD);
514 return NewMD;
515 }
516
stripDebugLocFromLoopID(MDNode * N)517 static MDNode *stripDebugLocFromLoopID(MDNode *N) {
518 assert(!N->operands().empty() && "Missing self reference?");
519 SmallPtrSet<Metadata *, 8> Visited, DILocationReachable, AllDILocation;
520 // If we already visited N, there is nothing to do.
521 if (!Visited.insert(N).second)
522 return N;
523
524 // If there is no debug location, we do not have to rewrite this
525 // MDNode. This loop also initializes DILocationReachable, later
526 // needed by updateLoopMetadataDebugLocationsImpl; the use of
527 // count_if avoids an early exit.
528 if (!llvm::count_if(llvm::drop_begin(N->operands()),
529 [&Visited, &DILocationReachable](const MDOperand &Op) {
530 return isDILocationReachable(
531 Visited, DILocationReachable, Op.get());
532 }))
533 return N;
534
535 Visited.clear();
536 // If there is only the debug location without any actual loop metadata, we
537 // can remove the metadata.
538 if (llvm::all_of(llvm::drop_begin(N->operands()),
539 [&Visited, &AllDILocation,
540 &DILocationReachable](const MDOperand &Op) {
541 return isAllDILocation(Visited, AllDILocation,
542 DILocationReachable, Op.get());
543 }))
544 return nullptr;
545
546 return updateLoopMetadataDebugLocationsImpl(
547 N, [&AllDILocation, &DILocationReachable](Metadata *MD) -> Metadata * {
548 return stripLoopMDLoc(AllDILocation, DILocationReachable, MD);
549 });
550 }
551
stripDebugInfo(Function & F)552 bool llvm::stripDebugInfo(Function &F) {
553 bool Changed = false;
554 if (F.hasMetadata(LLVMContext::MD_dbg)) {
555 Changed = true;
556 F.setSubprogram(nullptr);
557 }
558
559 DenseMap<MDNode *, MDNode *> LoopIDsMap;
560 for (BasicBlock &BB : F) {
561 for (Instruction &I : llvm::make_early_inc_range(BB)) {
562 if (isa<DbgInfoIntrinsic>(&I)) {
563 I.eraseFromParent();
564 Changed = true;
565 continue;
566 }
567 if (I.getDebugLoc()) {
568 Changed = true;
569 I.setDebugLoc(DebugLoc());
570 }
571 if (auto *LoopID = I.getMetadata(LLVMContext::MD_loop)) {
572 auto *NewLoopID = LoopIDsMap.lookup(LoopID);
573 if (!NewLoopID)
574 NewLoopID = LoopIDsMap[LoopID] = stripDebugLocFromLoopID(LoopID);
575 if (NewLoopID != LoopID)
576 I.setMetadata(LLVMContext::MD_loop, NewLoopID);
577 }
578 // Strip other attachments that are or use debug info.
579 if (I.hasMetadataOtherThanDebugLoc()) {
580 // Heapallocsites point into the DIType system.
581 I.setMetadata("heapallocsite", nullptr);
582 // DIAssignID are debug info metadata primitives.
583 I.setMetadata(LLVMContext::MD_DIAssignID, nullptr);
584 }
585 I.dropDbgRecords();
586 }
587 }
588 return Changed;
589 }
590
StripDebugInfo(Module & M)591 bool llvm::StripDebugInfo(Module &M) {
592 bool Changed = false;
593
594 for (NamedMDNode &NMD : llvm::make_early_inc_range(M.named_metadata())) {
595 // We're stripping debug info, and without them, coverage information
596 // doesn't quite make sense.
597 if (NMD.getName().starts_with("llvm.dbg.") ||
598 NMD.getName() == "llvm.gcov") {
599 NMD.eraseFromParent();
600 Changed = true;
601 }
602 }
603
604 for (Function &F : M)
605 Changed |= stripDebugInfo(F);
606
607 for (auto &GV : M.globals()) {
608 Changed |= GV.eraseMetadata(LLVMContext::MD_dbg);
609 }
610
611 if (GVMaterializer *Materializer = M.getMaterializer())
612 Materializer->setStripDebugInfo();
613
614 return Changed;
615 }
616
617 namespace {
618
619 /// Helper class to downgrade -g metadata to -gline-tables-only metadata.
620 class DebugTypeInfoRemoval {
621 DenseMap<Metadata *, Metadata *> Replacements;
622
623 public:
624 /// The (void)() type.
625 MDNode *EmptySubroutineType;
626
627 private:
628 /// Remember what linkage name we originally had before stripping. If we end
629 /// up making two subprograms identical who originally had different linkage
630 /// names, then we need to make one of them distinct, to avoid them getting
631 /// uniqued. Maps the new node to the old linkage name.
632 DenseMap<DISubprogram *, StringRef> NewToLinkageName;
633
634 // TODO: Remember the distinct subprogram we created for a given linkage name,
635 // so that we can continue to unique whenever possible. Map <newly created
636 // node, old linkage name> to the first (possibly distinct) mdsubprogram
637 // created for that combination. This is not strictly needed for correctness,
638 // but can cut down on the number of MDNodes and let us diff cleanly with the
639 // output of -gline-tables-only.
640
641 public:
DebugTypeInfoRemoval(LLVMContext & C)642 DebugTypeInfoRemoval(LLVMContext &C)
643 : EmptySubroutineType(DISubroutineType::get(C, DINode::FlagZero, 0,
644 MDNode::get(C, {}))) {}
645
map(Metadata * M)646 Metadata *map(Metadata *M) {
647 if (!M)
648 return nullptr;
649 auto Replacement = Replacements.find(M);
650 if (Replacement != Replacements.end())
651 return Replacement->second;
652
653 return M;
654 }
mapNode(Metadata * N)655 MDNode *mapNode(Metadata *N) { return dyn_cast_or_null<MDNode>(map(N)); }
656
657 /// Recursively remap N and all its referenced children. Does a DF post-order
658 /// traversal, so as to remap bottoms up.
traverseAndRemap(MDNode * N)659 void traverseAndRemap(MDNode *N) { traverse(N); }
660
661 private:
662 // Create a new DISubprogram, to replace the one given.
getReplacementSubprogram(DISubprogram * MDS)663 DISubprogram *getReplacementSubprogram(DISubprogram *MDS) {
664 auto *FileAndScope = cast_or_null<DIFile>(map(MDS->getFile()));
665 StringRef LinkageName = MDS->getName().empty() ? MDS->getLinkageName() : "";
666 DISubprogram *Declaration = nullptr;
667 auto *Type = cast_or_null<DISubroutineType>(map(MDS->getType()));
668 DIType *ContainingType =
669 cast_or_null<DIType>(map(MDS->getContainingType()));
670 auto *Unit = cast_or_null<DICompileUnit>(map(MDS->getUnit()));
671 auto Variables = nullptr;
672 auto TemplateParams = nullptr;
673
674 // Make a distinct DISubprogram, for situations that warrent it.
675 auto distinctMDSubprogram = [&]() {
676 return DISubprogram::getDistinct(
677 MDS->getContext(), FileAndScope, MDS->getName(), LinkageName,
678 FileAndScope, MDS->getLine(), Type, MDS->getScopeLine(),
679 ContainingType, MDS->getVirtualIndex(), MDS->getThisAdjustment(),
680 MDS->getFlags(), MDS->getSPFlags(), Unit, TemplateParams, Declaration,
681 Variables);
682 };
683
684 if (MDS->isDistinct())
685 return distinctMDSubprogram();
686
687 auto *NewMDS = DISubprogram::get(
688 MDS->getContext(), FileAndScope, MDS->getName(), LinkageName,
689 FileAndScope, MDS->getLine(), Type, MDS->getScopeLine(), ContainingType,
690 MDS->getVirtualIndex(), MDS->getThisAdjustment(), MDS->getFlags(),
691 MDS->getSPFlags(), Unit, TemplateParams, Declaration, Variables);
692
693 StringRef OldLinkageName = MDS->getLinkageName();
694
695 // See if we need to make a distinct one.
696 auto OrigLinkage = NewToLinkageName.find(NewMDS);
697 if (OrigLinkage != NewToLinkageName.end()) {
698 if (OrigLinkage->second == OldLinkageName)
699 // We're good.
700 return NewMDS;
701
702 // Otherwise, need to make a distinct one.
703 // TODO: Query the map to see if we already have one.
704 return distinctMDSubprogram();
705 }
706
707 NewToLinkageName.insert({NewMDS, MDS->getLinkageName()});
708 return NewMDS;
709 }
710
711 /// Create a new compile unit, to replace the one given
getReplacementCU(DICompileUnit * CU)712 DICompileUnit *getReplacementCU(DICompileUnit *CU) {
713 // Drop skeleton CUs.
714 if (CU->getDWOId())
715 return nullptr;
716
717 auto *File = cast_or_null<DIFile>(map(CU->getFile()));
718 MDTuple *EnumTypes = nullptr;
719 MDTuple *RetainedTypes = nullptr;
720 MDTuple *GlobalVariables = nullptr;
721 MDTuple *ImportedEntities = nullptr;
722 return DICompileUnit::getDistinct(
723 CU->getContext(), CU->getSourceLanguage(), File, CU->getProducer(),
724 CU->isOptimized(), CU->getFlags(), CU->getRuntimeVersion(),
725 CU->getSplitDebugFilename(), DICompileUnit::LineTablesOnly, EnumTypes,
726 RetainedTypes, GlobalVariables, ImportedEntities, CU->getMacros(),
727 CU->getDWOId(), CU->getSplitDebugInlining(),
728 CU->getDebugInfoForProfiling(), CU->getNameTableKind(),
729 CU->getRangesBaseAddress(), CU->getSysRoot(), CU->getSDK());
730 }
731
getReplacementMDLocation(DILocation * MLD)732 DILocation *getReplacementMDLocation(DILocation *MLD) {
733 auto *Scope = map(MLD->getScope());
734 auto *InlinedAt = map(MLD->getInlinedAt());
735 if (MLD->isDistinct())
736 return DILocation::getDistinct(MLD->getContext(), MLD->getLine(),
737 MLD->getColumn(), Scope, InlinedAt);
738 return DILocation::get(MLD->getContext(), MLD->getLine(), MLD->getColumn(),
739 Scope, InlinedAt);
740 }
741
742 /// Create a new generic MDNode, to replace the one given
getReplacementMDNode(MDNode * N)743 MDNode *getReplacementMDNode(MDNode *N) {
744 SmallVector<Metadata *, 8> Ops;
745 Ops.reserve(N->getNumOperands());
746 for (auto &I : N->operands())
747 if (I)
748 Ops.push_back(map(I));
749 auto *Ret = MDNode::get(N->getContext(), Ops);
750 return Ret;
751 }
752
753 /// Attempt to re-map N to a newly created node.
remap(MDNode * N)754 void remap(MDNode *N) {
755 if (Replacements.count(N))
756 return;
757
758 auto doRemap = [&](MDNode *N) -> MDNode * {
759 if (!N)
760 return nullptr;
761 if (auto *MDSub = dyn_cast<DISubprogram>(N)) {
762 remap(MDSub->getUnit());
763 return getReplacementSubprogram(MDSub);
764 }
765 if (isa<DISubroutineType>(N))
766 return EmptySubroutineType;
767 if (auto *CU = dyn_cast<DICompileUnit>(N))
768 return getReplacementCU(CU);
769 if (isa<DIFile>(N))
770 return N;
771 if (auto *MDLB = dyn_cast<DILexicalBlockBase>(N))
772 // Remap to our referenced scope (recursively).
773 return mapNode(MDLB->getScope());
774 if (auto *MLD = dyn_cast<DILocation>(N))
775 return getReplacementMDLocation(MLD);
776
777 // Otherwise, if we see these, just drop them now. Not strictly necessary,
778 // but this speeds things up a little.
779 if (isa<DINode>(N))
780 return nullptr;
781
782 return getReplacementMDNode(N);
783 };
784 Replacements[N] = doRemap(N);
785 }
786
787 /// Do the remapping traversal.
788 void traverse(MDNode *);
789 };
790
791 } // end anonymous namespace
792
traverse(MDNode * N)793 void DebugTypeInfoRemoval::traverse(MDNode *N) {
794 if (!N || Replacements.count(N))
795 return;
796
797 // To avoid cycles, as well as for efficiency sake, we will sometimes prune
798 // parts of the graph.
799 auto prune = [](MDNode *Parent, MDNode *Child) {
800 if (auto *MDS = dyn_cast<DISubprogram>(Parent))
801 return Child == MDS->getRetainedNodes().get();
802 return false;
803 };
804
805 SmallVector<MDNode *, 16> ToVisit;
806 DenseSet<MDNode *> Opened;
807
808 // Visit each node starting at N in post order, and map them.
809 ToVisit.push_back(N);
810 while (!ToVisit.empty()) {
811 auto *N = ToVisit.back();
812 if (!Opened.insert(N).second) {
813 // Close it.
814 remap(N);
815 ToVisit.pop_back();
816 continue;
817 }
818 for (auto &I : N->operands())
819 if (auto *MDN = dyn_cast_or_null<MDNode>(I))
820 if (!Opened.count(MDN) && !Replacements.count(MDN) && !prune(N, MDN) &&
821 !isa<DICompileUnit>(MDN))
822 ToVisit.push_back(MDN);
823 }
824 }
825
stripNonLineTableDebugInfo(Module & M)826 bool llvm::stripNonLineTableDebugInfo(Module &M) {
827 bool Changed = false;
828
829 // First off, delete the debug intrinsics.
830 auto RemoveUses = [&](StringRef Name) {
831 if (auto *DbgVal = M.getFunction(Name)) {
832 while (!DbgVal->use_empty())
833 cast<Instruction>(DbgVal->user_back())->eraseFromParent();
834 DbgVal->eraseFromParent();
835 Changed = true;
836 }
837 };
838 RemoveUses("llvm.dbg.declare");
839 RemoveUses("llvm.dbg.label");
840 RemoveUses("llvm.dbg.value");
841
842 // Delete non-CU debug info named metadata nodes.
843 for (auto NMI = M.named_metadata_begin(), NME = M.named_metadata_end();
844 NMI != NME;) {
845 NamedMDNode *NMD = &*NMI;
846 ++NMI;
847 // Specifically keep dbg.cu around.
848 if (NMD->getName() == "llvm.dbg.cu")
849 continue;
850 }
851
852 // Drop all dbg attachments from global variables.
853 for (auto &GV : M.globals())
854 GV.eraseMetadata(LLVMContext::MD_dbg);
855
856 DebugTypeInfoRemoval Mapper(M.getContext());
857 auto remap = [&](MDNode *Node) -> MDNode * {
858 if (!Node)
859 return nullptr;
860 Mapper.traverseAndRemap(Node);
861 auto *NewNode = Mapper.mapNode(Node);
862 Changed |= Node != NewNode;
863 Node = NewNode;
864 return NewNode;
865 };
866
867 // Rewrite the DebugLocs to be equivalent to what
868 // -gline-tables-only would have created.
869 for (auto &F : M) {
870 if (auto *SP = F.getSubprogram()) {
871 Mapper.traverseAndRemap(SP);
872 auto *NewSP = cast<DISubprogram>(Mapper.mapNode(SP));
873 Changed |= SP != NewSP;
874 F.setSubprogram(NewSP);
875 }
876 for (auto &BB : F) {
877 for (auto &I : BB) {
878 auto remapDebugLoc = [&](const DebugLoc &DL) -> DebugLoc {
879 auto *Scope = DL.getScope();
880 MDNode *InlinedAt = DL.getInlinedAt();
881 Scope = remap(Scope);
882 InlinedAt = remap(InlinedAt);
883 return DILocation::get(M.getContext(), DL.getLine(), DL.getCol(),
884 Scope, InlinedAt);
885 };
886
887 if (I.getDebugLoc() != DebugLoc())
888 I.setDebugLoc(remapDebugLoc(I.getDebugLoc()));
889
890 // Remap DILocations in llvm.loop attachments.
891 updateLoopMetadataDebugLocations(I, [&](Metadata *MD) -> Metadata * {
892 if (auto *Loc = dyn_cast_or_null<DILocation>(MD))
893 return remapDebugLoc(Loc).get();
894 return MD;
895 });
896
897 // Strip heapallocsite attachments, they point into the DIType system.
898 if (I.hasMetadataOtherThanDebugLoc())
899 I.setMetadata("heapallocsite", nullptr);
900
901 // Strip any DbgRecords attached.
902 I.dropDbgRecords();
903 }
904 }
905 }
906
907 // Create a new llvm.dbg.cu, which is equivalent to the one
908 // -gline-tables-only would have created.
909 for (auto &NMD : M.named_metadata()) {
910 SmallVector<MDNode *, 8> Ops;
911 for (MDNode *Op : NMD.operands())
912 Ops.push_back(remap(Op));
913
914 if (!Changed)
915 continue;
916
917 NMD.clearOperands();
918 for (auto *Op : Ops)
919 if (Op)
920 NMD.addOperand(Op);
921 }
922 return Changed;
923 }
924
getDebugMetadataVersionFromModule(const Module & M)925 unsigned llvm::getDebugMetadataVersionFromModule(const Module &M) {
926 if (auto *Val = mdconst::dyn_extract_or_null<ConstantInt>(
927 M.getModuleFlag("Debug Info Version")))
928 return Val->getZExtValue();
929 return 0;
930 }
931
applyMergedLocation(DILocation * LocA,DILocation * LocB)932 void Instruction::applyMergedLocation(DILocation *LocA, DILocation *LocB) {
933 setDebugLoc(DILocation::getMergedLocation(LocA, LocB));
934 }
935
mergeDIAssignID(ArrayRef<const Instruction * > SourceInstructions)936 void Instruction::mergeDIAssignID(
937 ArrayRef<const Instruction *> SourceInstructions) {
938 // Replace all uses (and attachments) of all the DIAssignIDs
939 // on SourceInstructions with a single merged value.
940 assert(getFunction() && "Uninserted instruction merged");
941 // Collect up the DIAssignID tags.
942 SmallVector<DIAssignID *, 4> IDs;
943 for (const Instruction *I : SourceInstructions) {
944 if (auto *MD = I->getMetadata(LLVMContext::MD_DIAssignID))
945 IDs.push_back(cast<DIAssignID>(MD));
946 assert(getFunction() == I->getFunction() &&
947 "Merging with instruction from another function not allowed");
948 }
949
950 // Add this instruction's DIAssignID too, if it has one.
951 if (auto *MD = getMetadata(LLVMContext::MD_DIAssignID))
952 IDs.push_back(cast<DIAssignID>(MD));
953
954 if (IDs.empty())
955 return; // No DIAssignID tags to process.
956
957 DIAssignID *MergeID = IDs[0];
958 for (auto It = std::next(IDs.begin()), End = IDs.end(); It != End; ++It) {
959 if (*It != MergeID)
960 at::RAUW(*It, MergeID);
961 }
962 setMetadata(LLVMContext::MD_DIAssignID, MergeID);
963 }
964
updateLocationAfterHoist()965 void Instruction::updateLocationAfterHoist() { dropLocation(); }
966
dropLocation()967 void Instruction::dropLocation() {
968 const DebugLoc &DL = getDebugLoc();
969 if (!DL)
970 return;
971
972 // If this isn't a call, drop the location to allow a location from a
973 // preceding instruction to propagate.
974 bool MayLowerToCall = false;
975 if (isa<CallBase>(this)) {
976 auto *II = dyn_cast<IntrinsicInst>(this);
977 MayLowerToCall =
978 !II || IntrinsicInst::mayLowerToFunctionCall(II->getIntrinsicID());
979 }
980
981 if (!MayLowerToCall) {
982 setDebugLoc(DebugLoc());
983 return;
984 }
985
986 // Set a line 0 location for calls to preserve scope information in case
987 // inlining occurs.
988 DISubprogram *SP = getFunction()->getSubprogram();
989 if (SP)
990 // If a function scope is available, set it on the line 0 location. When
991 // hoisting a call to a predecessor block, using the function scope avoids
992 // making it look like the callee was reached earlier than it should be.
993 setDebugLoc(DILocation::get(getContext(), 0, 0, SP));
994 else
995 // The parent function has no scope. Go ahead and drop the location. If
996 // the parent function is inlined, and the callee has a subprogram, the
997 // inliner will attach a location to the call.
998 //
999 // One alternative is to set a line 0 location with the existing scope and
1000 // inlinedAt info. The location might be sensitive to when inlining occurs.
1001 setDebugLoc(DebugLoc());
1002 }
1003
1004 //===----------------------------------------------------------------------===//
1005 // LLVM C API implementations.
1006 //===----------------------------------------------------------------------===//
1007
map_from_llvmDWARFsourcelanguage(LLVMDWARFSourceLanguage lang)1008 static unsigned map_from_llvmDWARFsourcelanguage(LLVMDWARFSourceLanguage lang) {
1009 switch (lang) {
1010 #define HANDLE_DW_LANG(ID, NAME, LOWER_BOUND, VERSION, VENDOR) \
1011 case LLVMDWARFSourceLanguage##NAME: \
1012 return ID;
1013 #include "llvm/BinaryFormat/Dwarf.def"
1014 #undef HANDLE_DW_LANG
1015 }
1016 llvm_unreachable("Unhandled Tag");
1017 }
1018
unwrapDI(LLVMMetadataRef Ref)1019 template <typename DIT> DIT *unwrapDI(LLVMMetadataRef Ref) {
1020 return (DIT *)(Ref ? unwrap<MDNode>(Ref) : nullptr);
1021 }
1022
map_from_llvmDIFlags(LLVMDIFlags Flags)1023 static DINode::DIFlags map_from_llvmDIFlags(LLVMDIFlags Flags) {
1024 return static_cast<DINode::DIFlags>(Flags);
1025 }
1026
map_to_llvmDIFlags(DINode::DIFlags Flags)1027 static LLVMDIFlags map_to_llvmDIFlags(DINode::DIFlags Flags) {
1028 return static_cast<LLVMDIFlags>(Flags);
1029 }
1030
1031 static DISubprogram::DISPFlags
pack_into_DISPFlags(bool IsLocalToUnit,bool IsDefinition,bool IsOptimized)1032 pack_into_DISPFlags(bool IsLocalToUnit, bool IsDefinition, bool IsOptimized) {
1033 return DISubprogram::toSPFlags(IsLocalToUnit, IsDefinition, IsOptimized);
1034 }
1035
LLVMDebugMetadataVersion()1036 unsigned LLVMDebugMetadataVersion() {
1037 return DEBUG_METADATA_VERSION;
1038 }
1039
LLVMCreateDIBuilderDisallowUnresolved(LLVMModuleRef M)1040 LLVMDIBuilderRef LLVMCreateDIBuilderDisallowUnresolved(LLVMModuleRef M) {
1041 return wrap(new DIBuilder(*unwrap(M), false));
1042 }
1043
LLVMCreateDIBuilder(LLVMModuleRef M)1044 LLVMDIBuilderRef LLVMCreateDIBuilder(LLVMModuleRef M) {
1045 return wrap(new DIBuilder(*unwrap(M)));
1046 }
1047
LLVMGetModuleDebugMetadataVersion(LLVMModuleRef M)1048 unsigned LLVMGetModuleDebugMetadataVersion(LLVMModuleRef M) {
1049 return getDebugMetadataVersionFromModule(*unwrap(M));
1050 }
1051
LLVMStripModuleDebugInfo(LLVMModuleRef M)1052 LLVMBool LLVMStripModuleDebugInfo(LLVMModuleRef M) {
1053 return StripDebugInfo(*unwrap(M));
1054 }
1055
LLVMDisposeDIBuilder(LLVMDIBuilderRef Builder)1056 void LLVMDisposeDIBuilder(LLVMDIBuilderRef Builder) {
1057 delete unwrap(Builder);
1058 }
1059
LLVMDIBuilderFinalize(LLVMDIBuilderRef Builder)1060 void LLVMDIBuilderFinalize(LLVMDIBuilderRef Builder) {
1061 unwrap(Builder)->finalize();
1062 }
1063
LLVMDIBuilderFinalizeSubprogram(LLVMDIBuilderRef Builder,LLVMMetadataRef subprogram)1064 void LLVMDIBuilderFinalizeSubprogram(LLVMDIBuilderRef Builder,
1065 LLVMMetadataRef subprogram) {
1066 unwrap(Builder)->finalizeSubprogram(unwrapDI<DISubprogram>(subprogram));
1067 }
1068
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)1069 LLVMMetadataRef LLVMDIBuilderCreateCompileUnit(
1070 LLVMDIBuilderRef Builder, LLVMDWARFSourceLanguage Lang,
1071 LLVMMetadataRef FileRef, const char *Producer, size_t ProducerLen,
1072 LLVMBool isOptimized, const char *Flags, size_t FlagsLen,
1073 unsigned RuntimeVer, const char *SplitName, size_t SplitNameLen,
1074 LLVMDWARFEmissionKind Kind, unsigned DWOId, LLVMBool SplitDebugInlining,
1075 LLVMBool DebugInfoForProfiling, const char *SysRoot, size_t SysRootLen,
1076 const char *SDK, size_t SDKLen) {
1077 auto File = unwrapDI<DIFile>(FileRef);
1078
1079 return wrap(unwrap(Builder)->createCompileUnit(
1080 map_from_llvmDWARFsourcelanguage(Lang), File,
1081 StringRef(Producer, ProducerLen), isOptimized, StringRef(Flags, FlagsLen),
1082 RuntimeVer, StringRef(SplitName, SplitNameLen),
1083 static_cast<DICompileUnit::DebugEmissionKind>(Kind), DWOId,
1084 SplitDebugInlining, DebugInfoForProfiling,
1085 DICompileUnit::DebugNameTableKind::Default, false,
1086 StringRef(SysRoot, SysRootLen), StringRef(SDK, SDKLen)));
1087 }
1088
1089 LLVMMetadataRef
LLVMDIBuilderCreateFile(LLVMDIBuilderRef Builder,const char * Filename,size_t FilenameLen,const char * Directory,size_t DirectoryLen)1090 LLVMDIBuilderCreateFile(LLVMDIBuilderRef Builder, const char *Filename,
1091 size_t FilenameLen, const char *Directory,
1092 size_t DirectoryLen) {
1093 return wrap(unwrap(Builder)->createFile(StringRef(Filename, FilenameLen),
1094 StringRef(Directory, DirectoryLen)));
1095 }
1096
1097 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)1098 LLVMDIBuilderCreateModule(LLVMDIBuilderRef Builder, LLVMMetadataRef ParentScope,
1099 const char *Name, size_t NameLen,
1100 const char *ConfigMacros, size_t ConfigMacrosLen,
1101 const char *IncludePath, size_t IncludePathLen,
1102 const char *APINotesFile, size_t APINotesFileLen) {
1103 return wrap(unwrap(Builder)->createModule(
1104 unwrapDI<DIScope>(ParentScope), StringRef(Name, NameLen),
1105 StringRef(ConfigMacros, ConfigMacrosLen),
1106 StringRef(IncludePath, IncludePathLen),
1107 StringRef(APINotesFile, APINotesFileLen)));
1108 }
1109
LLVMDIBuilderCreateNameSpace(LLVMDIBuilderRef Builder,LLVMMetadataRef ParentScope,const char * Name,size_t NameLen,LLVMBool ExportSymbols)1110 LLVMMetadataRef LLVMDIBuilderCreateNameSpace(LLVMDIBuilderRef Builder,
1111 LLVMMetadataRef ParentScope,
1112 const char *Name, size_t NameLen,
1113 LLVMBool ExportSymbols) {
1114 return wrap(unwrap(Builder)->createNameSpace(
1115 unwrapDI<DIScope>(ParentScope), StringRef(Name, NameLen), ExportSymbols));
1116 }
1117
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)1118 LLVMMetadataRef LLVMDIBuilderCreateFunction(
1119 LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
1120 size_t NameLen, const char *LinkageName, size_t LinkageNameLen,
1121 LLVMMetadataRef File, unsigned LineNo, LLVMMetadataRef Ty,
1122 LLVMBool IsLocalToUnit, LLVMBool IsDefinition,
1123 unsigned ScopeLine, LLVMDIFlags Flags, LLVMBool IsOptimized) {
1124 return wrap(unwrap(Builder)->createFunction(
1125 unwrapDI<DIScope>(Scope), {Name, NameLen}, {LinkageName, LinkageNameLen},
1126 unwrapDI<DIFile>(File), LineNo, unwrapDI<DISubroutineType>(Ty), ScopeLine,
1127 map_from_llvmDIFlags(Flags),
1128 pack_into_DISPFlags(IsLocalToUnit, IsDefinition, IsOptimized), nullptr,
1129 nullptr, nullptr));
1130 }
1131
1132
LLVMDIBuilderCreateLexicalBlock(LLVMDIBuilderRef Builder,LLVMMetadataRef Scope,LLVMMetadataRef File,unsigned Line,unsigned Col)1133 LLVMMetadataRef LLVMDIBuilderCreateLexicalBlock(
1134 LLVMDIBuilderRef Builder, LLVMMetadataRef Scope,
1135 LLVMMetadataRef File, unsigned Line, unsigned Col) {
1136 return wrap(unwrap(Builder)->createLexicalBlock(unwrapDI<DIScope>(Scope),
1137 unwrapDI<DIFile>(File),
1138 Line, Col));
1139 }
1140
1141 LLVMMetadataRef
LLVMDIBuilderCreateLexicalBlockFile(LLVMDIBuilderRef Builder,LLVMMetadataRef Scope,LLVMMetadataRef File,unsigned Discriminator)1142 LLVMDIBuilderCreateLexicalBlockFile(LLVMDIBuilderRef Builder,
1143 LLVMMetadataRef Scope,
1144 LLVMMetadataRef File,
1145 unsigned Discriminator) {
1146 return wrap(unwrap(Builder)->createLexicalBlockFile(unwrapDI<DIScope>(Scope),
1147 unwrapDI<DIFile>(File),
1148 Discriminator));
1149 }
1150
1151 LLVMMetadataRef
LLVMDIBuilderCreateImportedModuleFromNamespace(LLVMDIBuilderRef Builder,LLVMMetadataRef Scope,LLVMMetadataRef NS,LLVMMetadataRef File,unsigned Line)1152 LLVMDIBuilderCreateImportedModuleFromNamespace(LLVMDIBuilderRef Builder,
1153 LLVMMetadataRef Scope,
1154 LLVMMetadataRef NS,
1155 LLVMMetadataRef File,
1156 unsigned Line) {
1157 return wrap(unwrap(Builder)->createImportedModule(unwrapDI<DIScope>(Scope),
1158 unwrapDI<DINamespace>(NS),
1159 unwrapDI<DIFile>(File),
1160 Line));
1161 }
1162
LLVMDIBuilderCreateImportedModuleFromAlias(LLVMDIBuilderRef Builder,LLVMMetadataRef Scope,LLVMMetadataRef ImportedEntity,LLVMMetadataRef File,unsigned Line,LLVMMetadataRef * Elements,unsigned NumElements)1163 LLVMMetadataRef LLVMDIBuilderCreateImportedModuleFromAlias(
1164 LLVMDIBuilderRef Builder, LLVMMetadataRef Scope,
1165 LLVMMetadataRef ImportedEntity, LLVMMetadataRef File, unsigned Line,
1166 LLVMMetadataRef *Elements, unsigned NumElements) {
1167 auto Elts =
1168 (NumElements > 0)
1169 ? unwrap(Builder)->getOrCreateArray({unwrap(Elements), NumElements})
1170 : nullptr;
1171 return wrap(unwrap(Builder)->createImportedModule(
1172 unwrapDI<DIScope>(Scope), unwrapDI<DIImportedEntity>(ImportedEntity),
1173 unwrapDI<DIFile>(File), Line, Elts));
1174 }
1175
LLVMDIBuilderCreateImportedModuleFromModule(LLVMDIBuilderRef Builder,LLVMMetadataRef Scope,LLVMMetadataRef M,LLVMMetadataRef File,unsigned Line,LLVMMetadataRef * Elements,unsigned NumElements)1176 LLVMMetadataRef LLVMDIBuilderCreateImportedModuleFromModule(
1177 LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, LLVMMetadataRef M,
1178 LLVMMetadataRef File, unsigned Line, LLVMMetadataRef *Elements,
1179 unsigned NumElements) {
1180 auto Elts =
1181 (NumElements > 0)
1182 ? unwrap(Builder)->getOrCreateArray({unwrap(Elements), NumElements})
1183 : nullptr;
1184 return wrap(unwrap(Builder)->createImportedModule(
1185 unwrapDI<DIScope>(Scope), unwrapDI<DIModule>(M), unwrapDI<DIFile>(File),
1186 Line, Elts));
1187 }
1188
LLVMDIBuilderCreateImportedDeclaration(LLVMDIBuilderRef Builder,LLVMMetadataRef Scope,LLVMMetadataRef Decl,LLVMMetadataRef File,unsigned Line,const char * Name,size_t NameLen,LLVMMetadataRef * Elements,unsigned NumElements)1189 LLVMMetadataRef LLVMDIBuilderCreateImportedDeclaration(
1190 LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, LLVMMetadataRef Decl,
1191 LLVMMetadataRef File, unsigned Line, const char *Name, size_t NameLen,
1192 LLVMMetadataRef *Elements, unsigned NumElements) {
1193 auto Elts =
1194 (NumElements > 0)
1195 ? unwrap(Builder)->getOrCreateArray({unwrap(Elements), NumElements})
1196 : nullptr;
1197 return wrap(unwrap(Builder)->createImportedDeclaration(
1198 unwrapDI<DIScope>(Scope), unwrapDI<DINode>(Decl), unwrapDI<DIFile>(File),
1199 Line, {Name, NameLen}, Elts));
1200 }
1201
1202 LLVMMetadataRef
LLVMDIBuilderCreateDebugLocation(LLVMContextRef Ctx,unsigned Line,unsigned Column,LLVMMetadataRef Scope,LLVMMetadataRef InlinedAt)1203 LLVMDIBuilderCreateDebugLocation(LLVMContextRef Ctx, unsigned Line,
1204 unsigned Column, LLVMMetadataRef Scope,
1205 LLVMMetadataRef InlinedAt) {
1206 return wrap(DILocation::get(*unwrap(Ctx), Line, Column, unwrap(Scope),
1207 unwrap(InlinedAt)));
1208 }
1209
LLVMDILocationGetLine(LLVMMetadataRef Location)1210 unsigned LLVMDILocationGetLine(LLVMMetadataRef Location) {
1211 return unwrapDI<DILocation>(Location)->getLine();
1212 }
1213
LLVMDILocationGetColumn(LLVMMetadataRef Location)1214 unsigned LLVMDILocationGetColumn(LLVMMetadataRef Location) {
1215 return unwrapDI<DILocation>(Location)->getColumn();
1216 }
1217
LLVMDILocationGetScope(LLVMMetadataRef Location)1218 LLVMMetadataRef LLVMDILocationGetScope(LLVMMetadataRef Location) {
1219 return wrap(unwrapDI<DILocation>(Location)->getScope());
1220 }
1221
LLVMDILocationGetInlinedAt(LLVMMetadataRef Location)1222 LLVMMetadataRef LLVMDILocationGetInlinedAt(LLVMMetadataRef Location) {
1223 return wrap(unwrapDI<DILocation>(Location)->getInlinedAt());
1224 }
1225
LLVMDIScopeGetFile(LLVMMetadataRef Scope)1226 LLVMMetadataRef LLVMDIScopeGetFile(LLVMMetadataRef Scope) {
1227 return wrap(unwrapDI<DIScope>(Scope)->getFile());
1228 }
1229
LLVMDIFileGetDirectory(LLVMMetadataRef File,unsigned * Len)1230 const char *LLVMDIFileGetDirectory(LLVMMetadataRef File, unsigned *Len) {
1231 auto Dir = unwrapDI<DIFile>(File)->getDirectory();
1232 *Len = Dir.size();
1233 return Dir.data();
1234 }
1235
LLVMDIFileGetFilename(LLVMMetadataRef File,unsigned * Len)1236 const char *LLVMDIFileGetFilename(LLVMMetadataRef File, unsigned *Len) {
1237 auto Name = unwrapDI<DIFile>(File)->getFilename();
1238 *Len = Name.size();
1239 return Name.data();
1240 }
1241
LLVMDIFileGetSource(LLVMMetadataRef File,unsigned * Len)1242 const char *LLVMDIFileGetSource(LLVMMetadataRef File, unsigned *Len) {
1243 if (auto Src = unwrapDI<DIFile>(File)->getSource()) {
1244 *Len = Src->size();
1245 return Src->data();
1246 }
1247 *Len = 0;
1248 return "";
1249 }
1250
LLVMDIBuilderCreateMacro(LLVMDIBuilderRef Builder,LLVMMetadataRef ParentMacroFile,unsigned Line,LLVMDWARFMacinfoRecordType RecordType,const char * Name,size_t NameLen,const char * Value,size_t ValueLen)1251 LLVMMetadataRef LLVMDIBuilderCreateMacro(LLVMDIBuilderRef Builder,
1252 LLVMMetadataRef ParentMacroFile,
1253 unsigned Line,
1254 LLVMDWARFMacinfoRecordType RecordType,
1255 const char *Name, size_t NameLen,
1256 const char *Value, size_t ValueLen) {
1257 return wrap(
1258 unwrap(Builder)->createMacro(unwrapDI<DIMacroFile>(ParentMacroFile), Line,
1259 static_cast<MacinfoRecordType>(RecordType),
1260 {Name, NameLen}, {Value, ValueLen}));
1261 }
1262
1263 LLVMMetadataRef
LLVMDIBuilderCreateTempMacroFile(LLVMDIBuilderRef Builder,LLVMMetadataRef ParentMacroFile,unsigned Line,LLVMMetadataRef File)1264 LLVMDIBuilderCreateTempMacroFile(LLVMDIBuilderRef Builder,
1265 LLVMMetadataRef ParentMacroFile, unsigned Line,
1266 LLVMMetadataRef File) {
1267 return wrap(unwrap(Builder)->createTempMacroFile(
1268 unwrapDI<DIMacroFile>(ParentMacroFile), Line, unwrapDI<DIFile>(File)));
1269 }
1270
LLVMDIBuilderCreateEnumerator(LLVMDIBuilderRef Builder,const char * Name,size_t NameLen,int64_t Value,LLVMBool IsUnsigned)1271 LLVMMetadataRef LLVMDIBuilderCreateEnumerator(LLVMDIBuilderRef Builder,
1272 const char *Name, size_t NameLen,
1273 int64_t Value,
1274 LLVMBool IsUnsigned) {
1275 return wrap(unwrap(Builder)->createEnumerator({Name, NameLen}, Value,
1276 IsUnsigned != 0));
1277 }
1278
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)1279 LLVMMetadataRef LLVMDIBuilderCreateEnumerationType(
1280 LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
1281 size_t NameLen, LLVMMetadataRef File, unsigned LineNumber,
1282 uint64_t SizeInBits, uint32_t AlignInBits, LLVMMetadataRef *Elements,
1283 unsigned NumElements, LLVMMetadataRef ClassTy) {
1284 auto Elts = unwrap(Builder)->getOrCreateArray({unwrap(Elements),
1285 NumElements});
1286 return wrap(unwrap(Builder)->createEnumerationType(
1287 unwrapDI<DIScope>(Scope), {Name, NameLen}, unwrapDI<DIFile>(File),
1288 LineNumber, SizeInBits, AlignInBits, Elts, unwrapDI<DIType>(ClassTy)));
1289 }
1290
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)1291 LLVMMetadataRef LLVMDIBuilderCreateUnionType(
1292 LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
1293 size_t NameLen, LLVMMetadataRef File, unsigned LineNumber,
1294 uint64_t SizeInBits, uint32_t AlignInBits, LLVMDIFlags Flags,
1295 LLVMMetadataRef *Elements, unsigned NumElements, unsigned RunTimeLang,
1296 const char *UniqueId, size_t UniqueIdLen) {
1297 auto Elts = unwrap(Builder)->getOrCreateArray({unwrap(Elements),
1298 NumElements});
1299 return wrap(unwrap(Builder)->createUnionType(
1300 unwrapDI<DIScope>(Scope), {Name, NameLen}, unwrapDI<DIFile>(File),
1301 LineNumber, SizeInBits, AlignInBits, map_from_llvmDIFlags(Flags),
1302 Elts, RunTimeLang, {UniqueId, UniqueIdLen}));
1303 }
1304
1305
1306 LLVMMetadataRef
LLVMDIBuilderCreateArrayType(LLVMDIBuilderRef Builder,uint64_t Size,uint32_t AlignInBits,LLVMMetadataRef Ty,LLVMMetadataRef * Subscripts,unsigned NumSubscripts)1307 LLVMDIBuilderCreateArrayType(LLVMDIBuilderRef Builder, uint64_t Size,
1308 uint32_t AlignInBits, LLVMMetadataRef Ty,
1309 LLVMMetadataRef *Subscripts,
1310 unsigned NumSubscripts) {
1311 auto Subs = unwrap(Builder)->getOrCreateArray({unwrap(Subscripts),
1312 NumSubscripts});
1313 return wrap(unwrap(Builder)->createArrayType(Size, AlignInBits,
1314 unwrapDI<DIType>(Ty), Subs));
1315 }
1316
1317 LLVMMetadataRef
LLVMDIBuilderCreateVectorType(LLVMDIBuilderRef Builder,uint64_t Size,uint32_t AlignInBits,LLVMMetadataRef Ty,LLVMMetadataRef * Subscripts,unsigned NumSubscripts)1318 LLVMDIBuilderCreateVectorType(LLVMDIBuilderRef Builder, uint64_t Size,
1319 uint32_t AlignInBits, LLVMMetadataRef Ty,
1320 LLVMMetadataRef *Subscripts,
1321 unsigned NumSubscripts) {
1322 auto Subs = unwrap(Builder)->getOrCreateArray({unwrap(Subscripts),
1323 NumSubscripts});
1324 return wrap(unwrap(Builder)->createVectorType(Size, AlignInBits,
1325 unwrapDI<DIType>(Ty), Subs));
1326 }
1327
1328 LLVMMetadataRef
LLVMDIBuilderCreateBasicType(LLVMDIBuilderRef Builder,const char * Name,size_t NameLen,uint64_t SizeInBits,LLVMDWARFTypeEncoding Encoding,LLVMDIFlags Flags)1329 LLVMDIBuilderCreateBasicType(LLVMDIBuilderRef Builder, const char *Name,
1330 size_t NameLen, uint64_t SizeInBits,
1331 LLVMDWARFTypeEncoding Encoding,
1332 LLVMDIFlags Flags) {
1333 return wrap(unwrap(Builder)->createBasicType({Name, NameLen},
1334 SizeInBits, Encoding,
1335 map_from_llvmDIFlags(Flags)));
1336 }
1337
LLVMDIBuilderCreatePointerType(LLVMDIBuilderRef Builder,LLVMMetadataRef PointeeTy,uint64_t SizeInBits,uint32_t AlignInBits,unsigned AddressSpace,const char * Name,size_t NameLen)1338 LLVMMetadataRef LLVMDIBuilderCreatePointerType(
1339 LLVMDIBuilderRef Builder, LLVMMetadataRef PointeeTy,
1340 uint64_t SizeInBits, uint32_t AlignInBits, unsigned AddressSpace,
1341 const char *Name, size_t NameLen) {
1342 return wrap(unwrap(Builder)->createPointerType(
1343 unwrapDI<DIType>(PointeeTy), SizeInBits, AlignInBits, AddressSpace,
1344 {Name, NameLen}));
1345 }
1346
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)1347 LLVMMetadataRef LLVMDIBuilderCreateStructType(
1348 LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
1349 size_t NameLen, LLVMMetadataRef File, unsigned LineNumber,
1350 uint64_t SizeInBits, uint32_t AlignInBits, LLVMDIFlags Flags,
1351 LLVMMetadataRef DerivedFrom, LLVMMetadataRef *Elements,
1352 unsigned NumElements, unsigned RunTimeLang, LLVMMetadataRef VTableHolder,
1353 const char *UniqueId, size_t UniqueIdLen) {
1354 auto Elts = unwrap(Builder)->getOrCreateArray({unwrap(Elements),
1355 NumElements});
1356 return wrap(unwrap(Builder)->createStructType(
1357 unwrapDI<DIScope>(Scope), {Name, NameLen}, unwrapDI<DIFile>(File),
1358 LineNumber, SizeInBits, AlignInBits, map_from_llvmDIFlags(Flags),
1359 unwrapDI<DIType>(DerivedFrom), Elts, RunTimeLang,
1360 unwrapDI<DIType>(VTableHolder), {UniqueId, UniqueIdLen}));
1361 }
1362
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)1363 LLVMMetadataRef LLVMDIBuilderCreateMemberType(
1364 LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
1365 size_t NameLen, LLVMMetadataRef File, unsigned LineNo, uint64_t SizeInBits,
1366 uint32_t AlignInBits, uint64_t OffsetInBits, LLVMDIFlags Flags,
1367 LLVMMetadataRef Ty) {
1368 return wrap(unwrap(Builder)->createMemberType(unwrapDI<DIScope>(Scope),
1369 {Name, NameLen}, unwrapDI<DIFile>(File), LineNo, SizeInBits, AlignInBits,
1370 OffsetInBits, map_from_llvmDIFlags(Flags), unwrapDI<DIType>(Ty)));
1371 }
1372
1373 LLVMMetadataRef
LLVMDIBuilderCreateUnspecifiedType(LLVMDIBuilderRef Builder,const char * Name,size_t NameLen)1374 LLVMDIBuilderCreateUnspecifiedType(LLVMDIBuilderRef Builder, const char *Name,
1375 size_t NameLen) {
1376 return wrap(unwrap(Builder)->createUnspecifiedType({Name, NameLen}));
1377 }
1378
LLVMDIBuilderCreateStaticMemberType(LLVMDIBuilderRef Builder,LLVMMetadataRef Scope,const char * Name,size_t NameLen,LLVMMetadataRef File,unsigned LineNumber,LLVMMetadataRef Type,LLVMDIFlags Flags,LLVMValueRef ConstantVal,uint32_t AlignInBits)1379 LLVMMetadataRef LLVMDIBuilderCreateStaticMemberType(
1380 LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
1381 size_t NameLen, LLVMMetadataRef File, unsigned LineNumber,
1382 LLVMMetadataRef Type, LLVMDIFlags Flags, LLVMValueRef ConstantVal,
1383 uint32_t AlignInBits) {
1384 return wrap(unwrap(Builder)->createStaticMemberType(
1385 unwrapDI<DIScope>(Scope), {Name, NameLen}, unwrapDI<DIFile>(File),
1386 LineNumber, unwrapDI<DIType>(Type), map_from_llvmDIFlags(Flags),
1387 unwrap<Constant>(ConstantVal), DW_TAG_member, AlignInBits));
1388 }
1389
1390 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)1391 LLVMDIBuilderCreateObjCIVar(LLVMDIBuilderRef Builder,
1392 const char *Name, size_t NameLen,
1393 LLVMMetadataRef File, unsigned LineNo,
1394 uint64_t SizeInBits, uint32_t AlignInBits,
1395 uint64_t OffsetInBits, LLVMDIFlags Flags,
1396 LLVMMetadataRef Ty, LLVMMetadataRef PropertyNode) {
1397 return wrap(unwrap(Builder)->createObjCIVar(
1398 {Name, NameLen}, unwrapDI<DIFile>(File), LineNo,
1399 SizeInBits, AlignInBits, OffsetInBits,
1400 map_from_llvmDIFlags(Flags), unwrapDI<DIType>(Ty),
1401 unwrapDI<MDNode>(PropertyNode)));
1402 }
1403
1404 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)1405 LLVMDIBuilderCreateObjCProperty(LLVMDIBuilderRef Builder,
1406 const char *Name, size_t NameLen,
1407 LLVMMetadataRef File, unsigned LineNo,
1408 const char *GetterName, size_t GetterNameLen,
1409 const char *SetterName, size_t SetterNameLen,
1410 unsigned PropertyAttributes,
1411 LLVMMetadataRef Ty) {
1412 return wrap(unwrap(Builder)->createObjCProperty(
1413 {Name, NameLen}, unwrapDI<DIFile>(File), LineNo,
1414 {GetterName, GetterNameLen}, {SetterName, SetterNameLen},
1415 PropertyAttributes, unwrapDI<DIType>(Ty)));
1416 }
1417
1418 LLVMMetadataRef
LLVMDIBuilderCreateObjectPointerType(LLVMDIBuilderRef Builder,LLVMMetadataRef Type)1419 LLVMDIBuilderCreateObjectPointerType(LLVMDIBuilderRef Builder,
1420 LLVMMetadataRef Type) {
1421 return wrap(unwrap(Builder)->createObjectPointerType(unwrapDI<DIType>(Type)));
1422 }
1423
1424 LLVMMetadataRef
LLVMDIBuilderCreateTypedef(LLVMDIBuilderRef Builder,LLVMMetadataRef Type,const char * Name,size_t NameLen,LLVMMetadataRef File,unsigned LineNo,LLVMMetadataRef Scope,uint32_t AlignInBits)1425 LLVMDIBuilderCreateTypedef(LLVMDIBuilderRef Builder, LLVMMetadataRef Type,
1426 const char *Name, size_t NameLen,
1427 LLVMMetadataRef File, unsigned LineNo,
1428 LLVMMetadataRef Scope, uint32_t AlignInBits) {
1429 return wrap(unwrap(Builder)->createTypedef(
1430 unwrapDI<DIType>(Type), {Name, NameLen}, unwrapDI<DIFile>(File), LineNo,
1431 unwrapDI<DIScope>(Scope), AlignInBits));
1432 }
1433
1434 LLVMMetadataRef
LLVMDIBuilderCreateInheritance(LLVMDIBuilderRef Builder,LLVMMetadataRef Ty,LLVMMetadataRef BaseTy,uint64_t BaseOffset,uint32_t VBPtrOffset,LLVMDIFlags Flags)1435 LLVMDIBuilderCreateInheritance(LLVMDIBuilderRef Builder,
1436 LLVMMetadataRef Ty, LLVMMetadataRef BaseTy,
1437 uint64_t BaseOffset, uint32_t VBPtrOffset,
1438 LLVMDIFlags Flags) {
1439 return wrap(unwrap(Builder)->createInheritance(
1440 unwrapDI<DIType>(Ty), unwrapDI<DIType>(BaseTy),
1441 BaseOffset, VBPtrOffset, map_from_llvmDIFlags(Flags)));
1442 }
1443
1444 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)1445 LLVMDIBuilderCreateForwardDecl(
1446 LLVMDIBuilderRef Builder, unsigned Tag, const char *Name,
1447 size_t NameLen, LLVMMetadataRef Scope, LLVMMetadataRef File, unsigned Line,
1448 unsigned RuntimeLang, uint64_t SizeInBits, uint32_t AlignInBits,
1449 const char *UniqueIdentifier, size_t UniqueIdentifierLen) {
1450 return wrap(unwrap(Builder)->createForwardDecl(
1451 Tag, {Name, NameLen}, unwrapDI<DIScope>(Scope),
1452 unwrapDI<DIFile>(File), Line, RuntimeLang, SizeInBits,
1453 AlignInBits, {UniqueIdentifier, UniqueIdentifierLen}));
1454 }
1455
1456 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)1457 LLVMDIBuilderCreateReplaceableCompositeType(
1458 LLVMDIBuilderRef Builder, unsigned Tag, const char *Name,
1459 size_t NameLen, LLVMMetadataRef Scope, LLVMMetadataRef File, unsigned Line,
1460 unsigned RuntimeLang, uint64_t SizeInBits, uint32_t AlignInBits,
1461 LLVMDIFlags Flags, const char *UniqueIdentifier,
1462 size_t UniqueIdentifierLen) {
1463 return wrap(unwrap(Builder)->createReplaceableCompositeType(
1464 Tag, {Name, NameLen}, unwrapDI<DIScope>(Scope),
1465 unwrapDI<DIFile>(File), Line, RuntimeLang, SizeInBits,
1466 AlignInBits, map_from_llvmDIFlags(Flags),
1467 {UniqueIdentifier, UniqueIdentifierLen}));
1468 }
1469
1470 LLVMMetadataRef
LLVMDIBuilderCreateQualifiedType(LLVMDIBuilderRef Builder,unsigned Tag,LLVMMetadataRef Type)1471 LLVMDIBuilderCreateQualifiedType(LLVMDIBuilderRef Builder, unsigned Tag,
1472 LLVMMetadataRef Type) {
1473 return wrap(unwrap(Builder)->createQualifiedType(Tag,
1474 unwrapDI<DIType>(Type)));
1475 }
1476
1477 LLVMMetadataRef
LLVMDIBuilderCreateReferenceType(LLVMDIBuilderRef Builder,unsigned Tag,LLVMMetadataRef Type)1478 LLVMDIBuilderCreateReferenceType(LLVMDIBuilderRef Builder, unsigned Tag,
1479 LLVMMetadataRef Type) {
1480 return wrap(unwrap(Builder)->createReferenceType(Tag,
1481 unwrapDI<DIType>(Type)));
1482 }
1483
1484 LLVMMetadataRef
LLVMDIBuilderCreateNullPtrType(LLVMDIBuilderRef Builder)1485 LLVMDIBuilderCreateNullPtrType(LLVMDIBuilderRef Builder) {
1486 return wrap(unwrap(Builder)->createNullPtrType());
1487 }
1488
1489 LLVMMetadataRef
LLVMDIBuilderCreateMemberPointerType(LLVMDIBuilderRef Builder,LLVMMetadataRef PointeeType,LLVMMetadataRef ClassType,uint64_t SizeInBits,uint32_t AlignInBits,LLVMDIFlags Flags)1490 LLVMDIBuilderCreateMemberPointerType(LLVMDIBuilderRef Builder,
1491 LLVMMetadataRef PointeeType,
1492 LLVMMetadataRef ClassType,
1493 uint64_t SizeInBits,
1494 uint32_t AlignInBits,
1495 LLVMDIFlags Flags) {
1496 return wrap(unwrap(Builder)->createMemberPointerType(
1497 unwrapDI<DIType>(PointeeType),
1498 unwrapDI<DIType>(ClassType), AlignInBits, SizeInBits,
1499 map_from_llvmDIFlags(Flags)));
1500 }
1501
1502 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)1503 LLVMDIBuilderCreateBitFieldMemberType(LLVMDIBuilderRef Builder,
1504 LLVMMetadataRef Scope,
1505 const char *Name, size_t NameLen,
1506 LLVMMetadataRef File, unsigned LineNumber,
1507 uint64_t SizeInBits,
1508 uint64_t OffsetInBits,
1509 uint64_t StorageOffsetInBits,
1510 LLVMDIFlags Flags, LLVMMetadataRef Type) {
1511 return wrap(unwrap(Builder)->createBitFieldMemberType(
1512 unwrapDI<DIScope>(Scope), {Name, NameLen},
1513 unwrapDI<DIFile>(File), LineNumber,
1514 SizeInBits, OffsetInBits, StorageOffsetInBits,
1515 map_from_llvmDIFlags(Flags), unwrapDI<DIType>(Type)));
1516 }
1517
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)1518 LLVMMetadataRef LLVMDIBuilderCreateClassType(LLVMDIBuilderRef Builder,
1519 LLVMMetadataRef Scope, const char *Name, size_t NameLen,
1520 LLVMMetadataRef File, unsigned LineNumber, uint64_t SizeInBits,
1521 uint32_t AlignInBits, uint64_t OffsetInBits, LLVMDIFlags Flags,
1522 LLVMMetadataRef DerivedFrom,
1523 LLVMMetadataRef *Elements, unsigned NumElements,
1524 LLVMMetadataRef VTableHolder, LLVMMetadataRef TemplateParamsNode,
1525 const char *UniqueIdentifier, size_t UniqueIdentifierLen) {
1526 auto Elts = unwrap(Builder)->getOrCreateArray({unwrap(Elements),
1527 NumElements});
1528 return wrap(unwrap(Builder)->createClassType(
1529 unwrapDI<DIScope>(Scope), {Name, NameLen}, unwrapDI<DIFile>(File),
1530 LineNumber, SizeInBits, AlignInBits, OffsetInBits,
1531 map_from_llvmDIFlags(Flags), unwrapDI<DIType>(DerivedFrom), Elts,
1532 /*RunTimeLang=*/0, unwrapDI<DIType>(VTableHolder),
1533 unwrapDI<MDNode>(TemplateParamsNode),
1534 {UniqueIdentifier, UniqueIdentifierLen}));
1535 }
1536
1537 LLVMMetadataRef
LLVMDIBuilderCreateArtificialType(LLVMDIBuilderRef Builder,LLVMMetadataRef Type)1538 LLVMDIBuilderCreateArtificialType(LLVMDIBuilderRef Builder,
1539 LLVMMetadataRef Type) {
1540 return wrap(unwrap(Builder)->createArtificialType(unwrapDI<DIType>(Type)));
1541 }
1542
LLVMGetDINodeTag(LLVMMetadataRef MD)1543 uint16_t LLVMGetDINodeTag(LLVMMetadataRef MD) {
1544 return unwrapDI<DINode>(MD)->getTag();
1545 }
1546
LLVMDITypeGetName(LLVMMetadataRef DType,size_t * Length)1547 const char *LLVMDITypeGetName(LLVMMetadataRef DType, size_t *Length) {
1548 StringRef Str = unwrapDI<DIType>(DType)->getName();
1549 *Length = Str.size();
1550 return Str.data();
1551 }
1552
LLVMDITypeGetSizeInBits(LLVMMetadataRef DType)1553 uint64_t LLVMDITypeGetSizeInBits(LLVMMetadataRef DType) {
1554 return unwrapDI<DIType>(DType)->getSizeInBits();
1555 }
1556
LLVMDITypeGetOffsetInBits(LLVMMetadataRef DType)1557 uint64_t LLVMDITypeGetOffsetInBits(LLVMMetadataRef DType) {
1558 return unwrapDI<DIType>(DType)->getOffsetInBits();
1559 }
1560
LLVMDITypeGetAlignInBits(LLVMMetadataRef DType)1561 uint32_t LLVMDITypeGetAlignInBits(LLVMMetadataRef DType) {
1562 return unwrapDI<DIType>(DType)->getAlignInBits();
1563 }
1564
LLVMDITypeGetLine(LLVMMetadataRef DType)1565 unsigned LLVMDITypeGetLine(LLVMMetadataRef DType) {
1566 return unwrapDI<DIType>(DType)->getLine();
1567 }
1568
LLVMDITypeGetFlags(LLVMMetadataRef DType)1569 LLVMDIFlags LLVMDITypeGetFlags(LLVMMetadataRef DType) {
1570 return map_to_llvmDIFlags(unwrapDI<DIType>(DType)->getFlags());
1571 }
1572
LLVMDIBuilderGetOrCreateTypeArray(LLVMDIBuilderRef Builder,LLVMMetadataRef * Types,size_t Length)1573 LLVMMetadataRef LLVMDIBuilderGetOrCreateTypeArray(LLVMDIBuilderRef Builder,
1574 LLVMMetadataRef *Types,
1575 size_t Length) {
1576 return wrap(
1577 unwrap(Builder)->getOrCreateTypeArray({unwrap(Types), Length}).get());
1578 }
1579
1580 LLVMMetadataRef
LLVMDIBuilderCreateSubroutineType(LLVMDIBuilderRef Builder,LLVMMetadataRef File,LLVMMetadataRef * ParameterTypes,unsigned NumParameterTypes,LLVMDIFlags Flags)1581 LLVMDIBuilderCreateSubroutineType(LLVMDIBuilderRef Builder,
1582 LLVMMetadataRef File,
1583 LLVMMetadataRef *ParameterTypes,
1584 unsigned NumParameterTypes,
1585 LLVMDIFlags Flags) {
1586 auto Elts = unwrap(Builder)->getOrCreateTypeArray({unwrap(ParameterTypes),
1587 NumParameterTypes});
1588 return wrap(unwrap(Builder)->createSubroutineType(
1589 Elts, map_from_llvmDIFlags(Flags)));
1590 }
1591
LLVMDIBuilderCreateExpression(LLVMDIBuilderRef Builder,uint64_t * Addr,size_t Length)1592 LLVMMetadataRef LLVMDIBuilderCreateExpression(LLVMDIBuilderRef Builder,
1593 uint64_t *Addr, size_t Length) {
1594 return wrap(
1595 unwrap(Builder)->createExpression(ArrayRef<uint64_t>(Addr, Length)));
1596 }
1597
1598 LLVMMetadataRef
LLVMDIBuilderCreateConstantValueExpression(LLVMDIBuilderRef Builder,uint64_t Value)1599 LLVMDIBuilderCreateConstantValueExpression(LLVMDIBuilderRef Builder,
1600 uint64_t Value) {
1601 return wrap(unwrap(Builder)->createConstantValueExpression(Value));
1602 }
1603
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)1604 LLVMMetadataRef LLVMDIBuilderCreateGlobalVariableExpression(
1605 LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
1606 size_t NameLen, const char *Linkage, size_t LinkLen, LLVMMetadataRef File,
1607 unsigned LineNo, LLVMMetadataRef Ty, LLVMBool LocalToUnit,
1608 LLVMMetadataRef Expr, LLVMMetadataRef Decl, uint32_t AlignInBits) {
1609 return wrap(unwrap(Builder)->createGlobalVariableExpression(
1610 unwrapDI<DIScope>(Scope), {Name, NameLen}, {Linkage, LinkLen},
1611 unwrapDI<DIFile>(File), LineNo, unwrapDI<DIType>(Ty), LocalToUnit,
1612 true, unwrap<DIExpression>(Expr), unwrapDI<MDNode>(Decl),
1613 nullptr, AlignInBits));
1614 }
1615
LLVMDIGlobalVariableExpressionGetVariable(LLVMMetadataRef GVE)1616 LLVMMetadataRef LLVMDIGlobalVariableExpressionGetVariable(LLVMMetadataRef GVE) {
1617 return wrap(unwrapDI<DIGlobalVariableExpression>(GVE)->getVariable());
1618 }
1619
LLVMDIGlobalVariableExpressionGetExpression(LLVMMetadataRef GVE)1620 LLVMMetadataRef LLVMDIGlobalVariableExpressionGetExpression(
1621 LLVMMetadataRef GVE) {
1622 return wrap(unwrapDI<DIGlobalVariableExpression>(GVE)->getExpression());
1623 }
1624
LLVMDIVariableGetFile(LLVMMetadataRef Var)1625 LLVMMetadataRef LLVMDIVariableGetFile(LLVMMetadataRef Var) {
1626 return wrap(unwrapDI<DIVariable>(Var)->getFile());
1627 }
1628
LLVMDIVariableGetScope(LLVMMetadataRef Var)1629 LLVMMetadataRef LLVMDIVariableGetScope(LLVMMetadataRef Var) {
1630 return wrap(unwrapDI<DIVariable>(Var)->getScope());
1631 }
1632
LLVMDIVariableGetLine(LLVMMetadataRef Var)1633 unsigned LLVMDIVariableGetLine(LLVMMetadataRef Var) {
1634 return unwrapDI<DIVariable>(Var)->getLine();
1635 }
1636
LLVMTemporaryMDNode(LLVMContextRef Ctx,LLVMMetadataRef * Data,size_t Count)1637 LLVMMetadataRef LLVMTemporaryMDNode(LLVMContextRef Ctx, LLVMMetadataRef *Data,
1638 size_t Count) {
1639 return wrap(
1640 MDTuple::getTemporary(*unwrap(Ctx), {unwrap(Data), Count}).release());
1641 }
1642
LLVMDisposeTemporaryMDNode(LLVMMetadataRef TempNode)1643 void LLVMDisposeTemporaryMDNode(LLVMMetadataRef TempNode) {
1644 MDNode::deleteTemporary(unwrapDI<MDNode>(TempNode));
1645 }
1646
LLVMMetadataReplaceAllUsesWith(LLVMMetadataRef TargetMetadata,LLVMMetadataRef Replacement)1647 void LLVMMetadataReplaceAllUsesWith(LLVMMetadataRef TargetMetadata,
1648 LLVMMetadataRef Replacement) {
1649 auto *Node = unwrapDI<MDNode>(TargetMetadata);
1650 Node->replaceAllUsesWith(unwrap(Replacement));
1651 MDNode::deleteTemporary(Node);
1652 }
1653
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)1654 LLVMMetadataRef LLVMDIBuilderCreateTempGlobalVariableFwdDecl(
1655 LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
1656 size_t NameLen, const char *Linkage, size_t LnkLen, LLVMMetadataRef File,
1657 unsigned LineNo, LLVMMetadataRef Ty, LLVMBool LocalToUnit,
1658 LLVMMetadataRef Decl, uint32_t AlignInBits) {
1659 return wrap(unwrap(Builder)->createTempGlobalVariableFwdDecl(
1660 unwrapDI<DIScope>(Scope), {Name, NameLen}, {Linkage, LnkLen},
1661 unwrapDI<DIFile>(File), LineNo, unwrapDI<DIType>(Ty), LocalToUnit,
1662 unwrapDI<MDNode>(Decl), nullptr, AlignInBits));
1663 }
1664
LLVMDIBuilderInsertDeclareRecordBefore(LLVMDIBuilderRef Builder,LLVMValueRef Storage,LLVMMetadataRef VarInfo,LLVMMetadataRef Expr,LLVMMetadataRef DL,LLVMValueRef Instr)1665 LLVMDbgRecordRef LLVMDIBuilderInsertDeclareRecordBefore(
1666 LLVMDIBuilderRef Builder, LLVMValueRef Storage, LLVMMetadataRef VarInfo,
1667 LLVMMetadataRef Expr, LLVMMetadataRef DL, LLVMValueRef Instr) {
1668 DbgInstPtr DbgInst = unwrap(Builder)->insertDeclare(
1669 unwrap(Storage), unwrap<DILocalVariable>(VarInfo),
1670 unwrap<DIExpression>(Expr), unwrap<DILocation>(DL),
1671 unwrap<Instruction>(Instr));
1672 // This assert will fail if the module is in the old debug info format.
1673 // This function should only be called if the module is in the new
1674 // debug info format.
1675 // See https://llvm.org/docs/RemoveDIsDebugInfo.html#c-api-changes,
1676 // LLVMIsNewDbgInfoFormat, and LLVMSetIsNewDbgInfoFormat for more info.
1677 assert(isa<DbgRecord *>(DbgInst) &&
1678 "Function unexpectedly in old debug info format");
1679 return wrap(cast<DbgRecord *>(DbgInst));
1680 }
1681
LLVMDIBuilderInsertDeclareRecordAtEnd(LLVMDIBuilderRef Builder,LLVMValueRef Storage,LLVMMetadataRef VarInfo,LLVMMetadataRef Expr,LLVMMetadataRef DL,LLVMBasicBlockRef Block)1682 LLVMDbgRecordRef LLVMDIBuilderInsertDeclareRecordAtEnd(
1683 LLVMDIBuilderRef Builder, LLVMValueRef Storage, LLVMMetadataRef VarInfo,
1684 LLVMMetadataRef Expr, LLVMMetadataRef DL, LLVMBasicBlockRef Block) {
1685 DbgInstPtr DbgInst = unwrap(Builder)->insertDeclare(
1686 unwrap(Storage), unwrap<DILocalVariable>(VarInfo),
1687 unwrap<DIExpression>(Expr), unwrap<DILocation>(DL), unwrap(Block));
1688 // This assert will fail if the module is in the old debug info format.
1689 // This function should only be called if the module is in the new
1690 // debug info format.
1691 // See https://llvm.org/docs/RemoveDIsDebugInfo.html#c-api-changes,
1692 // LLVMIsNewDbgInfoFormat, and LLVMSetIsNewDbgInfoFormat for more info.
1693 assert(isa<DbgRecord *>(DbgInst) &&
1694 "Function unexpectedly in old debug info format");
1695 return wrap(cast<DbgRecord *>(DbgInst));
1696 }
1697
LLVMDIBuilderInsertDbgValueRecordBefore(LLVMDIBuilderRef Builder,LLVMValueRef Val,LLVMMetadataRef VarInfo,LLVMMetadataRef Expr,LLVMMetadataRef DebugLoc,LLVMValueRef Instr)1698 LLVMDbgRecordRef LLVMDIBuilderInsertDbgValueRecordBefore(
1699 LLVMDIBuilderRef Builder, LLVMValueRef Val, LLVMMetadataRef VarInfo,
1700 LLVMMetadataRef Expr, LLVMMetadataRef DebugLoc, LLVMValueRef Instr) {
1701 DbgInstPtr DbgInst = unwrap(Builder)->insertDbgValueIntrinsic(
1702 unwrap(Val), unwrap<DILocalVariable>(VarInfo), unwrap<DIExpression>(Expr),
1703 unwrap<DILocation>(DebugLoc), unwrap<Instruction>(Instr));
1704 // This assert will fail if the module is in the old debug info format.
1705 // This function should only be called if the module is in the new
1706 // debug info format.
1707 // See https://llvm.org/docs/RemoveDIsDebugInfo.html#c-api-changes,
1708 // LLVMIsNewDbgInfoFormat, and LLVMSetIsNewDbgInfoFormat for more info.
1709 assert(isa<DbgRecord *>(DbgInst) &&
1710 "Function unexpectedly in old debug info format");
1711 return wrap(cast<DbgRecord *>(DbgInst));
1712 }
1713
LLVMDIBuilderInsertDbgValueRecordAtEnd(LLVMDIBuilderRef Builder,LLVMValueRef Val,LLVMMetadataRef VarInfo,LLVMMetadataRef Expr,LLVMMetadataRef DebugLoc,LLVMBasicBlockRef Block)1714 LLVMDbgRecordRef LLVMDIBuilderInsertDbgValueRecordAtEnd(
1715 LLVMDIBuilderRef Builder, LLVMValueRef Val, LLVMMetadataRef VarInfo,
1716 LLVMMetadataRef Expr, LLVMMetadataRef DebugLoc, LLVMBasicBlockRef Block) {
1717 DbgInstPtr DbgInst = unwrap(Builder)->insertDbgValueIntrinsic(
1718 unwrap(Val), unwrap<DILocalVariable>(VarInfo), unwrap<DIExpression>(Expr),
1719 unwrap<DILocation>(DebugLoc), unwrap(Block));
1720 // This assert will fail if the module is in the old debug info format.
1721 // This function should only be called if the module is in the new
1722 // debug info format.
1723 // See https://llvm.org/docs/RemoveDIsDebugInfo.html#c-api-changes,
1724 // LLVMIsNewDbgInfoFormat, and LLVMSetIsNewDbgInfoFormat for more info.
1725 assert(isa<DbgRecord *>(DbgInst) &&
1726 "Function unexpectedly in old debug info format");
1727 return wrap(cast<DbgRecord *>(DbgInst));
1728 }
1729
LLVMDIBuilderCreateAutoVariable(LLVMDIBuilderRef Builder,LLVMMetadataRef Scope,const char * Name,size_t NameLen,LLVMMetadataRef File,unsigned LineNo,LLVMMetadataRef Ty,LLVMBool AlwaysPreserve,LLVMDIFlags Flags,uint32_t AlignInBits)1730 LLVMMetadataRef LLVMDIBuilderCreateAutoVariable(
1731 LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
1732 size_t NameLen, LLVMMetadataRef File, unsigned LineNo, LLVMMetadataRef Ty,
1733 LLVMBool AlwaysPreserve, LLVMDIFlags Flags, uint32_t AlignInBits) {
1734 return wrap(unwrap(Builder)->createAutoVariable(
1735 unwrap<DIScope>(Scope), {Name, NameLen}, unwrap<DIFile>(File),
1736 LineNo, unwrap<DIType>(Ty), AlwaysPreserve,
1737 map_from_llvmDIFlags(Flags), AlignInBits));
1738 }
1739
LLVMDIBuilderCreateParameterVariable(LLVMDIBuilderRef Builder,LLVMMetadataRef Scope,const char * Name,size_t NameLen,unsigned ArgNo,LLVMMetadataRef File,unsigned LineNo,LLVMMetadataRef Ty,LLVMBool AlwaysPreserve,LLVMDIFlags Flags)1740 LLVMMetadataRef LLVMDIBuilderCreateParameterVariable(
1741 LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
1742 size_t NameLen, unsigned ArgNo, LLVMMetadataRef File, unsigned LineNo,
1743 LLVMMetadataRef Ty, LLVMBool AlwaysPreserve, LLVMDIFlags Flags) {
1744 return wrap(unwrap(Builder)->createParameterVariable(
1745 unwrap<DIScope>(Scope), {Name, NameLen}, ArgNo, unwrap<DIFile>(File),
1746 LineNo, unwrap<DIType>(Ty), AlwaysPreserve,
1747 map_from_llvmDIFlags(Flags)));
1748 }
1749
LLVMDIBuilderGetOrCreateSubrange(LLVMDIBuilderRef Builder,int64_t Lo,int64_t Count)1750 LLVMMetadataRef LLVMDIBuilderGetOrCreateSubrange(LLVMDIBuilderRef Builder,
1751 int64_t Lo, int64_t Count) {
1752 return wrap(unwrap(Builder)->getOrCreateSubrange(Lo, Count));
1753 }
1754
LLVMDIBuilderGetOrCreateArray(LLVMDIBuilderRef Builder,LLVMMetadataRef * Data,size_t Length)1755 LLVMMetadataRef LLVMDIBuilderGetOrCreateArray(LLVMDIBuilderRef Builder,
1756 LLVMMetadataRef *Data,
1757 size_t Length) {
1758 Metadata **DataValue = unwrap(Data);
1759 return wrap(unwrap(Builder)->getOrCreateArray({DataValue, Length}).get());
1760 }
1761
LLVMGetSubprogram(LLVMValueRef Func)1762 LLVMMetadataRef LLVMGetSubprogram(LLVMValueRef Func) {
1763 return wrap(unwrap<Function>(Func)->getSubprogram());
1764 }
1765
LLVMSetSubprogram(LLVMValueRef Func,LLVMMetadataRef SP)1766 void LLVMSetSubprogram(LLVMValueRef Func, LLVMMetadataRef SP) {
1767 unwrap<Function>(Func)->setSubprogram(unwrap<DISubprogram>(SP));
1768 }
1769
LLVMDISubprogramGetLine(LLVMMetadataRef Subprogram)1770 unsigned LLVMDISubprogramGetLine(LLVMMetadataRef Subprogram) {
1771 return unwrapDI<DISubprogram>(Subprogram)->getLine();
1772 }
1773
LLVMInstructionGetDebugLoc(LLVMValueRef Inst)1774 LLVMMetadataRef LLVMInstructionGetDebugLoc(LLVMValueRef Inst) {
1775 return wrap(unwrap<Instruction>(Inst)->getDebugLoc().getAsMDNode());
1776 }
1777
LLVMInstructionSetDebugLoc(LLVMValueRef Inst,LLVMMetadataRef Loc)1778 void LLVMInstructionSetDebugLoc(LLVMValueRef Inst, LLVMMetadataRef Loc) {
1779 if (Loc)
1780 unwrap<Instruction>(Inst)->setDebugLoc(DebugLoc(unwrap<MDNode>(Loc)));
1781 else
1782 unwrap<Instruction>(Inst)->setDebugLoc(DebugLoc());
1783 }
1784
LLVMGetMetadataKind(LLVMMetadataRef Metadata)1785 LLVMMetadataKind LLVMGetMetadataKind(LLVMMetadataRef Metadata) {
1786 switch(unwrap(Metadata)->getMetadataID()) {
1787 #define HANDLE_METADATA_LEAF(CLASS) \
1788 case Metadata::CLASS##Kind: \
1789 return (LLVMMetadataKind)LLVM##CLASS##MetadataKind;
1790 #include "llvm/IR/Metadata.def"
1791 default:
1792 return (LLVMMetadataKind)LLVMGenericDINodeMetadataKind;
1793 }
1794 }
1795
getAssignmentInsts(DIAssignID * ID)1796 AssignmentInstRange at::getAssignmentInsts(DIAssignID *ID) {
1797 assert(ID && "Expected non-null ID");
1798 LLVMContext &Ctx = ID->getContext();
1799 auto &Map = Ctx.pImpl->AssignmentIDToInstrs;
1800
1801 auto MapIt = Map.find(ID);
1802 if (MapIt == Map.end())
1803 return make_range(nullptr, nullptr);
1804
1805 return make_range(MapIt->second.begin(), MapIt->second.end());
1806 }
1807
getAssignmentMarkers(DIAssignID * ID)1808 AssignmentMarkerRange at::getAssignmentMarkers(DIAssignID *ID) {
1809 assert(ID && "Expected non-null ID");
1810 LLVMContext &Ctx = ID->getContext();
1811
1812 auto *IDAsValue = MetadataAsValue::getIfExists(Ctx, ID);
1813
1814 // The ID is only used wrapped in MetadataAsValue(ID), so lets check that
1815 // one of those already exists first.
1816 if (!IDAsValue)
1817 return make_range(Value::user_iterator(), Value::user_iterator());
1818
1819 return make_range(IDAsValue->user_begin(), IDAsValue->user_end());
1820 }
1821
deleteAssignmentMarkers(const Instruction * Inst)1822 void at::deleteAssignmentMarkers(const Instruction *Inst) {
1823 auto Range = getAssignmentMarkers(Inst);
1824 SmallVector<DbgVariableRecord *> DVRAssigns = getDVRAssignmentMarkers(Inst);
1825 if (Range.empty() && DVRAssigns.empty())
1826 return;
1827 SmallVector<DbgAssignIntrinsic *> ToDelete(Range.begin(), Range.end());
1828 for (auto *DAI : ToDelete)
1829 DAI->eraseFromParent();
1830 for (auto *DVR : DVRAssigns)
1831 DVR->eraseFromParent();
1832 }
1833
RAUW(DIAssignID * Old,DIAssignID * New)1834 void at::RAUW(DIAssignID *Old, DIAssignID *New) {
1835 // Replace attachments.
1836 AssignmentInstRange InstRange = getAssignmentInsts(Old);
1837 // Use intermediate storage for the instruction ptrs because the
1838 // getAssignmentInsts range iterators will be invalidated by adding and
1839 // removing DIAssignID attachments.
1840 SmallVector<Instruction *> InstVec(InstRange.begin(), InstRange.end());
1841 for (auto *I : InstVec)
1842 I->setMetadata(LLVMContext::MD_DIAssignID, New);
1843
1844 Old->replaceAllUsesWith(New);
1845 }
1846
deleteAll(Function * F)1847 void at::deleteAll(Function *F) {
1848 SmallVector<DbgAssignIntrinsic *, 12> ToDelete;
1849 SmallVector<DbgVariableRecord *, 12> DPToDelete;
1850 for (BasicBlock &BB : *F) {
1851 for (Instruction &I : BB) {
1852 for (DbgVariableRecord &DVR : filterDbgVars(I.getDbgRecordRange()))
1853 if (DVR.isDbgAssign())
1854 DPToDelete.push_back(&DVR);
1855 if (auto *DAI = dyn_cast<DbgAssignIntrinsic>(&I))
1856 ToDelete.push_back(DAI);
1857 else
1858 I.setMetadata(LLVMContext::MD_DIAssignID, nullptr);
1859 }
1860 }
1861 for (auto *DAI : ToDelete)
1862 DAI->eraseFromParent();
1863 for (auto *DVR : DPToDelete)
1864 DVR->eraseFromParent();
1865 }
1866
1867 /// FIXME: Remove this wrapper function and call
1868 /// DIExpression::calculateFragmentIntersect directly.
1869 template <typename T>
calculateFragmentIntersectImpl(const DataLayout & DL,const Value * Dest,uint64_t SliceOffsetInBits,uint64_t SliceSizeInBits,const T * AssignRecord,std::optional<DIExpression::FragmentInfo> & Result)1870 bool calculateFragmentIntersectImpl(
1871 const DataLayout &DL, const Value *Dest, uint64_t SliceOffsetInBits,
1872 uint64_t SliceSizeInBits, const T *AssignRecord,
1873 std::optional<DIExpression::FragmentInfo> &Result) {
1874 // No overlap if this DbgRecord describes a killed location.
1875 if (AssignRecord->isKillAddress())
1876 return false;
1877
1878 int64_t AddrOffsetInBits;
1879 {
1880 int64_t AddrOffsetInBytes;
1881 SmallVector<uint64_t> PostOffsetOps; //< Unused.
1882 // Bail if we can't find a constant offset (or none) in the expression.
1883 if (!AssignRecord->getAddressExpression()->extractLeadingOffset(
1884 AddrOffsetInBytes, PostOffsetOps))
1885 return false;
1886 AddrOffsetInBits = AddrOffsetInBytes * 8;
1887 }
1888
1889 Value *Addr = AssignRecord->getAddress();
1890 // FIXME: It may not always be zero.
1891 int64_t BitExtractOffsetInBits = 0;
1892 DIExpression::FragmentInfo VarFrag =
1893 AssignRecord->getFragmentOrEntireVariable();
1894
1895 int64_t OffsetFromLocationInBits; //< Unused.
1896 return DIExpression::calculateFragmentIntersect(
1897 DL, Dest, SliceOffsetInBits, SliceSizeInBits, Addr, AddrOffsetInBits,
1898 BitExtractOffsetInBits, VarFrag, Result, OffsetFromLocationInBits);
1899 }
1900
1901 /// FIXME: Remove this wrapper function and call
1902 /// DIExpression::calculateFragmentIntersect directly.
calculateFragmentIntersect(const DataLayout & DL,const Value * Dest,uint64_t SliceOffsetInBits,uint64_t SliceSizeInBits,const DbgAssignIntrinsic * DbgAssign,std::optional<DIExpression::FragmentInfo> & Result)1903 bool at::calculateFragmentIntersect(
1904 const DataLayout &DL, const Value *Dest, uint64_t SliceOffsetInBits,
1905 uint64_t SliceSizeInBits, const DbgAssignIntrinsic *DbgAssign,
1906 std::optional<DIExpression::FragmentInfo> &Result) {
1907 return calculateFragmentIntersectImpl(DL, Dest, SliceOffsetInBits,
1908 SliceSizeInBits, DbgAssign, Result);
1909 }
1910
1911 /// FIXME: Remove this wrapper function and call
1912 /// DIExpression::calculateFragmentIntersect directly.
calculateFragmentIntersect(const DataLayout & DL,const Value * Dest,uint64_t SliceOffsetInBits,uint64_t SliceSizeInBits,const DbgVariableRecord * DVRAssign,std::optional<DIExpression::FragmentInfo> & Result)1913 bool at::calculateFragmentIntersect(
1914 const DataLayout &DL, const Value *Dest, uint64_t SliceOffsetInBits,
1915 uint64_t SliceSizeInBits, const DbgVariableRecord *DVRAssign,
1916 std::optional<DIExpression::FragmentInfo> &Result) {
1917 return calculateFragmentIntersectImpl(DL, Dest, SliceOffsetInBits,
1918 SliceSizeInBits, DVRAssign, Result);
1919 }
1920
1921 /// Update inlined instructions' DIAssignID metadata. We need to do this
1922 /// otherwise a function inlined more than once into the same function
1923 /// will cause DIAssignID to be shared by many instructions.
remapAssignID(DenseMap<DIAssignID *,DIAssignID * > & Map,Instruction & I)1924 void at::remapAssignID(DenseMap<DIAssignID *, DIAssignID *> &Map,
1925 Instruction &I) {
1926 auto GetNewID = [&Map](Metadata *Old) {
1927 DIAssignID *OldID = cast<DIAssignID>(Old);
1928 if (DIAssignID *NewID = Map.lookup(OldID))
1929 return NewID;
1930 DIAssignID *NewID = DIAssignID::getDistinct(OldID->getContext());
1931 Map[OldID] = NewID;
1932 return NewID;
1933 };
1934 // If we find a DIAssignID attachment or use, replace it with a new version.
1935 for (DbgVariableRecord &DVR : filterDbgVars(I.getDbgRecordRange())) {
1936 if (DVR.isDbgAssign())
1937 DVR.setAssignId(GetNewID(DVR.getAssignID()));
1938 }
1939 if (auto *ID = I.getMetadata(LLVMContext::MD_DIAssignID))
1940 I.setMetadata(LLVMContext::MD_DIAssignID, GetNewID(ID));
1941 else if (auto *DAI = dyn_cast<DbgAssignIntrinsic>(&I))
1942 DAI->setAssignId(GetNewID(DAI->getAssignID()));
1943 }
1944
1945 /// Collect constant properies (base, size, offset) of \p StoreDest.
1946 /// Return std::nullopt if any properties are not constants or the
1947 /// offset from the base pointer is negative.
1948 static std::optional<AssignmentInfo>
getAssignmentInfoImpl(const DataLayout & DL,const Value * StoreDest,TypeSize SizeInBits)1949 getAssignmentInfoImpl(const DataLayout &DL, const Value *StoreDest,
1950 TypeSize SizeInBits) {
1951 if (SizeInBits.isScalable())
1952 return std::nullopt;
1953 APInt GEPOffset(DL.getIndexTypeSizeInBits(StoreDest->getType()), 0);
1954 const Value *Base = StoreDest->stripAndAccumulateConstantOffsets(
1955 DL, GEPOffset, /*AllowNonInbounds*/ true);
1956
1957 if (GEPOffset.isNegative())
1958 return std::nullopt;
1959
1960 uint64_t OffsetInBytes = GEPOffset.getLimitedValue();
1961 // Check for overflow.
1962 if (OffsetInBytes == UINT64_MAX)
1963 return std::nullopt;
1964 if (const auto *Alloca = dyn_cast<AllocaInst>(Base))
1965 return AssignmentInfo(DL, Alloca, OffsetInBytes * 8, SizeInBits);
1966 return std::nullopt;
1967 }
1968
getAssignmentInfo(const DataLayout & DL,const MemIntrinsic * I)1969 std::optional<AssignmentInfo> at::getAssignmentInfo(const DataLayout &DL,
1970 const MemIntrinsic *I) {
1971 const Value *StoreDest = I->getRawDest();
1972 // Assume 8 bit bytes.
1973 auto *ConstLengthInBytes = dyn_cast<ConstantInt>(I->getLength());
1974 if (!ConstLengthInBytes)
1975 // We can't use a non-const size, bail.
1976 return std::nullopt;
1977 uint64_t SizeInBits = 8 * ConstLengthInBytes->getZExtValue();
1978 return getAssignmentInfoImpl(DL, StoreDest, TypeSize::getFixed(SizeInBits));
1979 }
1980
getAssignmentInfo(const DataLayout & DL,const StoreInst * SI)1981 std::optional<AssignmentInfo> at::getAssignmentInfo(const DataLayout &DL,
1982 const StoreInst *SI) {
1983 TypeSize SizeInBits = DL.getTypeSizeInBits(SI->getValueOperand()->getType());
1984 return getAssignmentInfoImpl(DL, SI->getPointerOperand(), SizeInBits);
1985 }
1986
getAssignmentInfo(const DataLayout & DL,const AllocaInst * AI)1987 std::optional<AssignmentInfo> at::getAssignmentInfo(const DataLayout &DL,
1988 const AllocaInst *AI) {
1989 TypeSize SizeInBits = DL.getTypeSizeInBits(AI->getAllocatedType());
1990 return getAssignmentInfoImpl(DL, AI, SizeInBits);
1991 }
1992
1993 /// Returns nullptr if the assignment shouldn't be attributed to this variable.
emitDbgAssign(AssignmentInfo Info,Value * Val,Value * Dest,Instruction & StoreLikeInst,const VarRecord & VarRec,DIBuilder & DIB)1994 static void emitDbgAssign(AssignmentInfo Info, Value *Val, Value *Dest,
1995 Instruction &StoreLikeInst, const VarRecord &VarRec,
1996 DIBuilder &DIB) {
1997 auto *ID = StoreLikeInst.getMetadata(LLVMContext::MD_DIAssignID);
1998 assert(ID && "Store instruction must have DIAssignID metadata");
1999 (void)ID;
2000
2001 const uint64_t StoreStartBit = Info.OffsetInBits;
2002 const uint64_t StoreEndBit = Info.OffsetInBits + Info.SizeInBits;
2003
2004 uint64_t FragStartBit = StoreStartBit;
2005 uint64_t FragEndBit = StoreEndBit;
2006
2007 bool StoreToWholeVariable = Info.StoreToWholeAlloca;
2008 if (auto Size = VarRec.Var->getSizeInBits()) {
2009 // NOTE: trackAssignments doesn't understand base expressions yet, so all
2010 // variables that reach here are guaranteed to start at offset 0 in the
2011 // alloca.
2012 const uint64_t VarStartBit = 0;
2013 const uint64_t VarEndBit = *Size;
2014
2015 // FIXME: trim FragStartBit when nonzero VarStartBit is supported.
2016 FragEndBit = std::min(FragEndBit, VarEndBit);
2017
2018 // Discard stores to bits outside this variable.
2019 if (FragStartBit >= FragEndBit)
2020 return;
2021
2022 StoreToWholeVariable = FragStartBit <= VarStartBit && FragEndBit >= *Size;
2023 }
2024
2025 DIExpression *Expr =
2026 DIExpression::get(StoreLikeInst.getContext(), std::nullopt);
2027 if (!StoreToWholeVariable) {
2028 auto R = DIExpression::createFragmentExpression(Expr, FragStartBit,
2029 FragEndBit - FragStartBit);
2030 assert(R.has_value() && "failed to create fragment expression");
2031 Expr = *R;
2032 }
2033 DIExpression *AddrExpr =
2034 DIExpression::get(StoreLikeInst.getContext(), std::nullopt);
2035 if (StoreLikeInst.getParent()->IsNewDbgInfoFormat) {
2036 auto *Assign = DbgVariableRecord::createLinkedDVRAssign(
2037 &StoreLikeInst, Val, VarRec.Var, Expr, Dest, AddrExpr, VarRec.DL);
2038 (void)Assign;
2039 LLVM_DEBUG(if (Assign) errs() << " > INSERT: " << *Assign << "\n");
2040 return;
2041 }
2042 auto Assign = DIB.insertDbgAssign(&StoreLikeInst, Val, VarRec.Var, Expr, Dest,
2043 AddrExpr, VarRec.DL);
2044 (void)Assign;
2045 LLVM_DEBUG(if (!Assign.isNull()) {
2046 if (Assign.is<DbgRecord *>())
2047 errs() << " > INSERT: " << *Assign.get<DbgRecord *>() << "\n";
2048 else
2049 errs() << " > INSERT: " << *Assign.get<Instruction *>() << "\n";
2050 });
2051 }
2052
2053 #undef DEBUG_TYPE // Silence redefinition warning (from ConstantsContext.h).
2054 #define DEBUG_TYPE "assignment-tracking"
2055
trackAssignments(Function::iterator Start,Function::iterator End,const StorageToVarsMap & Vars,const DataLayout & DL,bool DebugPrints)2056 void at::trackAssignments(Function::iterator Start, Function::iterator End,
2057 const StorageToVarsMap &Vars, const DataLayout &DL,
2058 bool DebugPrints) {
2059 // Early-exit if there are no interesting variables.
2060 if (Vars.empty())
2061 return;
2062
2063 auto &Ctx = Start->getContext();
2064 auto &Module = *Start->getModule();
2065
2066 // Undef type doesn't matter, so long as it isn't void. Let's just use i1.
2067 auto *Undef = UndefValue::get(Type::getInt1Ty(Ctx));
2068 DIBuilder DIB(Module, /*AllowUnresolved*/ false);
2069
2070 // Scan the instructions looking for stores to local variables' storage.
2071 LLVM_DEBUG(errs() << "# Scanning instructions\n");
2072 for (auto BBI = Start; BBI != End; ++BBI) {
2073 for (Instruction &I : *BBI) {
2074
2075 std::optional<AssignmentInfo> Info;
2076 Value *ValueComponent = nullptr;
2077 Value *DestComponent = nullptr;
2078 if (auto *AI = dyn_cast<AllocaInst>(&I)) {
2079 // We want to track the variable's stack home from its alloca's
2080 // position onwards so we treat it as an assignment (where the stored
2081 // value is Undef).
2082 Info = getAssignmentInfo(DL, AI);
2083 ValueComponent = Undef;
2084 DestComponent = AI;
2085 } else if (auto *SI = dyn_cast<StoreInst>(&I)) {
2086 Info = getAssignmentInfo(DL, SI);
2087 ValueComponent = SI->getValueOperand();
2088 DestComponent = SI->getPointerOperand();
2089 } else if (auto *MI = dyn_cast<MemTransferInst>(&I)) {
2090 Info = getAssignmentInfo(DL, MI);
2091 // May not be able to represent this value easily.
2092 ValueComponent = Undef;
2093 DestComponent = MI->getOperand(0);
2094 } else if (auto *MI = dyn_cast<MemSetInst>(&I)) {
2095 Info = getAssignmentInfo(DL, MI);
2096 // If we're zero-initing we can state the assigned value is zero,
2097 // otherwise use undef.
2098 auto *ConstValue = dyn_cast<ConstantInt>(MI->getOperand(1));
2099 if (ConstValue && ConstValue->isZero())
2100 ValueComponent = ConstValue;
2101 else
2102 ValueComponent = Undef;
2103 DestComponent = MI->getOperand(0);
2104 } else {
2105 // Not a store-like instruction.
2106 continue;
2107 }
2108
2109 assert(ValueComponent && DestComponent);
2110 LLVM_DEBUG(errs() << "SCAN: Found store-like: " << I << "\n");
2111
2112 // Check if getAssignmentInfo failed to understand this store.
2113 if (!Info.has_value()) {
2114 LLVM_DEBUG(
2115 errs()
2116 << " | SKIP: Untrackable store (e.g. through non-const gep)\n");
2117 continue;
2118 }
2119 LLVM_DEBUG(errs() << " | BASE: " << *Info->Base << "\n");
2120
2121 // Check if the store destination is a local variable with debug info.
2122 auto LocalIt = Vars.find(Info->Base);
2123 if (LocalIt == Vars.end()) {
2124 LLVM_DEBUG(
2125 errs()
2126 << " | SKIP: Base address not associated with local variable\n");
2127 continue;
2128 }
2129
2130 DIAssignID *ID =
2131 cast_or_null<DIAssignID>(I.getMetadata(LLVMContext::MD_DIAssignID));
2132 if (!ID) {
2133 ID = DIAssignID::getDistinct(Ctx);
2134 I.setMetadata(LLVMContext::MD_DIAssignID, ID);
2135 }
2136
2137 for (const VarRecord &R : LocalIt->second)
2138 emitDbgAssign(*Info, ValueComponent, DestComponent, I, R, DIB);
2139 }
2140 }
2141 }
2142
runOnFunction(Function & F)2143 bool AssignmentTrackingPass::runOnFunction(Function &F) {
2144 // No value in assignment tracking without optimisations.
2145 if (F.hasFnAttribute(Attribute::OptimizeNone))
2146 return /*Changed*/ false;
2147
2148 bool Changed = false;
2149 auto *DL = &F.getDataLayout();
2150 // Collect a map of {backing storage : dbg.declares} (currently "backing
2151 // storage" is limited to Allocas). We'll use this to find dbg.declares to
2152 // delete after running `trackAssignments`.
2153 DenseMap<const AllocaInst *, SmallPtrSet<DbgDeclareInst *, 2>> DbgDeclares;
2154 DenseMap<const AllocaInst *, SmallPtrSet<DbgVariableRecord *, 2>> DVRDeclares;
2155 // Create another similar map of {storage : variables} that we'll pass to
2156 // trackAssignments.
2157 StorageToVarsMap Vars;
2158 auto ProcessDeclare = [&](auto *Declare, auto &DeclareList) {
2159 // FIXME: trackAssignments doesn't let you specify any modifiers to the
2160 // variable (e.g. fragment) or location (e.g. offset), so we have to
2161 // leave dbg.declares with non-empty expressions in place.
2162 if (Declare->getExpression()->getNumElements() != 0)
2163 return;
2164 if (!Declare->getAddress())
2165 return;
2166 if (AllocaInst *Alloca =
2167 dyn_cast<AllocaInst>(Declare->getAddress()->stripPointerCasts())) {
2168 // FIXME: Skip VLAs for now (let these variables use dbg.declares).
2169 if (!Alloca->isStaticAlloca())
2170 return;
2171 // Similarly, skip scalable vectors (use dbg.declares instead).
2172 if (auto Sz = Alloca->getAllocationSize(*DL); Sz && Sz->isScalable())
2173 return;
2174 DeclareList[Alloca].insert(Declare);
2175 Vars[Alloca].insert(VarRecord(Declare));
2176 }
2177 };
2178 for (auto &BB : F) {
2179 for (auto &I : BB) {
2180 for (DbgVariableRecord &DVR : filterDbgVars(I.getDbgRecordRange())) {
2181 if (DVR.isDbgDeclare())
2182 ProcessDeclare(&DVR, DVRDeclares);
2183 }
2184 if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(&I))
2185 ProcessDeclare(DDI, DbgDeclares);
2186 }
2187 }
2188
2189 // FIXME: Locals can be backed by caller allocas (sret, byval).
2190 // Note: trackAssignments doesn't respect dbg.declare's IR positions (as it
2191 // doesn't "understand" dbg.declares). However, this doesn't appear to break
2192 // any rules given this description of dbg.declare from
2193 // llvm/docs/SourceLevelDebugging.rst:
2194 //
2195 // It is not control-dependent, meaning that if a call to llvm.dbg.declare
2196 // exists and has a valid location argument, that address is considered to
2197 // be the true home of the variable across its entire lifetime.
2198 trackAssignments(F.begin(), F.end(), Vars, *DL);
2199
2200 // Delete dbg.declares for variables now tracked with assignment tracking.
2201 auto DeleteSubsumedDeclare = [&](const auto &Markers, auto &Declares) {
2202 (void)Markers;
2203 for (auto *Declare : Declares) {
2204 // Assert that the alloca that Declare uses is now linked to a dbg.assign
2205 // describing the same variable (i.e. check that this dbg.declare has
2206 // been replaced by a dbg.assign). Use DebugVariableAggregate to Discard
2207 // the fragment part because trackAssignments may alter the
2208 // fragment. e.g. if the alloca is smaller than the variable, then
2209 // trackAssignments will create an alloca-sized fragment for the
2210 // dbg.assign.
2211 assert(llvm::any_of(Markers, [Declare](auto *Assign) {
2212 return DebugVariableAggregate(Assign) ==
2213 DebugVariableAggregate(Declare);
2214 }));
2215 // Delete Declare because the variable location is now tracked using
2216 // assignment tracking.
2217 Declare->eraseFromParent();
2218 Changed = true;
2219 }
2220 };
2221 for (auto &P : DbgDeclares)
2222 DeleteSubsumedDeclare(at::getAssignmentMarkers(P.first), P.second);
2223 for (auto &P : DVRDeclares)
2224 DeleteSubsumedDeclare(at::getDVRAssignmentMarkers(P.first), P.second);
2225 return Changed;
2226 }
2227
2228 static const char *AssignmentTrackingModuleFlag =
2229 "debug-info-assignment-tracking";
2230
setAssignmentTrackingModuleFlag(Module & M)2231 static void setAssignmentTrackingModuleFlag(Module &M) {
2232 M.setModuleFlag(Module::ModFlagBehavior::Max, AssignmentTrackingModuleFlag,
2233 ConstantAsMetadata::get(
2234 ConstantInt::get(Type::getInt1Ty(M.getContext()), 1)));
2235 }
2236
getAssignmentTrackingModuleFlag(const Module & M)2237 static bool getAssignmentTrackingModuleFlag(const Module &M) {
2238 Metadata *Value = M.getModuleFlag(AssignmentTrackingModuleFlag);
2239 return Value && !cast<ConstantAsMetadata>(Value)->getValue()->isZeroValue();
2240 }
2241
isAssignmentTrackingEnabled(const Module & M)2242 bool llvm::isAssignmentTrackingEnabled(const Module &M) {
2243 return getAssignmentTrackingModuleFlag(M);
2244 }
2245
run(Function & F,FunctionAnalysisManager & AM)2246 PreservedAnalyses AssignmentTrackingPass::run(Function &F,
2247 FunctionAnalysisManager &AM) {
2248 if (!runOnFunction(F))
2249 return PreservedAnalyses::all();
2250
2251 // Record that this module uses assignment tracking. It doesn't matter that
2252 // some functons in the module may not use it - the debug info in those
2253 // functions will still be handled properly.
2254 setAssignmentTrackingModuleFlag(*F.getParent());
2255
2256 // Q: Can we return a less conservative set than just CFGAnalyses? Can we
2257 // return PreservedAnalyses::all()?
2258 PreservedAnalyses PA;
2259 PA.preserveSet<CFGAnalyses>();
2260 return PA;
2261 }
2262
run(Module & M,ModuleAnalysisManager & AM)2263 PreservedAnalyses AssignmentTrackingPass::run(Module &M,
2264 ModuleAnalysisManager &AM) {
2265 bool Changed = false;
2266 for (auto &F : M)
2267 Changed |= runOnFunction(F);
2268
2269 if (!Changed)
2270 return PreservedAnalyses::all();
2271
2272 // Record that this module uses assignment tracking.
2273 setAssignmentTrackingModuleFlag(M);
2274
2275 // Q: Can we return a less conservative set than just CFGAnalyses? Can we
2276 // return PreservedAnalyses::all()?
2277 PreservedAnalyses PA;
2278 PA.preserveSet<CFGAnalyses>();
2279 return PA;
2280 }
2281
2282 #undef DEBUG_TYPE
2283