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