1 //===- DebugInfoMetadata.cpp - Implement debug info metadata --------------===//
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 implements the debug info Metadata classes.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/IR/DebugInfoMetadata.h"
15 #include "LLVMContextImpl.h"
16 #include "MetadataImpl.h"
17 #include "llvm/ADT/StringSwitch.h"
18 #include "llvm/IR/Function.h"
19 
20 using namespace llvm;
21 
22 DILocation::DILocation(LLVMContext &C, StorageType Storage, unsigned Line,
23                        unsigned Column, ArrayRef<Metadata *> MDs)
24     : MDNode(C, DILocationKind, Storage, MDs) {
25   assert((MDs.size() == 1 || MDs.size() == 2) &&
26          "Expected a scope and optional inlined-at");
27 
28   // Set line and column.
29   assert(Column < (1u << 16) && "Expected 16-bit column");
30 
31   SubclassData32 = Line;
32   SubclassData16 = Column;
33 }
34 
35 static void adjustColumn(unsigned &Column) {
36   // Set to unknown on overflow.  We only have 16 bits to play with here.
37   if (Column >= (1u << 16))
38     Column = 0;
39 }
40 
41 DILocation *DILocation::getImpl(LLVMContext &Context, unsigned Line,
42                                 unsigned Column, Metadata *Scope,
43                                 Metadata *InlinedAt, StorageType Storage,
44                                 bool ShouldCreate) {
45   // Fixup column.
46   adjustColumn(Column);
47 
48   if (Storage == Uniqued) {
49     if (auto *N =
50             getUniqued(Context.pImpl->DILocations,
51                        DILocationInfo::KeyTy(Line, Column, Scope, InlinedAt)))
52       return N;
53     if (!ShouldCreate)
54       return nullptr;
55   } else {
56     assert(ShouldCreate && "Expected non-uniqued nodes to always be created");
57   }
58 
59   SmallVector<Metadata *, 2> Ops;
60   Ops.push_back(Scope);
61   if (InlinedAt)
62     Ops.push_back(InlinedAt);
63   return storeImpl(new (Ops.size())
64                        DILocation(Context, Storage, Line, Column, Ops),
65                    Storage, Context.pImpl->DILocations);
66 }
67 
68 DINode::DIFlags DINode::getFlag(StringRef Flag) {
69   return StringSwitch<DIFlags>(Flag)
70 #define HANDLE_DI_FLAG(ID, NAME) .Case("DIFlag" #NAME, Flag##NAME)
71 #include "llvm/IR/DebugInfoFlags.def"
72       .Default(DINode::FlagZero);
73 }
74 
75 StringRef DINode::getFlagString(DIFlags Flag) {
76   switch (Flag) {
77 #define HANDLE_DI_FLAG(ID, NAME)                                               \
78   case Flag##NAME:                                                             \
79     return "DIFlag" #NAME;
80 #include "llvm/IR/DebugInfoFlags.def"
81   }
82   return "";
83 }
84 
85 DINode::DIFlags DINode::splitFlags(DIFlags Flags,
86                                    SmallVectorImpl<DIFlags> &SplitFlags) {
87   // Flags that are packed together need to be specially handled, so
88   // that, for example, we emit "DIFlagPublic" and not
89   // "DIFlagPrivate | DIFlagProtected".
90   if (DIFlags A = Flags & FlagAccessibility) {
91     if (A == FlagPrivate)
92       SplitFlags.push_back(FlagPrivate);
93     else if (A == FlagProtected)
94       SplitFlags.push_back(FlagProtected);
95     else
96       SplitFlags.push_back(FlagPublic);
97     Flags &= ~A;
98   }
99   if (DIFlags R = Flags & FlagPtrToMemberRep) {
100     if (R == FlagSingleInheritance)
101       SplitFlags.push_back(FlagSingleInheritance);
102     else if (R == FlagMultipleInheritance)
103       SplitFlags.push_back(FlagMultipleInheritance);
104     else
105       SplitFlags.push_back(FlagVirtualInheritance);
106     Flags &= ~R;
107   }
108   if ((Flags & FlagIndirectVirtualBase) == FlagIndirectVirtualBase) {
109     Flags &= ~FlagIndirectVirtualBase;
110     SplitFlags.push_back(FlagIndirectVirtualBase);
111   }
112 
113 #define HANDLE_DI_FLAG(ID, NAME)                                               \
114   if (DIFlags Bit = Flags & Flag##NAME) {                                      \
115     SplitFlags.push_back(Bit);                                                 \
116     Flags &= ~Bit;                                                             \
117   }
118 #include "llvm/IR/DebugInfoFlags.def"
119   return Flags;
120 }
121 
122 DIScopeRef DIScope::getScope() const {
123   if (auto *T = dyn_cast<DIType>(this))
124     return T->getScope();
125 
126   if (auto *SP = dyn_cast<DISubprogram>(this))
127     return SP->getScope();
128 
129   if (auto *LB = dyn_cast<DILexicalBlockBase>(this))
130     return LB->getScope();
131 
132   if (auto *NS = dyn_cast<DINamespace>(this))
133     return NS->getScope();
134 
135   if (auto *M = dyn_cast<DIModule>(this))
136     return M->getScope();
137 
138   assert((isa<DIFile>(this) || isa<DICompileUnit>(this)) &&
139          "Unhandled type of scope.");
140   return nullptr;
141 }
142 
143 StringRef DIScope::getName() const {
144   if (auto *T = dyn_cast<DIType>(this))
145     return T->getName();
146   if (auto *SP = dyn_cast<DISubprogram>(this))
147     return SP->getName();
148   if (auto *NS = dyn_cast<DINamespace>(this))
149     return NS->getName();
150   if (auto *M = dyn_cast<DIModule>(this))
151     return M->getName();
152   assert((isa<DILexicalBlockBase>(this) || isa<DIFile>(this) ||
153           isa<DICompileUnit>(this)) &&
154          "Unhandled type of scope.");
155   return "";
156 }
157 
158 #ifndef NDEBUG
159 static bool isCanonical(const MDString *S) {
160   return !S || !S->getString().empty();
161 }
162 #endif
163 
164 GenericDINode *GenericDINode::getImpl(LLVMContext &Context, unsigned Tag,
165                                       MDString *Header,
166                                       ArrayRef<Metadata *> DwarfOps,
167                                       StorageType Storage, bool ShouldCreate) {
168   unsigned Hash = 0;
169   if (Storage == Uniqued) {
170     GenericDINodeInfo::KeyTy Key(Tag, Header, DwarfOps);
171     if (auto *N = getUniqued(Context.pImpl->GenericDINodes, Key))
172       return N;
173     if (!ShouldCreate)
174       return nullptr;
175     Hash = Key.getHash();
176   } else {
177     assert(ShouldCreate && "Expected non-uniqued nodes to always be created");
178   }
179 
180   // Use a nullptr for empty headers.
181   assert(isCanonical(Header) && "Expected canonical MDString");
182   Metadata *PreOps[] = {Header};
183   return storeImpl(new (DwarfOps.size() + 1) GenericDINode(
184                        Context, Storage, Hash, Tag, PreOps, DwarfOps),
185                    Storage, Context.pImpl->GenericDINodes);
186 }
187 
188 void GenericDINode::recalculateHash() {
189   setHash(GenericDINodeInfo::KeyTy::calculateHash(this));
190 }
191 
192 #define UNWRAP_ARGS_IMPL(...) __VA_ARGS__
193 #define UNWRAP_ARGS(ARGS) UNWRAP_ARGS_IMPL ARGS
194 #define DEFINE_GETIMPL_LOOKUP(CLASS, ARGS)                                     \
195   do {                                                                         \
196     if (Storage == Uniqued) {                                                  \
197       if (auto *N = getUniqued(Context.pImpl->CLASS##s,                        \
198                                CLASS##Info::KeyTy(UNWRAP_ARGS(ARGS))))         \
199         return N;                                                              \
200       if (!ShouldCreate)                                                       \
201         return nullptr;                                                        \
202     } else {                                                                   \
203       assert(ShouldCreate &&                                                   \
204              "Expected non-uniqued nodes to always be created");               \
205     }                                                                          \
206   } while (false)
207 #define DEFINE_GETIMPL_STORE(CLASS, ARGS, OPS)                                 \
208   return storeImpl(new (array_lengthof(OPS))                                   \
209                        CLASS(Context, Storage, UNWRAP_ARGS(ARGS), OPS),        \
210                    Storage, Context.pImpl->CLASS##s)
211 #define DEFINE_GETIMPL_STORE_NO_OPS(CLASS, ARGS)                               \
212   return storeImpl(new (0u) CLASS(Context, Storage, UNWRAP_ARGS(ARGS)),        \
213                    Storage, Context.pImpl->CLASS##s)
214 #define DEFINE_GETIMPL_STORE_NO_CONSTRUCTOR_ARGS(CLASS, OPS)                   \
215   return storeImpl(new (array_lengthof(OPS)) CLASS(Context, Storage, OPS),     \
216                    Storage, Context.pImpl->CLASS##s)
217 
218 DISubrange *DISubrange::getImpl(LLVMContext &Context, int64_t Count, int64_t Lo,
219                                 StorageType Storage, bool ShouldCreate) {
220   DEFINE_GETIMPL_LOOKUP(DISubrange, (Count, Lo));
221   DEFINE_GETIMPL_STORE_NO_OPS(DISubrange, (Count, Lo));
222 }
223 
224 DIEnumerator *DIEnumerator::getImpl(LLVMContext &Context, int64_t Value,
225                                     MDString *Name, StorageType Storage,
226                                     bool ShouldCreate) {
227   assert(isCanonical(Name) && "Expected canonical MDString");
228   DEFINE_GETIMPL_LOOKUP(DIEnumerator, (Value, Name));
229   Metadata *Ops[] = {Name};
230   DEFINE_GETIMPL_STORE(DIEnumerator, (Value), Ops);
231 }
232 
233 DIBasicType *DIBasicType::getImpl(LLVMContext &Context, unsigned Tag,
234                                   MDString *Name, uint64_t SizeInBits,
235                                   uint32_t AlignInBits, unsigned Encoding,
236                                   StorageType Storage, bool ShouldCreate) {
237   assert(isCanonical(Name) && "Expected canonical MDString");
238   DEFINE_GETIMPL_LOOKUP(DIBasicType,
239                         (Tag, Name, SizeInBits, AlignInBits, Encoding));
240   Metadata *Ops[] = {nullptr, nullptr, Name};
241   DEFINE_GETIMPL_STORE(DIBasicType, (Tag, SizeInBits, AlignInBits, Encoding),
242                        Ops);
243 }
244 
245 DIDerivedType *DIDerivedType::getImpl(
246     LLVMContext &Context, unsigned Tag, MDString *Name, Metadata *File,
247     unsigned Line, Metadata *Scope, Metadata *BaseType, uint64_t SizeInBits,
248     uint32_t AlignInBits, uint64_t OffsetInBits,
249     Optional<unsigned> DWARFAddressSpace, DIFlags Flags, Metadata *ExtraData,
250     StorageType Storage, bool ShouldCreate) {
251   assert(isCanonical(Name) && "Expected canonical MDString");
252   DEFINE_GETIMPL_LOOKUP(DIDerivedType,
253                         (Tag, Name, File, Line, Scope, BaseType, SizeInBits,
254                          AlignInBits, OffsetInBits, DWARFAddressSpace, Flags,
255                          ExtraData));
256   Metadata *Ops[] = {File, Scope, Name, BaseType, ExtraData};
257   DEFINE_GETIMPL_STORE(
258       DIDerivedType, (Tag, Line, SizeInBits, AlignInBits, OffsetInBits,
259                       DWARFAddressSpace, Flags), Ops);
260 }
261 
262 DICompositeType *DICompositeType::getImpl(
263     LLVMContext &Context, unsigned Tag, MDString *Name, Metadata *File,
264     unsigned Line, Metadata *Scope, Metadata *BaseType, uint64_t SizeInBits,
265     uint32_t AlignInBits, uint64_t OffsetInBits, DIFlags Flags,
266     Metadata *Elements, unsigned RuntimeLang, Metadata *VTableHolder,
267     Metadata *TemplateParams, MDString *Identifier, StorageType Storage,
268     bool ShouldCreate) {
269   assert(isCanonical(Name) && "Expected canonical MDString");
270 
271   // Keep this in sync with buildODRType.
272   DEFINE_GETIMPL_LOOKUP(
273       DICompositeType, (Tag, Name, File, Line, Scope, BaseType, SizeInBits,
274                         AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang,
275                         VTableHolder, TemplateParams, Identifier));
276   Metadata *Ops[] = {File,     Scope,        Name,           BaseType,
277                      Elements, VTableHolder, TemplateParams, Identifier};
278   DEFINE_GETIMPL_STORE(DICompositeType, (Tag, Line, RuntimeLang, SizeInBits,
279                                          AlignInBits, OffsetInBits, Flags),
280                        Ops);
281 }
282 
283 DICompositeType *DICompositeType::buildODRType(
284     LLVMContext &Context, MDString &Identifier, unsigned Tag, MDString *Name,
285     Metadata *File, unsigned Line, Metadata *Scope, Metadata *BaseType,
286     uint64_t SizeInBits, uint32_t AlignInBits, uint64_t OffsetInBits,
287     DIFlags Flags, Metadata *Elements, unsigned RuntimeLang,
288     Metadata *VTableHolder, Metadata *TemplateParams) {
289   assert(!Identifier.getString().empty() && "Expected valid identifier");
290   if (!Context.isODRUniquingDebugTypes())
291     return nullptr;
292   auto *&CT = (*Context.pImpl->DITypeMap)[&Identifier];
293   if (!CT)
294     return CT = DICompositeType::getDistinct(
295                Context, Tag, Name, File, Line, Scope, BaseType, SizeInBits,
296                AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang,
297                VTableHolder, TemplateParams, &Identifier);
298 
299   // Only mutate CT if it's a forward declaration and the new operands aren't.
300   assert(CT->getRawIdentifier() == &Identifier && "Wrong ODR identifier?");
301   if (!CT->isForwardDecl() || (Flags & DINode::FlagFwdDecl))
302     return CT;
303 
304   // Mutate CT in place.  Keep this in sync with getImpl.
305   CT->mutate(Tag, Line, RuntimeLang, SizeInBits, AlignInBits, OffsetInBits,
306              Flags);
307   Metadata *Ops[] = {File,     Scope,        Name,           BaseType,
308                      Elements, VTableHolder, TemplateParams, &Identifier};
309   assert((std::end(Ops) - std::begin(Ops)) == (int)CT->getNumOperands() &&
310          "Mismatched number of operands");
311   for (unsigned I = 0, E = CT->getNumOperands(); I != E; ++I)
312     if (Ops[I] != CT->getOperand(I))
313       CT->setOperand(I, Ops[I]);
314   return CT;
315 }
316 
317 DICompositeType *DICompositeType::getODRType(
318     LLVMContext &Context, MDString &Identifier, unsigned Tag, MDString *Name,
319     Metadata *File, unsigned Line, Metadata *Scope, Metadata *BaseType,
320     uint64_t SizeInBits, uint32_t AlignInBits, uint64_t OffsetInBits,
321     DIFlags Flags, Metadata *Elements, unsigned RuntimeLang,
322     Metadata *VTableHolder, Metadata *TemplateParams) {
323   assert(!Identifier.getString().empty() && "Expected valid identifier");
324   if (!Context.isODRUniquingDebugTypes())
325     return nullptr;
326   auto *&CT = (*Context.pImpl->DITypeMap)[&Identifier];
327   if (!CT)
328     CT = DICompositeType::getDistinct(
329         Context, Tag, Name, File, Line, Scope, BaseType, SizeInBits,
330         AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang, VTableHolder,
331         TemplateParams, &Identifier);
332   return CT;
333 }
334 
335 DICompositeType *DICompositeType::getODRTypeIfExists(LLVMContext &Context,
336                                                      MDString &Identifier) {
337   assert(!Identifier.getString().empty() && "Expected valid identifier");
338   if (!Context.isODRUniquingDebugTypes())
339     return nullptr;
340   return Context.pImpl->DITypeMap->lookup(&Identifier);
341 }
342 
343 DISubroutineType *DISubroutineType::getImpl(LLVMContext &Context, DIFlags Flags,
344                                             uint8_t CC, Metadata *TypeArray,
345                                             StorageType Storage,
346                                             bool ShouldCreate) {
347   DEFINE_GETIMPL_LOOKUP(DISubroutineType, (Flags, CC, TypeArray));
348   Metadata *Ops[] = {nullptr, nullptr, nullptr, TypeArray};
349   DEFINE_GETIMPL_STORE(DISubroutineType, (Flags, CC), Ops);
350 }
351 
352 static const char *ChecksumKindName[DIFile::CSK_Last + 1] = {
353   "CSK_None",
354   "CSK_MD5",
355   "CSK_SHA1"
356 };
357 
358 DIFile::ChecksumKind DIFile::getChecksumKind(StringRef CSKindStr) {
359   return StringSwitch<DIFile::ChecksumKind>(CSKindStr)
360       .Case("CSK_MD5", DIFile::CSK_MD5)
361       .Case("CSK_SHA1", DIFile::CSK_SHA1)
362       .Default(DIFile::CSK_None);
363 }
364 
365 StringRef DIFile::getChecksumKindAsString() const {
366   assert(CSKind <= DIFile::CSK_Last && "Invalid checksum kind");
367   return ChecksumKindName[CSKind];
368 }
369 
370 DIFile *DIFile::getImpl(LLVMContext &Context, MDString *Filename,
371                         MDString *Directory, DIFile::ChecksumKind CSKind,
372                         MDString *Checksum, StorageType Storage,
373                         bool ShouldCreate) {
374   assert(isCanonical(Filename) && "Expected canonical MDString");
375   assert(isCanonical(Directory) && "Expected canonical MDString");
376   assert(isCanonical(Checksum) && "Expected canonical MDString");
377   DEFINE_GETIMPL_LOOKUP(DIFile, (Filename, Directory, CSKind, Checksum));
378   Metadata *Ops[] = {Filename, Directory, Checksum};
379   DEFINE_GETIMPL_STORE(DIFile, (CSKind), Ops);
380 }
381 
382 DICompileUnit *DICompileUnit::getImpl(
383     LLVMContext &Context, unsigned SourceLanguage, Metadata *File,
384     MDString *Producer, bool IsOptimized, MDString *Flags,
385     unsigned RuntimeVersion, MDString *SplitDebugFilename,
386     unsigned EmissionKind, Metadata *EnumTypes, Metadata *RetainedTypes,
387     Metadata *GlobalVariables, Metadata *ImportedEntities, Metadata *Macros,
388     uint64_t DWOId, bool SplitDebugInlining, bool DebugInfoForProfiling,
389     StorageType Storage, bool ShouldCreate) {
390   assert(Storage != Uniqued && "Cannot unique DICompileUnit");
391   assert(isCanonical(Producer) && "Expected canonical MDString");
392   assert(isCanonical(Flags) && "Expected canonical MDString");
393   assert(isCanonical(SplitDebugFilename) && "Expected canonical MDString");
394 
395   Metadata *Ops[] = {
396       File,      Producer,      Flags,           SplitDebugFilename,
397       EnumTypes, RetainedTypes, GlobalVariables, ImportedEntities,
398       Macros};
399   return storeImpl(new (array_lengthof(Ops))
400                        DICompileUnit(Context, Storage, SourceLanguage,
401                                      IsOptimized, RuntimeVersion, EmissionKind,
402                                      DWOId, SplitDebugInlining,
403                                      DebugInfoForProfiling, Ops),
404                    Storage);
405 }
406 
407 Optional<DICompileUnit::DebugEmissionKind>
408 DICompileUnit::getEmissionKind(StringRef Str) {
409   return StringSwitch<Optional<DebugEmissionKind>>(Str)
410       .Case("NoDebug", NoDebug)
411       .Case("FullDebug", FullDebug)
412       .Case("LineTablesOnly", LineTablesOnly)
413       .Default(None);
414 }
415 
416 const char *DICompileUnit::EmissionKindString(DebugEmissionKind EK) {
417   switch (EK) {
418   case NoDebug:        return "NoDebug";
419   case FullDebug:      return "FullDebug";
420   case LineTablesOnly: return "LineTablesOnly";
421   }
422   return nullptr;
423 }
424 
425 DISubprogram *DILocalScope::getSubprogram() const {
426   if (auto *Block = dyn_cast<DILexicalBlockBase>(this))
427     return Block->getScope()->getSubprogram();
428   return const_cast<DISubprogram *>(cast<DISubprogram>(this));
429 }
430 
431 DILocalScope *DILocalScope::getNonLexicalBlockFileScope() const {
432   if (auto *File = dyn_cast<DILexicalBlockFile>(this))
433     return File->getScope()->getNonLexicalBlockFileScope();
434   return const_cast<DILocalScope *>(this);
435 }
436 
437 DISubprogram *DISubprogram::getImpl(
438     LLVMContext &Context, Metadata *Scope, MDString *Name,
439     MDString *LinkageName, Metadata *File, unsigned Line, Metadata *Type,
440     bool IsLocalToUnit, bool IsDefinition, unsigned ScopeLine,
441     Metadata *ContainingType, unsigned Virtuality, unsigned VirtualIndex,
442     int ThisAdjustment, DIFlags Flags, bool IsOptimized, Metadata *Unit,
443     Metadata *TemplateParams, Metadata *Declaration, Metadata *Variables,
444     StorageType Storage, bool ShouldCreate) {
445   assert(isCanonical(Name) && "Expected canonical MDString");
446   assert(isCanonical(LinkageName) && "Expected canonical MDString");
447   DEFINE_GETIMPL_LOOKUP(
448       DISubprogram,
449       (Scope, Name, LinkageName, File, Line, Type, IsLocalToUnit, IsDefinition,
450        ScopeLine, ContainingType, Virtuality, VirtualIndex, ThisAdjustment,
451        Flags, IsOptimized, Unit, TemplateParams, Declaration, Variables));
452   Metadata *Ops[] = {File,           Scope,       Name,           Name,
453                      LinkageName,    Type,        ContainingType, Unit,
454                      TemplateParams, Declaration, Variables};
455   DEFINE_GETIMPL_STORE(DISubprogram, (Line, ScopeLine, Virtuality, VirtualIndex,
456                                       ThisAdjustment, Flags, IsLocalToUnit,
457                                       IsDefinition, IsOptimized),
458                        Ops);
459 }
460 
461 bool DISubprogram::describes(const Function *F) const {
462   assert(F && "Invalid function");
463   if (F->getSubprogram() == this)
464     return true;
465   StringRef Name = getLinkageName();
466   if (Name.empty())
467     Name = getName();
468   return F->getName() == Name;
469 }
470 
471 DILexicalBlock *DILexicalBlock::getImpl(LLVMContext &Context, Metadata *Scope,
472                                         Metadata *File, unsigned Line,
473                                         unsigned Column, StorageType Storage,
474                                         bool ShouldCreate) {
475   // Fixup column.
476   adjustColumn(Column);
477 
478   assert(Scope && "Expected scope");
479   DEFINE_GETIMPL_LOOKUP(DILexicalBlock, (Scope, File, Line, Column));
480   Metadata *Ops[] = {File, Scope};
481   DEFINE_GETIMPL_STORE(DILexicalBlock, (Line, Column), Ops);
482 }
483 
484 DILexicalBlockFile *DILexicalBlockFile::getImpl(LLVMContext &Context,
485                                                 Metadata *Scope, Metadata *File,
486                                                 unsigned Discriminator,
487                                                 StorageType Storage,
488                                                 bool ShouldCreate) {
489   assert(Scope && "Expected scope");
490   DEFINE_GETIMPL_LOOKUP(DILexicalBlockFile, (Scope, File, Discriminator));
491   Metadata *Ops[] = {File, Scope};
492   DEFINE_GETIMPL_STORE(DILexicalBlockFile, (Discriminator), Ops);
493 }
494 
495 DINamespace *DINamespace::getImpl(LLVMContext &Context, Metadata *Scope,
496                                   Metadata *File, MDString *Name, unsigned Line,
497                                   bool ExportSymbols, StorageType Storage,
498                                   bool ShouldCreate) {
499   assert(isCanonical(Name) && "Expected canonical MDString");
500   DEFINE_GETIMPL_LOOKUP(DINamespace, (Scope, File, Name, Line, ExportSymbols));
501   Metadata *Ops[] = {File, Scope, Name};
502   DEFINE_GETIMPL_STORE(DINamespace, (Line, ExportSymbols), Ops);
503 }
504 
505 DIModule *DIModule::getImpl(LLVMContext &Context, Metadata *Scope,
506                             MDString *Name, MDString *ConfigurationMacros,
507                             MDString *IncludePath, MDString *ISysRoot,
508                             StorageType Storage, bool ShouldCreate) {
509   assert(isCanonical(Name) && "Expected canonical MDString");
510   DEFINE_GETIMPL_LOOKUP(
511       DIModule, (Scope, Name, ConfigurationMacros, IncludePath, ISysRoot));
512   Metadata *Ops[] = {Scope, Name, ConfigurationMacros, IncludePath, ISysRoot};
513   DEFINE_GETIMPL_STORE_NO_CONSTRUCTOR_ARGS(DIModule, Ops);
514 }
515 
516 DITemplateTypeParameter *DITemplateTypeParameter::getImpl(LLVMContext &Context,
517                                                           MDString *Name,
518                                                           Metadata *Type,
519                                                           StorageType Storage,
520                                                           bool ShouldCreate) {
521   assert(isCanonical(Name) && "Expected canonical MDString");
522   DEFINE_GETIMPL_LOOKUP(DITemplateTypeParameter, (Name, Type));
523   Metadata *Ops[] = {Name, Type};
524   DEFINE_GETIMPL_STORE_NO_CONSTRUCTOR_ARGS(DITemplateTypeParameter, Ops);
525 }
526 
527 DITemplateValueParameter *DITemplateValueParameter::getImpl(
528     LLVMContext &Context, unsigned Tag, MDString *Name, Metadata *Type,
529     Metadata *Value, StorageType Storage, bool ShouldCreate) {
530   assert(isCanonical(Name) && "Expected canonical MDString");
531   DEFINE_GETIMPL_LOOKUP(DITemplateValueParameter, (Tag, Name, Type, Value));
532   Metadata *Ops[] = {Name, Type, Value};
533   DEFINE_GETIMPL_STORE(DITemplateValueParameter, (Tag), Ops);
534 }
535 
536 DIGlobalVariable *
537 DIGlobalVariable::getImpl(LLVMContext &Context, Metadata *Scope, MDString *Name,
538                           MDString *LinkageName, Metadata *File, unsigned Line,
539                           Metadata *Type, bool IsLocalToUnit, bool IsDefinition,
540                           Metadata *StaticDataMemberDeclaration,
541                           uint32_t AlignInBits, StorageType Storage,
542                           bool ShouldCreate) {
543   assert(isCanonical(Name) && "Expected canonical MDString");
544   assert(isCanonical(LinkageName) && "Expected canonical MDString");
545   DEFINE_GETIMPL_LOOKUP(DIGlobalVariable,
546                         (Scope, Name, LinkageName, File, Line, Type,
547                          IsLocalToUnit, IsDefinition,
548                          StaticDataMemberDeclaration, AlignInBits));
549   Metadata *Ops[] = {
550       Scope, Name, File, Type, Name, LinkageName, StaticDataMemberDeclaration};
551   DEFINE_GETIMPL_STORE(DIGlobalVariable,
552                        (Line, IsLocalToUnit, IsDefinition, AlignInBits),
553                        Ops);
554 }
555 
556 DILocalVariable *DILocalVariable::getImpl(LLVMContext &Context, Metadata *Scope,
557                                           MDString *Name, Metadata *File,
558                                           unsigned Line, Metadata *Type,
559                                           unsigned Arg, DIFlags Flags,
560                                           uint32_t AlignInBits,
561                                           StorageType Storage,
562                                           bool ShouldCreate) {
563   // 64K ought to be enough for any frontend.
564   assert(Arg <= UINT16_MAX && "Expected argument number to fit in 16-bits");
565 
566   assert(Scope && "Expected scope");
567   assert(isCanonical(Name) && "Expected canonical MDString");
568   DEFINE_GETIMPL_LOOKUP(DILocalVariable,
569                         (Scope, Name, File, Line, Type, Arg, Flags,
570                          AlignInBits));
571   Metadata *Ops[] = {Scope, Name, File, Type};
572   DEFINE_GETIMPL_STORE(DILocalVariable, (Line, Arg, Flags, AlignInBits), Ops);
573 }
574 
575 DIExpression *DIExpression::getImpl(LLVMContext &Context,
576                                     ArrayRef<uint64_t> Elements,
577                                     StorageType Storage, bool ShouldCreate) {
578   DEFINE_GETIMPL_LOOKUP(DIExpression, (Elements));
579   DEFINE_GETIMPL_STORE_NO_OPS(DIExpression, (Elements));
580 }
581 
582 unsigned DIExpression::ExprOperand::getSize() const {
583   switch (getOp()) {
584   case dwarf::DW_OP_LLVM_fragment:
585     return 3;
586   case dwarf::DW_OP_constu:
587   case dwarf::DW_OP_plus:
588   case dwarf::DW_OP_minus:
589     return 2;
590   default:
591     return 1;
592   }
593 }
594 
595 bool DIExpression::isValid() const {
596   for (auto I = expr_op_begin(), E = expr_op_end(); I != E; ++I) {
597     // Check that there's space for the operand.
598     if (I->get() + I->getSize() > E->get())
599       return false;
600 
601     // Check that the operand is valid.
602     switch (I->getOp()) {
603     default:
604       return false;
605     case dwarf::DW_OP_LLVM_fragment:
606       // A fragment operator must appear at the end.
607       return I->get() + I->getSize() == E->get();
608     case dwarf::DW_OP_stack_value: {
609       // Must be the last one or followed by a DW_OP_LLVM_fragment.
610       if (I->get() + I->getSize() == E->get())
611         break;
612       auto J = I;
613       if ((++J)->getOp() != dwarf::DW_OP_LLVM_fragment)
614         return false;
615       break;
616     }
617     case dwarf::DW_OP_swap: {
618       // Must be more than one implicit element on the stack.
619 
620       // FIXME: A better way to implement this would be to add a local variable
621       // that keeps track of the stack depth and introduce something like a
622       // DW_LLVM_OP_implicit_location as a placeholder for the location this
623       // DIExpression is attached to, or else pass the number of implicit stack
624       // elements into isValid.
625       if (getNumElements() == 1)
626         return false;
627       break;
628     }
629     case dwarf::DW_OP_constu:
630     case dwarf::DW_OP_plus:
631     case dwarf::DW_OP_minus:
632     case dwarf::DW_OP_deref:
633     case dwarf::DW_OP_xderef:
634       break;
635     }
636   }
637   return true;
638 }
639 
640 Optional<DIExpression::FragmentInfo>
641 DIExpression::getFragmentInfo(expr_op_iterator Start, expr_op_iterator End) {
642   for (auto I = Start; I != End; ++I)
643     if (I->getOp() == dwarf::DW_OP_LLVM_fragment) {
644       DIExpression::FragmentInfo Info = {I->getArg(1), I->getArg(0)};
645       return Info;
646     }
647   return None;
648 }
649 
650 bool DIExpression::isConstant() const {
651   // Recognize DW_OP_constu C DW_OP_stack_value (DW_OP_LLVM_fragment Len Ofs)?.
652   if (getNumElements() != 3 && getNumElements() != 6)
653     return false;
654   if (getElement(0) != dwarf::DW_OP_constu ||
655       getElement(2) != dwarf::DW_OP_stack_value)
656     return false;
657   if (getNumElements() == 6 && getElement(3) != dwarf::DW_OP_LLVM_fragment)
658     return false;
659   return true;
660 }
661 
662 DIGlobalVariableExpression *
663 DIGlobalVariableExpression::getImpl(LLVMContext &Context, Metadata *Variable,
664                                     Metadata *Expression, StorageType Storage,
665                                     bool ShouldCreate) {
666   DEFINE_GETIMPL_LOOKUP(DIGlobalVariableExpression, (Variable, Expression));
667   Metadata *Ops[] = {Variable, Expression};
668   DEFINE_GETIMPL_STORE_NO_CONSTRUCTOR_ARGS(DIGlobalVariableExpression, Ops);
669 }
670 
671 DIObjCProperty *DIObjCProperty::getImpl(
672     LLVMContext &Context, MDString *Name, Metadata *File, unsigned Line,
673     MDString *GetterName, MDString *SetterName, unsigned Attributes,
674     Metadata *Type, StorageType Storage, bool ShouldCreate) {
675   assert(isCanonical(Name) && "Expected canonical MDString");
676   assert(isCanonical(GetterName) && "Expected canonical MDString");
677   assert(isCanonical(SetterName) && "Expected canonical MDString");
678   DEFINE_GETIMPL_LOOKUP(DIObjCProperty, (Name, File, Line, GetterName,
679                                          SetterName, Attributes, Type));
680   Metadata *Ops[] = {Name, File, GetterName, SetterName, Type};
681   DEFINE_GETIMPL_STORE(DIObjCProperty, (Line, Attributes), Ops);
682 }
683 
684 DIImportedEntity *DIImportedEntity::getImpl(LLVMContext &Context, unsigned Tag,
685                                             Metadata *Scope, Metadata *Entity,
686                                             unsigned Line, MDString *Name,
687                                             StorageType Storage,
688                                             bool ShouldCreate) {
689   assert(isCanonical(Name) && "Expected canonical MDString");
690   DEFINE_GETIMPL_LOOKUP(DIImportedEntity, (Tag, Scope, Entity, Line, Name));
691   Metadata *Ops[] = {Scope, Entity, Name};
692   DEFINE_GETIMPL_STORE(DIImportedEntity, (Tag, Line), Ops);
693 }
694 
695 DIMacro *DIMacro::getImpl(LLVMContext &Context, unsigned MIType,
696                           unsigned Line, MDString *Name, MDString *Value,
697                           StorageType Storage, bool ShouldCreate) {
698   assert(isCanonical(Name) && "Expected canonical MDString");
699   DEFINE_GETIMPL_LOOKUP(DIMacro, (MIType, Line, Name, Value));
700   Metadata *Ops[] = { Name, Value };
701   DEFINE_GETIMPL_STORE(DIMacro, (MIType, Line), Ops);
702 }
703 
704 DIMacroFile *DIMacroFile::getImpl(LLVMContext &Context, unsigned MIType,
705                                   unsigned Line, Metadata *File,
706                                   Metadata *Elements, StorageType Storage,
707                                   bool ShouldCreate) {
708   DEFINE_GETIMPL_LOOKUP(DIMacroFile,
709                         (MIType, Line, File, Elements));
710   Metadata *Ops[] = { File, Elements };
711   DEFINE_GETIMPL_STORE(DIMacroFile, (MIType, Line), Ops);
712 }
713 
714