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