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