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