d2f752c5548dce850417ba6e3132508d4a4cc913
[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/SmallPtrSet.h"
22 #include "llvm/ADT/SmallVector.h"
23 #include "llvm/ADT/StringRef.h"
24 #include "llvm/ADT/iterator_range.h"
25 #include "llvm/IR/DebugInfoMetadata.h"
26 #include "llvm/Support/Casting.h"
27 #include "llvm/Support/Dwarf.h"
28 #include "llvm/Support/ErrorHandling.h"
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 Metadata;
43 class MDNode;
44 class MDString;
45 class NamedMDNode;
46 class LLVMContext;
47 class raw_ostream;
48
49 class DIFile;
50 class DISubprogram;
51 class DILexicalBlock;
52 class DILexicalBlockFile;
53 class DIVariable;
54 class DIType;
55 class DIScope;
56 class DIObjCProperty;
57
58 /// \brief Maps from type identifier to the actual MDNode.
59 typedef DenseMap<const MDString *, MDNode *> DITypeIdentifierMap;
60
61 class DIHeaderFieldIterator
62     : public std::iterator<std::input_iterator_tag, StringRef, std::ptrdiff_t,
63                            const StringRef *, StringRef> {
64   StringRef Header;
65   StringRef Current;
66
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   }
88
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   }
101
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   }
111
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 };
119
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;
128
129 public:
130   /// \brief Duplicated debug info flags.
131   ///
132   /// \see DebugNode::DIFlags.
133   enum {
134 #define HANDLE_DI_FLAG(ID, NAME) Flag##NAME = DebugNode::Flag##NAME,
135 #include "llvm/IR/DebugInfoFlags.def"
136     FlagAccessibility = DebugNode::FlagAccessibility
137   };
138
139   static unsigned getFlag(StringRef Flag);
140   static const char *getFlagString(unsigned Flag);
141
142   /// \brief Split up a flags bitfield.
143   ///
144   /// Split \c Flags into \c SplitFlags, a vector of its components.  Returns
145   /// any remaining (unrecognized) bits.
146   static unsigned splitFlags(unsigned Flags,
147                              SmallVectorImpl<unsigned> &SplitFlags);
148
149 protected:
150   const MDNode *DbgNode;
151
152   StringRef getStringField(unsigned Elt) const;
153   unsigned getUnsignedField(unsigned Elt) const {
154     return (unsigned)getUInt64Field(Elt);
155   }
156   uint64_t getUInt64Field(unsigned Elt) const;
157   int64_t getInt64Field(unsigned Elt) const;
158   DIDescriptor getDescriptorField(unsigned Elt) const;
159
160   template <typename DescTy> DescTy getFieldAs(unsigned Elt) const {
161     return DescTy(getDescriptorField(Elt));
162   }
163
164   GlobalVariable *getGlobalVariableField(unsigned Elt) const;
165   Constant *getConstantField(unsigned Elt) const;
166   Function *getFunctionField(unsigned Elt) const;
167
168 public:
169   explicit DIDescriptor(const MDNode *N = nullptr) : DbgNode(N) {}
170
171   bool Verify() const;
172
173   MDNode *get() const { return const_cast<MDNode *>(DbgNode); }
174   operator MDNode *() const { return get(); }
175   MDNode *operator->() const { return get(); }
176   MDNode &operator*() const {
177     assert(get() && "Expected valid pointer");
178     return *get();
179   }
180
181   // An explicit operator bool so that we can do testing of DI values
182   // easily.
183   // FIXME: This operator bool isn't actually protecting anything at the
184   // moment due to the conversion operator above making DIDescriptor nodes
185   // implicitly convertable to bool.
186   explicit operator bool() const { return DbgNode != nullptr; }
187
188   bool operator==(DIDescriptor Other) const { return DbgNode == Other.DbgNode; }
189   bool operator!=(DIDescriptor Other) const { return !operator==(Other); }
190
191   StringRef getHeader() const { return getStringField(0); }
192
193   size_t getNumHeaderFields() const {
194     return std::distance(DIHeaderFieldIterator(getHeader()),
195                          DIHeaderFieldIterator());
196   }
197
198   DIHeaderFieldIterator header_begin() const {
199     return DIHeaderFieldIterator(getHeader());
200   }
201   DIHeaderFieldIterator header_end() const { return DIHeaderFieldIterator(); }
202
203   DIHeaderFieldIterator getHeaderIterator(unsigned Index) const {
204     // Since callers expect an empty string for out-of-range accesses, we can't
205     // use std::advance() here.
206     for (auto I = header_begin(), E = header_end(); I != E; ++I, --Index)
207       if (!Index)
208         return I;
209     return header_end();
210   }
211
212   StringRef getHeaderField(unsigned Index) const {
213     return *getHeaderIterator(Index);
214   }
215
216   template <class T> T getHeaderFieldAs(unsigned Index) const {
217     return getHeaderIterator(Index).getNumber<T>();
218   }
219
220   uint16_t getTag() const {
221     if (auto *N = dyn_cast_or_null<DebugNode>(get()))
222       return N->getTag();
223     return 0;
224   }
225
226   bool isDerivedType() const { return get() && isa<MDDerivedTypeBase>(get()); }
227   bool isCompositeType() const {
228     return get() && isa<MDCompositeTypeBase>(get());
229   }
230   bool isSubroutineType() const {
231     return get() && isa<MDSubroutineType>(get());
232   }
233   bool isBasicType() const { return get() && isa<MDBasicType>(get()); }
234   bool isVariable() const { return get() && isa<MDLocalVariable>(get()); }
235   bool isSubprogram() const { return get() && isa<MDSubprogram>(get()); }
236   bool isGlobalVariable() const {
237     return get() && isa<MDGlobalVariable>(get());
238   }
239   bool isScope() const { return get() && isa<MDScope>(get()); }
240   bool isFile() const { return get() && isa<MDFile>(get()); }
241   bool isCompileUnit() const { return get() && isa<MDCompileUnit>(get()); }
242   bool isNameSpace() const{ return get() && isa<MDNamespace>(get()); }
243   bool isLexicalBlockFile() const {
244     return get() && isa<MDLexicalBlockFile>(get());
245   }
246   bool isLexicalBlock() const {
247     return get() && isa<MDLexicalBlockBase>(get());
248   }
249   bool isSubrange() const { return get() && isa<MDSubrange>(get()); }
250   bool isEnumerator() const { return get() && isa<MDEnumerator>(get()); }
251   bool isType() const { return get() && isa<MDType>(get()); }
252   bool isTemplateTypeParameter() const {
253     return get() && isa<MDTemplateTypeParameter>(get());
254   }
255   bool isTemplateValueParameter() const {
256     return get() && isa<MDTemplateValueParameter>(get());
257   }
258   bool isObjCProperty() const { return get() && isa<MDObjCProperty>(get()); }
259   bool isImportedEntity() const {
260     return get() && isa<MDImportedEntity>(get());
261   }
262   bool isExpression() const { return get() && isa<MDExpression>(get()); }
263
264   void print(raw_ostream &OS) const;
265   void dump() const;
266
267   /// \brief Replace all uses of debug info referenced by this descriptor.
268   void replaceAllUsesWith(LLVMContext &VMContext, DIDescriptor D);
269   void replaceAllUsesWith(MDNode *D);
270 };
271
272 /// \brief This is used to represent ranges, for array bounds.
273 class DISubrange : public DIDescriptor {
274 public:
275   explicit DISubrange(const MDNode *N = nullptr) : DIDescriptor(N) {}
276   DISubrange(const MDSubrange *N) : DIDescriptor(N) {}
277
278   MDSubrange *get() const {
279     return cast_or_null<MDSubrange>(DIDescriptor::get());
280   }
281   operator MDSubrange *() const { return get(); }
282   MDSubrange *operator->() const { return get(); }
283   MDSubrange &operator*() const {
284     assert(get() && "Expected valid pointer");
285     return *get();
286   }
287
288   int64_t getLo() const { return get()->getLo(); }
289   int64_t getCount() const { return get()->getCount(); }
290   bool Verify() const;
291 };
292
293 /// \brief This descriptor holds an array of nodes with type T.
294 template <typename T> class DITypedArray : public DIDescriptor {
295 public:
296   explicit DITypedArray(const MDNode *N = nullptr) : DIDescriptor(N) {}
297   unsigned getNumElements() const {
298     return DbgNode ? DbgNode->getNumOperands() : 0;
299   }
300   T getElement(unsigned Idx) const { return getFieldAs<T>(Idx); }
301 };
302
303 typedef DITypedArray<DIDescriptor> DIArray;
304
305 /// \brief A wrapper for an enumerator (e.g. X and Y in 'enum {X,Y}').
306 ///
307 /// FIXME: it seems strange that this doesn't have either a reference to the
308 /// type/precision or a file/line pair for location info.
309 class DIEnumerator : public DIDescriptor {
310 public:
311   explicit DIEnumerator(const MDNode *N = nullptr) : DIDescriptor(N) {}
312   DIEnumerator(const MDEnumerator *N) : DIDescriptor(N) {}
313
314   MDEnumerator *get() const {
315     return cast_or_null<MDEnumerator>(DIDescriptor::get());
316   }
317   operator MDEnumerator *() const { return get(); }
318   MDEnumerator *operator->() const { return get(); }
319   MDEnumerator &operator*() const {
320     assert(get() && "Expected valid pointer");
321     return *get();
322   }
323
324   StringRef getName() const { return get()->getName(); }
325   int64_t getEnumValue() const { return get()->getValue(); }
326   bool Verify() const;
327 };
328
329 template <typename T> class DIRef;
330 typedef DIRef<DIDescriptor> DIDescriptorRef;
331 typedef DIRef<DIScope> DIScopeRef;
332 typedef DIRef<DIType> DITypeRef;
333 typedef DITypedArray<DITypeRef> DITypeArray;
334
335 /// \brief A base class for various scopes.
336 ///
337 /// Although, implementation-wise, DIScope is the parent class of most
338 /// other DIxxx classes, including DIType and its descendants, most of
339 /// DIScope's descendants are not a substitutable subtype of
340 /// DIScope. The DIDescriptor::isScope() method only is true for
341 /// DIScopes that are scopes in the strict lexical scope sense
342 /// (DICompileUnit, DISubprogram, etc.), but not for, e.g., a DIType.
343 class DIScope : public DIDescriptor {
344 public:
345   explicit DIScope(const MDNode *N = nullptr) : DIDescriptor(N) {}
346   DIScope(const MDScope *N) : DIDescriptor(N) {}
347
348   MDScope *get() const { return cast_or_null<MDScope>(DIDescriptor::get()); }
349   operator MDScope *() const { return get(); }
350   MDScope *operator->() const { return get(); }
351   MDScope &operator*() const {
352     assert(get() && "Expected valid pointer");
353     return *get();
354   }
355
356   /// \brief Get the parent scope.
357   ///
358   /// Gets the parent scope for this scope node or returns a default
359   /// constructed scope.
360   DIScopeRef getContext() const;
361   /// \brief Get the scope name.
362   ///
363   /// If the scope node has a name, return that, else return an empty string.
364   StringRef getName() const;
365   StringRef getFilename() const;
366   StringRef getDirectory() const;
367
368   /// \brief Generate a reference to this DIScope.
369   ///
370   /// Uses the type identifier instead of the actual MDNode if possible, to
371   /// help type uniquing.
372   DIScopeRef getRef() const;
373 };
374
375 /// \brief Represents reference to a DIDescriptor.
376 ///
377 /// Abstracts over direct and identifier-based metadata references.
378 template <typename T> class DIRef {
379   template <typename DescTy>
380   friend DescTy DIDescriptor::getFieldAs(unsigned Elt) const;
381   friend DIScopeRef DIScope::getContext() const;
382   friend DIScopeRef DIScope::getRef() const;
383   friend class DIType;
384
385   /// \brief Val can be either a MDNode or a MDString.
386   ///
387   /// In the latter, MDString specifies the type identifier.
388   const Metadata *Val;
389   explicit DIRef(const Metadata *V);
390
391 public:
392   T resolve(const DITypeIdentifierMap &Map) const;
393   StringRef getName() const;
394   operator Metadata *() const { return const_cast<Metadata *>(Val); }
395
396   static DIRef get(const Metadata *MD) { return DIRef(MD); }
397 };
398
399 template <typename T>
400 T DIRef<T>::resolve(const DITypeIdentifierMap &Map) const {
401   if (!Val)
402     return T();
403
404   if (const MDNode *MD = dyn_cast<MDNode>(Val))
405     return T(MD);
406
407   const MDString *MS = cast<MDString>(Val);
408   // Find the corresponding MDNode.
409   DITypeIdentifierMap::const_iterator Iter = Map.find(MS);
410   assert(Iter != Map.end() && "Identifier not in the type map?");
411   assert(DIDescriptor(Iter->second).isType() &&
412          "MDNode in DITypeIdentifierMap should be a DIType.");
413   return T(Iter->second);
414 }
415
416 template <typename T> StringRef DIRef<T>::getName() const {
417   if (!Val)
418     return StringRef();
419
420   if (const MDNode *MD = dyn_cast<MDNode>(Val))
421     return T(MD).getName();
422
423   const MDString *MS = cast<MDString>(Val);
424   return MS->getString();
425 }
426
427 /// \brief Handle fields that are references to DIDescriptors.
428 template <>
429 DIDescriptorRef DIDescriptor::getFieldAs<DIDescriptorRef>(unsigned Elt) const;
430 /// \brief Specialize DIRef constructor for DIDescriptorRef.
431 template <> DIRef<DIDescriptor>::DIRef(const Metadata *V);
432
433 /// \brief Handle fields that are references to DIScopes.
434 template <> DIScopeRef DIDescriptor::getFieldAs<DIScopeRef>(unsigned Elt) const;
435 /// \brief Specialize DIRef constructor for DIScopeRef.
436 template <> DIRef<DIScope>::DIRef(const Metadata *V);
437
438 /// \brief Handle fields that are references to DITypes.
439 template <> DITypeRef DIDescriptor::getFieldAs<DITypeRef>(unsigned Elt) const;
440 /// \brief Specialize DIRef constructor for DITypeRef.
441 template <> DIRef<DIType>::DIRef(const Metadata *V);
442
443 /// \brief This is a wrapper for a type.
444 ///
445 /// FIXME: Types should be factored much better so that CV qualifiers and
446 /// others do not require a huge and empty descriptor full of zeros.
447 class DIType : public DIScope {
448 public:
449   explicit DIType(const MDNode *N = nullptr) : DIScope(N) {}
450   DIType(const MDType *N) : DIScope(N) {}
451
452   MDType *get() const { return cast_or_null<MDType>(DIDescriptor::get()); }
453   operator MDType *() const { return get(); }
454   MDType *operator->() const { return get(); }
455   MDType &operator*() const {
456     assert(get() && "Expected valid pointer");
457     return *get();
458   }
459
460   operator DITypeRef() const {
461     assert(isType() &&
462            "constructing DITypeRef from an MDNode that is not a type");
463     return DITypeRef(&*getRef());
464   }
465
466   bool Verify() const;
467
468   DIScopeRef getContext() const { return DIScopeRef::get(get()->getScope()); }
469   StringRef getName() const { return get()->getName(); }
470   unsigned getLineNumber() const { return get()->getLine(); }
471   uint64_t getSizeInBits() const { return get()->getSizeInBits(); }
472   uint64_t getAlignInBits() const { return get()->getAlignInBits(); }
473   // FIXME: Offset is only used for DW_TAG_member nodes.  Making every type
474   // carry this is just plain insane.
475   uint64_t getOffsetInBits() const { return get()->getOffsetInBits(); }
476   unsigned getFlags() const { return get()->getFlags(); }
477   bool isPrivate() const {
478     return (getFlags() & FlagAccessibility) == FlagPrivate;
479   }
480   bool isProtected() const {
481     return (getFlags() & FlagAccessibility) == FlagProtected;
482   }
483   bool isPublic() const {
484     return (getFlags() & FlagAccessibility) == FlagPublic;
485   }
486   bool isForwardDecl() const { return (getFlags() & FlagFwdDecl) != 0; }
487   bool isAppleBlockExtension() const {
488     return (getFlags() & FlagAppleBlock) != 0;
489   }
490   bool isBlockByrefStruct() const {
491     return (getFlags() & FlagBlockByrefStruct) != 0;
492   }
493   bool isVirtual() const { return (getFlags() & FlagVirtual) != 0; }
494   bool isArtificial() const { return (getFlags() & FlagArtificial) != 0; }
495   bool isObjectPointer() const { return (getFlags() & FlagObjectPointer) != 0; }
496   bool isObjcClassComplete() const {
497     return (getFlags() & FlagObjcClassComplete) != 0;
498   }
499   bool isVector() const { return (getFlags() & FlagVector) != 0; }
500   bool isStaticMember() const { return (getFlags() & FlagStaticMember) != 0; }
501   bool isLValueReference() const {
502     return (getFlags() & FlagLValueReference) != 0;
503   }
504   bool isRValueReference() const {
505     return (getFlags() & FlagRValueReference) != 0;
506   }
507   bool isValid() const { return DbgNode && isType(); }
508 };
509
510 /// \brief A basic type, like 'int' or 'float'.
511 class DIBasicType : public DIType {
512 public:
513   explicit DIBasicType(const MDNode *N = nullptr) : DIType(N) {}
514   DIBasicType(const MDBasicType *N) : DIType(N) {}
515
516   MDBasicType *get() const {
517     return cast_or_null<MDBasicType>(DIDescriptor::get());
518   }
519   operator MDBasicType *() const { return get(); }
520   MDBasicType *operator->() const { return get(); }
521   MDBasicType &operator*() const {
522     assert(get() && "Expected valid pointer");
523     return *get();
524   }
525
526   unsigned getEncoding() const { return get()->getEncoding(); }
527
528   bool Verify() const;
529 };
530
531 /// \brief A simple derived type
532 ///
533 /// Like a const qualified type, a typedef, a pointer or reference, et cetera.
534 /// Or, a data member of a class/struct/union.
535 class DIDerivedType : public DIType {
536 public:
537   explicit DIDerivedType(const MDNode *N = nullptr) : DIType(N) {}
538   DIDerivedType(const MDDerivedTypeBase *N) : DIType(N) {}
539
540   MDDerivedTypeBase *get() const {
541     return cast_or_null<MDDerivedTypeBase>(DIDescriptor::get());
542   }
543   operator MDDerivedTypeBase *() const { return get(); }
544   MDDerivedTypeBase *operator->() const { return get(); }
545   MDDerivedTypeBase &operator*() const {
546     assert(get() && "Expected valid pointer");
547     return *get();
548   }
549
550   DITypeRef getTypeDerivedFrom() const {
551     return DITypeRef::get(get()->getBaseType());
552   }
553
554   /// \brief Return property node, if this ivar is associated with one.
555   MDNode *getObjCProperty() const {
556     if (auto *N = dyn_cast<MDDerivedType>(get()))
557       return dyn_cast_or_null<MDNode>(N->getExtraData());
558     return nullptr;
559   }
560
561   DITypeRef getClassType() const {
562     assert(getTag() == dwarf::DW_TAG_ptr_to_member_type);
563     if (auto *N = dyn_cast<MDDerivedType>(get()))
564       return DITypeRef::get(N->getExtraData());
565     return DITypeRef::get(nullptr);
566   }
567
568   Constant *getConstant() const {
569     assert((getTag() == dwarf::DW_TAG_member) && isStaticMember());
570     if (auto *N = dyn_cast<MDDerivedType>(get()))
571       if (auto *C = dyn_cast_or_null<ConstantAsMetadata>(N->getExtraData()))
572         return C->getValue();
573
574     return nullptr;
575   }
576
577   bool Verify() const;
578 };
579
580 /// \brief Types that refer to multiple other types.
581 ///
582 /// This descriptor holds a type that can refer to multiple other types, like a
583 /// function or struct.
584 ///
585 /// DICompositeType is derived from DIDerivedType because some
586 /// composite types (such as enums) can be derived from basic types
587 // FIXME: Make this derive from DIType directly & just store the
588 // base type in a single DIType field.
589 class DICompositeType : public DIDerivedType {
590   friend class DIBuilder;
591
592   /// \brief Set the array of member DITypes.
593   void setArraysHelper(MDNode *Elements, MDNode *TParams);
594
595 public:
596   explicit DICompositeType(const MDNode *N = nullptr) : DIDerivedType(N) {}
597   DICompositeType(const MDCompositeTypeBase *N) : DIDerivedType(N) {}
598
599   MDCompositeTypeBase *get() const {
600     return cast_or_null<MDCompositeTypeBase>(DIDescriptor::get());
601   }
602   operator MDCompositeTypeBase *() const { return get(); }
603   MDCompositeTypeBase *operator->() const { return get(); }
604   MDCompositeTypeBase &operator*() const {
605     assert(get() && "Expected valid pointer");
606     return *get();
607   }
608
609   DIArray getElements() const {
610     assert(!isSubroutineType() && "no elements for DISubroutineType");
611     return DIArray(get()->getElements());
612   }
613
614 private:
615   template <typename T>
616   void setArrays(DITypedArray<T> Elements, DIArray TParams = DIArray()) {
617     assert(
618         (!TParams || DbgNode->getNumOperands() == 8) &&
619         "If you're setting the template parameters this should include a slot "
620         "for that!");
621     setArraysHelper(Elements, TParams);
622   }
623
624 public:
625   unsigned getRunTimeLang() const { return get()->getRuntimeLang(); }
626   DITypeRef getContainingType() const {
627     return DITypeRef::get(get()->getVTableHolder());
628   }
629
630 private:
631   /// \brief Set the containing type.
632   void setContainingType(DICompositeType ContainingType);
633
634 public:
635   DIArray getTemplateParams() const {
636     return DIArray(get()->getTemplateParams());
637   }
638   MDString *getIdentifier() const { return get()->getRawIdentifier(); }
639
640   bool Verify() const;
641 };
642
643 class DISubroutineType : public DICompositeType {
644 public:
645   explicit DISubroutineType(const MDNode *N = nullptr) : DICompositeType(N) {}
646   DISubroutineType(const MDSubroutineType *N) : DICompositeType(N) {}
647
648   MDSubroutineType *get() const {
649     return cast_or_null<MDSubroutineType>(DIDescriptor::get());
650   }
651   operator MDSubroutineType *() const { return get(); }
652   MDSubroutineType *operator->() const { return get(); }
653   MDSubroutineType &operator*() const {
654     assert(get() && "Expected valid pointer");
655     return *get();
656   }
657
658   DITypedArray<DITypeRef> getTypeArray() const {
659     return DITypedArray<DITypeRef>(get()->getTypeArray());
660   }
661 };
662
663 /// \brief This is a wrapper for a file.
664 class DIFile : public DIScope {
665 public:
666   explicit DIFile(const MDNode *N = nullptr) : DIScope(N) {}
667   DIFile(const MDFile *N) : DIScope(N) {}
668
669   MDFile *get() const { return cast_or_null<MDFile>(DIDescriptor::get()); }
670   operator MDFile *() const { return get(); }
671   MDFile *operator->() const { return get(); }
672   MDFile &operator*() const {
673     assert(get() && "Expected valid pointer");
674     return *get();
675   }
676
677   /// \brief Retrieve the MDNode for the directory/file pair.
678   MDNode *getFileNode() const { return get(); }
679   bool Verify() const;
680 };
681
682 /// \brief A wrapper for a compile unit.
683 class DICompileUnit : public DIScope {
684 public:
685   explicit DICompileUnit(const MDNode *N = nullptr) : DIScope(N) {}
686   DICompileUnit(const MDCompileUnit *N) : DIScope(N) {}
687
688   MDCompileUnit *get() const {
689     return cast_or_null<MDCompileUnit>(DIDescriptor::get());
690   }
691   operator MDCompileUnit *() const { return get(); }
692   MDCompileUnit *operator->() const { return get(); }
693   MDCompileUnit &operator*() const {
694     assert(get() && "Expected valid pointer");
695     return *get();
696   }
697
698   dwarf::SourceLanguage getLanguage() const {
699     return static_cast<dwarf::SourceLanguage>(get()->getSourceLanguage());
700   }
701   StringRef getProducer() const { return get()->getProducer(); }
702   bool isOptimized() const { return get()->isOptimized(); }
703   StringRef getFlags() const { return get()->getFlags(); }
704   unsigned getRunTimeVersion() const { return get()->getRuntimeVersion(); }
705
706   DIArray getEnumTypes() const { return DIArray(get()->getEnumTypes()); }
707   DIArray getRetainedTypes() const {
708     return DIArray(get()->getRetainedTypes());
709   }
710   DIArray getSubprograms() const { return DIArray(get()->getSubprograms()); }
711   DIArray getGlobalVariables() const {
712     return DIArray(get()->getGlobalVariables());
713   }
714   DIArray getImportedEntities() const {
715     return DIArray(get()->getImportedEntities());
716   }
717
718   void replaceSubprograms(DIArray Subprograms);
719   void replaceGlobalVariables(DIArray GlobalVariables);
720
721   StringRef getSplitDebugFilename() const {
722     return get()->getSplitDebugFilename();
723   }
724   unsigned getEmissionKind() const { return get()->getEmissionKind(); }
725
726   bool Verify() const;
727 };
728
729 /// \brief This is a wrapper for a subprogram (e.g. a function).
730 class DISubprogram : public DIScope {
731 public:
732   explicit DISubprogram(const MDNode *N = nullptr) : DIScope(N) {}
733   DISubprogram(const MDSubprogram *N) : DIScope(N) {}
734
735   MDSubprogram *get() const {
736     return cast_or_null<MDSubprogram>(DIDescriptor::get());
737   }
738   operator MDSubprogram *() const { return get(); }
739   MDSubprogram *operator->() const { return get(); }
740   MDSubprogram &operator*() const {
741     assert(get() && "Expected valid pointer");
742     return *get();
743   }
744
745   StringRef getName() const { return get()->getName(); }
746   StringRef getDisplayName() const { return get()->getDisplayName(); }
747   StringRef getLinkageName() const { return get()->getLinkageName(); }
748   unsigned getLineNumber() const { return get()->getLine(); }
749
750   /// \brief Check if this is local (like 'static' in C).
751   unsigned isLocalToUnit() const { return get()->isLocalToUnit(); }
752   unsigned isDefinition() const { return get()->isDefinition(); }
753
754   unsigned getVirtuality() const { return get()->getVirtuality(); }
755   unsigned getVirtualIndex() const { return get()->getVirtualIndex(); }
756
757   unsigned getFlags() const { return get()->getFlags(); }
758
759   unsigned isOptimized() const { return get()->isOptimized(); }
760
761   /// \brief Get the beginning of the scope of the function (not the name).
762   unsigned getScopeLineNumber() const { return get()->getScopeLine(); }
763
764   DIScopeRef getContext() const { return DIScopeRef::get(get()->getScope()); }
765   DISubroutineType getType() const {
766     return DISubroutineType(get()->getType());
767   }
768
769   DITypeRef getContainingType() const {
770     return DITypeRef::get(get()->getContainingType());
771   }
772
773   bool Verify() const;
774
775   /// \brief Check if this provides debugging information for the function F.
776   bool describes(const Function *F);
777
778   Function *getFunction() const;
779
780   void replaceFunction(Function *F) {
781     if (auto *N = get())
782       N->replaceFunction(F);
783   }
784   DIArray getTemplateParams() const {
785     return DIArray(get()->getTemplateParams());
786   }
787   DISubprogram getFunctionDeclaration() const {
788     return DISubprogram(get()->getDeclaration());
789   }
790   MDNode *getVariablesNodes() const { return getVariables(); }
791   DIArray getVariables() const { return DIArray(get()->getVariables()); }
792
793   unsigned isArtificial() const { return (getFlags() & FlagArtificial) != 0; }
794   /// \brief Check for the "private" access specifier.
795   bool isPrivate() const {
796     return (getFlags() & FlagAccessibility) == FlagPrivate;
797   }
798   /// \brief Check for the "protected" access specifier.
799   bool isProtected() const {
800     return (getFlags() & FlagAccessibility) == FlagProtected;
801   }
802   /// \brief Check for the "public" access specifier.
803   bool isPublic() const {
804     return (getFlags() & FlagAccessibility) == FlagPublic;
805   }
806   /// \brief Check for "explicit".
807   bool isExplicit() const { return (getFlags() & FlagExplicit) != 0; }
808   /// \brief Check if this is prototyped.
809   bool isPrototyped() const { return (getFlags() & FlagPrototyped) != 0; }
810
811   /// \brief Check if this is reference-qualified.
812   ///
813   /// Return true if this subprogram is a C++11 reference-qualified non-static
814   /// member function (void foo() &).
815   unsigned isLValueReference() const {
816     return (getFlags() & FlagLValueReference) != 0;
817   }
818
819   /// \brief Check if this is rvalue-reference-qualified.
820   ///
821   /// Return true if this subprogram is a C++11 rvalue-reference-qualified
822   /// non-static member function (void foo() &&).
823   unsigned isRValueReference() const {
824     return (getFlags() & FlagRValueReference) != 0;
825   }
826 };
827
828 /// \brief This is a wrapper for a lexical block.
829 class DILexicalBlock : public DIScope {
830 public:
831   explicit DILexicalBlock(const MDNode *N = nullptr) : DIScope(N) {}
832   DILexicalBlock(const MDLexicalBlock *N) : DIScope(N) {}
833
834   MDLexicalBlockBase *get() const {
835     return cast_or_null<MDLexicalBlockBase>(DIDescriptor::get());
836   }
837   operator MDLexicalBlockBase *() const { return get(); }
838   MDLexicalBlockBase *operator->() const { return get(); }
839   MDLexicalBlockBase &operator*() const {
840     assert(get() && "Expected valid pointer");
841     return *get();
842   }
843
844   DIScope getContext() const { return DIScope(get()->getScope()); }
845   unsigned getLineNumber() const {
846     if (auto *N = dyn_cast<MDLexicalBlock>(get()))
847       return N->getLine();
848     return 0;
849   }
850   unsigned getColumnNumber() const {
851     if (auto *N = dyn_cast<MDLexicalBlock>(get()))
852       return N->getColumn();
853     return 0;
854   }
855   bool Verify() const;
856 };
857
858 /// \brief This is a wrapper for a lexical block with a filename change.
859 class DILexicalBlockFile : public DIScope {
860 public:
861   explicit DILexicalBlockFile(const MDNode *N = nullptr) : DIScope(N) {}
862   DILexicalBlockFile(const MDLexicalBlockFile *N) : DIScope(N) {}
863
864   MDLexicalBlockFile *get() const {
865     return cast_or_null<MDLexicalBlockFile>(DIDescriptor::get());
866   }
867   operator MDLexicalBlockFile *() const { return get(); }
868   MDLexicalBlockFile *operator->() const { return get(); }
869   MDLexicalBlockFile &operator*() const {
870     assert(get() && "Expected valid pointer");
871     return *get();
872   }
873
874   DIScope getContext() const { return getScope(); }
875   unsigned getLineNumber() const { return getScope().getLineNumber(); }
876   unsigned getColumnNumber() const { return getScope().getColumnNumber(); }
877   DILexicalBlock getScope() const { return DILexicalBlock(get()->getScope()); }
878   unsigned getDiscriminator() const { return get()->getDiscriminator(); }
879   bool Verify() const;
880 };
881
882 /// \brief A wrapper for a C++ style name space.
883 class DINameSpace : public DIScope {
884 public:
885   explicit DINameSpace(const MDNode *N = nullptr) : DIScope(N) {}
886   DINameSpace(const MDNamespace *N) : DIScope(N) {}
887
888   MDNamespace *get() const {
889     return cast_or_null<MDNamespace>(DIDescriptor::get());
890   }
891   operator MDNamespace *() const { return get(); }
892   MDNamespace *operator->() const { return get(); }
893   MDNamespace &operator*() const {
894     assert(get() && "Expected valid pointer");
895     return *get();
896   }
897
898   StringRef getName() const { return get()->getName(); }
899   unsigned getLineNumber() const { return get()->getLine(); }
900   DIScope getContext() const { return DIScope(get()->getScope()); }
901   bool Verify() const;
902 };
903
904 /// \brief This is a wrapper for template type parameter.
905 class DITemplateTypeParameter : public DIDescriptor {
906 public:
907   explicit DITemplateTypeParameter(const MDNode *N = nullptr)
908       : DIDescriptor(N) {}
909   DITemplateTypeParameter(const MDTemplateTypeParameter *N) : DIDescriptor(N) {}
910
911   MDTemplateTypeParameter *get() const {
912     return cast_or_null<MDTemplateTypeParameter>(DIDescriptor::get());
913   }
914   operator MDTemplateTypeParameter *() const { return get(); }
915   MDTemplateTypeParameter *operator->() const { return get(); }
916   MDTemplateTypeParameter &operator*() const {
917     assert(get() && "Expected valid pointer");
918     return *get();
919   }
920
921   StringRef getName() const { return get()->getName(); }
922
923   DITypeRef getType() const { return DITypeRef::get(get()->getType()); }
924   bool Verify() const;
925 };
926
927 /// \brief This is a wrapper for template value parameter.
928 class DITemplateValueParameter : public DIDescriptor {
929 public:
930   explicit DITemplateValueParameter(const MDNode *N = nullptr)
931       : DIDescriptor(N) {}
932   DITemplateValueParameter(const MDTemplateValueParameter *N)
933       : DIDescriptor(N) {}
934
935   MDTemplateValueParameter *get() const {
936     return cast_or_null<MDTemplateValueParameter>(DIDescriptor::get());
937   }
938   operator MDTemplateValueParameter *() const { return get(); }
939   MDTemplateValueParameter *operator->() const { return get(); }
940   MDTemplateValueParameter &operator*() const {
941     assert(get() && "Expected valid pointer");
942     return *get();
943   }
944
945   StringRef getName() const { return get()->getName(); }
946   DITypeRef getType() const { return DITypeRef::get(get()->getType()); }
947   Metadata *getValue() const { return get()->getValue(); }
948   bool Verify() const;
949 };
950
951 /// \brief This is a wrapper for a global variable.
952 class DIGlobalVariable : public DIDescriptor {
953   DIFile getFile() const { return DIFile(get()->getFile()); }
954
955 public:
956   explicit DIGlobalVariable(const MDNode *N = nullptr) : DIDescriptor(N) {}
957   DIGlobalVariable(const MDGlobalVariable *N) : DIDescriptor(N) {}
958
959   MDGlobalVariable *get() const {
960     return cast_or_null<MDGlobalVariable>(DIDescriptor::get());
961   }
962   operator MDGlobalVariable *() const { return get(); }
963   MDGlobalVariable *operator->() const { return get(); }
964   MDGlobalVariable &operator*() const {
965     assert(get() && "Expected valid pointer");
966     return *get();
967   }
968
969   StringRef getName() const { return get()->getName(); }
970   StringRef getDisplayName() const { return get()->getDisplayName(); }
971   StringRef getLinkageName() const { return get()->getLinkageName(); }
972   unsigned getLineNumber() const { return get()->getLine(); }
973   unsigned isLocalToUnit() const { return get()->isLocalToUnit(); }
974   unsigned isDefinition() const { return get()->isDefinition(); }
975
976   DIScope getContext() const { return DIScope(get()->getScope()); }
977   StringRef getFilename() const { return getFile().getFilename(); }
978   StringRef getDirectory() const { return getFile().getDirectory(); }
979   DITypeRef getType() const { return DITypeRef::get(get()->getType()); }
980
981   GlobalVariable *getGlobal() const;
982   Constant *getConstant() const {
983     if (auto *N = get())
984       if (auto *C = dyn_cast_or_null<ConstantAsMetadata>(N->getVariable()))
985         return C->getValue();
986     return nullptr;
987   }
988   DIDerivedType getStaticDataMemberDeclaration() const {
989     return DIDerivedType(get()->getStaticDataMemberDeclaration());
990   }
991
992   bool Verify() const;
993 };
994
995 /// \brief This is a wrapper for a variable (e.g. parameter, local, global etc).
996 class DIVariable : public DIDescriptor {
997   unsigned getFlags() const { return get()->getFlags(); }
998
999 public:
1000   explicit DIVariable(const MDNode *N = nullptr) : DIDescriptor(N) {}
1001   DIVariable(const MDLocalVariable *N) : DIDescriptor(N) {}
1002
1003   MDLocalVariable *get() const {
1004     return cast_or_null<MDLocalVariable>(DIDescriptor::get());
1005   }
1006   operator MDLocalVariable *() const { return get(); }
1007   MDLocalVariable *operator->() const { return get(); }
1008   MDLocalVariable &operator*() const {
1009     assert(get() && "Expected valid pointer");
1010     return *get();
1011   }
1012
1013   StringRef getName() const { return get()->getName(); }
1014   unsigned getLineNumber() const { return get()->getLine(); }
1015   unsigned getArgNumber() const { return get()->getArg(); }
1016
1017   DIScope getContext() const { return DIScope(get()->getScope()); }
1018   DIFile getFile() const { return DIFile(get()->getFile()); }
1019   DITypeRef getType() const { return DITypeRef::get(get()->getType()); }
1020
1021   /// \brief Return true if this variable is marked as "artificial".
1022   bool isArtificial() const {
1023     return (getFlags() & FlagArtificial) != 0;
1024   }
1025
1026   bool isObjectPointer() const {
1027     return (getFlags() & FlagObjectPointer) != 0;
1028   }
1029
1030   /// \brief If this variable is inlined then return inline location.
1031   MDNode *getInlinedAt() const { return DIDescriptor(get()->getInlinedAt()); }
1032
1033   bool Verify() const;
1034
1035   /// \brief Check if this is a "__block" variable (Apple Blocks).
1036   bool isBlockByrefVariable(const DITypeIdentifierMap &Map) const {
1037     return (getType().resolve(Map)).isBlockByrefStruct();
1038   }
1039
1040   /// \brief Check if this is an inlined function argument.
1041   bool isInlinedFnArgument(const Function *CurFn);
1042
1043   /// \brief Return the size reported by the variable's type.
1044   unsigned getSizeInBits(const DITypeIdentifierMap &Map);
1045
1046   void printExtendedName(raw_ostream &OS) const;
1047 };
1048
1049 /// \brief A complex location expression in postfix notation.
1050 ///
1051 /// This is (almost) a DWARF expression that modifies the location of a
1052 /// variable or (or the location of a single piece of a variable).
1053 ///
1054 /// FIXME: Instead of DW_OP_plus taking an argument, this should use DW_OP_const
1055 /// and have DW_OP_plus consume the topmost elements on the stack.
1056 class DIExpression : public DIDescriptor {
1057 public:
1058   explicit DIExpression(const MDNode *N = nullptr) : DIDescriptor(N) {}
1059   DIExpression(const MDExpression *N) : DIDescriptor(N) {}
1060
1061   MDExpression *get() const {
1062     return cast_or_null<MDExpression>(DIDescriptor::get());
1063   }
1064   operator MDExpression *() const { return get(); }
1065   MDExpression *operator->() const { return get(); }
1066   MDExpression &operator*() const {
1067     assert(get() && "Expected valid pointer");
1068     return *get();
1069   }
1070
1071   // Don't call this.  Call isValid() directly.
1072   bool Verify() const = delete;
1073
1074   /// \brief Return the number of elements in the complex expression.
1075   unsigned getNumElements() const { return get()->getNumElements(); }
1076
1077   /// \brief return the Idx'th complex address element.
1078   uint64_t getElement(unsigned I) const { return get()->getElement(I); }
1079
1080   /// \brief Return whether this is a piece of an aggregate variable.
1081   bool isBitPiece() const;
1082   /// \brief Return the offset of this piece in bits.
1083   uint64_t getBitPieceOffset() const;
1084   /// \brief Return the size of this piece in bits.
1085   uint64_t getBitPieceSize() const;
1086
1087   class iterator;
1088   /// \brief A lightweight wrapper around an element of a DIExpression.
1089   class Operand {
1090     friend class iterator;
1091     MDExpression::element_iterator I;
1092     Operand() {}
1093     Operand(MDExpression::element_iterator I) : I(I) {}
1094   public:
1095     /// \brief Operands such as DW_OP_piece have explicit (non-stack) arguments.
1096     /// Argument 0 is the operand itself.
1097     uint64_t getArg(unsigned N) const {
1098       MDExpression::element_iterator In = I;
1099       std::advance(In, N);
1100       return *In;
1101     }
1102     operator uint64_t () const { return *I; }
1103     /// \brief Returns underlying MDExpression::element_iterator.
1104     const MDExpression::element_iterator &getBase() const { return I; }
1105     /// \brief Returns the next operand.
1106     iterator getNext() const;
1107   };
1108
1109   /// \brief An iterator for DIExpression elements.
1110   class iterator : public std::iterator<std::input_iterator_tag, StringRef,
1111                                         unsigned, const Operand*, Operand> {
1112     friend class Operand;
1113     MDExpression::element_iterator I;
1114     Operand Tmp;
1115
1116   public:
1117     iterator(MDExpression::element_iterator I) : I(I) {}
1118     const Operand &operator*() { return Tmp = Operand(I); }
1119     const Operand *operator->() { return &(Tmp = Operand(I)); }
1120     iterator &operator++() {
1121       increment();
1122       return *this;
1123     }
1124     iterator operator++(int) {
1125       iterator X(*this);
1126       increment();
1127       return X;
1128     }
1129     bool operator==(const iterator &X) const { return I == X.I; }
1130     bool operator!=(const iterator &X) const { return !(*this == X); }
1131
1132   private:
1133     void increment() {
1134       switch (**this) {
1135       case dwarf::DW_OP_bit_piece: std::advance(I, 3); break;
1136       case dwarf::DW_OP_plus:      std::advance(I, 2); break;
1137       case dwarf::DW_OP_deref:     std::advance(I, 1); break;
1138       default:
1139         llvm_unreachable("unsupported operand");
1140       }
1141     }
1142   };
1143
1144   iterator begin() const { return get()->elements_begin(); }
1145   iterator end() const { return get()->elements_end(); }
1146 };
1147
1148 /// \brief This object holds location information.
1149 ///
1150 /// This object is not associated with any DWARF tag.
1151 class DILocation : public DIDescriptor {
1152 public:
1153   explicit DILocation(const MDNode *N) : DIDescriptor(N) {}
1154   DILocation(const MDLocation *N) : DIDescriptor(N) {}
1155
1156   MDLocation *get() const {
1157     return cast_or_null<MDLocation>(DIDescriptor::get());
1158   }
1159   operator MDLocation *() const { return get(); }
1160   MDLocation *operator->() const { return get(); }
1161   MDLocation &operator*() const {
1162     assert(get() && "Expected valid pointer");
1163     return *get();
1164   }
1165
1166   unsigned getLineNumber() const { return get()->getLine(); }
1167   unsigned getColumnNumber() const { return get()->getColumn(); }
1168   DIScope getScope() const { return DIScope(get()->getScope()); }
1169   DILocation getOrigLocation() const {
1170     return DILocation(get()->getInlinedAt());
1171   }
1172   StringRef getFilename() const { return getScope().getFilename(); }
1173   StringRef getDirectory() const { return getScope().getDirectory(); }
1174   bool Verify() const;
1175   bool atSameLineAs(const DILocation &Other) const {
1176     return (getLineNumber() == Other.getLineNumber() &&
1177             getFilename() == Other.getFilename());
1178   }
1179   /// \brief Get the DWAF discriminator.
1180   ///
1181   /// DWARF discriminators are used to distinguish identical file locations for
1182   /// instructions that are on different basic blocks. If two instructions are
1183   /// inside the same lexical block and are in different basic blocks, we
1184   /// create a new lexical block with identical location as the original but
1185   /// with a different discriminator value
1186   /// (lib/Transforms/Util/AddDiscriminators.cpp for details).
1187   unsigned getDiscriminator() const {
1188     // Since discriminators are associated with lexical blocks, make
1189     // sure this location is a lexical block before retrieving its
1190     // value.
1191     return getScope().isLexicalBlockFile()
1192                ? DILexicalBlockFile(
1193                      cast<MDNode>(cast<MDLocation>(DbgNode)->getScope()))
1194                      .getDiscriminator()
1195                : 0;
1196   }
1197
1198   /// \brief Generate a new discriminator value for this location.
1199   unsigned computeNewDiscriminator(LLVMContext &Ctx);
1200
1201   /// \brief Return a copy of this location with a different scope.
1202   DILocation copyWithNewScope(LLVMContext &Ctx, DILexicalBlockFile NewScope);
1203 };
1204
1205 class DIObjCProperty : public DIDescriptor {
1206 public:
1207   explicit DIObjCProperty(const MDNode *N) : DIDescriptor(N) {}
1208   DIObjCProperty(const MDObjCProperty *N) : DIDescriptor(N) {}
1209
1210   MDObjCProperty *get() const {
1211     return cast_or_null<MDObjCProperty>(DIDescriptor::get());
1212   }
1213   operator MDObjCProperty *() const { return get(); }
1214   MDObjCProperty *operator->() const { return get(); }
1215   MDObjCProperty &operator*() const {
1216     assert(get() && "Expected valid pointer");
1217     return *get();
1218   }
1219
1220   StringRef getObjCPropertyName() const { return get()->getName(); }
1221   DIFile getFile() const { return DIFile(get()->getFile()); }
1222   unsigned getLineNumber() const { return get()->getLine(); }
1223
1224   StringRef getObjCPropertyGetterName() const { return get()->getGetterName(); }
1225   StringRef getObjCPropertySetterName() const { return get()->getSetterName(); }
1226   unsigned getAttributes() const { return get()->getAttributes(); }
1227   bool isReadOnlyObjCProperty() const {
1228     return (getAttributes() & dwarf::DW_APPLE_PROPERTY_readonly) != 0;
1229   }
1230   bool isReadWriteObjCProperty() const {
1231     return (getAttributes() & dwarf::DW_APPLE_PROPERTY_readwrite) != 0;
1232   }
1233   bool isAssignObjCProperty() const {
1234     return (getAttributes() & dwarf::DW_APPLE_PROPERTY_assign) != 0;
1235   }
1236   bool isRetainObjCProperty() const {
1237     return (getAttributes() & dwarf::DW_APPLE_PROPERTY_retain) != 0;
1238   }
1239   bool isCopyObjCProperty() const {
1240     return (getAttributes() & dwarf::DW_APPLE_PROPERTY_copy) != 0;
1241   }
1242   bool isNonAtomicObjCProperty() const {
1243     return (getAttributes() & dwarf::DW_APPLE_PROPERTY_nonatomic) != 0;
1244   }
1245
1246   /// \brief Get the type.
1247   ///
1248   /// \note Objective-C doesn't have an ODR, so there is no benefit in storing
1249   /// the type as a DITypeRef here.
1250   DIType getType() const { return DIType(get()->getType()); }
1251
1252   bool Verify() const;
1253 };
1254
1255 /// \brief An imported module (C++ using directive or similar).
1256 class DIImportedEntity : public DIDescriptor {
1257 public:
1258   DIImportedEntity() = default;
1259   explicit DIImportedEntity(const MDNode *N) : DIDescriptor(N) {}
1260   DIImportedEntity(const MDImportedEntity *N) : DIDescriptor(N) {}
1261
1262   MDImportedEntity *get() const {
1263     return cast_or_null<MDImportedEntity>(DIDescriptor::get());
1264   }
1265   operator MDImportedEntity *() const { return get(); }
1266   MDImportedEntity *operator->() const { return get(); }
1267   MDImportedEntity &operator*() const {
1268     assert(get() && "Expected valid pointer");
1269     return *get();
1270   }
1271
1272   DIScope getContext() const { return DIScope(get()->getScope()); }
1273   DIDescriptorRef getEntity() const {
1274     return DIDescriptorRef::get(get()->getEntity());
1275   }
1276   unsigned getLineNumber() const { return get()->getLine(); }
1277   StringRef getName() const { return get()->getName(); }
1278   bool Verify() const;
1279 };
1280
1281 /// \brief Find subprogram that is enclosing this scope.
1282 DISubprogram getDISubprogram(const MDNode *Scope);
1283
1284 /// \brief Find debug info for a given function.
1285 /// \returns a valid DISubprogram, if found. Otherwise, it returns an empty
1286 /// DISubprogram.
1287 DISubprogram getDISubprogram(const Function *F);
1288
1289 /// \brief Find underlying composite type.
1290 DICompositeType getDICompositeType(DIType T);
1291
1292 /// \brief Create a new inlined variable based on current variable.
1293 ///
1294 /// @param DV            Current Variable.
1295 /// @param InlinedScope  Location at current variable is inlined.
1296 DIVariable createInlinedVariable(MDNode *DV, MDNode *InlinedScope,
1297                                  LLVMContext &VMContext);
1298
1299 /// \brief Remove inlined scope from the variable.
1300 DIVariable cleanseInlinedVariable(MDNode *DV, LLVMContext &VMContext);
1301
1302 /// \brief Generate map by visiting all retained types.
1303 DITypeIdentifierMap generateDITypeIdentifierMap(const NamedMDNode *CU_Nodes);
1304
1305 /// \brief Strip debug info in the module if it exists.
1306 ///
1307 /// To do this, we remove all calls to the debugger intrinsics and any named
1308 /// metadata for debugging. We also remove debug locations for instructions.
1309 /// Return true if module is modified.
1310 bool StripDebugInfo(Module &M);
1311 bool stripDebugInfo(Function &F);
1312
1313 /// \brief Return Debug Info Metadata Version by checking module flags.
1314 unsigned getDebugMetadataVersionFromModule(const Module &M);
1315
1316 /// \brief Utility to find all debug info in a module.
1317 ///
1318 /// DebugInfoFinder tries to list all debug info MDNodes used in a module. To
1319 /// list debug info MDNodes used by an instruction, DebugInfoFinder uses
1320 /// processDeclare, processValue and processLocation to handle DbgDeclareInst,
1321 /// DbgValueInst and DbgLoc attached to instructions. processModule will go
1322 /// through all DICompileUnits in llvm.dbg.cu and list debug info MDNodes
1323 /// used by the CUs.
1324 class DebugInfoFinder {
1325 public:
1326   DebugInfoFinder() : TypeMapInitialized(false) {}
1327
1328   /// \brief Process entire module and collect debug info anchors.
1329   void processModule(const Module &M);
1330
1331   /// \brief Process DbgDeclareInst.
1332   void processDeclare(const Module &M, const DbgDeclareInst *DDI);
1333   /// \brief Process DbgValueInst.
1334   void processValue(const Module &M, const DbgValueInst *DVI);
1335   /// \brief Process DILocation.
1336   void processLocation(const Module &M, DILocation Loc);
1337
1338   /// \brief Clear all lists.
1339   void reset();
1340
1341 private:
1342   void InitializeTypeMap(const Module &M);
1343
1344   void processType(DIType DT);
1345   void processSubprogram(DISubprogram SP);
1346   void processScope(DIScope Scope);
1347   bool addCompileUnit(DICompileUnit CU);
1348   bool addGlobalVariable(DIGlobalVariable DIG);
1349   bool addSubprogram(DISubprogram SP);
1350   bool addType(DIType DT);
1351   bool addScope(DIScope Scope);
1352
1353 public:
1354   typedef SmallVectorImpl<DICompileUnit>::const_iterator compile_unit_iterator;
1355   typedef SmallVectorImpl<DISubprogram>::const_iterator subprogram_iterator;
1356   typedef SmallVectorImpl<DIGlobalVariable>::const_iterator
1357       global_variable_iterator;
1358   typedef SmallVectorImpl<DIType>::const_iterator type_iterator;
1359   typedef SmallVectorImpl<DIScope>::const_iterator scope_iterator;
1360
1361   iterator_range<compile_unit_iterator> compile_units() const {
1362     return iterator_range<compile_unit_iterator>(CUs.begin(), CUs.end());
1363   }
1364
1365   iterator_range<subprogram_iterator> subprograms() const {
1366     return iterator_range<subprogram_iterator>(SPs.begin(), SPs.end());
1367   }
1368
1369   iterator_range<global_variable_iterator> global_variables() const {
1370     return iterator_range<global_variable_iterator>(GVs.begin(), GVs.end());
1371   }
1372
1373   iterator_range<type_iterator> types() const {
1374     return iterator_range<type_iterator>(TYs.begin(), TYs.end());
1375   }
1376
1377   iterator_range<scope_iterator> scopes() const {
1378     return iterator_range<scope_iterator>(Scopes.begin(), Scopes.end());
1379   }
1380
1381   unsigned compile_unit_count() const { return CUs.size(); }
1382   unsigned global_variable_count() const { return GVs.size(); }
1383   unsigned subprogram_count() const { return SPs.size(); }
1384   unsigned type_count() const { return TYs.size(); }
1385   unsigned scope_count() const { return Scopes.size(); }
1386
1387 private:
1388   SmallVector<DICompileUnit, 8> CUs;
1389   SmallVector<DISubprogram, 8> SPs;
1390   SmallVector<DIGlobalVariable, 8> GVs;
1391   SmallVector<DIType, 8> TYs;
1392   SmallVector<DIScope, 8> Scopes;
1393   SmallPtrSet<MDNode *, 64> NodesSeen;
1394   DITypeIdentifierMap TypeIdentifierMap;
1395
1396   /// \brief Specify if TypeIdentifierMap is initialized.
1397   bool TypeMapInitialized;
1398 };
1399
1400 DenseMap<const Function *, DISubprogram> makeSubprogramMap(const Module &M);
1401
1402 } // end namespace llvm
1403
1404 #endif