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