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