1 //===- DebugInfo.h - Debug Information Helpers ------------------*- C++ -*-===//
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 defines a bunch of datatypes that are useful for creating and
11 // walking debug info in LLVM IR form. They essentially provide wrappers around
12 // the information in the global variables that's needed when constructing the
15 //===----------------------------------------------------------------------===//
17 #ifndef LLVM_IR_DEBUGINFO_H
18 #define LLVM_IR_DEBUGINFO_H
20 #include "llvm/ADT/DenseMap.h"
21 #include "llvm/ADT/SmallPtrSet.h"
22 #include "llvm/ADT/SmallVector.h"
23 #include "llvm/ADT/StringRef.h"
24 #include "llvm/ADT/iterator_range.h"
25 #include "llvm/IR/DebugInfoMetadata.h"
26 #include "llvm/Support/Casting.h"
27 #include "llvm/Support/Dwarf.h"
28 #include "llvm/Support/ErrorHandling.h"
52 class DILexicalBlockFile;
58 /// \brief Maps from type identifier to the actual MDNode.
59 typedef DenseMap<const MDString *, MDNode *> DITypeIdentifierMap;
61 class DIHeaderFieldIterator
62 : public std::iterator<std::input_iterator_tag, StringRef, std::ptrdiff_t,
63 const StringRef *, StringRef> {
68 DIHeaderFieldIterator() {}
69 explicit DIHeaderFieldIterator(StringRef Header)
70 : Header(Header), Current(Header.slice(0, Header.find('\0'))) {}
71 StringRef operator*() const { return Current; }
72 const StringRef *operator->() const { return &Current; }
73 DIHeaderFieldIterator &operator++() {
77 DIHeaderFieldIterator operator++(int) {
78 DIHeaderFieldIterator X(*this);
82 bool operator==(const DIHeaderFieldIterator &X) const {
83 return Current.data() == X.Current.data();
85 bool operator!=(const DIHeaderFieldIterator &X) const {
89 StringRef getHeader() const { return Header; }
90 StringRef getCurrent() const { return Current; }
91 StringRef getPrefix() const {
92 if (Current.begin() == Header.begin())
94 return Header.slice(0, Current.begin() - Header.begin() - 1);
96 StringRef getSuffix() const {
97 if (Current.end() == Header.end())
99 return Header.slice(Current.end() - Header.begin() + 1, StringRef::npos);
102 /// \brief Get the current field as a number.
104 /// Convert the current field into a number. Return \c 0 on error.
105 template <class T> T getNumber() const {
107 if (getCurrent().getAsInteger(0, Int))
114 assert(Current.data() != nullptr && "Cannot increment past the end");
115 StringRef Suffix = getSuffix();
116 Current = Suffix.slice(0, Suffix.find('\0'));
120 /// \brief A thin wraper around MDNode to access encoded debug info.
122 /// This should not be stored in a container, because the underlying MDNode may
123 /// change in certain situations.
125 // Befriends DIRef so DIRef can befriend the protected member
126 // function: getFieldAs<DIRef>.
127 template <typename T> friend class DIRef;
130 /// \brief Accessibility flags.
132 /// The three accessibility flags are mutually exclusive and rolled together
133 /// in the first two bits.
135 FlagAccessibility = 1 << 0 | 1 << 1,
140 FlagFwdDecl = 1 << 2,
141 FlagAppleBlock = 1 << 3,
142 FlagBlockByrefStruct = 1 << 4,
143 FlagVirtual = 1 << 5,
144 FlagArtificial = 1 << 6,
145 FlagExplicit = 1 << 7,
146 FlagPrototyped = 1 << 8,
147 FlagObjcClassComplete = 1 << 9,
148 FlagObjectPointer = 1 << 10,
149 FlagVector = 1 << 11,
150 FlagStaticMember = 1 << 12,
151 FlagLValueReference = 1 << 13,
152 FlagRValueReference = 1 << 14
156 const MDNode *DbgNode;
158 StringRef getStringField(unsigned Elt) const;
159 unsigned getUnsignedField(unsigned Elt) const {
160 return (unsigned)getUInt64Field(Elt);
162 uint64_t getUInt64Field(unsigned Elt) const;
163 int64_t getInt64Field(unsigned Elt) const;
164 DIDescriptor getDescriptorField(unsigned Elt) const;
166 template <typename DescTy> DescTy getFieldAs(unsigned Elt) const {
167 return DescTy(getDescriptorField(Elt));
170 GlobalVariable *getGlobalVariableField(unsigned Elt) const;
171 Constant *getConstantField(unsigned Elt) const;
172 Function *getFunctionField(unsigned Elt) const;
173 void replaceFunctionField(unsigned Elt, Function *F);
176 explicit DIDescriptor(const MDNode *N = nullptr) : DbgNode(N) {}
180 MDNode *get() const { return const_cast<MDNode *>(DbgNode); }
181 operator MDNode *() const { return get(); }
182 MDNode *operator->() const { return get(); }
184 // An explicit operator bool so that we can do testing of DI values
186 // FIXME: This operator bool isn't actually protecting anything at the
187 // moment due to the conversion operator above making DIDescriptor nodes
188 // implicitly convertable to bool.
189 explicit operator bool() const { return DbgNode != nullptr; }
191 bool operator==(DIDescriptor Other) const { return DbgNode == Other.DbgNode; }
192 bool operator!=(DIDescriptor Other) const { return !operator==(Other); }
194 StringRef getHeader() const { return getStringField(0); }
196 size_t getNumHeaderFields() const {
197 return std::distance(DIHeaderFieldIterator(getHeader()),
198 DIHeaderFieldIterator());
201 DIHeaderFieldIterator header_begin() const {
202 return DIHeaderFieldIterator(getHeader());
204 DIHeaderFieldIterator header_end() const { return DIHeaderFieldIterator(); }
206 DIHeaderFieldIterator getHeaderIterator(unsigned Index) const {
207 // Since callers expect an empty string for out-of-range accesses, we can't
208 // use std::advance() here.
209 for (auto I = header_begin(), E = header_end(); I != E; ++I, --Index)
215 StringRef getHeaderField(unsigned Index) const {
216 return *getHeaderIterator(Index);
219 template <class T> T getHeaderFieldAs(unsigned Index) const {
220 return getHeaderIterator(Index).getNumber<T>();
223 uint16_t getTag() const { return getHeaderFieldAs<uint16_t>(0); }
225 bool isDerivedType() const;
226 bool isCompositeType() const;
227 bool isSubroutineType() const;
228 bool isBasicType() const;
229 bool isVariable() const;
230 bool isSubprogram() const;
231 bool isGlobalVariable() const;
232 bool isScope() const;
234 bool isCompileUnit() const;
235 bool isNameSpace() const;
236 bool isLexicalBlockFile() const;
237 bool isLexicalBlock() const;
238 bool isSubrange() const;
239 bool isEnumerator() const;
241 bool isTemplateTypeParameter() const;
242 bool isTemplateValueParameter() const;
243 bool isObjCProperty() const;
244 bool isImportedEntity() const;
245 bool isExpression() const;
247 void print(raw_ostream &OS) const;
250 /// \brief Replace all uses of debug info referenced by this descriptor.
251 void replaceAllUsesWith(LLVMContext &VMContext, DIDescriptor D);
252 void replaceAllUsesWith(MDNode *D);
255 /// \brief This is used to represent ranges, for array bounds.
256 class DISubrange : public DIDescriptor {
257 friend class DIDescriptor;
258 void printInternal(raw_ostream &OS) const;
261 explicit DISubrange(const MDNode *N = nullptr) : DIDescriptor(N) {}
263 int64_t getLo() const { return getHeaderFieldAs<int64_t>(1); }
264 int64_t getCount() const { return getHeaderFieldAs<int64_t>(2); }
268 /// \brief This descriptor holds an array of nodes with type T.
269 template <typename T> class DITypedArray : public DIDescriptor {
271 explicit DITypedArray(const MDNode *N = nullptr) : DIDescriptor(N) {}
272 unsigned getNumElements() const {
273 return DbgNode ? DbgNode->getNumOperands() : 0;
275 T getElement(unsigned Idx) const { return getFieldAs<T>(Idx); }
278 typedef DITypedArray<DIDescriptor> DIArray;
280 /// \brief A wrapper for an enumerator (e.g. X and Y in 'enum {X,Y}').
282 /// FIXME: it seems strange that this doesn't have either a reference to the
283 /// type/precision or a file/line pair for location info.
284 class DIEnumerator : public DIDescriptor {
285 friend class DIDescriptor;
286 void printInternal(raw_ostream &OS) const;
289 explicit DIEnumerator(const MDNode *N = nullptr) : DIDescriptor(N) {}
291 StringRef getName() const { return getHeaderField(1); }
292 int64_t getEnumValue() const { return getHeaderFieldAs<int64_t>(2); }
296 template <typename T> class DIRef;
297 typedef DIRef<DIDescriptor> DIDescriptorRef;
298 typedef DIRef<DIScope> DIScopeRef;
299 typedef DIRef<DIType> DITypeRef;
300 typedef DITypedArray<DITypeRef> DITypeArray;
302 /// \brief A base class for various scopes.
304 /// Although, implementation-wise, DIScope is the parent class of most
305 /// other DIxxx classes, including DIType and its descendants, most of
306 /// DIScope's descendants are not a substitutable subtype of
307 /// DIScope. The DIDescriptor::isScope() method only is true for
308 /// DIScopes that are scopes in the strict lexical scope sense
309 /// (DICompileUnit, DISubprogram, etc.), but not for, e.g., a DIType.
310 class DIScope : public DIDescriptor {
312 friend class DIDescriptor;
313 void printInternal(raw_ostream &OS) const;
316 explicit DIScope(const MDNode *N = nullptr) : DIDescriptor(N) {}
318 /// \brief Get the parent scope.
320 /// Gets the parent scope for this scope node or returns a default
321 /// constructed scope.
322 DIScopeRef getContext() const;
323 /// \brief Get the scope name.
325 /// If the scope node has a name, return that, else return an empty string.
326 StringRef getName() const;
327 StringRef getFilename() const;
328 StringRef getDirectory() const;
330 /// \brief Generate a reference to this DIScope.
332 /// Uses the type identifier instead of the actual MDNode if possible, to
333 /// help type uniquing.
334 DIScopeRef getRef() const;
337 /// \brief Represents reference to a DIDescriptor.
339 /// Abstracts over direct and identifier-based metadata references.
340 template <typename T> class DIRef {
341 template <typename DescTy>
342 friend DescTy DIDescriptor::getFieldAs(unsigned Elt) const;
343 friend DIScopeRef DIScope::getContext() const;
344 friend DIScopeRef DIScope::getRef() const;
347 /// \brief Val can be either a MDNode or a MDString.
349 /// In the latter, MDString specifies the type identifier.
351 explicit DIRef(const Metadata *V);
354 T resolve(const DITypeIdentifierMap &Map) const;
355 StringRef getName() const;
356 operator Metadata *() const { return const_cast<Metadata *>(Val); }
359 template <typename T>
360 T DIRef<T>::resolve(const DITypeIdentifierMap &Map) const {
364 if (const MDNode *MD = dyn_cast<MDNode>(Val))
367 const MDString *MS = cast<MDString>(Val);
368 // Find the corresponding MDNode.
369 DITypeIdentifierMap::const_iterator Iter = Map.find(MS);
370 assert(Iter != Map.end() && "Identifier not in the type map?");
371 assert(DIDescriptor(Iter->second).isType() &&
372 "MDNode in DITypeIdentifierMap should be a DIType.");
373 return T(Iter->second);
376 template <typename T> StringRef DIRef<T>::getName() const {
380 if (const MDNode *MD = dyn_cast<MDNode>(Val))
381 return T(MD).getName();
383 const MDString *MS = cast<MDString>(Val);
384 return MS->getString();
387 /// \brief Handle fields that are references to DIDescriptors.
389 DIDescriptorRef DIDescriptor::getFieldAs<DIDescriptorRef>(unsigned Elt) const;
390 /// \brief Specialize DIRef constructor for DIDescriptorRef.
391 template <> DIRef<DIDescriptor>::DIRef(const Metadata *V);
393 /// \brief Handle fields that are references to DIScopes.
394 template <> DIScopeRef DIDescriptor::getFieldAs<DIScopeRef>(unsigned Elt) const;
395 /// \brief Specialize DIRef constructor for DIScopeRef.
396 template <> DIRef<DIScope>::DIRef(const Metadata *V);
398 /// \brief Handle fields that are references to DITypes.
399 template <> DITypeRef DIDescriptor::getFieldAs<DITypeRef>(unsigned Elt) const;
400 /// \brief Specialize DIRef constructor for DITypeRef.
401 template <> DIRef<DIType>::DIRef(const Metadata *V);
403 /// \brief This is a wrapper for a type.
405 /// FIXME: Types should be factored much better so that CV qualifiers and
406 /// others do not require a huge and empty descriptor full of zeros.
407 class DIType : public DIScope {
409 friend class DIDescriptor;
410 void printInternal(raw_ostream &OS) const;
413 explicit DIType(const MDNode *N = nullptr) : DIScope(N) {}
414 operator DITypeRef() const {
416 "constructing DITypeRef from an MDNode that is not a type");
417 return DITypeRef(&*getRef());
422 DIScopeRef getContext() const { return getFieldAs<DIScopeRef>(2); }
423 StringRef getName() const { return getHeaderField(1); }
424 unsigned getLineNumber() const { return getHeaderFieldAs<unsigned>(2); }
425 uint64_t getSizeInBits() const { return getHeaderFieldAs<unsigned>(3); }
426 uint64_t getAlignInBits() const { return getHeaderFieldAs<unsigned>(4); }
427 // FIXME: Offset is only used for DW_TAG_member nodes. Making every type
428 // carry this is just plain insane.
429 uint64_t getOffsetInBits() const { return getHeaderFieldAs<unsigned>(5); }
430 unsigned getFlags() const { return getHeaderFieldAs<unsigned>(6); }
431 bool isPrivate() const {
432 return (getFlags() & FlagAccessibility) == FlagPrivate;
434 bool isProtected() const {
435 return (getFlags() & FlagAccessibility) == FlagProtected;
437 bool isPublic() const {
438 return (getFlags() & FlagAccessibility) == FlagPublic;
440 bool isForwardDecl() const { return (getFlags() & FlagFwdDecl) != 0; }
441 bool isAppleBlockExtension() const {
442 return (getFlags() & FlagAppleBlock) != 0;
444 bool isBlockByrefStruct() const {
445 return (getFlags() & FlagBlockByrefStruct) != 0;
447 bool isVirtual() const { return (getFlags() & FlagVirtual) != 0; }
448 bool isArtificial() const { return (getFlags() & FlagArtificial) != 0; }
449 bool isObjectPointer() const { return (getFlags() & FlagObjectPointer) != 0; }
450 bool isObjcClassComplete() const {
451 return (getFlags() & FlagObjcClassComplete) != 0;
453 bool isVector() const { return (getFlags() & FlagVector) != 0; }
454 bool isStaticMember() const { return (getFlags() & FlagStaticMember) != 0; }
455 bool isLValueReference() const {
456 return (getFlags() & FlagLValueReference) != 0;
458 bool isRValueReference() const {
459 return (getFlags() & FlagRValueReference) != 0;
461 bool isValid() const { return DbgNode && isType(); }
464 /// \brief A basic type, like 'int' or 'float'.
465 class DIBasicType : public DIType {
467 explicit DIBasicType(const MDNode *N = nullptr) : DIType(N) {}
469 unsigned getEncoding() const { return getHeaderFieldAs<unsigned>(7); }
474 /// \brief A simple derived type
476 /// Like a const qualified type, a typedef, a pointer or reference, et cetera.
477 /// Or, a data member of a class/struct/union.
478 class DIDerivedType : public DIType {
479 friend class DIDescriptor;
480 void printInternal(raw_ostream &OS) const;
483 explicit DIDerivedType(const MDNode *N = nullptr) : DIType(N) {}
485 DITypeRef getTypeDerivedFrom() const { return getFieldAs<DITypeRef>(3); }
487 /// \brief Return property node, if this ivar is associated with one.
488 MDNode *getObjCProperty() const;
490 DITypeRef getClassType() const {
491 assert(getTag() == dwarf::DW_TAG_ptr_to_member_type);
492 return getFieldAs<DITypeRef>(4);
495 Constant *getConstant() const {
496 assert((getTag() == dwarf::DW_TAG_member) && isStaticMember());
497 return getConstantField(4);
503 /// \brief Types that refer to multiple other types.
505 /// This descriptor holds a type that can refer to multiple other types, like a
506 /// function or struct.
508 /// DICompositeType is derived from DIDerivedType because some
509 /// composite types (such as enums) can be derived from basic types
510 // FIXME: Make this derive from DIType directly & just store the
511 // base type in a single DIType field.
512 class DICompositeType : public DIDerivedType {
513 friend class DIBuilder;
514 friend class DIDescriptor;
515 void printInternal(raw_ostream &OS) const;
517 /// \brief Set the array of member DITypes.
518 void setArraysHelper(MDNode *Elements, MDNode *TParams);
521 explicit DICompositeType(const MDNode *N = nullptr) : DIDerivedType(N) {}
523 DIArray getElements() const {
524 assert(!isSubroutineType() && "no elements for DISubroutineType");
525 return getFieldAs<DIArray>(4);
529 template <typename T>
530 void setArrays(DITypedArray<T> Elements, DIArray TParams = DIArray()) {
532 (!TParams || DbgNode->getNumOperands() == 8) &&
533 "If you're setting the template parameters this should include a slot "
535 setArraysHelper(Elements, TParams);
539 unsigned getRunTimeLang() const { return getHeaderFieldAs<unsigned>(7); }
540 DITypeRef getContainingType() const { return getFieldAs<DITypeRef>(5); }
543 /// \brief Set the containing type.
544 void setContainingType(DICompositeType ContainingType);
547 DIArray getTemplateParams() const { return getFieldAs<DIArray>(6); }
548 MDString *getIdentifier() const;
553 class DISubroutineType : public DICompositeType {
555 explicit DISubroutineType(const MDNode *N = nullptr) : DICompositeType(N) {}
556 DITypedArray<DITypeRef> getTypeArray() const {
557 return getFieldAs<DITypedArray<DITypeRef>>(4);
561 /// \brief This is a wrapper for a file.
562 class DIFile : public DIScope {
563 friend class DIDescriptor;
566 explicit DIFile(const MDNode *N = nullptr) : DIScope(N) {}
568 /// \brief Retrieve the MDNode for the directory/file pair.
569 MDNode *getFileNode() const;
573 /// \brief A wrapper for a compile unit.
574 class DICompileUnit : public DIScope {
575 friend class DIDescriptor;
576 void printInternal(raw_ostream &OS) const;
579 explicit DICompileUnit(const MDNode *N = nullptr) : DIScope(N) {}
581 dwarf::SourceLanguage getLanguage() const {
582 return static_cast<dwarf::SourceLanguage>(getHeaderFieldAs<unsigned>(1));
584 StringRef getProducer() const { return getHeaderField(2); }
586 bool isOptimized() const { return getHeaderFieldAs<bool>(3) != 0; }
587 StringRef getFlags() const { return getHeaderField(4); }
588 unsigned getRunTimeVersion() const { return getHeaderFieldAs<unsigned>(5); }
590 DIArray getEnumTypes() const;
591 DIArray getRetainedTypes() const;
592 DIArray getSubprograms() const;
593 DIArray getGlobalVariables() const;
594 DIArray getImportedEntities() const;
596 void replaceSubprograms(DIArray Subprograms);
597 void replaceGlobalVariables(DIArray GlobalVariables);
599 StringRef getSplitDebugFilename() const { return getHeaderField(6); }
600 unsigned getEmissionKind() const { return getHeaderFieldAs<unsigned>(7); }
605 /// \brief This is a wrapper for a subprogram (e.g. a function).
606 class DISubprogram : public DIScope {
607 friend class DIDescriptor;
608 void printInternal(raw_ostream &OS) const;
611 explicit DISubprogram(const MDNode *N = nullptr) : DIScope(N) {}
613 StringRef getName() const { return getHeaderField(1); }
614 StringRef getDisplayName() const { return getHeaderField(2); }
615 StringRef getLinkageName() const { return getHeaderField(3); }
616 unsigned getLineNumber() const { return getHeaderFieldAs<unsigned>(4); }
618 /// \brief Check if this is local (like 'static' in C).
619 unsigned isLocalToUnit() const { return getHeaderFieldAs<unsigned>(5); }
620 unsigned isDefinition() const { return getHeaderFieldAs<unsigned>(6); }
622 unsigned getVirtuality() const { return getHeaderFieldAs<unsigned>(7); }
623 unsigned getVirtualIndex() const { return getHeaderFieldAs<unsigned>(8); }
625 unsigned getFlags() const { return getHeaderFieldAs<unsigned>(9); }
627 unsigned isOptimized() const { return getHeaderFieldAs<bool>(10); }
629 /// \brief Get the beginning of the scope of the function (not the name).
630 unsigned getScopeLineNumber() const { return getHeaderFieldAs<unsigned>(11); }
632 DIScopeRef getContext() const { return getFieldAs<DIScopeRef>(2); }
633 DISubroutineType getType() const { return getFieldAs<DISubroutineType>(3); }
635 DITypeRef getContainingType() const { return getFieldAs<DITypeRef>(4); }
639 /// \brief Check if this provides debugging information for the function F.
640 bool describes(const Function *F);
642 Function *getFunction() const { return getFunctionField(5); }
643 void replaceFunction(Function *F) { replaceFunctionField(5, F); }
644 DIArray getTemplateParams() const { return getFieldAs<DIArray>(6); }
645 DISubprogram getFunctionDeclaration() const {
646 return getFieldAs<DISubprogram>(7);
648 MDNode *getVariablesNodes() const;
649 DIArray getVariables() const;
651 unsigned isArtificial() const { return (getFlags() & FlagArtificial) != 0; }
652 /// \brief Check for the "private" access specifier.
653 bool isPrivate() const {
654 return (getFlags() & FlagAccessibility) == FlagPrivate;
656 /// \brief Check for the "protected" access specifier.
657 bool isProtected() const {
658 return (getFlags() & FlagAccessibility) == FlagProtected;
660 /// \brief Check for the "public" access specifier.
661 bool isPublic() const {
662 return (getFlags() & FlagAccessibility) == FlagPublic;
664 /// \brief Check for "explicit".
665 bool isExplicit() const { return (getFlags() & FlagExplicit) != 0; }
666 /// \brief Check if this is prototyped.
667 bool isPrototyped() const { return (getFlags() & FlagPrototyped) != 0; }
669 /// \brief Check if this is reference-qualified.
671 /// Return true if this subprogram is a C++11 reference-qualified non-static
672 /// member function (void foo() &).
673 unsigned isLValueReference() const {
674 return (getFlags() & FlagLValueReference) != 0;
677 /// \brief Check if this is rvalue-reference-qualified.
679 /// Return true if this subprogram is a C++11 rvalue-reference-qualified
680 /// non-static member function (void foo() &&).
681 unsigned isRValueReference() const {
682 return (getFlags() & FlagRValueReference) != 0;
686 /// \brief This is a wrapper for a lexical block.
687 class DILexicalBlock : public DIScope {
689 explicit DILexicalBlock(const MDNode *N = nullptr) : DIScope(N) {}
690 DIScope getContext() const { return getFieldAs<DIScope>(2); }
691 unsigned getLineNumber() const { return getHeaderFieldAs<unsigned>(1); }
692 unsigned getColumnNumber() const { return getHeaderFieldAs<unsigned>(2); }
696 /// \brief This is a wrapper for a lexical block with a filename change.
697 class DILexicalBlockFile : public DIScope {
699 explicit DILexicalBlockFile(const MDNode *N = nullptr) : DIScope(N) {}
700 DIScope getContext() const {
701 // FIXME: This logic is horrible. getScope() returns a DILexicalBlock, but
702 // then we check if it's a subprogram? WHAT?!?
703 if (getScope().isSubprogram())
705 return getScope().getContext();
707 unsigned getLineNumber() const { return getScope().getLineNumber(); }
708 unsigned getColumnNumber() const { return getScope().getColumnNumber(); }
709 DILexicalBlock getScope() const { return getFieldAs<DILexicalBlock>(2); }
710 unsigned getDiscriminator() const { return getHeaderFieldAs<unsigned>(1); }
714 /// \brief A wrapper for a C++ style name space.
715 class DINameSpace : public DIScope {
716 friend class DIDescriptor;
717 void printInternal(raw_ostream &OS) const;
720 explicit DINameSpace(const MDNode *N = nullptr) : DIScope(N) {}
721 StringRef getName() const { return getHeaderField(1); }
722 unsigned getLineNumber() const { return getHeaderFieldAs<unsigned>(2); }
723 DIScope getContext() const { return getFieldAs<DIScope>(2); }
727 /// \brief This is a wrapper for template type parameter.
728 class DITemplateTypeParameter : public DIDescriptor {
730 explicit DITemplateTypeParameter(const MDNode *N = nullptr)
733 StringRef getName() const { return getHeaderField(1); }
735 DITypeRef getType() const { return getFieldAs<DITypeRef>(2); }
739 /// \brief This is a wrapper for template value parameter.
740 class DITemplateValueParameter : public DIDescriptor {
742 explicit DITemplateValueParameter(const MDNode *N = nullptr)
745 StringRef getName() const { return getHeaderField(1); }
747 DITypeRef getType() const { return getFieldAs<DITypeRef>(2); }
748 Metadata *getValue() const;
752 /// \brief This is a wrapper for a global variable.
753 class DIGlobalVariable : public DIDescriptor {
754 friend class DIDescriptor;
755 void printInternal(raw_ostream &OS) const;
758 explicit DIGlobalVariable(const MDNode *N = nullptr) : DIDescriptor(N) {}
760 StringRef getName() const { return getHeaderField(1); }
761 StringRef getDisplayName() const { return getHeaderField(2); }
762 StringRef getLinkageName() const { return getHeaderField(3); }
763 unsigned getLineNumber() const { return getHeaderFieldAs<unsigned>(4); }
764 unsigned isLocalToUnit() const { return getHeaderFieldAs<bool>(5); }
765 unsigned isDefinition() const { return getHeaderFieldAs<bool>(6); }
767 DIScope getContext() const { return getFieldAs<DIScope>(1); }
768 StringRef getFilename() const { return getFieldAs<DIFile>(2).getFilename(); }
769 StringRef getDirectory() const {
770 return getFieldAs<DIFile>(2).getDirectory();
772 DITypeRef getType() const { return getFieldAs<DITypeRef>(3); }
774 GlobalVariable *getGlobal() const { return getGlobalVariableField(4); }
775 Constant *getConstant() const { return getConstantField(4); }
776 DIDerivedType getStaticDataMemberDeclaration() const {
777 return getFieldAs<DIDerivedType>(5);
783 /// \brief This is a wrapper for a variable (e.g. parameter, local, global etc).
784 class DIVariable : public DIDescriptor {
785 friend class DIDescriptor;
786 void printInternal(raw_ostream &OS) const;
789 explicit DIVariable(const MDNode *N = nullptr) : DIDescriptor(N) {}
791 StringRef getName() const { return getHeaderField(1); }
792 unsigned getLineNumber() const {
793 // FIXME: Line number and arg number shouldn't be merged together like this.
794 return (getHeaderFieldAs<unsigned>(2) << 8) >> 8;
796 unsigned getArgNumber() const { return getHeaderFieldAs<unsigned>(2) >> 24; }
798 DIScope getContext() const { return getFieldAs<DIScope>(1); }
799 DIFile getFile() const { return getFieldAs<DIFile>(2); }
800 DITypeRef getType() const { return getFieldAs<DITypeRef>(3); }
802 /// \brief Return true if this variable is marked as "artificial".
803 bool isArtificial() const {
804 return (getHeaderFieldAs<unsigned>(3) & FlagArtificial) != 0;
807 bool isObjectPointer() const {
808 return (getHeaderFieldAs<unsigned>(3) & FlagObjectPointer) != 0;
811 /// \brief If this variable is inlined then return inline location.
812 MDNode *getInlinedAt() const;
816 /// \brief Check if this is a "__block" variable (Apple Blocks).
817 bool isBlockByrefVariable(const DITypeIdentifierMap &Map) const {
818 return (getType().resolve(Map)).isBlockByrefStruct();
821 /// \brief Check if this is an inlined function argument.
822 bool isInlinedFnArgument(const Function *CurFn);
824 /// \brief Return the size reported by the variable's type.
825 unsigned getSizeInBits(const DITypeIdentifierMap &Map);
827 void printExtendedName(raw_ostream &OS) const;
830 /// \brief A complex location expression in postfix notation.
832 /// This is (almost) a DWARF expression that modifies the location of a
833 /// variable or (or the location of a single piece of a variable).
835 /// FIXME: Instead of DW_OP_plus taking an argument, this should use DW_OP_const
836 /// and have DW_OP_plus consume the topmost elements on the stack.
837 class DIExpression : public DIDescriptor {
838 friend class DIDescriptor;
839 void printInternal(raw_ostream &OS) const;
842 explicit DIExpression(const MDNode *N = nullptr) : DIDescriptor(N) {}
846 /// \brief Return the number of elements in the complex expression.
847 unsigned getNumElements() const {
850 unsigned N = getNumHeaderFields();
851 assert(N > 0 && "missing tag");
855 /// \brief return the Idx'th complex address element.
856 uint64_t getElement(unsigned Idx) const;
858 /// \brief Return whether this is a piece of an aggregate variable.
859 bool isBitPiece() const;
860 /// \brief Return the offset of this piece in bits.
861 uint64_t getBitPieceOffset() const;
862 /// \brief Return the size of this piece in bits.
863 uint64_t getBitPieceSize() const;
866 /// \brief A lightweight wrapper around an element of a DIExpression.
868 friend class iterator;
869 DIHeaderFieldIterator I;
871 Operand(DIHeaderFieldIterator I) : I(I) {}
873 /// \brief Operands such as DW_OP_piece have explicit (non-stack) arguments.
874 /// Argument 0 is the operand itself.
875 uint64_t getArg(unsigned N) const {
876 DIHeaderFieldIterator In = I;
878 return In.getNumber<uint64_t>();
880 operator uint64_t () const { return I.getNumber<uint64_t>(); }
881 /// \brief Returns underlying DIHeaderFieldIterator.
882 const DIHeaderFieldIterator &getBase() const { return I; }
883 /// \brief Returns the next operand.
884 Operand getNext() const;
887 /// \brief An iterator for DIExpression elements.
888 class iterator : public std::iterator<std::input_iterator_tag, StringRef,
889 unsigned, const Operand*, Operand> {
890 friend class Operand;
891 DIHeaderFieldIterator I;
893 iterator(DIHeaderFieldIterator I) : I(I) {}
896 iterator(const DIExpression &Expr) : I(++Expr.header_begin()) {}
897 const Operand &operator*() { return Tmp = Operand(I); }
898 const Operand *operator->() { return &(Tmp = Operand(I)); }
899 iterator &operator++() {
903 iterator operator++(int) {
908 bool operator==(const iterator &X) const { return I == X.I; }
909 bool operator!=(const iterator &X) const { return !(*this == X); }
914 case dwarf::DW_OP_bit_piece: std::advance(I, 3); break;
915 case dwarf::DW_OP_plus: std::advance(I, 2); break;
916 case dwarf::DW_OP_deref: std::advance(I, 1); break;
918 llvm_unreachable("unsupported operand");
923 iterator begin() const;
924 iterator end() const;
927 /// \brief This object holds location information.
929 /// This object is not associated with any DWARF tag.
930 class DILocation : public DIDescriptor {
932 explicit DILocation(const MDNode *N) : DIDescriptor(N) {}
934 unsigned getLineNumber() const {
935 if (auto *L = dyn_cast_or_null<MDLocation>(DbgNode))
939 unsigned getColumnNumber() const {
940 if (auto *L = dyn_cast_or_null<MDLocation>(DbgNode))
941 return L->getColumn();
944 DIScope getScope() const {
945 if (auto *L = dyn_cast_or_null<MDLocation>(DbgNode))
946 return DIScope(dyn_cast_or_null<MDNode>(L->getScope()));
947 return DIScope(nullptr);
949 DILocation getOrigLocation() const {
950 if (auto *L = dyn_cast_or_null<MDLocation>(DbgNode))
951 return DILocation(dyn_cast_or_null<MDNode>(L->getInlinedAt()));
952 return DILocation(nullptr);
954 StringRef getFilename() const { return getScope().getFilename(); }
955 StringRef getDirectory() const { return getScope().getDirectory(); }
957 bool atSameLineAs(const DILocation &Other) const {
958 return (getLineNumber() == Other.getLineNumber() &&
959 getFilename() == Other.getFilename());
961 /// \brief Get the DWAF discriminator.
963 /// DWARF discriminators are used to distinguish identical file locations for
964 /// instructions that are on different basic blocks. If two instructions are
965 /// inside the same lexical block and are in different basic blocks, we
966 /// create a new lexical block with identical location as the original but
967 /// with a different discriminator value
968 /// (lib/Transforms/Util/AddDiscriminators.cpp for details).
969 unsigned getDiscriminator() const {
970 // Since discriminators are associated with lexical blocks, make
971 // sure this location is a lexical block before retrieving its
973 return getScope().isLexicalBlockFile()
974 ? DILexicalBlockFile(
975 cast<MDNode>(cast<MDLocation>(DbgNode)->getScope()))
980 /// \brief Generate a new discriminator value for this location.
981 unsigned computeNewDiscriminator(LLVMContext &Ctx);
983 /// \brief Return a copy of this location with a different scope.
984 DILocation copyWithNewScope(LLVMContext &Ctx, DILexicalBlockFile NewScope);
987 class DIObjCProperty : public DIDescriptor {
988 friend class DIDescriptor;
989 void printInternal(raw_ostream &OS) const;
992 explicit DIObjCProperty(const MDNode *N) : DIDescriptor(N) {}
994 StringRef getObjCPropertyName() const { return getHeaderField(1); }
995 DIFile getFile() const { return getFieldAs<DIFile>(1); }
996 unsigned getLineNumber() const { return getHeaderFieldAs<unsigned>(2); }
998 StringRef getObjCPropertyGetterName() const { return getHeaderField(3); }
999 StringRef getObjCPropertySetterName() const { return getHeaderField(4); }
1000 unsigned getAttributes() const { return getHeaderFieldAs<unsigned>(5); }
1001 bool isReadOnlyObjCProperty() const {
1002 return (getAttributes() & dwarf::DW_APPLE_PROPERTY_readonly) != 0;
1004 bool isReadWriteObjCProperty() const {
1005 return (getAttributes() & dwarf::DW_APPLE_PROPERTY_readwrite) != 0;
1007 bool isAssignObjCProperty() const {
1008 return (getAttributes() & dwarf::DW_APPLE_PROPERTY_assign) != 0;
1010 bool isRetainObjCProperty() const {
1011 return (getAttributes() & dwarf::DW_APPLE_PROPERTY_retain) != 0;
1013 bool isCopyObjCProperty() const {
1014 return (getAttributes() & dwarf::DW_APPLE_PROPERTY_copy) != 0;
1016 bool isNonAtomicObjCProperty() const {
1017 return (getAttributes() & dwarf::DW_APPLE_PROPERTY_nonatomic) != 0;
1020 /// \brief Get the type.
1022 /// \note Objective-C doesn't have an ODR, so there is no benefit in storing
1023 /// the type as a DITypeRef here.
1024 DIType getType() const { return getFieldAs<DIType>(2); }
1026 bool Verify() const;
1029 /// \brief An imported module (C++ using directive or similar).
1030 class DIImportedEntity : public DIDescriptor {
1031 friend class DIDescriptor;
1032 void printInternal(raw_ostream &OS) const;
1035 explicit DIImportedEntity(const MDNode *N) : DIDescriptor(N) {}
1036 DIScope getContext() const { return getFieldAs<DIScope>(1); }
1037 DIDescriptorRef getEntity() const { return getFieldAs<DIDescriptorRef>(2); }
1038 unsigned getLineNumber() const { return getHeaderFieldAs<unsigned>(1); }
1039 StringRef getName() const { return getHeaderField(2); }
1040 bool Verify() const;
1043 /// \brief Find subprogram that is enclosing this scope.
1044 DISubprogram getDISubprogram(const MDNode *Scope);
1046 /// \brief Find debug info for a given function.
1047 /// \returns a valid DISubprogram, if found. Otherwise, it returns an empty
1049 DISubprogram getDISubprogram(const Function *F);
1051 /// \brief Find underlying composite type.
1052 DICompositeType getDICompositeType(DIType T);
1054 /// \brief Create a new inlined variable based on current variable.
1056 /// @param DV Current Variable.
1057 /// @param InlinedScope Location at current variable is inlined.
1058 DIVariable createInlinedVariable(MDNode *DV, MDNode *InlinedScope,
1059 LLVMContext &VMContext);
1061 /// \brief Remove inlined scope from the variable.
1062 DIVariable cleanseInlinedVariable(MDNode *DV, LLVMContext &VMContext);
1064 /// \brief Generate map by visiting all retained types.
1065 DITypeIdentifierMap generateDITypeIdentifierMap(const NamedMDNode *CU_Nodes);
1067 /// \brief Strip debug info in the module if it exists.
1069 /// To do this, we remove all calls to the debugger intrinsics and any named
1070 /// metadata for debugging. We also remove debug locations for instructions.
1071 /// Return true if module is modified.
1072 bool StripDebugInfo(Module &M);
1074 /// \brief Return Debug Info Metadata Version by checking module flags.
1075 unsigned getDebugMetadataVersionFromModule(const Module &M);
1077 /// \brief Utility to find all debug info in a module.
1079 /// DebugInfoFinder tries to list all debug info MDNodes used in a module. To
1080 /// list debug info MDNodes used by an instruction, DebugInfoFinder uses
1081 /// processDeclare, processValue and processLocation to handle DbgDeclareInst,
1082 /// DbgValueInst and DbgLoc attached to instructions. processModule will go
1083 /// through all DICompileUnits in llvm.dbg.cu and list debug info MDNodes
1084 /// used by the CUs.
1085 class DebugInfoFinder {
1087 DebugInfoFinder() : TypeMapInitialized(false) {}
1089 /// \brief Process entire module and collect debug info anchors.
1090 void processModule(const Module &M);
1092 /// \brief Process DbgDeclareInst.
1093 void processDeclare(const Module &M, const DbgDeclareInst *DDI);
1094 /// \brief Process DbgValueInst.
1095 void processValue(const Module &M, const DbgValueInst *DVI);
1096 /// \brief Process DILocation.
1097 void processLocation(const Module &M, DILocation Loc);
1099 /// \brief Process DIExpression.
1100 void processExpression(DIExpression Expr);
1102 /// \brief Clear all lists.
1106 void InitializeTypeMap(const Module &M);
1108 void processType(DIType DT);
1109 void processSubprogram(DISubprogram SP);
1110 void processScope(DIScope Scope);
1111 bool addCompileUnit(DICompileUnit CU);
1112 bool addGlobalVariable(DIGlobalVariable DIG);
1113 bool addSubprogram(DISubprogram SP);
1114 bool addType(DIType DT);
1115 bool addScope(DIScope Scope);
1118 typedef SmallVectorImpl<DICompileUnit>::const_iterator compile_unit_iterator;
1119 typedef SmallVectorImpl<DISubprogram>::const_iterator subprogram_iterator;
1120 typedef SmallVectorImpl<DIGlobalVariable>::const_iterator
1121 global_variable_iterator;
1122 typedef SmallVectorImpl<DIType>::const_iterator type_iterator;
1123 typedef SmallVectorImpl<DIScope>::const_iterator scope_iterator;
1125 iterator_range<compile_unit_iterator> compile_units() const {
1126 return iterator_range<compile_unit_iterator>(CUs.begin(), CUs.end());
1129 iterator_range<subprogram_iterator> subprograms() const {
1130 return iterator_range<subprogram_iterator>(SPs.begin(), SPs.end());
1133 iterator_range<global_variable_iterator> global_variables() const {
1134 return iterator_range<global_variable_iterator>(GVs.begin(), GVs.end());
1137 iterator_range<type_iterator> types() const {
1138 return iterator_range<type_iterator>(TYs.begin(), TYs.end());
1141 iterator_range<scope_iterator> scopes() const {
1142 return iterator_range<scope_iterator>(Scopes.begin(), Scopes.end());
1145 unsigned compile_unit_count() const { return CUs.size(); }
1146 unsigned global_variable_count() const { return GVs.size(); }
1147 unsigned subprogram_count() const { return SPs.size(); }
1148 unsigned type_count() const { return TYs.size(); }
1149 unsigned scope_count() const { return Scopes.size(); }
1152 SmallVector<DICompileUnit, 8> CUs;
1153 SmallVector<DISubprogram, 8> SPs;
1154 SmallVector<DIGlobalVariable, 8> GVs;
1155 SmallVector<DIType, 8> TYs;
1156 SmallVector<DIScope, 8> Scopes;
1157 SmallPtrSet<MDNode *, 64> NodesSeen;
1158 DITypeIdentifierMap TypeIdentifierMap;
1160 /// \brief Specify if TypeIdentifierMap is initialized.
1161 bool TypeMapInitialized;
1164 DenseMap<const Function *, DISubprogram> makeSubprogramMap(const Module &M);
1166 } // end namespace llvm