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