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