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