1 //===--- DebugInfo.cpp - Debug Information Helper Classes -----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the helper classes used to build and interpret debug
11 // information in LLVM IR form.
13 //===----------------------------------------------------------------------===//
15 #include "llvm/IR/DebugInfo.h"
16 #include "LLVMContextImpl.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/SmallPtrSet.h"
19 #include "llvm/ADT/SmallString.h"
20 #include "llvm/Analysis/ValueTracking.h"
21 #include "llvm/IR/Constants.h"
22 #include "llvm/IR/DIBuilder.h"
23 #include "llvm/IR/DerivedTypes.h"
24 #include "llvm/IR/Instructions.h"
25 #include "llvm/IR/IntrinsicInst.h"
26 #include "llvm/IR/Intrinsics.h"
27 #include "llvm/IR/GVMaterializer.h"
28 #include "llvm/IR/Module.h"
29 #include "llvm/IR/ValueHandle.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/Dwarf.h"
32 #include "llvm/Support/raw_ostream.h"
34 using namespace llvm::dwarf;
36 //===----------------------------------------------------------------------===//
38 //===----------------------------------------------------------------------===//
40 static Metadata *getField(const MDNode *DbgNode, unsigned Elt) {
41 if (!DbgNode || Elt >= DbgNode->getNumOperands())
43 return DbgNode->getOperand(Elt);
46 static MDNode *getNodeField(const MDNode *DbgNode, unsigned Elt) {
47 return dyn_cast_or_null<MDNode>(getField(DbgNode, Elt));
50 DIDescriptor DIDescriptor::getDescriptorField(unsigned Elt) const {
51 MDNode *Field = getNodeField(DbgNode, Elt);
52 return DIDescriptor(Field);
55 /// \brief Return the size reported by the variable's type.
56 unsigned DIVariable::getSizeInBits(const DITypeIdentifierMap &Map) {
57 DIType Ty = getType().resolve(Map);
58 // Follow derived types until we reach a type that
59 // reports back a size.
60 while (isa<MDDerivedType>(Ty) && !Ty.getSizeInBits()) {
61 DIDerivedType DT = cast<MDDerivedType>(Ty);
62 Ty = DT.getTypeDerivedFrom().resolve(Map);
64 assert(Ty.getSizeInBits() && "type with size 0");
65 return Ty.getSizeInBits();
68 //===----------------------------------------------------------------------===//
69 // Simple Descriptor Constructors and other Methods
70 //===----------------------------------------------------------------------===//
72 void DIDescriptor::replaceAllUsesWith(LLVMContext &, DIDescriptor D) {
73 assert(DbgNode && "Trying to replace an unverified type!");
74 assert(DbgNode->isTemporary() && "Expected temporary node");
75 TempMDNode Temp(get());
77 // Since we use a TrackingVH for the node, its easy for clients to manufacture
78 // legitimate situations where they want to replaceAllUsesWith() on something
79 // which, due to uniquing, has merged with the source. We shield clients from
80 // this detail by allowing a value to be replaced with replaceAllUsesWith()
82 if (Temp.get() == D.get()) {
83 DbgNode = MDNode::replaceWithUniqued(std::move(Temp));
87 Temp->replaceAllUsesWith(D.get());
91 void DIDescriptor::replaceAllUsesWith(MDNode *D) {
92 assert(DbgNode && "Trying to replace an unverified type!");
93 assert(DbgNode != D && "This replacement should always happen");
94 assert(DbgNode->isTemporary() && "Expected temporary node");
95 TempMDNode Node(get());
96 Node->replaceAllUsesWith(D);
100 /// \brief Check if a value can be a reference to a type.
101 static bool isTypeRef(const Metadata *MD) {
104 if (auto *S = dyn_cast<MDString>(MD))
105 return !S->getString().empty();
106 return isa<MDType>(MD);
109 /// \brief Check if a value can be a ScopeRef.
110 static bool isScopeRef(const Metadata *MD) {
113 if (auto *S = dyn_cast<MDString>(MD))
114 return !S->getString().empty();
115 return isa<MDScope>(MD);
118 /// \brief Check if a value can be a DescriptorRef.
119 static bool isDescriptorRef(const Metadata *MD) {
122 if (auto *S = dyn_cast<MDString>(MD))
123 return !S->getString().empty();
124 return isa<MDNode>(MD);
128 DIScopeRef DIScope::getRef() const { return MDScopeRef::get(get()); }
130 bool DIVariable::isInlinedFnArgument(const Function *CurFn) {
131 assert(CurFn && "Invalid function");
132 DISubprogram SP = dyn_cast<MDSubprogram>(getContext());
135 // This variable is not inlined function argument if its scope
136 // does not describe current function.
137 return !SP.describes(CurFn);
140 Function *DISubprogram::getFunction() const {
142 if (auto *C = dyn_cast_or_null<ConstantAsMetadata>(N->getFunction()))
143 return dyn_cast<Function>(C->getValue());
147 bool DISubprogram::describes(const Function *F) {
148 assert(F && "Invalid function");
149 if (F == getFunction())
151 StringRef Name = getLinkageName();
154 if (F->getName() == Name)
159 GlobalVariable *DIGlobalVariable::getGlobal() const {
160 return dyn_cast_or_null<GlobalVariable>(getConstant());
163 DIScopeRef DIScope::getContext() const {
164 if (DIType T = dyn_cast<MDType>(*this))
165 return T.getContext();
167 if (DISubprogram SP = dyn_cast<MDSubprogram>(*this))
168 return DIScopeRef(SP.getContext());
170 if (DILexicalBlock LB = dyn_cast<MDLexicalBlockBase>(*this))
171 return DIScopeRef(LB.getContext());
173 if (DINameSpace NS = dyn_cast<MDNamespace>(*this))
174 return DIScopeRef(NS.getContext());
176 assert((isa<MDFile>(*this) || isa<MDCompileUnit>(*this)) &&
177 "Unhandled type of scope.");
178 return DIScopeRef(nullptr);
181 StringRef DIScope::getName() const {
182 if (DIType T = dyn_cast<MDType>(*this))
184 if (DISubprogram SP = dyn_cast<MDSubprogram>(*this))
186 if (DINameSpace NS = dyn_cast<MDNamespace>(*this))
188 assert((isa<MDLexicalBlockBase>(*this) || isa<MDFile>(*this) ||
189 isa<MDCompileUnit>(*this)) &&
190 "Unhandled type of scope.");
194 StringRef DIScope::getFilename() const {
196 if (auto *F = N->getFile())
197 return F->getFilename();
201 StringRef DIScope::getDirectory() const {
203 if (auto *F = N->getFile())
204 return F->getDirectory();
208 void DICompileUnit::replaceSubprograms(DIArray Subprograms) {
209 get()->replaceSubprograms(Subprograms);
212 void DICompileUnit::replaceGlobalVariables(DIArray GlobalVariables) {
213 get()->replaceGlobalVariables(GlobalVariables);
216 DILocation DILocation::copyWithNewScope(LLVMContext &Ctx,
217 DILexicalBlockFile NewScope) {
218 assert(NewScope && "Expected valid scope");
220 const auto *Old = cast<MDLocation>(DbgNode);
221 return DILocation(MDLocation::get(Ctx, Old->getLine(), Old->getColumn(),
222 NewScope, Old->getInlinedAt()));
225 unsigned DILocation::computeNewDiscriminator(LLVMContext &Ctx) {
226 std::pair<const char *, unsigned> Key(getFilename().data(), getLineNumber());
227 return ++Ctx.pImpl->DiscriminatorTable[Key];
230 DIVariable llvm::createInlinedVariable(MDNode *DV, MDNode *InlinedScope,
231 LLVMContext &VMContext) {
232 return cast<MDLocalVariable>(DV)
233 ->withInline(cast_or_null<MDLocation>(InlinedScope));
236 DIVariable llvm::cleanseInlinedVariable(MDNode *DV, LLVMContext &VMContext) {
237 return cast<MDLocalVariable>(DV)->withoutInline();
240 DISubprogram llvm::getDISubprogram(const MDNode *Scope) {
241 if (auto *LocalScope = dyn_cast_or_null<MDLocalScope>(Scope))
242 return LocalScope->getSubprogram();
246 DISubprogram llvm::getDISubprogram(const Function *F) {
247 // We look for the first instr that has a debug annotation leading back to F.
248 for (auto &BB : *F) {
249 auto Inst = std::find_if(BB.begin(), BB.end(), [](const Instruction &Inst) {
250 return Inst.getDebugLoc();
252 if (Inst == BB.end())
254 DebugLoc DLoc = Inst->getDebugLoc();
255 const MDNode *Scope = DLoc.getInlinedAtScope();
256 DISubprogram Subprogram = getDISubprogram(Scope);
257 return Subprogram.describes(F) ? Subprogram : DISubprogram();
260 return DISubprogram();
263 DICompositeType llvm::getDICompositeType(DIType T) {
264 if (auto *C = dyn_cast_or_null<MDCompositeTypeBase>(T))
267 if (auto *D = dyn_cast_or_null<MDDerivedTypeBase>(T)) {
268 // This function is currently used by dragonegg and dragonegg does
269 // not generate identifier for types, so using an empty map to resolve
270 // DerivedFrom should be fine.
271 DITypeIdentifierMap EmptyMap;
272 return getDICompositeType(
273 DIDerivedType(D).getTypeDerivedFrom().resolve(EmptyMap));
280 llvm::generateDITypeIdentifierMap(const NamedMDNode *CU_Nodes) {
281 DITypeIdentifierMap Map;
282 for (unsigned CUi = 0, CUe = CU_Nodes->getNumOperands(); CUi != CUe; ++CUi) {
283 DICompileUnit CU = cast<MDCompileUnit>(CU_Nodes->getOperand(CUi));
284 DIArray Retain = CU.getRetainedTypes();
285 for (unsigned Ti = 0, Te = Retain.size(); Ti != Te; ++Ti) {
286 if (!isa<MDCompositeType>(Retain[Ti]))
288 DICompositeType Ty = cast<MDCompositeType>(Retain[Ti]);
289 if (MDString *TypeId = Ty.getIdentifier()) {
290 // Definition has priority over declaration.
291 // Try to insert (TypeId, Ty) to Map.
292 std::pair<DITypeIdentifierMap::iterator, bool> P =
293 Map.insert(std::make_pair(TypeId, Ty));
294 // If TypeId already exists in Map and this is a definition, replace
295 // whatever we had (declaration or definition) with the definition.
296 if (!P.second && !Ty.isForwardDecl())
297 P.first->second = Ty;
304 //===----------------------------------------------------------------------===//
305 // DebugInfoFinder implementations.
306 //===----------------------------------------------------------------------===//
308 void DebugInfoFinder::reset() {
315 TypeIdentifierMap.clear();
316 TypeMapInitialized = false;
319 void DebugInfoFinder::InitializeTypeMap(const Module &M) {
320 if (!TypeMapInitialized)
321 if (NamedMDNode *CU_Nodes = M.getNamedMetadata("llvm.dbg.cu")) {
322 TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
323 TypeMapInitialized = true;
327 void DebugInfoFinder::processModule(const Module &M) {
328 InitializeTypeMap(M);
329 if (NamedMDNode *CU_Nodes = M.getNamedMetadata("llvm.dbg.cu")) {
330 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
331 DICompileUnit CU = cast<MDCompileUnit>(CU_Nodes->getOperand(i));
333 for (DIGlobalVariable DIG : CU->getGlobalVariables()) {
334 if (addGlobalVariable(DIG)) {
335 processScope(DIG.getContext());
336 processType(DIG.getType().resolve(TypeIdentifierMap));
339 for (auto *SP : CU->getSubprograms())
340 processSubprogram(SP);
341 for (auto *ET : CU->getEnumTypes())
343 for (auto *RT : CU->getRetainedTypes())
345 for (DIImportedEntity Import : CU->getImportedEntities()) {
346 DIDescriptor Entity = Import.getEntity().resolve(TypeIdentifierMap);
347 if (auto *T = dyn_cast<MDType>(Entity))
349 else if (auto *SP = dyn_cast<MDSubprogram>(Entity))
350 processSubprogram(SP);
351 else if (auto *NS = dyn_cast<MDNamespace>(Entity))
352 processScope(NS->getScope());
358 void DebugInfoFinder::processLocation(const Module &M, DILocation Loc) {
361 InitializeTypeMap(M);
362 processScope(Loc.getScope());
363 processLocation(M, Loc.getOrigLocation());
366 void DebugInfoFinder::processType(DIType DT) {
369 processScope(DT.getContext().resolve(TypeIdentifierMap));
370 if (DICompositeType DCT = dyn_cast<MDCompositeTypeBase>(DT)) {
371 processType(DCT.getTypeDerivedFrom().resolve(TypeIdentifierMap));
372 if (DISubroutineType ST = dyn_cast<MDSubroutineType>(DCT)) {
373 for (MDTypeRef Ref : ST->getTypeArray())
374 processType(Ref.resolve(TypeIdentifierMap));
377 for (Metadata *D : DCT->getElements()->operands()) {
378 if (DIType T = dyn_cast<MDType>(D))
380 else if (DISubprogram SP = dyn_cast<MDSubprogram>(D))
381 processSubprogram(SP);
383 } else if (DIDerivedType DDT = dyn_cast<MDDerivedTypeBase>(DT)) {
384 processType(DDT.getTypeDerivedFrom().resolve(TypeIdentifierMap));
388 void DebugInfoFinder::processScope(DIScope Scope) {
391 if (DIType Ty = dyn_cast<MDType>(Scope)) {
395 if (DICompileUnit CU = dyn_cast<MDCompileUnit>(Scope)) {
399 if (DISubprogram SP = dyn_cast<MDSubprogram>(Scope)) {
400 processSubprogram(SP);
403 if (!addScope(Scope))
405 if (DILexicalBlock LB = dyn_cast<MDLexicalBlockBase>(Scope)) {
406 processScope(LB.getContext());
407 } else if (DINameSpace NS = dyn_cast<MDNamespace>(Scope)) {
408 processScope(NS.getContext());
412 void DebugInfoFinder::processSubprogram(DISubprogram SP) {
413 if (!addSubprogram(SP))
415 processScope(SP.getContext().resolve(TypeIdentifierMap));
416 processType(SP.getType());
417 for (auto *Element : SP.getTemplateParams()) {
418 if (DITemplateTypeParameter TType =
419 dyn_cast<MDTemplateTypeParameter>(Element)) {
420 processType(TType.getType().resolve(TypeIdentifierMap));
421 } else if (DITemplateValueParameter TVal =
422 dyn_cast<MDTemplateValueParameter>(Element)) {
423 processType(TVal.getType().resolve(TypeIdentifierMap));
428 void DebugInfoFinder::processDeclare(const Module &M,
429 const DbgDeclareInst *DDI) {
430 MDNode *N = dyn_cast<MDNode>(DDI->getVariable());
433 InitializeTypeMap(M);
435 DIVariable DV = dyn_cast<MDLocalVariable>(N);
439 if (!NodesSeen.insert(DV).second)
441 processScope(DV.getContext());
442 processType(DV.getType().resolve(TypeIdentifierMap));
445 void DebugInfoFinder::processValue(const Module &M, const DbgValueInst *DVI) {
446 MDNode *N = dyn_cast<MDNode>(DVI->getVariable());
449 InitializeTypeMap(M);
451 DIVariable DV = dyn_cast<MDLocalVariable>(N);
455 if (!NodesSeen.insert(DV).second)
457 processScope(DV.getContext());
458 processType(DV.getType().resolve(TypeIdentifierMap));
461 bool DebugInfoFinder::addType(DIType DT) {
465 if (!NodesSeen.insert(DT).second)
472 bool DebugInfoFinder::addCompileUnit(DICompileUnit CU) {
475 if (!NodesSeen.insert(CU).second)
482 bool DebugInfoFinder::addGlobalVariable(DIGlobalVariable DIG) {
486 if (!NodesSeen.insert(DIG).second)
493 bool DebugInfoFinder::addSubprogram(DISubprogram SP) {
497 if (!NodesSeen.insert(SP).second)
504 bool DebugInfoFinder::addScope(DIScope Scope) {
507 // FIXME: Ocaml binding generates a scope with no content, we treat it
509 if (Scope->getNumOperands() == 0)
511 if (!NodesSeen.insert(Scope).second)
513 Scopes.push_back(Scope);
517 //===----------------------------------------------------------------------===//
518 // DIDescriptor: dump routines for all descriptors.
519 //===----------------------------------------------------------------------===//
521 void DIDescriptor::dump() const {
526 void DIDescriptor::print(raw_ostream &OS) const {
532 static void printDebugLoc(DebugLoc DL, raw_ostream &CommentOS,
533 const LLVMContext &Ctx) {
537 DIScope Scope = cast<MDScope>(DL.getScope());
538 // Omit the directory, because it's likely to be long and uninteresting.
539 CommentOS << Scope.getFilename();
540 CommentOS << ':' << DL.getLine();
541 if (DL.getCol() != 0)
542 CommentOS << ':' << DL.getCol();
544 DebugLoc InlinedAtDL = DL.getInlinedAt();
549 printDebugLoc(InlinedAtDL, CommentOS, Ctx);
553 void DIVariable::printExtendedName(raw_ostream &OS) const {
554 const LLVMContext &Ctx = DbgNode->getContext();
555 StringRef Res = getName();
557 OS << Res << "," << getLineNumber();
558 if (auto *InlinedAt = get()->getInlinedAt()) {
559 if (DebugLoc InlinedAtDL = InlinedAt) {
561 printDebugLoc(InlinedAtDL, OS, Ctx);
567 template <> DIRef<DIDescriptor>::DIRef(const Metadata *V) : Val(V) {
568 assert(isDescriptorRef(V) &&
569 "DIDescriptorRef should be a MDString or MDNode");
571 template <> DIRef<DIScope>::DIRef(const Metadata *V) : Val(V) {
572 assert(isScopeRef(V) && "DIScopeRef should be a MDString or MDNode");
574 template <> DIRef<DIType>::DIRef(const Metadata *V) : Val(V) {
575 assert(isTypeRef(V) && "DITypeRef should be a MDString or MDNode");
579 DIDescriptorRef DIDescriptor::getFieldAs<DIDescriptorRef>(unsigned Elt) const {
580 return DIDescriptorRef(cast_or_null<Metadata>(getField(DbgNode, Elt)));
583 DIScopeRef DIDescriptor::getFieldAs<DIScopeRef>(unsigned Elt) const {
584 return DIScopeRef(cast_or_null<Metadata>(getField(DbgNode, Elt)));
586 template <> DITypeRef DIDescriptor::getFieldAs<DITypeRef>(unsigned Elt) const {
587 return DITypeRef(cast_or_null<Metadata>(getField(DbgNode, Elt)));
592 DIRef<DIDescriptor>::resolve(const DITypeIdentifierMap &Map) const {
593 return DIDescriptor(DebugNodeRef(Val).resolve(Map));
596 DIScope DIRef<DIScope>::resolve(const DITypeIdentifierMap &Map) const {
597 return MDScopeRef(Val).resolve(Map);
600 DIType DIRef<DIType>::resolve(const DITypeIdentifierMap &Map) const {
601 return MDTypeRef(Val).resolve(Map);
604 bool llvm::stripDebugInfo(Function &F) {
605 bool Changed = false;
606 for (BasicBlock &BB : F) {
607 for (Instruction &I : BB) {
608 if (I.getDebugLoc()) {
610 I.setDebugLoc(DebugLoc());
617 bool llvm::StripDebugInfo(Module &M) {
618 bool Changed = false;
620 // Remove all of the calls to the debugger intrinsics, and remove them from
622 if (Function *Declare = M.getFunction("llvm.dbg.declare")) {
623 while (!Declare->use_empty()) {
624 CallInst *CI = cast<CallInst>(Declare->user_back());
625 CI->eraseFromParent();
627 Declare->eraseFromParent();
631 if (Function *DbgVal = M.getFunction("llvm.dbg.value")) {
632 while (!DbgVal->use_empty()) {
633 CallInst *CI = cast<CallInst>(DbgVal->user_back());
634 CI->eraseFromParent();
636 DbgVal->eraseFromParent();
640 for (Module::named_metadata_iterator NMI = M.named_metadata_begin(),
641 NME = M.named_metadata_end(); NMI != NME;) {
642 NamedMDNode *NMD = NMI;
644 if (NMD->getName().startswith("llvm.dbg.")) {
645 NMD->eraseFromParent();
650 for (Function &F : M)
651 Changed |= stripDebugInfo(F);
653 if (GVMaterializer *Materializer = M.getMaterializer())
654 Materializer->setStripDebugInfo();
659 unsigned llvm::getDebugMetadataVersionFromModule(const Module &M) {
660 if (auto *Val = mdconst::dyn_extract_or_null<ConstantInt>(
661 M.getModuleFlag("Debug Info Version")))
662 return Val->getZExtValue();
666 llvm::DenseMap<const llvm::Function *, llvm::DISubprogram>
667 llvm::makeSubprogramMap(const Module &M) {
668 DenseMap<const Function *, DISubprogram> R;
670 NamedMDNode *CU_Nodes = M.getNamedMetadata("llvm.dbg.cu");
674 for (MDNode *N : CU_Nodes->operands()) {
675 DICompileUnit CUNode = cast<MDCompileUnit>(N);
676 for (DISubprogram SP : CUNode->getSubprograms()) {
677 if (Function *F = SP.getFunction())
678 R.insert(std::make_pair(F, SP));