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