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