]> Gitweb @ Texas Instruments - Open Source Git Repositories - git.TI.com/gitweb - opencl/llvm.git/blob - include/llvm/IR/DebugInfo.h
Revert "Revert "DI: Fold constant arguments into a single MDString""
[opencl/llvm.git] / include / llvm / IR / DebugInfo.h
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/iterator_range.h"
22 #include "llvm/ADT/SmallPtrSet.h"
23 #include "llvm/ADT/SmallVector.h"
24 #include "llvm/ADT/StringRef.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 MDNode;
43 class MDString;
44 class NamedMDNode;
45 class LLVMContext;
46 class raw_ostream;
48 class DIFile;
49 class DISubprogram;
50 class DILexicalBlock;
51 class DILexicalBlockFile;
52 class DIVariable;
53 class DIType;
54 class DIScope;
55 class DIObjCProperty;
57 /// Maps from type identifier to the actual MDNode.
58 typedef DenseMap<const MDString *, MDNode *> DITypeIdentifierMap;
60 class DIHeaderFieldIterator
61     : public std::iterator<std::input_iterator_tag, StringRef, std::ptrdiff_t,
62                            const StringRef *, StringRef> {
63   StringRef Header;
64   StringRef Current;
66 public:
67   DIHeaderFieldIterator() {}
68   DIHeaderFieldIterator(StringRef Header)
69       : Header(Header), Current(Header.slice(0, Header.find('\0'))) {}
70   StringRef operator*() const { return Current; }
71   const StringRef * operator->() const { return &Current; }
72   DIHeaderFieldIterator &operator++() {
73     increment();
74     return *this;
75   }
76   DIHeaderFieldIterator operator++(int) {
77     DIHeaderFieldIterator X(*this);
78     increment();
79     return X;
80   }
81   bool operator==(const DIHeaderFieldIterator &X) const {
82     return Current.data() == X.Current.data();
83   }
84   bool operator!=(const DIHeaderFieldIterator &X) const {
85     return !(*this == X);
86   }
88   StringRef getHeader() const { return Header; }
89   StringRef getCurrent() const { return Current; }
90   StringRef getPrefix() const {
91     if (Current.begin() == Header.begin())
92       return StringRef();
93     return Header.slice(0, Current.begin() - Header.begin() - 1);
94   }
95   StringRef getSuffix() const {
96     if (Current.end() == Header.end())
97       return StringRef();
98     return Header.slice(Current.end() - Header.begin() + 1, StringRef::npos);
99   }
101 private:
102   void increment() {
103     assert(Current.data() != nullptr && "Cannot increment past the end");
104     StringRef Suffix = getSuffix();
105     Current = Suffix.slice(0, Suffix.find('\0'));
106   }
107 };
109 /// DIDescriptor - A thin wraper around MDNode to access encoded debug info.
110 /// This should not be stored in a container, because the underlying MDNode
111 /// may change in certain situations.
112 class DIDescriptor {
113   // Befriends DIRef so DIRef can befriend the protected member
114   // function: getFieldAs<DIRef>.
115   template <typename T> friend class DIRef;
117 public:
118   /// The three accessibility flags are mutually exclusive and rolled
119   /// together in the first two bits.
120   enum {
121     FlagAccessibility     = 1 << 0 | 1 << 1,
122     FlagPrivate           = 1,
123     FlagProtected         = 2,
124     FlagPublic            = 3,
126     FlagFwdDecl           = 1 << 2,
127     FlagAppleBlock        = 1 << 3,
128     FlagBlockByrefStruct  = 1 << 4,
129     FlagVirtual           = 1 << 5,
130     FlagArtificial        = 1 << 6,
131     FlagExplicit          = 1 << 7,
132     FlagPrototyped        = 1 << 8,
133     FlagObjcClassComplete = 1 << 9,
134     FlagObjectPointer     = 1 << 10,
135     FlagVector            = 1 << 11,
136     FlagStaticMember      = 1 << 12,
137     FlagIndirectVariable  = 1 << 13,
138     FlagLValueReference   = 1 << 14,
139     FlagRValueReference   = 1 << 15
140   };
142 protected:
143   const MDNode *DbgNode;
145   StringRef getStringField(unsigned Elt) const;
146   unsigned getUnsignedField(unsigned Elt) const {
147     return (unsigned)getUInt64Field(Elt);
148   }
149   uint64_t getUInt64Field(unsigned Elt) const;
150   int64_t getInt64Field(unsigned Elt) const;
151   DIDescriptor getDescriptorField(unsigned Elt) const;
153   template <typename DescTy> DescTy getFieldAs(unsigned Elt) const {
154     return DescTy(getDescriptorField(Elt));
155   }
157   GlobalVariable *getGlobalVariableField(unsigned Elt) const;
158   Constant *getConstantField(unsigned Elt) const;
159   Function *getFunctionField(unsigned Elt) const;
160   void replaceFunctionField(unsigned Elt, Function *F);
162 public:
163   explicit DIDescriptor(const MDNode *N = nullptr) : DbgNode(N) {}
165   bool Verify() const;
167   operator MDNode *() const { return const_cast<MDNode *>(DbgNode); }
168   MDNode *operator->() const { return const_cast<MDNode *>(DbgNode); }
170   // An explicit operator bool so that we can do testing of DI values
171   // easily.
172   // FIXME: This operator bool isn't actually protecting anything at the
173   // moment due to the conversion operator above making DIDescriptor nodes
174   // implicitly convertable to bool.
175   LLVM_EXPLICIT operator bool() const { return DbgNode != nullptr; }
177   bool operator==(DIDescriptor Other) const { return DbgNode == Other.DbgNode; }
178   bool operator!=(DIDescriptor Other) const { return !operator==(Other); }
180   StringRef getHeader() const {
181     return getStringField(0);
182   }
184   size_t getNumHeaderFields() const {
185     return std::distance(DIHeaderFieldIterator(getHeader()),
186                          DIHeaderFieldIterator());
187   }
189   StringRef getHeaderField(unsigned Index) const {
190     // Since callers expect an empty string for out-of-range accesses, we can't
191     // use std::advance() here.
192     for (DIHeaderFieldIterator I(getHeader()), E; I != E; ++I, --Index)
193       if (!Index)
194         return *I;
195     return StringRef();
196   }
198   template <class T> T getHeaderFieldAs(unsigned Index) const {
199     T Int;
200     if (getHeaderField(Index).getAsInteger(0, Int))
201       return 0;
202     return Int;
203   }
205   uint16_t getTag() const { return getHeaderFieldAs<uint16_t>(0); }
207   bool isDerivedType() const;
208   bool isCompositeType() const;
209   bool isSubroutineType() const;
210   bool isBasicType() const;
211   bool isVariable() const;
212   bool isSubprogram() const;
213   bool isGlobalVariable() const;
214   bool isScope() const;
215   bool isFile() const;
216   bool isCompileUnit() const;
217   bool isNameSpace() const;
218   bool isLexicalBlockFile() const;
219   bool isLexicalBlock() const;
220   bool isSubrange() const;
221   bool isEnumerator() const;
222   bool isType() const;
223   bool isTemplateTypeParameter() const;
224   bool isTemplateValueParameter() const;
225   bool isObjCProperty() const;
226   bool isImportedEntity() const;
227   bool isExpression() const;
229   /// print - print descriptor.
230   void print(raw_ostream &OS) const;
232   /// dump - print descriptor to dbgs() with a newline.
233   void dump() const;
235   /// replaceAllUsesWith - Replace all uses of debug info referenced by
236   /// this descriptor.
237   void replaceAllUsesWith(LLVMContext &VMContext, DIDescriptor D);
238   void replaceAllUsesWith(MDNode *D);
239 };
241 /// DISubrange - This is used to represent ranges, for array bounds.
242 class DISubrange : public DIDescriptor {
243   friend class DIDescriptor;
244   void printInternal(raw_ostream &OS) const;
246 public:
247   explicit DISubrange(const MDNode *N = nullptr) : DIDescriptor(N) {}
249   int64_t getLo() const { return getHeaderFieldAs<int64_t>(1); }
250   int64_t getCount() const { return getHeaderFieldAs<int64_t>(2); }
251   bool Verify() const;
252 };
254 /// DITypedArray - This descriptor holds an array of nodes with type T.
255 template <typename T> class DITypedArray : public DIDescriptor {
256 public:
257   explicit DITypedArray(const MDNode *N = nullptr) : DIDescriptor(N) {}
258   unsigned getNumElements() const {
259     return DbgNode ? DbgNode->getNumOperands() : 0;
260   }
261   T getElement(unsigned Idx) const {
262     return getFieldAs<T>(Idx);
263   }
264 };
266 typedef DITypedArray<DIDescriptor> DIArray;
268 /// DIEnumerator - A wrapper for an enumerator (e.g. X and Y in 'enum {X,Y}').
269 /// FIXME: it seems strange that this doesn't have either a reference to the
270 /// type/precision or a file/line pair for location info.
271 class DIEnumerator : public DIDescriptor {
272   friend class DIDescriptor;
273   void printInternal(raw_ostream &OS) const;
275 public:
276   explicit DIEnumerator(const MDNode *N = nullptr) : DIDescriptor(N) {}
278   StringRef getName() const { return getHeaderField(1); }
279   int64_t getEnumValue() const { return getHeaderFieldAs<int64_t>(2); }
280   bool Verify() const;
281 };
283 template <typename T> class DIRef;
284 typedef DIRef<DIScope> DIScopeRef;
285 typedef DIRef<DIType> DITypeRef;
286 typedef DITypedArray<DITypeRef> DITypeArray;
288 /// DIScope - A base class for various scopes.
289 ///
290 /// Although, implementation-wise, DIScope is the parent class of most
291 /// other DIxxx classes, including DIType and its descendants, most of
292 /// DIScope's descendants are not a substitutable subtype of
293 /// DIScope. The DIDescriptor::isScope() method only is true for
294 /// DIScopes that are scopes in the strict lexical scope sense
295 /// (DICompileUnit, DISubprogram, etc.), but not for, e.g., a DIType.
296 class DIScope : public DIDescriptor {
297 protected:
298   friend class DIDescriptor;
299   void printInternal(raw_ostream &OS) const;
301 public:
302   explicit DIScope(const MDNode *N = nullptr) : DIDescriptor(N) {}
304   /// Gets the parent scope for this scope node or returns a
305   /// default constructed scope.
306   DIScopeRef getContext() const;
307   /// If the scope node has a name, return that, else return an empty string.
308   StringRef getName() const;
309   StringRef getFilename() const;
310   StringRef getDirectory() const;
312   /// Generate a reference to this DIScope. Uses the type identifier instead
313   /// of the actual MDNode if possible, to help type uniquing.
314   DIScopeRef getRef() const;
315 };
317 /// Represents reference to a DIDescriptor, abstracts over direct and
318 /// identifier-based metadata references.
319 template <typename T> class DIRef {
320   template <typename DescTy>
321   friend DescTy DIDescriptor::getFieldAs(unsigned Elt) const;
322   friend DIScopeRef DIScope::getContext() const;
323   friend DIScopeRef DIScope::getRef() const;
324   friend class DIType;
326   /// Val can be either a MDNode or a MDString, in the latter,
327   /// MDString specifies the type identifier.
328   const Value *Val;
329   explicit DIRef(const Value *V);
331 public:
332   T resolve(const DITypeIdentifierMap &Map) const;
333   StringRef getName() const;
334   operator Value *() const { return const_cast<Value *>(Val); }
335 };
337 template <typename T>
338 T DIRef<T>::resolve(const DITypeIdentifierMap &Map) const {
339   if (!Val)
340     return T();
342   if (const MDNode *MD = dyn_cast<MDNode>(Val))
343     return T(MD);
345   const MDString *MS = cast<MDString>(Val);
346   // Find the corresponding MDNode.
347   DITypeIdentifierMap::const_iterator Iter = Map.find(MS);
348   assert(Iter != Map.end() && "Identifier not in the type map?");
349   assert(DIDescriptor(Iter->second).isType() &&
350          "MDNode in DITypeIdentifierMap should be a DIType.");
351   return T(Iter->second);
354 template <typename T> StringRef DIRef<T>::getName() const {
355   if (!Val)
356     return StringRef();
358   if (const MDNode *MD = dyn_cast<MDNode>(Val))
359     return T(MD).getName();
361   const MDString *MS = cast<MDString>(Val);
362   return MS->getString();
365 /// Specialize getFieldAs to handle fields that are references to DIScopes.
366 template <> DIScopeRef DIDescriptor::getFieldAs<DIScopeRef>(unsigned Elt) const;
367 /// Specialize DIRef constructor for DIScopeRef.
368 template <> DIRef<DIScope>::DIRef(const Value *V);
370 /// Specialize getFieldAs to handle fields that are references to DITypes.
371 template <> DITypeRef DIDescriptor::getFieldAs<DITypeRef>(unsigned Elt) const;
372 /// Specialize DIRef constructor for DITypeRef.
373 template <> DIRef<DIType>::DIRef(const Value *V);
375 /// DIType - This is a wrapper for a type.
376 /// FIXME: Types should be factored much better so that CV qualifiers and
377 /// others do not require a huge and empty descriptor full of zeros.
378 class DIType : public DIScope {
379 protected:
380   friend class DIDescriptor;
381   void printInternal(raw_ostream &OS) const;
383 public:
384   explicit DIType(const MDNode *N = nullptr) : DIScope(N) {}
385   operator DITypeRef () const {
386     assert(isType() &&
387            "constructing DITypeRef from an MDNode that is not a type");
388     return DITypeRef(&*getRef());
389   }
391   /// Verify - Verify that a type descriptor is well formed.
392   bool Verify() const;
394   DIScopeRef getContext() const { return getFieldAs<DIScopeRef>(2); }
395   StringRef getName() const { return getHeaderField(1); }
396   unsigned getLineNumber() const {
397     return getHeaderFieldAs<unsigned>(2);
398   }
399   uint64_t getSizeInBits() const {
400     return getHeaderFieldAs<unsigned>(3);
401   }
402   uint64_t getAlignInBits() const {
403     return getHeaderFieldAs<unsigned>(4);
404   }
405   // FIXME: Offset is only used for DW_TAG_member nodes.  Making every type
406   // carry this is just plain insane.
407   uint64_t getOffsetInBits() const {
408     return getHeaderFieldAs<unsigned>(5);
409   }
410   unsigned getFlags() const { return getHeaderFieldAs<unsigned>(6); }
411   bool isPrivate() const {
412     return (getFlags() & FlagAccessibility) == FlagPrivate;
413   }
414   bool isProtected() const {
415     return (getFlags() & FlagAccessibility) == FlagProtected;
416   }
417   bool isPublic() const {
418     return (getFlags() & FlagAccessibility) == FlagPublic;
419   }
420   bool isForwardDecl() const { return (getFlags() & FlagFwdDecl) != 0; }
421   // isAppleBlock - Return true if this is the Apple Blocks extension.
422   bool isAppleBlockExtension() const {
423     return (getFlags() & FlagAppleBlock) != 0;
424   }
425   bool isBlockByrefStruct() const {
426     return (getFlags() & FlagBlockByrefStruct) != 0;
427   }
428   bool isVirtual() const { return (getFlags() & FlagVirtual) != 0; }
429   bool isArtificial() const { return (getFlags() & FlagArtificial) != 0; }
430   bool isObjectPointer() const { return (getFlags() & FlagObjectPointer) != 0; }
431   bool isObjcClassComplete() const {
432     return (getFlags() & FlagObjcClassComplete) != 0;
433   }
434   bool isVector() const { return (getFlags() & FlagVector) != 0; }
435   bool isStaticMember() const { return (getFlags() & FlagStaticMember) != 0; }
436   bool isLValueReference() const {
437     return (getFlags() & FlagLValueReference) != 0;
438   }
439   bool isRValueReference() const {
440     return (getFlags() & FlagRValueReference) != 0;
441   }
442   bool isValid() const { return DbgNode && isType(); }
443 };
445 /// DIBasicType - A basic type, like 'int' or 'float'.
446 class DIBasicType : public DIType {
447 public:
448   explicit DIBasicType(const MDNode *N = nullptr) : DIType(N) {}
450   unsigned getEncoding() const { return getHeaderFieldAs<unsigned>(7); }
452   /// Verify - Verify that a basic type descriptor is well formed.
453   bool Verify() const;
454 };
456 /// DIDerivedType - A simple derived type, like a const qualified type,
457 /// a typedef, a pointer or reference, et cetera.  Or, a data member of
458 /// a class/struct/union.
459 class DIDerivedType : public DIType {
460   friend class DIDescriptor;
461   void printInternal(raw_ostream &OS) const;
463 public:
464   explicit DIDerivedType(const MDNode *N = nullptr) : DIType(N) {}
466   DITypeRef getTypeDerivedFrom() const { return getFieldAs<DITypeRef>(3); }
468   /// getObjCProperty - Return property node, if this ivar is
469   /// associated with one.
470   MDNode *getObjCProperty() const;
472   DITypeRef getClassType() const {
473     assert(getTag() == dwarf::DW_TAG_ptr_to_member_type);
474     return getFieldAs<DITypeRef>(4);
475   }
477   Constant *getConstant() const {
478     assert((getTag() == dwarf::DW_TAG_member) && isStaticMember());
479     return getConstantField(4);
480   }
482   /// Verify - Verify that a derived type descriptor is well formed.
483   bool Verify() const;
484 };
486 /// DICompositeType - This descriptor holds a type that can refer to multiple
487 /// other types, like a function or struct.
488 /// DICompositeType is derived from DIDerivedType because some
489 /// composite types (such as enums) can be derived from basic types
490 // FIXME: Make this derive from DIType directly & just store the
491 // base type in a single DIType field.
492 class DICompositeType : public DIDerivedType {
493   friend class DIDescriptor;
494   void printInternal(raw_ostream &OS) const;
495   void setArraysHelper(MDNode *Elements, MDNode *TParams);
497 public:
498   explicit DICompositeType(const MDNode *N = nullptr) : DIDerivedType(N) {}
500   DIArray getElements() const {
501     assert(!isSubroutineType() && "no elements for DISubroutineType");
502     return getFieldAs<DIArray>(4);
503   }
504   template <typename T>
505   void setArrays(DITypedArray<T> Elements, DIArray TParams = DIArray()) {
506     assert((!TParams || DbgNode->getNumOperands() == 8) &&
507            "If you're setting the template parameters this should include a slot "
508            "for that!");
509     setArraysHelper(Elements, TParams);
510   }
511   unsigned getRunTimeLang() const {
512     return getHeaderFieldAs<unsigned>(7);
513   }
514   DITypeRef getContainingType() const { return getFieldAs<DITypeRef>(5); }
515   void setContainingType(DICompositeType ContainingType);
516   DIArray getTemplateParams() const { return getFieldAs<DIArray>(6); }
517   MDString *getIdentifier() const;
519   /// Verify - Verify that a composite type descriptor is well formed.
520   bool Verify() const;
521 };
523 class DISubroutineType : public DICompositeType {
524 public:
525   explicit DISubroutineType(const MDNode *N = nullptr) : DICompositeType(N) {}
526   DITypedArray<DITypeRef> getTypeArray() const {
527     return getFieldAs<DITypedArray<DITypeRef>>(4);
528   }
529 };
531 /// DIFile - This is a wrapper for a file.
532 class DIFile : public DIScope {
533   friend class DIDescriptor;
535 public:
536   explicit DIFile(const MDNode *N = nullptr) : DIScope(N) {}
537   MDNode *getFileNode() const;
538   bool Verify() const;
539 };
541 /// DICompileUnit - A wrapper for a compile unit.
542 class DICompileUnit : public DIScope {
543   friend class DIDescriptor;
544   void printInternal(raw_ostream &OS) const;
546 public:
547   explicit DICompileUnit(const MDNode *N = nullptr) : DIScope(N) {}
549   dwarf::SourceLanguage getLanguage() const {
550     return static_cast<dwarf::SourceLanguage>(getHeaderFieldAs<unsigned>(1));
551   }
552   StringRef getProducer() const { return getHeaderField(2); }
554   bool isOptimized() const { return getHeaderFieldAs<bool>(3) != 0; }
555   StringRef getFlags() const { return getHeaderField(4); }
556   unsigned getRunTimeVersion() const { return getHeaderFieldAs<unsigned>(5); }
558   DIArray getEnumTypes() const;
559   DIArray getRetainedTypes() const;
560   DIArray getSubprograms() const;
561   DIArray getGlobalVariables() const;
562   DIArray getImportedEntities() const;
564   void replaceSubprograms(DIArray Subprograms);
565   void replaceGlobalVariables(DIArray GlobalVariables);
567   StringRef getSplitDebugFilename() const { return getHeaderField(6); }
568   unsigned getEmissionKind() const { return getHeaderFieldAs<unsigned>(7); }
570   /// Verify - Verify that a compile unit is well formed.
571   bool Verify() const;
572 };
574 /// DISubprogram - This is a wrapper for a subprogram (e.g. a function).
575 class DISubprogram : public DIScope {
576   friend class DIDescriptor;
577   void printInternal(raw_ostream &OS) const;
579 public:
580   explicit DISubprogram(const MDNode *N = nullptr) : DIScope(N) {}
582   StringRef getName() const { return getHeaderField(1); }
583   StringRef getDisplayName() const { return getHeaderField(2); }
584   StringRef getLinkageName() const { return getHeaderField(3); }
585   unsigned getLineNumber() const { return getHeaderFieldAs<unsigned>(4); }
587   /// isLocalToUnit - Return true if this subprogram is local to the current
588   /// compile unit, like 'static' in C.
589   unsigned isLocalToUnit() const { return getHeaderFieldAs<unsigned>(5); }
590   unsigned isDefinition() const { return getHeaderFieldAs<unsigned>(6); }
592   unsigned getVirtuality() const { return getHeaderFieldAs<unsigned>(7); }
593   unsigned getVirtualIndex() const { return getHeaderFieldAs<unsigned>(8); }
595   unsigned getFlags() const { return getHeaderFieldAs<unsigned>(9); }
597   unsigned isOptimized() const { return getHeaderFieldAs<bool>(10); }
599   /// getScopeLineNumber - Get the beginning of the scope of the
600   /// function, not necessarily where the name of the program
601   /// starts.
602   unsigned getScopeLineNumber() const { return getHeaderFieldAs<unsigned>(11); }
604   DIScopeRef getContext() const { return getFieldAs<DIScopeRef>(2); }
605   DISubroutineType getType() const { return getFieldAs<DISubroutineType>(3); }
607   DITypeRef getContainingType() const { return getFieldAs<DITypeRef>(4); }
609   /// Verify - Verify that a subprogram descriptor is well formed.
610   bool Verify() const;
612   /// describes - Return true if this subprogram provides debugging
613   /// information for the function F.
614   bool describes(const Function *F);
616   Function *getFunction() const { return getFunctionField(5); }
617   void replaceFunction(Function *F) { replaceFunctionField(5, F); }
618   DIArray getTemplateParams() const { return getFieldAs<DIArray>(6); }
619   DISubprogram getFunctionDeclaration() const {
620     return getFieldAs<DISubprogram>(7);
621   }
622   MDNode *getVariablesNodes() const;
623   DIArray getVariables() const;
625   unsigned isArtificial() const { return (getFlags() & FlagArtificial) != 0; }
626   /// isPrivate - Return true if this subprogram has "private"
627   /// access specifier.
628   bool isPrivate() const {
629     return (getFlags() & FlagAccessibility) == FlagPrivate;
630   }
631   /// isProtected - Return true if this subprogram has "protected"
632   /// access specifier.
633   bool isProtected() const {
634     return (getFlags() & FlagAccessibility) == FlagProtected;
635   }
636   /// isPublic - Return true if this subprogram has "public"
637   /// access specifier.
638   bool isPublic() const {
639     return (getFlags() & FlagAccessibility) == FlagPublic;
640   }
641   /// isExplicit - Return true if this subprogram is marked as explicit.
642   bool isExplicit() const { return (getFlags() & FlagExplicit) != 0; }
643   /// isPrototyped - Return true if this subprogram is prototyped.
644   bool isPrototyped() const { return (getFlags() & FlagPrototyped) != 0; }
646   /// Return true if this subprogram is a C++11 reference-qualified
647   /// non-static member function (void foo() &).
648   unsigned isLValueReference() const {
649     return (getFlags() & FlagLValueReference) != 0;
650   }
652   /// Return true if this subprogram is a C++11
653   /// rvalue-reference-qualified non-static member function
654   /// (void foo() &&).
655   unsigned isRValueReference() const {
656     return (getFlags() & FlagRValueReference) != 0;
657   }
659 };
661 /// DILexicalBlock - This is a wrapper for a lexical block.
662 class DILexicalBlock : public DIScope {
663 public:
664   explicit DILexicalBlock(const MDNode *N = nullptr) : DIScope(N) {}
665   DIScope getContext() const { return getFieldAs<DIScope>(2); }
666   unsigned getLineNumber() const {
667     return getHeaderFieldAs<unsigned>(1);
668   }
669   unsigned getColumnNumber() const {
670     return getHeaderFieldAs<unsigned>(2);
671   }
672   bool Verify() const;
673 };
675 /// DILexicalBlockFile - This is a wrapper for a lexical block with
676 /// a filename change.
677 class DILexicalBlockFile : public DIScope {
678 public:
679   explicit DILexicalBlockFile(const MDNode *N = nullptr) : DIScope(N) {}
680   DIScope getContext() const {
681     if (getScope().isSubprogram())
682       return getScope();
683     return getScope().getContext();
684   }
685   unsigned getLineNumber() const { return getScope().getLineNumber(); }
686   unsigned getColumnNumber() const { return getScope().getColumnNumber(); }
687   DILexicalBlock getScope() const { return getFieldAs<DILexicalBlock>(2); }
688   unsigned getDiscriminator() const { return getHeaderFieldAs<unsigned>(1); }
689   bool Verify() const;
690 };
692 /// DINameSpace - A wrapper for a C++ style name space.
693 class DINameSpace : public DIScope {
694   friend class DIDescriptor;
695   void printInternal(raw_ostream &OS) const;
697 public:
698   explicit DINameSpace(const MDNode *N = nullptr) : DIScope(N) {}
699   StringRef getName() const { return getHeaderField(1); }
700   unsigned getLineNumber() const { return getHeaderFieldAs<unsigned>(2); }
701   DIScope getContext() const { return getFieldAs<DIScope>(2); }
702   bool Verify() const;
703 };
705 /// DITemplateTypeParameter - This is a wrapper for template type parameter.
706 class DITemplateTypeParameter : public DIDescriptor {
707 public:
708   explicit DITemplateTypeParameter(const MDNode *N = nullptr)
709     : DIDescriptor(N) {}
711   StringRef getName() const { return getHeaderField(1); }
712   unsigned getLineNumber() const { return getHeaderFieldAs<unsigned>(2); }
713   unsigned getColumnNumber() const { return getHeaderFieldAs<unsigned>(3); }
715   DIScopeRef getContext() const { return getFieldAs<DIScopeRef>(1); }
716   DITypeRef getType() const { return getFieldAs<DITypeRef>(2); }
717   StringRef getFilename() const { return getFieldAs<DIFile>(3).getFilename(); }
718   StringRef getDirectory() const {
719     return getFieldAs<DIFile>(3).getDirectory();
720   }
721   bool Verify() const;
722 };
724 /// DITemplateValueParameter - This is a wrapper for template value parameter.
725 class DITemplateValueParameter : public DIDescriptor {
726 public:
727   explicit DITemplateValueParameter(const MDNode *N = nullptr)
728     : DIDescriptor(N) {}
730   StringRef getName() const { return getHeaderField(1); }
731   unsigned getLineNumber() const { return getHeaderFieldAs<unsigned>(2); }
732   unsigned getColumnNumber() const { return getHeaderFieldAs<unsigned>(3); }
734   DIScopeRef getContext() const { return getFieldAs<DIScopeRef>(1); }
735   DITypeRef getType() const { return getFieldAs<DITypeRef>(2); }
736   Value *getValue() const;
737   StringRef getFilename() const { return getFieldAs<DIFile>(4).getFilename(); }
738   StringRef getDirectory() const {
739     return getFieldAs<DIFile>(4).getDirectory();
740   }
741   bool Verify() const;
742 };
744 /// DIGlobalVariable - This is a wrapper for a global variable.
745 class DIGlobalVariable : public DIDescriptor {
746   friend class DIDescriptor;
747   void printInternal(raw_ostream &OS) const;
749 public:
750   explicit DIGlobalVariable(const MDNode *N = nullptr) : DIDescriptor(N) {}
752   StringRef getName() const { return getHeaderField(1); }
753   StringRef getDisplayName() const { return getHeaderField(2); }
754   StringRef getLinkageName() const { return getHeaderField(3); }
755   unsigned getLineNumber() const { return getHeaderFieldAs<unsigned>(4); }
756   unsigned isLocalToUnit() const { return getHeaderFieldAs<bool>(5); }
757   unsigned isDefinition() const { return getHeaderFieldAs<bool>(6); }
759   DIScope getContext() const { return getFieldAs<DIScope>(1); }
760   StringRef getFilename() const { return getFieldAs<DIFile>(2).getFilename(); }
761   StringRef getDirectory() const {
762     return getFieldAs<DIFile>(2).getDirectory();
763   }
764   DITypeRef getType() const { return getFieldAs<DITypeRef>(3); }
766   GlobalVariable *getGlobal() const { return getGlobalVariableField(4); }
767   Constant *getConstant() const { return getConstantField(4); }
768   DIDerivedType getStaticDataMemberDeclaration() const {
769     return getFieldAs<DIDerivedType>(5);
770   }
772   /// Verify - Verify that a global variable descriptor is well formed.
773   bool Verify() const;
774 };
776 /// DIVariable - This is a wrapper for a variable (e.g. parameter, local,
777 /// global etc).
778 class DIVariable : public DIDescriptor {
779   friend class DIDescriptor;
780   void printInternal(raw_ostream &OS) const;
782 public:
783   explicit DIVariable(const MDNode *N = nullptr) : DIDescriptor(N) {}
785   StringRef getName() const { return getHeaderField(1); }
786   unsigned getLineNumber() const {
787     // FIXME: Line number and arg number shouldn't be merged together like this.
788     return (getHeaderFieldAs<unsigned>(2) << 8) >> 8;
789   }
790   unsigned getArgNumber() const { return getHeaderFieldAs<unsigned>(2) >> 24; }
792   DIScope getContext() const { return getFieldAs<DIScope>(1); }
793   DIFile getFile() const { return getFieldAs<DIFile>(2); }
794   DITypeRef getType() const { return getFieldAs<DITypeRef>(3); }
796   /// isArtificial - Return true if this variable is marked as "artificial".
797   bool isArtificial() const {
798     return (getHeaderFieldAs<unsigned>(3) & FlagArtificial) != 0;
799   }
801   bool isObjectPointer() const {
802     return (getHeaderFieldAs<unsigned>(3) & FlagObjectPointer) != 0;
803   }
805   /// \brief Return true if this variable is represented as a pointer.
806   bool isIndirect() const {
807     return (getHeaderFieldAs<unsigned>(3) & FlagIndirectVariable) != 0;
808   }
810   /// getInlinedAt - If this variable is inlined then return inline location.
811   MDNode *getInlinedAt() const;
813   /// Verify - Verify that a variable descriptor is well formed.
814   bool Verify() const;
816   /// isBlockByrefVariable - Return true if the variable was declared as
817   /// a "__block" variable (Apple Blocks).
818   bool isBlockByrefVariable(const DITypeIdentifierMap &Map) const {
819     return (getType().resolve(Map)).isBlockByrefStruct();
820   }
822   /// isInlinedFnArgument - Return true if this variable provides debugging
823   /// information for an inlined function arguments.
824   bool isInlinedFnArgument(const Function *CurFn);
826   /// Return the size reported by the variable's type.
827   unsigned getSizeInBits(const DITypeIdentifierMap &Map);
829   void printExtendedName(raw_ostream &OS) const;
830 };
832 /// DIExpression - A complex location expression.
833 class DIExpression : public DIDescriptor {
834   friend class DIDescriptor;
835   void printInternal(raw_ostream &OS) const;
837 public:
838   explicit DIExpression(const MDNode *N = nullptr) : DIDescriptor(N) {}
840   /// Verify - Verify that a variable descriptor is well formed.
841   bool Verify() const;
843   /// \brief Return the number of elements in the complex expression.
844   unsigned getNumElements() const {
845     if (!DbgNode)
846       return 0;
847     unsigned N = getNumHeaderFields();
848     assert(N > 0 && "missing tag");
849     return N - 1;
850   }
852   /// \brief return the Idx'th complex address element.
853   uint64_t getElement(unsigned Idx) const;
855   /// isVariablePiece - Return whether this is a piece of an aggregate
856   /// variable.
857   bool isVariablePiece() const;
858   /// getPieceOffset - Return the offset of this piece in bytes.
859   uint64_t getPieceOffset() const;
860   /// getPieceSize - Return the size of this piece in bytes.
861   uint64_t getPieceSize() const;
862 };
864 /// DILocation - This object holds location information. This object
865 /// is not associated with any DWARF tag.
866 class DILocation : public DIDescriptor {
867 public:
868   explicit DILocation(const MDNode *N) : DIDescriptor(N) {}
870   unsigned getLineNumber() const { return getUnsignedField(0); }
871   unsigned getColumnNumber() const { return getUnsignedField(1); }
872   DIScope getScope() const { return getFieldAs<DIScope>(2); }
873   DILocation getOrigLocation() const { return getFieldAs<DILocation>(3); }
874   StringRef getFilename() const { return getScope().getFilename(); }
875   StringRef getDirectory() const { return getScope().getDirectory(); }
876   bool Verify() const;
877   bool atSameLineAs(const DILocation &Other) const {
878     return (getLineNumber() == Other.getLineNumber() &&
879             getFilename() == Other.getFilename());
880   }
881   /// getDiscriminator - DWARF discriminators are used to distinguish
882   /// identical file locations for instructions that are on different
883   /// basic blocks. If two instructions are inside the same lexical block
884   /// and are in different basic blocks, we create a new lexical block
885   /// with identical location as the original but with a different
886   /// discriminator value (lib/Transforms/Util/AddDiscriminators.cpp
887   /// for details).
888   unsigned getDiscriminator() const {
889     // Since discriminators are associated with lexical blocks, make
890     // sure this location is a lexical block before retrieving its
891     // value.
892     return getScope().isLexicalBlockFile()
893                ? getFieldAs<DILexicalBlockFile>(2).getDiscriminator()
894                : 0;
895   }
896   unsigned computeNewDiscriminator(LLVMContext &Ctx);
897   DILocation copyWithNewScope(LLVMContext &Ctx, DILexicalBlockFile NewScope);
898 };
900 class DIObjCProperty : public DIDescriptor {
901   friend class DIDescriptor;
902   void printInternal(raw_ostream &OS) const;
904 public:
905   explicit DIObjCProperty(const MDNode *N) : DIDescriptor(N) {}
907   StringRef getObjCPropertyName() const { return getHeaderField(1); }
908   DIFile getFile() const { return getFieldAs<DIFile>(1); }
909   unsigned getLineNumber() const { return getHeaderFieldAs<unsigned>(2); }
911   StringRef getObjCPropertyGetterName() const { return getHeaderField(3); }
912   StringRef getObjCPropertySetterName() const { return getHeaderField(4); }
913   unsigned getAttributes() const { return getHeaderFieldAs<unsigned>(5); }
914   bool isReadOnlyObjCProperty() const {
915     return (getAttributes() & dwarf::DW_APPLE_PROPERTY_readonly) != 0;
916   }
917   bool isReadWriteObjCProperty() const {
918     return (getAttributes() & dwarf::DW_APPLE_PROPERTY_readwrite) != 0;
919   }
920   bool isAssignObjCProperty() const {
921     return (getAttributes() & dwarf::DW_APPLE_PROPERTY_assign) != 0;
922   }
923   bool isRetainObjCProperty() const {
924     return (getAttributes() & dwarf::DW_APPLE_PROPERTY_retain) != 0;
925   }
926   bool isCopyObjCProperty() const {
927     return (getAttributes() & dwarf::DW_APPLE_PROPERTY_copy) != 0;
928   }
929   bool isNonAtomicObjCProperty() const {
930     return (getAttributes() & dwarf::DW_APPLE_PROPERTY_nonatomic) != 0;
931   }
933   /// Objective-C doesn't have an ODR, so there is no benefit in storing
934   /// the type as a DITypeRef here.
935   DIType getType() const { return getFieldAs<DIType>(2); }
937   /// Verify - Verify that a derived type descriptor is well formed.
938   bool Verify() const;
939 };
941 /// \brief An imported module (C++ using directive or similar).
942 class DIImportedEntity : public DIDescriptor {
943   friend class DIDescriptor;
944   void printInternal(raw_ostream &OS) const;
946 public:
947   explicit DIImportedEntity(const MDNode *N) : DIDescriptor(N) {}
948   DIScope getContext() const { return getFieldAs<DIScope>(1); }
949   DIScopeRef getEntity() const { return getFieldAs<DIScopeRef>(2); }
950   unsigned getLineNumber() const { return getHeaderFieldAs<unsigned>(1); }
951   StringRef getName() const { return getHeaderField(2); }
952   bool Verify() const;
953 };
955 /// getDISubprogram - Find subprogram that is enclosing this scope.
956 DISubprogram getDISubprogram(const MDNode *Scope);
958 /// getDICompositeType - Find underlying composite type.
959 DICompositeType getDICompositeType(DIType T);
961 /// getOrInsertFnSpecificMDNode - Return a NameMDNode that is suitable
962 /// to hold function specific information.
963 NamedMDNode *getOrInsertFnSpecificMDNode(Module &M, DISubprogram SP);
965 /// getFnSpecificMDNode - Return a NameMDNode, if available, that is
966 /// suitable to hold function specific information.
967 NamedMDNode *getFnSpecificMDNode(const Module &M, DISubprogram SP);
969 /// createInlinedVariable - Create a new inlined variable based on current
970 /// variable.
971 /// @param DV            Current Variable.
972 /// @param InlinedScope  Location at current variable is inlined.
973 DIVariable createInlinedVariable(MDNode *DV, MDNode *InlinedScope,
974                                  LLVMContext &VMContext);
976 /// cleanseInlinedVariable - Remove inlined scope from the variable.
977 DIVariable cleanseInlinedVariable(MDNode *DV, LLVMContext &VMContext);
979 /// Construct DITypeIdentifierMap by going through retained types of each CU.
980 DITypeIdentifierMap generateDITypeIdentifierMap(const NamedMDNode *CU_Nodes);
982 /// Strip debug info in the module if it exists.
983 /// To do this, we remove all calls to the debugger intrinsics and any named
984 /// metadata for debugging. We also remove debug locations for instructions.
985 /// Return true if module is modified.
986 bool StripDebugInfo(Module &M);
988 /// Return Debug Info Metadata Version by checking module flags.
989 unsigned getDebugMetadataVersionFromModule(const Module &M);
991 /// DebugInfoFinder tries to list all debug info MDNodes used in a module. To
992 /// list debug info MDNodes used by an instruction, DebugInfoFinder uses
993 /// processDeclare, processValue and processLocation to handle DbgDeclareInst,
994 /// DbgValueInst and DbgLoc attached to instructions. processModule will go
995 /// through all DICompileUnits in llvm.dbg.cu and list debug info MDNodes
996 /// used by the CUs.
997 class DebugInfoFinder {
998 public:
999   DebugInfoFinder() : TypeMapInitialized(false) {}
1001   /// processModule - Process entire module and collect debug info
1002   /// anchors.
1003   void processModule(const Module &M);
1005   /// processDeclare - Process DbgDeclareInst.
1006   void processDeclare(const Module &M, const DbgDeclareInst *DDI);
1007   /// Process DbgValueInst.
1008   void processValue(const Module &M, const DbgValueInst *DVI);
1009   /// processLocation - Process DILocation.
1010   void processLocation(const Module &M, DILocation Loc);
1012   /// Clear all lists.
1013   void reset();
1015 private:
1016   /// Initialize TypeIdentifierMap.
1017   void InitializeTypeMap(const Module &M);
1019   /// processType - Process DIType.
1020   void processType(DIType DT);
1022   /// processSubprogram - Process DISubprogram.
1023   void processSubprogram(DISubprogram SP);
1025   void processScope(DIScope Scope);
1027   /// addCompileUnit - Add compile unit into CUs.
1028   bool addCompileUnit(DICompileUnit CU);
1030   /// addGlobalVariable - Add global variable into GVs.
1031   bool addGlobalVariable(DIGlobalVariable DIG);
1033   // addSubprogram - Add subprogram into SPs.
1034   bool addSubprogram(DISubprogram SP);
1036   /// addType - Add type into Tys.
1037   bool addType(DIType DT);
1039   bool addScope(DIScope Scope);
1041 public:
1042   typedef SmallVectorImpl<DICompileUnit>::const_iterator compile_unit_iterator;
1043   typedef SmallVectorImpl<DISubprogram>::const_iterator subprogram_iterator;
1044   typedef SmallVectorImpl<DIGlobalVariable>::const_iterator global_variable_iterator;
1045   typedef SmallVectorImpl<DIType>::const_iterator type_iterator;
1046   typedef SmallVectorImpl<DIScope>::const_iterator scope_iterator;
1048   iterator_range<compile_unit_iterator> compile_units() const {
1049     return iterator_range<compile_unit_iterator>(CUs.begin(), CUs.end());
1050   }
1052   iterator_range<subprogram_iterator> subprograms() const {
1053     return iterator_range<subprogram_iterator>(SPs.begin(), SPs.end());
1054   }
1056   iterator_range<global_variable_iterator> global_variables() const {
1057     return iterator_range<global_variable_iterator>(GVs.begin(), GVs.end());
1058   }
1060   iterator_range<type_iterator> types() const {
1061     return iterator_range<type_iterator>(TYs.begin(), TYs.end());
1062   }
1064   iterator_range<scope_iterator> scopes() const {
1065     return iterator_range<scope_iterator>(Scopes.begin(), Scopes.end());
1066   }
1068   unsigned compile_unit_count() const { return CUs.size(); }
1069   unsigned global_variable_count() const { return GVs.size(); }
1070   unsigned subprogram_count() const { return SPs.size(); }
1071   unsigned type_count() const { return TYs.size(); }
1072   unsigned scope_count() const { return Scopes.size(); }
1074 private:
1075   SmallVector<DICompileUnit, 8> CUs;    // Compile Units
1076   SmallVector<DISubprogram, 8> SPs;    // Subprograms
1077   SmallVector<DIGlobalVariable, 8> GVs;    // Global Variables;
1078   SmallVector<DIType, 8> TYs;    // Types
1079   SmallVector<DIScope, 8> Scopes; // Scopes
1080   SmallPtrSet<MDNode *, 64> NodesSeen;
1081   DITypeIdentifierMap TypeIdentifierMap;
1082   /// Specify if TypeIdentifierMap is initialized.
1083   bool TypeMapInitialized;
1084 };
1086 DenseMap<const Function *, DISubprogram> makeSubprogramMap(const Module &M);
1088 } // end namespace llvm
1090 #endif