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 #define HANDLE_DI_FLAG(ID, NAME) Flag##NAME = ID,
136 #include "llvm/IR/DebugInfoFlags.def"
137 FlagAccessibility = FlagPrivate | FlagProtected | FlagPublic
140 static unsigned getFlag(StringRef Flag);
141 static const char *getFlagString(unsigned Flag);
143 /// \brief Split up a flags bitfield.
145 /// Split \c Flags into \c SplitFlags, a vector of its components. Returns
146 /// any remaining (unrecognized) bits.
147 static unsigned splitFlags(unsigned Flags,
148 SmallVectorImpl<unsigned> &SplitFlags);
151 const MDNode *DbgNode;
153 StringRef getStringField(unsigned Elt) const;
154 unsigned getUnsignedField(unsigned Elt) const {
155 return (unsigned)getUInt64Field(Elt);
157 uint64_t getUInt64Field(unsigned Elt) const;
158 int64_t getInt64Field(unsigned Elt) const;
159 DIDescriptor getDescriptorField(unsigned Elt) const;
161 template <typename DescTy> DescTy getFieldAs(unsigned Elt) const {
162 return DescTy(getDescriptorField(Elt));
165 GlobalVariable *getGlobalVariableField(unsigned Elt) const;
166 Constant *getConstantField(unsigned Elt) const;
167 Function *getFunctionField(unsigned Elt) const;
168 void replaceFunctionField(unsigned Elt, Function *F);
171 explicit DIDescriptor(const MDNode *N = nullptr) : DbgNode(N) {}
175 MDNode *get() const { return const_cast<MDNode *>(DbgNode); }
176 operator MDNode *() const { return get(); }
177 MDNode *operator->() const { return get(); }
179 // An explicit operator bool so that we can do testing of DI values
181 // FIXME: This operator bool isn't actually protecting anything at the
182 // moment due to the conversion operator above making DIDescriptor nodes
183 // implicitly convertable to bool.
184 explicit operator bool() const { return DbgNode != nullptr; }
186 bool operator==(DIDescriptor Other) const { return DbgNode == Other.DbgNode; }
187 bool operator!=(DIDescriptor Other) const { return !operator==(Other); }
189 StringRef getHeader() const { return getStringField(0); }
191 size_t getNumHeaderFields() const {
192 return std::distance(DIHeaderFieldIterator(getHeader()),
193 DIHeaderFieldIterator());
196 DIHeaderFieldIterator header_begin() const {
197 return DIHeaderFieldIterator(getHeader());
199 DIHeaderFieldIterator header_end() const { return DIHeaderFieldIterator(); }
201 DIHeaderFieldIterator getHeaderIterator(unsigned Index) const {
202 // Since callers expect an empty string for out-of-range accesses, we can't
203 // use std::advance() here.
204 for (auto I = header_begin(), E = header_end(); I != E; ++I, --Index)
210 StringRef getHeaderField(unsigned Index) const {
211 return *getHeaderIterator(Index);
214 template <class T> T getHeaderFieldAs(unsigned Index) const {
215 return getHeaderIterator(Index).getNumber<T>();
218 uint16_t getTag() const { return getHeaderFieldAs<uint16_t>(0); }
220 bool isDerivedType() const;
221 bool isCompositeType() const;
222 bool isSubroutineType() const;
223 bool isBasicType() const;
224 bool isVariable() const;
225 bool isSubprogram() const;
226 bool isGlobalVariable() const;
227 bool isScope() const;
229 bool isCompileUnit() const;
230 bool isNameSpace() const;
231 bool isLexicalBlockFile() const;
232 bool isLexicalBlock() const;
233 bool isSubrange() const;
234 bool isEnumerator() const;
236 bool isTemplateTypeParameter() const;
237 bool isTemplateValueParameter() const;
238 bool isObjCProperty() const;
239 bool isImportedEntity() const;
240 bool isExpression() const;
242 void print(raw_ostream &OS) const;
245 /// \brief Replace all uses of debug info referenced by this descriptor.
246 void replaceAllUsesWith(LLVMContext &VMContext, DIDescriptor D);
247 void replaceAllUsesWith(MDNode *D);
250 #define RETURN_FROM_RAW(VALID, DEFAULT) \
252 if (auto *N = getRaw()) \
256 #define RETURN_DESCRIPTOR_FROM_RAW(DESC, VALID) \
258 if (auto *N = getRaw()) \
259 return DESC(dyn_cast_or_null<MDNode>(VALID)); \
260 return DESC(static_cast<const MDNode *>(nullptr)); \
263 /// \brief This is used to represent ranges, for array bounds.
264 class DISubrange : public DIDescriptor {
265 friend class DIDescriptor;
266 void printInternal(raw_ostream &OS) const;
269 explicit DISubrange(const MDNode *N = nullptr) : DIDescriptor(N) {}
271 int64_t getLo() const { return getHeaderFieldAs<int64_t>(1); }
272 int64_t getCount() const { return getHeaderFieldAs<int64_t>(2); }
276 /// \brief This descriptor holds an array of nodes with type T.
277 template <typename T> class DITypedArray : public DIDescriptor {
279 explicit DITypedArray(const MDNode *N = nullptr) : DIDescriptor(N) {}
280 unsigned getNumElements() const {
281 return DbgNode ? DbgNode->getNumOperands() : 0;
283 T getElement(unsigned Idx) const { return getFieldAs<T>(Idx); }
286 typedef DITypedArray<DIDescriptor> DIArray;
288 /// \brief A wrapper for an enumerator (e.g. X and Y in 'enum {X,Y}').
290 /// FIXME: it seems strange that this doesn't have either a reference to the
291 /// type/precision or a file/line pair for location info.
292 class DIEnumerator : public DIDescriptor {
293 friend class DIDescriptor;
294 void printInternal(raw_ostream &OS) const;
297 explicit DIEnumerator(const MDNode *N = nullptr) : DIDescriptor(N) {}
299 StringRef getName() const { return getHeaderField(1); }
300 int64_t getEnumValue() const { return getHeaderFieldAs<int64_t>(2); }
304 template <typename T> class DIRef;
305 typedef DIRef<DIDescriptor> DIDescriptorRef;
306 typedef DIRef<DIScope> DIScopeRef;
307 typedef DIRef<DIType> DITypeRef;
308 typedef DITypedArray<DITypeRef> DITypeArray;
310 /// \brief A base class for various scopes.
312 /// Although, implementation-wise, DIScope is the parent class of most
313 /// other DIxxx classes, including DIType and its descendants, most of
314 /// DIScope's descendants are not a substitutable subtype of
315 /// DIScope. The DIDescriptor::isScope() method only is true for
316 /// DIScopes that are scopes in the strict lexical scope sense
317 /// (DICompileUnit, DISubprogram, etc.), but not for, e.g., a DIType.
318 class DIScope : public DIDescriptor {
320 friend class DIDescriptor;
321 void printInternal(raw_ostream &OS) const;
324 explicit DIScope(const MDNode *N = nullptr) : DIDescriptor(N) {}
326 /// \brief Get the parent scope.
328 /// Gets the parent scope for this scope node or returns a default
329 /// constructed scope.
330 DIScopeRef getContext() const;
331 /// \brief Get the scope name.
333 /// If the scope node has a name, return that, else return an empty string.
334 StringRef getName() const;
335 StringRef getFilename() const;
336 StringRef getDirectory() const;
338 /// \brief Generate a reference to this DIScope.
340 /// Uses the type identifier instead of the actual MDNode if possible, to
341 /// help type uniquing.
342 DIScopeRef getRef() const;
345 /// \brief Represents reference to a DIDescriptor.
347 /// Abstracts over direct and identifier-based metadata references.
348 template <typename T> class DIRef {
349 template <typename DescTy>
350 friend DescTy DIDescriptor::getFieldAs(unsigned Elt) const;
351 friend DIScopeRef DIScope::getContext() const;
352 friend DIScopeRef DIScope::getRef() const;
355 /// \brief Val can be either a MDNode or a MDString.
357 /// In the latter, MDString specifies the type identifier.
359 explicit DIRef(const Metadata *V);
362 T resolve(const DITypeIdentifierMap &Map) const;
363 StringRef getName() const;
364 operator Metadata *() const { return const_cast<Metadata *>(Val); }
367 template <typename T>
368 T DIRef<T>::resolve(const DITypeIdentifierMap &Map) const {
372 if (const MDNode *MD = dyn_cast<MDNode>(Val))
375 const MDString *MS = cast<MDString>(Val);
376 // Find the corresponding MDNode.
377 DITypeIdentifierMap::const_iterator Iter = Map.find(MS);
378 assert(Iter != Map.end() && "Identifier not in the type map?");
379 assert(DIDescriptor(Iter->second).isType() &&
380 "MDNode in DITypeIdentifierMap should be a DIType.");
381 return T(Iter->second);
384 template <typename T> StringRef DIRef<T>::getName() const {
388 if (const MDNode *MD = dyn_cast<MDNode>(Val))
389 return T(MD).getName();
391 const MDString *MS = cast<MDString>(Val);
392 return MS->getString();
395 /// \brief Handle fields that are references to DIDescriptors.
397 DIDescriptorRef DIDescriptor::getFieldAs<DIDescriptorRef>(unsigned Elt) const;
398 /// \brief Specialize DIRef constructor for DIDescriptorRef.
399 template <> DIRef<DIDescriptor>::DIRef(const Metadata *V);
401 /// \brief Handle fields that are references to DIScopes.
402 template <> DIScopeRef DIDescriptor::getFieldAs<DIScopeRef>(unsigned Elt) const;
403 /// \brief Specialize DIRef constructor for DIScopeRef.
404 template <> DIRef<DIScope>::DIRef(const Metadata *V);
406 /// \brief Handle fields that are references to DITypes.
407 template <> DITypeRef DIDescriptor::getFieldAs<DITypeRef>(unsigned Elt) const;
408 /// \brief Specialize DIRef constructor for DITypeRef.
409 template <> DIRef<DIType>::DIRef(const Metadata *V);
411 /// \brief This is a wrapper for a type.
413 /// FIXME: Types should be factored much better so that CV qualifiers and
414 /// others do not require a huge and empty descriptor full of zeros.
415 class DIType : public DIScope {
417 friend class DIDescriptor;
418 void printInternal(raw_ostream &OS) const;
421 explicit DIType(const MDNode *N = nullptr) : DIScope(N) {}
422 operator DITypeRef() const {
424 "constructing DITypeRef from an MDNode that is not a type");
425 return DITypeRef(&*getRef());
430 DIScopeRef getContext() const { return getFieldAs<DIScopeRef>(2); }
431 StringRef getName() const { return getHeaderField(1); }
432 unsigned getLineNumber() const { return getHeaderFieldAs<unsigned>(2); }
433 uint64_t getSizeInBits() const { return getHeaderFieldAs<unsigned>(3); }
434 uint64_t getAlignInBits() const { return getHeaderFieldAs<unsigned>(4); }
435 // FIXME: Offset is only used for DW_TAG_member nodes. Making every type
436 // carry this is just plain insane.
437 uint64_t getOffsetInBits() const { return getHeaderFieldAs<unsigned>(5); }
438 unsigned getFlags() const { return getHeaderFieldAs<unsigned>(6); }
439 bool isPrivate() const {
440 return (getFlags() & FlagAccessibility) == FlagPrivate;
442 bool isProtected() const {
443 return (getFlags() & FlagAccessibility) == FlagProtected;
445 bool isPublic() const {
446 return (getFlags() & FlagAccessibility) == FlagPublic;
448 bool isForwardDecl() const { return (getFlags() & FlagFwdDecl) != 0; }
449 bool isAppleBlockExtension() const {
450 return (getFlags() & FlagAppleBlock) != 0;
452 bool isBlockByrefStruct() const {
453 return (getFlags() & FlagBlockByrefStruct) != 0;
455 bool isVirtual() const { return (getFlags() & FlagVirtual) != 0; }
456 bool isArtificial() const { return (getFlags() & FlagArtificial) != 0; }
457 bool isObjectPointer() const { return (getFlags() & FlagObjectPointer) != 0; }
458 bool isObjcClassComplete() const {
459 return (getFlags() & FlagObjcClassComplete) != 0;
461 bool isVector() const { return (getFlags() & FlagVector) != 0; }
462 bool isStaticMember() const { return (getFlags() & FlagStaticMember) != 0; }
463 bool isLValueReference() const {
464 return (getFlags() & FlagLValueReference) != 0;
466 bool isRValueReference() const {
467 return (getFlags() & FlagRValueReference) != 0;
469 bool isValid() const { return DbgNode && isType(); }
472 /// \brief A basic type, like 'int' or 'float'.
473 class DIBasicType : public DIType {
475 explicit DIBasicType(const MDNode *N = nullptr) : DIType(N) {}
477 unsigned getEncoding() const { return getHeaderFieldAs<unsigned>(7); }
482 /// \brief A simple derived type
484 /// Like a const qualified type, a typedef, a pointer or reference, et cetera.
485 /// Or, a data member of a class/struct/union.
486 class DIDerivedType : public DIType {
487 friend class DIDescriptor;
488 void printInternal(raw_ostream &OS) const;
491 explicit DIDerivedType(const MDNode *N = nullptr) : DIType(N) {}
493 DITypeRef getTypeDerivedFrom() const { return getFieldAs<DITypeRef>(3); }
495 /// \brief Return property node, if this ivar is associated with one.
496 MDNode *getObjCProperty() const;
498 DITypeRef getClassType() const {
499 assert(getTag() == dwarf::DW_TAG_ptr_to_member_type);
500 return getFieldAs<DITypeRef>(4);
503 Constant *getConstant() const {
504 assert((getTag() == dwarf::DW_TAG_member) && isStaticMember());
505 return getConstantField(4);
511 /// \brief Types that refer to multiple other types.
513 /// This descriptor holds a type that can refer to multiple other types, like a
514 /// function or struct.
516 /// DICompositeType is derived from DIDerivedType because some
517 /// composite types (such as enums) can be derived from basic types
518 // FIXME: Make this derive from DIType directly & just store the
519 // base type in a single DIType field.
520 class DICompositeType : public DIDerivedType {
521 friend class DIBuilder;
522 friend class DIDescriptor;
523 void printInternal(raw_ostream &OS) const;
525 /// \brief Set the array of member DITypes.
526 void setArraysHelper(MDNode *Elements, MDNode *TParams);
529 explicit DICompositeType(const MDNode *N = nullptr) : DIDerivedType(N) {}
531 DIArray getElements() const {
532 assert(!isSubroutineType() && "no elements for DISubroutineType");
533 return getFieldAs<DIArray>(4);
537 template <typename T>
538 void setArrays(DITypedArray<T> Elements, DIArray TParams = DIArray()) {
540 (!TParams || DbgNode->getNumOperands() == 8) &&
541 "If you're setting the template parameters this should include a slot "
543 setArraysHelper(Elements, TParams);
547 unsigned getRunTimeLang() const { return getHeaderFieldAs<unsigned>(7); }
548 DITypeRef getContainingType() const { return getFieldAs<DITypeRef>(5); }
551 /// \brief Set the containing type.
552 void setContainingType(DICompositeType ContainingType);
555 DIArray getTemplateParams() const { return getFieldAs<DIArray>(6); }
556 MDString *getIdentifier() const;
561 class DISubroutineType : public DICompositeType {
563 explicit DISubroutineType(const MDNode *N = nullptr) : DICompositeType(N) {}
564 DITypedArray<DITypeRef> getTypeArray() const {
565 return getFieldAs<DITypedArray<DITypeRef>>(4);
569 /// \brief This is a wrapper for a file.
570 class DIFile : public DIScope {
571 friend class DIDescriptor;
574 explicit DIFile(const MDNode *N = nullptr) : DIScope(N) {}
576 /// \brief Retrieve the MDNode for the directory/file pair.
577 MDNode *getFileNode() const;
581 /// \brief A wrapper for a compile unit.
582 class DICompileUnit : public DIScope {
583 friend class DIDescriptor;
584 void printInternal(raw_ostream &OS) const;
587 explicit DICompileUnit(const MDNode *N = nullptr) : DIScope(N) {}
589 dwarf::SourceLanguage getLanguage() const {
590 return static_cast<dwarf::SourceLanguage>(getHeaderFieldAs<unsigned>(1));
592 StringRef getProducer() const { return getHeaderField(2); }
594 bool isOptimized() const { return getHeaderFieldAs<bool>(3) != 0; }
595 StringRef getFlags() const { return getHeaderField(4); }
596 unsigned getRunTimeVersion() const { return getHeaderFieldAs<unsigned>(5); }
598 DIArray getEnumTypes() const;
599 DIArray getRetainedTypes() const;
600 DIArray getSubprograms() const;
601 DIArray getGlobalVariables() const;
602 DIArray getImportedEntities() const;
604 void replaceSubprograms(DIArray Subprograms);
605 void replaceGlobalVariables(DIArray GlobalVariables);
607 StringRef getSplitDebugFilename() const { return getHeaderField(6); }
608 unsigned getEmissionKind() const { return getHeaderFieldAs<unsigned>(7); }
613 /// \brief This is a wrapper for a subprogram (e.g. a function).
614 class DISubprogram : public DIScope {
615 friend class DIDescriptor;
616 void printInternal(raw_ostream &OS) const;
619 explicit DISubprogram(const MDNode *N = nullptr) : DIScope(N) {}
621 StringRef getName() const { return getHeaderField(1); }
622 StringRef getDisplayName() const { return getHeaderField(2); }
623 StringRef getLinkageName() const { return getHeaderField(3); }
624 unsigned getLineNumber() const { return getHeaderFieldAs<unsigned>(4); }
626 /// \brief Check if this is local (like 'static' in C).
627 unsigned isLocalToUnit() const { return getHeaderFieldAs<unsigned>(5); }
628 unsigned isDefinition() const { return getHeaderFieldAs<unsigned>(6); }
630 unsigned getVirtuality() const { return getHeaderFieldAs<unsigned>(7); }
631 unsigned getVirtualIndex() const { return getHeaderFieldAs<unsigned>(8); }
633 unsigned getFlags() const { return getHeaderFieldAs<unsigned>(9); }
635 unsigned isOptimized() const { return getHeaderFieldAs<bool>(10); }
637 /// \brief Get the beginning of the scope of the function (not the name).
638 unsigned getScopeLineNumber() const { return getHeaderFieldAs<unsigned>(11); }
640 DIScopeRef getContext() const { return getFieldAs<DIScopeRef>(2); }
641 DISubroutineType getType() const { return getFieldAs<DISubroutineType>(3); }
643 DITypeRef getContainingType() const { return getFieldAs<DITypeRef>(4); }
647 /// \brief Check if this provides debugging information for the function F.
648 bool describes(const Function *F);
650 Function *getFunction() const { return getFunctionField(5); }
651 void replaceFunction(Function *F) { replaceFunctionField(5, F); }
652 DIArray getTemplateParams() const { return getFieldAs<DIArray>(6); }
653 DISubprogram getFunctionDeclaration() const {
654 return getFieldAs<DISubprogram>(7);
656 MDNode *getVariablesNodes() const;
657 DIArray getVariables() const;
659 unsigned isArtificial() const { return (getFlags() & FlagArtificial) != 0; }
660 /// \brief Check for the "private" access specifier.
661 bool isPrivate() const {
662 return (getFlags() & FlagAccessibility) == FlagPrivate;
664 /// \brief Check for the "protected" access specifier.
665 bool isProtected() const {
666 return (getFlags() & FlagAccessibility) == FlagProtected;
668 /// \brief Check for the "public" access specifier.
669 bool isPublic() const {
670 return (getFlags() & FlagAccessibility) == FlagPublic;
672 /// \brief Check for "explicit".
673 bool isExplicit() const { return (getFlags() & FlagExplicit) != 0; }
674 /// \brief Check if this is prototyped.
675 bool isPrototyped() const { return (getFlags() & FlagPrototyped) != 0; }
677 /// \brief Check if this is reference-qualified.
679 /// Return true if this subprogram is a C++11 reference-qualified non-static
680 /// member function (void foo() &).
681 unsigned isLValueReference() const {
682 return (getFlags() & FlagLValueReference) != 0;
685 /// \brief Check if this is rvalue-reference-qualified.
687 /// Return true if this subprogram is a C++11 rvalue-reference-qualified
688 /// non-static member function (void foo() &&).
689 unsigned isRValueReference() const {
690 return (getFlags() & FlagRValueReference) != 0;
694 /// \brief This is a wrapper for a lexical block.
695 class DILexicalBlock : public DIScope {
697 explicit DILexicalBlock(const MDNode *N = nullptr) : DIScope(N) {}
698 DIScope getContext() const { return getFieldAs<DIScope>(2); }
699 unsigned getLineNumber() const { return getHeaderFieldAs<unsigned>(1); }
700 unsigned getColumnNumber() const { return getHeaderFieldAs<unsigned>(2); }
704 /// \brief This is a wrapper for a lexical block with a filename change.
705 class DILexicalBlockFile : public DIScope {
707 explicit DILexicalBlockFile(const MDNode *N = nullptr) : DIScope(N) {}
708 DIScope getContext() const {
709 // FIXME: This logic is horrible. getScope() returns a DILexicalBlock, but
710 // then we check if it's a subprogram? WHAT?!?
711 if (getScope().isSubprogram())
713 return getScope().getContext();
715 unsigned getLineNumber() const { return getScope().getLineNumber(); }
716 unsigned getColumnNumber() const { return getScope().getColumnNumber(); }
717 DILexicalBlock getScope() const { return getFieldAs<DILexicalBlock>(2); }
718 unsigned getDiscriminator() const { return getHeaderFieldAs<unsigned>(1); }
722 /// \brief A wrapper for a C++ style name space.
723 class DINameSpace : public DIScope {
724 friend class DIDescriptor;
725 void printInternal(raw_ostream &OS) const;
728 explicit DINameSpace(const MDNode *N = nullptr) : DIScope(N) {}
729 StringRef getName() const { return getHeaderField(1); }
730 unsigned getLineNumber() const { return getHeaderFieldAs<unsigned>(2); }
731 DIScope getContext() const { return getFieldAs<DIScope>(2); }
735 /// \brief This is a wrapper for template type parameter.
736 class DITemplateTypeParameter : public DIDescriptor {
738 explicit DITemplateTypeParameter(const MDNode *N = nullptr)
741 StringRef getName() const { return getHeaderField(1); }
743 DITypeRef getType() const { return getFieldAs<DITypeRef>(2); }
747 /// \brief This is a wrapper for template value parameter.
748 class DITemplateValueParameter : public DIDescriptor {
750 explicit DITemplateValueParameter(const MDNode *N = nullptr)
753 StringRef getName() const { return getHeaderField(1); }
755 DITypeRef getType() const { return getFieldAs<DITypeRef>(2); }
756 Metadata *getValue() const;
760 /// \brief This is a wrapper for a global variable.
761 class DIGlobalVariable : public DIDescriptor {
762 friend class DIDescriptor;
763 void printInternal(raw_ostream &OS) const;
766 explicit DIGlobalVariable(const MDNode *N = nullptr) : DIDescriptor(N) {}
768 StringRef getName() const { return getHeaderField(1); }
769 StringRef getDisplayName() const { return getHeaderField(2); }
770 StringRef getLinkageName() const { return getHeaderField(3); }
771 unsigned getLineNumber() const { return getHeaderFieldAs<unsigned>(4); }
772 unsigned isLocalToUnit() const { return getHeaderFieldAs<bool>(5); }
773 unsigned isDefinition() const { return getHeaderFieldAs<bool>(6); }
775 DIScope getContext() const { return getFieldAs<DIScope>(1); }
776 StringRef getFilename() const { return getFieldAs<DIFile>(2).getFilename(); }
777 StringRef getDirectory() const {
778 return getFieldAs<DIFile>(2).getDirectory();
780 DITypeRef getType() const { return getFieldAs<DITypeRef>(3); }
782 GlobalVariable *getGlobal() const { return getGlobalVariableField(4); }
783 Constant *getConstant() const { return getConstantField(4); }
784 DIDerivedType getStaticDataMemberDeclaration() const {
785 return getFieldAs<DIDerivedType>(5);
791 /// \brief This is a wrapper for a variable (e.g. parameter, local, global etc).
792 class DIVariable : public DIDescriptor {
793 friend class DIDescriptor;
794 void printInternal(raw_ostream &OS) const;
797 explicit DIVariable(const MDNode *N = nullptr) : DIDescriptor(N) {}
799 StringRef getName() const { return getHeaderField(1); }
800 unsigned getLineNumber() const {
801 // FIXME: Line number and arg number shouldn't be merged together like this.
802 return (getHeaderFieldAs<unsigned>(2) << 8) >> 8;
804 unsigned getArgNumber() const { return getHeaderFieldAs<unsigned>(2) >> 24; }
806 DIScope getContext() const { return getFieldAs<DIScope>(1); }
807 DIFile getFile() const { return getFieldAs<DIFile>(2); }
808 DITypeRef getType() const { return getFieldAs<DITypeRef>(3); }
810 /// \brief Return true if this variable is marked as "artificial".
811 bool isArtificial() const {
812 return (getHeaderFieldAs<unsigned>(3) & FlagArtificial) != 0;
815 bool isObjectPointer() const {
816 return (getHeaderFieldAs<unsigned>(3) & FlagObjectPointer) != 0;
819 /// \brief If this variable is inlined then return inline location.
820 MDNode *getInlinedAt() const;
824 /// \brief Check if this is a "__block" variable (Apple Blocks).
825 bool isBlockByrefVariable(const DITypeIdentifierMap &Map) const {
826 return (getType().resolve(Map)).isBlockByrefStruct();
829 /// \brief Check if this is an inlined function argument.
830 bool isInlinedFnArgument(const Function *CurFn);
832 /// \brief Return the size reported by the variable's type.
833 unsigned getSizeInBits(const DITypeIdentifierMap &Map);
835 void printExtendedName(raw_ostream &OS) const;
838 /// \brief A complex location expression in postfix notation.
840 /// This is (almost) a DWARF expression that modifies the location of a
841 /// variable or (or the location of a single piece of a variable).
843 /// FIXME: Instead of DW_OP_plus taking an argument, this should use DW_OP_const
844 /// and have DW_OP_plus consume the topmost elements on the stack.
845 class DIExpression : public DIDescriptor {
846 friend class DIDescriptor;
847 void printInternal(raw_ostream &OS) const;
850 explicit DIExpression(const MDNode *N = nullptr) : DIDescriptor(N) {}
854 /// \brief Return the number of elements in the complex expression.
855 unsigned getNumElements() const {
858 unsigned N = getNumHeaderFields();
859 assert(N > 0 && "missing tag");
863 /// \brief return the Idx'th complex address element.
864 uint64_t getElement(unsigned Idx) const;
866 /// \brief Return whether this is a piece of an aggregate variable.
867 bool isBitPiece() const;
868 /// \brief Return the offset of this piece in bits.
869 uint64_t getBitPieceOffset() const;
870 /// \brief Return the size of this piece in bits.
871 uint64_t getBitPieceSize() const;
874 /// \brief A lightweight wrapper around an element of a DIExpression.
876 friend class iterator;
877 DIHeaderFieldIterator I;
879 Operand(DIHeaderFieldIterator I) : I(I) {}
881 /// \brief Operands such as DW_OP_piece have explicit (non-stack) arguments.
882 /// Argument 0 is the operand itself.
883 uint64_t getArg(unsigned N) const {
884 DIHeaderFieldIterator In = I;
886 return In.getNumber<uint64_t>();
888 operator uint64_t () const { return I.getNumber<uint64_t>(); }
889 /// \brief Returns underlying DIHeaderFieldIterator.
890 const DIHeaderFieldIterator &getBase() const { return I; }
891 /// \brief Returns the next operand.
892 Operand getNext() const;
895 /// \brief An iterator for DIExpression elements.
896 class iterator : public std::iterator<std::input_iterator_tag, StringRef,
897 unsigned, const Operand*, Operand> {
898 friend class Operand;
899 DIHeaderFieldIterator I;
901 iterator(DIHeaderFieldIterator I) : I(I) {}
904 iterator(const DIExpression &Expr) : I(++Expr.header_begin()) {}
905 const Operand &operator*() { return Tmp = Operand(I); }
906 const Operand *operator->() { return &(Tmp = Operand(I)); }
907 iterator &operator++() {
911 iterator operator++(int) {
916 bool operator==(const iterator &X) const { return I == X.I; }
917 bool operator!=(const iterator &X) const { return !(*this == X); }
922 case dwarf::DW_OP_bit_piece: std::advance(I, 3); break;
923 case dwarf::DW_OP_plus: std::advance(I, 2); break;
924 case dwarf::DW_OP_deref: std::advance(I, 1); break;
926 llvm_unreachable("unsupported operand");
931 iterator begin() const;
932 iterator end() const;
935 /// \brief This object holds location information.
937 /// This object is not associated with any DWARF tag.
938 class DILocation : public DIDescriptor {
939 MDLocation *getRaw() const { return dyn_cast_or_null<MDLocation>(get()); }
942 explicit DILocation(const MDNode *N) : DIDescriptor(N) {}
944 unsigned getLineNumber() const { RETURN_FROM_RAW(N->getLine(), 0); }
945 unsigned getColumnNumber() const { RETURN_FROM_RAW(N->getColumn(), 0); }
946 DIScope getScope() const {
947 RETURN_DESCRIPTOR_FROM_RAW(DIScope, N->getScope());
949 DILocation getOrigLocation() const {
950 RETURN_DESCRIPTOR_FROM_RAW(DILocation, N->getInlinedAt());
952 StringRef getFilename() const { return getScope().getFilename(); }
953 StringRef getDirectory() const { return getScope().getDirectory(); }
955 bool atSameLineAs(const DILocation &Other) const {
956 return (getLineNumber() == Other.getLineNumber() &&
957 getFilename() == Other.getFilename());
959 /// \brief Get the DWAF discriminator.
961 /// DWARF discriminators are used to distinguish identical file locations for
962 /// instructions that are on different basic blocks. If two instructions are
963 /// inside the same lexical block and are in different basic blocks, we
964 /// create a new lexical block with identical location as the original but
965 /// with a different discriminator value
966 /// (lib/Transforms/Util/AddDiscriminators.cpp for details).
967 unsigned getDiscriminator() const {
968 // Since discriminators are associated with lexical blocks, make
969 // sure this location is a lexical block before retrieving its
971 return getScope().isLexicalBlockFile()
972 ? DILexicalBlockFile(
973 cast<MDNode>(cast<MDLocation>(DbgNode)->getScope()))
978 /// \brief Generate a new discriminator value for this location.
979 unsigned computeNewDiscriminator(LLVMContext &Ctx);
981 /// \brief Return a copy of this location with a different scope.
982 DILocation copyWithNewScope(LLVMContext &Ctx, DILexicalBlockFile NewScope);
985 class DIObjCProperty : public DIDescriptor {
986 friend class DIDescriptor;
987 void printInternal(raw_ostream &OS) const;
990 explicit DIObjCProperty(const MDNode *N) : DIDescriptor(N) {}
992 StringRef getObjCPropertyName() const { return getHeaderField(1); }
993 DIFile getFile() const { return getFieldAs<DIFile>(1); }
994 unsigned getLineNumber() const { return getHeaderFieldAs<unsigned>(2); }
996 StringRef getObjCPropertyGetterName() const { return getHeaderField(3); }
997 StringRef getObjCPropertySetterName() const { return getHeaderField(4); }
998 unsigned getAttributes() const { return getHeaderFieldAs<unsigned>(5); }
999 bool isReadOnlyObjCProperty() const {
1000 return (getAttributes() & dwarf::DW_APPLE_PROPERTY_readonly) != 0;
1002 bool isReadWriteObjCProperty() const {
1003 return (getAttributes() & dwarf::DW_APPLE_PROPERTY_readwrite) != 0;
1005 bool isAssignObjCProperty() const {
1006 return (getAttributes() & dwarf::DW_APPLE_PROPERTY_assign) != 0;
1008 bool isRetainObjCProperty() const {
1009 return (getAttributes() & dwarf::DW_APPLE_PROPERTY_retain) != 0;
1011 bool isCopyObjCProperty() const {
1012 return (getAttributes() & dwarf::DW_APPLE_PROPERTY_copy) != 0;
1014 bool isNonAtomicObjCProperty() const {
1015 return (getAttributes() & dwarf::DW_APPLE_PROPERTY_nonatomic) != 0;
1018 /// \brief Get the type.
1020 /// \note Objective-C doesn't have an ODR, so there is no benefit in storing
1021 /// the type as a DITypeRef here.
1022 DIType getType() const { return getFieldAs<DIType>(2); }
1024 bool Verify() const;
1027 /// \brief An imported module (C++ using directive or similar).
1028 class DIImportedEntity : public DIDescriptor {
1029 friend class DIDescriptor;
1030 void printInternal(raw_ostream &OS) const;
1033 DIImportedEntity() = default;
1034 explicit DIImportedEntity(const MDNode *N) : DIDescriptor(N) {}
1035 DIScope getContext() const { return getFieldAs<DIScope>(1); }
1036 DIDescriptorRef getEntity() const { return getFieldAs<DIDescriptorRef>(2); }
1037 unsigned getLineNumber() const { return getHeaderFieldAs<unsigned>(1); }
1038 StringRef getName() const { return getHeaderField(2); }
1039 bool Verify() const;
1042 #undef RETURN_FROM_RAW
1043 #undef RETURN_DESCRIPTOR_FROM_RAW
1045 /// \brief Find subprogram that is enclosing this scope.
1046 DISubprogram getDISubprogram(const MDNode *Scope);
1048 /// \brief Find debug info for a given function.
1049 /// \returns a valid DISubprogram, if found. Otherwise, it returns an empty
1051 DISubprogram getDISubprogram(const Function *F);
1053 /// \brief Find underlying composite type.
1054 DICompositeType getDICompositeType(DIType T);
1056 /// \brief Create a new inlined variable based on current variable.
1058 /// @param DV Current Variable.
1059 /// @param InlinedScope Location at current variable is inlined.
1060 DIVariable createInlinedVariable(MDNode *DV, MDNode *InlinedScope,
1061 LLVMContext &VMContext);
1063 /// \brief Remove inlined scope from the variable.
1064 DIVariable cleanseInlinedVariable(MDNode *DV, LLVMContext &VMContext);
1066 /// \brief Generate map by visiting all retained types.
1067 DITypeIdentifierMap generateDITypeIdentifierMap(const NamedMDNode *CU_Nodes);
1069 /// \brief Strip debug info in the module if it exists.
1071 /// To do this, we remove all calls to the debugger intrinsics and any named
1072 /// metadata for debugging. We also remove debug locations for instructions.
1073 /// Return true if module is modified.
1074 bool StripDebugInfo(Module &M);
1076 /// \brief Return Debug Info Metadata Version by checking module flags.
1077 unsigned getDebugMetadataVersionFromModule(const Module &M);
1079 /// \brief Utility to find all debug info in a module.
1081 /// DebugInfoFinder tries to list all debug info MDNodes used in a module. To
1082 /// list debug info MDNodes used by an instruction, DebugInfoFinder uses
1083 /// processDeclare, processValue and processLocation to handle DbgDeclareInst,
1084 /// DbgValueInst and DbgLoc attached to instructions. processModule will go
1085 /// through all DICompileUnits in llvm.dbg.cu and list debug info MDNodes
1086 /// used by the CUs.
1087 class DebugInfoFinder {
1089 DebugInfoFinder() : TypeMapInitialized(false) {}
1091 /// \brief Process entire module and collect debug info anchors.
1092 void processModule(const Module &M);
1094 /// \brief Process DbgDeclareInst.
1095 void processDeclare(const Module &M, const DbgDeclareInst *DDI);
1096 /// \brief Process DbgValueInst.
1097 void processValue(const Module &M, const DbgValueInst *DVI);
1098 /// \brief Process DILocation.
1099 void processLocation(const Module &M, DILocation Loc);
1101 /// \brief Process DIExpression.
1102 void processExpression(DIExpression Expr);
1104 /// \brief Clear all lists.
1108 void InitializeTypeMap(const Module &M);
1110 void processType(DIType DT);
1111 void processSubprogram(DISubprogram SP);
1112 void processScope(DIScope Scope);
1113 bool addCompileUnit(DICompileUnit CU);
1114 bool addGlobalVariable(DIGlobalVariable DIG);
1115 bool addSubprogram(DISubprogram SP);
1116 bool addType(DIType DT);
1117 bool addScope(DIScope Scope);
1120 typedef SmallVectorImpl<DICompileUnit>::const_iterator compile_unit_iterator;
1121 typedef SmallVectorImpl<DISubprogram>::const_iterator subprogram_iterator;
1122 typedef SmallVectorImpl<DIGlobalVariable>::const_iterator
1123 global_variable_iterator;
1124 typedef SmallVectorImpl<DIType>::const_iterator type_iterator;
1125 typedef SmallVectorImpl<DIScope>::const_iterator scope_iterator;
1127 iterator_range<compile_unit_iterator> compile_units() const {
1128 return iterator_range<compile_unit_iterator>(CUs.begin(), CUs.end());
1131 iterator_range<subprogram_iterator> subprograms() const {
1132 return iterator_range<subprogram_iterator>(SPs.begin(), SPs.end());
1135 iterator_range<global_variable_iterator> global_variables() const {
1136 return iterator_range<global_variable_iterator>(GVs.begin(), GVs.end());
1139 iterator_range<type_iterator> types() const {
1140 return iterator_range<type_iterator>(TYs.begin(), TYs.end());
1143 iterator_range<scope_iterator> scopes() const {
1144 return iterator_range<scope_iterator>(Scopes.begin(), Scopes.end());
1147 unsigned compile_unit_count() const { return CUs.size(); }
1148 unsigned global_variable_count() const { return GVs.size(); }
1149 unsigned subprogram_count() const { return SPs.size(); }
1150 unsigned type_count() const { return TYs.size(); }
1151 unsigned scope_count() const { return Scopes.size(); }
1154 SmallVector<DICompileUnit, 8> CUs;
1155 SmallVector<DISubprogram, 8> SPs;
1156 SmallVector<DIGlobalVariable, 8> GVs;
1157 SmallVector<DIType, 8> TYs;
1158 SmallVector<DIScope, 8> Scopes;
1159 SmallPtrSet<MDNode *, 64> NodesSeen;
1160 DITypeIdentifierMap TypeIdentifierMap;
1162 /// \brief Specify if TypeIdentifierMap is initialized.
1163 bool TypeMapInitialized;
1166 DenseMap<const Function *, DISubprogram> makeSubprogramMap(const Module &M);
1168 } // end namespace llvm