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 bool DIExpression::isBitPiece() const {
69 unsigned N = getNumElements();
70 return N >=3 && getElement(N-3) == dwarf::DW_OP_bit_piece;
73 uint64_t DIExpression::getBitPieceOffset() const {
74 assert(isBitPiece() && "not a piece");
75 return getElement(getNumElements()-2);
78 uint64_t DIExpression::getBitPieceSize() const {
79 assert(isBitPiece() && "not a piece");
80 return getElement(getNumElements()-1);
83 DIExpression::iterator DIExpression::Operand::getNext() const {
88 //===----------------------------------------------------------------------===//
89 // Simple Descriptor Constructors and other Methods
90 //===----------------------------------------------------------------------===//
92 void DIDescriptor::replaceAllUsesWith(LLVMContext &, DIDescriptor D) {
93 assert(DbgNode && "Trying to replace an unverified type!");
94 assert(DbgNode->isTemporary() && "Expected temporary node");
95 TempMDNode Temp(get());
97 // Since we use a TrackingVH for the node, its easy for clients to manufacture
98 // legitimate situations where they want to replaceAllUsesWith() on something
99 // which, due to uniquing, has merged with the source. We shield clients from
100 // this detail by allowing a value to be replaced with replaceAllUsesWith()
102 if (Temp.get() == D.get()) {
103 DbgNode = MDNode::replaceWithUniqued(std::move(Temp));
107 Temp->replaceAllUsesWith(D.get());
111 void DIDescriptor::replaceAllUsesWith(MDNode *D) {
112 assert(DbgNode && "Trying to replace an unverified type!");
113 assert(DbgNode != D && "This replacement should always happen");
114 assert(DbgNode->isTemporary() && "Expected temporary node");
115 TempMDNode Node(get());
116 Node->replaceAllUsesWith(D);
120 /// \brief Check if a value can be a reference to a type.
121 static bool isTypeRef(const Metadata *MD) {
124 if (auto *S = dyn_cast<MDString>(MD))
125 return !S->getString().empty();
126 return isa<MDType>(MD);
129 /// \brief Check if a value can be a ScopeRef.
130 static bool isScopeRef(const Metadata *MD) {
133 if (auto *S = dyn_cast<MDString>(MD))
134 return !S->getString().empty();
135 return isa<MDScope>(MD);
138 /// \brief Check if a value can be a DescriptorRef.
139 static bool isDescriptorRef(const Metadata *MD) {
142 if (auto *S = dyn_cast<MDString>(MD))
143 return !S->getString().empty();
144 return isa<MDNode>(MD);
148 void DICompositeType::setArraysHelper(MDNode *Elements, MDNode *TParams) {
149 TypedTrackingMDRef<MDCompositeTypeBase> N(get());
151 N->replaceElements(cast<MDTuple>(Elements));
153 N->replaceTemplateParams(cast<MDTuple>(TParams));
157 DIScopeRef DIScope::getRef() const { return MDScopeRef::get(get()); }
159 void DICompositeType::setContainingType(DICompositeType ContainingType) {
160 TypedTrackingMDRef<MDCompositeTypeBase> N(get());
161 N->replaceVTableHolder(MDTypeRef::get(ContainingType));
165 bool DIVariable::isInlinedFnArgument(const Function *CurFn) {
166 assert(CurFn && "Invalid function");
167 DISubprogram SP = dyn_cast<MDSubprogram>(getContext());
170 // This variable is not inlined function argument if its scope
171 // does not describe current function.
172 return !SP.describes(CurFn);
175 Function *DISubprogram::getFunction() const {
177 if (auto *C = dyn_cast_or_null<ConstantAsMetadata>(N->getFunction()))
178 return dyn_cast<Function>(C->getValue());
182 bool DISubprogram::describes(const Function *F) {
183 assert(F && "Invalid function");
184 if (F == getFunction())
186 StringRef Name = getLinkageName();
189 if (F->getName() == Name)
194 GlobalVariable *DIGlobalVariable::getGlobal() const {
195 return dyn_cast_or_null<GlobalVariable>(getConstant());
198 DIScopeRef DIScope::getContext() const {
199 if (DIType T = dyn_cast<MDType>(*this))
200 return T.getContext();
202 if (DISubprogram SP = dyn_cast<MDSubprogram>(*this))
203 return DIScopeRef(SP.getContext());
205 if (DILexicalBlock LB = dyn_cast<MDLexicalBlockBase>(*this))
206 return DIScopeRef(LB.getContext());
208 if (DINameSpace NS = dyn_cast<MDNamespace>(*this))
209 return DIScopeRef(NS.getContext());
211 assert((isa<MDFile>(*this) || isa<MDCompileUnit>(*this)) &&
212 "Unhandled type of scope.");
213 return DIScopeRef(nullptr);
216 StringRef DIScope::getName() const {
217 if (DIType T = dyn_cast<MDType>(*this))
219 if (DISubprogram SP = dyn_cast<MDSubprogram>(*this))
221 if (DINameSpace NS = dyn_cast<MDNamespace>(*this))
223 assert((isa<MDLexicalBlockBase>(*this) || isa<MDFile>(*this) ||
224 isa<MDCompileUnit>(*this)) &&
225 "Unhandled type of scope.");
229 StringRef DIScope::getFilename() const {
231 if (auto *F = N->getFile())
232 return F->getFilename();
236 StringRef DIScope::getDirectory() const {
238 if (auto *F = N->getFile())
239 return F->getDirectory();
243 void DICompileUnit::replaceSubprograms(DIArray Subprograms) {
244 get()->replaceSubprograms(cast_or_null<MDTuple>(Subprograms.get()));
247 void DICompileUnit::replaceGlobalVariables(DIArray GlobalVariables) {
248 get()->replaceGlobalVariables(cast_or_null<MDTuple>(GlobalVariables.get()));
251 DILocation DILocation::copyWithNewScope(LLVMContext &Ctx,
252 DILexicalBlockFile NewScope) {
253 assert(NewScope && "Expected valid scope");
255 const auto *Old = cast<MDLocation>(DbgNode);
256 return DILocation(MDLocation::get(Ctx, Old->getLine(), Old->getColumn(),
257 NewScope, Old->getInlinedAt()));
260 unsigned DILocation::computeNewDiscriminator(LLVMContext &Ctx) {
261 std::pair<const char *, unsigned> Key(getFilename().data(), getLineNumber());
262 return ++Ctx.pImpl->DiscriminatorTable[Key];
265 DIVariable llvm::createInlinedVariable(MDNode *DV, MDNode *InlinedScope,
266 LLVMContext &VMContext) {
267 return cast<MDLocalVariable>(DV)
268 ->withInline(cast_or_null<MDLocation>(InlinedScope));
271 DIVariable llvm::cleanseInlinedVariable(MDNode *DV, LLVMContext &VMContext) {
272 return cast<MDLocalVariable>(DV)->withoutInline();
275 DISubprogram llvm::getDISubprogram(const MDNode *Scope) {
276 if (auto *LocalScope = dyn_cast_or_null<MDLocalScope>(Scope))
277 return LocalScope->getSubprogram();
281 DISubprogram llvm::getDISubprogram(const Function *F) {
282 // We look for the first instr that has a debug annotation leading back to F.
283 for (auto &BB : *F) {
284 auto Inst = std::find_if(BB.begin(), BB.end(), [](const Instruction &Inst) {
285 return Inst.getDebugLoc();
287 if (Inst == BB.end())
289 DebugLoc DLoc = Inst->getDebugLoc();
290 const MDNode *Scope = DLoc.getInlinedAtScope();
291 DISubprogram Subprogram = getDISubprogram(Scope);
292 return Subprogram.describes(F) ? Subprogram : DISubprogram();
295 return DISubprogram();
298 DICompositeType llvm::getDICompositeType(DIType T) {
299 if (auto *C = dyn_cast_or_null<MDCompositeTypeBase>(T))
302 if (auto *D = dyn_cast_or_null<MDDerivedTypeBase>(T)) {
303 // This function is currently used by dragonegg and dragonegg does
304 // not generate identifier for types, so using an empty map to resolve
305 // DerivedFrom should be fine.
306 DITypeIdentifierMap EmptyMap;
307 return getDICompositeType(
308 DIDerivedType(D).getTypeDerivedFrom().resolve(EmptyMap));
315 llvm::generateDITypeIdentifierMap(const NamedMDNode *CU_Nodes) {
316 DITypeIdentifierMap Map;
317 for (unsigned CUi = 0, CUe = CU_Nodes->getNumOperands(); CUi != CUe; ++CUi) {
318 DICompileUnit CU = cast<MDCompileUnit>(CU_Nodes->getOperand(CUi));
319 DIArray Retain = CU.getRetainedTypes();
320 for (unsigned Ti = 0, Te = Retain.getNumElements(); Ti != Te; ++Ti) {
321 if (!isa<MDCompositeType>(Retain.getElement(Ti)))
323 DICompositeType Ty = cast<MDCompositeType>(Retain.getElement(Ti));
324 if (MDString *TypeId = Ty.getIdentifier()) {
325 // Definition has priority over declaration.
326 // Try to insert (TypeId, Ty) to Map.
327 std::pair<DITypeIdentifierMap::iterator, bool> P =
328 Map.insert(std::make_pair(TypeId, Ty));
329 // If TypeId already exists in Map and this is a definition, replace
330 // whatever we had (declaration or definition) with the definition.
331 if (!P.second && !Ty.isForwardDecl())
332 P.first->second = Ty;
339 //===----------------------------------------------------------------------===//
340 // DebugInfoFinder implementations.
341 //===----------------------------------------------------------------------===//
343 void DebugInfoFinder::reset() {
350 TypeIdentifierMap.clear();
351 TypeMapInitialized = false;
354 void DebugInfoFinder::InitializeTypeMap(const Module &M) {
355 if (!TypeMapInitialized)
356 if (NamedMDNode *CU_Nodes = M.getNamedMetadata("llvm.dbg.cu")) {
357 TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
358 TypeMapInitialized = true;
362 void DebugInfoFinder::processModule(const Module &M) {
363 InitializeTypeMap(M);
364 if (NamedMDNode *CU_Nodes = M.getNamedMetadata("llvm.dbg.cu")) {
365 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
366 DICompileUnit CU = cast<MDCompileUnit>(CU_Nodes->getOperand(i));
368 DIArray GVs = CU.getGlobalVariables();
369 for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i) {
370 DIGlobalVariable DIG = cast<MDGlobalVariable>(GVs.getElement(i));
371 if (addGlobalVariable(DIG)) {
372 processScope(DIG.getContext());
373 processType(DIG.getType().resolve(TypeIdentifierMap));
376 DIArray SPs = CU.getSubprograms();
377 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
378 processSubprogram(cast<MDSubprogram>(SPs.getElement(i)));
379 DIArray EnumTypes = CU.getEnumTypes();
380 for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i)
381 processType(cast<MDType>(EnumTypes.getElement(i)));
382 DIArray RetainedTypes = CU.getRetainedTypes();
383 for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i)
384 processType(cast<MDType>(RetainedTypes.getElement(i)));
385 DIArray Imports = CU.getImportedEntities();
386 for (unsigned i = 0, e = Imports.getNumElements(); i != e; ++i) {
387 DIImportedEntity Import = cast<MDImportedEntity>(Imports.getElement(i));
388 DIDescriptor Entity = Import.getEntity().resolve(TypeIdentifierMap);
389 if (auto *T = dyn_cast<MDType>(Entity))
391 else if (auto *SP = dyn_cast<MDSubprogram>(Entity))
392 processSubprogram(SP);
393 else if (auto *NS = dyn_cast<MDNamespace>(Entity))
394 processScope(NS->getScope());
400 void DebugInfoFinder::processLocation(const Module &M, DILocation Loc) {
403 InitializeTypeMap(M);
404 processScope(Loc.getScope());
405 processLocation(M, Loc.getOrigLocation());
408 void DebugInfoFinder::processType(DIType DT) {
411 processScope(DT.getContext().resolve(TypeIdentifierMap));
412 if (DICompositeType DCT = dyn_cast<MDCompositeTypeBase>(DT)) {
413 processType(DCT.getTypeDerivedFrom().resolve(TypeIdentifierMap));
414 if (DISubroutineType ST = dyn_cast<MDSubroutineType>(DCT)) {
415 DITypeArray DTA = ST.getTypeArray();
416 for (unsigned i = 0, e = DTA.getNumElements(); i != e; ++i)
417 processType(DTA.getElement(i).resolve(TypeIdentifierMap));
420 DIArray DA = DCT.getElements();
421 for (unsigned i = 0, e = DA.getNumElements(); i != e; ++i) {
422 DIDescriptor D = DA.getElement(i);
423 if (DIType T = dyn_cast<MDType>(D))
425 else if (DISubprogram SP = dyn_cast<MDSubprogram>(D))
426 processSubprogram(SP);
428 } else if (DIDerivedType DDT = dyn_cast<MDDerivedTypeBase>(DT)) {
429 processType(DDT.getTypeDerivedFrom().resolve(TypeIdentifierMap));
433 void DebugInfoFinder::processScope(DIScope Scope) {
436 if (DIType Ty = dyn_cast<MDType>(Scope)) {
440 if (DICompileUnit CU = dyn_cast<MDCompileUnit>(Scope)) {
444 if (DISubprogram SP = dyn_cast<MDSubprogram>(Scope)) {
445 processSubprogram(SP);
448 if (!addScope(Scope))
450 if (DILexicalBlock LB = dyn_cast<MDLexicalBlockBase>(Scope)) {
451 processScope(LB.getContext());
452 } else if (DINameSpace NS = dyn_cast<MDNamespace>(Scope)) {
453 processScope(NS.getContext());
457 void DebugInfoFinder::processSubprogram(DISubprogram SP) {
458 if (!addSubprogram(SP))
460 processScope(SP.getContext().resolve(TypeIdentifierMap));
461 processType(SP.getType());
462 DIArray TParams = SP.getTemplateParams();
463 for (unsigned I = 0, E = TParams.getNumElements(); I != E; ++I) {
464 DIDescriptor Element = TParams.getElement(I);
465 if (DITemplateTypeParameter TType =
466 dyn_cast<MDTemplateTypeParameter>(Element)) {
467 processType(TType.getType().resolve(TypeIdentifierMap));
468 } else if (DITemplateValueParameter TVal =
469 dyn_cast<MDTemplateValueParameter>(Element)) {
470 processType(TVal.getType().resolve(TypeIdentifierMap));
475 void DebugInfoFinder::processDeclare(const Module &M,
476 const DbgDeclareInst *DDI) {
477 MDNode *N = dyn_cast<MDNode>(DDI->getVariable());
480 InitializeTypeMap(M);
482 DIVariable DV = dyn_cast<MDLocalVariable>(N);
486 if (!NodesSeen.insert(DV).second)
488 processScope(DV.getContext());
489 processType(DV.getType().resolve(TypeIdentifierMap));
492 void DebugInfoFinder::processValue(const Module &M, const DbgValueInst *DVI) {
493 MDNode *N = dyn_cast<MDNode>(DVI->getVariable());
496 InitializeTypeMap(M);
498 DIVariable DV = dyn_cast<MDLocalVariable>(N);
502 if (!NodesSeen.insert(DV).second)
504 processScope(DV.getContext());
505 processType(DV.getType().resolve(TypeIdentifierMap));
508 bool DebugInfoFinder::addType(DIType DT) {
512 if (!NodesSeen.insert(DT).second)
519 bool DebugInfoFinder::addCompileUnit(DICompileUnit CU) {
522 if (!NodesSeen.insert(CU).second)
529 bool DebugInfoFinder::addGlobalVariable(DIGlobalVariable DIG) {
533 if (!NodesSeen.insert(DIG).second)
540 bool DebugInfoFinder::addSubprogram(DISubprogram SP) {
544 if (!NodesSeen.insert(SP).second)
551 bool DebugInfoFinder::addScope(DIScope Scope) {
554 // FIXME: Ocaml binding generates a scope with no content, we treat it
556 if (Scope->getNumOperands() == 0)
558 if (!NodesSeen.insert(Scope).second)
560 Scopes.push_back(Scope);
564 //===----------------------------------------------------------------------===//
565 // DIDescriptor: dump routines for all descriptors.
566 //===----------------------------------------------------------------------===//
568 void DIDescriptor::dump() const {
573 void DIDescriptor::print(raw_ostream &OS) const {
579 static void printDebugLoc(DebugLoc DL, raw_ostream &CommentOS,
580 const LLVMContext &Ctx) {
584 DIScope Scope = cast<MDScope>(DL.getScope());
585 // Omit the directory, because it's likely to be long and uninteresting.
586 CommentOS << Scope.getFilename();
587 CommentOS << ':' << DL.getLine();
588 if (DL.getCol() != 0)
589 CommentOS << ':' << DL.getCol();
591 DebugLoc InlinedAtDL = DL.getInlinedAt();
596 printDebugLoc(InlinedAtDL, CommentOS, Ctx);
600 void DIVariable::printExtendedName(raw_ostream &OS) const {
601 const LLVMContext &Ctx = DbgNode->getContext();
602 StringRef Res = getName();
604 OS << Res << "," << getLineNumber();
605 if (auto *InlinedAt = get()->getInlinedAt()) {
606 if (DebugLoc InlinedAtDL = InlinedAt) {
608 printDebugLoc(InlinedAtDL, OS, Ctx);
614 template <> DIRef<DIDescriptor>::DIRef(const Metadata *V) : Val(V) {
615 assert(isDescriptorRef(V) &&
616 "DIDescriptorRef should be a MDString or MDNode");
618 template <> DIRef<DIScope>::DIRef(const Metadata *V) : Val(V) {
619 assert(isScopeRef(V) && "DIScopeRef should be a MDString or MDNode");
621 template <> DIRef<DIType>::DIRef(const Metadata *V) : Val(V) {
622 assert(isTypeRef(V) && "DITypeRef should be a MDString or MDNode");
626 DIDescriptorRef DIDescriptor::getFieldAs<DIDescriptorRef>(unsigned Elt) const {
627 return DIDescriptorRef(cast_or_null<Metadata>(getField(DbgNode, Elt)));
630 DIScopeRef DIDescriptor::getFieldAs<DIScopeRef>(unsigned Elt) const {
631 return DIScopeRef(cast_or_null<Metadata>(getField(DbgNode, Elt)));
633 template <> DITypeRef DIDescriptor::getFieldAs<DITypeRef>(unsigned Elt) const {
634 return DITypeRef(cast_or_null<Metadata>(getField(DbgNode, Elt)));
639 DIRef<DIDescriptor>::resolve(const DITypeIdentifierMap &Map) const {
640 return DIDescriptor(DebugNodeRef(Val).resolve(Map));
643 DIScope DIRef<DIScope>::resolve(const DITypeIdentifierMap &Map) const {
644 return MDScopeRef(Val).resolve(Map);
647 DIType DIRef<DIType>::resolve(const DITypeIdentifierMap &Map) const {
648 return MDTypeRef(Val).resolve(Map);
651 bool llvm::stripDebugInfo(Function &F) {
652 bool Changed = false;
653 for (BasicBlock &BB : F) {
654 for (Instruction &I : BB) {
655 if (I.getDebugLoc()) {
657 I.setDebugLoc(DebugLoc());
664 bool llvm::StripDebugInfo(Module &M) {
665 bool Changed = false;
667 // Remove all of the calls to the debugger intrinsics, and remove them from
669 if (Function *Declare = M.getFunction("llvm.dbg.declare")) {
670 while (!Declare->use_empty()) {
671 CallInst *CI = cast<CallInst>(Declare->user_back());
672 CI->eraseFromParent();
674 Declare->eraseFromParent();
678 if (Function *DbgVal = M.getFunction("llvm.dbg.value")) {
679 while (!DbgVal->use_empty()) {
680 CallInst *CI = cast<CallInst>(DbgVal->user_back());
681 CI->eraseFromParent();
683 DbgVal->eraseFromParent();
687 for (Module::named_metadata_iterator NMI = M.named_metadata_begin(),
688 NME = M.named_metadata_end(); NMI != NME;) {
689 NamedMDNode *NMD = NMI;
691 if (NMD->getName().startswith("llvm.dbg.")) {
692 NMD->eraseFromParent();
697 for (Function &F : M)
698 Changed |= stripDebugInfo(F);
700 if (GVMaterializer *Materializer = M.getMaterializer())
701 Materializer->setStripDebugInfo();
706 unsigned llvm::getDebugMetadataVersionFromModule(const Module &M) {
707 if (auto *Val = mdconst::dyn_extract_or_null<ConstantInt>(
708 M.getModuleFlag("Debug Info Version")))
709 return Val->getZExtValue();
713 llvm::DenseMap<const llvm::Function *, llvm::DISubprogram>
714 llvm::makeSubprogramMap(const Module &M) {
715 DenseMap<const Function *, DISubprogram> R;
717 NamedMDNode *CU_Nodes = M.getNamedMetadata("llvm.dbg.cu");
721 for (MDNode *N : CU_Nodes->operands()) {
722 DICompileUnit CUNode = cast<MDCompileUnit>(N);
723 DIArray SPs = CUNode.getSubprograms();
724 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i) {
725 DISubprogram SP = cast<MDSubprogram>(SPs.getElement(i));
726 if (Function *F = SP.getFunction())
727 R.insert(std::make_pair(F, SP));