8d6dbc67f741fa7d630e202c17a4718b256c589c
[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 {
443     return DIArray(get()->getTemplateParams());
444   }
445   MDString *getIdentifier() const { return get()->getRawIdentifier(); }
446 };
447
448 class DISubroutineType : public DICompositeType {
449 public:
450   DISubroutineType() = default;
451   DISubroutineType(const MDSubroutineType *N) : DICompositeType(N) {}
452
453   MDSubroutineType *get() const {
454     return cast_or_null<MDSubroutineType>(DIDescriptor::get());
455   }
456   operator MDSubroutineType *() const { return get(); }
457   MDSubroutineType *operator->() const { return get(); }
458   MDSubroutineType &operator*() const {
459     assert(get() && "Expected valid pointer");
460     return *get();
461   }
462
463   MDTypeRefArray getTypeArray() const { return get()->getTypeArray(); }
464 };
465
466 /// \brief This is a wrapper for a file.
467 class DIFile : public DIScope {
468 public:
469   DIFile() = default;
470   DIFile(const MDFile *N) : DIScope(N) {}
471
472   MDFile *get() const { return cast_or_null<MDFile>(DIDescriptor::get()); }
473   operator MDFile *() const { return get(); }
474   MDFile *operator->() const { return get(); }
475   MDFile &operator*() const {
476     assert(get() && "Expected valid pointer");
477     return *get();
478   }
479
480   /// \brief Retrieve the MDNode for the directory/file pair.
481   MDNode *getFileNode() const { return get(); }
482 };
483
484 /// \brief A wrapper for a compile unit.
485 class DICompileUnit : public DIScope {
486 public:
487   DICompileUnit() = default;
488   DICompileUnit(const MDCompileUnit *N) : DIScope(N) {}
489
490   MDCompileUnit *get() const {
491     return cast_or_null<MDCompileUnit>(DIDescriptor::get());
492   }
493   operator MDCompileUnit *() const { return get(); }
494   MDCompileUnit *operator->() const { return get(); }
495   MDCompileUnit &operator*() const {
496     assert(get() && "Expected valid pointer");
497     return *get();
498   }
499
500   dwarf::SourceLanguage getLanguage() const {
501     return static_cast<dwarf::SourceLanguage>(get()->getSourceLanguage());
502   }
503   StringRef getProducer() const { return get()->getProducer(); }
504   bool isOptimized() const { return get()->isOptimized(); }
505   StringRef getFlags() const { return get()->getFlags(); }
506   unsigned getRunTimeVersion() const { return get()->getRuntimeVersion(); }
507
508   DIArray getEnumTypes() const { return DIArray(get()->getEnumTypes()); }
509   DIArray getRetainedTypes() const {
510     return DIArray(get()->getRetainedTypes());
511   }
512   DIArray getSubprograms() const { return DIArray(get()->getSubprograms()); }
513   DIArray getGlobalVariables() const {
514     return DIArray(get()->getGlobalVariables());
515   }
516   DIArray getImportedEntities() const {
517     return DIArray(get()->getImportedEntities());
518   }
519
520   void replaceSubprograms(DIArray Subprograms);
521   void replaceGlobalVariables(DIArray GlobalVariables);
522
523   StringRef getSplitDebugFilename() const {
524     return get()->getSplitDebugFilename();
525   }
526   unsigned getEmissionKind() const { return get()->getEmissionKind(); }
527 };
528
529 /// \brief This is a wrapper for a subprogram (e.g. a function).
530 class DISubprogram : public DIScope {
531 public:
532   DISubprogram() = default;
533   DISubprogram(const MDSubprogram *N) : DIScope(N) {}
534
535   MDSubprogram *get() const {
536     return cast_or_null<MDSubprogram>(DIDescriptor::get());
537   }
538   operator MDSubprogram *() const { return get(); }
539   MDSubprogram *operator->() const { return get(); }
540   MDSubprogram &operator*() const {
541     assert(get() && "Expected valid pointer");
542     return *get();
543   }
544
545   StringRef getName() const { return get()->getName(); }
546   StringRef getDisplayName() const { return get()->getDisplayName(); }
547   StringRef getLinkageName() const { return get()->getLinkageName(); }
548   unsigned getLineNumber() const { return get()->getLine(); }
549
550   /// \brief Check if this is local (like 'static' in C).
551   unsigned isLocalToUnit() const { return get()->isLocalToUnit(); }
552   unsigned isDefinition() const { return get()->isDefinition(); }
553
554   unsigned getVirtuality() const { return get()->getVirtuality(); }
555   unsigned getVirtualIndex() const { return get()->getVirtualIndex(); }
556
557   unsigned getFlags() const { return get()->getFlags(); }
558
559   unsigned isOptimized() const { return get()->isOptimized(); }
560
561   /// \brief Get the beginning of the scope of the function (not the name).
562   unsigned getScopeLineNumber() const { return get()->getScopeLine(); }
563
564   DIScopeRef getContext() const { return DIScopeRef::get(get()->getScope()); }
565   DISubroutineType getType() const {
566     return DISubroutineType(get()->getType());
567   }
568
569   DITypeRef getContainingType() const {
570     return DITypeRef::get(get()->getContainingType());
571   }
572
573   /// \brief Check if this provides debugging information for the function F.
574   bool describes(const Function *F);
575
576   Function *getFunction() const;
577
578   void replaceFunction(Function *F) {
579     if (auto *N = get())
580       N->replaceFunction(F);
581   }
582   DIArray getTemplateParams() const {
583     return DIArray(get()->getTemplateParams());
584   }
585   DISubprogram getFunctionDeclaration() const {
586     return DISubprogram(get()->getDeclaration());
587   }
588   MDNode *getVariablesNodes() const { return getVariables(); }
589   DIArray getVariables() const { return DIArray(get()->getVariables()); }
590
591   unsigned isArtificial() const { return get()->isArtificial(); }
592   bool isPrivate() const { return get()->isPrivate(); }
593   bool isProtected() const { return get()->isProtected(); }
594   bool isPublic() const { return get()->isPublic(); }
595   bool isExplicit() const { return get()->isExplicit(); }
596   bool isPrototyped() const { return get()->isPrototyped(); }
597   unsigned isLValueReference() const { return get()->isLValueReference(); }
598   unsigned isRValueReference() const { return get()->isRValueReference(); }
599 };
600
601 /// \brief This is a wrapper for a lexical block.
602 class DILexicalBlock : public DIScope {
603 public:
604   DILexicalBlock() = default;
605   DILexicalBlock(const MDLexicalBlockBase *N) : DIScope(N) {}
606
607   MDLexicalBlockBase *get() const {
608     return cast_or_null<MDLexicalBlockBase>(DIDescriptor::get());
609   }
610   operator MDLexicalBlockBase *() const { return get(); }
611   MDLexicalBlockBase *operator->() const { return get(); }
612   MDLexicalBlockBase &operator*() const {
613     assert(get() && "Expected valid pointer");
614     return *get();
615   }
616
617   DIScope getContext() const { return DIScope(get()->getScope()); }
618   unsigned getLineNumber() const {
619     if (auto *N = dyn_cast<MDLexicalBlock>(get()))
620       return N->getLine();
621     return 0;
622   }
623   unsigned getColumnNumber() const {
624     if (auto *N = dyn_cast<MDLexicalBlock>(get()))
625       return N->getColumn();
626     return 0;
627   }
628 };
629
630 /// \brief This is a wrapper for a lexical block with a filename change.
631 class DILexicalBlockFile : public DIScope {
632 public:
633   DILexicalBlockFile() = default;
634   DILexicalBlockFile(const MDLexicalBlockFile *N) : DIScope(N) {}
635
636   MDLexicalBlockFile *get() const {
637     return cast_or_null<MDLexicalBlockFile>(DIDescriptor::get());
638   }
639   operator MDLexicalBlockFile *() const { return get(); }
640   MDLexicalBlockFile *operator->() const { return get(); }
641   MDLexicalBlockFile &operator*() const {
642     assert(get() && "Expected valid pointer");
643     return *get();
644   }
645
646   DIScope getContext() const { return get()->getScope(); }
647   unsigned getDiscriminator() const { return get()->getDiscriminator(); }
648 };
649
650 /// \brief A wrapper for a C++ style name space.
651 class DINameSpace : public DIScope {
652 public:
653   DINameSpace() = default;
654   DINameSpace(const MDNamespace *N) : DIScope(N) {}
655
656   MDNamespace *get() const {
657     return cast_or_null<MDNamespace>(DIDescriptor::get());
658   }
659   operator MDNamespace *() const { return get(); }
660   MDNamespace *operator->() const { return get(); }
661   MDNamespace &operator*() const {
662     assert(get() && "Expected valid pointer");
663     return *get();
664   }
665
666   StringRef getName() const { return get()->getName(); }
667   unsigned getLineNumber() const { return get()->getLine(); }
668   DIScope getContext() const { return DIScope(get()->getScope()); }
669 };
670
671 /// \brief This is a wrapper for template type parameter.
672 class DITemplateTypeParameter : public DIDescriptor {
673 public:
674   DITemplateTypeParameter() = default;
675   DITemplateTypeParameter(const MDTemplateTypeParameter *N) : DIDescriptor(N) {}
676
677   MDTemplateTypeParameter *get() const {
678     return cast_or_null<MDTemplateTypeParameter>(DIDescriptor::get());
679   }
680   operator MDTemplateTypeParameter *() const { return get(); }
681   MDTemplateTypeParameter *operator->() const { return get(); }
682   MDTemplateTypeParameter &operator*() const {
683     assert(get() && "Expected valid pointer");
684     return *get();
685   }
686
687   StringRef getName() const { return get()->getName(); }
688
689   DITypeRef getType() const { return DITypeRef::get(get()->getType()); }
690 };
691
692 /// \brief This is a wrapper for template value parameter.
693 class DITemplateValueParameter : public DIDescriptor {
694 public:
695   DITemplateValueParameter() = default;
696   DITemplateValueParameter(const MDTemplateValueParameter *N)
697       : DIDescriptor(N) {}
698
699   MDTemplateValueParameter *get() const {
700     return cast_or_null<MDTemplateValueParameter>(DIDescriptor::get());
701   }
702   operator MDTemplateValueParameter *() const { return get(); }
703   MDTemplateValueParameter *operator->() const { return get(); }
704   MDTemplateValueParameter &operator*() const {
705     assert(get() && "Expected valid pointer");
706     return *get();
707   }
708
709   StringRef getName() const { return get()->getName(); }
710   DITypeRef getType() const { return DITypeRef::get(get()->getType()); }
711   Metadata *getValue() const { return get()->getValue(); }
712 };
713
714 /// \brief This is a wrapper for a global variable.
715 class DIGlobalVariable : public DIDescriptor {
716   DIFile getFile() const { return DIFile(get()->getFile()); }
717
718 public:
719   DIGlobalVariable() = default;
720   DIGlobalVariable(const MDGlobalVariable *N) : DIDescriptor(N) {}
721
722   MDGlobalVariable *get() const {
723     return cast_or_null<MDGlobalVariable>(DIDescriptor::get());
724   }
725   operator MDGlobalVariable *() const { return get(); }
726   MDGlobalVariable *operator->() const { return get(); }
727   MDGlobalVariable &operator*() const {
728     assert(get() && "Expected valid pointer");
729     return *get();
730   }
731
732   StringRef getName() const { return get()->getName(); }
733   StringRef getDisplayName() const { return get()->getDisplayName(); }
734   StringRef getLinkageName() const { return get()->getLinkageName(); }
735   unsigned getLineNumber() const { return get()->getLine(); }
736   unsigned isLocalToUnit() const { return get()->isLocalToUnit(); }
737   unsigned isDefinition() const { return get()->isDefinition(); }
738
739   DIScope getContext() const { return DIScope(get()->getScope()); }
740   StringRef getFilename() const { return getFile().getFilename(); }
741   StringRef getDirectory() const { return getFile().getDirectory(); }
742   DITypeRef getType() const { return DITypeRef::get(get()->getType()); }
743
744   GlobalVariable *getGlobal() const;
745   Constant *getConstant() const {
746     if (auto *N = get())
747       if (auto *C = dyn_cast_or_null<ConstantAsMetadata>(N->getVariable()))
748         return C->getValue();
749     return nullptr;
750   }
751   DIDerivedType getStaticDataMemberDeclaration() const {
752     return DIDerivedType(get()->getStaticDataMemberDeclaration());
753   }
754 };
755
756 /// \brief This is a wrapper for a variable (e.g. parameter, local, global etc).
757 class DIVariable : public DIDescriptor {
758   unsigned getFlags() const { return get()->getFlags(); }
759
760 public:
761   DIVariable() = default;
762   DIVariable(const MDLocalVariable *N) : DIDescriptor(N) {}
763
764   MDLocalVariable *get() const {
765     return cast_or_null<MDLocalVariable>(DIDescriptor::get());
766   }
767   operator MDLocalVariable *() const { return get(); }
768   MDLocalVariable *operator->() const { return get(); }
769   MDLocalVariable &operator*() const {
770     assert(get() && "Expected valid pointer");
771     return *get();
772   }
773
774   StringRef getName() const { return get()->getName(); }
775   unsigned getLineNumber() const { return get()->getLine(); }
776   unsigned getArgNumber() const { return get()->getArg(); }
777
778   DIScope getContext() const { return DIScope(get()->getScope()); }
779   DIFile getFile() const { return DIFile(get()->getFile()); }
780   DITypeRef getType() const { return DITypeRef::get(get()->getType()); }
781
782   bool isArtificial() const { return get()->isArtificial(); }
783   bool isObjectPointer() const { return get()->isObjectPointer(); }
784
785   /// \brief If this variable is inlined then return inline location.
786   MDNode *getInlinedAt() const { return DIDescriptor(get()->getInlinedAt()); }
787
788   /// \brief Check if this is a "__block" variable (Apple Blocks).
789   bool isBlockByrefVariable(const DITypeIdentifierMap &Map) const {
790     return (getType().resolve(Map)).isBlockByrefStruct();
791   }
792
793   /// \brief Check if this is an inlined function argument.
794   bool isInlinedFnArgument(const Function *CurFn);
795
796   /// \brief Return the size reported by the variable's type.
797   unsigned getSizeInBits(const DITypeIdentifierMap &Map);
798
799   void printExtendedName(raw_ostream &OS) const;
800 };
801
802 /// \brief A complex location expression in postfix notation.
803 ///
804 /// This is (almost) a DWARF expression that modifies the location of a
805 /// variable or (or the location of a single piece of a variable).
806 ///
807 /// FIXME: Instead of DW_OP_plus taking an argument, this should use DW_OP_const
808 /// and have DW_OP_plus consume the topmost elements on the stack.
809 class DIExpression : public DIDescriptor {
810 public:
811   DIExpression() = default;
812   DIExpression(const MDExpression *N) : DIDescriptor(N) {}
813
814   MDExpression *get() const {
815     return cast_or_null<MDExpression>(DIDescriptor::get());
816   }
817   operator MDExpression *() const { return get(); }
818   MDExpression *operator->() const { return get(); }
819   MDExpression &operator*() const {
820     assert(get() && "Expected valid pointer");
821     return *get();
822   }
823
824   unsigned getNumElements() const { return get()->getNumElements(); }
825   uint64_t getElement(unsigned I) const { return get()->getElement(I); }
826   bool isBitPiece() const { return get()->isBitPiece(); }
827   uint64_t getBitPieceOffset() const { return get()->getBitPieceOffset(); }
828   uint64_t getBitPieceSize() const { return get()->getBitPieceSize(); }
829 };
830
831 /// \brief This object holds location information.
832 ///
833 /// This object is not associated with any DWARF tag.
834 class DILocation : public DIDescriptor {
835 public:
836   DILocation() = default;
837   DILocation(const MDLocation *N) : DIDescriptor(N) {}
838
839   MDLocation *get() const {
840     return cast_or_null<MDLocation>(DIDescriptor::get());
841   }
842   operator MDLocation *() const { return get(); }
843   MDLocation *operator->() const { return get(); }
844   MDLocation &operator*() const {
845     assert(get() && "Expected valid pointer");
846     return *get();
847   }
848
849   unsigned getLineNumber() const { return get()->getLine(); }
850   unsigned getColumnNumber() const { return get()->getColumn(); }
851   DIScope getScope() const { return DIScope(get()->getScope()); }
852   DILocation getOrigLocation() const {
853     return DILocation(get()->getInlinedAt());
854   }
855   StringRef getFilename() const { return getScope().getFilename(); }
856   StringRef getDirectory() const { return getScope().getDirectory(); }
857   bool atSameLineAs(const DILocation &Other) const {
858     return (getLineNumber() == Other.getLineNumber() &&
859             getFilename() == Other.getFilename());
860   }
861   /// \brief Get the DWAF discriminator.
862   ///
863   /// DWARF discriminators are used to distinguish identical file locations for
864   /// instructions that are on different basic blocks. If two instructions are
865   /// inside the same lexical block and are in different basic blocks, we
866   /// create a new lexical block with identical location as the original but
867   /// with a different discriminator value
868   /// (lib/Transforms/Util/AddDiscriminators.cpp for details).
869   unsigned getDiscriminator() const {
870     // Since discriminators are associated with lexical blocks, make
871     // sure this location is a lexical block before retrieving its
872     // value.
873     if (auto *F = dyn_cast<MDLexicalBlockFile>(get()->getScope()))
874       return F->getDiscriminator();
875     return 0;
876   }
877
878   /// \brief Generate a new discriminator value for this location.
879   unsigned computeNewDiscriminator(LLVMContext &Ctx);
880
881   /// \brief Return a copy of this location with a different scope.
882   DILocation copyWithNewScope(LLVMContext &Ctx, DILexicalBlockFile NewScope);
883 };
884
885 class DIObjCProperty : public DIDescriptor {
886 public:
887   DIObjCProperty() = default;
888   DIObjCProperty(const MDObjCProperty *N) : DIDescriptor(N) {}
889
890   MDObjCProperty *get() const {
891     return cast_or_null<MDObjCProperty>(DIDescriptor::get());
892   }
893   operator MDObjCProperty *() const { return get(); }
894   MDObjCProperty *operator->() const { return get(); }
895   MDObjCProperty &operator*() const {
896     assert(get() && "Expected valid pointer");
897     return *get();
898   }
899
900   StringRef getObjCPropertyName() const { return get()->getName(); }
901   DIFile getFile() const { return DIFile(get()->getFile()); }
902   unsigned getLineNumber() const { return get()->getLine(); }
903
904   StringRef getObjCPropertyGetterName() const { return get()->getGetterName(); }
905   StringRef getObjCPropertySetterName() const { return get()->getSetterName(); }
906   unsigned getAttributes() const { return get()->getAttributes(); }
907   bool isReadOnlyObjCProperty() const {
908     return (getAttributes() & dwarf::DW_APPLE_PROPERTY_readonly) != 0;
909   }
910   bool isReadWriteObjCProperty() const {
911     return (getAttributes() & dwarf::DW_APPLE_PROPERTY_readwrite) != 0;
912   }
913   bool isAssignObjCProperty() const {
914     return (getAttributes() & dwarf::DW_APPLE_PROPERTY_assign) != 0;
915   }
916   bool isRetainObjCProperty() const {
917     return (getAttributes() & dwarf::DW_APPLE_PROPERTY_retain) != 0;
918   }
919   bool isCopyObjCProperty() const {
920     return (getAttributes() & dwarf::DW_APPLE_PROPERTY_copy) != 0;
921   }
922   bool isNonAtomicObjCProperty() const {
923     return (getAttributes() & dwarf::DW_APPLE_PROPERTY_nonatomic) != 0;
924   }
925
926   /// \brief Get the type.
927   ///
928   /// \note Objective-C doesn't have an ODR, so there is no benefit in storing
929   /// the type as a DITypeRef here.
930   DIType getType() const { return DIType(get()->getType()); }
931 };
932
933 /// \brief An imported module (C++ using directive or similar).
934 class DIImportedEntity : public DIDescriptor {
935 public:
936   DIImportedEntity() = default;
937   DIImportedEntity(const MDImportedEntity *N) : DIDescriptor(N) {}
938
939   MDImportedEntity *get() const {
940     return cast_or_null<MDImportedEntity>(DIDescriptor::get());
941   }
942   operator MDImportedEntity *() const { return get(); }
943   MDImportedEntity *operator->() const { return get(); }
944   MDImportedEntity &operator*() const {
945     assert(get() && "Expected valid pointer");
946     return *get();
947   }
948
949   DIScope getContext() const { return DIScope(get()->getScope()); }
950   DIDescriptorRef getEntity() const {
951     return DIDescriptorRef::get(get()->getEntity());
952   }
953   unsigned getLineNumber() const { return get()->getLine(); }
954   StringRef getName() const { return get()->getName(); }
955 };
956
957 #define SIMPLIFY_DESCRIPTOR(DESC)                                              \
958   template <> struct simplify_type<const DESC> {                               \
959     typedef Metadata *SimpleType;                                              \
960     static SimpleType getSimplifiedValue(const DESC &DI) { return DI; }        \
961   };                                                                           \
962   template <> struct simplify_type<DESC> : simplify_type<const DESC> {};
963 SIMPLIFY_DESCRIPTOR(DIDescriptor)
964 SIMPLIFY_DESCRIPTOR(DISubrange)
965 SIMPLIFY_DESCRIPTOR(DIEnumerator)
966 SIMPLIFY_DESCRIPTOR(DIScope)
967 SIMPLIFY_DESCRIPTOR(DIType)
968 SIMPLIFY_DESCRIPTOR(DIBasicType)
969 SIMPLIFY_DESCRIPTOR(DIDerivedType)
970 SIMPLIFY_DESCRIPTOR(DICompositeType)
971 SIMPLIFY_DESCRIPTOR(DISubroutineType)
972 SIMPLIFY_DESCRIPTOR(DIFile)
973 SIMPLIFY_DESCRIPTOR(DICompileUnit)
974 SIMPLIFY_DESCRIPTOR(DISubprogram)
975 SIMPLIFY_DESCRIPTOR(DILexicalBlock)
976 SIMPLIFY_DESCRIPTOR(DILexicalBlockFile)
977 SIMPLIFY_DESCRIPTOR(DINameSpace)
978 SIMPLIFY_DESCRIPTOR(DITemplateTypeParameter)
979 SIMPLIFY_DESCRIPTOR(DITemplateValueParameter)
980 SIMPLIFY_DESCRIPTOR(DIGlobalVariable)
981 SIMPLIFY_DESCRIPTOR(DIVariable)
982 SIMPLIFY_DESCRIPTOR(DIExpression)
983 SIMPLIFY_DESCRIPTOR(DILocation)
984 SIMPLIFY_DESCRIPTOR(DIObjCProperty)
985 SIMPLIFY_DESCRIPTOR(DIImportedEntity)
986 #undef SIMPLIFY_DESCRIPTOR
987
988 /// \brief Find subprogram that is enclosing this scope.
989 DISubprogram getDISubprogram(const MDNode *Scope);
990
991 /// \brief Find debug info for a given function.
992 /// \returns a valid DISubprogram, if found. Otherwise, it returns an empty
993 /// DISubprogram.
994 DISubprogram getDISubprogram(const Function *F);
995
996 /// \brief Find underlying composite type.
997 DICompositeType getDICompositeType(DIType T);
998
999 /// \brief Create a new inlined variable based on current variable.
1000 ///
1001 /// @param DV            Current Variable.
1002 /// @param InlinedScope  Location at current variable is inlined.
1003 DIVariable createInlinedVariable(MDNode *DV, MDNode *InlinedScope,
1004                                  LLVMContext &VMContext);
1005
1006 /// \brief Remove inlined scope from the variable.
1007 DIVariable cleanseInlinedVariable(MDNode *DV, LLVMContext &VMContext);
1008
1009 /// \brief Generate map by visiting all retained types.
1010 DITypeIdentifierMap generateDITypeIdentifierMap(const NamedMDNode *CU_Nodes);
1011
1012 /// \brief Strip debug info in the module if it exists.
1013 ///
1014 /// To do this, we remove all calls to the debugger intrinsics and any named
1015 /// metadata for debugging. We also remove debug locations for instructions.
1016 /// Return true if module is modified.
1017 bool StripDebugInfo(Module &M);
1018 bool stripDebugInfo(Function &F);
1019
1020 /// \brief Return Debug Info Metadata Version by checking module flags.
1021 unsigned getDebugMetadataVersionFromModule(const Module &M);
1022
1023 /// \brief Utility to find all debug info in a module.
1024 ///
1025 /// DebugInfoFinder tries to list all debug info MDNodes used in a module. To
1026 /// list debug info MDNodes used by an instruction, DebugInfoFinder uses
1027 /// processDeclare, processValue and processLocation to handle DbgDeclareInst,
1028 /// DbgValueInst and DbgLoc attached to instructions. processModule will go
1029 /// through all DICompileUnits in llvm.dbg.cu and list debug info MDNodes
1030 /// used by the CUs.
1031 class DebugInfoFinder {
1032 public:
1033   DebugInfoFinder() : TypeMapInitialized(false) {}
1034
1035   /// \brief Process entire module and collect debug info anchors.
1036   void processModule(const Module &M);
1037
1038   /// \brief Process DbgDeclareInst.
1039   void processDeclare(const Module &M, const DbgDeclareInst *DDI);
1040   /// \brief Process DbgValueInst.
1041   void processValue(const Module &M, const DbgValueInst *DVI);
1042   /// \brief Process DILocation.
1043   void processLocation(const Module &M, DILocation Loc);
1044
1045   /// \brief Clear all lists.
1046   void reset();
1047
1048 private:
1049   void InitializeTypeMap(const Module &M);
1050
1051   void processType(DIType DT);
1052   void processSubprogram(DISubprogram SP);
1053   void processScope(DIScope Scope);
1054   bool addCompileUnit(DICompileUnit CU);
1055   bool addGlobalVariable(DIGlobalVariable DIG);
1056   bool addSubprogram(DISubprogram SP);
1057   bool addType(DIType DT);
1058   bool addScope(DIScope Scope);
1059
1060 public:
1061   typedef SmallVectorImpl<DICompileUnit>::const_iterator compile_unit_iterator;
1062   typedef SmallVectorImpl<DISubprogram>::const_iterator subprogram_iterator;
1063   typedef SmallVectorImpl<DIGlobalVariable>::const_iterator
1064       global_variable_iterator;
1065   typedef SmallVectorImpl<DIType>::const_iterator type_iterator;
1066   typedef SmallVectorImpl<DIScope>::const_iterator scope_iterator;
1067
1068   iterator_range<compile_unit_iterator> compile_units() const {
1069     return iterator_range<compile_unit_iterator>(CUs.begin(), CUs.end());
1070   }
1071
1072   iterator_range<subprogram_iterator> subprograms() const {
1073     return iterator_range<subprogram_iterator>(SPs.begin(), SPs.end());
1074   }
1075
1076   iterator_range<global_variable_iterator> global_variables() const {
1077     return iterator_range<global_variable_iterator>(GVs.begin(), GVs.end());
1078   }
1079
1080   iterator_range<type_iterator> types() const {
1081     return iterator_range<type_iterator>(TYs.begin(), TYs.end());
1082   }
1083
1084   iterator_range<scope_iterator> scopes() const {
1085     return iterator_range<scope_iterator>(Scopes.begin(), Scopes.end());
1086   }
1087
1088   unsigned compile_unit_count() const { return CUs.size(); }
1089   unsigned global_variable_count() const { return GVs.size(); }
1090   unsigned subprogram_count() const { return SPs.size(); }
1091   unsigned type_count() const { return TYs.size(); }
1092   unsigned scope_count() const { return Scopes.size(); }
1093
1094 private:
1095   SmallVector<DICompileUnit, 8> CUs;
1096   SmallVector<DISubprogram, 8> SPs;
1097   SmallVector<DIGlobalVariable, 8> GVs;
1098   SmallVector<DIType, 8> TYs;
1099   SmallVector<DIScope, 8> Scopes;
1100   SmallPtrSet<MDNode *, 64> NodesSeen;
1101   DITypeIdentifierMap TypeIdentifierMap;
1102
1103   /// \brief Specify if TypeIdentifierMap is initialized.
1104   bool TypeMapInitialized;
1105 };
1106
1107 DenseMap<const Function *, DISubprogram> makeSubprogramMap(const Module &M);
1108
1109 } // end namespace llvm
1110
1111 #endif