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