1 //===- DebugInfoMetadata.cpp - Implement debug info metadata --------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the debug info Metadata classes.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "llvm/IR/DebugInfoMetadata.h"
14 #include "LLVMContextImpl.h"
15 #include "MetadataImpl.h"
16 #include "llvm/ADT/SmallSet.h"
17 #include "llvm/ADT/StringSwitch.h"
18 #include "llvm/IR/DIBuilder.h"
19 #include "llvm/IR/Function.h"
20 #include "llvm/IR/Instructions.h"
21 
22 #include <numeric>
23 
24 using namespace llvm;
25 
26 namespace llvm {
27 // Use FS-AFDO discriminator.
28 cl::opt<bool> EnableFSDiscriminator(
29     "enable-fs-discriminator", cl::Hidden, cl::init(false),
30     cl::desc("Enable adding flow sensitive discriminators"));
31 } // namespace llvm
32 
33 const DIExpression::FragmentInfo DebugVariable::DefaultFragment = {
34     std::numeric_limits<uint64_t>::max(), std::numeric_limits<uint64_t>::min()};
35 
36 DILocation::DILocation(LLVMContext &C, StorageType Storage, unsigned Line,
37                        unsigned Column, ArrayRef<Metadata *> MDs,
38                        bool ImplicitCode)
39     : MDNode(C, DILocationKind, Storage, MDs) {
40   assert((MDs.size() == 1 || MDs.size() == 2) &&
41          "Expected a scope and optional inlined-at");
42 
43   // Set line and column.
44   assert(Column < (1u << 16) && "Expected 16-bit column");
45 
46   SubclassData32 = Line;
47   SubclassData16 = Column;
48 
49   setImplicitCode(ImplicitCode);
50 }
51 
52 static void adjustColumn(unsigned &Column) {
53   // Set to unknown on overflow.  We only have 16 bits to play with here.
54   if (Column >= (1u << 16))
55     Column = 0;
56 }
57 
58 DILocation *DILocation::getImpl(LLVMContext &Context, unsigned Line,
59                                 unsigned Column, Metadata *Scope,
60                                 Metadata *InlinedAt, bool ImplicitCode,
61                                 StorageType Storage, bool ShouldCreate) {
62   // Fixup column.
63   adjustColumn(Column);
64 
65   if (Storage == Uniqued) {
66     if (auto *N = getUniqued(Context.pImpl->DILocations,
67                              DILocationInfo::KeyTy(Line, Column, Scope,
68                                                    InlinedAt, ImplicitCode)))
69       return N;
70     if (!ShouldCreate)
71       return nullptr;
72   } else {
73     assert(ShouldCreate && "Expected non-uniqued nodes to always be created");
74   }
75 
76   SmallVector<Metadata *, 2> Ops;
77   Ops.push_back(Scope);
78   if (InlinedAt)
79     Ops.push_back(InlinedAt);
80   return storeImpl(new (Ops.size()) DILocation(Context, Storage, Line, Column,
81                                                Ops, ImplicitCode),
82                    Storage, Context.pImpl->DILocations);
83 }
84 
85 const
86 DILocation *DILocation::getMergedLocations(ArrayRef<const DILocation *> Locs) {
87   if (Locs.empty())
88     return nullptr;
89   if (Locs.size() == 1)
90     return Locs[0];
91   auto *Merged = Locs[0];
92   for (const DILocation *L : llvm::drop_begin(Locs)) {
93     Merged = getMergedLocation(Merged, L);
94     if (Merged == nullptr)
95       break;
96   }
97   return Merged;
98 }
99 
100 const DILocation *DILocation::getMergedLocation(const DILocation *LocA,
101                                                 const DILocation *LocB) {
102   if (!LocA || !LocB)
103     return nullptr;
104 
105   if (LocA == LocB)
106     return LocA;
107 
108   SmallPtrSet<DILocation *, 5> InlinedLocationsA;
109   for (DILocation *L = LocA->getInlinedAt(); L; L = L->getInlinedAt())
110     InlinedLocationsA.insert(L);
111   SmallSet<std::pair<DIScope *, DILocation *>, 5> Locations;
112   DIScope *S = LocA->getScope();
113   DILocation *L = LocA->getInlinedAt();
114   while (S) {
115     Locations.insert(std::make_pair(S, L));
116     S = S->getScope();
117     if (!S && L) {
118       S = L->getScope();
119       L = L->getInlinedAt();
120     }
121   }
122   const DILocation *Result = LocB;
123   S = LocB->getScope();
124   L = LocB->getInlinedAt();
125   while (S) {
126     if (Locations.count(std::make_pair(S, L)))
127       break;
128     S = S->getScope();
129     if (!S && L) {
130       S = L->getScope();
131       L = L->getInlinedAt();
132     }
133   }
134 
135   // If the two locations are irreconsilable, just pick one. This is misleading,
136   // but on the other hand, it's a "line 0" location.
137   if (!S || !isa<DILocalScope>(S))
138     S = LocA->getScope();
139   return DILocation::get(Result->getContext(), 0, 0, S, L);
140 }
141 
142 Optional<unsigned> DILocation::encodeDiscriminator(unsigned BD, unsigned DF, unsigned CI) {
143   std::array<unsigned, 3> Components = {BD, DF, CI};
144   uint64_t RemainingWork = 0U;
145   // We use RemainingWork to figure out if we have no remaining components to
146   // encode. For example: if BD != 0 but DF == 0 && CI == 0, we don't need to
147   // encode anything for the latter 2.
148   // Since any of the input components is at most 32 bits, their sum will be
149   // less than 34 bits, and thus RemainingWork won't overflow.
150   RemainingWork = std::accumulate(Components.begin(), Components.end(), RemainingWork);
151 
152   int I = 0;
153   unsigned Ret = 0;
154   unsigned NextBitInsertionIndex = 0;
155   while (RemainingWork > 0) {
156     unsigned C = Components[I++];
157     RemainingWork -= C;
158     unsigned EC = encodeComponent(C);
159     Ret |= (EC << NextBitInsertionIndex);
160     NextBitInsertionIndex += encodingBits(C);
161   }
162 
163   // Encoding may be unsuccessful because of overflow. We determine success by
164   // checking equivalence of components before & after encoding. Alternatively,
165   // we could determine Success during encoding, but the current alternative is
166   // simpler.
167   unsigned TBD, TDF, TCI = 0;
168   decodeDiscriminator(Ret, TBD, TDF, TCI);
169   if (TBD == BD && TDF == DF && TCI == CI)
170     return Ret;
171   return None;
172 }
173 
174 void DILocation::decodeDiscriminator(unsigned D, unsigned &BD, unsigned &DF,
175                                      unsigned &CI) {
176   BD = getUnsignedFromPrefixEncoding(D);
177   DF = getUnsignedFromPrefixEncoding(getNextComponentInDiscriminator(D));
178   CI = getUnsignedFromPrefixEncoding(
179       getNextComponentInDiscriminator(getNextComponentInDiscriminator(D)));
180 }
181 
182 
183 DINode::DIFlags DINode::getFlag(StringRef Flag) {
184   return StringSwitch<DIFlags>(Flag)
185 #define HANDLE_DI_FLAG(ID, NAME) .Case("DIFlag" #NAME, Flag##NAME)
186 #include "llvm/IR/DebugInfoFlags.def"
187       .Default(DINode::FlagZero);
188 }
189 
190 StringRef DINode::getFlagString(DIFlags Flag) {
191   switch (Flag) {
192 #define HANDLE_DI_FLAG(ID, NAME)                                               \
193   case Flag##NAME:                                                             \
194     return "DIFlag" #NAME;
195 #include "llvm/IR/DebugInfoFlags.def"
196   }
197   return "";
198 }
199 
200 DINode::DIFlags DINode::splitFlags(DIFlags Flags,
201                                    SmallVectorImpl<DIFlags> &SplitFlags) {
202   // Flags that are packed together need to be specially handled, so
203   // that, for example, we emit "DIFlagPublic" and not
204   // "DIFlagPrivate | DIFlagProtected".
205   if (DIFlags A = Flags & FlagAccessibility) {
206     if (A == FlagPrivate)
207       SplitFlags.push_back(FlagPrivate);
208     else if (A == FlagProtected)
209       SplitFlags.push_back(FlagProtected);
210     else
211       SplitFlags.push_back(FlagPublic);
212     Flags &= ~A;
213   }
214   if (DIFlags R = Flags & FlagPtrToMemberRep) {
215     if (R == FlagSingleInheritance)
216       SplitFlags.push_back(FlagSingleInheritance);
217     else if (R == FlagMultipleInheritance)
218       SplitFlags.push_back(FlagMultipleInheritance);
219     else
220       SplitFlags.push_back(FlagVirtualInheritance);
221     Flags &= ~R;
222   }
223   if ((Flags & FlagIndirectVirtualBase) == FlagIndirectVirtualBase) {
224     Flags &= ~FlagIndirectVirtualBase;
225     SplitFlags.push_back(FlagIndirectVirtualBase);
226   }
227 
228 #define HANDLE_DI_FLAG(ID, NAME)                                               \
229   if (DIFlags Bit = Flags & Flag##NAME) {                                      \
230     SplitFlags.push_back(Bit);                                                 \
231     Flags &= ~Bit;                                                             \
232   }
233 #include "llvm/IR/DebugInfoFlags.def"
234   return Flags;
235 }
236 
237 DIScope *DIScope::getScope() const {
238   if (auto *T = dyn_cast<DIType>(this))
239     return T->getScope();
240 
241   if (auto *SP = dyn_cast<DISubprogram>(this))
242     return SP->getScope();
243 
244   if (auto *LB = dyn_cast<DILexicalBlockBase>(this))
245     return LB->getScope();
246 
247   if (auto *NS = dyn_cast<DINamespace>(this))
248     return NS->getScope();
249 
250   if (auto *CB = dyn_cast<DICommonBlock>(this))
251     return CB->getScope();
252 
253   if (auto *M = dyn_cast<DIModule>(this))
254     return M->getScope();
255 
256   assert((isa<DIFile>(this) || isa<DICompileUnit>(this)) &&
257          "Unhandled type of scope.");
258   return nullptr;
259 }
260 
261 StringRef DIScope::getName() const {
262   if (auto *T = dyn_cast<DIType>(this))
263     return T->getName();
264   if (auto *SP = dyn_cast<DISubprogram>(this))
265     return SP->getName();
266   if (auto *NS = dyn_cast<DINamespace>(this))
267     return NS->getName();
268   if (auto *CB = dyn_cast<DICommonBlock>(this))
269     return CB->getName();
270   if (auto *M = dyn_cast<DIModule>(this))
271     return M->getName();
272   assert((isa<DILexicalBlockBase>(this) || isa<DIFile>(this) ||
273           isa<DICompileUnit>(this)) &&
274          "Unhandled type of scope.");
275   return "";
276 }
277 
278 #ifndef NDEBUG
279 static bool isCanonical(const MDString *S) {
280   return !S || !S->getString().empty();
281 }
282 #endif
283 
284 GenericDINode *GenericDINode::getImpl(LLVMContext &Context, unsigned Tag,
285                                       MDString *Header,
286                                       ArrayRef<Metadata *> DwarfOps,
287                                       StorageType Storage, bool ShouldCreate) {
288   unsigned Hash = 0;
289   if (Storage == Uniqued) {
290     GenericDINodeInfo::KeyTy Key(Tag, Header, DwarfOps);
291     if (auto *N = getUniqued(Context.pImpl->GenericDINodes, Key))
292       return N;
293     if (!ShouldCreate)
294       return nullptr;
295     Hash = Key.getHash();
296   } else {
297     assert(ShouldCreate && "Expected non-uniqued nodes to always be created");
298   }
299 
300   // Use a nullptr for empty headers.
301   assert(isCanonical(Header) && "Expected canonical MDString");
302   Metadata *PreOps[] = {Header};
303   return storeImpl(new (DwarfOps.size() + 1) GenericDINode(
304                        Context, Storage, Hash, Tag, PreOps, DwarfOps),
305                    Storage, Context.pImpl->GenericDINodes);
306 }
307 
308 void GenericDINode::recalculateHash() {
309   setHash(GenericDINodeInfo::KeyTy::calculateHash(this));
310 }
311 
312 #define UNWRAP_ARGS_IMPL(...) __VA_ARGS__
313 #define UNWRAP_ARGS(ARGS) UNWRAP_ARGS_IMPL ARGS
314 #define DEFINE_GETIMPL_LOOKUP(CLASS, ARGS)                                     \
315   do {                                                                         \
316     if (Storage == Uniqued) {                                                  \
317       if (auto *N = getUniqued(Context.pImpl->CLASS##s,                        \
318                                CLASS##Info::KeyTy(UNWRAP_ARGS(ARGS))))         \
319         return N;                                                              \
320       if (!ShouldCreate)                                                       \
321         return nullptr;                                                        \
322     } else {                                                                   \
323       assert(ShouldCreate &&                                                   \
324              "Expected non-uniqued nodes to always be created");               \
325     }                                                                          \
326   } while (false)
327 #define DEFINE_GETIMPL_STORE(CLASS, ARGS, OPS)                                 \
328   return storeImpl(new (array_lengthof(OPS))                                   \
329                        CLASS(Context, Storage, UNWRAP_ARGS(ARGS), OPS),        \
330                    Storage, Context.pImpl->CLASS##s)
331 #define DEFINE_GETIMPL_STORE_NO_OPS(CLASS, ARGS)                               \
332   return storeImpl(new (0u) CLASS(Context, Storage, UNWRAP_ARGS(ARGS)),        \
333                    Storage, Context.pImpl->CLASS##s)
334 #define DEFINE_GETIMPL_STORE_NO_CONSTRUCTOR_ARGS(CLASS, OPS)                   \
335   return storeImpl(new (array_lengthof(OPS)) CLASS(Context, Storage, OPS),     \
336                    Storage, Context.pImpl->CLASS##s)
337 #define DEFINE_GETIMPL_STORE_N(CLASS, ARGS, OPS, NUM_OPS)                      \
338   return storeImpl(new (NUM_OPS)                                               \
339                        CLASS(Context, Storage, UNWRAP_ARGS(ARGS), OPS),        \
340                    Storage, Context.pImpl->CLASS##s)
341 
342 DISubrange *DISubrange::getImpl(LLVMContext &Context, int64_t Count, int64_t Lo,
343                                 StorageType Storage, bool ShouldCreate) {
344   auto *CountNode = ConstantAsMetadata::get(
345       ConstantInt::getSigned(Type::getInt64Ty(Context), Count));
346   auto *LB = ConstantAsMetadata::get(
347       ConstantInt::getSigned(Type::getInt64Ty(Context), Lo));
348   return getImpl(Context, CountNode, LB, nullptr, nullptr, Storage,
349                  ShouldCreate);
350 }
351 
352 DISubrange *DISubrange::getImpl(LLVMContext &Context, Metadata *CountNode,
353                                 int64_t Lo, StorageType Storage,
354                                 bool ShouldCreate) {
355   auto *LB = ConstantAsMetadata::get(
356       ConstantInt::getSigned(Type::getInt64Ty(Context), Lo));
357   return getImpl(Context, CountNode, LB, nullptr, nullptr, Storage,
358                  ShouldCreate);
359 }
360 
361 DISubrange *DISubrange::getImpl(LLVMContext &Context, Metadata *CountNode,
362                                 Metadata *LB, Metadata *UB, Metadata *Stride,
363                                 StorageType Storage, bool ShouldCreate) {
364   DEFINE_GETIMPL_LOOKUP(DISubrange, (CountNode, LB, UB, Stride));
365   Metadata *Ops[] = {CountNode, LB, UB, Stride};
366   DEFINE_GETIMPL_STORE_NO_CONSTRUCTOR_ARGS(DISubrange, Ops);
367 }
368 
369 DISubrange::BoundType DISubrange::getCount() const {
370   Metadata *CB = getRawCountNode();
371   if (!CB)
372     return BoundType();
373 
374   assert((isa<ConstantAsMetadata>(CB) || isa<DIVariable>(CB) ||
375           isa<DIExpression>(CB)) &&
376          "Count must be signed constant or DIVariable or DIExpression");
377 
378   if (auto *MD = dyn_cast<ConstantAsMetadata>(CB))
379     return BoundType(cast<ConstantInt>(MD->getValue()));
380 
381   if (auto *MD = dyn_cast<DIVariable>(CB))
382     return BoundType(MD);
383 
384   if (auto *MD = dyn_cast<DIExpression>(CB))
385     return BoundType(MD);
386 
387   return BoundType();
388 }
389 
390 DISubrange::BoundType DISubrange::getLowerBound() const {
391   Metadata *LB = getRawLowerBound();
392   if (!LB)
393     return BoundType();
394 
395   assert((isa<ConstantAsMetadata>(LB) || isa<DIVariable>(LB) ||
396           isa<DIExpression>(LB)) &&
397          "LowerBound must be signed constant or DIVariable or DIExpression");
398 
399   if (auto *MD = dyn_cast<ConstantAsMetadata>(LB))
400     return BoundType(cast<ConstantInt>(MD->getValue()));
401 
402   if (auto *MD = dyn_cast<DIVariable>(LB))
403     return BoundType(MD);
404 
405   if (auto *MD = dyn_cast<DIExpression>(LB))
406     return BoundType(MD);
407 
408   return BoundType();
409 }
410 
411 DISubrange::BoundType DISubrange::getUpperBound() const {
412   Metadata *UB = getRawUpperBound();
413   if (!UB)
414     return BoundType();
415 
416   assert((isa<ConstantAsMetadata>(UB) || isa<DIVariable>(UB) ||
417           isa<DIExpression>(UB)) &&
418          "UpperBound must be signed constant or DIVariable or DIExpression");
419 
420   if (auto *MD = dyn_cast<ConstantAsMetadata>(UB))
421     return BoundType(cast<ConstantInt>(MD->getValue()));
422 
423   if (auto *MD = dyn_cast<DIVariable>(UB))
424     return BoundType(MD);
425 
426   if (auto *MD = dyn_cast<DIExpression>(UB))
427     return BoundType(MD);
428 
429   return BoundType();
430 }
431 
432 DISubrange::BoundType DISubrange::getStride() const {
433   Metadata *ST = getRawStride();
434   if (!ST)
435     return BoundType();
436 
437   assert((isa<ConstantAsMetadata>(ST) || isa<DIVariable>(ST) ||
438           isa<DIExpression>(ST)) &&
439          "Stride must be signed constant or DIVariable or DIExpression");
440 
441   if (auto *MD = dyn_cast<ConstantAsMetadata>(ST))
442     return BoundType(cast<ConstantInt>(MD->getValue()));
443 
444   if (auto *MD = dyn_cast<DIVariable>(ST))
445     return BoundType(MD);
446 
447   if (auto *MD = dyn_cast<DIExpression>(ST))
448     return BoundType(MD);
449 
450   return BoundType();
451 }
452 
453 DIGenericSubrange *DIGenericSubrange::getImpl(LLVMContext &Context,
454                                               Metadata *CountNode, Metadata *LB,
455                                               Metadata *UB, Metadata *Stride,
456                                               StorageType Storage,
457                                               bool ShouldCreate) {
458   DEFINE_GETIMPL_LOOKUP(DIGenericSubrange, (CountNode, LB, UB, Stride));
459   Metadata *Ops[] = {CountNode, LB, UB, Stride};
460   DEFINE_GETIMPL_STORE_NO_CONSTRUCTOR_ARGS(DIGenericSubrange, Ops);
461 }
462 
463 DIGenericSubrange::BoundType DIGenericSubrange::getCount() const {
464   Metadata *CB = getRawCountNode();
465   if (!CB)
466     return BoundType();
467 
468   assert((isa<DIVariable>(CB) || isa<DIExpression>(CB)) &&
469          "Count must be signed constant or DIVariable or DIExpression");
470 
471   if (auto *MD = dyn_cast<DIVariable>(CB))
472     return BoundType(MD);
473 
474   if (auto *MD = dyn_cast<DIExpression>(CB))
475     return BoundType(MD);
476 
477   return BoundType();
478 }
479 
480 DIGenericSubrange::BoundType DIGenericSubrange::getLowerBound() const {
481   Metadata *LB = getRawLowerBound();
482   if (!LB)
483     return BoundType();
484 
485   assert((isa<DIVariable>(LB) || isa<DIExpression>(LB)) &&
486          "LowerBound must be signed constant or DIVariable or DIExpression");
487 
488   if (auto *MD = dyn_cast<DIVariable>(LB))
489     return BoundType(MD);
490 
491   if (auto *MD = dyn_cast<DIExpression>(LB))
492     return BoundType(MD);
493 
494   return BoundType();
495 }
496 
497 DIGenericSubrange::BoundType DIGenericSubrange::getUpperBound() const {
498   Metadata *UB = getRawUpperBound();
499   if (!UB)
500     return BoundType();
501 
502   assert((isa<DIVariable>(UB) || isa<DIExpression>(UB)) &&
503          "UpperBound must be signed constant or DIVariable or DIExpression");
504 
505   if (auto *MD = dyn_cast<DIVariable>(UB))
506     return BoundType(MD);
507 
508   if (auto *MD = dyn_cast<DIExpression>(UB))
509     return BoundType(MD);
510 
511   return BoundType();
512 }
513 
514 DIGenericSubrange::BoundType DIGenericSubrange::getStride() const {
515   Metadata *ST = getRawStride();
516   if (!ST)
517     return BoundType();
518 
519   assert((isa<DIVariable>(ST) || isa<DIExpression>(ST)) &&
520          "Stride must be signed constant or DIVariable or DIExpression");
521 
522   if (auto *MD = dyn_cast<DIVariable>(ST))
523     return BoundType(MD);
524 
525   if (auto *MD = dyn_cast<DIExpression>(ST))
526     return BoundType(MD);
527 
528   return BoundType();
529 }
530 
531 DIEnumerator *DIEnumerator::getImpl(LLVMContext &Context, const APInt &Value,
532                                     bool IsUnsigned, MDString *Name,
533                                     StorageType Storage, bool ShouldCreate) {
534   assert(isCanonical(Name) && "Expected canonical MDString");
535   DEFINE_GETIMPL_LOOKUP(DIEnumerator, (Value, IsUnsigned, Name));
536   Metadata *Ops[] = {Name};
537   DEFINE_GETIMPL_STORE(DIEnumerator, (Value, IsUnsigned), Ops);
538 }
539 
540 DIBasicType *DIBasicType::getImpl(LLVMContext &Context, unsigned Tag,
541                                   MDString *Name, uint64_t SizeInBits,
542                                   uint32_t AlignInBits, unsigned Encoding,
543                                   DIFlags Flags, StorageType Storage,
544                                   bool ShouldCreate) {
545   assert(isCanonical(Name) && "Expected canonical MDString");
546   DEFINE_GETIMPL_LOOKUP(DIBasicType,
547                         (Tag, Name, SizeInBits, AlignInBits, Encoding, Flags));
548   Metadata *Ops[] = {nullptr, nullptr, Name};
549   DEFINE_GETIMPL_STORE(DIBasicType, (Tag, SizeInBits, AlignInBits, Encoding,
550                       Flags), Ops);
551 }
552 
553 Optional<DIBasicType::Signedness> DIBasicType::getSignedness() const {
554   switch (getEncoding()) {
555   case dwarf::DW_ATE_signed:
556   case dwarf::DW_ATE_signed_char:
557     return Signedness::Signed;
558   case dwarf::DW_ATE_unsigned:
559   case dwarf::DW_ATE_unsigned_char:
560     return Signedness::Unsigned;
561   default:
562     return None;
563   }
564 }
565 
566 DIStringType *DIStringType::getImpl(LLVMContext &Context, unsigned Tag,
567                                     MDString *Name, Metadata *StringLength,
568                                     Metadata *StringLengthExp,
569                                     uint64_t SizeInBits, uint32_t AlignInBits,
570                                     unsigned Encoding, StorageType Storage,
571                                     bool ShouldCreate) {
572   assert(isCanonical(Name) && "Expected canonical MDString");
573   DEFINE_GETIMPL_LOOKUP(DIStringType, (Tag, Name, StringLength, StringLengthExp,
574                                        SizeInBits, AlignInBits, Encoding));
575   Metadata *Ops[] = {nullptr, nullptr, Name, StringLength, StringLengthExp};
576   DEFINE_GETIMPL_STORE(DIStringType, (Tag, SizeInBits, AlignInBits, Encoding),
577                        Ops);
578 }
579 
580 DIDerivedType *DIDerivedType::getImpl(
581     LLVMContext &Context, unsigned Tag, MDString *Name, Metadata *File,
582     unsigned Line, Metadata *Scope, Metadata *BaseType, uint64_t SizeInBits,
583     uint32_t AlignInBits, uint64_t OffsetInBits,
584     Optional<unsigned> DWARFAddressSpace, DIFlags Flags, Metadata *ExtraData,
585     Metadata *Annotations, StorageType Storage, bool ShouldCreate) {
586   assert(isCanonical(Name) && "Expected canonical MDString");
587   DEFINE_GETIMPL_LOOKUP(DIDerivedType,
588                         (Tag, Name, File, Line, Scope, BaseType, SizeInBits,
589                          AlignInBits, OffsetInBits, DWARFAddressSpace, Flags,
590                          ExtraData, Annotations));
591   Metadata *Ops[] = {File, Scope, Name, BaseType, ExtraData, Annotations};
592   DEFINE_GETIMPL_STORE(
593       DIDerivedType, (Tag, Line, SizeInBits, AlignInBits, OffsetInBits,
594                       DWARFAddressSpace, Flags), Ops);
595 }
596 
597 DICompositeType *DICompositeType::getImpl(
598     LLVMContext &Context, unsigned Tag, MDString *Name, Metadata *File,
599     unsigned Line, Metadata *Scope, Metadata *BaseType, uint64_t SizeInBits,
600     uint32_t AlignInBits, uint64_t OffsetInBits, DIFlags Flags,
601     Metadata *Elements, unsigned RuntimeLang, Metadata *VTableHolder,
602     Metadata *TemplateParams, MDString *Identifier, Metadata *Discriminator,
603     Metadata *DataLocation, Metadata *Associated, Metadata *Allocated,
604     Metadata *Rank, Metadata *Annotations, StorageType Storage,
605     bool ShouldCreate) {
606   assert(isCanonical(Name) && "Expected canonical MDString");
607 
608   // Keep this in sync with buildODRType.
609   DEFINE_GETIMPL_LOOKUP(DICompositeType,
610                         (Tag, Name, File, Line, Scope, BaseType, SizeInBits,
611                          AlignInBits, OffsetInBits, Flags, Elements,
612                          RuntimeLang, VTableHolder, TemplateParams, Identifier,
613                          Discriminator, DataLocation, Associated, Allocated,
614                          Rank, Annotations));
615   Metadata *Ops[] = {File,          Scope,        Name,           BaseType,
616                      Elements,      VTableHolder, TemplateParams, Identifier,
617                      Discriminator, DataLocation, Associated,     Allocated,
618                      Rank,          Annotations};
619   DEFINE_GETIMPL_STORE(DICompositeType, (Tag, Line, RuntimeLang, SizeInBits,
620                                          AlignInBits, OffsetInBits, Flags),
621                        Ops);
622 }
623 
624 DICompositeType *DICompositeType::buildODRType(
625     LLVMContext &Context, MDString &Identifier, unsigned Tag, MDString *Name,
626     Metadata *File, unsigned Line, Metadata *Scope, Metadata *BaseType,
627     uint64_t SizeInBits, uint32_t AlignInBits, uint64_t OffsetInBits,
628     DIFlags Flags, Metadata *Elements, unsigned RuntimeLang,
629     Metadata *VTableHolder, Metadata *TemplateParams, Metadata *Discriminator,
630     Metadata *DataLocation, Metadata *Associated, Metadata *Allocated,
631     Metadata *Rank, Metadata *Annotations) {
632   assert(!Identifier.getString().empty() && "Expected valid identifier");
633   if (!Context.isODRUniquingDebugTypes())
634     return nullptr;
635   auto *&CT = (*Context.pImpl->DITypeMap)[&Identifier];
636   if (!CT)
637     return CT = DICompositeType::getDistinct(
638                Context, Tag, Name, File, Line, Scope, BaseType, SizeInBits,
639                AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang,
640                VTableHolder, TemplateParams, &Identifier, Discriminator,
641                DataLocation, Associated, Allocated, Rank, Annotations);
642 
643   if (CT->getTag() != Tag)
644     return nullptr;
645 
646   // Only mutate CT if it's a forward declaration and the new operands aren't.
647   assert(CT->getRawIdentifier() == &Identifier && "Wrong ODR identifier?");
648   if (!CT->isForwardDecl() || (Flags & DINode::FlagFwdDecl))
649     return CT;
650 
651   // Mutate CT in place.  Keep this in sync with getImpl.
652   CT->mutate(Tag, Line, RuntimeLang, SizeInBits, AlignInBits, OffsetInBits,
653              Flags);
654   Metadata *Ops[] = {File,          Scope,        Name,           BaseType,
655                      Elements,      VTableHolder, TemplateParams, &Identifier,
656                      Discriminator, DataLocation, Associated,     Allocated,
657                      Rank,          Annotations};
658   assert((std::end(Ops) - std::begin(Ops)) == (int)CT->getNumOperands() &&
659          "Mismatched number of operands");
660   for (unsigned I = 0, E = CT->getNumOperands(); I != E; ++I)
661     if (Ops[I] != CT->getOperand(I))
662       CT->setOperand(I, Ops[I]);
663   return CT;
664 }
665 
666 DICompositeType *DICompositeType::getODRType(
667     LLVMContext &Context, MDString &Identifier, unsigned Tag, MDString *Name,
668     Metadata *File, unsigned Line, Metadata *Scope, Metadata *BaseType,
669     uint64_t SizeInBits, uint32_t AlignInBits, uint64_t OffsetInBits,
670     DIFlags Flags, Metadata *Elements, unsigned RuntimeLang,
671     Metadata *VTableHolder, Metadata *TemplateParams, Metadata *Discriminator,
672     Metadata *DataLocation, Metadata *Associated, Metadata *Allocated,
673     Metadata *Rank, Metadata *Annotations) {
674   assert(!Identifier.getString().empty() && "Expected valid identifier");
675   if (!Context.isODRUniquingDebugTypes())
676     return nullptr;
677   auto *&CT = (*Context.pImpl->DITypeMap)[&Identifier];
678   if (!CT) {
679     CT = DICompositeType::getDistinct(
680         Context, Tag, Name, File, Line, Scope, BaseType, SizeInBits,
681         AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang, VTableHolder,
682         TemplateParams, &Identifier, Discriminator, DataLocation, Associated,
683         Allocated, Rank, Annotations);
684   } else {
685     if (CT->getTag() != Tag)
686       return nullptr;
687   }
688   return CT;
689 }
690 
691 DICompositeType *DICompositeType::getODRTypeIfExists(LLVMContext &Context,
692                                                      MDString &Identifier) {
693   assert(!Identifier.getString().empty() && "Expected valid identifier");
694   if (!Context.isODRUniquingDebugTypes())
695     return nullptr;
696   return Context.pImpl->DITypeMap->lookup(&Identifier);
697 }
698 
699 DISubroutineType *DISubroutineType::getImpl(LLVMContext &Context, DIFlags Flags,
700                                             uint8_t CC, Metadata *TypeArray,
701                                             StorageType Storage,
702                                             bool ShouldCreate) {
703   DEFINE_GETIMPL_LOOKUP(DISubroutineType, (Flags, CC, TypeArray));
704   Metadata *Ops[] = {nullptr, nullptr, nullptr, TypeArray};
705   DEFINE_GETIMPL_STORE(DISubroutineType, (Flags, CC), Ops);
706 }
707 
708 // FIXME: Implement this string-enum correspondence with a .def file and macros,
709 // so that the association is explicit rather than implied.
710 static const char *ChecksumKindName[DIFile::CSK_Last] = {
711     "CSK_MD5",
712     "CSK_SHA1",
713     "CSK_SHA256",
714 };
715 
716 StringRef DIFile::getChecksumKindAsString(ChecksumKind CSKind) {
717   assert(CSKind <= DIFile::CSK_Last && "Invalid checksum kind");
718   // The first space was originally the CSK_None variant, which is now
719   // obsolete, but the space is still reserved in ChecksumKind, so we account
720   // for it here.
721   return ChecksumKindName[CSKind - 1];
722 }
723 
724 Optional<DIFile::ChecksumKind> DIFile::getChecksumKind(StringRef CSKindStr) {
725   return StringSwitch<Optional<DIFile::ChecksumKind>>(CSKindStr)
726       .Case("CSK_MD5", DIFile::CSK_MD5)
727       .Case("CSK_SHA1", DIFile::CSK_SHA1)
728       .Case("CSK_SHA256", DIFile::CSK_SHA256)
729       .Default(None);
730 }
731 
732 DIFile *DIFile::getImpl(LLVMContext &Context, MDString *Filename,
733                         MDString *Directory,
734                         Optional<DIFile::ChecksumInfo<MDString *>> CS,
735                         Optional<MDString *> Source, StorageType Storage,
736                         bool ShouldCreate) {
737   assert(isCanonical(Filename) && "Expected canonical MDString");
738   assert(isCanonical(Directory) && "Expected canonical MDString");
739   assert((!CS || isCanonical(CS->Value)) && "Expected canonical MDString");
740   assert((!Source || isCanonical(*Source)) && "Expected canonical MDString");
741   DEFINE_GETIMPL_LOOKUP(DIFile, (Filename, Directory, CS, Source));
742   Metadata *Ops[] = {Filename, Directory, CS ? CS->Value : nullptr,
743                      Source.getValueOr(nullptr)};
744   DEFINE_GETIMPL_STORE(DIFile, (CS, Source), Ops);
745 }
746 
747 DICompileUnit *DICompileUnit::getImpl(
748     LLVMContext &Context, unsigned SourceLanguage, Metadata *File,
749     MDString *Producer, bool IsOptimized, MDString *Flags,
750     unsigned RuntimeVersion, MDString *SplitDebugFilename,
751     unsigned EmissionKind, Metadata *EnumTypes, Metadata *RetainedTypes,
752     Metadata *GlobalVariables, Metadata *ImportedEntities, Metadata *Macros,
753     uint64_t DWOId, bool SplitDebugInlining, bool DebugInfoForProfiling,
754     unsigned NameTableKind, bool RangesBaseAddress, MDString *SysRoot,
755     MDString *SDK, StorageType Storage, bool ShouldCreate) {
756   assert(Storage != Uniqued && "Cannot unique DICompileUnit");
757   assert(isCanonical(Producer) && "Expected canonical MDString");
758   assert(isCanonical(Flags) && "Expected canonical MDString");
759   assert(isCanonical(SplitDebugFilename) && "Expected canonical MDString");
760 
761   Metadata *Ops[] = {File,
762                      Producer,
763                      Flags,
764                      SplitDebugFilename,
765                      EnumTypes,
766                      RetainedTypes,
767                      GlobalVariables,
768                      ImportedEntities,
769                      Macros,
770                      SysRoot,
771                      SDK};
772   return storeImpl(new (array_lengthof(Ops)) DICompileUnit(
773                        Context, Storage, SourceLanguage, IsOptimized,
774                        RuntimeVersion, EmissionKind, DWOId, SplitDebugInlining,
775                        DebugInfoForProfiling, NameTableKind, RangesBaseAddress,
776                        Ops),
777                    Storage);
778 }
779 
780 Optional<DICompileUnit::DebugEmissionKind>
781 DICompileUnit::getEmissionKind(StringRef Str) {
782   return StringSwitch<Optional<DebugEmissionKind>>(Str)
783       .Case("NoDebug", NoDebug)
784       .Case("FullDebug", FullDebug)
785       .Case("LineTablesOnly", LineTablesOnly)
786       .Case("DebugDirectivesOnly", DebugDirectivesOnly)
787       .Default(None);
788 }
789 
790 Optional<DICompileUnit::DebugNameTableKind>
791 DICompileUnit::getNameTableKind(StringRef Str) {
792   return StringSwitch<Optional<DebugNameTableKind>>(Str)
793       .Case("Default", DebugNameTableKind::Default)
794       .Case("GNU", DebugNameTableKind::GNU)
795       .Case("None", DebugNameTableKind::None)
796       .Default(None);
797 }
798 
799 const char *DICompileUnit::emissionKindString(DebugEmissionKind EK) {
800   switch (EK) {
801   case NoDebug:        return "NoDebug";
802   case FullDebug:      return "FullDebug";
803   case LineTablesOnly: return "LineTablesOnly";
804   case DebugDirectivesOnly: return "DebugDirectivesOnly";
805   }
806   return nullptr;
807 }
808 
809 const char *DICompileUnit::nameTableKindString(DebugNameTableKind NTK) {
810   switch (NTK) {
811   case DebugNameTableKind::Default:
812     return nullptr;
813   case DebugNameTableKind::GNU:
814     return "GNU";
815   case DebugNameTableKind::None:
816     return "None";
817   }
818   return nullptr;
819 }
820 
821 DISubprogram *DILocalScope::getSubprogram() const {
822   if (auto *Block = dyn_cast<DILexicalBlockBase>(this))
823     return Block->getScope()->getSubprogram();
824   return const_cast<DISubprogram *>(cast<DISubprogram>(this));
825 }
826 
827 DILocalScope *DILocalScope::getNonLexicalBlockFileScope() const {
828   if (auto *File = dyn_cast<DILexicalBlockFile>(this))
829     return File->getScope()->getNonLexicalBlockFileScope();
830   return const_cast<DILocalScope *>(this);
831 }
832 
833 DISubprogram::DISPFlags DISubprogram::getFlag(StringRef Flag) {
834   return StringSwitch<DISPFlags>(Flag)
835 #define HANDLE_DISP_FLAG(ID, NAME) .Case("DISPFlag" #NAME, SPFlag##NAME)
836 #include "llvm/IR/DebugInfoFlags.def"
837       .Default(SPFlagZero);
838 }
839 
840 StringRef DISubprogram::getFlagString(DISPFlags Flag) {
841   switch (Flag) {
842   // Appease a warning.
843   case SPFlagVirtuality:
844     return "";
845 #define HANDLE_DISP_FLAG(ID, NAME)                                             \
846   case SPFlag##NAME:                                                           \
847     return "DISPFlag" #NAME;
848 #include "llvm/IR/DebugInfoFlags.def"
849   }
850   return "";
851 }
852 
853 DISubprogram::DISPFlags
854 DISubprogram::splitFlags(DISPFlags Flags,
855                          SmallVectorImpl<DISPFlags> &SplitFlags) {
856   // Multi-bit fields can require special handling. In our case, however, the
857   // only multi-bit field is virtuality, and all its values happen to be
858   // single-bit values, so the right behavior just falls out.
859 #define HANDLE_DISP_FLAG(ID, NAME)                                             \
860   if (DISPFlags Bit = Flags & SPFlag##NAME) {                                  \
861     SplitFlags.push_back(Bit);                                                 \
862     Flags &= ~Bit;                                                             \
863   }
864 #include "llvm/IR/DebugInfoFlags.def"
865   return Flags;
866 }
867 
868 DISubprogram *DISubprogram::getImpl(
869     LLVMContext &Context, Metadata *Scope, MDString *Name,
870     MDString *LinkageName, Metadata *File, unsigned Line, Metadata *Type,
871     unsigned ScopeLine, Metadata *ContainingType, unsigned VirtualIndex,
872     int ThisAdjustment, DIFlags Flags, DISPFlags SPFlags, Metadata *Unit,
873     Metadata *TemplateParams, Metadata *Declaration, Metadata *RetainedNodes,
874     Metadata *ThrownTypes, Metadata *Annotations, StorageType Storage,
875     bool ShouldCreate) {
876   assert(isCanonical(Name) && "Expected canonical MDString");
877   assert(isCanonical(LinkageName) && "Expected canonical MDString");
878   DEFINE_GETIMPL_LOOKUP(DISubprogram,
879                         (Scope, Name, LinkageName, File, Line, Type, ScopeLine,
880                          ContainingType, VirtualIndex, ThisAdjustment, Flags,
881                          SPFlags, Unit, TemplateParams, Declaration,
882                          RetainedNodes, ThrownTypes, Annotations));
883   SmallVector<Metadata *, 12> Ops = {
884       File,        Scope,         Name,           LinkageName,    Type,       Unit,
885       Declaration, RetainedNodes, ContainingType, TemplateParams, ThrownTypes,
886       Annotations};
887   if (!Annotations) {
888     Ops.pop_back();
889     if (!ThrownTypes) {
890       Ops.pop_back();
891       if (!TemplateParams) {
892         Ops.pop_back();
893         if (!ContainingType)
894           Ops.pop_back();
895       }
896     }
897   }
898   DEFINE_GETIMPL_STORE_N(
899       DISubprogram,
900       (Line, ScopeLine, VirtualIndex, ThisAdjustment, Flags, SPFlags), Ops,
901       Ops.size());
902 }
903 
904 bool DISubprogram::describes(const Function *F) const {
905   assert(F && "Invalid function");
906   return F->getSubprogram() == this;
907 }
908 
909 DILexicalBlock *DILexicalBlock::getImpl(LLVMContext &Context, Metadata *Scope,
910                                         Metadata *File, unsigned Line,
911                                         unsigned Column, StorageType Storage,
912                                         bool ShouldCreate) {
913   // Fixup column.
914   adjustColumn(Column);
915 
916   assert(Scope && "Expected scope");
917   DEFINE_GETIMPL_LOOKUP(DILexicalBlock, (Scope, File, Line, Column));
918   Metadata *Ops[] = {File, Scope};
919   DEFINE_GETIMPL_STORE(DILexicalBlock, (Line, Column), Ops);
920 }
921 
922 DILexicalBlockFile *DILexicalBlockFile::getImpl(LLVMContext &Context,
923                                                 Metadata *Scope, Metadata *File,
924                                                 unsigned Discriminator,
925                                                 StorageType Storage,
926                                                 bool ShouldCreate) {
927   assert(Scope && "Expected scope");
928   DEFINE_GETIMPL_LOOKUP(DILexicalBlockFile, (Scope, File, Discriminator));
929   Metadata *Ops[] = {File, Scope};
930   DEFINE_GETIMPL_STORE(DILexicalBlockFile, (Discriminator), Ops);
931 }
932 
933 DINamespace *DINamespace::getImpl(LLVMContext &Context, Metadata *Scope,
934                                   MDString *Name, bool ExportSymbols,
935                                   StorageType Storage, bool ShouldCreate) {
936   assert(isCanonical(Name) && "Expected canonical MDString");
937   DEFINE_GETIMPL_LOOKUP(DINamespace, (Scope, Name, ExportSymbols));
938   // The nullptr is for DIScope's File operand. This should be refactored.
939   Metadata *Ops[] = {nullptr, Scope, Name};
940   DEFINE_GETIMPL_STORE(DINamespace, (ExportSymbols), Ops);
941 }
942 
943 DICommonBlock *DICommonBlock::getImpl(LLVMContext &Context, Metadata *Scope,
944                                       Metadata *Decl, MDString *Name,
945                                       Metadata *File, unsigned LineNo,
946                                       StorageType Storage, bool ShouldCreate) {
947   assert(isCanonical(Name) && "Expected canonical MDString");
948   DEFINE_GETIMPL_LOOKUP(DICommonBlock, (Scope, Decl, Name, File, LineNo));
949   // The nullptr is for DIScope's File operand. This should be refactored.
950   Metadata *Ops[] = {Scope, Decl, Name, File};
951   DEFINE_GETIMPL_STORE(DICommonBlock, (LineNo), Ops);
952 }
953 
954 DIModule *DIModule::getImpl(LLVMContext &Context, Metadata *File,
955                             Metadata *Scope, MDString *Name,
956                             MDString *ConfigurationMacros,
957                             MDString *IncludePath, MDString *APINotesFile,
958                             unsigned LineNo, bool IsDecl, StorageType Storage,
959                             bool ShouldCreate) {
960   assert(isCanonical(Name) && "Expected canonical MDString");
961   DEFINE_GETIMPL_LOOKUP(DIModule, (File, Scope, Name, ConfigurationMacros,
962                                    IncludePath, APINotesFile, LineNo, IsDecl));
963   Metadata *Ops[] = {File,        Scope,       Name, ConfigurationMacros,
964                      IncludePath, APINotesFile};
965   DEFINE_GETIMPL_STORE(DIModule, (LineNo, IsDecl), Ops);
966 }
967 
968 DITemplateTypeParameter *
969 DITemplateTypeParameter::getImpl(LLVMContext &Context, MDString *Name,
970                                  Metadata *Type, bool isDefault,
971                                  StorageType Storage, bool ShouldCreate) {
972   assert(isCanonical(Name) && "Expected canonical MDString");
973   DEFINE_GETIMPL_LOOKUP(DITemplateTypeParameter, (Name, Type, isDefault));
974   Metadata *Ops[] = {Name, Type};
975   DEFINE_GETIMPL_STORE(DITemplateTypeParameter, (isDefault), Ops);
976 }
977 
978 DITemplateValueParameter *DITemplateValueParameter::getImpl(
979     LLVMContext &Context, unsigned Tag, MDString *Name, Metadata *Type,
980     bool isDefault, Metadata *Value, StorageType Storage, bool ShouldCreate) {
981   assert(isCanonical(Name) && "Expected canonical MDString");
982   DEFINE_GETIMPL_LOOKUP(DITemplateValueParameter,
983                         (Tag, Name, Type, isDefault, Value));
984   Metadata *Ops[] = {Name, Type, Value};
985   DEFINE_GETIMPL_STORE(DITemplateValueParameter, (Tag, isDefault), Ops);
986 }
987 
988 DIGlobalVariable *
989 DIGlobalVariable::getImpl(LLVMContext &Context, Metadata *Scope, MDString *Name,
990                           MDString *LinkageName, Metadata *File, unsigned Line,
991                           Metadata *Type, bool IsLocalToUnit, bool IsDefinition,
992                           Metadata *StaticDataMemberDeclaration,
993                           Metadata *TemplateParams, uint32_t AlignInBits,
994                           Metadata *Annotations, StorageType Storage,
995                           bool ShouldCreate) {
996   assert(isCanonical(Name) && "Expected canonical MDString");
997   assert(isCanonical(LinkageName) && "Expected canonical MDString");
998   DEFINE_GETIMPL_LOOKUP(DIGlobalVariable, (Scope, Name, LinkageName, File, Line,
999                                            Type, IsLocalToUnit, IsDefinition,
1000                                            StaticDataMemberDeclaration,
1001                                            TemplateParams, AlignInBits,
1002                                            Annotations));
1003   Metadata *Ops[] = {Scope,
1004                      Name,
1005                      File,
1006                      Type,
1007                      Name,
1008                      LinkageName,
1009                      StaticDataMemberDeclaration,
1010                      TemplateParams,
1011                      Annotations};
1012   DEFINE_GETIMPL_STORE(DIGlobalVariable,
1013                        (Line, IsLocalToUnit, IsDefinition, AlignInBits), Ops);
1014 }
1015 
1016 DILocalVariable *DILocalVariable::getImpl(LLVMContext &Context, Metadata *Scope,
1017                                           MDString *Name, Metadata *File,
1018                                           unsigned Line, Metadata *Type,
1019                                           unsigned Arg, DIFlags Flags,
1020                                           uint32_t AlignInBits,
1021                                           Metadata *Annotations,
1022                                           StorageType Storage,
1023                                           bool ShouldCreate) {
1024   // 64K ought to be enough for any frontend.
1025   assert(Arg <= UINT16_MAX && "Expected argument number to fit in 16-bits");
1026 
1027   assert(Scope && "Expected scope");
1028   assert(isCanonical(Name) && "Expected canonical MDString");
1029   DEFINE_GETIMPL_LOOKUP(DILocalVariable,
1030                         (Scope, Name, File, Line, Type, Arg, Flags,
1031                          AlignInBits, Annotations));
1032   Metadata *Ops[] = {Scope, Name, File, Type, Annotations};
1033   DEFINE_GETIMPL_STORE(DILocalVariable, (Line, Arg, Flags, AlignInBits), Ops);
1034 }
1035 
1036 Optional<uint64_t> DIVariable::getSizeInBits() const {
1037   // This is used by the Verifier so be mindful of broken types.
1038   const Metadata *RawType = getRawType();
1039   while (RawType) {
1040     // Try to get the size directly.
1041     if (auto *T = dyn_cast<DIType>(RawType))
1042       if (uint64_t Size = T->getSizeInBits())
1043         return Size;
1044 
1045     if (auto *DT = dyn_cast<DIDerivedType>(RawType)) {
1046       // Look at the base type.
1047       RawType = DT->getRawBaseType();
1048       continue;
1049     }
1050 
1051     // Missing type or size.
1052     break;
1053   }
1054 
1055   // Fail gracefully.
1056   return None;
1057 }
1058 
1059 DILabel *DILabel::getImpl(LLVMContext &Context, Metadata *Scope,
1060                           MDString *Name, Metadata *File, unsigned Line,
1061                           StorageType Storage,
1062                           bool ShouldCreate) {
1063   assert(Scope && "Expected scope");
1064   assert(isCanonical(Name) && "Expected canonical MDString");
1065   DEFINE_GETIMPL_LOOKUP(DILabel,
1066                         (Scope, Name, File, Line));
1067   Metadata *Ops[] = {Scope, Name, File};
1068   DEFINE_GETIMPL_STORE(DILabel, (Line), Ops);
1069 }
1070 
1071 DIExpression *DIExpression::getImpl(LLVMContext &Context,
1072                                     ArrayRef<uint64_t> Elements,
1073                                     StorageType Storage, bool ShouldCreate) {
1074   DEFINE_GETIMPL_LOOKUP(DIExpression, (Elements));
1075   DEFINE_GETIMPL_STORE_NO_OPS(DIExpression, (Elements));
1076 }
1077 
1078 unsigned DIExpression::ExprOperand::getSize() const {
1079   uint64_t Op = getOp();
1080 
1081   if (Op >= dwarf::DW_OP_breg0 && Op <= dwarf::DW_OP_breg31)
1082     return 2;
1083 
1084   switch (Op) {
1085   case dwarf::DW_OP_LLVM_convert:
1086   case dwarf::DW_OP_LLVM_fragment:
1087   case dwarf::DW_OP_bregx:
1088     return 3;
1089   case dwarf::DW_OP_constu:
1090   case dwarf::DW_OP_consts:
1091   case dwarf::DW_OP_deref_size:
1092   case dwarf::DW_OP_plus_uconst:
1093   case dwarf::DW_OP_LLVM_tag_offset:
1094   case dwarf::DW_OP_LLVM_entry_value:
1095   case dwarf::DW_OP_LLVM_arg:
1096   case dwarf::DW_OP_regx:
1097     return 2;
1098   default:
1099     return 1;
1100   }
1101 }
1102 
1103 bool DIExpression::isValid() const {
1104   for (auto I = expr_op_begin(), E = expr_op_end(); I != E; ++I) {
1105     // Check that there's space for the operand.
1106     if (I->get() + I->getSize() > E->get())
1107       return false;
1108 
1109     uint64_t Op = I->getOp();
1110     if ((Op >= dwarf::DW_OP_reg0 && Op <= dwarf::DW_OP_reg31) ||
1111         (Op >= dwarf::DW_OP_breg0 && Op <= dwarf::DW_OP_breg31))
1112       return true;
1113 
1114     // Check that the operand is valid.
1115     switch (Op) {
1116     default:
1117       return false;
1118     case dwarf::DW_OP_LLVM_fragment:
1119       // A fragment operator must appear at the end.
1120       return I->get() + I->getSize() == E->get();
1121     case dwarf::DW_OP_stack_value: {
1122       // Must be the last one or followed by a DW_OP_LLVM_fragment.
1123       if (I->get() + I->getSize() == E->get())
1124         break;
1125       auto J = I;
1126       if ((++J)->getOp() != dwarf::DW_OP_LLVM_fragment)
1127         return false;
1128       break;
1129     }
1130     case dwarf::DW_OP_swap: {
1131       // Must be more than one implicit element on the stack.
1132 
1133       // FIXME: A better way to implement this would be to add a local variable
1134       // that keeps track of the stack depth and introduce something like a
1135       // DW_LLVM_OP_implicit_location as a placeholder for the location this
1136       // DIExpression is attached to, or else pass the number of implicit stack
1137       // elements into isValid.
1138       if (getNumElements() == 1)
1139         return false;
1140       break;
1141     }
1142     case dwarf::DW_OP_LLVM_entry_value: {
1143       // An entry value operator must appear at the beginning and the number of
1144       // operations it cover can currently only be 1, because we support only
1145       // entry values of a simple register location. One reason for this is that
1146       // we currently can't calculate the size of the resulting DWARF block for
1147       // other expressions.
1148       return I->get() == expr_op_begin()->get() && I->getArg(0) == 1;
1149     }
1150     case dwarf::DW_OP_LLVM_implicit_pointer:
1151     case dwarf::DW_OP_LLVM_convert:
1152     case dwarf::DW_OP_LLVM_arg:
1153     case dwarf::DW_OP_LLVM_tag_offset:
1154     case dwarf::DW_OP_constu:
1155     case dwarf::DW_OP_plus_uconst:
1156     case dwarf::DW_OP_plus:
1157     case dwarf::DW_OP_minus:
1158     case dwarf::DW_OP_mul:
1159     case dwarf::DW_OP_div:
1160     case dwarf::DW_OP_mod:
1161     case dwarf::DW_OP_or:
1162     case dwarf::DW_OP_and:
1163     case dwarf::DW_OP_xor:
1164     case dwarf::DW_OP_shl:
1165     case dwarf::DW_OP_shr:
1166     case dwarf::DW_OP_shra:
1167     case dwarf::DW_OP_deref:
1168     case dwarf::DW_OP_deref_size:
1169     case dwarf::DW_OP_xderef:
1170     case dwarf::DW_OP_lit0:
1171     case dwarf::DW_OP_not:
1172     case dwarf::DW_OP_dup:
1173     case dwarf::DW_OP_regx:
1174     case dwarf::DW_OP_bregx:
1175     case dwarf::DW_OP_push_object_address:
1176     case dwarf::DW_OP_over:
1177     case dwarf::DW_OP_consts:
1178       break;
1179     }
1180   }
1181   return true;
1182 }
1183 
1184 bool DIExpression::isImplicit() const {
1185   if (!isValid())
1186     return false;
1187 
1188   if (getNumElements() == 0)
1189     return false;
1190 
1191   for (const auto &It : expr_ops()) {
1192     switch (It.getOp()) {
1193     default:
1194       break;
1195     case dwarf::DW_OP_stack_value:
1196     case dwarf::DW_OP_LLVM_tag_offset:
1197       return true;
1198     }
1199   }
1200 
1201   return false;
1202 }
1203 
1204 bool DIExpression::isComplex() const {
1205   if (!isValid())
1206     return false;
1207 
1208   if (getNumElements() == 0)
1209     return false;
1210 
1211   // If there are any elements other than fragment or tag_offset, then some
1212   // kind of complex computation occurs.
1213   for (const auto &It : expr_ops()) {
1214     switch (It.getOp()) {
1215       case dwarf::DW_OP_LLVM_tag_offset:
1216       case dwarf::DW_OP_LLVM_fragment:
1217         continue;
1218       default: return true;
1219     }
1220   }
1221 
1222   return false;
1223 }
1224 
1225 Optional<DIExpression::FragmentInfo>
1226 DIExpression::getFragmentInfo(expr_op_iterator Start, expr_op_iterator End) {
1227   for (auto I = Start; I != End; ++I)
1228     if (I->getOp() == dwarf::DW_OP_LLVM_fragment) {
1229       DIExpression::FragmentInfo Info = {I->getArg(1), I->getArg(0)};
1230       return Info;
1231     }
1232   return None;
1233 }
1234 
1235 void DIExpression::appendOffset(SmallVectorImpl<uint64_t> &Ops,
1236                                 int64_t Offset) {
1237   if (Offset > 0) {
1238     Ops.push_back(dwarf::DW_OP_plus_uconst);
1239     Ops.push_back(Offset);
1240   } else if (Offset < 0) {
1241     Ops.push_back(dwarf::DW_OP_constu);
1242     Ops.push_back(-Offset);
1243     Ops.push_back(dwarf::DW_OP_minus);
1244   }
1245 }
1246 
1247 bool DIExpression::extractIfOffset(int64_t &Offset) const {
1248   if (getNumElements() == 0) {
1249     Offset = 0;
1250     return true;
1251   }
1252 
1253   if (getNumElements() == 2 && Elements[0] == dwarf::DW_OP_plus_uconst) {
1254     Offset = Elements[1];
1255     return true;
1256   }
1257 
1258   if (getNumElements() == 3 && Elements[0] == dwarf::DW_OP_constu) {
1259     if (Elements[2] == dwarf::DW_OP_plus) {
1260       Offset = Elements[1];
1261       return true;
1262     }
1263     if (Elements[2] == dwarf::DW_OP_minus) {
1264       Offset = -Elements[1];
1265       return true;
1266     }
1267   }
1268 
1269   return false;
1270 }
1271 
1272 bool DIExpression::hasAllLocationOps(unsigned N) const {
1273   SmallDenseSet<uint64_t, 4> SeenOps;
1274   for (auto ExprOp : expr_ops())
1275     if (ExprOp.getOp() == dwarf::DW_OP_LLVM_arg)
1276       SeenOps.insert(ExprOp.getArg(0));
1277   for (uint64_t Idx = 0; Idx < N; ++Idx)
1278     if (!is_contained(SeenOps, Idx))
1279       return false;
1280   return true;
1281 }
1282 
1283 const DIExpression *DIExpression::extractAddressClass(const DIExpression *Expr,
1284                                                       unsigned &AddrClass) {
1285   // FIXME: This seems fragile. Nothing that verifies that these elements
1286   // actually map to ops and not operands.
1287   const unsigned PatternSize = 4;
1288   if (Expr->Elements.size() >= PatternSize &&
1289       Expr->Elements[PatternSize - 4] == dwarf::DW_OP_constu &&
1290       Expr->Elements[PatternSize - 2] == dwarf::DW_OP_swap &&
1291       Expr->Elements[PatternSize - 1] == dwarf::DW_OP_xderef) {
1292     AddrClass = Expr->Elements[PatternSize - 3];
1293 
1294     if (Expr->Elements.size() == PatternSize)
1295       return nullptr;
1296     return DIExpression::get(Expr->getContext(),
1297                              makeArrayRef(&*Expr->Elements.begin(),
1298                                           Expr->Elements.size() - PatternSize));
1299   }
1300   return Expr;
1301 }
1302 
1303 DIExpression *DIExpression::prepend(const DIExpression *Expr, uint8_t Flags,
1304                                     int64_t Offset) {
1305   SmallVector<uint64_t, 8> Ops;
1306   if (Flags & DIExpression::DerefBefore)
1307     Ops.push_back(dwarf::DW_OP_deref);
1308 
1309   appendOffset(Ops, Offset);
1310   if (Flags & DIExpression::DerefAfter)
1311     Ops.push_back(dwarf::DW_OP_deref);
1312 
1313   bool StackValue = Flags & DIExpression::StackValue;
1314   bool EntryValue = Flags & DIExpression::EntryValue;
1315 
1316   return prependOpcodes(Expr, Ops, StackValue, EntryValue);
1317 }
1318 
1319 DIExpression *DIExpression::appendOpsToArg(const DIExpression *Expr,
1320                                            ArrayRef<uint64_t> Ops,
1321                                            unsigned ArgNo, bool StackValue) {
1322   assert(Expr && "Can't add ops to this expression");
1323 
1324   // Handle non-variadic intrinsics by prepending the opcodes.
1325   if (!any_of(Expr->expr_ops(),
1326               [](auto Op) { return Op.getOp() == dwarf::DW_OP_LLVM_arg; })) {
1327     assert(ArgNo == 0 &&
1328            "Location Index must be 0 for a non-variadic expression.");
1329     SmallVector<uint64_t, 8> NewOps(Ops.begin(), Ops.end());
1330     return DIExpression::prependOpcodes(Expr, NewOps, StackValue);
1331   }
1332 
1333   SmallVector<uint64_t, 8> NewOps;
1334   for (auto Op : Expr->expr_ops()) {
1335     Op.appendToVector(NewOps);
1336     if (Op.getOp() == dwarf::DW_OP_LLVM_arg && Op.getArg(0) == ArgNo)
1337       NewOps.insert(NewOps.end(), Ops.begin(), Ops.end());
1338   }
1339 
1340   return DIExpression::get(Expr->getContext(), NewOps);
1341 }
1342 
1343 DIExpression *DIExpression::replaceArg(const DIExpression *Expr,
1344                                        uint64_t OldArg, uint64_t NewArg) {
1345   assert(Expr && "Can't replace args in this expression");
1346 
1347   SmallVector<uint64_t, 8> NewOps;
1348 
1349   for (auto Op : Expr->expr_ops()) {
1350     if (Op.getOp() != dwarf::DW_OP_LLVM_arg || Op.getArg(0) < OldArg) {
1351       Op.appendToVector(NewOps);
1352       continue;
1353     }
1354     NewOps.push_back(dwarf::DW_OP_LLVM_arg);
1355     uint64_t Arg = Op.getArg(0) == OldArg ? NewArg : Op.getArg(0);
1356     // OldArg has been deleted from the Op list, so decrement all indices
1357     // greater than it.
1358     if (Arg > OldArg)
1359       --Arg;
1360     NewOps.push_back(Arg);
1361   }
1362   return DIExpression::get(Expr->getContext(), NewOps);
1363 }
1364 
1365 DIExpression *DIExpression::prependOpcodes(const DIExpression *Expr,
1366                                            SmallVectorImpl<uint64_t> &Ops,
1367                                            bool StackValue,
1368                                            bool EntryValue) {
1369   assert(Expr && "Can't prepend ops to this expression");
1370 
1371   if (EntryValue) {
1372     Ops.push_back(dwarf::DW_OP_LLVM_entry_value);
1373     // Use a block size of 1 for the target register operand.  The
1374     // DWARF backend currently cannot emit entry values with a block
1375     // size > 1.
1376     Ops.push_back(1);
1377   }
1378 
1379   // If there are no ops to prepend, do not even add the DW_OP_stack_value.
1380   if (Ops.empty())
1381     StackValue = false;
1382   for (auto Op : Expr->expr_ops()) {
1383     // A DW_OP_stack_value comes at the end, but before a DW_OP_LLVM_fragment.
1384     if (StackValue) {
1385       if (Op.getOp() == dwarf::DW_OP_stack_value)
1386         StackValue = false;
1387       else if (Op.getOp() == dwarf::DW_OP_LLVM_fragment) {
1388         Ops.push_back(dwarf::DW_OP_stack_value);
1389         StackValue = false;
1390       }
1391     }
1392     Op.appendToVector(Ops);
1393   }
1394   if (StackValue)
1395     Ops.push_back(dwarf::DW_OP_stack_value);
1396   return DIExpression::get(Expr->getContext(), Ops);
1397 }
1398 
1399 DIExpression *DIExpression::append(const DIExpression *Expr,
1400                                    ArrayRef<uint64_t> Ops) {
1401   assert(Expr && !Ops.empty() && "Can't append ops to this expression");
1402 
1403   // Copy Expr's current op list.
1404   SmallVector<uint64_t, 16> NewOps;
1405   for (auto Op : Expr->expr_ops()) {
1406     // Append new opcodes before DW_OP_{stack_value, LLVM_fragment}.
1407     if (Op.getOp() == dwarf::DW_OP_stack_value ||
1408         Op.getOp() == dwarf::DW_OP_LLVM_fragment) {
1409       NewOps.append(Ops.begin(), Ops.end());
1410 
1411       // Ensure that the new opcodes are only appended once.
1412       Ops = None;
1413     }
1414     Op.appendToVector(NewOps);
1415   }
1416 
1417   NewOps.append(Ops.begin(), Ops.end());
1418   auto *result = DIExpression::get(Expr->getContext(), NewOps);
1419   assert(result->isValid() && "concatenated expression is not valid");
1420   return result;
1421 }
1422 
1423 DIExpression *DIExpression::appendToStack(const DIExpression *Expr,
1424                                           ArrayRef<uint64_t> Ops) {
1425   assert(Expr && !Ops.empty() && "Can't append ops to this expression");
1426   assert(none_of(Ops,
1427                  [](uint64_t Op) {
1428                    return Op == dwarf::DW_OP_stack_value ||
1429                           Op == dwarf::DW_OP_LLVM_fragment;
1430                  }) &&
1431          "Can't append this op");
1432 
1433   // Append a DW_OP_deref after Expr's current op list if it's non-empty and
1434   // has no DW_OP_stack_value.
1435   //
1436   // Match .* DW_OP_stack_value (DW_OP_LLVM_fragment A B)?.
1437   Optional<FragmentInfo> FI = Expr->getFragmentInfo();
1438   unsigned DropUntilStackValue = FI.hasValue() ? 3 : 0;
1439   ArrayRef<uint64_t> ExprOpsBeforeFragment =
1440       Expr->getElements().drop_back(DropUntilStackValue);
1441   bool NeedsDeref = (Expr->getNumElements() > DropUntilStackValue) &&
1442                     (ExprOpsBeforeFragment.back() != dwarf::DW_OP_stack_value);
1443   bool NeedsStackValue = NeedsDeref || ExprOpsBeforeFragment.empty();
1444 
1445   // Append a DW_OP_deref after Expr's current op list if needed, then append
1446   // the new ops, and finally ensure that a single DW_OP_stack_value is present.
1447   SmallVector<uint64_t, 16> NewOps;
1448   if (NeedsDeref)
1449     NewOps.push_back(dwarf::DW_OP_deref);
1450   NewOps.append(Ops.begin(), Ops.end());
1451   if (NeedsStackValue)
1452     NewOps.push_back(dwarf::DW_OP_stack_value);
1453   return DIExpression::append(Expr, NewOps);
1454 }
1455 
1456 Optional<DIExpression *> DIExpression::createFragmentExpression(
1457     const DIExpression *Expr, unsigned OffsetInBits, unsigned SizeInBits) {
1458   SmallVector<uint64_t, 8> Ops;
1459   // Copy over the expression, but leave off any trailing DW_OP_LLVM_fragment.
1460   if (Expr) {
1461     for (auto Op : Expr->expr_ops()) {
1462       switch (Op.getOp()) {
1463       default: break;
1464       case dwarf::DW_OP_shr:
1465       case dwarf::DW_OP_shra:
1466       case dwarf::DW_OP_shl:
1467       case dwarf::DW_OP_plus:
1468       case dwarf::DW_OP_plus_uconst:
1469       case dwarf::DW_OP_minus:
1470         // We can't safely split arithmetic or shift operations into multiple
1471         // fragments because we can't express carry-over between fragments.
1472         //
1473         // FIXME: We *could* preserve the lowest fragment of a constant offset
1474         // operation if the offset fits into SizeInBits.
1475         return None;
1476       case dwarf::DW_OP_LLVM_fragment: {
1477         // Make the new offset point into the existing fragment.
1478         uint64_t FragmentOffsetInBits = Op.getArg(0);
1479         uint64_t FragmentSizeInBits = Op.getArg(1);
1480         (void)FragmentSizeInBits;
1481         assert((OffsetInBits + SizeInBits <= FragmentSizeInBits) &&
1482                "new fragment outside of original fragment");
1483         OffsetInBits += FragmentOffsetInBits;
1484         continue;
1485       }
1486       }
1487       Op.appendToVector(Ops);
1488     }
1489   }
1490   assert(Expr && "Unknown DIExpression");
1491   Ops.push_back(dwarf::DW_OP_LLVM_fragment);
1492   Ops.push_back(OffsetInBits);
1493   Ops.push_back(SizeInBits);
1494   return DIExpression::get(Expr->getContext(), Ops);
1495 }
1496 
1497 std::pair<DIExpression *, const ConstantInt *>
1498 DIExpression::constantFold(const ConstantInt *CI) {
1499   // Copy the APInt so we can modify it.
1500   APInt NewInt = CI->getValue();
1501   SmallVector<uint64_t, 8> Ops;
1502 
1503   // Fold operators only at the beginning of the expression.
1504   bool First = true;
1505   bool Changed = false;
1506   for (auto Op : expr_ops()) {
1507     switch (Op.getOp()) {
1508     default:
1509       // We fold only the leading part of the expression; if we get to a part
1510       // that we're going to copy unchanged, and haven't done any folding,
1511       // then the entire expression is unchanged and we can return early.
1512       if (!Changed)
1513         return {this, CI};
1514       First = false;
1515       break;
1516     case dwarf::DW_OP_LLVM_convert:
1517       if (!First)
1518         break;
1519       Changed = true;
1520       if (Op.getArg(1) == dwarf::DW_ATE_signed)
1521         NewInt = NewInt.sextOrTrunc(Op.getArg(0));
1522       else {
1523         assert(Op.getArg(1) == dwarf::DW_ATE_unsigned && "Unexpected operand");
1524         NewInt = NewInt.zextOrTrunc(Op.getArg(0));
1525       }
1526       continue;
1527     }
1528     Op.appendToVector(Ops);
1529   }
1530   if (!Changed)
1531     return {this, CI};
1532   return {DIExpression::get(getContext(), Ops),
1533           ConstantInt::get(getContext(), NewInt)};
1534 }
1535 
1536 uint64_t DIExpression::getNumLocationOperands() const {
1537   uint64_t Result = 0;
1538   for (auto ExprOp : expr_ops())
1539     if (ExprOp.getOp() == dwarf::DW_OP_LLVM_arg)
1540       Result = std::max(Result, ExprOp.getArg(0) + 1);
1541   assert(hasAllLocationOps(Result) &&
1542          "Expression is missing one or more location operands.");
1543   return Result;
1544 }
1545 
1546 llvm::Optional<DIExpression::SignedOrUnsignedConstant>
1547 DIExpression::isConstant() const {
1548 
1549   // Recognize signed and unsigned constants.
1550   // An signed constants can be represented as DW_OP_consts C DW_OP_stack_value
1551   // (DW_OP_LLVM_fragment of Len).
1552   // An unsigned constant can be represented as
1553   // DW_OP_constu C DW_OP_stack_value (DW_OP_LLVM_fragment of Len).
1554 
1555   if ((getNumElements() != 2 && getNumElements() != 3 &&
1556        getNumElements() != 6) ||
1557       (getElement(0) != dwarf::DW_OP_consts &&
1558        getElement(0) != dwarf::DW_OP_constu))
1559     return None;
1560 
1561   if (getNumElements() == 2 && getElement(0) == dwarf::DW_OP_consts)
1562     return SignedOrUnsignedConstant::SignedConstant;
1563 
1564   if ((getNumElements() == 3 && getElement(2) != dwarf::DW_OP_stack_value) ||
1565       (getNumElements() == 6 && (getElement(2) != dwarf::DW_OP_stack_value ||
1566                                  getElement(3) != dwarf::DW_OP_LLVM_fragment)))
1567     return None;
1568   return getElement(0) == dwarf::DW_OP_constu
1569              ? SignedOrUnsignedConstant::UnsignedConstant
1570              : SignedOrUnsignedConstant::SignedConstant;
1571 }
1572 
1573 DIExpression::ExtOps DIExpression::getExtOps(unsigned FromSize, unsigned ToSize,
1574                                              bool Signed) {
1575   dwarf::TypeKind TK = Signed ? dwarf::DW_ATE_signed : dwarf::DW_ATE_unsigned;
1576   DIExpression::ExtOps Ops{{dwarf::DW_OP_LLVM_convert, FromSize, TK,
1577                             dwarf::DW_OP_LLVM_convert, ToSize, TK}};
1578   return Ops;
1579 }
1580 
1581 DIExpression *DIExpression::appendExt(const DIExpression *Expr,
1582                                       unsigned FromSize, unsigned ToSize,
1583                                       bool Signed) {
1584   return appendToStack(Expr, getExtOps(FromSize, ToSize, Signed));
1585 }
1586 
1587 DIGlobalVariableExpression *
1588 DIGlobalVariableExpression::getImpl(LLVMContext &Context, Metadata *Variable,
1589                                     Metadata *Expression, StorageType Storage,
1590                                     bool ShouldCreate) {
1591   DEFINE_GETIMPL_LOOKUP(DIGlobalVariableExpression, (Variable, Expression));
1592   Metadata *Ops[] = {Variable, Expression};
1593   DEFINE_GETIMPL_STORE_NO_CONSTRUCTOR_ARGS(DIGlobalVariableExpression, Ops);
1594 }
1595 
1596 DIObjCProperty *DIObjCProperty::getImpl(
1597     LLVMContext &Context, MDString *Name, Metadata *File, unsigned Line,
1598     MDString *GetterName, MDString *SetterName, unsigned Attributes,
1599     Metadata *Type, StorageType Storage, bool ShouldCreate) {
1600   assert(isCanonical(Name) && "Expected canonical MDString");
1601   assert(isCanonical(GetterName) && "Expected canonical MDString");
1602   assert(isCanonical(SetterName) && "Expected canonical MDString");
1603   DEFINE_GETIMPL_LOOKUP(DIObjCProperty, (Name, File, Line, GetterName,
1604                                          SetterName, Attributes, Type));
1605   Metadata *Ops[] = {Name, File, GetterName, SetterName, Type};
1606   DEFINE_GETIMPL_STORE(DIObjCProperty, (Line, Attributes), Ops);
1607 }
1608 
1609 DIImportedEntity *DIImportedEntity::getImpl(LLVMContext &Context, unsigned Tag,
1610                                             Metadata *Scope, Metadata *Entity,
1611                                             Metadata *File, unsigned Line,
1612                                             MDString *Name, Metadata *Elements,
1613                                             StorageType Storage,
1614                                             bool ShouldCreate) {
1615   assert(isCanonical(Name) && "Expected canonical MDString");
1616   DEFINE_GETIMPL_LOOKUP(DIImportedEntity,
1617                         (Tag, Scope, Entity, File, Line, Name, Elements));
1618   Metadata *Ops[] = {Scope, Entity, Name, File, Elements};
1619   DEFINE_GETIMPL_STORE(DIImportedEntity, (Tag, Line), Ops);
1620 }
1621 
1622 DIMacro *DIMacro::getImpl(LLVMContext &Context, unsigned MIType,
1623                           unsigned Line, MDString *Name, MDString *Value,
1624                           StorageType Storage, bool ShouldCreate) {
1625   assert(isCanonical(Name) && "Expected canonical MDString");
1626   DEFINE_GETIMPL_LOOKUP(DIMacro, (MIType, Line, Name, Value));
1627   Metadata *Ops[] = { Name, Value };
1628   DEFINE_GETIMPL_STORE(DIMacro, (MIType, Line), Ops);
1629 }
1630 
1631 DIMacroFile *DIMacroFile::getImpl(LLVMContext &Context, unsigned MIType,
1632                                   unsigned Line, Metadata *File,
1633                                   Metadata *Elements, StorageType Storage,
1634                                   bool ShouldCreate) {
1635   DEFINE_GETIMPL_LOOKUP(DIMacroFile,
1636                         (MIType, Line, File, Elements));
1637   Metadata *Ops[] = { File, Elements };
1638   DEFINE_GETIMPL_STORE(DIMacroFile, (MIType, Line), Ops);
1639 }
1640 
1641 DIArgList *DIArgList::getImpl(LLVMContext &Context,
1642                               ArrayRef<ValueAsMetadata *> Args,
1643                               StorageType Storage, bool ShouldCreate) {
1644   DEFINE_GETIMPL_LOOKUP(DIArgList, (Args));
1645   DEFINE_GETIMPL_STORE_NO_OPS(DIArgList, (Args));
1646 }
1647 
1648 void DIArgList::handleChangedOperand(void *Ref, Metadata *New) {
1649   ValueAsMetadata **OldVMPtr = static_cast<ValueAsMetadata **>(Ref);
1650   assert((!New || isa<ValueAsMetadata>(New)) &&
1651          "DIArgList must be passed a ValueAsMetadata");
1652   untrack();
1653   bool Uniq = isUniqued();
1654   if (Uniq) {
1655     // We need to update the uniqueness once the Args are updated since they
1656     // form the key to the DIArgLists store.
1657     eraseFromStore();
1658   }
1659   ValueAsMetadata *NewVM = cast_or_null<ValueAsMetadata>(New);
1660   for (ValueAsMetadata *&VM : Args) {
1661     if (&VM == OldVMPtr) {
1662       if (NewVM)
1663         VM = NewVM;
1664       else
1665         VM = ValueAsMetadata::get(UndefValue::get(VM->getValue()->getType()));
1666     }
1667   }
1668   if (Uniq) {
1669     if (uniquify() != this)
1670       storeDistinctInContext();
1671   }
1672   track();
1673 }
1674 void DIArgList::track() {
1675   for (ValueAsMetadata *&VAM : Args)
1676     if (VAM)
1677       MetadataTracking::track(&VAM, *VAM, *this);
1678 }
1679 void DIArgList::untrack() {
1680   for (ValueAsMetadata *&VAM : Args)
1681     if (VAM)
1682       MetadataTracking::untrack(&VAM, *VAM);
1683 }
1684 void DIArgList::dropAllReferences() {
1685   untrack();
1686   Args.clear();
1687   MDNode::dropAllReferences();
1688 }
1689