1 //===- DebugInfo.h - Debug Information Helpers ------------------*- C++ -*-===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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
13 // DWARF information.
14 //
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/Metadata.h"
26 #include "llvm/Support/Casting.h"
27 #include "llvm/Support/Dwarf.h"
28 #include "llvm/Support/ErrorHandling.h"
29 #include <iterator>
31 namespace llvm {
32 class BasicBlock;
33 class Constant;
34 class Function;
35 class GlobalVariable;
36 class Module;
37 class Type;
38 class Value;
39 class DbgDeclareInst;
40 class DbgValueInst;
41 class Instruction;
42 class Metadata;
43 class MDNode;
44 class MDString;
45 class NamedMDNode;
46 class LLVMContext;
47 class raw_ostream;
49 class DIFile;
50 class DISubprogram;
51 class DILexicalBlock;
52 class DILexicalBlockFile;
53 class DIVariable;
54 class DIType;
55 class DIScope;
56 class DIObjCProperty;
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::forward_iterator_tag, StringRef, std::ptrdiff_t,
63 const StringRef *, StringRef> {
64 StringRef Header;
65 StringRef Current;
67 public:
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++() {
74 increment();
75 return *this;
76 }
77 DIHeaderFieldIterator operator++(int) {
78 DIHeaderFieldIterator X(*this);
79 increment();
80 return X;
81 }
82 bool operator==(const DIHeaderFieldIterator &X) const {
83 return Current.data() == X.Current.data();
84 }
85 bool operator!=(const DIHeaderFieldIterator &X) const {
86 return !(*this == X);
87 }
89 StringRef getHeader() const { return Header; }
90 StringRef getCurrent() const { return Current; }
91 StringRef getPrefix() const {
92 if (Current.begin() == Header.begin())
93 return StringRef();
94 return Header.slice(0, Current.begin() - Header.begin() - 1);
95 }
96 StringRef getSuffix() const {
97 if (Current.end() == Header.end())
98 return StringRef();
99 return Header.slice(Current.end() - Header.begin() + 1, StringRef::npos);
100 }
102 /// \brief Get the current field as a number.
103 ///
104 /// Convert the current field into a number. Return \c 0 on error.
105 template <class T> T getNumber() const {
106 T Int;
107 if (getCurrent().getAsInteger(0, Int))
108 return 0;
109 return Int;
110 }
112 private:
113 void increment() {
114 assert(Current.data() != nullptr && "Cannot increment past the end");
115 StringRef Suffix = getSuffix();
116 Current = Suffix.slice(0, Suffix.find('\0'));
117 }
118 };
120 /// \brief A thin wraper around MDNode to access encoded debug info.
121 ///
122 /// This should not be stored in a container, because the underlying MDNode may
123 /// change in certain situations.
124 class DIDescriptor {
125 // Befriends DIRef so DIRef can befriend the protected member
126 // function: getFieldAs<DIRef>.
127 template <typename T> friend class DIRef;
129 public:
130 /// \brief Accessibility flags.
131 ///
132 /// The three accessibility flags are mutually exclusive and rolled together
133 /// in the first two bits.
134 enum {
135 FlagAccessibility = 1 << 0 | 1 << 1,
136 FlagPrivate = 1,
137 FlagProtected = 2,
138 FlagPublic = 3,
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
153 };
155 protected:
156 const MDNode *DbgNode;
158 StringRef getStringField(unsigned Elt) const;
159 unsigned getUnsignedField(unsigned Elt) const {
160 return (unsigned)getUInt64Field(Elt);
161 }
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));
168 }
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);
175 public:
176 explicit DIDescriptor(const MDNode *N = nullptr) : DbgNode(N) {}
178 bool Verify() const;
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
185 // easily.
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 LLVM_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 {
195 return getStringField(0);
196 }
198 size_t getNumHeaderFields() const {
199 return std::distance(DIHeaderFieldIterator(getHeader()),
200 DIHeaderFieldIterator());
201 }
203 DIHeaderFieldIterator header_begin() const {
204 return DIHeaderFieldIterator(getHeader());
205 }
206 DIHeaderFieldIterator header_end() const { return DIHeaderFieldIterator(); }
208 DIHeaderFieldIterator getHeaderIterator(unsigned Index) const {
209 // Since callers expect an empty string for out-of-range accesses, we can't
210 // use std::advance() here.
211 for (auto I = header_begin(), E = header_end(); I != E; ++I, --Index)
212 if (!Index)
213 return I;
214 return header_end();
215 }
217 StringRef getHeaderField(unsigned Index) const {
218 return *getHeaderIterator(Index);
219 }
221 template <class T> T getHeaderFieldAs(unsigned Index) const {
222 return getHeaderIterator(Index).getNumber<T>();
223 }
225 uint16_t getTag() const { return getHeaderFieldAs<uint16_t>(0); }
227 bool isDerivedType() const;
228 bool isCompositeType() const;
229 bool isSubroutineType() const;
230 bool isBasicType() const;
231 bool isVariable() const;
232 bool isSubprogram() const;
233 bool isGlobalVariable() const;
234 bool isScope() const;
235 bool isFile() const;
236 bool isCompileUnit() const;
237 bool isNameSpace() const;
238 bool isLexicalBlockFile() const;
239 bool isLexicalBlock() const;
240 bool isSubrange() const;
241 bool isEnumerator() const;
242 bool isType() const;
243 bool isTemplateTypeParameter() const;
244 bool isTemplateValueParameter() const;
245 bool isObjCProperty() const;
246 bool isImportedEntity() const;
247 bool isExpression() const;
249 void print(raw_ostream &OS) const;
250 void dump() const;
252 /// \brief Replace all uses of debug info referenced by this descriptor.
253 void replaceAllUsesWith(LLVMContext &VMContext, DIDescriptor D);
254 void replaceAllUsesWith(MDNode *D);
255 };
257 /// \brief This is used to represent ranges, for array bounds.
258 class DISubrange : public DIDescriptor {
259 friend class DIDescriptor;
260 void printInternal(raw_ostream &OS) const;
262 public:
263 explicit DISubrange(const MDNode *N = nullptr) : DIDescriptor(N) {}
265 int64_t getLo() const { return getHeaderFieldAs<int64_t>(1); }
266 int64_t getCount() const { return getHeaderFieldAs<int64_t>(2); }
267 bool Verify() const;
268 };
270 /// \brief This descriptor holds an array of nodes with type T.
271 template <typename T> class DITypedArray : public DIDescriptor {
272 public:
273 explicit DITypedArray(const MDNode *N = nullptr) : DIDescriptor(N) {}
274 unsigned getNumElements() const {
275 return DbgNode ? DbgNode->getNumOperands() : 0;
276 }
277 T getElement(unsigned Idx) const {
278 return getFieldAs<T>(Idx);
279 }
280 };
282 typedef DITypedArray<DIDescriptor> DIArray;
284 /// \brief A wrapper for an enumerator (e.g. X and Y in 'enum {X,Y}').
285 ///
286 /// FIXME: it seems strange that this doesn't have either a reference to the
287 /// type/precision or a file/line pair for location info.
288 class DIEnumerator : public DIDescriptor {
289 friend class DIDescriptor;
290 void printInternal(raw_ostream &OS) const;
292 public:
293 explicit DIEnumerator(const MDNode *N = nullptr) : DIDescriptor(N) {}
295 StringRef getName() const { return getHeaderField(1); }
296 int64_t getEnumValue() const { return getHeaderFieldAs<int64_t>(2); }
297 bool Verify() const;
298 };
300 template <typename T> class DIRef;
301 typedef DIRef<DIScope> DIScopeRef;
302 typedef DIRef<DIType> DITypeRef;
303 typedef DITypedArray<DITypeRef> DITypeArray;
305 /// \brief A base class for various scopes.
306 ///
307 /// Although, implementation-wise, DIScope is the parent class of most
308 /// other DIxxx classes, including DIType and its descendants, most of
309 /// DIScope's descendants are not a substitutable subtype of
310 /// DIScope. The DIDescriptor::isScope() method only is true for
311 /// DIScopes that are scopes in the strict lexical scope sense
312 /// (DICompileUnit, DISubprogram, etc.), but not for, e.g., a DIType.
313 class DIScope : public DIDescriptor {
314 protected:
315 friend class DIDescriptor;
316 void printInternal(raw_ostream &OS) const;
318 public:
319 explicit DIScope(const MDNode *N = nullptr) : DIDescriptor(N) {}
321 /// \brief Get the parent scope.
322 ///
323 /// Gets the parent scope for this scope node or returns a default
324 /// constructed scope.
325 DIScopeRef getContext() const;
326 /// \brief Get the scope name.
327 ///
328 /// If the scope node has a name, return that, else return an empty string.
329 StringRef getName() const;
330 StringRef getFilename() const;
331 StringRef getDirectory() const;
333 /// \brief Generate a reference to this DIScope.
334 ///
335 /// Uses the type identifier instead of the actual MDNode if possible, to
336 /// help type uniquing.
337 DIScopeRef getRef() const;
338 };
340 /// \brief Represents reference to a DIDescriptor.
341 ///
342 /// Abstracts over direct and identifier-based metadata references.
343 template <typename T> class DIRef {
344 template <typename DescTy>
345 friend DescTy DIDescriptor::getFieldAs(unsigned Elt) const;
346 friend DIScopeRef DIScope::getContext() const;
347 friend DIScopeRef DIScope::getRef() const;
348 friend class DIType;
350 /// \brief Val can be either a MDNode or a MDString.
351 ///
352 /// In the latter, MDString specifies the type identifier.
353 const Metadata *Val;
354 explicit DIRef(const Metadata *V);
356 public:
357 T resolve(const DITypeIdentifierMap &Map) const;
358 StringRef getName() const;
359 operator Metadata *() const { return const_cast<Metadata *>(Val); }
360 };
362 template <typename T>
363 T DIRef<T>::resolve(const DITypeIdentifierMap &Map) const {
364 if (!Val)
365 return T();
367 if (const MDNode *MD = dyn_cast<MDNode>(Val))
368 return T(MD);
370 const MDString *MS = cast<MDString>(Val);
371 // Find the corresponding MDNode.
372 DITypeIdentifierMap::const_iterator Iter = Map.find(MS);
373 assert(Iter != Map.end() && "Identifier not in the type map?");
374 assert(DIDescriptor(Iter->second).isType() &&
375 "MDNode in DITypeIdentifierMap should be a DIType.");
376 return T(Iter->second);
377 }
379 template <typename T> StringRef DIRef<T>::getName() const {
380 if (!Val)
381 return StringRef();
383 if (const MDNode *MD = dyn_cast<MDNode>(Val))
384 return T(MD).getName();
386 const MDString *MS = cast<MDString>(Val);
387 return MS->getString();
388 }
390 /// \brief Handle fields that are references to DIScopes.
391 template <> DIScopeRef DIDescriptor::getFieldAs<DIScopeRef>(unsigned Elt) const;
392 /// \brief Specialize DIRef constructor for DIScopeRef.
393 template <> DIRef<DIScope>::DIRef(const Metadata *V);
395 /// \brief Handle fields that are references to DITypes.
396 template <> DITypeRef DIDescriptor::getFieldAs<DITypeRef>(unsigned Elt) const;
397 /// \brief Specialize DIRef constructor for DITypeRef.
398 template <> DIRef<DIType>::DIRef(const Metadata *V);
400 /// \brief This is a wrapper for a type.
401 ///
402 /// FIXME: Types should be factored much better so that CV qualifiers and
403 /// others do not require a huge and empty descriptor full of zeros.
404 class DIType : public DIScope {
405 protected:
406 friend class DIDescriptor;
407 void printInternal(raw_ostream &OS) const;
409 public:
410 explicit DIType(const MDNode *N = nullptr) : DIScope(N) {}
411 operator DITypeRef () const {
412 assert(isType() &&
413 "constructing DITypeRef from an MDNode that is not a type");
414 return DITypeRef(&*getRef());
415 }
417 bool Verify() const;
419 DIScopeRef getContext() const { return getFieldAs<DIScopeRef>(2); }
420 StringRef getName() const { return getHeaderField(1); }
421 unsigned getLineNumber() const {
422 return getHeaderFieldAs<unsigned>(2);
423 }
424 uint64_t getSizeInBits() const {
425 return getHeaderFieldAs<unsigned>(3);
426 }
427 uint64_t getAlignInBits() const {
428 return getHeaderFieldAs<unsigned>(4);
429 }
430 // FIXME: Offset is only used for DW_TAG_member nodes. Making every type
431 // carry this is just plain insane.
432 uint64_t getOffsetInBits() const {
433 return getHeaderFieldAs<unsigned>(5);
434 }
435 unsigned getFlags() const { return getHeaderFieldAs<unsigned>(6); }
436 bool isPrivate() const {
437 return (getFlags() & FlagAccessibility) == FlagPrivate;
438 }
439 bool isProtected() const {
440 return (getFlags() & FlagAccessibility) == FlagProtected;
441 }
442 bool isPublic() const {
443 return (getFlags() & FlagAccessibility) == FlagPublic;
444 }
445 bool isForwardDecl() const { return (getFlags() & FlagFwdDecl) != 0; }
446 bool isAppleBlockExtension() const {
447 return (getFlags() & FlagAppleBlock) != 0;
448 }
449 bool isBlockByrefStruct() const {
450 return (getFlags() & FlagBlockByrefStruct) != 0;
451 }
452 bool isVirtual() const { return (getFlags() & FlagVirtual) != 0; }
453 bool isArtificial() const { return (getFlags() & FlagArtificial) != 0; }
454 bool isObjectPointer() const { return (getFlags() & FlagObjectPointer) != 0; }
455 bool isObjcClassComplete() const {
456 return (getFlags() & FlagObjcClassComplete) != 0;
457 }
458 bool isVector() const { return (getFlags() & FlagVector) != 0; }
459 bool isStaticMember() const { return (getFlags() & FlagStaticMember) != 0; }
460 bool isLValueReference() const {
461 return (getFlags() & FlagLValueReference) != 0;
462 }
463 bool isRValueReference() const {
464 return (getFlags() & FlagRValueReference) != 0;
465 }
466 bool isValid() const { return DbgNode && isType(); }
467 };
469 /// \brief A basic type, like 'int' or 'float'.
470 class DIBasicType : public DIType {
471 public:
472 explicit DIBasicType(const MDNode *N = nullptr) : DIType(N) {}
474 unsigned getEncoding() const { return getHeaderFieldAs<unsigned>(7); }
476 bool Verify() const;
477 };
479 /// \brief A simple derived type
480 ///
481 /// Like a const qualified type, a typedef, a pointer or reference, et cetera.
482 /// Or, a data member of a class/struct/union.
483 class DIDerivedType : public DIType {
484 friend class DIDescriptor;
485 void printInternal(raw_ostream &OS) const;
487 public:
488 explicit DIDerivedType(const MDNode *N = nullptr) : DIType(N) {}
490 DITypeRef getTypeDerivedFrom() const { return getFieldAs<DITypeRef>(3); }
492 /// \brief Return property node, if this ivar is associated with one.
493 MDNode *getObjCProperty() const;
495 DITypeRef getClassType() const {
496 assert(getTag() == dwarf::DW_TAG_ptr_to_member_type);
497 return getFieldAs<DITypeRef>(4);
498 }
500 Constant *getConstant() const {
501 assert((getTag() == dwarf::DW_TAG_member) && isStaticMember());
502 return getConstantField(4);
503 }
505 bool Verify() const;
506 };
508 /// \brief Types that refer to multiple other types.
509 ///
510 /// This descriptor holds a type that can refer to multiple other types, like a
511 /// function or struct.
512 ///
513 /// DICompositeType is derived from DIDerivedType because some
514 /// composite types (such as enums) can be derived from basic types
515 // FIXME: Make this derive from DIType directly & just store the
516 // base type in a single DIType field.
517 class DICompositeType : public DIDerivedType {
518 friend class DIBuilder;
519 friend class DIDescriptor;
520 void printInternal(raw_ostream &OS) const;
522 /// \brief Set the array of member DITypes.
523 void setArraysHelper(MDNode *Elements, MDNode *TParams);
525 public:
526 explicit DICompositeType(const MDNode *N = nullptr) : DIDerivedType(N) {}
528 DIArray getElements() const {
529 assert(!isSubroutineType() && "no elements for DISubroutineType");
530 return getFieldAs<DIArray>(4);
531 }
533 private:
534 template <typename T>
535 void setArrays(DITypedArray<T> Elements, DIArray TParams = DIArray()) {
536 assert((!TParams || DbgNode->getNumOperands() == 8) &&
537 "If you're setting the template parameters this should include a slot "
538 "for that!");
539 setArraysHelper(Elements, TParams);
540 }
542 public:
543 unsigned getRunTimeLang() const {
544 return getHeaderFieldAs<unsigned>(7);
545 }
546 DITypeRef getContainingType() const { return getFieldAs<DITypeRef>(5); }
548 private:
549 /// \brief Set the containing type.
550 void setContainingType(DICompositeType ContainingType);
552 public:
553 DIArray getTemplateParams() const { return getFieldAs<DIArray>(6); }
554 MDString *getIdentifier() const;
556 bool Verify() const;
557 };
559 class DISubroutineType : public DICompositeType {
560 public:
561 explicit DISubroutineType(const MDNode *N = nullptr) : DICompositeType(N) {}
562 DITypedArray<DITypeRef> getTypeArray() const {
563 return getFieldAs<DITypedArray<DITypeRef>>(4);
564 }
565 };
567 /// \brief This is a wrapper for a file.
568 class DIFile : public DIScope {
569 friend class DIDescriptor;
571 public:
572 explicit DIFile(const MDNode *N = nullptr) : DIScope(N) {}
574 /// \brief Retrieve the MDNode for the directory/file pair.
575 MDNode *getFileNode() const;
576 bool Verify() const;
577 };
579 /// \brief A wrapper for a compile unit.
580 class DICompileUnit : public DIScope {
581 friend class DIDescriptor;
582 void printInternal(raw_ostream &OS) const;
584 public:
585 explicit DICompileUnit(const MDNode *N = nullptr) : DIScope(N) {}
587 dwarf::SourceLanguage getLanguage() const {
588 return static_cast<dwarf::SourceLanguage>(getHeaderFieldAs<unsigned>(1));
589 }
590 StringRef getProducer() const { return getHeaderField(2); }
592 bool isOptimized() const { return getHeaderFieldAs<bool>(3) != 0; }
593 StringRef getFlags() const { return getHeaderField(4); }
594 unsigned getRunTimeVersion() const { return getHeaderFieldAs<unsigned>(5); }
596 DIArray getEnumTypes() const;
597 DIArray getRetainedTypes() const;
598 DIArray getSubprograms() const;
599 DIArray getGlobalVariables() const;
600 DIArray getImportedEntities() const;
602 void replaceSubprograms(DIArray Subprograms);
603 void replaceGlobalVariables(DIArray GlobalVariables);
605 StringRef getSplitDebugFilename() const { return getHeaderField(6); }
606 unsigned getEmissionKind() const { return getHeaderFieldAs<unsigned>(7); }
608 bool Verify() const;
609 };
611 /// \brief This is a wrapper for a subprogram (e.g. a function).
612 class DISubprogram : public DIScope {
613 friend class DIDescriptor;
614 void printInternal(raw_ostream &OS) const;
616 public:
617 explicit DISubprogram(const MDNode *N = nullptr) : DIScope(N) {}
619 StringRef getName() const { return getHeaderField(1); }
620 StringRef getDisplayName() const { return getHeaderField(2); }
621 StringRef getLinkageName() const { return getHeaderField(3); }
622 unsigned getLineNumber() const { return getHeaderFieldAs<unsigned>(4); }
624 /// \brief Check if this is local (like 'static' in C).
625 unsigned isLocalToUnit() const { return getHeaderFieldAs<unsigned>(5); }
626 unsigned isDefinition() const { return getHeaderFieldAs<unsigned>(6); }
628 unsigned getVirtuality() const { return getHeaderFieldAs<unsigned>(7); }
629 unsigned getVirtualIndex() const { return getHeaderFieldAs<unsigned>(8); }
631 unsigned getFlags() const { return getHeaderFieldAs<unsigned>(9); }
633 unsigned isOptimized() const { return getHeaderFieldAs<bool>(10); }
635 /// \brief Get the beginning of the scope of the function (not the name).
636 unsigned getScopeLineNumber() const { return getHeaderFieldAs<unsigned>(11); }
638 DIScopeRef getContext() const { return getFieldAs<DIScopeRef>(2); }
639 DISubroutineType getType() const { return getFieldAs<DISubroutineType>(3); }
641 DITypeRef getContainingType() const { return getFieldAs<DITypeRef>(4); }
643 bool Verify() const;
645 /// \brief Check if this provides debugging information for the function F.
646 bool describes(const Function *F);
648 Function *getFunction() const { return getFunctionField(5); }
649 void replaceFunction(Function *F) { replaceFunctionField(5, F); }
650 DIArray getTemplateParams() const { return getFieldAs<DIArray>(6); }
651 DISubprogram getFunctionDeclaration() const {
652 return getFieldAs<DISubprogram>(7);
653 }
654 MDNode *getVariablesNodes() const;
655 DIArray getVariables() const;
657 unsigned isArtificial() const { return (getFlags() & FlagArtificial) != 0; }
658 /// \brief Check for the "private" access specifier.
659 bool isPrivate() const {
660 return (getFlags() & FlagAccessibility) == FlagPrivate;
661 }
662 /// \brief Check for the "protected" access specifier.
663 bool isProtected() const {
664 return (getFlags() & FlagAccessibility) == FlagProtected;
665 }
666 /// \brief Check for the "public" access specifier.
667 bool isPublic() const {
668 return (getFlags() & FlagAccessibility) == FlagPublic;
669 }
670 /// \brief Check for "explicit".
671 bool isExplicit() const { return (getFlags() & FlagExplicit) != 0; }
672 /// \brief Check if this is prototyped.
673 bool isPrototyped() const { return (getFlags() & FlagPrototyped) != 0; }
675 /// \brief Check if this is reference-qualified.
676 ///
677 /// Return true if this subprogram is a C++11 reference-qualified non-static
678 /// member function (void foo() &).
679 unsigned isLValueReference() const {
680 return (getFlags() & FlagLValueReference) != 0;
681 }
683 /// \brief Check if this is rvalue-reference-qualified.
684 ///
685 /// Return true if this subprogram is a C++11 rvalue-reference-qualified
686 /// non-static member function (void foo() &&).
687 unsigned isRValueReference() const {
688 return (getFlags() & FlagRValueReference) != 0;
689 }
691 };
693 /// \brief This is a wrapper for a lexical block.
694 class DILexicalBlock : public DIScope {
695 public:
696 explicit DILexicalBlock(const MDNode *N = nullptr) : DIScope(N) {}
697 DIScope getContext() const { return getFieldAs<DIScope>(2); }
698 unsigned getLineNumber() const {
699 return getHeaderFieldAs<unsigned>(1);
700 }
701 unsigned getColumnNumber() const {
702 return getHeaderFieldAs<unsigned>(2);
703 }
704 bool Verify() const;
705 };
707 /// \brief This is a wrapper for a lexical block with a filename change.
708 class DILexicalBlockFile : public DIScope {
709 public:
710 explicit DILexicalBlockFile(const MDNode *N = nullptr) : DIScope(N) {}
711 DIScope getContext() const {
712 if (getScope().isSubprogram())
713 return getScope();
714 return getScope().getContext();
715 }
716 unsigned getLineNumber() const { return getScope().getLineNumber(); }
717 unsigned getColumnNumber() const { return getScope().getColumnNumber(); }
718 DILexicalBlock getScope() const { return getFieldAs<DILexicalBlock>(2); }
719 unsigned getDiscriminator() const { return getHeaderFieldAs<unsigned>(1); }
720 bool Verify() const;
721 };
723 /// \brief A wrapper for a C++ style name space.
724 class DINameSpace : public DIScope {
725 friend class DIDescriptor;
726 void printInternal(raw_ostream &OS) const;
728 public:
729 explicit DINameSpace(const MDNode *N = nullptr) : DIScope(N) {}
730 StringRef getName() const { return getHeaderField(1); }
731 unsigned getLineNumber() const { return getHeaderFieldAs<unsigned>(2); }
732 DIScope getContext() const { return getFieldAs<DIScope>(2); }
733 bool Verify() const;
734 };
736 /// \brief This is a wrapper for template type parameter.
737 class DITemplateTypeParameter : public DIDescriptor {
738 public:
739 explicit DITemplateTypeParameter(const MDNode *N = nullptr)
740 : DIDescriptor(N) {}
742 StringRef getName() const { return getHeaderField(1); }
743 unsigned getLineNumber() const { return getHeaderFieldAs<unsigned>(2); }
744 unsigned getColumnNumber() const { return getHeaderFieldAs<unsigned>(3); }
746 DIScopeRef getContext() const { return getFieldAs<DIScopeRef>(1); }
747 DITypeRef getType() const { return getFieldAs<DITypeRef>(2); }
748 StringRef getFilename() const { return getFieldAs<DIFile>(3).getFilename(); }
749 StringRef getDirectory() const {
750 return getFieldAs<DIFile>(3).getDirectory();
751 }
752 bool Verify() const;
753 };
755 /// \brief This is a wrapper for template value parameter.
756 class DITemplateValueParameter : public DIDescriptor {
757 public:
758 explicit DITemplateValueParameter(const MDNode *N = nullptr)
759 : DIDescriptor(N) {}
761 StringRef getName() const { return getHeaderField(1); }
762 unsigned getLineNumber() const { return getHeaderFieldAs<unsigned>(2); }
763 unsigned getColumnNumber() const { return getHeaderFieldAs<unsigned>(3); }
765 DIScopeRef getContext() const { return getFieldAs<DIScopeRef>(1); }
766 DITypeRef getType() const { return getFieldAs<DITypeRef>(2); }
767 Metadata *getValue() const;
768 StringRef getFilename() const { return getFieldAs<DIFile>(4).getFilename(); }
769 StringRef getDirectory() const {
770 return getFieldAs<DIFile>(4).getDirectory();
771 }
772 bool Verify() const;
773 };
775 /// \brief This is a wrapper for a global variable.
776 class DIGlobalVariable : public DIDescriptor {
777 friend class DIDescriptor;
778 void printInternal(raw_ostream &OS) const;
780 public:
781 explicit DIGlobalVariable(const MDNode *N = nullptr) : DIDescriptor(N) {}
783 StringRef getName() const { return getHeaderField(1); }
784 StringRef getDisplayName() const { return getHeaderField(2); }
785 StringRef getLinkageName() const { return getHeaderField(3); }
786 unsigned getLineNumber() const { return getHeaderFieldAs<unsigned>(4); }
787 unsigned isLocalToUnit() const { return getHeaderFieldAs<bool>(5); }
788 unsigned isDefinition() const { return getHeaderFieldAs<bool>(6); }
790 DIScope getContext() const { return getFieldAs<DIScope>(1); }
791 StringRef getFilename() const { return getFieldAs<DIFile>(2).getFilename(); }
792 StringRef getDirectory() const {
793 return getFieldAs<DIFile>(2).getDirectory();
794 }
795 DITypeRef getType() const { return getFieldAs<DITypeRef>(3); }
797 GlobalVariable *getGlobal() const { return getGlobalVariableField(4); }
798 Constant *getConstant() const { return getConstantField(4); }
799 DIDerivedType getStaticDataMemberDeclaration() const {
800 return getFieldAs<DIDerivedType>(5);
801 }
803 bool Verify() const;
804 };
806 /// \brief This is a wrapper for a variable (e.g. parameter, local, global etc).
807 class DIVariable : public DIDescriptor {
808 friend class DIDescriptor;
809 void printInternal(raw_ostream &OS) const;
811 public:
812 explicit DIVariable(const MDNode *N = nullptr) : DIDescriptor(N) {}
814 StringRef getName() const { return getHeaderField(1); }
815 unsigned getLineNumber() const {
816 // FIXME: Line number and arg number shouldn't be merged together like this.
817 return (getHeaderFieldAs<unsigned>(2) << 8) >> 8;
818 }
819 unsigned getArgNumber() const { return getHeaderFieldAs<unsigned>(2) >> 24; }
821 DIScope getContext() const { return getFieldAs<DIScope>(1); }
822 DIFile getFile() const { return getFieldAs<DIFile>(2); }
823 DITypeRef getType() const { return getFieldAs<DITypeRef>(3); }
825 /// \brief Return true if this variable is marked as "artificial".
826 bool isArtificial() const {
827 return (getHeaderFieldAs<unsigned>(3) & FlagArtificial) != 0;
828 }
830 bool isObjectPointer() const {
831 return (getHeaderFieldAs<unsigned>(3) & FlagObjectPointer) != 0;
832 }
834 /// \brief If this variable is inlined then return inline location.
835 MDNode *getInlinedAt() const;
837 bool Verify() const;
839 /// \brief Check if this is a "__block" variable (Apple Blocks).
840 bool isBlockByrefVariable(const DITypeIdentifierMap &Map) const {
841 return (getType().resolve(Map)).isBlockByrefStruct();
842 }
844 /// \brief Check if this is an inlined function argument.
845 bool isInlinedFnArgument(const Function *CurFn);
847 /// \brief Return the size reported by the variable's type.
848 unsigned getSizeInBits(const DITypeIdentifierMap &Map);
850 void printExtendedName(raw_ostream &OS) const;
851 };
853 /// \brief A complex location expression.
854 class DIExpression : public DIDescriptor {
855 friend class DIDescriptor;
856 void printInternal(raw_ostream &OS) const;
858 public:
859 explicit DIExpression(const MDNode *N = nullptr) : DIDescriptor(N) {}
861 bool Verify() const;
863 /// \brief Return the number of elements in the complex expression.
864 unsigned getNumElements() const {
865 if (!DbgNode)
866 return 0;
867 unsigned N = getNumHeaderFields();
868 assert(N > 0 && "missing tag");
869 return N - 1;
870 }
872 /// \brief return the Idx'th complex address element.
873 uint64_t getElement(unsigned Idx) const;
875 /// \brief Return whether this is a piece of an aggregate variable.
876 bool isVariablePiece() const;
877 /// \brief Return the offset of this piece in bytes.
878 uint64_t getPieceOffset() const;
879 /// \brief Return the size of this piece in bytes.
880 uint64_t getPieceSize() const;
882 /// \brief An iterator for DIExpression elements.
883 class iterator
884 : public std::iterator<std::forward_iterator_tag, StringRef, unsigned,
885 const uint64_t *, uint64_t> {
886 DIHeaderFieldIterator I;
887 iterator(DIHeaderFieldIterator I) : I(I) {}
888 public:
889 iterator() {}
890 iterator(const DIExpression &Expr) : I(++Expr.header_begin()) {}
891 uint64_t operator*() const { return I.getNumber<uint64_t>(); }
892 iterator &operator++() {
893 increment();
894 return *this;
895 }
896 iterator operator++(int) {
897 iterator X(*this);
898 increment();
899 return X;
900 }
901 bool operator==(const iterator &X) const {
902 return I == X.I;
903 }
904 bool operator!=(const iterator &X) const {
905 return !(*this == X);
906 }
908 uint64_t getArg(unsigned N) const {
909 auto In = I;
910 std::advance(In, N);
911 return In.getNumber<uint64_t>();
912 }
914 const DIHeaderFieldIterator& getBase() const { return I; }
916 private:
917 void increment() {
918 switch (**this) {
919 case dwarf::DW_OP_piece: std::advance(I, 3); break;
920 case dwarf::DW_OP_plus: std::advance(I, 2); break;
921 case dwarf::DW_OP_deref: std::advance(I, 1); break;
922 default:
923 assert("unsupported operand");
924 }
925 }
926 };
928 iterator begin() const;
929 iterator end() const;
930 };
932 /// \brief This object holds location information.
933 ///
934 /// This object is not associated with any DWARF tag.
935 class DILocation : public DIDescriptor {
936 public:
937 explicit DILocation(const MDNode *N) : DIDescriptor(N) {}
939 unsigned getLineNumber() const {
940 if (auto *L = dyn_cast_or_null<MDLocation>(DbgNode))
941 return L->getLine();
942 return 0;
943 }
944 unsigned getColumnNumber() const {
945 if (auto *L = dyn_cast_or_null<MDLocation>(DbgNode))
946 return L->getColumn();
947 return 0;
948 }
949 DIScope getScope() const {
950 if (auto *L = dyn_cast_or_null<MDLocation>(DbgNode))
951 return DIScope(dyn_cast_or_null<MDNode>(L->getScope()));
952 return DIScope(nullptr);
953 }
954 DILocation getOrigLocation() const {
955 if (auto *L = dyn_cast_or_null<MDLocation>(DbgNode))
956 return DILocation(dyn_cast_or_null<MDNode>(L->getInlinedAt()));
957 return DILocation(nullptr);
958 }
959 StringRef getFilename() const { return getScope().getFilename(); }
960 StringRef getDirectory() const { return getScope().getDirectory(); }
961 bool Verify() const;
962 bool atSameLineAs(const DILocation &Other) const {
963 return (getLineNumber() == Other.getLineNumber() &&
964 getFilename() == Other.getFilename());
965 }
966 /// \brief Get the DWAF discriminator.
967 ///
968 /// DWARF discriminators are used to distinguish identical file locations for
969 /// instructions that are on different basic blocks. If two instructions are
970 /// inside the same lexical block and are in different basic blocks, we
971 /// create a new lexical block with identical location as the original but
972 /// with a different discriminator value
973 /// (lib/Transforms/Util/AddDiscriminators.cpp for details).
974 unsigned getDiscriminator() const {
975 // Since discriminators are associated with lexical blocks, make
976 // sure this location is a lexical block before retrieving its
977 // value.
978 return getScope().isLexicalBlockFile()
979 ? DILexicalBlockFile(
980 cast<MDNode>(cast<MDLocation>(DbgNode)->getScope()))
981 .getDiscriminator()
982 : 0;
983 }
985 /// \brief Generate a new discriminator value for this location.
986 unsigned computeNewDiscriminator(LLVMContext &Ctx);
988 /// \brief Return a copy of this location with a different scope.
989 DILocation copyWithNewScope(LLVMContext &Ctx, DILexicalBlockFile NewScope);
990 };
992 class DIObjCProperty : public DIDescriptor {
993 friend class DIDescriptor;
994 void printInternal(raw_ostream &OS) const;
996 public:
997 explicit DIObjCProperty(const MDNode *N) : DIDescriptor(N) {}
999 StringRef getObjCPropertyName() const { return getHeaderField(1); }
1000 DIFile getFile() const { return getFieldAs<DIFile>(1); }
1001 unsigned getLineNumber() const { return getHeaderFieldAs<unsigned>(2); }
1003 StringRef getObjCPropertyGetterName() const { return getHeaderField(3); }
1004 StringRef getObjCPropertySetterName() const { return getHeaderField(4); }
1005 unsigned getAttributes() const { return getHeaderFieldAs<unsigned>(5); }
1006 bool isReadOnlyObjCProperty() const {
1007 return (getAttributes() & dwarf::DW_APPLE_PROPERTY_readonly) != 0;
1008 }
1009 bool isReadWriteObjCProperty() const {
1010 return (getAttributes() & dwarf::DW_APPLE_PROPERTY_readwrite) != 0;
1011 }
1012 bool isAssignObjCProperty() const {
1013 return (getAttributes() & dwarf::DW_APPLE_PROPERTY_assign) != 0;
1014 }
1015 bool isRetainObjCProperty() const {
1016 return (getAttributes() & dwarf::DW_APPLE_PROPERTY_retain) != 0;
1017 }
1018 bool isCopyObjCProperty() const {
1019 return (getAttributes() & dwarf::DW_APPLE_PROPERTY_copy) != 0;
1020 }
1021 bool isNonAtomicObjCProperty() const {
1022 return (getAttributes() & dwarf::DW_APPLE_PROPERTY_nonatomic) != 0;
1023 }
1025 /// \brief Get the type.
1026 ///
1027 /// \note Objective-C doesn't have an ODR, so there is no benefit in storing
1028 /// the type as a DITypeRef here.
1029 DIType getType() const { return getFieldAs<DIType>(2); }
1031 bool Verify() const;
1032 };
1034 /// \brief An imported module (C++ using directive or similar).
1035 class DIImportedEntity : public DIDescriptor {
1036 friend class DIDescriptor;
1037 void printInternal(raw_ostream &OS) const;
1039 public:
1040 explicit DIImportedEntity(const MDNode *N) : DIDescriptor(N) {}
1041 DIScope getContext() const { return getFieldAs<DIScope>(1); }
1042 DIScopeRef getEntity() const { return getFieldAs<DIScopeRef>(2); }
1043 unsigned getLineNumber() const { return getHeaderFieldAs<unsigned>(1); }
1044 StringRef getName() const { return getHeaderField(2); }
1045 bool Verify() const;
1046 };
1048 /// \brief Find subprogram that is enclosing this scope.
1049 DISubprogram getDISubprogram(const MDNode *Scope);
1051 /// \brief Find debug info for a given function.
1052 /// \returns a valid DISubprogram, if found. Otherwise, it returns an empty
1053 /// DISubprogram.
1054 DISubprogram getDISubprogram(const Function *F);
1056 /// \brief Find underlying composite type.
1057 DICompositeType getDICompositeType(DIType T);
1059 /// \brief Create a new inlined variable based on current variable.
1060 ///
1061 /// @param DV Current Variable.
1062 /// @param InlinedScope Location at current variable is inlined.
1063 DIVariable createInlinedVariable(MDNode *DV, MDNode *InlinedScope,
1064 LLVMContext &VMContext);
1066 /// \brief Remove inlined scope from the variable.
1067 DIVariable cleanseInlinedVariable(MDNode *DV, LLVMContext &VMContext);
1069 /// \brief Generate map by visiting all retained types.
1070 DITypeIdentifierMap generateDITypeIdentifierMap(const NamedMDNode *CU_Nodes);
1072 /// \brief Strip debug info in the module if it exists.
1073 ///
1074 /// To do this, we remove all calls to the debugger intrinsics and any named
1075 /// metadata for debugging. We also remove debug locations for instructions.
1076 /// Return true if module is modified.
1077 bool StripDebugInfo(Module &M);
1079 /// \brief Return Debug Info Metadata Version by checking module flags.
1080 unsigned getDebugMetadataVersionFromModule(const Module &M);
1082 /// \brief Utility to find all debug info in a module.
1083 ///
1084 /// DebugInfoFinder tries to list all debug info MDNodes used in a module. To
1085 /// list debug info MDNodes used by an instruction, DebugInfoFinder uses
1086 /// processDeclare, processValue and processLocation to handle DbgDeclareInst,
1087 /// DbgValueInst and DbgLoc attached to instructions. processModule will go
1088 /// through all DICompileUnits in llvm.dbg.cu and list debug info MDNodes
1089 /// used by the CUs.
1090 class DebugInfoFinder {
1091 public:
1092 DebugInfoFinder() : TypeMapInitialized(false) {}
1094 /// \brief Process entire module and collect debug info anchors.
1095 void processModule(const Module &M);
1097 /// \brief Process DbgDeclareInst.
1098 void processDeclare(const Module &M, const DbgDeclareInst *DDI);
1099 /// \brief Process DbgValueInst.
1100 void processValue(const Module &M, const DbgValueInst *DVI);
1101 /// \brief Process DILocation.
1102 void processLocation(const Module &M, DILocation Loc);
1104 /// \brief Process DIExpression.
1105 void processExpression(DIExpression Expr);
1107 /// \brief Clear all lists.
1108 void reset();
1110 private:
1111 void InitializeTypeMap(const Module &M);
1113 void processType(DIType DT);
1114 void processSubprogram(DISubprogram SP);
1115 void processScope(DIScope Scope);
1116 bool addCompileUnit(DICompileUnit CU);
1117 bool addGlobalVariable(DIGlobalVariable DIG);
1118 bool addSubprogram(DISubprogram SP);
1119 bool addType(DIType DT);
1120 bool addScope(DIScope Scope);
1122 public:
1123 typedef SmallVectorImpl<DICompileUnit>::const_iterator compile_unit_iterator;
1124 typedef SmallVectorImpl<DISubprogram>::const_iterator subprogram_iterator;
1125 typedef SmallVectorImpl<DIGlobalVariable>::const_iterator global_variable_iterator;
1126 typedef SmallVectorImpl<DIType>::const_iterator type_iterator;
1127 typedef SmallVectorImpl<DIScope>::const_iterator scope_iterator;
1129 iterator_range<compile_unit_iterator> compile_units() const {
1130 return iterator_range<compile_unit_iterator>(CUs.begin(), CUs.end());
1131 }
1133 iterator_range<subprogram_iterator> subprograms() const {
1134 return iterator_range<subprogram_iterator>(SPs.begin(), SPs.end());
1135 }
1137 iterator_range<global_variable_iterator> global_variables() const {
1138 return iterator_range<global_variable_iterator>(GVs.begin(), GVs.end());
1139 }
1141 iterator_range<type_iterator> types() const {
1142 return iterator_range<type_iterator>(TYs.begin(), TYs.end());
1143 }
1145 iterator_range<scope_iterator> scopes() const {
1146 return iterator_range<scope_iterator>(Scopes.begin(), Scopes.end());
1147 }
1149 unsigned compile_unit_count() const { return CUs.size(); }
1150 unsigned global_variable_count() const { return GVs.size(); }
1151 unsigned subprogram_count() const { return SPs.size(); }
1152 unsigned type_count() const { return TYs.size(); }
1153 unsigned scope_count() const { return Scopes.size(); }
1155 private:
1156 SmallVector<DICompileUnit, 8> CUs;
1157 SmallVector<DISubprogram, 8> SPs;
1158 SmallVector<DIGlobalVariable, 8> GVs;
1159 SmallVector<DIType, 8> TYs;
1160 SmallVector<DIScope, 8> Scopes;
1161 SmallPtrSet<MDNode *, 64> NodesSeen;
1162 DITypeIdentifierMap TypeIdentifierMap;
1164 /// \brief Specify if TypeIdentifierMap is initialized.
1165 bool TypeMapInitialized;
1166 };
1168 DenseMap<const Function *, DISubprogram> makeSubprogramMap(const Module &M);
1170 } // end namespace llvm
1172 #endif