Revert "Create overloads of debug intrinsic utilities for DPValues (#78313)"
[llvm-project.git] / llvm / lib / IR / DebugInfo.cpp
blob312d670d5b30e72916280c686f76235d04ebeb98
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.
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<DPValue *> llvm::findDPVDeclares(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 {};
75 TinyPtrVector<DPValue *> Declares;
76 for (DPValue *DPV : L->getAllDPValueUsers())
77 if (DPV->getType() == DPValue::LocationType::Declare)
78 Declares.push_back(DPV);
80 return Declares;
83 template <typename IntrinsicT,
84 DPValue::LocationType Type = DPValue::LocationType::Any>
85 static void findDbgIntrinsics(SmallVectorImpl<IntrinsicT *> &Result, Value *V,
86 SmallVectorImpl<DPValue *> *DPValues) {
87 // This function is hot. Check whether the value has any metadata to avoid a
88 // DenseMap lookup.
89 if (!V->isUsedByMetadata())
90 return;
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<DPValue *, 4> EncounteredDPValues;
101 /// Append IntrinsicT users of MetadataAsValue(MD).
102 auto AppendUsers = [&Ctx, &EncounteredIntrinsics, &Result,
103 DPValues](Metadata *MD) {
104 if (auto *MDV = MetadataAsValue::getIfExists(Ctx, MD)) {
105 for (User *U : MDV->users())
106 if (IntrinsicT *DVI = dyn_cast<IntrinsicT>(U))
107 if (EncounteredIntrinsics.insert(DVI).second)
108 Result.push_back(DVI);
110 if (!DPValues)
111 return;
112 // Get DPValues that use this as a single value.
113 if (LocalAsMetadata *L = dyn_cast<LocalAsMetadata>(MD)) {
114 for (DPValue *DPV : L->getAllDPValueUsers()) {
115 if (Type == DPValue::LocationType::Any || DPV->getType() == Type)
116 DPValues->push_back(DPV);
121 if (auto *L = LocalAsMetadata::getIfExists(V)) {
122 AppendUsers(L);
123 for (Metadata *AL : L->getAllArgListUsers()) {
124 AppendUsers(AL);
125 if (!DPValues)
126 continue;
127 DIArgList *DI = cast<DIArgList>(AL);
128 for (DPValue *DPV : DI->getAllDPValueUsers())
129 if (Type == DPValue::LocationType::Any || DPV->getType() == Type)
130 if (EncounteredDPValues.insert(DPV).second)
131 DPValues->push_back(DPV);
136 void llvm::findDbgValues(SmallVectorImpl<DbgValueInst *> &DbgValues,
137 Value *V, SmallVectorImpl<DPValue *> *DPValues) {
138 findDbgIntrinsics<DbgValueInst, DPValue::LocationType::Value>(DbgValues, V,
139 DPValues);
142 void llvm::findDbgUsers(SmallVectorImpl<DbgVariableIntrinsic *> &DbgUsers,
143 Value *V, SmallVectorImpl<DPValue *> *DPValues) {
144 findDbgIntrinsics<DbgVariableIntrinsic, DPValue::LocationType::Any>(
145 DbgUsers, V, DPValues);
148 DISubprogram *llvm::getDISubprogram(const MDNode *Scope) {
149 if (auto *LocalScope = dyn_cast_or_null<DILocalScope>(Scope))
150 return LocalScope->getSubprogram();
151 return nullptr;
154 DebugLoc llvm::getDebugValueLoc(DbgVariableIntrinsic *DII) {
155 // Original dbg.declare must have a location.
156 const DebugLoc &DeclareLoc = DII->getDebugLoc();
157 MDNode *Scope = DeclareLoc.getScope();
158 DILocation *InlinedAt = DeclareLoc.getInlinedAt();
159 // Because no machine insts can come from debug intrinsics, only the scope
160 // and inlinedAt is significant. Zero line numbers are used in case this
161 // DebugLoc leaks into any adjacent instructions. Produce an unknown location
162 // with the correct scope / inlinedAt fields.
163 return DILocation::get(DII->getContext(), 0, 0, Scope, InlinedAt);
166 //===----------------------------------------------------------------------===//
167 // DebugInfoFinder implementations.
168 //===----------------------------------------------------------------------===//
170 void DebugInfoFinder::reset() {
171 CUs.clear();
172 SPs.clear();
173 GVs.clear();
174 TYs.clear();
175 Scopes.clear();
176 NodesSeen.clear();
179 void DebugInfoFinder::processModule(const Module &M) {
180 for (auto *CU : M.debug_compile_units())
181 processCompileUnit(CU);
182 for (auto &F : M.functions()) {
183 if (auto *SP = cast_or_null<DISubprogram>(F.getSubprogram()))
184 processSubprogram(SP);
185 // There could be subprograms from inlined functions referenced from
186 // instructions only. Walk the function to find them.
187 for (const BasicBlock &BB : F)
188 for (const Instruction &I : BB)
189 processInstruction(M, I);
193 void DebugInfoFinder::processCompileUnit(DICompileUnit *CU) {
194 if (!addCompileUnit(CU))
195 return;
196 for (auto *DIG : CU->getGlobalVariables()) {
197 if (!addGlobalVariable(DIG))
198 continue;
199 auto *GV = DIG->getVariable();
200 processScope(GV->getScope());
201 processType(GV->getType());
203 for (auto *ET : CU->getEnumTypes())
204 processType(ET);
205 for (auto *RT : CU->getRetainedTypes())
206 if (auto *T = dyn_cast<DIType>(RT))
207 processType(T);
208 else
209 processSubprogram(cast<DISubprogram>(RT));
210 for (auto *Import : CU->getImportedEntities()) {
211 auto *Entity = Import->getEntity();
212 if (auto *T = dyn_cast<DIType>(Entity))
213 processType(T);
214 else if (auto *SP = dyn_cast<DISubprogram>(Entity))
215 processSubprogram(SP);
216 else if (auto *NS = dyn_cast<DINamespace>(Entity))
217 processScope(NS->getScope());
218 else if (auto *M = dyn_cast<DIModule>(Entity))
219 processScope(M->getScope());
223 void DebugInfoFinder::processInstruction(const Module &M,
224 const Instruction &I) {
225 if (auto *DVI = dyn_cast<DbgVariableIntrinsic>(&I))
226 processVariable(M, DVI->getVariable());
228 if (auto DbgLoc = I.getDebugLoc())
229 processLocation(M, DbgLoc.get());
231 for (const DPValue &DPV : I.getDbgValueRange())
232 processDPValue(M, DPV);
235 void DebugInfoFinder::processLocation(const Module &M, const DILocation *Loc) {
236 if (!Loc)
237 return;
238 processScope(Loc->getScope());
239 processLocation(M, Loc->getInlinedAt());
242 void DebugInfoFinder::processDPValue(const Module &M, const DPValue &DPV) {
243 processVariable(M, DPV.getVariable());
244 processLocation(M, DPV.getDebugLoc().get());
247 void DebugInfoFinder::processType(DIType *DT) {
248 if (!addType(DT))
249 return;
250 processScope(DT->getScope());
251 if (auto *ST = dyn_cast<DISubroutineType>(DT)) {
252 for (DIType *Ref : ST->getTypeArray())
253 processType(Ref);
254 return;
256 if (auto *DCT = dyn_cast<DICompositeType>(DT)) {
257 processType(DCT->getBaseType());
258 for (Metadata *D : DCT->getElements()) {
259 if (auto *T = dyn_cast<DIType>(D))
260 processType(T);
261 else if (auto *SP = dyn_cast<DISubprogram>(D))
262 processSubprogram(SP);
264 return;
266 if (auto *DDT = dyn_cast<DIDerivedType>(DT)) {
267 processType(DDT->getBaseType());
271 void DebugInfoFinder::processScope(DIScope *Scope) {
272 if (!Scope)
273 return;
274 if (auto *Ty = dyn_cast<DIType>(Scope)) {
275 processType(Ty);
276 return;
278 if (auto *CU = dyn_cast<DICompileUnit>(Scope)) {
279 addCompileUnit(CU);
280 return;
282 if (auto *SP = dyn_cast<DISubprogram>(Scope)) {
283 processSubprogram(SP);
284 return;
286 if (!addScope(Scope))
287 return;
288 if (auto *LB = dyn_cast<DILexicalBlockBase>(Scope)) {
289 processScope(LB->getScope());
290 } else if (auto *NS = dyn_cast<DINamespace>(Scope)) {
291 processScope(NS->getScope());
292 } else if (auto *M = dyn_cast<DIModule>(Scope)) {
293 processScope(M->getScope());
297 void DebugInfoFinder::processSubprogram(DISubprogram *SP) {
298 if (!addSubprogram(SP))
299 return;
300 processScope(SP->getScope());
301 // Some of the users, e.g. CloneFunctionInto / CloneModule, need to set up a
302 // ValueMap containing identity mappings for all of the DICompileUnit's, not
303 // just DISubprogram's, referenced from anywhere within the Function being
304 // cloned prior to calling MapMetadata / RemapInstruction to avoid their
305 // duplication later as DICompileUnit's are also directly referenced by
306 // llvm.dbg.cu list. Thefore we need to collect DICompileUnit's here as well.
307 // Also, DICompileUnit's may reference DISubprogram's too and therefore need
308 // to be at least looked through.
309 processCompileUnit(SP->getUnit());
310 processType(SP->getType());
311 for (auto *Element : SP->getTemplateParams()) {
312 if (auto *TType = dyn_cast<DITemplateTypeParameter>(Element)) {
313 processType(TType->getType());
314 } else if (auto *TVal = dyn_cast<DITemplateValueParameter>(Element)) {
315 processType(TVal->getType());
320 void DebugInfoFinder::processVariable(const Module &M,
321 const DILocalVariable *DV) {
322 if (!NodesSeen.insert(DV).second)
323 return;
324 processScope(DV->getScope());
325 processType(DV->getType());
328 bool DebugInfoFinder::addType(DIType *DT) {
329 if (!DT)
330 return false;
332 if (!NodesSeen.insert(DT).second)
333 return false;
335 TYs.push_back(const_cast<DIType *>(DT));
336 return true;
339 bool DebugInfoFinder::addCompileUnit(DICompileUnit *CU) {
340 if (!CU)
341 return false;
342 if (!NodesSeen.insert(CU).second)
343 return false;
345 CUs.push_back(CU);
346 return true;
349 bool DebugInfoFinder::addGlobalVariable(DIGlobalVariableExpression *DIG) {
350 if (!NodesSeen.insert(DIG).second)
351 return false;
353 GVs.push_back(DIG);
354 return true;
357 bool DebugInfoFinder::addSubprogram(DISubprogram *SP) {
358 if (!SP)
359 return false;
361 if (!NodesSeen.insert(SP).second)
362 return false;
364 SPs.push_back(SP);
365 return true;
368 bool DebugInfoFinder::addScope(DIScope *Scope) {
369 if (!Scope)
370 return false;
371 // FIXME: Ocaml binding generates a scope with no content, we treat it
372 // as null for now.
373 if (Scope->getNumOperands() == 0)
374 return false;
375 if (!NodesSeen.insert(Scope).second)
376 return false;
377 Scopes.push_back(Scope);
378 return true;
381 static MDNode *updateLoopMetadataDebugLocationsImpl(
382 MDNode *OrigLoopID, function_ref<Metadata *(Metadata *)> Updater) {
383 assert(OrigLoopID && OrigLoopID->getNumOperands() > 0 &&
384 "Loop ID needs at least one operand");
385 assert(OrigLoopID && OrigLoopID->getOperand(0).get() == OrigLoopID &&
386 "Loop ID should refer to itself");
388 // Save space for the self-referential LoopID.
389 SmallVector<Metadata *, 4> MDs = {nullptr};
391 for (unsigned i = 1; i < OrigLoopID->getNumOperands(); ++i) {
392 Metadata *MD = OrigLoopID->getOperand(i);
393 if (!MD)
394 MDs.push_back(nullptr);
395 else if (Metadata *NewMD = Updater(MD))
396 MDs.push_back(NewMD);
399 MDNode *NewLoopID = MDNode::getDistinct(OrigLoopID->getContext(), MDs);
400 // Insert the self-referential LoopID.
401 NewLoopID->replaceOperandWith(0, NewLoopID);
402 return NewLoopID;
405 void llvm::updateLoopMetadataDebugLocations(
406 Instruction &I, function_ref<Metadata *(Metadata *)> Updater) {
407 MDNode *OrigLoopID = I.getMetadata(LLVMContext::MD_loop);
408 if (!OrigLoopID)
409 return;
410 MDNode *NewLoopID = updateLoopMetadataDebugLocationsImpl(OrigLoopID, Updater);
411 I.setMetadata(LLVMContext::MD_loop, NewLoopID);
414 /// Return true if a node is a DILocation or if a DILocation is
415 /// indirectly referenced by one of the node's children.
416 static bool isDILocationReachable(SmallPtrSetImpl<Metadata *> &Visited,
417 SmallPtrSetImpl<Metadata *> &Reachable,
418 Metadata *MD) {
419 MDNode *N = dyn_cast_or_null<MDNode>(MD);
420 if (!N)
421 return false;
422 if (isa<DILocation>(N) || Reachable.count(N))
423 return true;
424 if (!Visited.insert(N).second)
425 return false;
426 for (auto &OpIt : N->operands()) {
427 Metadata *Op = OpIt.get();
428 if (isDILocationReachable(Visited, Reachable, Op)) {
429 // Don't return just yet as we want to visit all MD's children to
430 // initialize DILocationReachable in stripDebugLocFromLoopID
431 Reachable.insert(N);
434 return Reachable.count(N);
437 static bool isAllDILocation(SmallPtrSetImpl<Metadata *> &Visited,
438 SmallPtrSetImpl<Metadata *> &AllDILocation,
439 const SmallPtrSetImpl<Metadata *> &DIReachable,
440 Metadata *MD) {
441 MDNode *N = dyn_cast_or_null<MDNode>(MD);
442 if (!N)
443 return false;
444 if (isa<DILocation>(N) || AllDILocation.count(N))
445 return true;
446 if (!DIReachable.count(N))
447 return false;
448 if (!Visited.insert(N).second)
449 return false;
450 for (auto &OpIt : N->operands()) {
451 Metadata *Op = OpIt.get();
452 if (Op == MD)
453 continue;
454 if (!isAllDILocation(Visited, AllDILocation, DIReachable, Op)) {
455 return false;
458 AllDILocation.insert(N);
459 return true;
462 static Metadata *
463 stripLoopMDLoc(const SmallPtrSetImpl<Metadata *> &AllDILocation,
464 const SmallPtrSetImpl<Metadata *> &DIReachable, Metadata *MD) {
465 if (isa<DILocation>(MD) || AllDILocation.count(MD))
466 return nullptr;
468 if (!DIReachable.count(MD))
469 return MD;
471 MDNode *N = dyn_cast_or_null<MDNode>(MD);
472 if (!N)
473 return MD;
475 SmallVector<Metadata *, 4> Args;
476 bool HasSelfRef = false;
477 for (unsigned i = 0; i < N->getNumOperands(); ++i) {
478 Metadata *A = N->getOperand(i);
479 if (!A) {
480 Args.push_back(nullptr);
481 } else if (A == MD) {
482 assert(i == 0 && "expected i==0 for self-reference");
483 HasSelfRef = true;
484 Args.push_back(nullptr);
485 } else if (Metadata *NewArg =
486 stripLoopMDLoc(AllDILocation, DIReachable, A)) {
487 Args.push_back(NewArg);
490 if (Args.empty() || (HasSelfRef && Args.size() == 1))
491 return nullptr;
493 MDNode *NewMD = N->isDistinct() ? MDNode::getDistinct(N->getContext(), Args)
494 : MDNode::get(N->getContext(), Args);
495 if (HasSelfRef)
496 NewMD->replaceOperandWith(0, NewMD);
497 return NewMD;
500 static MDNode *stripDebugLocFromLoopID(MDNode *N) {
501 assert(!N->operands().empty() && "Missing self reference?");
502 SmallPtrSet<Metadata *, 8> Visited, DILocationReachable, AllDILocation;
503 // If we already visited N, there is nothing to do.
504 if (!Visited.insert(N).second)
505 return N;
507 // If there is no debug location, we do not have to rewrite this
508 // MDNode. This loop also initializes DILocationReachable, later
509 // needed by updateLoopMetadataDebugLocationsImpl; the use of
510 // count_if avoids an early exit.
511 if (!llvm::count_if(llvm::drop_begin(N->operands()),
512 [&Visited, &DILocationReachable](const MDOperand &Op) {
513 return isDILocationReachable(
514 Visited, DILocationReachable, Op.get());
516 return N;
518 Visited.clear();
519 // If there is only the debug location without any actual loop metadata, we
520 // can remove the metadata.
521 if (llvm::all_of(llvm::drop_begin(N->operands()),
522 [&Visited, &AllDILocation,
523 &DILocationReachable](const MDOperand &Op) {
524 return isAllDILocation(Visited, AllDILocation,
525 DILocationReachable, Op.get());
527 return nullptr;
529 return updateLoopMetadataDebugLocationsImpl(
530 N, [&AllDILocation, &DILocationReachable](Metadata *MD) -> Metadata * {
531 return stripLoopMDLoc(AllDILocation, DILocationReachable, MD);
535 bool llvm::stripDebugInfo(Function &F) {
536 bool Changed = false;
537 if (F.hasMetadata(LLVMContext::MD_dbg)) {
538 Changed = true;
539 F.setSubprogram(nullptr);
542 DenseMap<MDNode *, MDNode *> LoopIDsMap;
543 for (BasicBlock &BB : F) {
544 for (Instruction &I : llvm::make_early_inc_range(BB)) {
545 if (isa<DbgInfoIntrinsic>(&I)) {
546 I.eraseFromParent();
547 Changed = true;
548 continue;
550 if (I.getDebugLoc()) {
551 Changed = true;
552 I.setDebugLoc(DebugLoc());
554 if (auto *LoopID = I.getMetadata(LLVMContext::MD_loop)) {
555 auto *NewLoopID = LoopIDsMap.lookup(LoopID);
556 if (!NewLoopID)
557 NewLoopID = LoopIDsMap[LoopID] = stripDebugLocFromLoopID(LoopID);
558 if (NewLoopID != LoopID)
559 I.setMetadata(LLVMContext::MD_loop, NewLoopID);
561 // Strip other attachments that are or use debug info.
562 if (I.hasMetadataOtherThanDebugLoc()) {
563 // Heapallocsites point into the DIType system.
564 I.setMetadata("heapallocsite", nullptr);
565 // DIAssignID are debug info metadata primitives.
566 I.setMetadata(LLVMContext::MD_DIAssignID, nullptr);
568 I.dropDbgValues();
571 return Changed;
574 bool llvm::StripDebugInfo(Module &M) {
575 bool Changed = false;
577 for (NamedMDNode &NMD : llvm::make_early_inc_range(M.named_metadata())) {
578 // We're stripping debug info, and without them, coverage information
579 // doesn't quite make sense.
580 if (NMD.getName().starts_with("llvm.dbg.") ||
581 NMD.getName() == "llvm.gcov") {
582 NMD.eraseFromParent();
583 Changed = true;
587 for (Function &F : M)
588 Changed |= stripDebugInfo(F);
590 for (auto &GV : M.globals()) {
591 Changed |= GV.eraseMetadata(LLVMContext::MD_dbg);
594 if (GVMaterializer *Materializer = M.getMaterializer())
595 Materializer->setStripDebugInfo();
597 return Changed;
600 namespace {
602 /// Helper class to downgrade -g metadata to -gline-tables-only metadata.
603 class DebugTypeInfoRemoval {
604 DenseMap<Metadata *, Metadata *> Replacements;
606 public:
607 /// The (void)() type.
608 MDNode *EmptySubroutineType;
610 private:
611 /// Remember what linkage name we originally had before stripping. If we end
612 /// up making two subprograms identical who originally had different linkage
613 /// names, then we need to make one of them distinct, to avoid them getting
614 /// uniqued. Maps the new node to the old linkage name.
615 DenseMap<DISubprogram *, StringRef> NewToLinkageName;
617 // TODO: Remember the distinct subprogram we created for a given linkage name,
618 // so that we can continue to unique whenever possible. Map <newly created
619 // node, old linkage name> to the first (possibly distinct) mdsubprogram
620 // created for that combination. This is not strictly needed for correctness,
621 // but can cut down on the number of MDNodes and let us diff cleanly with the
622 // output of -gline-tables-only.
624 public:
625 DebugTypeInfoRemoval(LLVMContext &C)
626 : EmptySubroutineType(DISubroutineType::get(C, DINode::FlagZero, 0,
627 MDNode::get(C, {}))) {}
629 Metadata *map(Metadata *M) {
630 if (!M)
631 return nullptr;
632 auto Replacement = Replacements.find(M);
633 if (Replacement != Replacements.end())
634 return Replacement->second;
636 return M;
638 MDNode *mapNode(Metadata *N) { return dyn_cast_or_null<MDNode>(map(N)); }
640 /// Recursively remap N and all its referenced children. Does a DF post-order
641 /// traversal, so as to remap bottoms up.
642 void traverseAndRemap(MDNode *N) { traverse(N); }
644 private:
645 // Create a new DISubprogram, to replace the one given.
646 DISubprogram *getReplacementSubprogram(DISubprogram *MDS) {
647 auto *FileAndScope = cast_or_null<DIFile>(map(MDS->getFile()));
648 StringRef LinkageName = MDS->getName().empty() ? MDS->getLinkageName() : "";
649 DISubprogram *Declaration = nullptr;
650 auto *Type = cast_or_null<DISubroutineType>(map(MDS->getType()));
651 DIType *ContainingType =
652 cast_or_null<DIType>(map(MDS->getContainingType()));
653 auto *Unit = cast_or_null<DICompileUnit>(map(MDS->getUnit()));
654 auto Variables = nullptr;
655 auto TemplateParams = nullptr;
657 // Make a distinct DISubprogram, for situations that warrent it.
658 auto distinctMDSubprogram = [&]() {
659 return DISubprogram::getDistinct(
660 MDS->getContext(), FileAndScope, MDS->getName(), LinkageName,
661 FileAndScope, MDS->getLine(), Type, MDS->getScopeLine(),
662 ContainingType, MDS->getVirtualIndex(), MDS->getThisAdjustment(),
663 MDS->getFlags(), MDS->getSPFlags(), Unit, TemplateParams, Declaration,
664 Variables);
667 if (MDS->isDistinct())
668 return distinctMDSubprogram();
670 auto *NewMDS = DISubprogram::get(
671 MDS->getContext(), FileAndScope, MDS->getName(), LinkageName,
672 FileAndScope, MDS->getLine(), Type, MDS->getScopeLine(), ContainingType,
673 MDS->getVirtualIndex(), MDS->getThisAdjustment(), MDS->getFlags(),
674 MDS->getSPFlags(), Unit, TemplateParams, Declaration, Variables);
676 StringRef OldLinkageName = MDS->getLinkageName();
678 // See if we need to make a distinct one.
679 auto OrigLinkage = NewToLinkageName.find(NewMDS);
680 if (OrigLinkage != NewToLinkageName.end()) {
681 if (OrigLinkage->second == OldLinkageName)
682 // We're good.
683 return NewMDS;
685 // Otherwise, need to make a distinct one.
686 // TODO: Query the map to see if we already have one.
687 return distinctMDSubprogram();
690 NewToLinkageName.insert({NewMDS, MDS->getLinkageName()});
691 return NewMDS;
694 /// Create a new compile unit, to replace the one given
695 DICompileUnit *getReplacementCU(DICompileUnit *CU) {
696 // Drop skeleton CUs.
697 if (CU->getDWOId())
698 return nullptr;
700 auto *File = cast_or_null<DIFile>(map(CU->getFile()));
701 MDTuple *EnumTypes = nullptr;
702 MDTuple *RetainedTypes = nullptr;
703 MDTuple *GlobalVariables = nullptr;
704 MDTuple *ImportedEntities = nullptr;
705 return DICompileUnit::getDistinct(
706 CU->getContext(), CU->getSourceLanguage(), File, CU->getProducer(),
707 CU->isOptimized(), CU->getFlags(), CU->getRuntimeVersion(),
708 CU->getSplitDebugFilename(), DICompileUnit::LineTablesOnly, EnumTypes,
709 RetainedTypes, GlobalVariables, ImportedEntities, CU->getMacros(),
710 CU->getDWOId(), CU->getSplitDebugInlining(),
711 CU->getDebugInfoForProfiling(), CU->getNameTableKind(),
712 CU->getRangesBaseAddress(), CU->getSysRoot(), CU->getSDK());
715 DILocation *getReplacementMDLocation(DILocation *MLD) {
716 auto *Scope = map(MLD->getScope());
717 auto *InlinedAt = map(MLD->getInlinedAt());
718 if (MLD->isDistinct())
719 return DILocation::getDistinct(MLD->getContext(), MLD->getLine(),
720 MLD->getColumn(), Scope, InlinedAt);
721 return DILocation::get(MLD->getContext(), MLD->getLine(), MLD->getColumn(),
722 Scope, InlinedAt);
725 /// Create a new generic MDNode, to replace the one given
726 MDNode *getReplacementMDNode(MDNode *N) {
727 SmallVector<Metadata *, 8> Ops;
728 Ops.reserve(N->getNumOperands());
729 for (auto &I : N->operands())
730 if (I)
731 Ops.push_back(map(I));
732 auto *Ret = MDNode::get(N->getContext(), Ops);
733 return Ret;
736 /// Attempt to re-map N to a newly created node.
737 void remap(MDNode *N) {
738 if (Replacements.count(N))
739 return;
741 auto doRemap = [&](MDNode *N) -> MDNode * {
742 if (!N)
743 return nullptr;
744 if (auto *MDSub = dyn_cast<DISubprogram>(N)) {
745 remap(MDSub->getUnit());
746 return getReplacementSubprogram(MDSub);
748 if (isa<DISubroutineType>(N))
749 return EmptySubroutineType;
750 if (auto *CU = dyn_cast<DICompileUnit>(N))
751 return getReplacementCU(CU);
752 if (isa<DIFile>(N))
753 return N;
754 if (auto *MDLB = dyn_cast<DILexicalBlockBase>(N))
755 // Remap to our referenced scope (recursively).
756 return mapNode(MDLB->getScope());
757 if (auto *MLD = dyn_cast<DILocation>(N))
758 return getReplacementMDLocation(MLD);
760 // Otherwise, if we see these, just drop them now. Not strictly necessary,
761 // but this speeds things up a little.
762 if (isa<DINode>(N))
763 return nullptr;
765 return getReplacementMDNode(N);
767 Replacements[N] = doRemap(N);
770 /// Do the remapping traversal.
771 void traverse(MDNode *);
774 } // end anonymous namespace
776 void DebugTypeInfoRemoval::traverse(MDNode *N) {
777 if (!N || Replacements.count(N))
778 return;
780 // To avoid cycles, as well as for efficiency sake, we will sometimes prune
781 // parts of the graph.
782 auto prune = [](MDNode *Parent, MDNode *Child) {
783 if (auto *MDS = dyn_cast<DISubprogram>(Parent))
784 return Child == MDS->getRetainedNodes().get();
785 return false;
788 SmallVector<MDNode *, 16> ToVisit;
789 DenseSet<MDNode *> Opened;
791 // Visit each node starting at N in post order, and map them.
792 ToVisit.push_back(N);
793 while (!ToVisit.empty()) {
794 auto *N = ToVisit.back();
795 if (!Opened.insert(N).second) {
796 // Close it.
797 remap(N);
798 ToVisit.pop_back();
799 continue;
801 for (auto &I : N->operands())
802 if (auto *MDN = dyn_cast_or_null<MDNode>(I))
803 if (!Opened.count(MDN) && !Replacements.count(MDN) && !prune(N, MDN) &&
804 !isa<DICompileUnit>(MDN))
805 ToVisit.push_back(MDN);
809 bool llvm::stripNonLineTableDebugInfo(Module &M) {
810 bool Changed = false;
812 // First off, delete the debug intrinsics.
813 auto RemoveUses = [&](StringRef Name) {
814 if (auto *DbgVal = M.getFunction(Name)) {
815 while (!DbgVal->use_empty())
816 cast<Instruction>(DbgVal->user_back())->eraseFromParent();
817 DbgVal->eraseFromParent();
818 Changed = true;
821 RemoveUses("llvm.dbg.declare");
822 RemoveUses("llvm.dbg.label");
823 RemoveUses("llvm.dbg.value");
825 // Delete non-CU debug info named metadata nodes.
826 for (auto NMI = M.named_metadata_begin(), NME = M.named_metadata_end();
827 NMI != NME;) {
828 NamedMDNode *NMD = &*NMI;
829 ++NMI;
830 // Specifically keep dbg.cu around.
831 if (NMD->getName() == "llvm.dbg.cu")
832 continue;
835 // Drop all dbg attachments from global variables.
836 for (auto &GV : M.globals())
837 GV.eraseMetadata(LLVMContext::MD_dbg);
839 DebugTypeInfoRemoval Mapper(M.getContext());
840 auto remap = [&](MDNode *Node) -> MDNode * {
841 if (!Node)
842 return nullptr;
843 Mapper.traverseAndRemap(Node);
844 auto *NewNode = Mapper.mapNode(Node);
845 Changed |= Node != NewNode;
846 Node = NewNode;
847 return NewNode;
850 // Rewrite the DebugLocs to be equivalent to what
851 // -gline-tables-only would have created.
852 for (auto &F : M) {
853 if (auto *SP = F.getSubprogram()) {
854 Mapper.traverseAndRemap(SP);
855 auto *NewSP = cast<DISubprogram>(Mapper.mapNode(SP));
856 Changed |= SP != NewSP;
857 F.setSubprogram(NewSP);
859 for (auto &BB : F) {
860 for (auto &I : BB) {
861 auto remapDebugLoc = [&](const DebugLoc &DL) -> DebugLoc {
862 auto *Scope = DL.getScope();
863 MDNode *InlinedAt = DL.getInlinedAt();
864 Scope = remap(Scope);
865 InlinedAt = remap(InlinedAt);
866 return DILocation::get(M.getContext(), DL.getLine(), DL.getCol(),
867 Scope, InlinedAt);
870 if (I.getDebugLoc() != DebugLoc())
871 I.setDebugLoc(remapDebugLoc(I.getDebugLoc()));
873 // Remap DILocations in llvm.loop attachments.
874 updateLoopMetadataDebugLocations(I, [&](Metadata *MD) -> Metadata * {
875 if (auto *Loc = dyn_cast_or_null<DILocation>(MD))
876 return remapDebugLoc(Loc).get();
877 return MD;
880 // Strip heapallocsite attachments, they point into the DIType system.
881 if (I.hasMetadataOtherThanDebugLoc())
882 I.setMetadata("heapallocsite", nullptr);
887 // Create a new llvm.dbg.cu, which is equivalent to the one
888 // -gline-tables-only would have created.
889 for (auto &NMD : M.named_metadata()) {
890 SmallVector<MDNode *, 8> Ops;
891 for (MDNode *Op : NMD.operands())
892 Ops.push_back(remap(Op));
894 if (!Changed)
895 continue;
897 NMD.clearOperands();
898 for (auto *Op : Ops)
899 if (Op)
900 NMD.addOperand(Op);
902 return Changed;
905 unsigned llvm::getDebugMetadataVersionFromModule(const Module &M) {
906 if (auto *Val = mdconst::dyn_extract_or_null<ConstantInt>(
907 M.getModuleFlag("Debug Info Version")))
908 return Val->getZExtValue();
909 return 0;
912 void Instruction::applyMergedLocation(DILocation *LocA, DILocation *LocB) {
913 setDebugLoc(DILocation::getMergedLocation(LocA, LocB));
916 void Instruction::mergeDIAssignID(
917 ArrayRef<const Instruction *> SourceInstructions) {
918 // Replace all uses (and attachments) of all the DIAssignIDs
919 // on SourceInstructions with a single merged value.
920 assert(getFunction() && "Uninserted instruction merged");
921 // Collect up the DIAssignID tags.
922 SmallVector<DIAssignID *, 4> IDs;
923 for (const Instruction *I : SourceInstructions) {
924 if (auto *MD = I->getMetadata(LLVMContext::MD_DIAssignID))
925 IDs.push_back(cast<DIAssignID>(MD));
926 assert(getFunction() == I->getFunction() &&
927 "Merging with instruction from another function not allowed");
930 // Add this instruction's DIAssignID too, if it has one.
931 if (auto *MD = getMetadata(LLVMContext::MD_DIAssignID))
932 IDs.push_back(cast<DIAssignID>(MD));
934 if (IDs.empty())
935 return; // No DIAssignID tags to process.
937 DIAssignID *MergeID = IDs[0];
938 for (auto It = std::next(IDs.begin()), End = IDs.end(); It != End; ++It) {
939 if (*It != MergeID)
940 at::RAUW(*It, MergeID);
942 setMetadata(LLVMContext::MD_DIAssignID, MergeID);
945 void Instruction::updateLocationAfterHoist() { dropLocation(); }
947 void Instruction::dropLocation() {
948 const DebugLoc &DL = getDebugLoc();
949 if (!DL)
950 return;
952 // If this isn't a call, drop the location to allow a location from a
953 // preceding instruction to propagate.
954 bool MayLowerToCall = false;
955 if (isa<CallBase>(this)) {
956 auto *II = dyn_cast<IntrinsicInst>(this);
957 MayLowerToCall =
958 !II || IntrinsicInst::mayLowerToFunctionCall(II->getIntrinsicID());
961 if (!MayLowerToCall) {
962 setDebugLoc(DebugLoc());
963 return;
966 // Set a line 0 location for calls to preserve scope information in case
967 // inlining occurs.
968 DISubprogram *SP = getFunction()->getSubprogram();
969 if (SP)
970 // If a function scope is available, set it on the line 0 location. When
971 // hoisting a call to a predecessor block, using the function scope avoids
972 // making it look like the callee was reached earlier than it should be.
973 setDebugLoc(DILocation::get(getContext(), 0, 0, SP));
974 else
975 // The parent function has no scope. Go ahead and drop the location. If
976 // the parent function is inlined, and the callee has a subprogram, the
977 // inliner will attach a location to the call.
979 // One alternative is to set a line 0 location with the existing scope and
980 // inlinedAt info. The location might be sensitive to when inlining occurs.
981 setDebugLoc(DebugLoc());
984 //===----------------------------------------------------------------------===//
985 // LLVM C API implementations.
986 //===----------------------------------------------------------------------===//
988 static unsigned map_from_llvmDWARFsourcelanguage(LLVMDWARFSourceLanguage lang) {
989 switch (lang) {
990 #define HANDLE_DW_LANG(ID, NAME, LOWER_BOUND, VERSION, VENDOR) \
991 case LLVMDWARFSourceLanguage##NAME: \
992 return ID;
993 #include "llvm/BinaryFormat/Dwarf.def"
994 #undef HANDLE_DW_LANG
996 llvm_unreachable("Unhandled Tag");
999 template <typename DIT> DIT *unwrapDI(LLVMMetadataRef Ref) {
1000 return (DIT *)(Ref ? unwrap<MDNode>(Ref) : nullptr);
1003 static DINode::DIFlags map_from_llvmDIFlags(LLVMDIFlags Flags) {
1004 return static_cast<DINode::DIFlags>(Flags);
1007 static LLVMDIFlags map_to_llvmDIFlags(DINode::DIFlags Flags) {
1008 return static_cast<LLVMDIFlags>(Flags);
1011 static DISubprogram::DISPFlags
1012 pack_into_DISPFlags(bool IsLocalToUnit, bool IsDefinition, bool IsOptimized) {
1013 return DISubprogram::toSPFlags(IsLocalToUnit, IsDefinition, IsOptimized);
1016 unsigned LLVMDebugMetadataVersion() {
1017 return DEBUG_METADATA_VERSION;
1020 LLVMDIBuilderRef LLVMCreateDIBuilderDisallowUnresolved(LLVMModuleRef M) {
1021 return wrap(new DIBuilder(*unwrap(M), false));
1024 LLVMDIBuilderRef LLVMCreateDIBuilder(LLVMModuleRef M) {
1025 return wrap(new DIBuilder(*unwrap(M)));
1028 unsigned LLVMGetModuleDebugMetadataVersion(LLVMModuleRef M) {
1029 return getDebugMetadataVersionFromModule(*unwrap(M));
1032 LLVMBool LLVMStripModuleDebugInfo(LLVMModuleRef M) {
1033 return StripDebugInfo(*unwrap(M));
1036 void LLVMDisposeDIBuilder(LLVMDIBuilderRef Builder) {
1037 delete unwrap(Builder);
1040 void LLVMDIBuilderFinalize(LLVMDIBuilderRef Builder) {
1041 unwrap(Builder)->finalize();
1044 void LLVMDIBuilderFinalizeSubprogram(LLVMDIBuilderRef Builder,
1045 LLVMMetadataRef subprogram) {
1046 unwrap(Builder)->finalizeSubprogram(unwrapDI<DISubprogram>(subprogram));
1049 LLVMMetadataRef LLVMDIBuilderCreateCompileUnit(
1050 LLVMDIBuilderRef Builder, LLVMDWARFSourceLanguage Lang,
1051 LLVMMetadataRef FileRef, const char *Producer, size_t ProducerLen,
1052 LLVMBool isOptimized, const char *Flags, size_t FlagsLen,
1053 unsigned RuntimeVer, const char *SplitName, size_t SplitNameLen,
1054 LLVMDWARFEmissionKind Kind, unsigned DWOId, LLVMBool SplitDebugInlining,
1055 LLVMBool DebugInfoForProfiling, const char *SysRoot, size_t SysRootLen,
1056 const char *SDK, size_t SDKLen) {
1057 auto File = unwrapDI<DIFile>(FileRef);
1059 return wrap(unwrap(Builder)->createCompileUnit(
1060 map_from_llvmDWARFsourcelanguage(Lang), File,
1061 StringRef(Producer, ProducerLen), isOptimized, StringRef(Flags, FlagsLen),
1062 RuntimeVer, StringRef(SplitName, SplitNameLen),
1063 static_cast<DICompileUnit::DebugEmissionKind>(Kind), DWOId,
1064 SplitDebugInlining, DebugInfoForProfiling,
1065 DICompileUnit::DebugNameTableKind::Default, false,
1066 StringRef(SysRoot, SysRootLen), StringRef(SDK, SDKLen)));
1069 LLVMMetadataRef
1070 LLVMDIBuilderCreateFile(LLVMDIBuilderRef Builder, const char *Filename,
1071 size_t FilenameLen, const char *Directory,
1072 size_t DirectoryLen) {
1073 return wrap(unwrap(Builder)->createFile(StringRef(Filename, FilenameLen),
1074 StringRef(Directory, DirectoryLen)));
1077 LLVMMetadataRef
1078 LLVMDIBuilderCreateModule(LLVMDIBuilderRef Builder, LLVMMetadataRef ParentScope,
1079 const char *Name, size_t NameLen,
1080 const char *ConfigMacros, size_t ConfigMacrosLen,
1081 const char *IncludePath, size_t IncludePathLen,
1082 const char *APINotesFile, size_t APINotesFileLen) {
1083 return wrap(unwrap(Builder)->createModule(
1084 unwrapDI<DIScope>(ParentScope), StringRef(Name, NameLen),
1085 StringRef(ConfigMacros, ConfigMacrosLen),
1086 StringRef(IncludePath, IncludePathLen),
1087 StringRef(APINotesFile, APINotesFileLen)));
1090 LLVMMetadataRef LLVMDIBuilderCreateNameSpace(LLVMDIBuilderRef Builder,
1091 LLVMMetadataRef ParentScope,
1092 const char *Name, size_t NameLen,
1093 LLVMBool ExportSymbols) {
1094 return wrap(unwrap(Builder)->createNameSpace(
1095 unwrapDI<DIScope>(ParentScope), StringRef(Name, NameLen), ExportSymbols));
1098 LLVMMetadataRef LLVMDIBuilderCreateFunction(
1099 LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
1100 size_t NameLen, const char *LinkageName, size_t LinkageNameLen,
1101 LLVMMetadataRef File, unsigned LineNo, LLVMMetadataRef Ty,
1102 LLVMBool IsLocalToUnit, LLVMBool IsDefinition,
1103 unsigned ScopeLine, LLVMDIFlags Flags, LLVMBool IsOptimized) {
1104 return wrap(unwrap(Builder)->createFunction(
1105 unwrapDI<DIScope>(Scope), {Name, NameLen}, {LinkageName, LinkageNameLen},
1106 unwrapDI<DIFile>(File), LineNo, unwrapDI<DISubroutineType>(Ty), ScopeLine,
1107 map_from_llvmDIFlags(Flags),
1108 pack_into_DISPFlags(IsLocalToUnit, IsDefinition, IsOptimized), nullptr,
1109 nullptr, nullptr));
1113 LLVMMetadataRef LLVMDIBuilderCreateLexicalBlock(
1114 LLVMDIBuilderRef Builder, LLVMMetadataRef Scope,
1115 LLVMMetadataRef File, unsigned Line, unsigned Col) {
1116 return wrap(unwrap(Builder)->createLexicalBlock(unwrapDI<DIScope>(Scope),
1117 unwrapDI<DIFile>(File),
1118 Line, Col));
1121 LLVMMetadataRef
1122 LLVMDIBuilderCreateLexicalBlockFile(LLVMDIBuilderRef Builder,
1123 LLVMMetadataRef Scope,
1124 LLVMMetadataRef File,
1125 unsigned Discriminator) {
1126 return wrap(unwrap(Builder)->createLexicalBlockFile(unwrapDI<DIScope>(Scope),
1127 unwrapDI<DIFile>(File),
1128 Discriminator));
1131 LLVMMetadataRef
1132 LLVMDIBuilderCreateImportedModuleFromNamespace(LLVMDIBuilderRef Builder,
1133 LLVMMetadataRef Scope,
1134 LLVMMetadataRef NS,
1135 LLVMMetadataRef File,
1136 unsigned Line) {
1137 return wrap(unwrap(Builder)->createImportedModule(unwrapDI<DIScope>(Scope),
1138 unwrapDI<DINamespace>(NS),
1139 unwrapDI<DIFile>(File),
1140 Line));
1143 LLVMMetadataRef LLVMDIBuilderCreateImportedModuleFromAlias(
1144 LLVMDIBuilderRef Builder, LLVMMetadataRef Scope,
1145 LLVMMetadataRef ImportedEntity, LLVMMetadataRef File, unsigned Line,
1146 LLVMMetadataRef *Elements, unsigned NumElements) {
1147 auto Elts =
1148 (NumElements > 0)
1149 ? unwrap(Builder)->getOrCreateArray({unwrap(Elements), NumElements})
1150 : nullptr;
1151 return wrap(unwrap(Builder)->createImportedModule(
1152 unwrapDI<DIScope>(Scope), unwrapDI<DIImportedEntity>(ImportedEntity),
1153 unwrapDI<DIFile>(File), Line, Elts));
1156 LLVMMetadataRef LLVMDIBuilderCreateImportedModuleFromModule(
1157 LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, LLVMMetadataRef M,
1158 LLVMMetadataRef File, unsigned Line, LLVMMetadataRef *Elements,
1159 unsigned NumElements) {
1160 auto Elts =
1161 (NumElements > 0)
1162 ? unwrap(Builder)->getOrCreateArray({unwrap(Elements), NumElements})
1163 : nullptr;
1164 return wrap(unwrap(Builder)->createImportedModule(
1165 unwrapDI<DIScope>(Scope), unwrapDI<DIModule>(M), unwrapDI<DIFile>(File),
1166 Line, Elts));
1169 LLVMMetadataRef LLVMDIBuilderCreateImportedDeclaration(
1170 LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, LLVMMetadataRef Decl,
1171 LLVMMetadataRef File, unsigned Line, const char *Name, size_t NameLen,
1172 LLVMMetadataRef *Elements, unsigned NumElements) {
1173 auto Elts =
1174 (NumElements > 0)
1175 ? unwrap(Builder)->getOrCreateArray({unwrap(Elements), NumElements})
1176 : nullptr;
1177 return wrap(unwrap(Builder)->createImportedDeclaration(
1178 unwrapDI<DIScope>(Scope), unwrapDI<DINode>(Decl), unwrapDI<DIFile>(File),
1179 Line, {Name, NameLen}, Elts));
1182 LLVMMetadataRef
1183 LLVMDIBuilderCreateDebugLocation(LLVMContextRef Ctx, unsigned Line,
1184 unsigned Column, LLVMMetadataRef Scope,
1185 LLVMMetadataRef InlinedAt) {
1186 return wrap(DILocation::get(*unwrap(Ctx), Line, Column, unwrap(Scope),
1187 unwrap(InlinedAt)));
1190 unsigned LLVMDILocationGetLine(LLVMMetadataRef Location) {
1191 return unwrapDI<DILocation>(Location)->getLine();
1194 unsigned LLVMDILocationGetColumn(LLVMMetadataRef Location) {
1195 return unwrapDI<DILocation>(Location)->getColumn();
1198 LLVMMetadataRef LLVMDILocationGetScope(LLVMMetadataRef Location) {
1199 return wrap(unwrapDI<DILocation>(Location)->getScope());
1202 LLVMMetadataRef LLVMDILocationGetInlinedAt(LLVMMetadataRef Location) {
1203 return wrap(unwrapDI<DILocation>(Location)->getInlinedAt());
1206 LLVMMetadataRef LLVMDIScopeGetFile(LLVMMetadataRef Scope) {
1207 return wrap(unwrapDI<DIScope>(Scope)->getFile());
1210 const char *LLVMDIFileGetDirectory(LLVMMetadataRef File, unsigned *Len) {
1211 auto Dir = unwrapDI<DIFile>(File)->getDirectory();
1212 *Len = Dir.size();
1213 return Dir.data();
1216 const char *LLVMDIFileGetFilename(LLVMMetadataRef File, unsigned *Len) {
1217 auto Name = unwrapDI<DIFile>(File)->getFilename();
1218 *Len = Name.size();
1219 return Name.data();
1222 const char *LLVMDIFileGetSource(LLVMMetadataRef File, unsigned *Len) {
1223 if (auto Src = unwrapDI<DIFile>(File)->getSource()) {
1224 *Len = Src->size();
1225 return Src->data();
1227 *Len = 0;
1228 return "";
1231 LLVMMetadataRef LLVMDIBuilderCreateMacro(LLVMDIBuilderRef Builder,
1232 LLVMMetadataRef ParentMacroFile,
1233 unsigned Line,
1234 LLVMDWARFMacinfoRecordType RecordType,
1235 const char *Name, size_t NameLen,
1236 const char *Value, size_t ValueLen) {
1237 return wrap(
1238 unwrap(Builder)->createMacro(unwrapDI<DIMacroFile>(ParentMacroFile), Line,
1239 static_cast<MacinfoRecordType>(RecordType),
1240 {Name, NameLen}, {Value, ValueLen}));
1243 LLVMMetadataRef
1244 LLVMDIBuilderCreateTempMacroFile(LLVMDIBuilderRef Builder,
1245 LLVMMetadataRef ParentMacroFile, unsigned Line,
1246 LLVMMetadataRef File) {
1247 return wrap(unwrap(Builder)->createTempMacroFile(
1248 unwrapDI<DIMacroFile>(ParentMacroFile), Line, unwrapDI<DIFile>(File)));
1251 LLVMMetadataRef LLVMDIBuilderCreateEnumerator(LLVMDIBuilderRef Builder,
1252 const char *Name, size_t NameLen,
1253 int64_t Value,
1254 LLVMBool IsUnsigned) {
1255 return wrap(unwrap(Builder)->createEnumerator({Name, NameLen}, Value,
1256 IsUnsigned != 0));
1259 LLVMMetadataRef LLVMDIBuilderCreateEnumerationType(
1260 LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
1261 size_t NameLen, LLVMMetadataRef File, unsigned LineNumber,
1262 uint64_t SizeInBits, uint32_t AlignInBits, LLVMMetadataRef *Elements,
1263 unsigned NumElements, LLVMMetadataRef ClassTy) {
1264 auto Elts = unwrap(Builder)->getOrCreateArray({unwrap(Elements),
1265 NumElements});
1266 return wrap(unwrap(Builder)->createEnumerationType(
1267 unwrapDI<DIScope>(Scope), {Name, NameLen}, unwrapDI<DIFile>(File),
1268 LineNumber, SizeInBits, AlignInBits, Elts, unwrapDI<DIType>(ClassTy)));
1271 LLVMMetadataRef LLVMDIBuilderCreateUnionType(
1272 LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
1273 size_t NameLen, LLVMMetadataRef File, unsigned LineNumber,
1274 uint64_t SizeInBits, uint32_t AlignInBits, LLVMDIFlags Flags,
1275 LLVMMetadataRef *Elements, unsigned NumElements, unsigned RunTimeLang,
1276 const char *UniqueId, size_t UniqueIdLen) {
1277 auto Elts = unwrap(Builder)->getOrCreateArray({unwrap(Elements),
1278 NumElements});
1279 return wrap(unwrap(Builder)->createUnionType(
1280 unwrapDI<DIScope>(Scope), {Name, NameLen}, unwrapDI<DIFile>(File),
1281 LineNumber, SizeInBits, AlignInBits, map_from_llvmDIFlags(Flags),
1282 Elts, RunTimeLang, {UniqueId, UniqueIdLen}));
1286 LLVMMetadataRef
1287 LLVMDIBuilderCreateArrayType(LLVMDIBuilderRef Builder, uint64_t Size,
1288 uint32_t AlignInBits, LLVMMetadataRef Ty,
1289 LLVMMetadataRef *Subscripts,
1290 unsigned NumSubscripts) {
1291 auto Subs = unwrap(Builder)->getOrCreateArray({unwrap(Subscripts),
1292 NumSubscripts});
1293 return wrap(unwrap(Builder)->createArrayType(Size, AlignInBits,
1294 unwrapDI<DIType>(Ty), Subs));
1297 LLVMMetadataRef
1298 LLVMDIBuilderCreateVectorType(LLVMDIBuilderRef Builder, uint64_t Size,
1299 uint32_t AlignInBits, LLVMMetadataRef Ty,
1300 LLVMMetadataRef *Subscripts,
1301 unsigned NumSubscripts) {
1302 auto Subs = unwrap(Builder)->getOrCreateArray({unwrap(Subscripts),
1303 NumSubscripts});
1304 return wrap(unwrap(Builder)->createVectorType(Size, AlignInBits,
1305 unwrapDI<DIType>(Ty), Subs));
1308 LLVMMetadataRef
1309 LLVMDIBuilderCreateBasicType(LLVMDIBuilderRef Builder, const char *Name,
1310 size_t NameLen, uint64_t SizeInBits,
1311 LLVMDWARFTypeEncoding Encoding,
1312 LLVMDIFlags Flags) {
1313 return wrap(unwrap(Builder)->createBasicType({Name, NameLen},
1314 SizeInBits, Encoding,
1315 map_from_llvmDIFlags(Flags)));
1318 LLVMMetadataRef LLVMDIBuilderCreatePointerType(
1319 LLVMDIBuilderRef Builder, LLVMMetadataRef PointeeTy,
1320 uint64_t SizeInBits, uint32_t AlignInBits, unsigned AddressSpace,
1321 const char *Name, size_t NameLen) {
1322 return wrap(unwrap(Builder)->createPointerType(unwrapDI<DIType>(PointeeTy),
1323 SizeInBits, AlignInBits,
1324 AddressSpace, {Name, NameLen}));
1327 LLVMMetadataRef LLVMDIBuilderCreateStructType(
1328 LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
1329 size_t NameLen, LLVMMetadataRef File, unsigned LineNumber,
1330 uint64_t SizeInBits, uint32_t AlignInBits, LLVMDIFlags Flags,
1331 LLVMMetadataRef DerivedFrom, LLVMMetadataRef *Elements,
1332 unsigned NumElements, unsigned RunTimeLang, LLVMMetadataRef VTableHolder,
1333 const char *UniqueId, size_t UniqueIdLen) {
1334 auto Elts = unwrap(Builder)->getOrCreateArray({unwrap(Elements),
1335 NumElements});
1336 return wrap(unwrap(Builder)->createStructType(
1337 unwrapDI<DIScope>(Scope), {Name, NameLen}, unwrapDI<DIFile>(File),
1338 LineNumber, SizeInBits, AlignInBits, map_from_llvmDIFlags(Flags),
1339 unwrapDI<DIType>(DerivedFrom), Elts, RunTimeLang,
1340 unwrapDI<DIType>(VTableHolder), {UniqueId, UniqueIdLen}));
1343 LLVMMetadataRef LLVMDIBuilderCreateMemberType(
1344 LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
1345 size_t NameLen, LLVMMetadataRef File, unsigned LineNo, uint64_t SizeInBits,
1346 uint32_t AlignInBits, uint64_t OffsetInBits, LLVMDIFlags Flags,
1347 LLVMMetadataRef Ty) {
1348 return wrap(unwrap(Builder)->createMemberType(unwrapDI<DIScope>(Scope),
1349 {Name, NameLen}, unwrapDI<DIFile>(File), LineNo, SizeInBits, AlignInBits,
1350 OffsetInBits, map_from_llvmDIFlags(Flags), unwrapDI<DIType>(Ty)));
1353 LLVMMetadataRef
1354 LLVMDIBuilderCreateUnspecifiedType(LLVMDIBuilderRef Builder, const char *Name,
1355 size_t NameLen) {
1356 return wrap(unwrap(Builder)->createUnspecifiedType({Name, NameLen}));
1359 LLVMMetadataRef LLVMDIBuilderCreateStaticMemberType(
1360 LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
1361 size_t NameLen, LLVMMetadataRef File, unsigned LineNumber,
1362 LLVMMetadataRef Type, LLVMDIFlags Flags, LLVMValueRef ConstantVal,
1363 uint32_t AlignInBits) {
1364 return wrap(unwrap(Builder)->createStaticMemberType(
1365 unwrapDI<DIScope>(Scope), {Name, NameLen}, unwrapDI<DIFile>(File),
1366 LineNumber, unwrapDI<DIType>(Type), map_from_llvmDIFlags(Flags),
1367 unwrap<Constant>(ConstantVal), DW_TAG_member, AlignInBits));
1370 LLVMMetadataRef
1371 LLVMDIBuilderCreateObjCIVar(LLVMDIBuilderRef Builder,
1372 const char *Name, size_t NameLen,
1373 LLVMMetadataRef File, unsigned LineNo,
1374 uint64_t SizeInBits, uint32_t AlignInBits,
1375 uint64_t OffsetInBits, LLVMDIFlags Flags,
1376 LLVMMetadataRef Ty, LLVMMetadataRef PropertyNode) {
1377 return wrap(unwrap(Builder)->createObjCIVar(
1378 {Name, NameLen}, unwrapDI<DIFile>(File), LineNo,
1379 SizeInBits, AlignInBits, OffsetInBits,
1380 map_from_llvmDIFlags(Flags), unwrapDI<DIType>(Ty),
1381 unwrapDI<MDNode>(PropertyNode)));
1384 LLVMMetadataRef
1385 LLVMDIBuilderCreateObjCProperty(LLVMDIBuilderRef Builder,
1386 const char *Name, size_t NameLen,
1387 LLVMMetadataRef File, unsigned LineNo,
1388 const char *GetterName, size_t GetterNameLen,
1389 const char *SetterName, size_t SetterNameLen,
1390 unsigned PropertyAttributes,
1391 LLVMMetadataRef Ty) {
1392 return wrap(unwrap(Builder)->createObjCProperty(
1393 {Name, NameLen}, unwrapDI<DIFile>(File), LineNo,
1394 {GetterName, GetterNameLen}, {SetterName, SetterNameLen},
1395 PropertyAttributes, unwrapDI<DIType>(Ty)));
1398 LLVMMetadataRef
1399 LLVMDIBuilderCreateObjectPointerType(LLVMDIBuilderRef Builder,
1400 LLVMMetadataRef Type) {
1401 return wrap(unwrap(Builder)->createObjectPointerType(unwrapDI<DIType>(Type)));
1404 LLVMMetadataRef
1405 LLVMDIBuilderCreateTypedef(LLVMDIBuilderRef Builder, LLVMMetadataRef Type,
1406 const char *Name, size_t NameLen,
1407 LLVMMetadataRef File, unsigned LineNo,
1408 LLVMMetadataRef Scope, uint32_t AlignInBits) {
1409 return wrap(unwrap(Builder)->createTypedef(
1410 unwrapDI<DIType>(Type), {Name, NameLen}, unwrapDI<DIFile>(File), LineNo,
1411 unwrapDI<DIScope>(Scope), AlignInBits));
1414 LLVMMetadataRef
1415 LLVMDIBuilderCreateInheritance(LLVMDIBuilderRef Builder,
1416 LLVMMetadataRef Ty, LLVMMetadataRef BaseTy,
1417 uint64_t BaseOffset, uint32_t VBPtrOffset,
1418 LLVMDIFlags Flags) {
1419 return wrap(unwrap(Builder)->createInheritance(
1420 unwrapDI<DIType>(Ty), unwrapDI<DIType>(BaseTy),
1421 BaseOffset, VBPtrOffset, map_from_llvmDIFlags(Flags)));
1424 LLVMMetadataRef
1425 LLVMDIBuilderCreateForwardDecl(
1426 LLVMDIBuilderRef Builder, unsigned Tag, const char *Name,
1427 size_t NameLen, LLVMMetadataRef Scope, LLVMMetadataRef File, unsigned Line,
1428 unsigned RuntimeLang, uint64_t SizeInBits, uint32_t AlignInBits,
1429 const char *UniqueIdentifier, size_t UniqueIdentifierLen) {
1430 return wrap(unwrap(Builder)->createForwardDecl(
1431 Tag, {Name, NameLen}, unwrapDI<DIScope>(Scope),
1432 unwrapDI<DIFile>(File), Line, RuntimeLang, SizeInBits,
1433 AlignInBits, {UniqueIdentifier, UniqueIdentifierLen}));
1436 LLVMMetadataRef
1437 LLVMDIBuilderCreateReplaceableCompositeType(
1438 LLVMDIBuilderRef Builder, unsigned Tag, const char *Name,
1439 size_t NameLen, LLVMMetadataRef Scope, LLVMMetadataRef File, unsigned Line,
1440 unsigned RuntimeLang, uint64_t SizeInBits, uint32_t AlignInBits,
1441 LLVMDIFlags Flags, const char *UniqueIdentifier,
1442 size_t UniqueIdentifierLen) {
1443 return wrap(unwrap(Builder)->createReplaceableCompositeType(
1444 Tag, {Name, NameLen}, unwrapDI<DIScope>(Scope),
1445 unwrapDI<DIFile>(File), Line, RuntimeLang, SizeInBits,
1446 AlignInBits, map_from_llvmDIFlags(Flags),
1447 {UniqueIdentifier, UniqueIdentifierLen}));
1450 LLVMMetadataRef
1451 LLVMDIBuilderCreateQualifiedType(LLVMDIBuilderRef Builder, unsigned Tag,
1452 LLVMMetadataRef Type) {
1453 return wrap(unwrap(Builder)->createQualifiedType(Tag,
1454 unwrapDI<DIType>(Type)));
1457 LLVMMetadataRef
1458 LLVMDIBuilderCreateReferenceType(LLVMDIBuilderRef Builder, unsigned Tag,
1459 LLVMMetadataRef Type) {
1460 return wrap(unwrap(Builder)->createReferenceType(Tag,
1461 unwrapDI<DIType>(Type)));
1464 LLVMMetadataRef
1465 LLVMDIBuilderCreateNullPtrType(LLVMDIBuilderRef Builder) {
1466 return wrap(unwrap(Builder)->createNullPtrType());
1469 LLVMMetadataRef
1470 LLVMDIBuilderCreateMemberPointerType(LLVMDIBuilderRef Builder,
1471 LLVMMetadataRef PointeeType,
1472 LLVMMetadataRef ClassType,
1473 uint64_t SizeInBits,
1474 uint32_t AlignInBits,
1475 LLVMDIFlags Flags) {
1476 return wrap(unwrap(Builder)->createMemberPointerType(
1477 unwrapDI<DIType>(PointeeType),
1478 unwrapDI<DIType>(ClassType), AlignInBits, SizeInBits,
1479 map_from_llvmDIFlags(Flags)));
1482 LLVMMetadataRef
1483 LLVMDIBuilderCreateBitFieldMemberType(LLVMDIBuilderRef Builder,
1484 LLVMMetadataRef Scope,
1485 const char *Name, size_t NameLen,
1486 LLVMMetadataRef File, unsigned LineNumber,
1487 uint64_t SizeInBits,
1488 uint64_t OffsetInBits,
1489 uint64_t StorageOffsetInBits,
1490 LLVMDIFlags Flags, LLVMMetadataRef Type) {
1491 return wrap(unwrap(Builder)->createBitFieldMemberType(
1492 unwrapDI<DIScope>(Scope), {Name, NameLen},
1493 unwrapDI<DIFile>(File), LineNumber,
1494 SizeInBits, OffsetInBits, StorageOffsetInBits,
1495 map_from_llvmDIFlags(Flags), unwrapDI<DIType>(Type)));
1498 LLVMMetadataRef LLVMDIBuilderCreateClassType(LLVMDIBuilderRef Builder,
1499 LLVMMetadataRef Scope, const char *Name, size_t NameLen,
1500 LLVMMetadataRef File, unsigned LineNumber, uint64_t SizeInBits,
1501 uint32_t AlignInBits, uint64_t OffsetInBits, LLVMDIFlags Flags,
1502 LLVMMetadataRef DerivedFrom,
1503 LLVMMetadataRef *Elements, unsigned NumElements,
1504 LLVMMetadataRef VTableHolder, LLVMMetadataRef TemplateParamsNode,
1505 const char *UniqueIdentifier, size_t UniqueIdentifierLen) {
1506 auto Elts = unwrap(Builder)->getOrCreateArray({unwrap(Elements),
1507 NumElements});
1508 return wrap(unwrap(Builder)->createClassType(
1509 unwrapDI<DIScope>(Scope), {Name, NameLen}, unwrapDI<DIFile>(File),
1510 LineNumber, SizeInBits, AlignInBits, OffsetInBits,
1511 map_from_llvmDIFlags(Flags), unwrapDI<DIType>(DerivedFrom), Elts,
1512 /*RunTimeLang=*/0, unwrapDI<DIType>(VTableHolder),
1513 unwrapDI<MDNode>(TemplateParamsNode),
1514 {UniqueIdentifier, UniqueIdentifierLen}));
1517 LLVMMetadataRef
1518 LLVMDIBuilderCreateArtificialType(LLVMDIBuilderRef Builder,
1519 LLVMMetadataRef Type) {
1520 return wrap(unwrap(Builder)->createArtificialType(unwrapDI<DIType>(Type)));
1523 uint16_t LLVMGetDINodeTag(LLVMMetadataRef MD) {
1524 return unwrapDI<DINode>(MD)->getTag();
1527 const char *LLVMDITypeGetName(LLVMMetadataRef DType, size_t *Length) {
1528 StringRef Str = unwrapDI<DIType>(DType)->getName();
1529 *Length = Str.size();
1530 return Str.data();
1533 uint64_t LLVMDITypeGetSizeInBits(LLVMMetadataRef DType) {
1534 return unwrapDI<DIType>(DType)->getSizeInBits();
1537 uint64_t LLVMDITypeGetOffsetInBits(LLVMMetadataRef DType) {
1538 return unwrapDI<DIType>(DType)->getOffsetInBits();
1541 uint32_t LLVMDITypeGetAlignInBits(LLVMMetadataRef DType) {
1542 return unwrapDI<DIType>(DType)->getAlignInBits();
1545 unsigned LLVMDITypeGetLine(LLVMMetadataRef DType) {
1546 return unwrapDI<DIType>(DType)->getLine();
1549 LLVMDIFlags LLVMDITypeGetFlags(LLVMMetadataRef DType) {
1550 return map_to_llvmDIFlags(unwrapDI<DIType>(DType)->getFlags());
1553 LLVMMetadataRef LLVMDIBuilderGetOrCreateTypeArray(LLVMDIBuilderRef Builder,
1554 LLVMMetadataRef *Types,
1555 size_t Length) {
1556 return wrap(
1557 unwrap(Builder)->getOrCreateTypeArray({unwrap(Types), Length}).get());
1560 LLVMMetadataRef
1561 LLVMDIBuilderCreateSubroutineType(LLVMDIBuilderRef Builder,
1562 LLVMMetadataRef File,
1563 LLVMMetadataRef *ParameterTypes,
1564 unsigned NumParameterTypes,
1565 LLVMDIFlags Flags) {
1566 auto Elts = unwrap(Builder)->getOrCreateTypeArray({unwrap(ParameterTypes),
1567 NumParameterTypes});
1568 return wrap(unwrap(Builder)->createSubroutineType(
1569 Elts, map_from_llvmDIFlags(Flags)));
1572 LLVMMetadataRef LLVMDIBuilderCreateExpression(LLVMDIBuilderRef Builder,
1573 uint64_t *Addr, size_t Length) {
1574 return wrap(
1575 unwrap(Builder)->createExpression(ArrayRef<uint64_t>(Addr, Length)));
1578 LLVMMetadataRef
1579 LLVMDIBuilderCreateConstantValueExpression(LLVMDIBuilderRef Builder,
1580 uint64_t Value) {
1581 return wrap(unwrap(Builder)->createConstantValueExpression(Value));
1584 LLVMMetadataRef LLVMDIBuilderCreateGlobalVariableExpression(
1585 LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
1586 size_t NameLen, const char *Linkage, size_t LinkLen, LLVMMetadataRef File,
1587 unsigned LineNo, LLVMMetadataRef Ty, LLVMBool LocalToUnit,
1588 LLVMMetadataRef Expr, LLVMMetadataRef Decl, uint32_t AlignInBits) {
1589 return wrap(unwrap(Builder)->createGlobalVariableExpression(
1590 unwrapDI<DIScope>(Scope), {Name, NameLen}, {Linkage, LinkLen},
1591 unwrapDI<DIFile>(File), LineNo, unwrapDI<DIType>(Ty), LocalToUnit,
1592 true, unwrap<DIExpression>(Expr), unwrapDI<MDNode>(Decl),
1593 nullptr, AlignInBits));
1596 LLVMMetadataRef LLVMDIGlobalVariableExpressionGetVariable(LLVMMetadataRef GVE) {
1597 return wrap(unwrapDI<DIGlobalVariableExpression>(GVE)->getVariable());
1600 LLVMMetadataRef LLVMDIGlobalVariableExpressionGetExpression(
1601 LLVMMetadataRef GVE) {
1602 return wrap(unwrapDI<DIGlobalVariableExpression>(GVE)->getExpression());
1605 LLVMMetadataRef LLVMDIVariableGetFile(LLVMMetadataRef Var) {
1606 return wrap(unwrapDI<DIVariable>(Var)->getFile());
1609 LLVMMetadataRef LLVMDIVariableGetScope(LLVMMetadataRef Var) {
1610 return wrap(unwrapDI<DIVariable>(Var)->getScope());
1613 unsigned LLVMDIVariableGetLine(LLVMMetadataRef Var) {
1614 return unwrapDI<DIVariable>(Var)->getLine();
1617 LLVMMetadataRef LLVMTemporaryMDNode(LLVMContextRef Ctx, LLVMMetadataRef *Data,
1618 size_t Count) {
1619 return wrap(
1620 MDTuple::getTemporary(*unwrap(Ctx), {unwrap(Data), Count}).release());
1623 void LLVMDisposeTemporaryMDNode(LLVMMetadataRef TempNode) {
1624 MDNode::deleteTemporary(unwrapDI<MDNode>(TempNode));
1627 void LLVMMetadataReplaceAllUsesWith(LLVMMetadataRef TargetMetadata,
1628 LLVMMetadataRef Replacement) {
1629 auto *Node = unwrapDI<MDNode>(TargetMetadata);
1630 Node->replaceAllUsesWith(unwrap(Replacement));
1631 MDNode::deleteTemporary(Node);
1634 LLVMMetadataRef LLVMDIBuilderCreateTempGlobalVariableFwdDecl(
1635 LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
1636 size_t NameLen, const char *Linkage, size_t LnkLen, LLVMMetadataRef File,
1637 unsigned LineNo, LLVMMetadataRef Ty, LLVMBool LocalToUnit,
1638 LLVMMetadataRef Decl, uint32_t AlignInBits) {
1639 return wrap(unwrap(Builder)->createTempGlobalVariableFwdDecl(
1640 unwrapDI<DIScope>(Scope), {Name, NameLen}, {Linkage, LnkLen},
1641 unwrapDI<DIFile>(File), LineNo, unwrapDI<DIType>(Ty), LocalToUnit,
1642 unwrapDI<MDNode>(Decl), nullptr, AlignInBits));
1645 LLVMValueRef
1646 LLVMDIBuilderInsertDeclareBefore(LLVMDIBuilderRef Builder, LLVMValueRef Storage,
1647 LLVMMetadataRef VarInfo, LLVMMetadataRef Expr,
1648 LLVMMetadataRef DL, LLVMValueRef Instr) {
1649 return wrap(unwrap(Builder)->insertDeclare(
1650 unwrap(Storage), unwrap<DILocalVariable>(VarInfo),
1651 unwrap<DIExpression>(Expr), unwrap<DILocation>(DL),
1652 unwrap<Instruction>(Instr)));
1655 LLVMValueRef LLVMDIBuilderInsertDeclareAtEnd(
1656 LLVMDIBuilderRef Builder, LLVMValueRef Storage, LLVMMetadataRef VarInfo,
1657 LLVMMetadataRef Expr, LLVMMetadataRef DL, LLVMBasicBlockRef Block) {
1658 return wrap(unwrap(Builder)->insertDeclare(
1659 unwrap(Storage), unwrap<DILocalVariable>(VarInfo),
1660 unwrap<DIExpression>(Expr), unwrap<DILocation>(DL),
1661 unwrap(Block)));
1664 LLVMValueRef LLVMDIBuilderInsertDbgValueBefore(LLVMDIBuilderRef Builder,
1665 LLVMValueRef Val,
1666 LLVMMetadataRef VarInfo,
1667 LLVMMetadataRef Expr,
1668 LLVMMetadataRef DebugLoc,
1669 LLVMValueRef Instr) {
1670 return wrap(unwrap(Builder)->insertDbgValueIntrinsic(
1671 unwrap(Val), unwrap<DILocalVariable>(VarInfo),
1672 unwrap<DIExpression>(Expr), unwrap<DILocation>(DebugLoc),
1673 unwrap<Instruction>(Instr)));
1676 LLVMValueRef LLVMDIBuilderInsertDbgValueAtEnd(LLVMDIBuilderRef Builder,
1677 LLVMValueRef Val,
1678 LLVMMetadataRef VarInfo,
1679 LLVMMetadataRef Expr,
1680 LLVMMetadataRef DebugLoc,
1681 LLVMBasicBlockRef Block) {
1682 return wrap(unwrap(Builder)->insertDbgValueIntrinsic(
1683 unwrap(Val), unwrap<DILocalVariable>(VarInfo),
1684 unwrap<DIExpression>(Expr), unwrap<DILocation>(DebugLoc),
1685 unwrap(Block)));
1688 LLVMMetadataRef LLVMDIBuilderCreateAutoVariable(
1689 LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
1690 size_t NameLen, LLVMMetadataRef File, unsigned LineNo, LLVMMetadataRef Ty,
1691 LLVMBool AlwaysPreserve, LLVMDIFlags Flags, uint32_t AlignInBits) {
1692 return wrap(unwrap(Builder)->createAutoVariable(
1693 unwrap<DIScope>(Scope), {Name, NameLen}, unwrap<DIFile>(File),
1694 LineNo, unwrap<DIType>(Ty), AlwaysPreserve,
1695 map_from_llvmDIFlags(Flags), AlignInBits));
1698 LLVMMetadataRef LLVMDIBuilderCreateParameterVariable(
1699 LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
1700 size_t NameLen, unsigned ArgNo, LLVMMetadataRef File, unsigned LineNo,
1701 LLVMMetadataRef Ty, LLVMBool AlwaysPreserve, LLVMDIFlags Flags) {
1702 return wrap(unwrap(Builder)->createParameterVariable(
1703 unwrap<DIScope>(Scope), {Name, NameLen}, ArgNo, unwrap<DIFile>(File),
1704 LineNo, unwrap<DIType>(Ty), AlwaysPreserve,
1705 map_from_llvmDIFlags(Flags)));
1708 LLVMMetadataRef LLVMDIBuilderGetOrCreateSubrange(LLVMDIBuilderRef Builder,
1709 int64_t Lo, int64_t Count) {
1710 return wrap(unwrap(Builder)->getOrCreateSubrange(Lo, Count));
1713 LLVMMetadataRef LLVMDIBuilderGetOrCreateArray(LLVMDIBuilderRef Builder,
1714 LLVMMetadataRef *Data,
1715 size_t Length) {
1716 Metadata **DataValue = unwrap(Data);
1717 return wrap(unwrap(Builder)->getOrCreateArray({DataValue, Length}).get());
1720 LLVMMetadataRef LLVMGetSubprogram(LLVMValueRef Func) {
1721 return wrap(unwrap<Function>(Func)->getSubprogram());
1724 void LLVMSetSubprogram(LLVMValueRef Func, LLVMMetadataRef SP) {
1725 unwrap<Function>(Func)->setSubprogram(unwrap<DISubprogram>(SP));
1728 unsigned LLVMDISubprogramGetLine(LLVMMetadataRef Subprogram) {
1729 return unwrapDI<DISubprogram>(Subprogram)->getLine();
1732 LLVMMetadataRef LLVMInstructionGetDebugLoc(LLVMValueRef Inst) {
1733 return wrap(unwrap<Instruction>(Inst)->getDebugLoc().getAsMDNode());
1736 void LLVMInstructionSetDebugLoc(LLVMValueRef Inst, LLVMMetadataRef Loc) {
1737 if (Loc)
1738 unwrap<Instruction>(Inst)->setDebugLoc(DebugLoc(unwrap<MDNode>(Loc)));
1739 else
1740 unwrap<Instruction>(Inst)->setDebugLoc(DebugLoc());
1743 LLVMMetadataKind LLVMGetMetadataKind(LLVMMetadataRef Metadata) {
1744 switch(unwrap(Metadata)->getMetadataID()) {
1745 #define HANDLE_METADATA_LEAF(CLASS) \
1746 case Metadata::CLASS##Kind: \
1747 return (LLVMMetadataKind)LLVM##CLASS##MetadataKind;
1748 #include "llvm/IR/Metadata.def"
1749 default:
1750 return (LLVMMetadataKind)LLVMGenericDINodeMetadataKind;
1754 AssignmentInstRange at::getAssignmentInsts(DIAssignID *ID) {
1755 assert(ID && "Expected non-null ID");
1756 LLVMContext &Ctx = ID->getContext();
1757 auto &Map = Ctx.pImpl->AssignmentIDToInstrs;
1759 auto MapIt = Map.find(ID);
1760 if (MapIt == Map.end())
1761 return make_range(nullptr, nullptr);
1763 return make_range(MapIt->second.begin(), MapIt->second.end());
1766 AssignmentMarkerRange at::getAssignmentMarkers(DIAssignID *ID) {
1767 assert(ID && "Expected non-null ID");
1768 LLVMContext &Ctx = ID->getContext();
1770 auto *IDAsValue = MetadataAsValue::getIfExists(Ctx, ID);
1772 // The ID is only used wrapped in MetadataAsValue(ID), so lets check that
1773 // one of those already exists first.
1774 if (!IDAsValue)
1775 return make_range(Value::user_iterator(), Value::user_iterator());
1777 return make_range(IDAsValue->user_begin(), IDAsValue->user_end());
1780 void at::deleteAssignmentMarkers(const Instruction *Inst) {
1781 auto Range = getAssignmentMarkers(Inst);
1782 if (Range.empty())
1783 return;
1784 SmallVector<DbgAssignIntrinsic *> ToDelete(Range.begin(), Range.end());
1785 for (auto *DAI : ToDelete)
1786 DAI->eraseFromParent();
1789 void at::RAUW(DIAssignID *Old, DIAssignID *New) {
1790 // Replace attachments.
1791 AssignmentInstRange InstRange = getAssignmentInsts(Old);
1792 // Use intermediate storage for the instruction ptrs because the
1793 // getAssignmentInsts range iterators will be invalidated by adding and
1794 // removing DIAssignID attachments.
1795 SmallVector<Instruction *> InstVec(InstRange.begin(), InstRange.end());
1796 for (auto *I : InstVec)
1797 I->setMetadata(LLVMContext::MD_DIAssignID, New);
1799 Old->replaceAllUsesWith(New);
1802 void at::deleteAll(Function *F) {
1803 SmallVector<DbgAssignIntrinsic *, 12> ToDelete;
1804 for (BasicBlock &BB : *F) {
1805 for (Instruction &I : BB) {
1806 if (auto *DAI = dyn_cast<DbgAssignIntrinsic>(&I))
1807 ToDelete.push_back(DAI);
1808 else
1809 I.setMetadata(LLVMContext::MD_DIAssignID, nullptr);
1812 for (auto *DAI : ToDelete)
1813 DAI->eraseFromParent();
1816 bool at::calculateFragmentIntersect(
1817 const DataLayout &DL, const Value *Dest, uint64_t SliceOffsetInBits,
1818 uint64_t SliceSizeInBits, const DbgAssignIntrinsic *DAI,
1819 std::optional<DIExpression::FragmentInfo> &Result) {
1820 // There are multiple offsets at play in this function, so let's break it
1821 // down. Starting with how variables may be stored in allocas:
1823 // 1 Simplest case: variable is alloca sized and starts at offset 0.
1824 // 2 Variable is larger than the alloca: the alloca holds just a part of it.
1825 // 3 Variable is smaller than the alloca: the alloca may hold multiple
1826 // variables.
1828 // Imagine we have a store to the entire alloca. In case (3) the store
1829 // affects bits outside of the bounds of each variable. In case (2), where
1830 // the alloca holds the Xth bit to the Yth bit of a variable, the
1831 // zero-offset store doesn't represent an assignment at offset zero to the
1832 // variable. It is an assignment to offset X.
1834 // # Example 1
1835 // Obviously, not all stores are alloca-sized and have zero offset. Imagine
1836 // the lower 32 bits of this store are dead and are going to be DSEd:
1838 // store i64 %v, ptr %dest, !DIAssignID !1
1839 // dbg.assign(..., !DIExpression(fragment, 128, 32), !1, %dest,
1840 // !DIExpression(DW_OP_plus_uconst, 4))
1842 // Goal: Given our dead bits at offset:0 size:32 for the store, determine the
1843 // part of the variable, which fits in the fragment expressed by the
1844 // dbg.assign, that has been killed, if any.
1846 // calculateFragmentIntersect(..., SliceOffsetInBits=0,
1847 // SliceSizeInBits=32, Dest=%dest, DAI=dbg.assign)
1849 // Drawing the store (s) in memory followed by the shortened version ($),
1850 // then the dbg.assign (d), with the fragment information on a seperate scale
1851 // underneath:
1853 // Memory
1854 // offset
1855 // from
1856 // dest 0 63
1857 // | |
1858 // s[######] - Original stores 64 bits to Dest.
1859 // $----[##] - DSE says the lower 32 bits are dead, to be removed.
1860 // d [##] - DAI's address-modifying expression adds 4 bytes to dest.
1861 // Variable | |
1862 // Fragment 128|
1863 // Offsets 159
1865 // The answer is achieved in a few steps:
1866 // 1. Add the fragment offset to the store offset:
1867 // SliceOffsetInBits:0 + VarFrag.OffsetInBits:128 = 128
1869 // 2. Subtract the address-modifying expression offset plus difference
1870 // between d.address and dest:
1871 // 128 - (expression_offset:32 + (d.address - dest):0) = 96
1873 // 3. That offset along with the store size (32) represents the bits of the
1874 // variable that'd be affected by the store. Call it SliceOfVariable.
1875 // Intersect that with DAI's fragment info:
1876 // SliceOfVariable ∩ DAI_fragment = none
1878 // In this case: none of the dead bits of the store affect DAI.
1880 // # Example 2
1881 // Similar example with the same goal. This time the upper 16 bits
1882 // of the store are going to be DSE'd.
1884 // store i64 %v, ptr %dest, !DIAssignID !1
1885 // dbg.assign(..., !DIExpression(fragment, 128, 32), !1, %dest,
1886 // !DIExpression(DW_OP_plus_uconst, 4))
1888 // calculateFragmentIntersect(..., SliceOffsetInBits=48,
1889 // SliceSizeInBits=16, Dest=%dest, DAI=dbg.assign)
1891 // Memory
1892 // offset
1893 // from
1894 // dest 0 63
1895 // | |
1896 // s[######] - Original stores 64 bits to Dest.
1897 // $[####]-- - DSE says the upper 16 bits are dead, to be removed.
1898 // d [##] - DAI's address-modifying expression adds 4 bytes to dest.
1899 // Variable | |
1900 // Fragment 128|
1901 // Offsets 159
1903 // Using the same steps in the first example:
1904 // 1. SliceOffsetInBits:48 + VarFrag.OffsetInBits:128 = 176
1905 // 2. 176 - (expression_offset:32 + (d.address - dest):0) = 144
1906 // 3. SliceOfVariable offset = 144, size = 16:
1907 // SliceOfVariable ∩ DAI_fragment = (offset: 144, size: 16)
1908 // SliceOfVariable tells us the bits of the variable described by DAI that are
1909 // affected by the DSE.
1910 if (DAI->isKillAddress())
1911 return false;
1913 DIExpression::FragmentInfo VarFrag = DAI->getFragmentOrEntireVariable();
1914 if (VarFrag.SizeInBits == 0)
1915 return false; // Variable size is unknown.
1917 // Calculate the difference between Dest and the dbg.assign address +
1918 // address-modifying expression.
1919 int64_t PointerOffsetInBits;
1921 auto DestOffsetInBytes = DAI->getAddress()->getPointerOffsetFrom(Dest, DL);
1922 if (!DestOffsetInBytes)
1923 return false; // Can't calculate difference in addresses.
1925 int64_t ExprOffsetInBytes;
1926 if (!DAI->getAddressExpression()->extractIfOffset(ExprOffsetInBytes))
1927 return false;
1929 int64_t PointerOffsetInBytes = *DestOffsetInBytes + ExprOffsetInBytes;
1930 PointerOffsetInBits = PointerOffsetInBytes * 8;
1933 // Adjust the slice offset so that we go from describing the a slice
1934 // of memory to a slice of the variable.
1935 int64_t NewOffsetInBits =
1936 SliceOffsetInBits + VarFrag.OffsetInBits - PointerOffsetInBits;
1937 if (NewOffsetInBits < 0)
1938 return false; // Fragment offsets can only be positive.
1939 DIExpression::FragmentInfo SliceOfVariable(SliceSizeInBits, NewOffsetInBits);
1940 // Intersect the variable slice with DAI's fragment to trim it down to size.
1941 DIExpression::FragmentInfo TrimmedSliceOfVariable =
1942 DIExpression::FragmentInfo::intersect(SliceOfVariable, VarFrag);
1943 if (TrimmedSliceOfVariable == VarFrag)
1944 Result = std::nullopt;
1945 else
1946 Result = TrimmedSliceOfVariable;
1947 return true;
1950 /// Collect constant properies (base, size, offset) of \p StoreDest.
1951 /// Return std::nullopt if any properties are not constants or the
1952 /// offset from the base pointer is negative.
1953 static std::optional<AssignmentInfo>
1954 getAssignmentInfoImpl(const DataLayout &DL, const Value *StoreDest,
1955 TypeSize SizeInBits) {
1956 if (SizeInBits.isScalable())
1957 return std::nullopt;
1958 APInt GEPOffset(DL.getIndexTypeSizeInBits(StoreDest->getType()), 0);
1959 const Value *Base = StoreDest->stripAndAccumulateConstantOffsets(
1960 DL, GEPOffset, /*AllowNonInbounds*/ true);
1962 if (GEPOffset.isNegative())
1963 return std::nullopt;
1965 uint64_t OffsetInBytes = GEPOffset.getLimitedValue();
1966 // Check for overflow.
1967 if (OffsetInBytes == UINT64_MAX)
1968 return std::nullopt;
1969 if (const auto *Alloca = dyn_cast<AllocaInst>(Base))
1970 return AssignmentInfo(DL, Alloca, OffsetInBytes * 8, SizeInBits);
1971 return std::nullopt;
1974 std::optional<AssignmentInfo> at::getAssignmentInfo(const DataLayout &DL,
1975 const MemIntrinsic *I) {
1976 const Value *StoreDest = I->getRawDest();
1977 // Assume 8 bit bytes.
1978 auto *ConstLengthInBytes = dyn_cast<ConstantInt>(I->getLength());
1979 if (!ConstLengthInBytes)
1980 // We can't use a non-const size, bail.
1981 return std::nullopt;
1982 uint64_t SizeInBits = 8 * ConstLengthInBytes->getZExtValue();
1983 return getAssignmentInfoImpl(DL, StoreDest, TypeSize::getFixed(SizeInBits));
1986 std::optional<AssignmentInfo> at::getAssignmentInfo(const DataLayout &DL,
1987 const StoreInst *SI) {
1988 TypeSize SizeInBits = DL.getTypeSizeInBits(SI->getValueOperand()->getType());
1989 return getAssignmentInfoImpl(DL, SI->getPointerOperand(), SizeInBits);
1992 std::optional<AssignmentInfo> at::getAssignmentInfo(const DataLayout &DL,
1993 const AllocaInst *AI) {
1994 TypeSize SizeInBits = DL.getTypeSizeInBits(AI->getAllocatedType());
1995 return getAssignmentInfoImpl(DL, AI, SizeInBits);
1998 /// Returns nullptr if the assignment shouldn't be attributed to this variable.
1999 static CallInst *emitDbgAssign(AssignmentInfo Info, Value *Val, Value *Dest,
2000 Instruction &StoreLikeInst,
2001 const VarRecord &VarRec, DIBuilder &DIB) {
2002 auto *ID = StoreLikeInst.getMetadata(LLVMContext::MD_DIAssignID);
2003 assert(ID && "Store instruction must have DIAssignID metadata");
2004 (void)ID;
2006 const uint64_t StoreStartBit = Info.OffsetInBits;
2007 const uint64_t StoreEndBit = Info.OffsetInBits + Info.SizeInBits;
2009 uint64_t FragStartBit = StoreStartBit;
2010 uint64_t FragEndBit = StoreEndBit;
2012 bool StoreToWholeVariable = Info.StoreToWholeAlloca;
2013 if (auto Size = VarRec.Var->getSizeInBits()) {
2014 // NOTE: trackAssignments doesn't understand base expressions yet, so all
2015 // variables that reach here are guaranteed to start at offset 0 in the
2016 // alloca.
2017 const uint64_t VarStartBit = 0;
2018 const uint64_t VarEndBit = *Size;
2020 // FIXME: trim FragStartBit when nonzero VarStartBit is supported.
2021 FragEndBit = std::min(FragEndBit, VarEndBit);
2023 // Discard stores to bits outside this variable.
2024 if (FragStartBit >= FragEndBit)
2025 return nullptr;
2027 StoreToWholeVariable = FragStartBit <= VarStartBit && FragEndBit >= *Size;
2030 DIExpression *Expr =
2031 DIExpression::get(StoreLikeInst.getContext(), std::nullopt);
2032 if (!StoreToWholeVariable) {
2033 auto R = DIExpression::createFragmentExpression(Expr, FragStartBit,
2034 FragEndBit - FragStartBit);
2035 assert(R.has_value() && "failed to create fragment expression");
2036 Expr = *R;
2038 DIExpression *AddrExpr =
2039 DIExpression::get(StoreLikeInst.getContext(), std::nullopt);
2040 return DIB.insertDbgAssign(&StoreLikeInst, Val, VarRec.Var, Expr, Dest,
2041 AddrExpr, VarRec.DL);
2044 #undef DEBUG_TYPE // Silence redefinition warning (from ConstantsContext.h).
2045 #define DEBUG_TYPE "assignment-tracking"
2047 void at::trackAssignments(Function::iterator Start, Function::iterator End,
2048 const StorageToVarsMap &Vars, const DataLayout &DL,
2049 bool DebugPrints) {
2050 // Early-exit if there are no interesting variables.
2051 if (Vars.empty())
2052 return;
2054 auto &Ctx = Start->getContext();
2055 auto &Module = *Start->getModule();
2057 // Undef type doesn't matter, so long as it isn't void. Let's just use i1.
2058 auto *Undef = UndefValue::get(Type::getInt1Ty(Ctx));
2059 DIBuilder DIB(Module, /*AllowUnresolved*/ false);
2061 // Scan the instructions looking for stores to local variables' storage.
2062 LLVM_DEBUG(errs() << "# Scanning instructions\n");
2063 for (auto BBI = Start; BBI != End; ++BBI) {
2064 for (Instruction &I : *BBI) {
2066 std::optional<AssignmentInfo> Info;
2067 Value *ValueComponent = nullptr;
2068 Value *DestComponent = nullptr;
2069 if (auto *AI = dyn_cast<AllocaInst>(&I)) {
2070 // We want to track the variable's stack home from its alloca's
2071 // position onwards so we treat it as an assignment (where the stored
2072 // value is Undef).
2073 Info = getAssignmentInfo(DL, AI);
2074 ValueComponent = Undef;
2075 DestComponent = AI;
2076 } else if (auto *SI = dyn_cast<StoreInst>(&I)) {
2077 Info = getAssignmentInfo(DL, SI);
2078 ValueComponent = SI->getValueOperand();
2079 DestComponent = SI->getPointerOperand();
2080 } else if (auto *MI = dyn_cast<MemTransferInst>(&I)) {
2081 Info = getAssignmentInfo(DL, MI);
2082 // May not be able to represent this value easily.
2083 ValueComponent = Undef;
2084 DestComponent = MI->getOperand(0);
2085 } else if (auto *MI = dyn_cast<MemSetInst>(&I)) {
2086 Info = getAssignmentInfo(DL, MI);
2087 // If we're zero-initing we can state the assigned value is zero,
2088 // otherwise use undef.
2089 auto *ConstValue = dyn_cast<ConstantInt>(MI->getOperand(1));
2090 if (ConstValue && ConstValue->isZero())
2091 ValueComponent = ConstValue;
2092 else
2093 ValueComponent = Undef;
2094 DestComponent = MI->getOperand(0);
2095 } else {
2096 // Not a store-like instruction.
2097 continue;
2100 assert(ValueComponent && DestComponent);
2101 LLVM_DEBUG(errs() << "SCAN: Found store-like: " << I << "\n");
2103 // Check if getAssignmentInfo failed to understand this store.
2104 if (!Info.has_value()) {
2105 LLVM_DEBUG(
2106 errs()
2107 << " | SKIP: Untrackable store (e.g. through non-const gep)\n");
2108 continue;
2110 LLVM_DEBUG(errs() << " | BASE: " << *Info->Base << "\n");
2112 // Check if the store destination is a local variable with debug info.
2113 auto LocalIt = Vars.find(Info->Base);
2114 if (LocalIt == Vars.end()) {
2115 LLVM_DEBUG(
2116 errs()
2117 << " | SKIP: Base address not associated with local variable\n");
2118 continue;
2121 DIAssignID *ID =
2122 cast_or_null<DIAssignID>(I.getMetadata(LLVMContext::MD_DIAssignID));
2123 if (!ID) {
2124 ID = DIAssignID::getDistinct(Ctx);
2125 I.setMetadata(LLVMContext::MD_DIAssignID, ID);
2128 for (const VarRecord &R : LocalIt->second) {
2129 auto *Assign =
2130 emitDbgAssign(*Info, ValueComponent, DestComponent, I, R, DIB);
2131 (void)Assign;
2132 LLVM_DEBUG(if (Assign) errs() << " > INSERT: " << *Assign << "\n");
2138 bool AssignmentTrackingPass::runOnFunction(Function &F) {
2139 // No value in assignment tracking without optimisations.
2140 if (F.hasFnAttribute(Attribute::OptimizeNone))
2141 return /*Changed*/ false;
2143 // FIXME: https://github.com/llvm/llvm-project/issues/76545
2144 if (F.hasFnAttribute(Attribute::SanitizeHWAddress))
2145 return /*Changed*/ false;
2147 bool Changed = false;
2148 auto *DL = &F.getParent()->getDataLayout();
2149 // Collect a map of {backing storage : dbg.declares} (currently "backing
2150 // storage" is limited to Allocas). We'll use this to find dbg.declares to
2151 // delete after running `trackAssignments`.
2152 DenseMap<const AllocaInst *, SmallPtrSet<DbgDeclareInst *, 2>> DbgDeclares;
2153 // Create another similar map of {storage : variables} that we'll pass to
2154 // trackAssignments.
2155 StorageToVarsMap Vars;
2156 for (auto &BB : F) {
2157 for (auto &I : BB) {
2158 DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(&I);
2159 if (!DDI)
2160 continue;
2161 // FIXME: trackAssignments doesn't let you specify any modifiers to the
2162 // variable (e.g. fragment) or location (e.g. offset), so we have to
2163 // leave dbg.declares with non-empty expressions in place.
2164 if (DDI->getExpression()->getNumElements() != 0)
2165 continue;
2166 if (!DDI->getAddress())
2167 continue;
2168 if (AllocaInst *Alloca =
2169 dyn_cast<AllocaInst>(DDI->getAddress()->stripPointerCasts())) {
2170 // FIXME: Skip VLAs for now (let these variables use dbg.declares).
2171 if (!Alloca->isStaticAlloca())
2172 continue;
2173 // Similarly, skip scalable vectors (use dbg.declares instead).
2174 if (auto Sz = Alloca->getAllocationSize(*DL); Sz && Sz->isScalable())
2175 continue;
2176 DbgDeclares[Alloca].insert(DDI);
2177 Vars[Alloca].insert(VarRecord(DDI));
2182 // FIXME: Locals can be backed by caller allocas (sret, byval).
2183 // Note: trackAssignments doesn't respect dbg.declare's IR positions (as it
2184 // doesn't "understand" dbg.declares). However, this doesn't appear to break
2185 // any rules given this description of dbg.declare from
2186 // llvm/docs/SourceLevelDebugging.rst:
2188 // It is not control-dependent, meaning that if a call to llvm.dbg.declare
2189 // exists and has a valid location argument, that address is considered to
2190 // be the true home of the variable across its entire lifetime.
2191 trackAssignments(F.begin(), F.end(), Vars, *DL);
2193 // Delete dbg.declares for variables now tracked with assignment tracking.
2194 for (auto &P : DbgDeclares) {
2195 const AllocaInst *Alloca = P.first;
2196 auto Markers = at::getAssignmentMarkers(Alloca);
2197 (void)Markers;
2198 for (DbgDeclareInst *DDI : P.second) {
2199 // Assert that the alloca that DDI uses is now linked to a dbg.assign
2200 // describing the same variable (i.e. check that this dbg.declare has
2201 // been replaced by a dbg.assign). Use DebugVariableAggregate to Discard
2202 // the fragment part because trackAssignments may alter the
2203 // fragment. e.g. if the alloca is smaller than the variable, then
2204 // trackAssignments will create an alloca-sized fragment for the
2205 // dbg.assign.
2206 assert(llvm::any_of(Markers, [DDI](DbgAssignIntrinsic *DAI) {
2207 return DebugVariableAggregate(DAI) == DebugVariableAggregate(DDI);
2208 }));
2209 // Delete DDI because the variable location is now tracked using
2210 // assignment tracking.
2211 DDI->eraseFromParent();
2212 Changed = true;
2215 return Changed;
2218 static const char *AssignmentTrackingModuleFlag =
2219 "debug-info-assignment-tracking";
2221 static void setAssignmentTrackingModuleFlag(Module &M) {
2222 M.setModuleFlag(Module::ModFlagBehavior::Max, AssignmentTrackingModuleFlag,
2223 ConstantAsMetadata::get(
2224 ConstantInt::get(Type::getInt1Ty(M.getContext()), 1)));
2227 static bool getAssignmentTrackingModuleFlag(const Module &M) {
2228 Metadata *Value = M.getModuleFlag(AssignmentTrackingModuleFlag);
2229 return Value && !cast<ConstantAsMetadata>(Value)->getValue()->isZeroValue();
2232 bool llvm::isAssignmentTrackingEnabled(const Module &M) {
2233 return getAssignmentTrackingModuleFlag(M);
2236 PreservedAnalyses AssignmentTrackingPass::run(Function &F,
2237 FunctionAnalysisManager &AM) {
2238 if (!runOnFunction(F))
2239 return PreservedAnalyses::all();
2241 // Record that this module uses assignment tracking. It doesn't matter that
2242 // some functons in the module may not use it - the debug info in those
2243 // functions will still be handled properly.
2244 setAssignmentTrackingModuleFlag(*F.getParent());
2246 // Q: Can we return a less conservative set than just CFGAnalyses? Can we
2247 // return PreservedAnalyses::all()?
2248 PreservedAnalyses PA;
2249 PA.preserveSet<CFGAnalyses>();
2250 return PA;
2253 PreservedAnalyses AssignmentTrackingPass::run(Module &M,
2254 ModuleAnalysisManager &AM) {
2255 bool Changed = false;
2256 for (auto &F : M)
2257 Changed |= runOnFunction(F);
2259 if (!Changed)
2260 return PreservedAnalyses::all();
2262 // Record that this module uses assignment tracking.
2263 setAssignmentTrackingModuleFlag(M);
2265 // Q: Can we return a less conservative set than just CFGAnalyses? Can we
2266 // return PreservedAnalyses::all()?
2267 PreservedAnalyses PA;
2268 PA.preserveSet<CFGAnalyses>();
2269 return PA;
2272 #undef DEBUG_TYPE