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/ADT/StringSwitch.h"
21 #include "llvm/Analysis/ValueTracking.h"
22 #include "llvm/IR/Constants.h"
23 #include "llvm/IR/DIBuilder.h"
24 #include "llvm/IR/DerivedTypes.h"
25 #include "llvm/IR/Instructions.h"
26 #include "llvm/IR/IntrinsicInst.h"
27 #include "llvm/IR/Intrinsics.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 unsigned DIDescriptor::getFlag(StringRef Flag) {
41 return StringSwitch<unsigned>(Flag)
42 #define HANDLE_DI_FLAG(ID, NAME) .Case("DIFlag" #NAME, Flag##NAME)
43 #include "llvm/IR/DebugInfoFlags.def"
47 const char *DIDescriptor::getFlagString(unsigned Flag) {
51 #define HANDLE_DI_FLAG(ID, NAME) \
53 return "DIFlag" #NAME;
54 #include "llvm/IR/DebugInfoFlags.def"
58 unsigned DIDescriptor::splitFlags(unsigned Flags,
59 SmallVectorImpl<unsigned> &SplitFlags) {
60 // Accessibility flags need to be specially handled, since they're packed
62 if (unsigned A = Flags & FlagAccessibility) {
64 SplitFlags.push_back(FlagPrivate);
65 else if (A == FlagProtected)
66 SplitFlags.push_back(FlagProtected);
68 SplitFlags.push_back(FlagPublic);
72 #define HANDLE_DI_FLAG(ID, NAME) \
73 if (unsigned Bit = Flags & ID) { \
74 SplitFlags.push_back(Bit); \
77 #include "llvm/IR/DebugInfoFlags.def"
82 bool DIDescriptor::Verify() const {
84 (DIDerivedType(DbgNode).Verify() ||
85 DICompositeType(DbgNode).Verify() || DIBasicType(DbgNode).Verify() ||
86 DIVariable(DbgNode).Verify() || DISubprogram(DbgNode).Verify() ||
87 DIGlobalVariable(DbgNode).Verify() || DIFile(DbgNode).Verify() ||
88 DICompileUnit(DbgNode).Verify() || DINameSpace(DbgNode).Verify() ||
89 DILexicalBlock(DbgNode).Verify() ||
90 DILexicalBlockFile(DbgNode).Verify() ||
91 DISubrange(DbgNode).Verify() || DIEnumerator(DbgNode).Verify() ||
92 DIObjCProperty(DbgNode).Verify() ||
93 DITemplateTypeParameter(DbgNode).Verify() ||
94 DITemplateValueParameter(DbgNode).Verify() ||
95 DIImportedEntity(DbgNode).Verify() || DIExpression(DbgNode).Verify());
98 static Metadata *getField(const MDNode *DbgNode, unsigned Elt) {
99 if (!DbgNode || Elt >= DbgNode->getNumOperands())
101 return DbgNode->getOperand(Elt);
104 static MDNode *getNodeField(const MDNode *DbgNode, unsigned Elt) {
105 return dyn_cast_or_null<MDNode>(getField(DbgNode, Elt));
108 static StringRef getStringField(const MDNode *DbgNode, unsigned Elt) {
109 if (MDString *MDS = dyn_cast_or_null<MDString>(getField(DbgNode, Elt)))
110 return MDS->getString();
114 StringRef DIDescriptor::getStringField(unsigned Elt) const {
115 return ::getStringField(DbgNode, Elt);
118 uint64_t DIDescriptor::getUInt64Field(unsigned Elt) const {
119 if (auto *C = getConstantField(Elt))
120 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
121 return CI->getZExtValue();
126 int64_t DIDescriptor::getInt64Field(unsigned Elt) const {
127 if (auto *C = getConstantField(Elt))
128 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
129 return CI->getZExtValue();
134 DIDescriptor DIDescriptor::getDescriptorField(unsigned Elt) const {
135 MDNode *Field = getNodeField(DbgNode, Elt);
136 return DIDescriptor(Field);
139 GlobalVariable *DIDescriptor::getGlobalVariableField(unsigned Elt) const {
140 return dyn_cast_or_null<GlobalVariable>(getConstantField(Elt));
143 Constant *DIDescriptor::getConstantField(unsigned Elt) const {
147 if (Elt < DbgNode->getNumOperands())
149 dyn_cast_or_null<ConstantAsMetadata>(DbgNode->getOperand(Elt)))
150 return C->getValue();
154 Function *DIDescriptor::getFunctionField(unsigned Elt) const {
155 return dyn_cast_or_null<Function>(getConstantField(Elt));
158 /// \brief Return the size reported by the variable's type.
159 unsigned DIVariable::getSizeInBits(const DITypeIdentifierMap &Map) {
160 DIType Ty = getType().resolve(Map);
161 // Follow derived types until we reach a type that
162 // reports back a size.
163 while (Ty.isDerivedType() && !Ty.getSizeInBits()) {
164 DIDerivedType DT(&*Ty);
165 Ty = DT.getTypeDerivedFrom().resolve(Map);
167 assert(Ty.getSizeInBits() && "type with size 0");
168 return Ty.getSizeInBits();
171 bool DIExpression::isBitPiece() const {
172 unsigned N = getNumElements();
173 return N >=3 && getElement(N-3) == dwarf::DW_OP_bit_piece;
176 uint64_t DIExpression::getBitPieceOffset() const {
177 assert(isBitPiece() && "not a piece");
178 return getElement(getNumElements()-2);
181 uint64_t DIExpression::getBitPieceSize() const {
182 assert(isBitPiece() && "not a piece");
183 return getElement(getNumElements()-1);
186 DIExpression::iterator DIExpression::Operand::getNext() const {
191 //===----------------------------------------------------------------------===//
192 // Simple Descriptor Constructors and other Methods
193 //===----------------------------------------------------------------------===//
195 void DIDescriptor::replaceAllUsesWith(LLVMContext &, DIDescriptor D) {
196 assert(DbgNode && "Trying to replace an unverified type!");
197 assert(DbgNode->isTemporary() && "Expected temporary node");
198 TempMDNode Temp(get());
200 // Since we use a TrackingVH for the node, its easy for clients to manufacture
201 // legitimate situations where they want to replaceAllUsesWith() on something
202 // which, due to uniquing, has merged with the source. We shield clients from
203 // this detail by allowing a value to be replaced with replaceAllUsesWith()
205 if (Temp.get() == D.get()) {
206 DbgNode = MDNode::replaceWithUniqued(std::move(Temp));
210 Temp->replaceAllUsesWith(D.get());
214 void DIDescriptor::replaceAllUsesWith(MDNode *D) {
215 assert(DbgNode && "Trying to replace an unverified type!");
216 assert(DbgNode != D && "This replacement should always happen");
217 assert(DbgNode->isTemporary() && "Expected temporary node");
218 TempMDNode Node(get());
219 Node->replaceAllUsesWith(D);
222 bool DICompileUnit::Verify() const {
223 if (!isCompileUnit())
226 // Don't bother verifying the compilation directory or producer string
227 // as those could be empty.
228 return !getFilename().empty();
231 bool DIObjCProperty::Verify() const { return isObjCProperty(); }
233 /// \brief Check if a value can be a reference to a type.
234 static bool isTypeRef(const Metadata *MD) {
237 if (auto *S = dyn_cast<MDString>(MD))
238 return !S->getString().empty();
239 return isa<MDType>(MD);
242 /// \brief Check if a value can be a ScopeRef.
243 static bool isScopeRef(const Metadata *MD) {
246 if (auto *S = dyn_cast<MDString>(MD))
247 return !S->getString().empty();
248 return isa<MDScope>(MD);
252 /// \brief Check if a value can be a DescriptorRef.
253 static bool isDescriptorRef(const Metadata *MD) {
256 if (auto *S = dyn_cast<MDString>(MD))
257 return !S->getString().empty();
258 return isa<MDNode>(MD);
262 bool DIType::Verify() const {
266 if (!isScopeRef(N->getScope()))
269 // FIXME: Sink this into the various subclass verifies.
270 uint16_t Tag = getTag();
271 if (!isBasicType() && Tag != dwarf::DW_TAG_const_type &&
272 Tag != dwarf::DW_TAG_volatile_type && Tag != dwarf::DW_TAG_pointer_type &&
273 Tag != dwarf::DW_TAG_ptr_to_member_type &&
274 Tag != dwarf::DW_TAG_reference_type &&
275 Tag != dwarf::DW_TAG_rvalue_reference_type &&
276 Tag != dwarf::DW_TAG_restrict_type && Tag != dwarf::DW_TAG_array_type &&
277 Tag != dwarf::DW_TAG_enumeration_type &&
278 Tag != dwarf::DW_TAG_subroutine_type &&
279 Tag != dwarf::DW_TAG_inheritance && Tag != dwarf::DW_TAG_friend &&
280 getFilename().empty())
283 // DIType is abstract, it should be a BasicType, a DerivedType or
286 return DIBasicType(DbgNode).Verify();
287 else if (isCompositeType())
288 return DICompositeType(DbgNode).Verify();
289 else if (isDerivedType())
290 return DIDerivedType(DbgNode).Verify();
295 bool DIBasicType::Verify() const { return getRaw(); }
297 bool DIDerivedType::Verify() const {
301 if (getTag() == dwarf::DW_TAG_ptr_to_member_type) {
302 auto *D = dyn_cast<MDDerivedType>(N);
305 if (!isTypeRef(D->getExtraData()))
308 return isTypeRef(N->getBaseType());
311 bool DICompositeType::Verify() const {
313 return N && isTypeRef(N->getBaseType()) && isTypeRef(N->getVTableHolder()) &&
314 !(isLValueReference() && isRValueReference());
317 bool DISubprogram::Verify() const {
322 if (!isScopeRef(N->getScope()))
325 if (auto *Op = N->getType())
326 if (!isa<MDNode>(Op))
329 if (!isTypeRef(getContainingType()))
332 if (isLValueReference() && isRValueReference())
335 // If a DISubprogram has an llvm::Function*, then scope chains from all
336 // instructions within the function should lead to this DISubprogram.
337 if (auto *F = getFunction()) {
338 for (auto &BB : *F) {
340 DebugLoc DL = I.getDebugLoc();
344 MDNode *Scope = nullptr;
345 MDNode *IA = nullptr;
346 // walk the inlined-at scopes
347 while ((IA = DL.getInlinedAt()))
348 DL = DebugLoc::getFromDILocation(IA);
349 DL.getScopeAndInlinedAt(Scope, IA);
353 while (!DIDescriptor(Scope).isSubprogram()) {
354 DILexicalBlockFile D(Scope);
355 Scope = D.isLexicalBlockFile()
357 : DebugLoc::getFromDILexicalBlock(Scope).getScope();
361 if (!DISubprogram(Scope).describes(F))
370 bool DIGlobalVariable::Verify() const {
376 if (N->getDisplayName().empty())
379 if (auto *Op = N->getScope())
380 if (!isa<MDNode>(Op))
383 if (auto *Op = N->getStaticDataMemberDeclaration())
384 if (!isa<MDNode>(Op))
387 return isTypeRef(N->getType());
390 bool DIVariable::Verify() const {
396 if (auto *Op = N->getScope())
397 if (!isa<MDNode>(Op))
400 return isTypeRef(N->getType());
403 bool DIExpression::Verify() const {
404 // FIXME: This should return false if it's null!
406 return !N || N->isValid();
409 bool DILocation::Verify() const { return getRaw(); }
410 bool DINameSpace::Verify() const { return getRaw(); }
411 bool DIFile::Verify() const { return getRaw(); }
412 bool DIEnumerator::Verify() const { return getRaw(); }
413 bool DISubrange::Verify() const { return getRaw(); }
414 bool DILexicalBlock::Verify() const { return getRaw(); }
415 bool DILexicalBlockFile::Verify() const { return getRaw(); }
416 bool DITemplateTypeParameter::Verify() const { return getRaw(); }
417 bool DITemplateValueParameter::Verify() const { return getRaw(); }
418 bool DIImportedEntity::Verify() const { return getRaw(); }
420 void DICompositeType::setArraysHelper(MDNode *Elements, MDNode *TParams) {
421 TypedTrackingMDRef<MDCompositeTypeBase> N(getRaw());
423 N->replaceElements(cast<MDTuple>(Elements));
425 N->replaceTemplateParams(cast<MDTuple>(TParams));
429 DIScopeRef DIScope::getRef() const {
430 if (!isCompositeType())
431 return DIScopeRef(*this);
432 DICompositeType DTy(DbgNode);
433 if (!DTy.getIdentifier())
434 return DIScopeRef(*this);
435 return DIScopeRef(DTy.getIdentifier());
438 void DICompositeType::setContainingType(DICompositeType ContainingType) {
439 TypedTrackingMDRef<MDCompositeTypeBase> N(getRaw());
440 N->replaceVTableHolder(ContainingType.getRef());
444 bool DIVariable::isInlinedFnArgument(const Function *CurFn) {
445 assert(CurFn && "Invalid function");
446 if (!getContext().isSubprogram())
448 // This variable is not inlined function argument if its scope
449 // does not describe current function.
450 return !DISubprogram(getContext()).describes(CurFn);
453 Function *DISubprogram::getFunction() const {
454 if (auto *N = getRaw())
455 if (auto *C = dyn_cast_or_null<ConstantAsMetadata>(N->getFunction()))
456 return dyn_cast<Function>(C->getValue());
460 bool DISubprogram::describes(const Function *F) {
461 assert(F && "Invalid function");
462 if (F == getFunction())
464 StringRef Name = getLinkageName();
467 if (F->getName() == Name)
472 GlobalVariable *DIGlobalVariable::getGlobal() const {
473 return dyn_cast_or_null<GlobalVariable>(getConstant());
476 DIScopeRef DIScope::getContext() const {
479 return DIType(DbgNode).getContext();
482 return DIScopeRef(DISubprogram(DbgNode).getContext());
484 if (isLexicalBlock())
485 return DIScopeRef(DILexicalBlock(DbgNode).getContext());
487 if (isLexicalBlockFile())
488 return DIScopeRef(DILexicalBlockFile(DbgNode).getContext());
491 return DIScopeRef(DINameSpace(DbgNode).getContext());
493 assert((isFile() || isCompileUnit()) && "Unhandled type of scope.");
494 return DIScopeRef(nullptr);
497 StringRef DIScope::getName() const {
499 return DIType(DbgNode).getName();
501 return DISubprogram(DbgNode).getName();
503 return DINameSpace(DbgNode).getName();
504 assert((isLexicalBlock() || isLexicalBlockFile() || isFile() ||
506 "Unhandled type of scope.");
510 StringRef DIScope::getFilename() const {
511 if (auto *N = getRaw())
512 return ::getStringField(dyn_cast_or_null<MDNode>(N->getFile()), 0);
516 StringRef DIScope::getDirectory() const {
517 if (auto *N = getRaw())
518 return ::getStringField(dyn_cast_or_null<MDNode>(N->getFile()), 1);
522 void DICompileUnit::replaceSubprograms(DIArray Subprograms) {
523 assert(Verify() && "Expected compile unit");
524 getRaw()->replaceSubprograms(cast_or_null<MDTuple>(Subprograms.get()));
527 void DICompileUnit::replaceGlobalVariables(DIArray GlobalVariables) {
528 assert(Verify() && "Expected compile unit");
529 getRaw()->replaceGlobalVariables(
530 cast_or_null<MDTuple>(GlobalVariables.get()));
533 DILocation DILocation::copyWithNewScope(LLVMContext &Ctx,
534 DILexicalBlockFile NewScope) {
536 assert(NewScope && "Expected valid scope");
538 const auto *Old = cast<MDLocation>(DbgNode);
539 return DILocation(MDLocation::get(Ctx, Old->getLine(), Old->getColumn(),
540 NewScope, Old->getInlinedAt()));
543 unsigned DILocation::computeNewDiscriminator(LLVMContext &Ctx) {
544 std::pair<const char *, unsigned> Key(getFilename().data(), getLineNumber());
545 return ++Ctx.pImpl->DiscriminatorTable[Key];
548 DIVariable llvm::createInlinedVariable(MDNode *DV, MDNode *InlinedScope,
549 LLVMContext &VMContext) {
550 assert(DIVariable(DV).Verify() && "Expected a DIVariable");
551 return cast<MDLocalVariable>(DV)
552 ->withInline(cast_or_null<MDLocation>(InlinedScope));
555 DIVariable llvm::cleanseInlinedVariable(MDNode *DV, LLVMContext &VMContext) {
556 assert(DIVariable(DV).Verify() && "Expected a DIVariable");
557 return cast<MDLocalVariable>(DV)->withoutInline();
560 DISubprogram llvm::getDISubprogram(const MDNode *Scope) {
561 DIDescriptor D(Scope);
562 if (D.isSubprogram())
563 return DISubprogram(Scope);
565 if (D.isLexicalBlockFile())
566 return getDISubprogram(DILexicalBlockFile(Scope).getContext());
568 if (D.isLexicalBlock())
569 return getDISubprogram(DILexicalBlock(Scope).getContext());
571 return DISubprogram();
574 DISubprogram llvm::getDISubprogram(const Function *F) {
575 // We look for the first instr that has a debug annotation leading back to F.
576 for (auto &BB : *F) {
577 auto Inst = std::find_if(BB.begin(), BB.end(), [](const Instruction &Inst) {
578 return !Inst.getDebugLoc().isUnknown();
580 if (Inst == BB.end())
582 DebugLoc DLoc = Inst->getDebugLoc();
583 const MDNode *Scope = DLoc.getScopeNode();
584 DISubprogram Subprogram = getDISubprogram(Scope);
585 return Subprogram.describes(F) ? Subprogram : DISubprogram();
588 return DISubprogram();
591 DICompositeType llvm::getDICompositeType(DIType T) {
592 if (T.isCompositeType())
593 return DICompositeType(T);
595 if (T.isDerivedType()) {
596 // This function is currently used by dragonegg and dragonegg does
597 // not generate identifier for types, so using an empty map to resolve
598 // DerivedFrom should be fine.
599 DITypeIdentifierMap EmptyMap;
600 return getDICompositeType(
601 DIDerivedType(T).getTypeDerivedFrom().resolve(EmptyMap));
604 return DICompositeType();
608 llvm::generateDITypeIdentifierMap(const NamedMDNode *CU_Nodes) {
609 DITypeIdentifierMap Map;
610 for (unsigned CUi = 0, CUe = CU_Nodes->getNumOperands(); CUi != CUe; ++CUi) {
611 DICompileUnit CU(CU_Nodes->getOperand(CUi));
612 DIArray Retain = CU.getRetainedTypes();
613 for (unsigned Ti = 0, Te = Retain.getNumElements(); Ti != Te; ++Ti) {
614 if (!Retain.getElement(Ti).isCompositeType())
616 DICompositeType Ty(Retain.getElement(Ti));
617 if (MDString *TypeId = Ty.getIdentifier()) {
618 // Definition has priority over declaration.
619 // Try to insert (TypeId, Ty) to Map.
620 std::pair<DITypeIdentifierMap::iterator, bool> P =
621 Map.insert(std::make_pair(TypeId, Ty));
622 // If TypeId already exists in Map and this is a definition, replace
623 // whatever we had (declaration or definition) with the definition.
624 if (!P.second && !Ty.isForwardDecl())
625 P.first->second = Ty;
632 //===----------------------------------------------------------------------===//
633 // DebugInfoFinder implementations.
634 //===----------------------------------------------------------------------===//
636 void DebugInfoFinder::reset() {
643 TypeIdentifierMap.clear();
644 TypeMapInitialized = false;
647 void DebugInfoFinder::InitializeTypeMap(const Module &M) {
648 if (!TypeMapInitialized)
649 if (NamedMDNode *CU_Nodes = M.getNamedMetadata("llvm.dbg.cu")) {
650 TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
651 TypeMapInitialized = true;
655 void DebugInfoFinder::processModule(const Module &M) {
656 InitializeTypeMap(M);
657 if (NamedMDNode *CU_Nodes = M.getNamedMetadata("llvm.dbg.cu")) {
658 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
659 DICompileUnit CU(CU_Nodes->getOperand(i));
661 DIArray GVs = CU.getGlobalVariables();
662 for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i) {
663 DIGlobalVariable DIG(GVs.getElement(i));
664 if (addGlobalVariable(DIG)) {
665 processScope(DIG.getContext());
666 processType(DIG.getType().resolve(TypeIdentifierMap));
669 DIArray SPs = CU.getSubprograms();
670 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
671 processSubprogram(DISubprogram(SPs.getElement(i)));
672 DIArray EnumTypes = CU.getEnumTypes();
673 for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i)
674 processType(DIType(EnumTypes.getElement(i)));
675 DIArray RetainedTypes = CU.getRetainedTypes();
676 for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i)
677 processType(DIType(RetainedTypes.getElement(i)));
678 DIArray Imports = CU.getImportedEntities();
679 for (unsigned i = 0, e = Imports.getNumElements(); i != e; ++i) {
680 DIImportedEntity Import = DIImportedEntity(Imports.getElement(i));
681 DIDescriptor Entity = Import.getEntity().resolve(TypeIdentifierMap);
683 processType(DIType(Entity));
684 else if (Entity.isSubprogram())
685 processSubprogram(DISubprogram(Entity));
686 else if (Entity.isNameSpace())
687 processScope(DINameSpace(Entity).getContext());
693 void DebugInfoFinder::processLocation(const Module &M, DILocation Loc) {
696 InitializeTypeMap(M);
697 processScope(Loc.getScope());
698 processLocation(M, Loc.getOrigLocation());
701 void DebugInfoFinder::processType(DIType DT) {
704 processScope(DT.getContext().resolve(TypeIdentifierMap));
705 if (DT.isCompositeType()) {
706 DICompositeType DCT(DT);
707 processType(DCT.getTypeDerivedFrom().resolve(TypeIdentifierMap));
708 if (DT.isSubroutineType()) {
709 DITypeArray DTA = DISubroutineType(DT).getTypeArray();
710 for (unsigned i = 0, e = DTA.getNumElements(); i != e; ++i)
711 processType(DTA.getElement(i).resolve(TypeIdentifierMap));
714 DIArray DA = DCT.getElements();
715 for (unsigned i = 0, e = DA.getNumElements(); i != e; ++i) {
716 DIDescriptor D = DA.getElement(i);
718 processType(DIType(D));
719 else if (D.isSubprogram())
720 processSubprogram(DISubprogram(D));
722 } else if (DT.isDerivedType()) {
723 DIDerivedType DDT(DT);
724 processType(DDT.getTypeDerivedFrom().resolve(TypeIdentifierMap));
728 void DebugInfoFinder::processScope(DIScope Scope) {
729 if (Scope.isType()) {
734 if (Scope.isCompileUnit()) {
735 addCompileUnit(DICompileUnit(Scope));
738 if (Scope.isSubprogram()) {
739 processSubprogram(DISubprogram(Scope));
742 if (!addScope(Scope))
744 if (Scope.isLexicalBlock()) {
745 DILexicalBlock LB(Scope);
746 processScope(LB.getContext());
747 } else if (Scope.isLexicalBlockFile()) {
748 DILexicalBlockFile LBF = DILexicalBlockFile(Scope);
749 processScope(LBF.getScope());
750 } else if (Scope.isNameSpace()) {
751 DINameSpace NS(Scope);
752 processScope(NS.getContext());
756 void DebugInfoFinder::processSubprogram(DISubprogram SP) {
757 if (!addSubprogram(SP))
759 processScope(SP.getContext().resolve(TypeIdentifierMap));
760 processType(SP.getType());
761 DIArray TParams = SP.getTemplateParams();
762 for (unsigned I = 0, E = TParams.getNumElements(); I != E; ++I) {
763 DIDescriptor Element = TParams.getElement(I);
764 if (Element.isTemplateTypeParameter()) {
765 DITemplateTypeParameter TType(Element);
766 processType(TType.getType().resolve(TypeIdentifierMap));
767 } else if (Element.isTemplateValueParameter()) {
768 DITemplateValueParameter TVal(Element);
769 processType(TVal.getType().resolve(TypeIdentifierMap));
774 void DebugInfoFinder::processDeclare(const Module &M,
775 const DbgDeclareInst *DDI) {
776 MDNode *N = dyn_cast<MDNode>(DDI->getVariable());
779 InitializeTypeMap(M);
782 if (!DV.isVariable())
785 if (!NodesSeen.insert(DV).second)
787 processScope(DIVariable(N).getContext());
788 processType(DIVariable(N).getType().resolve(TypeIdentifierMap));
791 void DebugInfoFinder::processValue(const Module &M, const DbgValueInst *DVI) {
792 MDNode *N = dyn_cast<MDNode>(DVI->getVariable());
795 InitializeTypeMap(M);
798 if (!DV.isVariable())
801 if (!NodesSeen.insert(DV).second)
803 processScope(DIVariable(N).getContext());
804 processType(DIVariable(N).getType().resolve(TypeIdentifierMap));
807 bool DebugInfoFinder::addType(DIType DT) {
811 if (!NodesSeen.insert(DT).second)
818 bool DebugInfoFinder::addCompileUnit(DICompileUnit CU) {
821 if (!NodesSeen.insert(CU).second)
828 bool DebugInfoFinder::addGlobalVariable(DIGlobalVariable DIG) {
832 if (!NodesSeen.insert(DIG).second)
839 bool DebugInfoFinder::addSubprogram(DISubprogram SP) {
843 if (!NodesSeen.insert(SP).second)
850 bool DebugInfoFinder::addScope(DIScope Scope) {
853 // FIXME: Ocaml binding generates a scope with no content, we treat it
855 if (Scope->getNumOperands() == 0)
857 if (!NodesSeen.insert(Scope).second)
859 Scopes.push_back(Scope);
863 //===----------------------------------------------------------------------===//
864 // DIDescriptor: dump routines for all descriptors.
865 //===----------------------------------------------------------------------===//
867 void DIDescriptor::dump() const {
872 void DIDescriptor::print(raw_ostream &OS) const {
878 static void printDebugLoc(DebugLoc DL, raw_ostream &CommentOS,
879 const LLVMContext &Ctx) {
880 if (!DL.isUnknown()) { // Print source line info.
881 DIScope Scope(DL.getScope(Ctx));
882 assert(Scope.isScope() && "Scope of a DebugLoc should be a DIScope.");
883 // Omit the directory, because it's likely to be long and uninteresting.
884 CommentOS << Scope.getFilename();
885 CommentOS << ':' << DL.getLine();
886 if (DL.getCol() != 0)
887 CommentOS << ':' << DL.getCol();
888 DebugLoc InlinedAtDL = DebugLoc::getFromDILocation(DL.getInlinedAt(Ctx));
889 if (!InlinedAtDL.isUnknown()) {
891 printDebugLoc(InlinedAtDL, CommentOS, Ctx);
897 void DIVariable::printExtendedName(raw_ostream &OS) const {
898 const LLVMContext &Ctx = DbgNode->getContext();
899 StringRef Res = getName();
901 OS << Res << "," << getLineNumber();
902 if (MDNode *InlinedAt = getInlinedAt()) {
903 DebugLoc InlinedAtDL = DebugLoc::getFromDILocation(InlinedAt);
904 if (!InlinedAtDL.isUnknown()) {
906 printDebugLoc(InlinedAtDL, OS, Ctx);
912 template <> DIRef<DIDescriptor>::DIRef(const Metadata *V) : Val(V) {
913 assert(isDescriptorRef(V) &&
914 "DIDescriptorRef should be a MDString or MDNode");
916 template <> DIRef<DIScope>::DIRef(const Metadata *V) : Val(V) {
917 assert(isScopeRef(V) && "DIScopeRef should be a MDString or MDNode");
919 template <> DIRef<DIType>::DIRef(const Metadata *V) : Val(V) {
920 assert(isTypeRef(V) && "DITypeRef should be a MDString or MDNode");
924 DIDescriptorRef DIDescriptor::getFieldAs<DIDescriptorRef>(unsigned Elt) const {
925 return DIDescriptorRef(cast_or_null<Metadata>(getField(DbgNode, Elt)));
928 DIScopeRef DIDescriptor::getFieldAs<DIScopeRef>(unsigned Elt) const {
929 return DIScopeRef(cast_or_null<Metadata>(getField(DbgNode, Elt)));
931 template <> DITypeRef DIDescriptor::getFieldAs<DITypeRef>(unsigned Elt) const {
932 return DITypeRef(cast_or_null<Metadata>(getField(DbgNode, Elt)));
935 bool llvm::StripDebugInfo(Module &M) {
936 bool Changed = false;
938 // Remove all of the calls to the debugger intrinsics, and remove them from
940 if (Function *Declare = M.getFunction("llvm.dbg.declare")) {
941 while (!Declare->use_empty()) {
942 CallInst *CI = cast<CallInst>(Declare->user_back());
943 CI->eraseFromParent();
945 Declare->eraseFromParent();
949 if (Function *DbgVal = M.getFunction("llvm.dbg.value")) {
950 while (!DbgVal->use_empty()) {
951 CallInst *CI = cast<CallInst>(DbgVal->user_back());
952 CI->eraseFromParent();
954 DbgVal->eraseFromParent();
958 for (Module::named_metadata_iterator NMI = M.named_metadata_begin(),
959 NME = M.named_metadata_end(); NMI != NME;) {
960 NamedMDNode *NMD = NMI;
962 if (NMD->getName().startswith("llvm.dbg.")) {
963 NMD->eraseFromParent();
968 for (Module::iterator MI = M.begin(), ME = M.end(); MI != ME; ++MI)
969 for (Function::iterator FI = MI->begin(), FE = MI->end(); FI != FE;
971 for (BasicBlock::iterator BI = FI->begin(), BE = FI->end(); BI != BE;
973 if (!BI->getDebugLoc().isUnknown()) {
975 BI->setDebugLoc(DebugLoc());
982 unsigned llvm::getDebugMetadataVersionFromModule(const Module &M) {
983 if (auto *Val = mdconst::dyn_extract_or_null<ConstantInt>(
984 M.getModuleFlag("Debug Info Version")))
985 return Val->getZExtValue();
989 llvm::DenseMap<const llvm::Function *, llvm::DISubprogram>
990 llvm::makeSubprogramMap(const Module &M) {
991 DenseMap<const Function *, DISubprogram> R;
993 NamedMDNode *CU_Nodes = M.getNamedMetadata("llvm.dbg.cu");
997 for (MDNode *N : CU_Nodes->operands()) {
998 DICompileUnit CUNode(N);
999 DIArray SPs = CUNode.getSubprograms();
1000 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i) {
1001 DISubprogram SP(SPs.getElement(i));
1002 if (Function *F = SP.getFunction())
1003 R.insert(std::make_pair(F, SP));