DI: Make comments "brief"-er, NFC
[oota-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 //===----------------------------------------------------------------------===//
16
17 #ifndef LLVM_IR_DEBUGINFO_H
18 #define LLVM_IR_DEBUGINFO_H
19
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>
30
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;
47
48 class DIFile;
49 class DISubprogram;
50 class DILexicalBlock;
51 class DILexicalBlockFile;
52 class DIVariable;
53 class DIType;
54 class DIScope;
55 class DIObjCProperty;
56
57 /// \brief Maps from type identifier to the actual MDNode.
58 typedef DenseMap<const MDString *, MDNode *> DITypeIdentifierMap;
59
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;
65
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   }
87
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   }
100
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 };
108
109 /// \brief A thin wraper around MDNode to access encoded debug info.
110 ///
111 /// This should not be stored in a container, because the underlying MDNode may
112 /// change in certain situations.
113 class DIDescriptor {
114   // Befriends DIRef so DIRef can befriend the protected member
115   // function: getFieldAs<DIRef>.
116   template <typename T> friend class DIRef;
117
118 public:
119   /// \brief Accessibility flags.
120   ///
121   /// The three accessibility flags are mutually exclusive and rolled together
122   /// in the first two bits.
123   enum {
124     FlagAccessibility     = 1 << 0 | 1 << 1,
125     FlagPrivate           = 1,
126     FlagProtected         = 2,
127     FlagPublic            = 3,
128
129     FlagFwdDecl           = 1 << 2,
130     FlagAppleBlock        = 1 << 3,
131     FlagBlockByrefStruct  = 1 << 4,
132     FlagVirtual           = 1 << 5,
133     FlagArtificial        = 1 << 6,
134     FlagExplicit          = 1 << 7,
135     FlagPrototyped        = 1 << 8,
136     FlagObjcClassComplete = 1 << 9,
137     FlagObjectPointer     = 1 << 10,
138     FlagVector            = 1 << 11,
139     FlagStaticMember      = 1 << 12,
140     FlagIndirectVariable  = 1 << 13,
141     FlagLValueReference   = 1 << 14,
142     FlagRValueReference   = 1 << 15
143   };
144
145 protected:
146   const MDNode *DbgNode;
147
148   StringRef getStringField(unsigned Elt) const;
149   unsigned getUnsignedField(unsigned Elt) const {
150     return (unsigned)getUInt64Field(Elt);
151   }
152   uint64_t getUInt64Field(unsigned Elt) const;
153   int64_t getInt64Field(unsigned Elt) const;
154   DIDescriptor getDescriptorField(unsigned Elt) const;
155
156   template <typename DescTy> DescTy getFieldAs(unsigned Elt) const {
157     return DescTy(getDescriptorField(Elt));
158   }
159
160   GlobalVariable *getGlobalVariableField(unsigned Elt) const;
161   Constant *getConstantField(unsigned Elt) const;
162   Function *getFunctionField(unsigned Elt) const;
163   void replaceFunctionField(unsigned Elt, Function *F);
164
165 public:
166   explicit DIDescriptor(const MDNode *N = nullptr) : DbgNode(N) {}
167
168   bool Verify() const;
169
170   operator MDNode *() const { return const_cast<MDNode *>(DbgNode); }
171   MDNode *operator->() const { return const_cast<MDNode *>(DbgNode); }
172
173   // An explicit operator bool so that we can do testing of DI values
174   // easily.
175   // FIXME: This operator bool isn't actually protecting anything at the
176   // moment due to the conversion operator above making DIDescriptor nodes
177   // implicitly convertable to bool.
178   LLVM_EXPLICIT operator bool() const { return DbgNode != nullptr; }
179
180   bool operator==(DIDescriptor Other) const { return DbgNode == Other.DbgNode; }
181   bool operator!=(DIDescriptor Other) const { return !operator==(Other); }
182
183   StringRef getHeader() const {
184     return getStringField(0);
185   }
186
187   size_t getNumHeaderFields() const {
188     return std::distance(DIHeaderFieldIterator(getHeader()),
189                          DIHeaderFieldIterator());
190   }
191
192   StringRef getHeaderField(unsigned Index) const {
193     // Since callers expect an empty string for out-of-range accesses, we can't
194     // use std::advance() here.
195     for (DIHeaderFieldIterator I(getHeader()), E; I != E; ++I, --Index)
196       if (!Index)
197         return *I;
198     return StringRef();
199   }
200
201   template <class T> T getHeaderFieldAs(unsigned Index) const {
202     T Int;
203     if (getHeaderField(Index).getAsInteger(0, Int))
204       return 0;
205     return Int;
206   }
207
208   uint16_t getTag() const { return getHeaderFieldAs<uint16_t>(0); }
209
210   bool isDerivedType() const;
211   bool isCompositeType() const;
212   bool isSubroutineType() const;
213   bool isBasicType() const;
214   bool isVariable() const;
215   bool isSubprogram() const;
216   bool isGlobalVariable() const;
217   bool isScope() const;
218   bool isFile() const;
219   bool isCompileUnit() const;
220   bool isNameSpace() const;
221   bool isLexicalBlockFile() const;
222   bool isLexicalBlock() const;
223   bool isSubrange() const;
224   bool isEnumerator() const;
225   bool isType() const;
226   bool isTemplateTypeParameter() const;
227   bool isTemplateValueParameter() const;
228   bool isObjCProperty() const;
229   bool isImportedEntity() const;
230   bool isExpression() const;
231
232   void print(raw_ostream &OS) const;
233   void dump() const;
234
235   /// \brief Replace all uses of debug info referenced by this descriptor.
236   void replaceAllUsesWith(LLVMContext &VMContext, DIDescriptor D);
237   void replaceAllUsesWith(MDNode *D);
238 };
239
240 /// \brief This is used to represent ranges, for array bounds.
241 class DISubrange : public DIDescriptor {
242   friend class DIDescriptor;
243   void printInternal(raw_ostream &OS) const;
244
245 public:
246   explicit DISubrange(const MDNode *N = nullptr) : DIDescriptor(N) {}
247
248   int64_t getLo() const { return getHeaderFieldAs<int64_t>(1); }
249   int64_t getCount() const { return getHeaderFieldAs<int64_t>(2); }
250   bool Verify() const;
251 };
252
253 /// \brief This descriptor holds an array of nodes with type T.
254 template <typename T> class DITypedArray : public DIDescriptor {
255 public:
256   explicit DITypedArray(const MDNode *N = nullptr) : DIDescriptor(N) {}
257   unsigned getNumElements() const {
258     return DbgNode ? DbgNode->getNumOperands() : 0;
259   }
260   T getElement(unsigned Idx) const {
261     return getFieldAs<T>(Idx);
262   }
263 };
264
265 typedef DITypedArray<DIDescriptor> DIArray;
266
267 /// \brief A wrapper for an enumerator (e.g. X and Y in 'enum {X,Y}').
268 ///
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;
274
275 public:
276   explicit DIEnumerator(const MDNode *N = nullptr) : DIDescriptor(N) {}
277
278   StringRef getName() const { return getHeaderField(1); }
279   int64_t getEnumValue() const { return getHeaderFieldAs<int64_t>(2); }
280   bool Verify() const;
281 };
282
283 template <typename T> class DIRef;
284 typedef DIRef<DIScope> DIScopeRef;
285 typedef DIRef<DIType> DITypeRef;
286 typedef DITypedArray<DITypeRef> DITypeArray;
287
288 /// \brief 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;
300
301 public:
302   explicit DIScope(const MDNode *N = nullptr) : DIDescriptor(N) {}
303
304   /// \brief Get the parent scope.
305   ///
306   /// Gets the parent scope for this scope node or returns a default
307   /// constructed scope.
308   DIScopeRef getContext() const;
309   /// \brief Get the scope name.
310   ///
311   /// If the scope node has a name, return that, else return an empty string.
312   StringRef getName() const;
313   StringRef getFilename() const;
314   StringRef getDirectory() const;
315
316   /// \brief Generate a reference to this DIScope.
317   ///
318   /// Uses the type identifier instead of the actual MDNode if possible, to
319   /// help type uniquing.
320   DIScopeRef getRef() const;
321 };
322
323 /// \brief Represents reference to a DIDescriptor.
324 ///
325 /// Abstracts over direct and identifier-based metadata references.
326 template <typename T> class DIRef {
327   template <typename DescTy>
328   friend DescTy DIDescriptor::getFieldAs(unsigned Elt) const;
329   friend DIScopeRef DIScope::getContext() const;
330   friend DIScopeRef DIScope::getRef() const;
331   friend class DIType;
332
333   /// \brief Val can be either a MDNode or a MDString.
334   ///
335   /// In the latter, MDString specifies the type identifier.
336   const Value *Val;
337   explicit DIRef(const Value *V);
338
339 public:
340   T resolve(const DITypeIdentifierMap &Map) const;
341   StringRef getName() const;
342   operator Value *() const { return const_cast<Value *>(Val); }
343 };
344
345 template <typename T>
346 T DIRef<T>::resolve(const DITypeIdentifierMap &Map) const {
347   if (!Val)
348     return T();
349
350   if (const MDNode *MD = dyn_cast<MDNode>(Val))
351     return T(MD);
352
353   const MDString *MS = cast<MDString>(Val);
354   // Find the corresponding MDNode.
355   DITypeIdentifierMap::const_iterator Iter = Map.find(MS);
356   assert(Iter != Map.end() && "Identifier not in the type map?");
357   assert(DIDescriptor(Iter->second).isType() &&
358          "MDNode in DITypeIdentifierMap should be a DIType.");
359   return T(Iter->second);
360 }
361
362 template <typename T> StringRef DIRef<T>::getName() const {
363   if (!Val)
364     return StringRef();
365
366   if (const MDNode *MD = dyn_cast<MDNode>(Val))
367     return T(MD).getName();
368
369   const MDString *MS = cast<MDString>(Val);
370   return MS->getString();
371 }
372
373 /// \brief Handle fields that are references to DIScopes.
374 template <> DIScopeRef DIDescriptor::getFieldAs<DIScopeRef>(unsigned Elt) const;
375 /// \brief Specialize DIRef constructor for DIScopeRef.
376 template <> DIRef<DIScope>::DIRef(const Value *V);
377
378 /// \brief Handle fields that are references to DITypes.
379 template <> DITypeRef DIDescriptor::getFieldAs<DITypeRef>(unsigned Elt) const;
380 /// \brief Specialize DIRef constructor for DITypeRef.
381 template <> DIRef<DIType>::DIRef(const Value *V);
382
383 /// \briefThis is a wrapper for a type.
384 ///
385 /// FIXME: Types should be factored much better so that CV qualifiers and
386 /// others do not require a huge and empty descriptor full of zeros.
387 class DIType : public DIScope {
388 protected:
389   friend class DIDescriptor;
390   void printInternal(raw_ostream &OS) const;
391
392 public:
393   explicit DIType(const MDNode *N = nullptr) : DIScope(N) {}
394   operator DITypeRef () const {
395     assert(isType() &&
396            "constructing DITypeRef from an MDNode that is not a type");
397     return DITypeRef(&*getRef());
398   }
399
400   bool Verify() const;
401
402   DIScopeRef getContext() const { return getFieldAs<DIScopeRef>(2); }
403   StringRef getName() const { return getHeaderField(1); }
404   unsigned getLineNumber() const {
405     return getHeaderFieldAs<unsigned>(2);
406   }
407   uint64_t getSizeInBits() const {
408     return getHeaderFieldAs<unsigned>(3);
409   }
410   uint64_t getAlignInBits() const {
411     return getHeaderFieldAs<unsigned>(4);
412   }
413   // FIXME: Offset is only used for DW_TAG_member nodes.  Making every type
414   // carry this is just plain insane.
415   uint64_t getOffsetInBits() const {
416     return getHeaderFieldAs<unsigned>(5);
417   }
418   unsigned getFlags() const { return getHeaderFieldAs<unsigned>(6); }
419   bool isPrivate() const {
420     return (getFlags() & FlagAccessibility) == FlagPrivate;
421   }
422   bool isProtected() const {
423     return (getFlags() & FlagAccessibility) == FlagProtected;
424   }
425   bool isPublic() const {
426     return (getFlags() & FlagAccessibility) == FlagPublic;
427   }
428   bool isForwardDecl() const { return (getFlags() & FlagFwdDecl) != 0; }
429   bool isAppleBlockExtension() const {
430     return (getFlags() & FlagAppleBlock) != 0;
431   }
432   bool isBlockByrefStruct() const {
433     return (getFlags() & FlagBlockByrefStruct) != 0;
434   }
435   bool isVirtual() const { return (getFlags() & FlagVirtual) != 0; }
436   bool isArtificial() const { return (getFlags() & FlagArtificial) != 0; }
437   bool isObjectPointer() const { return (getFlags() & FlagObjectPointer) != 0; }
438   bool isObjcClassComplete() const {
439     return (getFlags() & FlagObjcClassComplete) != 0;
440   }
441   bool isVector() const { return (getFlags() & FlagVector) != 0; }
442   bool isStaticMember() const { return (getFlags() & FlagStaticMember) != 0; }
443   bool isLValueReference() const {
444     return (getFlags() & FlagLValueReference) != 0;
445   }
446   bool isRValueReference() const {
447     return (getFlags() & FlagRValueReference) != 0;
448   }
449   bool isValid() const { return DbgNode && isType(); }
450 };
451
452 /// \brief A basic type, like 'int' or 'float'.
453 class DIBasicType : public DIType {
454 public:
455   explicit DIBasicType(const MDNode *N = nullptr) : DIType(N) {}
456
457   unsigned getEncoding() const { return getHeaderFieldAs<unsigned>(7); }
458
459   bool Verify() const;
460 };
461
462 /// \brief A simple derived type
463 ///
464 /// Like a const qualified type, a typedef, a pointer or reference, et cetera.
465 /// Or, a data member of a class/struct/union.
466 class DIDerivedType : public DIType {
467   friend class DIDescriptor;
468   void printInternal(raw_ostream &OS) const;
469
470 public:
471   explicit DIDerivedType(const MDNode *N = nullptr) : DIType(N) {}
472
473   DITypeRef getTypeDerivedFrom() const { return getFieldAs<DITypeRef>(3); }
474
475   /// \brief Return property node, if this ivar is associated with one.
476   MDNode *getObjCProperty() const;
477
478   DITypeRef getClassType() const {
479     assert(getTag() == dwarf::DW_TAG_ptr_to_member_type);
480     return getFieldAs<DITypeRef>(4);
481   }
482
483   Constant *getConstant() const {
484     assert((getTag() == dwarf::DW_TAG_member) && isStaticMember());
485     return getConstantField(4);
486   }
487
488   bool Verify() const;
489 };
490
491 /// \brief Types that refer to multiple other types.
492 ///
493 /// This descriptor holds a type that can refer to multiple other types, like a
494 /// function or struct.
495 ///
496 /// DICompositeType is derived from DIDerivedType because some
497 /// composite types (such as enums) can be derived from basic types
498 // FIXME: Make this derive from DIType directly & just store the
499 // base type in a single DIType field.
500 class DICompositeType : public DIDerivedType {
501   friend class DIDescriptor;
502   void printInternal(raw_ostream &OS) const;
503
504   /// \brief Set the array of member DITypes.
505   void setArraysHelper(MDNode *Elements, MDNode *TParams);
506
507 public:
508   explicit DICompositeType(const MDNode *N = nullptr) : DIDerivedType(N) {}
509
510   DIArray getElements() const {
511     assert(!isSubroutineType() && "no elements for DISubroutineType");
512     return getFieldAs<DIArray>(4);
513   }
514   template <typename T>
515   void setArrays(DITypedArray<T> Elements, DIArray TParams = DIArray()) {
516     assert((!TParams || DbgNode->getNumOperands() == 8) &&
517            "If you're setting the template parameters this should include a slot "
518            "for that!");
519     setArraysHelper(Elements, TParams);
520   }
521   unsigned getRunTimeLang() const {
522     return getHeaderFieldAs<unsigned>(7);
523   }
524   DITypeRef getContainingType() const { return getFieldAs<DITypeRef>(5); }
525
526   /// \brief Set the containing type.
527   void setContainingType(DICompositeType ContainingType);
528   DIArray getTemplateParams() const { return getFieldAs<DIArray>(6); }
529   MDString *getIdentifier() const;
530
531   bool Verify() const;
532 };
533
534 class DISubroutineType : public DICompositeType {
535 public:
536   explicit DISubroutineType(const MDNode *N = nullptr) : DICompositeType(N) {}
537   DITypedArray<DITypeRef> getTypeArray() const {
538     return getFieldAs<DITypedArray<DITypeRef>>(4);
539   }
540 };
541
542 /// \brief This is a wrapper for a file.
543 class DIFile : public DIScope {
544   friend class DIDescriptor;
545
546 public:
547   explicit DIFile(const MDNode *N = nullptr) : DIScope(N) {}
548
549   /// \brief Retrieve the MDNode for the directory/file pair.
550   MDNode *getFileNode() const;
551   bool Verify() const;
552 };
553
554 /// \brief A wrapper for a compile unit.
555 class DICompileUnit : public DIScope {
556   friend class DIDescriptor;
557   void printInternal(raw_ostream &OS) const;
558
559 public:
560   explicit DICompileUnit(const MDNode *N = nullptr) : DIScope(N) {}
561
562   dwarf::SourceLanguage getLanguage() const {
563     return static_cast<dwarf::SourceLanguage>(getHeaderFieldAs<unsigned>(1));
564   }
565   StringRef getProducer() const { return getHeaderField(2); }
566
567   bool isOptimized() const { return getHeaderFieldAs<bool>(3) != 0; }
568   StringRef getFlags() const { return getHeaderField(4); }
569   unsigned getRunTimeVersion() const { return getHeaderFieldAs<unsigned>(5); }
570
571   DIArray getEnumTypes() const;
572   DIArray getRetainedTypes() const;
573   DIArray getSubprograms() const;
574   DIArray getGlobalVariables() const;
575   DIArray getImportedEntities() const;
576
577   void replaceSubprograms(DIArray Subprograms);
578   void replaceGlobalVariables(DIArray GlobalVariables);
579
580   StringRef getSplitDebugFilename() const { return getHeaderField(6); }
581   unsigned getEmissionKind() const { return getHeaderFieldAs<unsigned>(7); }
582
583   bool Verify() const;
584 };
585
586 /// \brief This is a wrapper for a subprogram (e.g. a function).
587 class DISubprogram : public DIScope {
588   friend class DIDescriptor;
589   void printInternal(raw_ostream &OS) const;
590
591 public:
592   explicit DISubprogram(const MDNode *N = nullptr) : DIScope(N) {}
593
594   StringRef getName() const { return getHeaderField(1); }
595   StringRef getDisplayName() const { return getHeaderField(2); }
596   StringRef getLinkageName() const { return getHeaderField(3); }
597   unsigned getLineNumber() const { return getHeaderFieldAs<unsigned>(4); }
598
599   /// \brief Check if this is local (like 'static' in C).
600   unsigned isLocalToUnit() const { return getHeaderFieldAs<unsigned>(5); }
601   unsigned isDefinition() const { return getHeaderFieldAs<unsigned>(6); }
602
603   unsigned getVirtuality() const { return getHeaderFieldAs<unsigned>(7); }
604   unsigned getVirtualIndex() const { return getHeaderFieldAs<unsigned>(8); }
605
606   unsigned getFlags() const { return getHeaderFieldAs<unsigned>(9); }
607
608   unsigned isOptimized() const { return getHeaderFieldAs<bool>(10); }
609
610   /// \brief Get the beginning of the scope of the function (not the name).
611   unsigned getScopeLineNumber() const { return getHeaderFieldAs<unsigned>(11); }
612
613   DIScopeRef getContext() const { return getFieldAs<DIScopeRef>(2); }
614   DISubroutineType getType() const { return getFieldAs<DISubroutineType>(3); }
615
616   DITypeRef getContainingType() const { return getFieldAs<DITypeRef>(4); }
617
618   bool Verify() const;
619
620   /// \brief Check if this provides debugging information for the function F.
621   bool describes(const Function *F);
622
623   Function *getFunction() const { return getFunctionField(5); }
624   void replaceFunction(Function *F) { replaceFunctionField(5, F); }
625   DIArray getTemplateParams() const { return getFieldAs<DIArray>(6); }
626   DISubprogram getFunctionDeclaration() const {
627     return getFieldAs<DISubprogram>(7);
628   }
629   MDNode *getVariablesNodes() const;
630   DIArray getVariables() const;
631
632   unsigned isArtificial() const { return (getFlags() & FlagArtificial) != 0; }
633   /// \brief Check for the "private" access specifier.
634   bool isPrivate() const {
635     return (getFlags() & FlagAccessibility) == FlagPrivate;
636   }
637   /// \brief Check for the "protected" access specifier.
638   bool isProtected() const {
639     return (getFlags() & FlagAccessibility) == FlagProtected;
640   }
641   /// \brief Check for the "public" access specifier.
642   bool isPublic() const {
643     return (getFlags() & FlagAccessibility) == FlagPublic;
644   }
645   /// \brief Check for "explicit".
646   bool isExplicit() const { return (getFlags() & FlagExplicit) != 0; }
647   /// \brief Check if this is prototyped.
648   bool isPrototyped() const { return (getFlags() & FlagPrototyped) != 0; }
649
650   /// \brief Check if this is reference-qualified.
651   ///
652   /// Return true if this subprogram is a C++11 reference-qualified non-static
653   /// member function (void foo() &).
654   unsigned isLValueReference() const {
655     return (getFlags() & FlagLValueReference) != 0;
656   }
657
658   /// \brief Check if this is rvalue-reference-qualified.
659   ///
660   /// Return true if this subprogram is a C++11 rvalue-reference-qualified
661   /// non-static member function (void foo() &&).
662   unsigned isRValueReference() const {
663     return (getFlags() & FlagRValueReference) != 0;
664   }
665
666 };
667
668 /// \brief This is a wrapper for a lexical block.
669 class DILexicalBlock : public DIScope {
670 public:
671   explicit DILexicalBlock(const MDNode *N = nullptr) : DIScope(N) {}
672   DIScope getContext() const { return getFieldAs<DIScope>(2); }
673   unsigned getLineNumber() const {
674     return getHeaderFieldAs<unsigned>(1);
675   }
676   unsigned getColumnNumber() const {
677     return getHeaderFieldAs<unsigned>(2);
678   }
679   bool Verify() const;
680 };
681
682 /// \brief This is a wrapper for a lexical block with a filename change.
683 class DILexicalBlockFile : public DIScope {
684 public:
685   explicit DILexicalBlockFile(const MDNode *N = nullptr) : DIScope(N) {}
686   DIScope getContext() const {
687     if (getScope().isSubprogram())
688       return getScope();
689     return getScope().getContext();
690   }
691   unsigned getLineNumber() const { return getScope().getLineNumber(); }
692   unsigned getColumnNumber() const { return getScope().getColumnNumber(); }
693   DILexicalBlock getScope() const { return getFieldAs<DILexicalBlock>(2); }
694   unsigned getDiscriminator() const { return getHeaderFieldAs<unsigned>(1); }
695   bool Verify() const;
696 };
697
698 /// \brief A wrapper for a C++ style name space.
699 class DINameSpace : public DIScope {
700   friend class DIDescriptor;
701   void printInternal(raw_ostream &OS) const;
702
703 public:
704   explicit DINameSpace(const MDNode *N = nullptr) : DIScope(N) {}
705   StringRef getName() const { return getHeaderField(1); }
706   unsigned getLineNumber() const { return getHeaderFieldAs<unsigned>(2); }
707   DIScope getContext() const { return getFieldAs<DIScope>(2); }
708   bool Verify() const;
709 };
710
711 /// \brief This is a wrapper for template type parameter.
712 class DITemplateTypeParameter : public DIDescriptor {
713 public:
714   explicit DITemplateTypeParameter(const MDNode *N = nullptr)
715     : DIDescriptor(N) {}
716
717   StringRef getName() const { return getHeaderField(1); }
718   unsigned getLineNumber() const { return getHeaderFieldAs<unsigned>(2); }
719   unsigned getColumnNumber() const { return getHeaderFieldAs<unsigned>(3); }
720
721   DIScopeRef getContext() const { return getFieldAs<DIScopeRef>(1); }
722   DITypeRef getType() const { return getFieldAs<DITypeRef>(2); }
723   StringRef getFilename() const { return getFieldAs<DIFile>(3).getFilename(); }
724   StringRef getDirectory() const {
725     return getFieldAs<DIFile>(3).getDirectory();
726   }
727   bool Verify() const;
728 };
729
730 /// \brief This is a wrapper for template value parameter.
731 class DITemplateValueParameter : public DIDescriptor {
732 public:
733   explicit DITemplateValueParameter(const MDNode *N = nullptr)
734     : DIDescriptor(N) {}
735
736   StringRef getName() const { return getHeaderField(1); }
737   unsigned getLineNumber() const { return getHeaderFieldAs<unsigned>(2); }
738   unsigned getColumnNumber() const { return getHeaderFieldAs<unsigned>(3); }
739
740   DIScopeRef getContext() const { return getFieldAs<DIScopeRef>(1); }
741   DITypeRef getType() const { return getFieldAs<DITypeRef>(2); }
742   Value *getValue() const;
743   StringRef getFilename() const { return getFieldAs<DIFile>(4).getFilename(); }
744   StringRef getDirectory() const {
745     return getFieldAs<DIFile>(4).getDirectory();
746   }
747   bool Verify() const;
748 };
749
750 /// \brief This is a wrapper for a global variable.
751 class DIGlobalVariable : public DIDescriptor {
752   friend class DIDescriptor;
753   void printInternal(raw_ostream &OS) const;
754
755 public:
756   explicit DIGlobalVariable(const MDNode *N = nullptr) : DIDescriptor(N) {}
757
758   StringRef getName() const { return getHeaderField(1); }
759   StringRef getDisplayName() const { return getHeaderField(2); }
760   StringRef getLinkageName() const { return getHeaderField(3); }
761   unsigned getLineNumber() const { return getHeaderFieldAs<unsigned>(4); }
762   unsigned isLocalToUnit() const { return getHeaderFieldAs<bool>(5); }
763   unsigned isDefinition() const { return getHeaderFieldAs<bool>(6); }
764
765   DIScope getContext() const { return getFieldAs<DIScope>(1); }
766   StringRef getFilename() const { return getFieldAs<DIFile>(2).getFilename(); }
767   StringRef getDirectory() const {
768     return getFieldAs<DIFile>(2).getDirectory();
769   }
770   DITypeRef getType() const { return getFieldAs<DITypeRef>(3); }
771
772   GlobalVariable *getGlobal() const { return getGlobalVariableField(4); }
773   Constant *getConstant() const { return getConstantField(4); }
774   DIDerivedType getStaticDataMemberDeclaration() const {
775     return getFieldAs<DIDerivedType>(5);
776   }
777
778   bool Verify() const;
779 };
780
781 /// \brief This is a wrapper for a variable (e.g. parameter, local, global etc).
782 class DIVariable : public DIDescriptor {
783   friend class DIDescriptor;
784   void printInternal(raw_ostream &OS) const;
785
786 public:
787   explicit DIVariable(const MDNode *N = nullptr) : DIDescriptor(N) {}
788
789   StringRef getName() const { return getHeaderField(1); }
790   unsigned getLineNumber() const {
791     // FIXME: Line number and arg number shouldn't be merged together like this.
792     return (getHeaderFieldAs<unsigned>(2) << 8) >> 8;
793   }
794   unsigned getArgNumber() const { return getHeaderFieldAs<unsigned>(2) >> 24; }
795
796   DIScope getContext() const { return getFieldAs<DIScope>(1); }
797   DIFile getFile() const { return getFieldAs<DIFile>(2); }
798   DITypeRef getType() const { return getFieldAs<DITypeRef>(3); }
799
800   /// \brief Return true if this variable is marked as "artificial".
801   bool isArtificial() const {
802     return (getHeaderFieldAs<unsigned>(3) & FlagArtificial) != 0;
803   }
804
805   bool isObjectPointer() const {
806     return (getHeaderFieldAs<unsigned>(3) & FlagObjectPointer) != 0;
807   }
808
809   /// \brief Return true if this variable is represented as a pointer.
810   bool isIndirect() const {
811     return (getHeaderFieldAs<unsigned>(3) & FlagIndirectVariable) != 0;
812   }
813
814   /// \brief If this variable is inlined then return inline location.
815   MDNode *getInlinedAt() const;
816
817   bool Verify() const;
818
819   /// \brief Check if this is a "__block" variable (Apple Blocks).
820   bool isBlockByrefVariable(const DITypeIdentifierMap &Map) const {
821     return (getType().resolve(Map)).isBlockByrefStruct();
822   }
823
824   /// \brief Check if this is an inlined function argument.
825   bool isInlinedFnArgument(const Function *CurFn);
826
827   /// \brief Return the size reported by the variable's type.
828   unsigned getSizeInBits(const DITypeIdentifierMap &Map);
829
830   void printExtendedName(raw_ostream &OS) const;
831 };
832
833 /// \brief A complex location expression.
834 class DIExpression : public DIDescriptor {
835   friend class DIDescriptor;
836   void printInternal(raw_ostream &OS) const;
837
838 public:
839   explicit DIExpression(const MDNode *N = nullptr) : DIDescriptor(N) {}
840
841   bool Verify() const;
842
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   }
851
852   /// \brief return the Idx'th complex address element.
853   uint64_t getElement(unsigned Idx) const;
854
855   /// \brief Return whether this is a piece of an aggregate variable.
856   bool isVariablePiece() const;
857   /// \brief Return the offset of this piece in bytes.
858   uint64_t getPieceOffset() const;
859   /// \brief Return the size of this piece in bytes.
860   uint64_t getPieceSize() const;
861 };
862
863 /// \brief This object holds location information.
864 ///
865 /// This object is not associated with any DWARF tag.
866 class DILocation : public DIDescriptor {
867 public:
868   explicit DILocation(const MDNode *N) : DIDescriptor(N) {}
869
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   /// \brief Get the DWAF discriminator.
882   ///
883   /// DWARF discriminators are used to distinguish identical file locations for
884   /// instructions that are on different basic blocks. If two instructions are
885   /// inside the same lexical block and are in different basic blocks, we
886   /// create a new lexical block with identical location as the original but
887   /// with a different discriminator value
888   /// (lib/Transforms/Util/AddDiscriminators.cpp for details).
889   unsigned getDiscriminator() const {
890     // Since discriminators are associated with lexical blocks, make
891     // sure this location is a lexical block before retrieving its
892     // value.
893     return getScope().isLexicalBlockFile()
894                ? getFieldAs<DILexicalBlockFile>(2).getDiscriminator()
895                : 0;
896   }
897
898   /// \brief Generate a new discriminator value for this location.
899   unsigned computeNewDiscriminator(LLVMContext &Ctx);
900
901   /// \brief Return a copy of this location with a different scope.
902   DILocation copyWithNewScope(LLVMContext &Ctx, DILexicalBlockFile NewScope);
903 };
904
905 class DIObjCProperty : public DIDescriptor {
906   friend class DIDescriptor;
907   void printInternal(raw_ostream &OS) const;
908
909 public:
910   explicit DIObjCProperty(const MDNode *N) : DIDescriptor(N) {}
911
912   StringRef getObjCPropertyName() const { return getHeaderField(1); }
913   DIFile getFile() const { return getFieldAs<DIFile>(1); }
914   unsigned getLineNumber() const { return getHeaderFieldAs<unsigned>(2); }
915
916   StringRef getObjCPropertyGetterName() const { return getHeaderField(3); }
917   StringRef getObjCPropertySetterName() const { return getHeaderField(4); }
918   unsigned getAttributes() const { return getHeaderFieldAs<unsigned>(5); }
919   bool isReadOnlyObjCProperty() const {
920     return (getAttributes() & dwarf::DW_APPLE_PROPERTY_readonly) != 0;
921   }
922   bool isReadWriteObjCProperty() const {
923     return (getAttributes() & dwarf::DW_APPLE_PROPERTY_readwrite) != 0;
924   }
925   bool isAssignObjCProperty() const {
926     return (getAttributes() & dwarf::DW_APPLE_PROPERTY_assign) != 0;
927   }
928   bool isRetainObjCProperty() const {
929     return (getAttributes() & dwarf::DW_APPLE_PROPERTY_retain) != 0;
930   }
931   bool isCopyObjCProperty() const {
932     return (getAttributes() & dwarf::DW_APPLE_PROPERTY_copy) != 0;
933   }
934   bool isNonAtomicObjCProperty() const {
935     return (getAttributes() & dwarf::DW_APPLE_PROPERTY_nonatomic) != 0;
936   }
937
938   /// \brief Get the type.
939   ///
940   /// \note Objective-C doesn't have an ODR, so there is no benefit in storing
941   /// the type as a DITypeRef here.
942   DIType getType() const { return getFieldAs<DIType>(2); }
943
944   bool Verify() const;
945 };
946
947 /// \brief An imported module (C++ using directive or similar).
948 class DIImportedEntity : public DIDescriptor {
949   friend class DIDescriptor;
950   void printInternal(raw_ostream &OS) const;
951
952 public:
953   explicit DIImportedEntity(const MDNode *N) : DIDescriptor(N) {}
954   DIScope getContext() const { return getFieldAs<DIScope>(1); }
955   DIScopeRef getEntity() const { return getFieldAs<DIScopeRef>(2); }
956   unsigned getLineNumber() const { return getHeaderFieldAs<unsigned>(1); }
957   StringRef getName() const { return getHeaderField(2); }
958   bool Verify() const;
959 };
960
961 /// \brief Find subprogram that is enclosing this scope.
962 DISubprogram getDISubprogram(const MDNode *Scope);
963
964 /// \brief Find underlying composite type.
965 DICompositeType getDICompositeType(DIType T);
966
967 /// \brief Create a new inlined variable based on current variable.
968 ///
969 /// @param DV            Current Variable.
970 /// @param InlinedScope  Location at current variable is inlined.
971 DIVariable createInlinedVariable(MDNode *DV, MDNode *InlinedScope,
972                                  LLVMContext &VMContext);
973
974 /// \brief Remove inlined scope from the variable.
975 DIVariable cleanseInlinedVariable(MDNode *DV, LLVMContext &VMContext);
976
977 /// \brief Generate map by visiting all retained types.
978 DITypeIdentifierMap generateDITypeIdentifierMap(const NamedMDNode *CU_Nodes);
979
980 /// \brief Strip debug info in the module if it exists.
981 ///
982 /// To do this, we remove all calls to the debugger intrinsics and any named
983 /// metadata for debugging. We also remove debug locations for instructions.
984 /// Return true if module is modified.
985 bool StripDebugInfo(Module &M);
986
987 /// \brief Return Debug Info Metadata Version by checking module flags.
988 unsigned getDebugMetadataVersionFromModule(const Module &M);
989
990 /// \brief Utility to find all debug info in a module.
991 ///
992 /// DebugInfoFinder tries to list all debug info MDNodes used in a module. To
993 /// list debug info MDNodes used by an instruction, DebugInfoFinder uses
994 /// processDeclare, processValue and processLocation to handle DbgDeclareInst,
995 /// DbgValueInst and DbgLoc attached to instructions. processModule will go
996 /// through all DICompileUnits in llvm.dbg.cu and list debug info MDNodes
997 /// used by the CUs.
998 class DebugInfoFinder {
999 public:
1000   DebugInfoFinder() : TypeMapInitialized(false) {}
1001
1002   /// \brief Process entire module and collect debug info anchors.
1003   void processModule(const Module &M);
1004
1005   /// \brief Process DbgDeclareInst.
1006   void processDeclare(const Module &M, const DbgDeclareInst *DDI);
1007   /// \brief Process DbgValueInst.
1008   void processValue(const Module &M, const DbgValueInst *DVI);
1009   /// \brief Process DILocation.
1010   void processLocation(const Module &M, DILocation Loc);
1011
1012   /// \brief Clear all lists.
1013   void reset();
1014
1015 private:
1016   void InitializeTypeMap(const Module &M);
1017
1018   void processType(DIType DT);
1019   void processSubprogram(DISubprogram SP);
1020   void processScope(DIScope Scope);
1021   bool addCompileUnit(DICompileUnit CU);
1022   bool addGlobalVariable(DIGlobalVariable DIG);
1023   bool addSubprogram(DISubprogram SP);
1024   bool addType(DIType DT);
1025   bool addScope(DIScope Scope);
1026
1027 public:
1028   typedef SmallVectorImpl<DICompileUnit>::const_iterator compile_unit_iterator;
1029   typedef SmallVectorImpl<DISubprogram>::const_iterator subprogram_iterator;
1030   typedef SmallVectorImpl<DIGlobalVariable>::const_iterator global_variable_iterator;
1031   typedef SmallVectorImpl<DIType>::const_iterator type_iterator;
1032   typedef SmallVectorImpl<DIScope>::const_iterator scope_iterator;
1033
1034   iterator_range<compile_unit_iterator> compile_units() const {
1035     return iterator_range<compile_unit_iterator>(CUs.begin(), CUs.end());
1036   }
1037
1038   iterator_range<subprogram_iterator> subprograms() const {
1039     return iterator_range<subprogram_iterator>(SPs.begin(), SPs.end());
1040   }
1041
1042   iterator_range<global_variable_iterator> global_variables() const {
1043     return iterator_range<global_variable_iterator>(GVs.begin(), GVs.end());
1044   }
1045
1046   iterator_range<type_iterator> types() const {
1047     return iterator_range<type_iterator>(TYs.begin(), TYs.end());
1048   }
1049
1050   iterator_range<scope_iterator> scopes() const {
1051     return iterator_range<scope_iterator>(Scopes.begin(), Scopes.end());
1052   }
1053
1054   unsigned compile_unit_count() const { return CUs.size(); }
1055   unsigned global_variable_count() const { return GVs.size(); }
1056   unsigned subprogram_count() const { return SPs.size(); }
1057   unsigned type_count() const { return TYs.size(); }
1058   unsigned scope_count() const { return Scopes.size(); }
1059
1060 private:
1061   SmallVector<DICompileUnit, 8> CUs;
1062   SmallVector<DISubprogram, 8> SPs;
1063   SmallVector<DIGlobalVariable, 8> GVs;
1064   SmallVector<DIType, 8> TYs;
1065   SmallVector<DIScope, 8> Scopes;
1066   SmallPtrSet<MDNode *, 64> NodesSeen;
1067   DITypeIdentifierMap TypeIdentifierMap;
1068
1069   /// \brief Specify if TypeIdentifierMap is initialized.
1070   bool TypeMapInitialized;
1071 };
1072
1073 DenseMap<const Function *, DISubprogram> makeSubprogramMap(const Module &M);
1074
1075 } // end namespace llvm
1076
1077 #endif