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/SmallPtrSet.h"
18 #include "llvm/ADT/StringSwitch.h"
19 #include "llvm/IR/DIBuilder.h"
20 #include "llvm/IR/Function.h"
21 #include "llvm/IR/Instructions.h"
22 
23 using namespace llvm;
24 
25 DILocation::DILocation(LLVMContext &C, StorageType Storage, unsigned Line,
26                        unsigned Column, ArrayRef<Metadata *> MDs)
27     : MDNode(C, DILocationKind, Storage, MDs) {
28   assert((MDs.size() == 1 || MDs.size() == 2) &&
29          "Expected a scope and optional inlined-at");
30 
31   // Set line and column.
32   assert(Column < (1u << 16) && "Expected 16-bit column");
33 
34   SubclassData32 = Line;
35   SubclassData16 = Column;
36 }
37 
38 static void adjustColumn(unsigned &Column) {
39   // Set to unknown on overflow.  We only have 16 bits to play with here.
40   if (Column >= (1u << 16))
41     Column = 0;
42 }
43 
44 DILocation *DILocation::getImpl(LLVMContext &Context, unsigned Line,
45                                 unsigned Column, Metadata *Scope,
46                                 Metadata *InlinedAt, StorageType Storage,
47                                 bool ShouldCreate) {
48   // Fixup column.
49   adjustColumn(Column);
50 
51   if (Storage == Uniqued) {
52     if (auto *N =
53             getUniqued(Context.pImpl->DILocations,
54                        DILocationInfo::KeyTy(Line, Column, Scope, InlinedAt)))
55       return N;
56     if (!ShouldCreate)
57       return nullptr;
58   } else {
59     assert(ShouldCreate && "Expected non-uniqued nodes to always be created");
60   }
61 
62   SmallVector<Metadata *, 2> Ops;
63   Ops.push_back(Scope);
64   if (InlinedAt)
65     Ops.push_back(InlinedAt);
66   return storeImpl(new (Ops.size())
67                        DILocation(Context, Storage, Line, Column, Ops),
68                    Storage, Context.pImpl->DILocations);
69 }
70 
71 const DILocation *
72 DILocation::getMergedLocation(const DILocation *LocA, const DILocation *LocB,
73                               const Instruction *ForInst) {
74   if (!LocA || !LocB)
75     return nullptr;
76 
77   if (LocA == LocB || !LocA->canDiscriminate(*LocB))
78     return LocA;
79 
80   if (!dyn_cast_or_null<CallInst>(ForInst))
81     return nullptr;
82 
83   SmallPtrSet<DILocation *, 5> InlinedLocationsA;
84   for (DILocation *L = LocA->getInlinedAt(); L; L = L->getInlinedAt())
85     InlinedLocationsA.insert(L);
86   const DILocation *Result = LocB;
87   for (DILocation *L = LocB->getInlinedAt(); L; L = L->getInlinedAt()) {
88     Result = L;
89     if (InlinedLocationsA.count(L))
90       break;
91   }
92   return DILocation::get(Result->getContext(), 0, 0, Result->getScope(),
93                          Result->getInlinedAt());
94 }
95 
96 DINode::DIFlags DINode::getFlag(StringRef Flag) {
97   return StringSwitch<DIFlags>(Flag)
98 #define HANDLE_DI_FLAG(ID, NAME) .Case("DIFlag" #NAME, Flag##NAME)
99 #include "llvm/IR/DebugInfoFlags.def"
100       .Default(DINode::FlagZero);
101 }
102 
103 StringRef DINode::getFlagString(DIFlags Flag) {
104   switch (Flag) {
105 #define HANDLE_DI_FLAG(ID, NAME)                                               \
106   case Flag##NAME:                                                             \
107     return "DIFlag" #NAME;
108 #include "llvm/IR/DebugInfoFlags.def"
109   }
110   return "";
111 }
112 
113 DINode::DIFlags DINode::splitFlags(DIFlags Flags,
114                                    SmallVectorImpl<DIFlags> &SplitFlags) {
115   // Flags that are packed together need to be specially handled, so
116   // that, for example, we emit "DIFlagPublic" and not
117   // "DIFlagPrivate | DIFlagProtected".
118   if (DIFlags A = Flags & FlagAccessibility) {
119     if (A == FlagPrivate)
120       SplitFlags.push_back(FlagPrivate);
121     else if (A == FlagProtected)
122       SplitFlags.push_back(FlagProtected);
123     else
124       SplitFlags.push_back(FlagPublic);
125     Flags &= ~A;
126   }
127   if (DIFlags R = Flags & FlagPtrToMemberRep) {
128     if (R == FlagSingleInheritance)
129       SplitFlags.push_back(FlagSingleInheritance);
130     else if (R == FlagMultipleInheritance)
131       SplitFlags.push_back(FlagMultipleInheritance);
132     else
133       SplitFlags.push_back(FlagVirtualInheritance);
134     Flags &= ~R;
135   }
136   if ((Flags & FlagIndirectVirtualBase) == FlagIndirectVirtualBase) {
137     Flags &= ~FlagIndirectVirtualBase;
138     SplitFlags.push_back(FlagIndirectVirtualBase);
139   }
140 
141 #define HANDLE_DI_FLAG(ID, NAME)                                               \
142   if (DIFlags Bit = Flags & Flag##NAME) {                                      \
143     SplitFlags.push_back(Bit);                                                 \
144     Flags &= ~Bit;                                                             \
145   }
146 #include "llvm/IR/DebugInfoFlags.def"
147   return Flags;
148 }
149 
150 DIScopeRef DIScope::getScope() const {
151   if (auto *T = dyn_cast<DIType>(this))
152     return T->getScope();
153 
154   if (auto *SP = dyn_cast<DISubprogram>(this))
155     return SP->getScope();
156 
157   if (auto *LB = dyn_cast<DILexicalBlockBase>(this))
158     return LB->getScope();
159 
160   if (auto *NS = dyn_cast<DINamespace>(this))
161     return NS->getScope();
162 
163   if (auto *M = dyn_cast<DIModule>(this))
164     return M->getScope();
165 
166   assert((isa<DIFile>(this) || isa<DICompileUnit>(this)) &&
167          "Unhandled type of scope.");
168   return nullptr;
169 }
170 
171 StringRef DIScope::getName() const {
172   if (auto *T = dyn_cast<DIType>(this))
173     return T->getName();
174   if (auto *SP = dyn_cast<DISubprogram>(this))
175     return SP->getName();
176   if (auto *NS = dyn_cast<DINamespace>(this))
177     return NS->getName();
178   if (auto *M = dyn_cast<DIModule>(this))
179     return M->getName();
180   assert((isa<DILexicalBlockBase>(this) || isa<DIFile>(this) ||
181           isa<DICompileUnit>(this)) &&
182          "Unhandled type of scope.");
183   return "";
184 }
185 
186 #ifndef NDEBUG
187 static bool isCanonical(const MDString *S) {
188   return !S || !S->getString().empty();
189 }
190 #endif
191 
192 GenericDINode *GenericDINode::getImpl(LLVMContext &Context, unsigned Tag,
193                                       MDString *Header,
194                                       ArrayRef<Metadata *> DwarfOps,
195                                       StorageType Storage, bool ShouldCreate) {
196   unsigned Hash = 0;
197   if (Storage == Uniqued) {
198     GenericDINodeInfo::KeyTy Key(Tag, Header, DwarfOps);
199     if (auto *N = getUniqued(Context.pImpl->GenericDINodes, Key))
200       return N;
201     if (!ShouldCreate)
202       return nullptr;
203     Hash = Key.getHash();
204   } else {
205     assert(ShouldCreate && "Expected non-uniqued nodes to always be created");
206   }
207 
208   // Use a nullptr for empty headers.
209   assert(isCanonical(Header) && "Expected canonical MDString");
210   Metadata *PreOps[] = {Header};
211   return storeImpl(new (DwarfOps.size() + 1) GenericDINode(
212                        Context, Storage, Hash, Tag, PreOps, DwarfOps),
213                    Storage, Context.pImpl->GenericDINodes);
214 }
215 
216 void GenericDINode::recalculateHash() {
217   setHash(GenericDINodeInfo::KeyTy::calculateHash(this));
218 }
219 
220 #define UNWRAP_ARGS_IMPL(...) __VA_ARGS__
221 #define UNWRAP_ARGS(ARGS) UNWRAP_ARGS_IMPL ARGS
222 #define DEFINE_GETIMPL_LOOKUP(CLASS, ARGS)                                     \
223   do {                                                                         \
224     if (Storage == Uniqued) {                                                  \
225       if (auto *N = getUniqued(Context.pImpl->CLASS##s,                        \
226                                CLASS##Info::KeyTy(UNWRAP_ARGS(ARGS))))         \
227         return N;                                                              \
228       if (!ShouldCreate)                                                       \
229         return nullptr;                                                        \
230     } else {                                                                   \
231       assert(ShouldCreate &&                                                   \
232              "Expected non-uniqued nodes to always be created");               \
233     }                                                                          \
234   } while (false)
235 #define DEFINE_GETIMPL_STORE(CLASS, ARGS, OPS)                                 \
236   return storeImpl(new (array_lengthof(OPS))                                   \
237                        CLASS(Context, Storage, UNWRAP_ARGS(ARGS), OPS),        \
238                    Storage, Context.pImpl->CLASS##s)
239 #define DEFINE_GETIMPL_STORE_NO_OPS(CLASS, ARGS)                               \
240   return storeImpl(new (0u) CLASS(Context, Storage, UNWRAP_ARGS(ARGS)),        \
241                    Storage, Context.pImpl->CLASS##s)
242 #define DEFINE_GETIMPL_STORE_NO_CONSTRUCTOR_ARGS(CLASS, OPS)                   \
243   return storeImpl(new (array_lengthof(OPS)) CLASS(Context, Storage, OPS),     \
244                    Storage, Context.pImpl->CLASS##s)
245 #define DEFINE_GETIMPL_STORE_N(CLASS, ARGS, OPS, NUM_OPS)                      \
246   return storeImpl(new (NUM_OPS)                                               \
247                        CLASS(Context, Storage, UNWRAP_ARGS(ARGS), OPS),        \
248                    Storage, Context.pImpl->CLASS##s)
249 
250 DISubrange *DISubrange::getImpl(LLVMContext &Context, int64_t Count, int64_t Lo,
251                                 StorageType Storage, bool ShouldCreate) {
252   auto *CountNode = ConstantAsMetadata::get(
253       ConstantInt::getSigned(Type::getInt64Ty(Context), Count));
254   return getImpl(Context, CountNode, Lo, Storage, ShouldCreate);
255 }
256 
257 DISubrange *DISubrange::getImpl(LLVMContext &Context, Metadata *CountNode,
258                                 int64_t Lo, StorageType Storage,
259                                 bool ShouldCreate) {
260   DEFINE_GETIMPL_LOOKUP(DISubrange, (CountNode, Lo));
261   Metadata *Ops[] = { CountNode };
262   DEFINE_GETIMPL_STORE(DISubrange, (CountNode, Lo), Ops);
263 }
264 
265 DIEnumerator *DIEnumerator::getImpl(LLVMContext &Context, int64_t Value,
266                                     MDString *Name, StorageType Storage,
267                                     bool ShouldCreate) {
268   assert(isCanonical(Name) && "Expected canonical MDString");
269   DEFINE_GETIMPL_LOOKUP(DIEnumerator, (Value, Name));
270   Metadata *Ops[] = {Name};
271   DEFINE_GETIMPL_STORE(DIEnumerator, (Value), Ops);
272 }
273 
274 DIBasicType *DIBasicType::getImpl(LLVMContext &Context, unsigned Tag,
275                                   MDString *Name, uint64_t SizeInBits,
276                                   uint32_t AlignInBits, unsigned Encoding,
277                                   StorageType Storage, bool ShouldCreate) {
278   assert(isCanonical(Name) && "Expected canonical MDString");
279   DEFINE_GETIMPL_LOOKUP(DIBasicType,
280                         (Tag, Name, SizeInBits, AlignInBits, Encoding));
281   Metadata *Ops[] = {nullptr, nullptr, Name};
282   DEFINE_GETIMPL_STORE(DIBasicType, (Tag, SizeInBits, AlignInBits, Encoding),
283                        Ops);
284 }
285 
286 DIDerivedType *DIDerivedType::getImpl(
287     LLVMContext &Context, unsigned Tag, MDString *Name, Metadata *File,
288     unsigned Line, Metadata *Scope, Metadata *BaseType, uint64_t SizeInBits,
289     uint32_t AlignInBits, uint64_t OffsetInBits,
290     Optional<unsigned> DWARFAddressSpace, DIFlags Flags, Metadata *ExtraData,
291     StorageType Storage, bool ShouldCreate) {
292   assert(isCanonical(Name) && "Expected canonical MDString");
293   DEFINE_GETIMPL_LOOKUP(DIDerivedType,
294                         (Tag, Name, File, Line, Scope, BaseType, SizeInBits,
295                          AlignInBits, OffsetInBits, DWARFAddressSpace, Flags,
296                          ExtraData));
297   Metadata *Ops[] = {File, Scope, Name, BaseType, ExtraData};
298   DEFINE_GETIMPL_STORE(
299       DIDerivedType, (Tag, Line, SizeInBits, AlignInBits, OffsetInBits,
300                       DWARFAddressSpace, Flags), Ops);
301 }
302 
303 DICompositeType *DICompositeType::getImpl(
304     LLVMContext &Context, unsigned Tag, MDString *Name, Metadata *File,
305     unsigned Line, Metadata *Scope, Metadata *BaseType, uint64_t SizeInBits,
306     uint32_t AlignInBits, uint64_t OffsetInBits, DIFlags Flags,
307     Metadata *Elements, unsigned RuntimeLang, Metadata *VTableHolder,
308     Metadata *TemplateParams, MDString *Identifier, StorageType Storage,
309     bool ShouldCreate) {
310   assert(isCanonical(Name) && "Expected canonical MDString");
311 
312   // Keep this in sync with buildODRType.
313   DEFINE_GETIMPL_LOOKUP(
314       DICompositeType, (Tag, Name, File, Line, Scope, BaseType, SizeInBits,
315                         AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang,
316                         VTableHolder, TemplateParams, Identifier));
317   Metadata *Ops[] = {File,     Scope,        Name,           BaseType,
318                      Elements, VTableHolder, TemplateParams, Identifier};
319   DEFINE_GETIMPL_STORE(DICompositeType, (Tag, Line, RuntimeLang, SizeInBits,
320                                          AlignInBits, OffsetInBits, Flags),
321                        Ops);
322 }
323 
324 DICompositeType *DICompositeType::buildODRType(
325     LLVMContext &Context, MDString &Identifier, unsigned Tag, MDString *Name,
326     Metadata *File, unsigned Line, Metadata *Scope, Metadata *BaseType,
327     uint64_t SizeInBits, uint32_t AlignInBits, uint64_t OffsetInBits,
328     DIFlags Flags, Metadata *Elements, unsigned RuntimeLang,
329     Metadata *VTableHolder, Metadata *TemplateParams) {
330   assert(!Identifier.getString().empty() && "Expected valid identifier");
331   if (!Context.isODRUniquingDebugTypes())
332     return nullptr;
333   auto *&CT = (*Context.pImpl->DITypeMap)[&Identifier];
334   if (!CT)
335     return CT = DICompositeType::getDistinct(
336                Context, Tag, Name, File, Line, Scope, BaseType, SizeInBits,
337                AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang,
338                VTableHolder, TemplateParams, &Identifier);
339 
340   // Only mutate CT if it's a forward declaration and the new operands aren't.
341   assert(CT->getRawIdentifier() == &Identifier && "Wrong ODR identifier?");
342   if (!CT->isForwardDecl() || (Flags & DINode::FlagFwdDecl))
343     return CT;
344 
345   // Mutate CT in place.  Keep this in sync with getImpl.
346   CT->mutate(Tag, Line, RuntimeLang, SizeInBits, AlignInBits, OffsetInBits,
347              Flags);
348   Metadata *Ops[] = {File,     Scope,        Name,           BaseType,
349                      Elements, VTableHolder, TemplateParams, &Identifier};
350   assert((std::end(Ops) - std::begin(Ops)) == (int)CT->getNumOperands() &&
351          "Mismatched number of operands");
352   for (unsigned I = 0, E = CT->getNumOperands(); I != E; ++I)
353     if (Ops[I] != CT->getOperand(I))
354       CT->setOperand(I, Ops[I]);
355   return CT;
356 }
357 
358 DICompositeType *DICompositeType::getODRType(
359     LLVMContext &Context, MDString &Identifier, unsigned Tag, MDString *Name,
360     Metadata *File, unsigned Line, Metadata *Scope, Metadata *BaseType,
361     uint64_t SizeInBits, uint32_t AlignInBits, uint64_t OffsetInBits,
362     DIFlags Flags, Metadata *Elements, unsigned RuntimeLang,
363     Metadata *VTableHolder, Metadata *TemplateParams) {
364   assert(!Identifier.getString().empty() && "Expected valid identifier");
365   if (!Context.isODRUniquingDebugTypes())
366     return nullptr;
367   auto *&CT = (*Context.pImpl->DITypeMap)[&Identifier];
368   if (!CT)
369     CT = DICompositeType::getDistinct(
370         Context, Tag, Name, File, Line, Scope, BaseType, SizeInBits,
371         AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang, VTableHolder,
372         TemplateParams, &Identifier);
373   return CT;
374 }
375 
376 DICompositeType *DICompositeType::getODRTypeIfExists(LLVMContext &Context,
377                                                      MDString &Identifier) {
378   assert(!Identifier.getString().empty() && "Expected valid identifier");
379   if (!Context.isODRUniquingDebugTypes())
380     return nullptr;
381   return Context.pImpl->DITypeMap->lookup(&Identifier);
382 }
383 
384 DISubroutineType *DISubroutineType::getImpl(LLVMContext &Context, DIFlags Flags,
385                                             uint8_t CC, Metadata *TypeArray,
386                                             StorageType Storage,
387                                             bool ShouldCreate) {
388   DEFINE_GETIMPL_LOOKUP(DISubroutineType, (Flags, CC, TypeArray));
389   Metadata *Ops[] = {nullptr, nullptr, nullptr, TypeArray};
390   DEFINE_GETIMPL_STORE(DISubroutineType, (Flags, CC), Ops);
391 }
392 
393 // FIXME: Implement this string-enum correspondence with a .def file and macros,
394 // so that the association is explicit rather than implied.
395 static const char *ChecksumKindName[DIFile::CSK_Last + 1] = {
396   "CSK_None",
397   "CSK_MD5",
398   "CSK_SHA1"
399 };
400 
401 DIFile::ChecksumKind DIFile::getChecksumKind(StringRef CSKindStr) {
402   return StringSwitch<DIFile::ChecksumKind>(CSKindStr)
403       .Case("CSK_MD5", DIFile::CSK_MD5)
404       .Case("CSK_SHA1", DIFile::CSK_SHA1)
405       .Default(DIFile::CSK_None);
406 }
407 
408 StringRef DIFile::getChecksumKindAsString() const {
409   assert(CSKind <= DIFile::CSK_Last && "Invalid checksum kind");
410   return ChecksumKindName[CSKind];
411 }
412 
413 DIFile *DIFile::getImpl(LLVMContext &Context, MDString *Filename,
414                         MDString *Directory, DIFile::ChecksumKind CSKind,
415                         MDString *Checksum, StorageType Storage,
416                         bool ShouldCreate) {
417   assert(isCanonical(Filename) && "Expected canonical MDString");
418   assert(isCanonical(Directory) && "Expected canonical MDString");
419   assert(isCanonical(Checksum) && "Expected canonical MDString");
420   DEFINE_GETIMPL_LOOKUP(DIFile, (Filename, Directory, CSKind, Checksum));
421   Metadata *Ops[] = {Filename, Directory, Checksum};
422   DEFINE_GETIMPL_STORE(DIFile, (CSKind), Ops);
423 }
424 
425 DICompileUnit *DICompileUnit::getImpl(
426     LLVMContext &Context, unsigned SourceLanguage, Metadata *File,
427     MDString *Producer, bool IsOptimized, MDString *Flags,
428     unsigned RuntimeVersion, MDString *SplitDebugFilename,
429     unsigned EmissionKind, Metadata *EnumTypes, Metadata *RetainedTypes,
430     Metadata *GlobalVariables, Metadata *ImportedEntities, Metadata *Macros,
431     uint64_t DWOId, bool SplitDebugInlining, bool DebugInfoForProfiling,
432     bool GnuPubnames, StorageType Storage, bool ShouldCreate) {
433   assert(Storage != Uniqued && "Cannot unique DICompileUnit");
434   assert(isCanonical(Producer) && "Expected canonical MDString");
435   assert(isCanonical(Flags) && "Expected canonical MDString");
436   assert(isCanonical(SplitDebugFilename) && "Expected canonical MDString");
437 
438   Metadata *Ops[] = {
439       File,      Producer,      Flags,           SplitDebugFilename,
440       EnumTypes, RetainedTypes, GlobalVariables, ImportedEntities,
441       Macros};
442   return storeImpl(new (array_lengthof(Ops)) DICompileUnit(
443                        Context, Storage, SourceLanguage, IsOptimized,
444                        RuntimeVersion, EmissionKind, DWOId, SplitDebugInlining,
445                        DebugInfoForProfiling, GnuPubnames, Ops),
446                    Storage);
447 }
448 
449 Optional<DICompileUnit::DebugEmissionKind>
450 DICompileUnit::getEmissionKind(StringRef Str) {
451   return StringSwitch<Optional<DebugEmissionKind>>(Str)
452       .Case("NoDebug", NoDebug)
453       .Case("FullDebug", FullDebug)
454       .Case("LineTablesOnly", LineTablesOnly)
455       .Default(None);
456 }
457 
458 const char *DICompileUnit::EmissionKindString(DebugEmissionKind EK) {
459   switch (EK) {
460   case NoDebug:        return "NoDebug";
461   case FullDebug:      return "FullDebug";
462   case LineTablesOnly: return "LineTablesOnly";
463   }
464   return nullptr;
465 }
466 
467 DISubprogram *DILocalScope::getSubprogram() const {
468   if (auto *Block = dyn_cast<DILexicalBlockBase>(this))
469     return Block->getScope()->getSubprogram();
470   return const_cast<DISubprogram *>(cast<DISubprogram>(this));
471 }
472 
473 DILocalScope *DILocalScope::getNonLexicalBlockFileScope() const {
474   if (auto *File = dyn_cast<DILexicalBlockFile>(this))
475     return File->getScope()->getNonLexicalBlockFileScope();
476   return const_cast<DILocalScope *>(this);
477 }
478 
479 DISubprogram *DISubprogram::getImpl(
480     LLVMContext &Context, Metadata *Scope, MDString *Name,
481     MDString *LinkageName, Metadata *File, unsigned Line, Metadata *Type,
482     bool IsLocalToUnit, bool IsDefinition, unsigned ScopeLine,
483     Metadata *ContainingType, unsigned Virtuality, unsigned VirtualIndex,
484     int ThisAdjustment, DIFlags Flags, bool IsOptimized, Metadata *Unit,
485     Metadata *TemplateParams, Metadata *Declaration, Metadata *Variables,
486     Metadata *ThrownTypes, StorageType Storage, bool ShouldCreate) {
487   assert(isCanonical(Name) && "Expected canonical MDString");
488   assert(isCanonical(LinkageName) && "Expected canonical MDString");
489   DEFINE_GETIMPL_LOOKUP(
490       DISubprogram, (Scope, Name, LinkageName, File, Line, Type, IsLocalToUnit,
491                      IsDefinition, ScopeLine, ContainingType, Virtuality,
492                      VirtualIndex, ThisAdjustment, Flags, IsOptimized, Unit,
493                      TemplateParams, Declaration, Variables, ThrownTypes));
494   SmallVector<Metadata *, 11> Ops = {
495       File,        Scope,     Name,           LinkageName,    Type,       Unit,
496       Declaration, Variables, ContainingType, TemplateParams, ThrownTypes};
497   if (!ThrownTypes) {
498     Ops.pop_back();
499     if (!TemplateParams) {
500       Ops.pop_back();
501       if (!ContainingType)
502         Ops.pop_back();
503     }
504   }
505   DEFINE_GETIMPL_STORE_N(DISubprogram,
506                          (Line, ScopeLine, Virtuality, VirtualIndex,
507                           ThisAdjustment, Flags, IsLocalToUnit, IsDefinition,
508                           IsOptimized),
509                          Ops, Ops.size());
510 }
511 
512 bool DISubprogram::describes(const Function *F) const {
513   assert(F && "Invalid function");
514   if (F->getSubprogram() == this)
515     return true;
516   StringRef Name = getLinkageName();
517   if (Name.empty())
518     Name = getName();
519   return F->getName() == Name;
520 }
521 
522 DILexicalBlock *DILexicalBlock::getImpl(LLVMContext &Context, Metadata *Scope,
523                                         Metadata *File, unsigned Line,
524                                         unsigned Column, StorageType Storage,
525                                         bool ShouldCreate) {
526   // Fixup column.
527   adjustColumn(Column);
528 
529   assert(Scope && "Expected scope");
530   DEFINE_GETIMPL_LOOKUP(DILexicalBlock, (Scope, File, Line, Column));
531   Metadata *Ops[] = {File, Scope};
532   DEFINE_GETIMPL_STORE(DILexicalBlock, (Line, Column), Ops);
533 }
534 
535 DILexicalBlockFile *DILexicalBlockFile::getImpl(LLVMContext &Context,
536                                                 Metadata *Scope, Metadata *File,
537                                                 unsigned Discriminator,
538                                                 StorageType Storage,
539                                                 bool ShouldCreate) {
540   assert(Scope && "Expected scope");
541   DEFINE_GETIMPL_LOOKUP(DILexicalBlockFile, (Scope, File, Discriminator));
542   Metadata *Ops[] = {File, Scope};
543   DEFINE_GETIMPL_STORE(DILexicalBlockFile, (Discriminator), Ops);
544 }
545 
546 DINamespace *DINamespace::getImpl(LLVMContext &Context, Metadata *Scope,
547                                   MDString *Name, bool ExportSymbols,
548                                   StorageType Storage, bool ShouldCreate) {
549   assert(isCanonical(Name) && "Expected canonical MDString");
550   DEFINE_GETIMPL_LOOKUP(DINamespace, (Scope, Name, ExportSymbols));
551   // The nullptr is for DIScope's File operand. This should be refactored.
552   Metadata *Ops[] = {nullptr, Scope, Name};
553   DEFINE_GETIMPL_STORE(DINamespace, (ExportSymbols), Ops);
554 }
555 
556 DIModule *DIModule::getImpl(LLVMContext &Context, Metadata *Scope,
557                             MDString *Name, MDString *ConfigurationMacros,
558                             MDString *IncludePath, MDString *ISysRoot,
559                             StorageType Storage, bool ShouldCreate) {
560   assert(isCanonical(Name) && "Expected canonical MDString");
561   DEFINE_GETIMPL_LOOKUP(
562       DIModule, (Scope, Name, ConfigurationMacros, IncludePath, ISysRoot));
563   Metadata *Ops[] = {Scope, Name, ConfigurationMacros, IncludePath, ISysRoot};
564   DEFINE_GETIMPL_STORE_NO_CONSTRUCTOR_ARGS(DIModule, Ops);
565 }
566 
567 DITemplateTypeParameter *DITemplateTypeParameter::getImpl(LLVMContext &Context,
568                                                           MDString *Name,
569                                                           Metadata *Type,
570                                                           StorageType Storage,
571                                                           bool ShouldCreate) {
572   assert(isCanonical(Name) && "Expected canonical MDString");
573   DEFINE_GETIMPL_LOOKUP(DITemplateTypeParameter, (Name, Type));
574   Metadata *Ops[] = {Name, Type};
575   DEFINE_GETIMPL_STORE_NO_CONSTRUCTOR_ARGS(DITemplateTypeParameter, Ops);
576 }
577 
578 DITemplateValueParameter *DITemplateValueParameter::getImpl(
579     LLVMContext &Context, unsigned Tag, MDString *Name, Metadata *Type,
580     Metadata *Value, StorageType Storage, bool ShouldCreate) {
581   assert(isCanonical(Name) && "Expected canonical MDString");
582   DEFINE_GETIMPL_LOOKUP(DITemplateValueParameter, (Tag, Name, Type, Value));
583   Metadata *Ops[] = {Name, Type, Value};
584   DEFINE_GETIMPL_STORE(DITemplateValueParameter, (Tag), Ops);
585 }
586 
587 DIGlobalVariable *
588 DIGlobalVariable::getImpl(LLVMContext &Context, Metadata *Scope, MDString *Name,
589                           MDString *LinkageName, Metadata *File, unsigned Line,
590                           Metadata *Type, bool IsLocalToUnit, bool IsDefinition,
591                           Metadata *StaticDataMemberDeclaration,
592                           uint32_t AlignInBits, StorageType Storage,
593                           bool ShouldCreate) {
594   assert(isCanonical(Name) && "Expected canonical MDString");
595   assert(isCanonical(LinkageName) && "Expected canonical MDString");
596   DEFINE_GETIMPL_LOOKUP(DIGlobalVariable,
597                         (Scope, Name, LinkageName, File, Line, Type,
598                          IsLocalToUnit, IsDefinition,
599                          StaticDataMemberDeclaration, AlignInBits));
600   Metadata *Ops[] = {
601       Scope, Name, File, Type, Name, LinkageName, StaticDataMemberDeclaration};
602   DEFINE_GETIMPL_STORE(DIGlobalVariable,
603                        (Line, IsLocalToUnit, IsDefinition, AlignInBits),
604                        Ops);
605 }
606 
607 DILocalVariable *DILocalVariable::getImpl(LLVMContext &Context, Metadata *Scope,
608                                           MDString *Name, Metadata *File,
609                                           unsigned Line, Metadata *Type,
610                                           unsigned Arg, DIFlags Flags,
611                                           uint32_t AlignInBits,
612                                           StorageType Storage,
613                                           bool ShouldCreate) {
614   // 64K ought to be enough for any frontend.
615   assert(Arg <= UINT16_MAX && "Expected argument number to fit in 16-bits");
616 
617   assert(Scope && "Expected scope");
618   assert(isCanonical(Name) && "Expected canonical MDString");
619   DEFINE_GETIMPL_LOOKUP(DILocalVariable,
620                         (Scope, Name, File, Line, Type, Arg, Flags,
621                          AlignInBits));
622   Metadata *Ops[] = {Scope, Name, File, Type};
623   DEFINE_GETIMPL_STORE(DILocalVariable, (Line, Arg, Flags, AlignInBits), Ops);
624 }
625 
626 Optional<uint64_t> DIVariable::getSizeInBits() const {
627   // This is used by the Verifier so be mindful of broken types.
628   const Metadata *RawType = getRawType();
629   while (RawType) {
630     // Try to get the size directly.
631     if (auto *T = dyn_cast<DIType>(RawType))
632       if (uint64_t Size = T->getSizeInBits())
633         return Size;
634 
635     if (auto *DT = dyn_cast<DIDerivedType>(RawType)) {
636       // Look at the base type.
637       RawType = DT->getRawBaseType();
638       continue;
639     }
640 
641     // Missing type or size.
642     break;
643   }
644 
645   // Fail gracefully.
646   return None;
647 }
648 
649 DIExpression *DIExpression::getImpl(LLVMContext &Context,
650                                     ArrayRef<uint64_t> Elements,
651                                     StorageType Storage, bool ShouldCreate) {
652   DEFINE_GETIMPL_LOOKUP(DIExpression, (Elements));
653   DEFINE_GETIMPL_STORE_NO_OPS(DIExpression, (Elements));
654 }
655 
656 unsigned DIExpression::ExprOperand::getSize() const {
657   switch (getOp()) {
658   case dwarf::DW_OP_LLVM_fragment:
659     return 3;
660   case dwarf::DW_OP_constu:
661   case dwarf::DW_OP_plus_uconst:
662     return 2;
663   default:
664     return 1;
665   }
666 }
667 
668 bool DIExpression::isValid() const {
669   for (auto I = expr_op_begin(), E = expr_op_end(); I != E; ++I) {
670     // Check that there's space for the operand.
671     if (I->get() + I->getSize() > E->get())
672       return false;
673 
674     // Check that the operand is valid.
675     switch (I->getOp()) {
676     default:
677       return false;
678     case dwarf::DW_OP_LLVM_fragment:
679       // A fragment operator must appear at the end.
680       return I->get() + I->getSize() == E->get();
681     case dwarf::DW_OP_stack_value: {
682       // Must be the last one or followed by a DW_OP_LLVM_fragment.
683       if (I->get() + I->getSize() == E->get())
684         break;
685       auto J = I;
686       if ((++J)->getOp() != dwarf::DW_OP_LLVM_fragment)
687         return false;
688       break;
689     }
690     case dwarf::DW_OP_swap: {
691       // Must be more than one implicit element on the stack.
692 
693       // FIXME: A better way to implement this would be to add a local variable
694       // that keeps track of the stack depth and introduce something like a
695       // DW_LLVM_OP_implicit_location as a placeholder for the location this
696       // DIExpression is attached to, or else pass the number of implicit stack
697       // elements into isValid.
698       if (getNumElements() == 1)
699         return false;
700       break;
701     }
702     case dwarf::DW_OP_constu:
703     case dwarf::DW_OP_plus_uconst:
704     case dwarf::DW_OP_plus:
705     case dwarf::DW_OP_minus:
706     case dwarf::DW_OP_mul:
707     case dwarf::DW_OP_deref:
708     case dwarf::DW_OP_xderef:
709       break;
710     }
711   }
712   return true;
713 }
714 
715 Optional<DIExpression::FragmentInfo>
716 DIExpression::getFragmentInfo(expr_op_iterator Start, expr_op_iterator End) {
717   for (auto I = Start; I != End; ++I)
718     if (I->getOp() == dwarf::DW_OP_LLVM_fragment) {
719       DIExpression::FragmentInfo Info = {I->getArg(1), I->getArg(0)};
720       return Info;
721     }
722   return None;
723 }
724 
725 void DIExpression::appendOffset(SmallVectorImpl<uint64_t> &Ops,
726                                 int64_t Offset) {
727   if (Offset > 0) {
728     Ops.push_back(dwarf::DW_OP_plus_uconst);
729     Ops.push_back(Offset);
730   } else if (Offset < 0) {
731     Ops.push_back(dwarf::DW_OP_constu);
732     Ops.push_back(-Offset);
733     Ops.push_back(dwarf::DW_OP_minus);
734   }
735 }
736 
737 bool DIExpression::extractIfOffset(int64_t &Offset) const {
738   if (getNumElements() == 0) {
739     Offset = 0;
740     return true;
741   }
742 
743   if (getNumElements() == 2 && Elements[0] == dwarf::DW_OP_plus_uconst) {
744     Offset = Elements[1];
745     return true;
746   }
747 
748   if (getNumElements() == 3 && Elements[0] == dwarf::DW_OP_constu) {
749     if (Elements[2] == dwarf::DW_OP_plus) {
750       Offset = Elements[1];
751       return true;
752     }
753     if (Elements[2] == dwarf::DW_OP_minus) {
754       Offset = -Elements[1];
755       return true;
756     }
757   }
758 
759   return false;
760 }
761 
762 DIExpression *DIExpression::prepend(const DIExpression *Expr, bool DerefBefore,
763                                     int64_t Offset, bool DerefAfter,
764                                     bool StackValue) {
765   SmallVector<uint64_t, 8> Ops;
766   if (DerefBefore)
767     Ops.push_back(dwarf::DW_OP_deref);
768 
769   appendOffset(Ops, Offset);
770   if (DerefAfter)
771     Ops.push_back(dwarf::DW_OP_deref);
772 
773   if (Expr)
774     for (auto Op : Expr->expr_ops()) {
775       // A DW_OP_stack_value comes at the end, but before a DW_OP_LLVM_fragment.
776       if (StackValue) {
777         if (Op.getOp() == dwarf::DW_OP_stack_value)
778           StackValue = false;
779         else if (Op.getOp() == dwarf::DW_OP_LLVM_fragment) {
780           Ops.push_back(dwarf::DW_OP_stack_value);
781           StackValue = false;
782         }
783       }
784       Ops.push_back(Op.getOp());
785       for (unsigned I = 0; I < Op.getNumArgs(); ++I)
786         Ops.push_back(Op.getArg(I));
787     }
788   if (StackValue)
789     Ops.push_back(dwarf::DW_OP_stack_value);
790   return DIExpression::get(Expr->getContext(), Ops);
791 }
792 
793 Optional<DIExpression *> DIExpression::createFragmentExpression(
794     const DIExpression *Expr, unsigned OffsetInBits, unsigned SizeInBits) {
795   SmallVector<uint64_t, 8> Ops;
796   // Copy over the expression, but leave off any trailing DW_OP_LLVM_fragment.
797   if (Expr) {
798     for (auto Op : Expr->expr_ops()) {
799       switch (Op.getOp()) {
800       default: break;
801       case dwarf::DW_OP_plus:
802       case dwarf::DW_OP_minus:
803         // We can't safely split arithmetic into multiple fragments because we
804         // can't express carry-over between fragments.
805         //
806         // FIXME: We *could* preserve the lowest fragment of a constant offset
807         // operation if the offset fits into SizeInBits.
808         return None;
809       case dwarf::DW_OP_LLVM_fragment: {
810         // Make the new offset point into the existing fragment.
811         uint64_t FragmentOffsetInBits = Op.getArg(0);
812         // Op.getArg(0) is FragmentOffsetInBits.
813         // Op.getArg(1) is FragmentSizeInBits.
814         assert((OffsetInBits + SizeInBits <= Op.getArg(0) + Op.getArg(1)) &&
815                "new fragment outside of original fragment");
816         OffsetInBits += FragmentOffsetInBits;
817         continue;
818       }
819       }
820       Ops.push_back(Op.getOp());
821       for (unsigned I = 0; I < Op.getNumArgs(); ++I)
822         Ops.push_back(Op.getArg(I));
823     }
824   }
825   Ops.push_back(dwarf::DW_OP_LLVM_fragment);
826   Ops.push_back(OffsetInBits);
827   Ops.push_back(SizeInBits);
828   return DIExpression::get(Expr->getContext(), Ops);
829 }
830 
831 bool DIExpression::isConstant() const {
832   // Recognize DW_OP_constu C DW_OP_stack_value (DW_OP_LLVM_fragment Len Ofs)?.
833   if (getNumElements() != 3 && getNumElements() != 6)
834     return false;
835   if (getElement(0) != dwarf::DW_OP_constu ||
836       getElement(2) != dwarf::DW_OP_stack_value)
837     return false;
838   if (getNumElements() == 6 && getElement(3) != dwarf::DW_OP_LLVM_fragment)
839     return false;
840   return true;
841 }
842 
843 DIGlobalVariableExpression *
844 DIGlobalVariableExpression::getImpl(LLVMContext &Context, Metadata *Variable,
845                                     Metadata *Expression, StorageType Storage,
846                                     bool ShouldCreate) {
847   DEFINE_GETIMPL_LOOKUP(DIGlobalVariableExpression, (Variable, Expression));
848   Metadata *Ops[] = {Variable, Expression};
849   DEFINE_GETIMPL_STORE_NO_CONSTRUCTOR_ARGS(DIGlobalVariableExpression, Ops);
850 }
851 
852 DIObjCProperty *DIObjCProperty::getImpl(
853     LLVMContext &Context, MDString *Name, Metadata *File, unsigned Line,
854     MDString *GetterName, MDString *SetterName, unsigned Attributes,
855     Metadata *Type, StorageType Storage, bool ShouldCreate) {
856   assert(isCanonical(Name) && "Expected canonical MDString");
857   assert(isCanonical(GetterName) && "Expected canonical MDString");
858   assert(isCanonical(SetterName) && "Expected canonical MDString");
859   DEFINE_GETIMPL_LOOKUP(DIObjCProperty, (Name, File, Line, GetterName,
860                                          SetterName, Attributes, Type));
861   Metadata *Ops[] = {Name, File, GetterName, SetterName, Type};
862   DEFINE_GETIMPL_STORE(DIObjCProperty, (Line, Attributes), Ops);
863 }
864 
865 DIImportedEntity *DIImportedEntity::getImpl(LLVMContext &Context, unsigned Tag,
866                                             Metadata *Scope, Metadata *Entity,
867                                             Metadata *File, unsigned Line,
868                                             MDString *Name, StorageType Storage,
869                                             bool ShouldCreate) {
870   assert(isCanonical(Name) && "Expected canonical MDString");
871   DEFINE_GETIMPL_LOOKUP(DIImportedEntity,
872                         (Tag, Scope, Entity, File, Line, Name));
873   Metadata *Ops[] = {Scope, Entity, Name, File};
874   DEFINE_GETIMPL_STORE(DIImportedEntity, (Tag, Line), Ops);
875 }
876 
877 DIMacro *DIMacro::getImpl(LLVMContext &Context, unsigned MIType,
878                           unsigned Line, MDString *Name, MDString *Value,
879                           StorageType Storage, bool ShouldCreate) {
880   assert(isCanonical(Name) && "Expected canonical MDString");
881   DEFINE_GETIMPL_LOOKUP(DIMacro, (MIType, Line, Name, Value));
882   Metadata *Ops[] = { Name, Value };
883   DEFINE_GETIMPL_STORE(DIMacro, (MIType, Line), Ops);
884 }
885 
886 DIMacroFile *DIMacroFile::getImpl(LLVMContext &Context, unsigned MIType,
887                                   unsigned Line, Metadata *File,
888                                   Metadata *Elements, StorageType Storage,
889                                   bool ShouldCreate) {
890   DEFINE_GETIMPL_LOOKUP(DIMacroFile,
891                         (MIType, Line, File, Elements));
892   Metadata *Ops[] = { File, Elements };
893   DEFINE_GETIMPL_STORE(DIMacroFile, (MIType, Line), Ops);
894 }
895 
896