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/Module.h"
28 #include "llvm/IR/ValueHandle.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/Support/Dwarf.h"
31 #include "llvm/Support/raw_ostream.h"
33 using namespace llvm::dwarf;
35 //===----------------------------------------------------------------------===//
37 //===----------------------------------------------------------------------===//
39 bool DIDescriptor::Verify() const {
41 (DIDerivedType(DbgNode).Verify() ||
42 DICompositeType(DbgNode).Verify() || DIBasicType(DbgNode).Verify() ||
43 DIVariable(DbgNode).Verify() || DISubprogram(DbgNode).Verify() ||
44 DIGlobalVariable(DbgNode).Verify() || DIFile(DbgNode).Verify() ||
45 DICompileUnit(DbgNode).Verify() || DINameSpace(DbgNode).Verify() ||
46 DILexicalBlock(DbgNode).Verify() ||
47 DILexicalBlockFile(DbgNode).Verify() ||
48 DISubrange(DbgNode).Verify() || DIEnumerator(DbgNode).Verify() ||
49 DIObjCProperty(DbgNode).Verify() ||
50 DITemplateTypeParameter(DbgNode).Verify() ||
51 DITemplateValueParameter(DbgNode).Verify() ||
52 DIImportedEntity(DbgNode).Verify() || DIExpression(DbgNode).Verify());
55 static Metadata *getField(const MDNode *DbgNode, unsigned Elt) {
56 if (!DbgNode || Elt >= DbgNode->getNumOperands())
58 return DbgNode->getOperand(Elt);
61 static MDNode *getNodeField(const MDNode *DbgNode, unsigned Elt) {
62 return dyn_cast_or_null<MDNode>(getField(DbgNode, Elt));
65 static StringRef getStringField(const MDNode *DbgNode, unsigned Elt) {
66 if (MDString *MDS = dyn_cast_or_null<MDString>(getField(DbgNode, Elt)))
67 return MDS->getString();
71 StringRef DIDescriptor::getStringField(unsigned Elt) const {
72 return ::getStringField(DbgNode, Elt);
75 uint64_t DIDescriptor::getUInt64Field(unsigned Elt) const {
76 if (auto *C = getConstantField(Elt))
77 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
78 return CI->getZExtValue();
83 int64_t DIDescriptor::getInt64Field(unsigned Elt) const {
84 if (auto *C = getConstantField(Elt))
85 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
86 return CI->getZExtValue();
91 DIDescriptor DIDescriptor::getDescriptorField(unsigned Elt) const {
92 MDNode *Field = getNodeField(DbgNode, Elt);
93 return DIDescriptor(Field);
96 GlobalVariable *DIDescriptor::getGlobalVariableField(unsigned Elt) const {
97 return dyn_cast_or_null<GlobalVariable>(getConstantField(Elt));
100 Constant *DIDescriptor::getConstantField(unsigned Elt) const {
104 if (Elt < DbgNode->getNumOperands())
106 dyn_cast_or_null<ConstantAsMetadata>(DbgNode->getOperand(Elt)))
107 return C->getValue();
111 Function *DIDescriptor::getFunctionField(unsigned Elt) const {
112 return dyn_cast_or_null<Function>(getConstantField(Elt));
115 void DIDescriptor::replaceFunctionField(unsigned Elt, Function *F) {
119 if (Elt < DbgNode->getNumOperands()) {
120 MDNode *Node = const_cast<MDNode *>(DbgNode);
121 Node->replaceOperandWith(Elt, F ? ConstantAsMetadata::get(F) : nullptr);
125 static unsigned DIVariableInlinedAtIndex = 4;
126 MDNode *DIVariable::getInlinedAt() const {
127 return getNodeField(DbgNode, DIVariableInlinedAtIndex);
130 /// \brief Return the size reported by the variable's type.
131 unsigned DIVariable::getSizeInBits(const DITypeIdentifierMap &Map) {
132 DIType Ty = getType().resolve(Map);
133 // Follow derived types until we reach a type that
134 // reports back a size.
135 while (Ty.isDerivedType() && !Ty.getSizeInBits()) {
136 DIDerivedType DT(&*Ty);
137 Ty = DT.getTypeDerivedFrom().resolve(Map);
139 assert(Ty.getSizeInBits() && "type with size 0");
140 return Ty.getSizeInBits();
143 uint64_t DIExpression::getElement(unsigned Idx) const {
144 unsigned I = Idx + 1;
145 assert(I < getNumHeaderFields() &&
146 "non-existing complex address element requested");
147 return getHeaderFieldAs<int64_t>(I);
150 bool DIExpression::isVariablePiece() const {
151 return getNumElements() && getElement(0) == dwarf::DW_OP_piece;
154 uint64_t DIExpression::getPieceOffset() const {
155 assert(isVariablePiece());
156 return getElement(1);
159 uint64_t DIExpression::getPieceSize() const {
160 assert(isVariablePiece());
161 return getElement(2);
164 //===----------------------------------------------------------------------===//
166 //===----------------------------------------------------------------------===//
168 bool DIDescriptor::isSubroutineType() const {
169 return DbgNode && getTag() == dwarf::DW_TAG_subroutine_type;
172 bool DIDescriptor::isBasicType() const {
176 case dwarf::DW_TAG_base_type:
177 case dwarf::DW_TAG_unspecified_type:
184 bool DIDescriptor::isDerivedType() const {
188 case dwarf::DW_TAG_typedef:
189 case dwarf::DW_TAG_pointer_type:
190 case dwarf::DW_TAG_ptr_to_member_type:
191 case dwarf::DW_TAG_reference_type:
192 case dwarf::DW_TAG_rvalue_reference_type:
193 case dwarf::DW_TAG_const_type:
194 case dwarf::DW_TAG_volatile_type:
195 case dwarf::DW_TAG_restrict_type:
196 case dwarf::DW_TAG_member:
197 case dwarf::DW_TAG_inheritance:
198 case dwarf::DW_TAG_friend:
201 // CompositeTypes are currently modelled as DerivedTypes.
202 return isCompositeType();
206 bool DIDescriptor::isCompositeType() const {
210 case dwarf::DW_TAG_array_type:
211 case dwarf::DW_TAG_structure_type:
212 case dwarf::DW_TAG_union_type:
213 case dwarf::DW_TAG_enumeration_type:
214 case dwarf::DW_TAG_subroutine_type:
215 case dwarf::DW_TAG_class_type:
222 bool DIDescriptor::isVariable() const {
226 case dwarf::DW_TAG_auto_variable:
227 case dwarf::DW_TAG_arg_variable:
234 bool DIDescriptor::isType() const {
235 return isBasicType() || isCompositeType() || isDerivedType();
238 bool DIDescriptor::isSubprogram() const {
239 return DbgNode && getTag() == dwarf::DW_TAG_subprogram;
242 bool DIDescriptor::isGlobalVariable() const {
243 return DbgNode && (getTag() == dwarf::DW_TAG_variable ||
244 getTag() == dwarf::DW_TAG_constant);
247 bool DIDescriptor::isScope() const {
251 case dwarf::DW_TAG_compile_unit:
252 case dwarf::DW_TAG_lexical_block:
253 case dwarf::DW_TAG_subprogram:
254 case dwarf::DW_TAG_namespace:
255 case dwarf::DW_TAG_file_type:
263 bool DIDescriptor::isTemplateTypeParameter() const {
264 return DbgNode && getTag() == dwarf::DW_TAG_template_type_parameter;
267 bool DIDescriptor::isTemplateValueParameter() const {
268 return DbgNode && (getTag() == dwarf::DW_TAG_template_value_parameter ||
269 getTag() == dwarf::DW_TAG_GNU_template_template_param ||
270 getTag() == dwarf::DW_TAG_GNU_template_parameter_pack);
273 bool DIDescriptor::isCompileUnit() const {
274 return DbgNode && getTag() == dwarf::DW_TAG_compile_unit;
277 bool DIDescriptor::isFile() const {
278 return DbgNode && getTag() == dwarf::DW_TAG_file_type;
281 bool DIDescriptor::isNameSpace() const {
282 return DbgNode && getTag() == dwarf::DW_TAG_namespace;
285 bool DIDescriptor::isLexicalBlockFile() const {
286 return DbgNode && getTag() == dwarf::DW_TAG_lexical_block &&
287 DbgNode->getNumOperands() == 3 && getNumHeaderFields() == 2;
290 bool DIDescriptor::isLexicalBlock() const {
291 // FIXME: There are always exactly 4 header fields in DILexicalBlock, but
292 // something relies on this returning true for DILexicalBlockFile.
293 return DbgNode && getTag() == dwarf::DW_TAG_lexical_block &&
294 DbgNode->getNumOperands() == 3 &&
295 (getNumHeaderFields() == 2 || getNumHeaderFields() == 4);
298 bool DIDescriptor::isSubrange() const {
299 return DbgNode && getTag() == dwarf::DW_TAG_subrange_type;
302 bool DIDescriptor::isEnumerator() const {
303 return DbgNode && getTag() == dwarf::DW_TAG_enumerator;
306 bool DIDescriptor::isObjCProperty() const {
307 return DbgNode && getTag() == dwarf::DW_TAG_APPLE_property;
310 bool DIDescriptor::isImportedEntity() const {
311 return DbgNode && (getTag() == dwarf::DW_TAG_imported_module ||
312 getTag() == dwarf::DW_TAG_imported_declaration);
315 bool DIDescriptor::isExpression() const {
316 return DbgNode && (getTag() == dwarf::DW_TAG_expression);
319 //===----------------------------------------------------------------------===//
320 // Simple Descriptor Constructors and other Methods
321 //===----------------------------------------------------------------------===//
323 void DIDescriptor::replaceAllUsesWith(LLVMContext &VMContext, DIDescriptor D) {
325 assert(DbgNode && "Trying to replace an unverified type!");
327 // Since we use a TrackingVH for the node, its easy for clients to manufacture
328 // legitimate situations where they want to replaceAllUsesWith() on something
329 // which, due to uniquing, has merged with the source. We shield clients from
330 // this detail by allowing a value to be replaced with replaceAllUsesWith()
332 const MDNode *DN = D;
334 SmallVector<Metadata *, 10> Ops(DbgNode->getNumOperands());
335 for (size_t i = 0; i != Ops.size(); ++i)
336 Ops[i] = DbgNode->getOperand(i);
337 DN = MDNode::get(VMContext, Ops);
340 assert(DbgNode->isTemporary() && "Expected temporary node");
341 auto *Node = const_cast<MDNode *>(DbgNode);
342 Node->replaceAllUsesWith(const_cast<MDNode *>(DN));
343 MDNode::deleteTemporary(Node);
347 void DIDescriptor::replaceAllUsesWith(MDNode *D) {
348 assert(DbgNode && "Trying to replace an unverified type!");
349 assert(DbgNode != D && "This replacement should always happen");
350 assert(DbgNode->isTemporary() && "Expected temporary node");
351 auto *Node = const_cast<MDNode *>(DbgNode);
352 Node->replaceAllUsesWith(D);
353 MDNode::deleteTemporary(Node);
356 bool DICompileUnit::Verify() const {
357 if (!isCompileUnit())
360 // Don't bother verifying the compilation directory or producer string
361 // as those could be empty.
362 if (getFilename().empty())
365 return DbgNode->getNumOperands() == 7 && getNumHeaderFields() == 8;
368 bool DIObjCProperty::Verify() const {
369 if (!isObjCProperty())
372 // Don't worry about the rest of the strings for now.
373 return DbgNode->getNumOperands() == 3 && getNumHeaderFields() == 6;
376 /// \brief Check if a field at position Elt of a MDNode is a MDNode.
378 /// We currently allow an empty string and an integer.
379 /// But we don't allow a non-empty string in a MDNode field.
380 static bool fieldIsMDNode(const MDNode *DbgNode, unsigned Elt) {
381 // FIXME: This function should return true, if the field is null or the field
382 // is indeed a MDNode: return !Fld || isa<MDNode>(Fld).
383 Metadata *Fld = getField(DbgNode, Elt);
384 if (Fld && isa<MDString>(Fld) && !cast<MDString>(Fld)->getString().empty())
389 /// \brief Check if a field at position Elt of a MDNode is a MDString.
390 static bool fieldIsMDString(const MDNode *DbgNode, unsigned Elt) {
391 Metadata *Fld = getField(DbgNode, Elt);
392 return !Fld || isa<MDString>(Fld);
395 /// \brief Check if a value can be a reference to a type.
396 static bool isTypeRef(const Metadata *MD) {
399 if (auto *S = dyn_cast<MDString>(MD))
400 return !S->getString().empty();
401 if (auto *N = dyn_cast<MDNode>(MD))
402 return DIType(N).isType();
406 /// \brief Check if referenced field might be a type.
407 static bool fieldIsTypeRef(const MDNode *DbgNode, unsigned Elt) {
408 return isTypeRef(dyn_cast_or_null<Metadata>(getField(DbgNode, Elt)));
411 /// \brief Check if a value can be a ScopeRef.
412 static bool isScopeRef(const Metadata *MD) {
415 if (auto *S = dyn_cast<MDString>(MD))
416 return !S->getString().empty();
417 return isa<MDNode>(MD);
420 /// \brief Check if a field at position Elt of a MDNode can be a ScopeRef.
421 static bool fieldIsScopeRef(const MDNode *DbgNode, unsigned Elt) {
422 return isScopeRef(dyn_cast_or_null<Metadata>(getField(DbgNode, Elt)));
425 bool DIType::Verify() const {
428 // Make sure Context @ field 2 is MDNode.
429 if (!fieldIsScopeRef(DbgNode, 2))
432 // FIXME: Sink this into the various subclass verifies.
433 uint16_t Tag = getTag();
434 if (!isBasicType() && Tag != dwarf::DW_TAG_const_type &&
435 Tag != dwarf::DW_TAG_volatile_type && Tag != dwarf::DW_TAG_pointer_type &&
436 Tag != dwarf::DW_TAG_ptr_to_member_type &&
437 Tag != dwarf::DW_TAG_reference_type &&
438 Tag != dwarf::DW_TAG_rvalue_reference_type &&
439 Tag != dwarf::DW_TAG_restrict_type && Tag != dwarf::DW_TAG_array_type &&
440 Tag != dwarf::DW_TAG_enumeration_type &&
441 Tag != dwarf::DW_TAG_subroutine_type &&
442 Tag != dwarf::DW_TAG_inheritance && Tag != dwarf::DW_TAG_friend &&
443 getFilename().empty())
446 // DIType is abstract, it should be a BasicType, a DerivedType or
449 return DIBasicType(DbgNode).Verify();
450 else if (isCompositeType())
451 return DICompositeType(DbgNode).Verify();
452 else if (isDerivedType())
453 return DIDerivedType(DbgNode).Verify();
458 bool DIBasicType::Verify() const {
459 return isBasicType() && DbgNode->getNumOperands() == 3 &&
460 getNumHeaderFields() == 8;
463 bool DIDerivedType::Verify() const {
464 // Make sure DerivedFrom @ field 3 is TypeRef.
465 if (!fieldIsTypeRef(DbgNode, 3))
467 if (getTag() == dwarf::DW_TAG_ptr_to_member_type)
468 // Make sure ClassType @ field 4 is a TypeRef.
469 if (!fieldIsTypeRef(DbgNode, 4))
472 return isDerivedType() && DbgNode->getNumOperands() >= 4 &&
473 DbgNode->getNumOperands() <= 8 && getNumHeaderFields() >= 7 &&
474 getNumHeaderFields() <= 8;
477 bool DICompositeType::Verify() const {
478 if (!isCompositeType())
481 // Make sure DerivedFrom @ field 3 and ContainingType @ field 5 are TypeRef.
482 if (!fieldIsTypeRef(DbgNode, 3))
484 if (!fieldIsTypeRef(DbgNode, 5))
487 // Make sure the type identifier at field 7 is MDString, it can be null.
488 if (!fieldIsMDString(DbgNode, 7))
491 // A subroutine type can't be both & and &&.
492 if (isLValueReference() && isRValueReference())
495 return DbgNode->getNumOperands() == 8 && getNumHeaderFields() == 8;
498 bool DISubprogram::Verify() const {
502 // Make sure context @ field 2 is a ScopeRef and type @ field 3 is a MDNode.
503 if (!fieldIsScopeRef(DbgNode, 2))
505 if (!fieldIsMDNode(DbgNode, 3))
507 // Containing type @ field 4.
508 if (!fieldIsTypeRef(DbgNode, 4))
511 // A subprogram can't be both & and &&.
512 if (isLValueReference() && isRValueReference())
515 // If a DISubprogram has an llvm::Function*, then scope chains from all
516 // instructions within the function should lead to this DISubprogram.
517 if (auto *F = getFunction()) {
518 for (auto &BB : *F) {
520 DebugLoc DL = I.getDebugLoc();
524 MDNode *Scope = nullptr;
525 MDNode *IA = nullptr;
526 // walk the inlined-at scopes
527 while ((IA = DL.getInlinedAt()))
528 DL = DebugLoc::getFromDILocation(IA);
529 DL.getScopeAndInlinedAt(Scope, IA);
531 while (!DIDescriptor(Scope).isSubprogram()) {
532 DILexicalBlockFile D(Scope);
533 Scope = D.isLexicalBlockFile()
535 : DebugLoc::getFromDILexicalBlock(Scope).getScope();
537 if (!DISubprogram(Scope).describes(F))
542 return DbgNode->getNumOperands() == 9 && getNumHeaderFields() == 12;
545 bool DIGlobalVariable::Verify() const {
546 if (!isGlobalVariable())
549 if (getDisplayName().empty())
551 // Make sure context @ field 1 is an MDNode.
552 if (!fieldIsMDNode(DbgNode, 1))
554 // Make sure that type @ field 3 is a DITypeRef.
555 if (!fieldIsTypeRef(DbgNode, 3))
557 // Make sure StaticDataMemberDeclaration @ field 5 is MDNode.
558 if (!fieldIsMDNode(DbgNode, 5))
561 return DbgNode->getNumOperands() == 6 && getNumHeaderFields() == 7;
564 bool DIVariable::Verify() const {
568 // Make sure context @ field 1 is an MDNode.
569 if (!fieldIsMDNode(DbgNode, 1))
571 // Make sure that type @ field 3 is a DITypeRef.
572 if (!fieldIsTypeRef(DbgNode, 3))
575 // Check the number of header fields, which is common between complex and
577 if (getNumHeaderFields() != 4)
580 // Variable without an inline location.
581 if (DbgNode->getNumOperands() == 4)
584 // Variable with an inline location.
585 return getInlinedAt() != nullptr && DbgNode->getNumOperands() == 5;
588 bool DIExpression::Verify() const {
589 // Empty DIExpressions may be represented as a nullptr.
593 return isExpression() && DbgNode->getNumOperands() == 1;
596 bool DILocation::Verify() const {
597 return DbgNode && isa<MDLocation>(DbgNode);
600 bool DINameSpace::Verify() const {
603 return DbgNode->getNumOperands() == 3 && getNumHeaderFields() == 3;
606 MDNode *DIFile::getFileNode() const { return getNodeField(DbgNode, 1); }
608 bool DIFile::Verify() const {
609 return isFile() && DbgNode->getNumOperands() == 2;
612 bool DIEnumerator::Verify() const {
613 return isEnumerator() && DbgNode->getNumOperands() == 1 &&
614 getNumHeaderFields() == 3;
617 bool DISubrange::Verify() const {
618 return isSubrange() && DbgNode->getNumOperands() == 1 &&
619 getNumHeaderFields() == 3;
622 bool DILexicalBlock::Verify() const {
623 return isLexicalBlock() && DbgNode->getNumOperands() == 3 &&
624 getNumHeaderFields() == 4;
627 bool DILexicalBlockFile::Verify() const {
628 return isLexicalBlockFile() && DbgNode->getNumOperands() == 3 &&
629 getNumHeaderFields() == 2;
632 bool DITemplateTypeParameter::Verify() const {
633 return isTemplateTypeParameter() && DbgNode->getNumOperands() == 4 &&
634 getNumHeaderFields() == 4;
637 bool DITemplateValueParameter::Verify() const {
638 return isTemplateValueParameter() && DbgNode->getNumOperands() == 5 &&
639 getNumHeaderFields() == 4;
642 bool DIImportedEntity::Verify() const {
643 return isImportedEntity() && DbgNode->getNumOperands() == 3 &&
644 getNumHeaderFields() == 3;
647 MDNode *DIDerivedType::getObjCProperty() const {
648 return getNodeField(DbgNode, 4);
651 MDString *DICompositeType::getIdentifier() const {
652 return cast_or_null<MDString>(getField(DbgNode, 7));
656 static void VerifySubsetOf(const MDNode *LHS, const MDNode *RHS) {
657 for (unsigned i = 0; i != LHS->getNumOperands(); ++i) {
658 // Skip the 'empty' list (that's a single i32 0, rather than truly empty).
659 if (i == 0 && mdconst::hasa<ConstantInt>(LHS->getOperand(i)))
661 const MDNode *E = cast<MDNode>(LHS->getOperand(i));
663 for (unsigned j = 0; !found && j != RHS->getNumOperands(); ++j)
664 found = (E == cast<MDNode>(RHS->getOperand(j)));
665 assert(found && "Losing a member during member list replacement");
670 void DICompositeType::setArraysHelper(MDNode *Elements, MDNode *TParams) {
671 TrackingMDNodeRef N(*this);
674 // Check that the new list of members contains all the old members as well.
675 if (const MDNode *El = cast_or_null<MDNode>(N->getOperand(4)))
676 VerifySubsetOf(El, Elements);
678 N->replaceOperandWith(4, Elements);
681 N->replaceOperandWith(6, TParams);
685 DIScopeRef DIScope::getRef() const {
686 if (!isCompositeType())
687 return DIScopeRef(*this);
688 DICompositeType DTy(DbgNode);
689 if (!DTy.getIdentifier())
690 return DIScopeRef(*this);
691 return DIScopeRef(DTy.getIdentifier());
694 void DICompositeType::setContainingType(DICompositeType ContainingType) {
695 TrackingMDNodeRef N(*this);
696 N->replaceOperandWith(5, ContainingType.getRef());
700 bool DIVariable::isInlinedFnArgument(const Function *CurFn) {
701 assert(CurFn && "Invalid function");
702 if (!getContext().isSubprogram())
704 // This variable is not inlined function argument if its scope
705 // does not describe current function.
706 return !DISubprogram(getContext()).describes(CurFn);
709 bool DISubprogram::describes(const Function *F) {
710 assert(F && "Invalid function");
711 if (F == getFunction())
713 StringRef Name = getLinkageName();
716 if (F->getName() == Name)
721 MDNode *DISubprogram::getVariablesNodes() const {
722 return getNodeField(DbgNode, 8);
725 DIArray DISubprogram::getVariables() const {
726 return DIArray(getNodeField(DbgNode, 8));
729 Metadata *DITemplateValueParameter::getValue() const {
730 return DbgNode->getOperand(3);
733 DIScopeRef DIScope::getContext() const {
736 return DIType(DbgNode).getContext();
739 return DIScopeRef(DISubprogram(DbgNode).getContext());
741 if (isLexicalBlock())
742 return DIScopeRef(DILexicalBlock(DbgNode).getContext());
744 if (isLexicalBlockFile())
745 return DIScopeRef(DILexicalBlockFile(DbgNode).getContext());
748 return DIScopeRef(DINameSpace(DbgNode).getContext());
750 assert((isFile() || isCompileUnit()) && "Unhandled type of scope.");
751 return DIScopeRef(nullptr);
754 StringRef DIScope::getName() const {
756 return DIType(DbgNode).getName();
758 return DISubprogram(DbgNode).getName();
760 return DINameSpace(DbgNode).getName();
761 assert((isLexicalBlock() || isLexicalBlockFile() || isFile() ||
763 "Unhandled type of scope.");
767 StringRef DIScope::getFilename() const {
770 return ::getStringField(getNodeField(DbgNode, 1), 0);
773 StringRef DIScope::getDirectory() const {
776 return ::getStringField(getNodeField(DbgNode, 1), 1);
779 DIArray DICompileUnit::getEnumTypes() const {
780 if (!DbgNode || DbgNode->getNumOperands() < 7)
783 return DIArray(getNodeField(DbgNode, 2));
786 DIArray DICompileUnit::getRetainedTypes() const {
787 if (!DbgNode || DbgNode->getNumOperands() < 7)
790 return DIArray(getNodeField(DbgNode, 3));
793 DIArray DICompileUnit::getSubprograms() const {
794 if (!DbgNode || DbgNode->getNumOperands() < 7)
797 return DIArray(getNodeField(DbgNode, 4));
800 DIArray DICompileUnit::getGlobalVariables() const {
801 if (!DbgNode || DbgNode->getNumOperands() < 7)
804 return DIArray(getNodeField(DbgNode, 5));
807 DIArray DICompileUnit::getImportedEntities() const {
808 if (!DbgNode || DbgNode->getNumOperands() < 7)
811 return DIArray(getNodeField(DbgNode, 6));
814 void DICompileUnit::replaceSubprograms(DIArray Subprograms) {
815 assert(Verify() && "Expected compile unit");
816 if (Subprograms == getSubprograms())
819 const_cast<MDNode *>(DbgNode)->replaceOperandWith(4, Subprograms);
822 void DICompileUnit::replaceGlobalVariables(DIArray GlobalVariables) {
823 assert(Verify() && "Expected compile unit");
824 if (GlobalVariables == getGlobalVariables())
827 const_cast<MDNode *>(DbgNode)->replaceOperandWith(5, GlobalVariables);
830 DILocation DILocation::copyWithNewScope(LLVMContext &Ctx,
831 DILexicalBlockFile NewScope) {
833 assert(NewScope && "Expected valid scope");
835 const auto *Old = cast<MDLocation>(DbgNode);
836 return DILocation(MDLocation::get(Ctx, Old->getLine(), Old->getColumn(),
837 NewScope, Old->getInlinedAt()));
840 unsigned DILocation::computeNewDiscriminator(LLVMContext &Ctx) {
841 std::pair<const char *, unsigned> Key(getFilename().data(), getLineNumber());
842 return ++Ctx.pImpl->DiscriminatorTable[Key];
845 DIVariable llvm::createInlinedVariable(MDNode *DV, MDNode *InlinedScope,
846 LLVMContext &VMContext) {
847 assert(DIVariable(DV).Verify() && "Expected a DIVariable");
849 return cleanseInlinedVariable(DV, VMContext);
851 // Insert inlined scope.
852 SmallVector<Metadata *, 8> Elts;
853 for (unsigned I = 0, E = DIVariableInlinedAtIndex; I != E; ++I)
854 Elts.push_back(DV->getOperand(I));
855 Elts.push_back(InlinedScope);
857 DIVariable Inlined(MDNode::get(VMContext, Elts));
858 assert(Inlined.Verify() && "Expected to create a DIVariable");
862 DIVariable llvm::cleanseInlinedVariable(MDNode *DV, LLVMContext &VMContext) {
863 assert(DIVariable(DV).Verify() && "Expected a DIVariable");
864 if (!DIVariable(DV).getInlinedAt())
865 return DIVariable(DV);
867 // Remove inlined scope.
868 SmallVector<Metadata *, 8> Elts;
869 for (unsigned I = 0, E = DIVariableInlinedAtIndex; I != E; ++I)
870 Elts.push_back(DV->getOperand(I));
872 DIVariable Cleansed(MDNode::get(VMContext, Elts));
873 assert(Cleansed.Verify() && "Expected to create a DIVariable");
877 DISubprogram llvm::getDISubprogram(const MDNode *Scope) {
878 DIDescriptor D(Scope);
879 if (D.isSubprogram())
880 return DISubprogram(Scope);
882 if (D.isLexicalBlockFile())
883 return getDISubprogram(DILexicalBlockFile(Scope).getContext());
885 if (D.isLexicalBlock())
886 return getDISubprogram(DILexicalBlock(Scope).getContext());
888 return DISubprogram();
891 DISubprogram llvm::getDISubprogram(const Function *F) {
892 // We look for the first instr that has a debug annotation leading back to F.
893 for (auto &BB : *F) {
894 auto Inst = std::find_if(BB.begin(), BB.end(), [](const Instruction &Inst) {
895 return !Inst.getDebugLoc().isUnknown();
897 if (Inst == BB.end())
899 DebugLoc DLoc = Inst->getDebugLoc();
900 const MDNode *Scope = DLoc.getScopeNode();
901 DISubprogram Subprogram = getDISubprogram(Scope);
902 return Subprogram.describes(F) ? Subprogram : DISubprogram();
905 return DISubprogram();
908 DICompositeType llvm::getDICompositeType(DIType T) {
909 if (T.isCompositeType())
910 return DICompositeType(T);
912 if (T.isDerivedType()) {
913 // This function is currently used by dragonegg and dragonegg does
914 // not generate identifier for types, so using an empty map to resolve
915 // DerivedFrom should be fine.
916 DITypeIdentifierMap EmptyMap;
917 return getDICompositeType(
918 DIDerivedType(T).getTypeDerivedFrom().resolve(EmptyMap));
921 return DICompositeType();
925 llvm::generateDITypeIdentifierMap(const NamedMDNode *CU_Nodes) {
926 DITypeIdentifierMap Map;
927 for (unsigned CUi = 0, CUe = CU_Nodes->getNumOperands(); CUi != CUe; ++CUi) {
928 DICompileUnit CU(CU_Nodes->getOperand(CUi));
929 DIArray Retain = CU.getRetainedTypes();
930 for (unsigned Ti = 0, Te = Retain.getNumElements(); Ti != Te; ++Ti) {
931 if (!Retain.getElement(Ti).isCompositeType())
933 DICompositeType Ty(Retain.getElement(Ti));
934 if (MDString *TypeId = Ty.getIdentifier()) {
935 // Definition has priority over declaration.
936 // Try to insert (TypeId, Ty) to Map.
937 std::pair<DITypeIdentifierMap::iterator, bool> P =
938 Map.insert(std::make_pair(TypeId, Ty));
939 // If TypeId already exists in Map and this is a definition, replace
940 // whatever we had (declaration or definition) with the definition.
941 if (!P.second && !Ty.isForwardDecl())
942 P.first->second = Ty;
949 //===----------------------------------------------------------------------===//
950 // DebugInfoFinder implementations.
951 //===----------------------------------------------------------------------===//
953 void DebugInfoFinder::reset() {
960 TypeIdentifierMap.clear();
961 TypeMapInitialized = false;
964 void DebugInfoFinder::InitializeTypeMap(const Module &M) {
965 if (!TypeMapInitialized)
966 if (NamedMDNode *CU_Nodes = M.getNamedMetadata("llvm.dbg.cu")) {
967 TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
968 TypeMapInitialized = true;
972 void DebugInfoFinder::processModule(const Module &M) {
973 InitializeTypeMap(M);
974 if (NamedMDNode *CU_Nodes = M.getNamedMetadata("llvm.dbg.cu")) {
975 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
976 DICompileUnit CU(CU_Nodes->getOperand(i));
978 DIArray GVs = CU.getGlobalVariables();
979 for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i) {
980 DIGlobalVariable DIG(GVs.getElement(i));
981 if (addGlobalVariable(DIG)) {
982 processScope(DIG.getContext());
983 processType(DIG.getType().resolve(TypeIdentifierMap));
986 DIArray SPs = CU.getSubprograms();
987 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
988 processSubprogram(DISubprogram(SPs.getElement(i)));
989 DIArray EnumTypes = CU.getEnumTypes();
990 for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i)
991 processType(DIType(EnumTypes.getElement(i)));
992 DIArray RetainedTypes = CU.getRetainedTypes();
993 for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i)
994 processType(DIType(RetainedTypes.getElement(i)));
995 DIArray Imports = CU.getImportedEntities();
996 for (unsigned i = 0, e = Imports.getNumElements(); i != e; ++i) {
997 DIImportedEntity Import = DIImportedEntity(Imports.getElement(i));
998 DIDescriptor Entity = Import.getEntity().resolve(TypeIdentifierMap);
1000 processType(DIType(Entity));
1001 else if (Entity.isSubprogram())
1002 processSubprogram(DISubprogram(Entity));
1003 else if (Entity.isNameSpace())
1004 processScope(DINameSpace(Entity).getContext());
1010 void DebugInfoFinder::processLocation(const Module &M, DILocation Loc) {
1013 InitializeTypeMap(M);
1014 processScope(Loc.getScope());
1015 processLocation(M, Loc.getOrigLocation());
1018 void DebugInfoFinder::processType(DIType DT) {
1021 processScope(DT.getContext().resolve(TypeIdentifierMap));
1022 if (DT.isCompositeType()) {
1023 DICompositeType DCT(DT);
1024 processType(DCT.getTypeDerivedFrom().resolve(TypeIdentifierMap));
1025 if (DT.isSubroutineType()) {
1026 DITypeArray DTA = DISubroutineType(DT).getTypeArray();
1027 for (unsigned i = 0, e = DTA.getNumElements(); i != e; ++i)
1028 processType(DTA.getElement(i).resolve(TypeIdentifierMap));
1031 DIArray DA = DCT.getElements();
1032 for (unsigned i = 0, e = DA.getNumElements(); i != e; ++i) {
1033 DIDescriptor D = DA.getElement(i);
1035 processType(DIType(D));
1036 else if (D.isSubprogram())
1037 processSubprogram(DISubprogram(D));
1039 } else if (DT.isDerivedType()) {
1040 DIDerivedType DDT(DT);
1041 processType(DDT.getTypeDerivedFrom().resolve(TypeIdentifierMap));
1045 void DebugInfoFinder::processScope(DIScope Scope) {
1046 if (Scope.isType()) {
1051 if (Scope.isCompileUnit()) {
1052 addCompileUnit(DICompileUnit(Scope));
1055 if (Scope.isSubprogram()) {
1056 processSubprogram(DISubprogram(Scope));
1059 if (!addScope(Scope))
1061 if (Scope.isLexicalBlock()) {
1062 DILexicalBlock LB(Scope);
1063 processScope(LB.getContext());
1064 } else if (Scope.isLexicalBlockFile()) {
1065 DILexicalBlockFile LBF = DILexicalBlockFile(Scope);
1066 processScope(LBF.getScope());
1067 } else if (Scope.isNameSpace()) {
1068 DINameSpace NS(Scope);
1069 processScope(NS.getContext());
1073 void DebugInfoFinder::processSubprogram(DISubprogram SP) {
1074 if (!addSubprogram(SP))
1076 processScope(SP.getContext().resolve(TypeIdentifierMap));
1077 processType(SP.getType());
1078 DIArray TParams = SP.getTemplateParams();
1079 for (unsigned I = 0, E = TParams.getNumElements(); I != E; ++I) {
1080 DIDescriptor Element = TParams.getElement(I);
1081 if (Element.isTemplateTypeParameter()) {
1082 DITemplateTypeParameter TType(Element);
1083 processScope(TType.getContext().resolve(TypeIdentifierMap));
1084 processType(TType.getType().resolve(TypeIdentifierMap));
1085 } else if (Element.isTemplateValueParameter()) {
1086 DITemplateValueParameter TVal(Element);
1087 processScope(TVal.getContext().resolve(TypeIdentifierMap));
1088 processType(TVal.getType().resolve(TypeIdentifierMap));
1093 void DebugInfoFinder::processDeclare(const Module &M,
1094 const DbgDeclareInst *DDI) {
1095 MDNode *N = dyn_cast<MDNode>(DDI->getVariable());
1098 InitializeTypeMap(M);
1101 if (!DV.isVariable())
1104 if (!NodesSeen.insert(DV).second)
1106 processScope(DIVariable(N).getContext());
1107 processType(DIVariable(N).getType().resolve(TypeIdentifierMap));
1110 void DebugInfoFinder::processValue(const Module &M, const DbgValueInst *DVI) {
1111 MDNode *N = dyn_cast<MDNode>(DVI->getVariable());
1114 InitializeTypeMap(M);
1117 if (!DV.isVariable())
1120 if (!NodesSeen.insert(DV).second)
1122 processScope(DIVariable(N).getContext());
1123 processType(DIVariable(N).getType().resolve(TypeIdentifierMap));
1126 bool DebugInfoFinder::addType(DIType DT) {
1130 if (!NodesSeen.insert(DT).second)
1137 bool DebugInfoFinder::addCompileUnit(DICompileUnit CU) {
1140 if (!NodesSeen.insert(CU).second)
1147 bool DebugInfoFinder::addGlobalVariable(DIGlobalVariable DIG) {
1151 if (!NodesSeen.insert(DIG).second)
1158 bool DebugInfoFinder::addSubprogram(DISubprogram SP) {
1162 if (!NodesSeen.insert(SP).second)
1169 bool DebugInfoFinder::addScope(DIScope Scope) {
1172 // FIXME: Ocaml binding generates a scope with no content, we treat it
1174 if (Scope->getNumOperands() == 0)
1176 if (!NodesSeen.insert(Scope).second)
1178 Scopes.push_back(Scope);
1182 //===----------------------------------------------------------------------===//
1183 // DIDescriptor: dump routines for all descriptors.
1184 //===----------------------------------------------------------------------===//
1186 void DIDescriptor::dump() const {
1191 void DIDescriptor::print(raw_ostream &OS) const {
1195 if (const char *Tag = dwarf::TagString(getTag()))
1196 OS << "[ " << Tag << " ]";
1198 if (this->isSubrange()) {
1199 DISubrange(DbgNode).printInternal(OS);
1200 } else if (this->isCompileUnit()) {
1201 DICompileUnit(DbgNode).printInternal(OS);
1202 } else if (this->isFile()) {
1203 DIFile(DbgNode).printInternal(OS);
1204 } else if (this->isEnumerator()) {
1205 DIEnumerator(DbgNode).printInternal(OS);
1206 } else if (this->isBasicType()) {
1207 DIType(DbgNode).printInternal(OS);
1208 } else if (this->isDerivedType()) {
1209 DIDerivedType(DbgNode).printInternal(OS);
1210 } else if (this->isCompositeType()) {
1211 DICompositeType(DbgNode).printInternal(OS);
1212 } else if (this->isSubprogram()) {
1213 DISubprogram(DbgNode).printInternal(OS);
1214 } else if (this->isGlobalVariable()) {
1215 DIGlobalVariable(DbgNode).printInternal(OS);
1216 } else if (this->isVariable()) {
1217 DIVariable(DbgNode).printInternal(OS);
1218 } else if (this->isObjCProperty()) {
1219 DIObjCProperty(DbgNode).printInternal(OS);
1220 } else if (this->isNameSpace()) {
1221 DINameSpace(DbgNode).printInternal(OS);
1222 } else if (this->isScope()) {
1223 DIScope(DbgNode).printInternal(OS);
1224 } else if (this->isExpression()) {
1225 DIExpression(DbgNode).printInternal(OS);
1229 void DISubrange::printInternal(raw_ostream &OS) const {
1230 int64_t Count = getCount();
1232 OS << " [" << getLo() << ", " << Count - 1 << ']';
1234 OS << " [unbounded]";
1237 void DIScope::printInternal(raw_ostream &OS) const {
1238 OS << " [" << getDirectory() << "/" << getFilename() << ']';
1241 void DICompileUnit::printInternal(raw_ostream &OS) const {
1242 DIScope::printInternal(OS);
1244 unsigned Lang = getLanguage();
1245 if (const char *LangStr = dwarf::LanguageString(Lang))
1248 (OS << "lang 0x").write_hex(Lang);
1252 void DIEnumerator::printInternal(raw_ostream &OS) const {
1253 OS << " [" << getName() << " :: " << getEnumValue() << ']';
1256 void DIType::printInternal(raw_ostream &OS) const {
1260 StringRef Res = getName();
1262 OS << " [" << Res << "]";
1264 // TODO: Print context?
1266 OS << " [line " << getLineNumber() << ", size " << getSizeInBits()
1267 << ", align " << getAlignInBits() << ", offset " << getOffsetInBits();
1269 if (const char *Enc =
1270 dwarf::AttributeEncodingString(DIBasicType(DbgNode).getEncoding()))
1271 OS << ", enc " << Enc;
1276 else if (isProtected())
1277 OS << " [protected]";
1278 else if (isPublic())
1282 OS << " [artificial]";
1284 if (isForwardDecl())
1286 else if (getTag() == dwarf::DW_TAG_structure_type ||
1287 getTag() == dwarf::DW_TAG_union_type ||
1288 getTag() == dwarf::DW_TAG_enumeration_type ||
1289 getTag() == dwarf::DW_TAG_class_type)
1293 if (isStaticMember())
1296 if (isLValueReference())
1297 OS << " [reference]";
1299 if (isRValueReference())
1300 OS << " [rvalue reference]";
1303 void DIDerivedType::printInternal(raw_ostream &OS) const {
1304 DIType::printInternal(OS);
1305 OS << " [from " << getTypeDerivedFrom().getName() << ']';
1308 void DICompositeType::printInternal(raw_ostream &OS) const {
1309 DIType::printInternal(OS);
1310 DIArray A = getElements();
1311 OS << " [" << A.getNumElements() << " elements]";
1314 void DINameSpace::printInternal(raw_ostream &OS) const {
1315 StringRef Name = getName();
1317 OS << " [" << Name << ']';
1319 OS << " [line " << getLineNumber() << ']';
1322 void DISubprogram::printInternal(raw_ostream &OS) const {
1323 // TODO : Print context
1324 OS << " [line " << getLineNumber() << ']';
1326 if (isLocalToUnit())
1332 if (getScopeLineNumber() != getLineNumber())
1333 OS << " [scope " << getScopeLineNumber() << "]";
1337 else if (isProtected())
1338 OS << " [protected]";
1339 else if (isPublic())
1342 if (isLValueReference())
1343 OS << " [reference]";
1345 if (isRValueReference())
1346 OS << " [rvalue reference]";
1348 StringRef Res = getName();
1350 OS << " [" << Res << ']';
1353 void DIGlobalVariable::printInternal(raw_ostream &OS) const {
1354 StringRef Res = getName();
1356 OS << " [" << Res << ']';
1358 OS << " [line " << getLineNumber() << ']';
1360 // TODO : Print context
1362 if (isLocalToUnit())
1369 void DIVariable::printInternal(raw_ostream &OS) const {
1370 StringRef Res = getName();
1372 OS << " [" << Res << ']';
1374 OS << " [line " << getLineNumber() << ']';
1377 void DIExpression::printInternal(raw_ostream &OS) const {
1378 for (unsigned I = 0; I < getNumElements(); ++I) {
1379 uint64_t OpCode = getElement(I);
1380 OS << " [" << OperationEncodingString(OpCode);
1383 OS << " " << getElement(++I);
1387 unsigned Offset = getElement(++I);
1388 unsigned Size = getElement(++I);
1389 OS << " offset=" << Offset << ", size=" << Size;
1396 // Else bail out early. This may be a line table entry.
1404 void DIObjCProperty::printInternal(raw_ostream &OS) const {
1405 StringRef Name = getObjCPropertyName();
1407 OS << " [" << Name << ']';
1409 OS << " [line " << getLineNumber() << ", properties " << getUnsignedField(6)
1413 static void printDebugLoc(DebugLoc DL, raw_ostream &CommentOS,
1414 const LLVMContext &Ctx) {
1415 if (!DL.isUnknown()) { // Print source line info.
1416 DIScope Scope(DL.getScope(Ctx));
1417 assert(Scope.isScope() && "Scope of a DebugLoc should be a DIScope.");
1418 // Omit the directory, because it's likely to be long and uninteresting.
1419 CommentOS << Scope.getFilename();
1420 CommentOS << ':' << DL.getLine();
1421 if (DL.getCol() != 0)
1422 CommentOS << ':' << DL.getCol();
1423 DebugLoc InlinedAtDL = DebugLoc::getFromDILocation(DL.getInlinedAt(Ctx));
1424 if (!InlinedAtDL.isUnknown()) {
1425 CommentOS << " @[ ";
1426 printDebugLoc(InlinedAtDL, CommentOS, Ctx);
1432 void DIVariable::printExtendedName(raw_ostream &OS) const {
1433 const LLVMContext &Ctx = DbgNode->getContext();
1434 StringRef Res = getName();
1436 OS << Res << "," << getLineNumber();
1437 if (MDNode *InlinedAt = getInlinedAt()) {
1438 DebugLoc InlinedAtDL = DebugLoc::getFromDILocation(InlinedAt);
1439 if (!InlinedAtDL.isUnknown()) {
1441 printDebugLoc(InlinedAtDL, OS, Ctx);
1447 template <> DIRef<DIScope>::DIRef(const Metadata *V) : Val(V) {
1448 assert(isScopeRef(V) && "DIScopeRef should be a MDString or MDNode");
1450 template <> DIRef<DIType>::DIRef(const Metadata *V) : Val(V) {
1451 assert(isTypeRef(V) && "DITypeRef should be a MDString or MDNode");
1455 DIScopeRef DIDescriptor::getFieldAs<DIScopeRef>(unsigned Elt) const {
1456 return DIScopeRef(cast_or_null<Metadata>(getField(DbgNode, Elt)));
1458 template <> DITypeRef DIDescriptor::getFieldAs<DITypeRef>(unsigned Elt) const {
1459 return DITypeRef(cast_or_null<Metadata>(getField(DbgNode, Elt)));
1462 bool llvm::StripDebugInfo(Module &M) {
1463 bool Changed = false;
1465 // Remove all of the calls to the debugger intrinsics, and remove them from
1467 if (Function *Declare = M.getFunction("llvm.dbg.declare")) {
1468 while (!Declare->use_empty()) {
1469 CallInst *CI = cast<CallInst>(Declare->user_back());
1470 CI->eraseFromParent();
1472 Declare->eraseFromParent();
1476 if (Function *DbgVal = M.getFunction("llvm.dbg.value")) {
1477 while (!DbgVal->use_empty()) {
1478 CallInst *CI = cast<CallInst>(DbgVal->user_back());
1479 CI->eraseFromParent();
1481 DbgVal->eraseFromParent();
1485 for (Module::named_metadata_iterator NMI = M.named_metadata_begin(),
1486 NME = M.named_metadata_end(); NMI != NME;) {
1487 NamedMDNode *NMD = NMI;
1489 if (NMD->getName().startswith("llvm.dbg.")) {
1490 NMD->eraseFromParent();
1495 for (Module::iterator MI = M.begin(), ME = M.end(); MI != ME; ++MI)
1496 for (Function::iterator FI = MI->begin(), FE = MI->end(); FI != FE;
1498 for (BasicBlock::iterator BI = FI->begin(), BE = FI->end(); BI != BE;
1500 if (!BI->getDebugLoc().isUnknown()) {
1502 BI->setDebugLoc(DebugLoc());
1509 unsigned llvm::getDebugMetadataVersionFromModule(const Module &M) {
1510 if (auto *Val = mdconst::extract_or_null<ConstantInt>(
1511 M.getModuleFlag("Debug Info Version")))
1512 return Val->getZExtValue();
1516 llvm::DenseMap<const llvm::Function *, llvm::DISubprogram>
1517 llvm::makeSubprogramMap(const Module &M) {
1518 DenseMap<const Function *, DISubprogram> R;
1520 NamedMDNode *CU_Nodes = M.getNamedMetadata("llvm.dbg.cu");
1524 for (MDNode *N : CU_Nodes->operands()) {
1525 DICompileUnit CUNode(N);
1526 DIArray SPs = CUNode.getSubprograms();
1527 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i) {
1528 DISubprogram SP(SPs.getElement(i));
1529 if (Function *F = SP.getFunction())
1530 R.insert(std::make_pair(F, SP));