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/SmallPtrSet.h"
17 #include "llvm/ADT/SmallSet.h"
18 #include "llvm/ADT/StringSwitch.h"
19 #include "llvm/BinaryFormat/Dwarf.h"
20 #include "llvm/IR/Function.h"
21 #include "llvm/IR/IntrinsicInst.h"
22 #include "llvm/IR/Type.h"
23 #include "llvm/IR/Value.h"
24 
25 #include <numeric>
26 #include <optional>
27 
28 using namespace llvm;
29 
30 namespace llvm {
31 // Use FS-AFDO discriminator.
32 cl::opt<bool> EnableFSDiscriminator(
33     "enable-fs-discriminator", cl::Hidden,
34     cl::desc("Enable adding flow sensitive discriminators"));
35 } // namespace llvm
36 
37 const DIExpression::FragmentInfo DebugVariable::DefaultFragment = {
38     std::numeric_limits<uint64_t>::max(), std::numeric_limits<uint64_t>::min()};
39 
40 DebugVariable::DebugVariable(const DbgVariableIntrinsic *DII)
41     : Variable(DII->getVariable()),
42       Fragment(DII->getExpression()->getFragmentInfo()),
43       InlinedAt(DII->getDebugLoc().getInlinedAt()) {}
44 
45 DebugVariableAggregate::DebugVariableAggregate(const DbgVariableIntrinsic *DVI)
46     : DebugVariable(DVI->getVariable(), std::nullopt,
47                     DVI->getDebugLoc()->getInlinedAt()) {}
48 
49 DILocation::DILocation(LLVMContext &C, StorageType Storage, unsigned Line,
50                        unsigned Column, ArrayRef<Metadata *> MDs,
51                        bool ImplicitCode)
52     : MDNode(C, DILocationKind, Storage, MDs) {
53   assert((MDs.size() == 1 || MDs.size() == 2) &&
54          "Expected a scope and optional inlined-at");
55 
56   // Set line and column.
57   assert(Column < (1u << 16) && "Expected 16-bit column");
58 
59   SubclassData32 = Line;
60   SubclassData16 = Column;
61 
62   setImplicitCode(ImplicitCode);
63 }
64 
65 static void adjustColumn(unsigned &Column) {
66   // Set to unknown on overflow.  We only have 16 bits to play with here.
67   if (Column >= (1u << 16))
68     Column = 0;
69 }
70 
71 DILocation *DILocation::getImpl(LLVMContext &Context, unsigned Line,
72                                 unsigned Column, Metadata *Scope,
73                                 Metadata *InlinedAt, bool ImplicitCode,
74                                 StorageType Storage, bool ShouldCreate) {
75   // Fixup column.
76   adjustColumn(Column);
77 
78   if (Storage == Uniqued) {
79     if (auto *N = getUniqued(Context.pImpl->DILocations,
80                              DILocationInfo::KeyTy(Line, Column, Scope,
81                                                    InlinedAt, ImplicitCode)))
82       return N;
83     if (!ShouldCreate)
84       return nullptr;
85   } else {
86     assert(ShouldCreate && "Expected non-uniqued nodes to always be created");
87   }
88 
89   SmallVector<Metadata *, 2> Ops;
90   Ops.push_back(Scope);
91   if (InlinedAt)
92     Ops.push_back(InlinedAt);
93   return storeImpl(new (Ops.size(), Storage) DILocation(
94                        Context, Storage, Line, Column, Ops, ImplicitCode),
95                    Storage, Context.pImpl->DILocations);
96 }
97 
98 DILocation *DILocation::getMergedLocations(ArrayRef<DILocation *> Locs) {
99   if (Locs.empty())
100     return nullptr;
101   if (Locs.size() == 1)
102     return Locs[0];
103   auto *Merged = Locs[0];
104   for (DILocation *L : llvm::drop_begin(Locs)) {
105     Merged = getMergedLocation(Merged, L);
106     if (Merged == nullptr)
107       break;
108   }
109   return Merged;
110 }
111 
112 DILocation *DILocation::getMergedLocation(DILocation *LocA, DILocation *LocB) {
113   if (!LocA || !LocB)
114     return nullptr;
115 
116   if (LocA == LocB)
117     return LocA;
118 
119   LLVMContext &C = LocA->getContext();
120 
121   using LocVec = SmallVector<const DILocation *>;
122   LocVec ALocs;
123   LocVec BLocs;
124   SmallDenseMap<std::pair<const DISubprogram *, const DILocation *>, unsigned,
125                 4>
126       ALookup;
127 
128   // Walk through LocA and its inlined-at locations, populate them in ALocs and
129   // save the index for the subprogram and inlined-at pair, which we use to find
130   // a matching starting location in LocB's chain.
131   for (auto [L, I] = std::make_pair(LocA, 0U); L; L = L->getInlinedAt(), I++) {
132     ALocs.push_back(L);
133     auto Res = ALookup.try_emplace(
134         {L->getScope()->getSubprogram(), L->getInlinedAt()}, I);
135     assert(Res.second && "Multiple <SP, InlinedAt> pairs in a location chain?");
136     (void)Res;
137   }
138 
139   LocVec::reverse_iterator ARIt = ALocs.rend();
140   LocVec::reverse_iterator BRIt = BLocs.rend();
141 
142   // Populate BLocs and look for a matching starting location, the first
143   // location with the same subprogram and inlined-at location as in LocA's
144   // chain. Since the two locations have the same inlined-at location we do
145   // not need to look at those parts of the chains.
146   for (auto [L, I] = std::make_pair(LocB, 0U); L; L = L->getInlinedAt(), I++) {
147     BLocs.push_back(L);
148 
149     if (ARIt != ALocs.rend())
150       // We have already found a matching starting location.
151       continue;
152 
153     auto IT = ALookup.find({L->getScope()->getSubprogram(), L->getInlinedAt()});
154     if (IT == ALookup.end())
155       continue;
156 
157     // The + 1 is to account for the &*rev_it = &(it - 1) relationship.
158     ARIt = LocVec::reverse_iterator(ALocs.begin() + IT->second + 1);
159     BRIt = LocVec::reverse_iterator(BLocs.begin() + I + 1);
160 
161     // If we have found a matching starting location we do not need to add more
162     // locations to BLocs, since we will only look at location pairs preceding
163     // the matching starting location, and adding more elements to BLocs could
164     // invalidate the iterator that we initialized here.
165     break;
166   }
167 
168   // Merge the two locations if possible, using the supplied
169   // inlined-at location for the created location.
170   auto MergeLocPair = [&C](const DILocation *L1, const DILocation *L2,
171                            DILocation *InlinedAt) -> DILocation * {
172     if (L1 == L2)
173       return DILocation::get(C, L1->getLine(), L1->getColumn(), L1->getScope(),
174                              InlinedAt);
175 
176     // If the locations originate from different subprograms we can't produce
177     // a common location.
178     if (L1->getScope()->getSubprogram() != L2->getScope()->getSubprogram())
179       return nullptr;
180 
181     // Return the nearest common scope inside a subprogram.
182     auto GetNearestCommonScope = [](DIScope *S1, DIScope *S2) -> DIScope * {
183       SmallPtrSet<DIScope *, 8> Scopes;
184       for (; S1; S1 = S1->getScope()) {
185         Scopes.insert(S1);
186         if (isa<DISubprogram>(S1))
187           break;
188       }
189 
190       for (; S2; S2 = S2->getScope()) {
191         if (Scopes.count(S2))
192           return S2;
193         if (isa<DISubprogram>(S2))
194           break;
195       }
196 
197       return nullptr;
198     };
199 
200     auto Scope = GetNearestCommonScope(L1->getScope(), L2->getScope());
201     assert(Scope && "No common scope in the same subprogram?");
202 
203     bool SameLine = L1->getLine() == L2->getLine();
204     bool SameCol = L1->getColumn() == L2->getColumn();
205     unsigned Line = SameLine ? L1->getLine() : 0;
206     unsigned Col = SameLine && SameCol ? L1->getColumn() : 0;
207 
208     return DILocation::get(C, Line, Col, Scope, InlinedAt);
209   };
210 
211   DILocation *Result = ARIt != ALocs.rend() ? (*ARIt)->getInlinedAt() : nullptr;
212 
213   // If we have found a common starting location, walk up the inlined-at chains
214   // and try to produce common locations.
215   for (; ARIt != ALocs.rend() && BRIt != BLocs.rend(); ++ARIt, ++BRIt) {
216     DILocation *Tmp = MergeLocPair(*ARIt, *BRIt, Result);
217 
218     if (!Tmp)
219       // We have walked up to a point in the chains where the two locations
220       // are irreconsilable. At this point Result contains the nearest common
221       // location in the inlined-at chains of LocA and LocB, so we break here.
222       break;
223 
224     Result = Tmp;
225   }
226 
227   if (Result)
228     return Result;
229 
230   // We ended up with LocA and LocB as irreconsilable locations. Produce a
231   // location at 0:0 with one of the locations' scope. The function has
232   // historically picked A's scope, and a nullptr inlined-at location, so that
233   // behavior is mimicked here but I am not sure if this is always the correct
234   // way to handle this.
235   return DILocation::get(C, 0, 0, LocA->getScope(), nullptr);
236 }
237 
238 std::optional<unsigned>
239 DILocation::encodeDiscriminator(unsigned BD, unsigned DF, unsigned CI) {
240   std::array<unsigned, 3> Components = {BD, DF, CI};
241   uint64_t RemainingWork = 0U;
242   // We use RemainingWork to figure out if we have no remaining components to
243   // encode. For example: if BD != 0 but DF == 0 && CI == 0, we don't need to
244   // encode anything for the latter 2.
245   // Since any of the input components is at most 32 bits, their sum will be
246   // less than 34 bits, and thus RemainingWork won't overflow.
247   RemainingWork =
248       std::accumulate(Components.begin(), Components.end(), RemainingWork);
249 
250   int I = 0;
251   unsigned Ret = 0;
252   unsigned NextBitInsertionIndex = 0;
253   while (RemainingWork > 0) {
254     unsigned C = Components[I++];
255     RemainingWork -= C;
256     unsigned EC = encodeComponent(C);
257     Ret |= (EC << NextBitInsertionIndex);
258     NextBitInsertionIndex += encodingBits(C);
259   }
260 
261   // Encoding may be unsuccessful because of overflow. We determine success by
262   // checking equivalence of components before & after encoding. Alternatively,
263   // we could determine Success during encoding, but the current alternative is
264   // simpler.
265   unsigned TBD, TDF, TCI = 0;
266   decodeDiscriminator(Ret, TBD, TDF, TCI);
267   if (TBD == BD && TDF == DF && TCI == CI)
268     return Ret;
269   return std::nullopt;
270 }
271 
272 void DILocation::decodeDiscriminator(unsigned D, unsigned &BD, unsigned &DF,
273                                      unsigned &CI) {
274   BD = getUnsignedFromPrefixEncoding(D);
275   DF = getUnsignedFromPrefixEncoding(getNextComponentInDiscriminator(D));
276   CI = getUnsignedFromPrefixEncoding(
277       getNextComponentInDiscriminator(getNextComponentInDiscriminator(D)));
278 }
279 dwarf::Tag DINode::getTag() const { return (dwarf::Tag)SubclassData16; }
280 
281 DINode::DIFlags DINode::getFlag(StringRef Flag) {
282   return StringSwitch<DIFlags>(Flag)
283 #define HANDLE_DI_FLAG(ID, NAME) .Case("DIFlag" #NAME, Flag##NAME)
284 #include "llvm/IR/DebugInfoFlags.def"
285       .Default(DINode::FlagZero);
286 }
287 
288 StringRef DINode::getFlagString(DIFlags Flag) {
289   switch (Flag) {
290 #define HANDLE_DI_FLAG(ID, NAME)                                               \
291   case Flag##NAME:                                                             \
292     return "DIFlag" #NAME;
293 #include "llvm/IR/DebugInfoFlags.def"
294   }
295   return "";
296 }
297 
298 DINode::DIFlags DINode::splitFlags(DIFlags Flags,
299                                    SmallVectorImpl<DIFlags> &SplitFlags) {
300   // Flags that are packed together need to be specially handled, so
301   // that, for example, we emit "DIFlagPublic" and not
302   // "DIFlagPrivate | DIFlagProtected".
303   if (DIFlags A = Flags & FlagAccessibility) {
304     if (A == FlagPrivate)
305       SplitFlags.push_back(FlagPrivate);
306     else if (A == FlagProtected)
307       SplitFlags.push_back(FlagProtected);
308     else
309       SplitFlags.push_back(FlagPublic);
310     Flags &= ~A;
311   }
312   if (DIFlags R = Flags & FlagPtrToMemberRep) {
313     if (R == FlagSingleInheritance)
314       SplitFlags.push_back(FlagSingleInheritance);
315     else if (R == FlagMultipleInheritance)
316       SplitFlags.push_back(FlagMultipleInheritance);
317     else
318       SplitFlags.push_back(FlagVirtualInheritance);
319     Flags &= ~R;
320   }
321   if ((Flags & FlagIndirectVirtualBase) == FlagIndirectVirtualBase) {
322     Flags &= ~FlagIndirectVirtualBase;
323     SplitFlags.push_back(FlagIndirectVirtualBase);
324   }
325 
326 #define HANDLE_DI_FLAG(ID, NAME)                                               \
327   if (DIFlags Bit = Flags & Flag##NAME) {                                      \
328     SplitFlags.push_back(Bit);                                                 \
329     Flags &= ~Bit;                                                             \
330   }
331 #include "llvm/IR/DebugInfoFlags.def"
332   return Flags;
333 }
334 
335 DIScope *DIScope::getScope() const {
336   if (auto *T = dyn_cast<DIType>(this))
337     return T->getScope();
338 
339   if (auto *SP = dyn_cast<DISubprogram>(this))
340     return SP->getScope();
341 
342   if (auto *LB = dyn_cast<DILexicalBlockBase>(this))
343     return LB->getScope();
344 
345   if (auto *NS = dyn_cast<DINamespace>(this))
346     return NS->getScope();
347 
348   if (auto *CB = dyn_cast<DICommonBlock>(this))
349     return CB->getScope();
350 
351   if (auto *M = dyn_cast<DIModule>(this))
352     return M->getScope();
353 
354   assert((isa<DIFile>(this) || isa<DICompileUnit>(this)) &&
355          "Unhandled type of scope.");
356   return nullptr;
357 }
358 
359 StringRef DIScope::getName() const {
360   if (auto *T = dyn_cast<DIType>(this))
361     return T->getName();
362   if (auto *SP = dyn_cast<DISubprogram>(this))
363     return SP->getName();
364   if (auto *NS = dyn_cast<DINamespace>(this))
365     return NS->getName();
366   if (auto *CB = dyn_cast<DICommonBlock>(this))
367     return CB->getName();
368   if (auto *M = dyn_cast<DIModule>(this))
369     return M->getName();
370   assert((isa<DILexicalBlockBase>(this) || isa<DIFile>(this) ||
371           isa<DICompileUnit>(this)) &&
372          "Unhandled type of scope.");
373   return "";
374 }
375 
376 #ifndef NDEBUG
377 static bool isCanonical(const MDString *S) {
378   return !S || !S->getString().empty();
379 }
380 #endif
381 
382 dwarf::Tag GenericDINode::getTag() const { return (dwarf::Tag)SubclassData16; }
383 GenericDINode *GenericDINode::getImpl(LLVMContext &Context, unsigned Tag,
384                                       MDString *Header,
385                                       ArrayRef<Metadata *> DwarfOps,
386                                       StorageType Storage, bool ShouldCreate) {
387   unsigned Hash = 0;
388   if (Storage == Uniqued) {
389     GenericDINodeInfo::KeyTy Key(Tag, Header, DwarfOps);
390     if (auto *N = getUniqued(Context.pImpl->GenericDINodes, Key))
391       return N;
392     if (!ShouldCreate)
393       return nullptr;
394     Hash = Key.getHash();
395   } else {
396     assert(ShouldCreate && "Expected non-uniqued nodes to always be created");
397   }
398 
399   // Use a nullptr for empty headers.
400   assert(isCanonical(Header) && "Expected canonical MDString");
401   Metadata *PreOps[] = {Header};
402   return storeImpl(new (DwarfOps.size() + 1, Storage) GenericDINode(
403                        Context, Storage, Hash, Tag, PreOps, DwarfOps),
404                    Storage, Context.pImpl->GenericDINodes);
405 }
406 
407 void GenericDINode::recalculateHash() {
408   setHash(GenericDINodeInfo::KeyTy::calculateHash(this));
409 }
410 
411 #define UNWRAP_ARGS_IMPL(...) __VA_ARGS__
412 #define UNWRAP_ARGS(ARGS) UNWRAP_ARGS_IMPL ARGS
413 #define DEFINE_GETIMPL_LOOKUP(CLASS, ARGS)                                     \
414   do {                                                                         \
415     if (Storage == Uniqued) {                                                  \
416       if (auto *N = getUniqued(Context.pImpl->CLASS##s,                        \
417                                CLASS##Info::KeyTy(UNWRAP_ARGS(ARGS))))         \
418         return N;                                                              \
419       if (!ShouldCreate)                                                       \
420         return nullptr;                                                        \
421     } else {                                                                   \
422       assert(ShouldCreate &&                                                   \
423              "Expected non-uniqued nodes to always be created");               \
424     }                                                                          \
425   } while (false)
426 #define DEFINE_GETIMPL_STORE(CLASS, ARGS, OPS)                                 \
427   return storeImpl(new (std::size(OPS), Storage)                               \
428                        CLASS(Context, Storage, UNWRAP_ARGS(ARGS), OPS),        \
429                    Storage, Context.pImpl->CLASS##s)
430 #define DEFINE_GETIMPL_STORE_NO_OPS(CLASS, ARGS)                               \
431   return storeImpl(new (0u, Storage)                                           \
432                        CLASS(Context, Storage, UNWRAP_ARGS(ARGS)),             \
433                    Storage, Context.pImpl->CLASS##s)
434 #define DEFINE_GETIMPL_STORE_NO_CONSTRUCTOR_ARGS(CLASS, OPS)                   \
435   return storeImpl(new (std::size(OPS), Storage) CLASS(Context, Storage, OPS), \
436                    Storage, Context.pImpl->CLASS##s)
437 #define DEFINE_GETIMPL_STORE_N(CLASS, ARGS, OPS, NUM_OPS)                      \
438   return storeImpl(new (NUM_OPS, Storage)                                      \
439                        CLASS(Context, Storage, UNWRAP_ARGS(ARGS), OPS),        \
440                    Storage, Context.pImpl->CLASS##s)
441 
442 DISubrange::DISubrange(LLVMContext &C, StorageType Storage,
443                        ArrayRef<Metadata *> Ops)
444     : DINode(C, DISubrangeKind, Storage, dwarf::DW_TAG_subrange_type, Ops) {}
445 DISubrange *DISubrange::getImpl(LLVMContext &Context, int64_t Count, int64_t Lo,
446                                 StorageType Storage, bool ShouldCreate) {
447   auto *CountNode = ConstantAsMetadata::get(
448       ConstantInt::getSigned(Type::getInt64Ty(Context), Count));
449   auto *LB = ConstantAsMetadata::get(
450       ConstantInt::getSigned(Type::getInt64Ty(Context), Lo));
451   return getImpl(Context, CountNode, LB, nullptr, nullptr, Storage,
452                  ShouldCreate);
453 }
454 
455 DISubrange *DISubrange::getImpl(LLVMContext &Context, Metadata *CountNode,
456                                 int64_t Lo, StorageType Storage,
457                                 bool ShouldCreate) {
458   auto *LB = ConstantAsMetadata::get(
459       ConstantInt::getSigned(Type::getInt64Ty(Context), Lo));
460   return getImpl(Context, CountNode, LB, nullptr, nullptr, Storage,
461                  ShouldCreate);
462 }
463 
464 DISubrange *DISubrange::getImpl(LLVMContext &Context, Metadata *CountNode,
465                                 Metadata *LB, Metadata *UB, Metadata *Stride,
466                                 StorageType Storage, bool ShouldCreate) {
467   DEFINE_GETIMPL_LOOKUP(DISubrange, (CountNode, LB, UB, Stride));
468   Metadata *Ops[] = {CountNode, LB, UB, Stride};
469   DEFINE_GETIMPL_STORE_NO_CONSTRUCTOR_ARGS(DISubrange, Ops);
470 }
471 
472 DISubrange::BoundType DISubrange::getCount() const {
473   Metadata *CB = getRawCountNode();
474   if (!CB)
475     return BoundType();
476 
477   assert((isa<ConstantAsMetadata>(CB) || isa<DIVariable>(CB) ||
478           isa<DIExpression>(CB)) &&
479          "Count must be signed constant or DIVariable or DIExpression");
480 
481   if (auto *MD = dyn_cast<ConstantAsMetadata>(CB))
482     return BoundType(cast<ConstantInt>(MD->getValue()));
483 
484   if (auto *MD = dyn_cast<DIVariable>(CB))
485     return BoundType(MD);
486 
487   if (auto *MD = dyn_cast<DIExpression>(CB))
488     return BoundType(MD);
489 
490   return BoundType();
491 }
492 
493 DISubrange::BoundType DISubrange::getLowerBound() const {
494   Metadata *LB = getRawLowerBound();
495   if (!LB)
496     return BoundType();
497 
498   assert((isa<ConstantAsMetadata>(LB) || isa<DIVariable>(LB) ||
499           isa<DIExpression>(LB)) &&
500          "LowerBound must be signed constant or DIVariable or DIExpression");
501 
502   if (auto *MD = dyn_cast<ConstantAsMetadata>(LB))
503     return BoundType(cast<ConstantInt>(MD->getValue()));
504 
505   if (auto *MD = dyn_cast<DIVariable>(LB))
506     return BoundType(MD);
507 
508   if (auto *MD = dyn_cast<DIExpression>(LB))
509     return BoundType(MD);
510 
511   return BoundType();
512 }
513 
514 DISubrange::BoundType DISubrange::getUpperBound() const {
515   Metadata *UB = getRawUpperBound();
516   if (!UB)
517     return BoundType();
518 
519   assert((isa<ConstantAsMetadata>(UB) || isa<DIVariable>(UB) ||
520           isa<DIExpression>(UB)) &&
521          "UpperBound must be signed constant or DIVariable or DIExpression");
522 
523   if (auto *MD = dyn_cast<ConstantAsMetadata>(UB))
524     return BoundType(cast<ConstantInt>(MD->getValue()));
525 
526   if (auto *MD = dyn_cast<DIVariable>(UB))
527     return BoundType(MD);
528 
529   if (auto *MD = dyn_cast<DIExpression>(UB))
530     return BoundType(MD);
531 
532   return BoundType();
533 }
534 
535 DISubrange::BoundType DISubrange::getStride() const {
536   Metadata *ST = getRawStride();
537   if (!ST)
538     return BoundType();
539 
540   assert((isa<ConstantAsMetadata>(ST) || isa<DIVariable>(ST) ||
541           isa<DIExpression>(ST)) &&
542          "Stride must be signed constant or DIVariable or DIExpression");
543 
544   if (auto *MD = dyn_cast<ConstantAsMetadata>(ST))
545     return BoundType(cast<ConstantInt>(MD->getValue()));
546 
547   if (auto *MD = dyn_cast<DIVariable>(ST))
548     return BoundType(MD);
549 
550   if (auto *MD = dyn_cast<DIExpression>(ST))
551     return BoundType(MD);
552 
553   return BoundType();
554 }
555 DIGenericSubrange::DIGenericSubrange(LLVMContext &C, StorageType Storage,
556                                      ArrayRef<Metadata *> Ops)
557     : DINode(C, DIGenericSubrangeKind, Storage, dwarf::DW_TAG_generic_subrange,
558              Ops) {}
559 
560 DIGenericSubrange *DIGenericSubrange::getImpl(LLVMContext &Context,
561                                               Metadata *CountNode, Metadata *LB,
562                                               Metadata *UB, Metadata *Stride,
563                                               StorageType Storage,
564                                               bool ShouldCreate) {
565   DEFINE_GETIMPL_LOOKUP(DIGenericSubrange, (CountNode, LB, UB, Stride));
566   Metadata *Ops[] = {CountNode, LB, UB, Stride};
567   DEFINE_GETIMPL_STORE_NO_CONSTRUCTOR_ARGS(DIGenericSubrange, Ops);
568 }
569 
570 DIGenericSubrange::BoundType DIGenericSubrange::getCount() const {
571   Metadata *CB = getRawCountNode();
572   if (!CB)
573     return BoundType();
574 
575   assert((isa<DIVariable>(CB) || isa<DIExpression>(CB)) &&
576          "Count must be signed constant or DIVariable or DIExpression");
577 
578   if (auto *MD = dyn_cast<DIVariable>(CB))
579     return BoundType(MD);
580 
581   if (auto *MD = dyn_cast<DIExpression>(CB))
582     return BoundType(MD);
583 
584   return BoundType();
585 }
586 
587 DIGenericSubrange::BoundType DIGenericSubrange::getLowerBound() const {
588   Metadata *LB = getRawLowerBound();
589   if (!LB)
590     return BoundType();
591 
592   assert((isa<DIVariable>(LB) || isa<DIExpression>(LB)) &&
593          "LowerBound must be signed constant or DIVariable or DIExpression");
594 
595   if (auto *MD = dyn_cast<DIVariable>(LB))
596     return BoundType(MD);
597 
598   if (auto *MD = dyn_cast<DIExpression>(LB))
599     return BoundType(MD);
600 
601   return BoundType();
602 }
603 
604 DIGenericSubrange::BoundType DIGenericSubrange::getUpperBound() const {
605   Metadata *UB = getRawUpperBound();
606   if (!UB)
607     return BoundType();
608 
609   assert((isa<DIVariable>(UB) || isa<DIExpression>(UB)) &&
610          "UpperBound must be signed constant or DIVariable or DIExpression");
611 
612   if (auto *MD = dyn_cast<DIVariable>(UB))
613     return BoundType(MD);
614 
615   if (auto *MD = dyn_cast<DIExpression>(UB))
616     return BoundType(MD);
617 
618   return BoundType();
619 }
620 
621 DIGenericSubrange::BoundType DIGenericSubrange::getStride() const {
622   Metadata *ST = getRawStride();
623   if (!ST)
624     return BoundType();
625 
626   assert((isa<DIVariable>(ST) || isa<DIExpression>(ST)) &&
627          "Stride must be signed constant or DIVariable or DIExpression");
628 
629   if (auto *MD = dyn_cast<DIVariable>(ST))
630     return BoundType(MD);
631 
632   if (auto *MD = dyn_cast<DIExpression>(ST))
633     return BoundType(MD);
634 
635   return BoundType();
636 }
637 
638 DIEnumerator::DIEnumerator(LLVMContext &C, StorageType Storage,
639                            const APInt &Value, bool IsUnsigned,
640                            ArrayRef<Metadata *> Ops)
641     : DINode(C, DIEnumeratorKind, Storage, dwarf::DW_TAG_enumerator, Ops),
642       Value(Value) {
643   SubclassData32 = IsUnsigned;
644 }
645 DIEnumerator *DIEnumerator::getImpl(LLVMContext &Context, const APInt &Value,
646                                     bool IsUnsigned, MDString *Name,
647                                     StorageType Storage, bool ShouldCreate) {
648   assert(isCanonical(Name) && "Expected canonical MDString");
649   DEFINE_GETIMPL_LOOKUP(DIEnumerator, (Value, IsUnsigned, Name));
650   Metadata *Ops[] = {Name};
651   DEFINE_GETIMPL_STORE(DIEnumerator, (Value, IsUnsigned), Ops);
652 }
653 
654 DIBasicType *DIBasicType::getImpl(LLVMContext &Context, unsigned Tag,
655                                   MDString *Name, uint64_t SizeInBits,
656                                   uint32_t AlignInBits, unsigned Encoding,
657                                   DIFlags Flags, StorageType Storage,
658                                   bool ShouldCreate) {
659   assert(isCanonical(Name) && "Expected canonical MDString");
660   DEFINE_GETIMPL_LOOKUP(DIBasicType,
661                         (Tag, Name, SizeInBits, AlignInBits, Encoding, Flags));
662   Metadata *Ops[] = {nullptr, nullptr, Name};
663   DEFINE_GETIMPL_STORE(DIBasicType,
664                        (Tag, SizeInBits, AlignInBits, Encoding, Flags), Ops);
665 }
666 
667 std::optional<DIBasicType::Signedness> DIBasicType::getSignedness() const {
668   switch (getEncoding()) {
669   case dwarf::DW_ATE_signed:
670   case dwarf::DW_ATE_signed_char:
671     return Signedness::Signed;
672   case dwarf::DW_ATE_unsigned:
673   case dwarf::DW_ATE_unsigned_char:
674     return Signedness::Unsigned;
675   default:
676     return std::nullopt;
677   }
678 }
679 
680 DIStringType *DIStringType::getImpl(LLVMContext &Context, unsigned Tag,
681                                     MDString *Name, Metadata *StringLength,
682                                     Metadata *StringLengthExp,
683                                     Metadata *StringLocationExp,
684                                     uint64_t SizeInBits, uint32_t AlignInBits,
685                                     unsigned Encoding, StorageType Storage,
686                                     bool ShouldCreate) {
687   assert(isCanonical(Name) && "Expected canonical MDString");
688   DEFINE_GETIMPL_LOOKUP(DIStringType,
689                         (Tag, Name, StringLength, StringLengthExp,
690                          StringLocationExp, SizeInBits, AlignInBits, Encoding));
691   Metadata *Ops[] = {nullptr,      nullptr,         Name,
692                      StringLength, StringLengthExp, StringLocationExp};
693   DEFINE_GETIMPL_STORE(DIStringType, (Tag, SizeInBits, AlignInBits, Encoding),
694                        Ops);
695 }
696 DIType *DIDerivedType::getClassType() const {
697   assert(getTag() == dwarf::DW_TAG_ptr_to_member_type);
698   return cast_or_null<DIType>(getExtraData());
699 }
700 uint32_t DIDerivedType::getVBPtrOffset() const {
701   assert(getTag() == dwarf::DW_TAG_inheritance);
702   if (auto *CM = cast_or_null<ConstantAsMetadata>(getExtraData()))
703     if (auto *CI = dyn_cast_or_null<ConstantInt>(CM->getValue()))
704       return static_cast<uint32_t>(CI->getZExtValue());
705   return 0;
706 }
707 Constant *DIDerivedType::getStorageOffsetInBits() const {
708   assert(getTag() == dwarf::DW_TAG_member && isBitField());
709   if (auto *C = cast_or_null<ConstantAsMetadata>(getExtraData()))
710     return C->getValue();
711   return nullptr;
712 }
713 
714 Constant *DIDerivedType::getConstant() const {
715   assert(getTag() == dwarf::DW_TAG_member && isStaticMember());
716   if (auto *C = cast_or_null<ConstantAsMetadata>(getExtraData()))
717     return C->getValue();
718   return nullptr;
719 }
720 Constant *DIDerivedType::getDiscriminantValue() const {
721   assert(getTag() == dwarf::DW_TAG_member && !isStaticMember());
722   if (auto *C = cast_or_null<ConstantAsMetadata>(getExtraData()))
723     return C->getValue();
724   return nullptr;
725 }
726 
727 DIDerivedType *
728 DIDerivedType::getImpl(LLVMContext &Context, unsigned Tag, MDString *Name,
729                        Metadata *File, unsigned Line, Metadata *Scope,
730                        Metadata *BaseType, uint64_t SizeInBits,
731                        uint32_t AlignInBits, uint64_t OffsetInBits,
732                        std::optional<unsigned> DWARFAddressSpace, DIFlags Flags,
733                        Metadata *ExtraData, Metadata *Annotations,
734                        StorageType Storage, bool ShouldCreate) {
735   assert(isCanonical(Name) && "Expected canonical MDString");
736   DEFINE_GETIMPL_LOOKUP(DIDerivedType,
737                         (Tag, Name, File, Line, Scope, BaseType, SizeInBits,
738                          AlignInBits, OffsetInBits, DWARFAddressSpace, Flags,
739                          ExtraData, Annotations));
740   Metadata *Ops[] = {File, Scope, Name, BaseType, ExtraData, Annotations};
741   DEFINE_GETIMPL_STORE(DIDerivedType,
742                        (Tag, Line, SizeInBits, AlignInBits, OffsetInBits,
743                         DWARFAddressSpace, Flags),
744                        Ops);
745 }
746 
747 DICompositeType *DICompositeType::getImpl(
748     LLVMContext &Context, unsigned Tag, MDString *Name, Metadata *File,
749     unsigned Line, Metadata *Scope, Metadata *BaseType, uint64_t SizeInBits,
750     uint32_t AlignInBits, uint64_t OffsetInBits, DIFlags Flags,
751     Metadata *Elements, unsigned RuntimeLang, Metadata *VTableHolder,
752     Metadata *TemplateParams, MDString *Identifier, Metadata *Discriminator,
753     Metadata *DataLocation, Metadata *Associated, Metadata *Allocated,
754     Metadata *Rank, Metadata *Annotations, StorageType Storage,
755     bool ShouldCreate) {
756   assert(isCanonical(Name) && "Expected canonical MDString");
757 
758   // Keep this in sync with buildODRType.
759   DEFINE_GETIMPL_LOOKUP(DICompositeType,
760                         (Tag, Name, File, Line, Scope, BaseType, SizeInBits,
761                          AlignInBits, OffsetInBits, Flags, Elements,
762                          RuntimeLang, VTableHolder, TemplateParams, Identifier,
763                          Discriminator, DataLocation, Associated, Allocated,
764                          Rank, Annotations));
765   Metadata *Ops[] = {File,          Scope,        Name,           BaseType,
766                      Elements,      VTableHolder, TemplateParams, Identifier,
767                      Discriminator, DataLocation, Associated,     Allocated,
768                      Rank,          Annotations};
769   DEFINE_GETIMPL_STORE(
770       DICompositeType,
771       (Tag, Line, RuntimeLang, SizeInBits, AlignInBits, OffsetInBits, Flags),
772       Ops);
773 }
774 
775 DICompositeType *DICompositeType::buildODRType(
776     LLVMContext &Context, MDString &Identifier, unsigned Tag, MDString *Name,
777     Metadata *File, unsigned Line, Metadata *Scope, Metadata *BaseType,
778     uint64_t SizeInBits, uint32_t AlignInBits, uint64_t OffsetInBits,
779     DIFlags Flags, Metadata *Elements, unsigned RuntimeLang,
780     Metadata *VTableHolder, Metadata *TemplateParams, Metadata *Discriminator,
781     Metadata *DataLocation, Metadata *Associated, Metadata *Allocated,
782     Metadata *Rank, Metadata *Annotations) {
783   assert(!Identifier.getString().empty() && "Expected valid identifier");
784   if (!Context.isODRUniquingDebugTypes())
785     return nullptr;
786   auto *&CT = (*Context.pImpl->DITypeMap)[&Identifier];
787   if (!CT)
788     return CT = DICompositeType::getDistinct(
789                Context, Tag, Name, File, Line, Scope, BaseType, SizeInBits,
790                AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang,
791                VTableHolder, TemplateParams, &Identifier, Discriminator,
792                DataLocation, Associated, Allocated, Rank, Annotations);
793 
794   if (CT->getTag() != Tag)
795     return nullptr;
796 
797   // Only mutate CT if it's a forward declaration and the new operands aren't.
798   assert(CT->getRawIdentifier() == &Identifier && "Wrong ODR identifier?");
799   if (!CT->isForwardDecl() || (Flags & DINode::FlagFwdDecl))
800     return CT;
801 
802   // Mutate CT in place.  Keep this in sync with getImpl.
803   CT->mutate(Tag, Line, RuntimeLang, SizeInBits, AlignInBits, OffsetInBits,
804              Flags);
805   Metadata *Ops[] = {File,          Scope,        Name,           BaseType,
806                      Elements,      VTableHolder, TemplateParams, &Identifier,
807                      Discriminator, DataLocation, Associated,     Allocated,
808                      Rank,          Annotations};
809   assert((std::end(Ops) - std::begin(Ops)) == (int)CT->getNumOperands() &&
810          "Mismatched number of operands");
811   for (unsigned I = 0, E = CT->getNumOperands(); I != E; ++I)
812     if (Ops[I] != CT->getOperand(I))
813       CT->setOperand(I, Ops[I]);
814   return CT;
815 }
816 
817 DICompositeType *DICompositeType::getODRType(
818     LLVMContext &Context, MDString &Identifier, unsigned Tag, MDString *Name,
819     Metadata *File, unsigned Line, Metadata *Scope, Metadata *BaseType,
820     uint64_t SizeInBits, uint32_t AlignInBits, uint64_t OffsetInBits,
821     DIFlags Flags, Metadata *Elements, unsigned RuntimeLang,
822     Metadata *VTableHolder, Metadata *TemplateParams, Metadata *Discriminator,
823     Metadata *DataLocation, Metadata *Associated, Metadata *Allocated,
824     Metadata *Rank, Metadata *Annotations) {
825   assert(!Identifier.getString().empty() && "Expected valid identifier");
826   if (!Context.isODRUniquingDebugTypes())
827     return nullptr;
828   auto *&CT = (*Context.pImpl->DITypeMap)[&Identifier];
829   if (!CT) {
830     CT = DICompositeType::getDistinct(
831         Context, Tag, Name, File, Line, Scope, BaseType, SizeInBits,
832         AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang, VTableHolder,
833         TemplateParams, &Identifier, Discriminator, DataLocation, Associated,
834         Allocated, Rank, Annotations);
835   } else {
836     if (CT->getTag() != Tag)
837       return nullptr;
838   }
839   return CT;
840 }
841 
842 DICompositeType *DICompositeType::getODRTypeIfExists(LLVMContext &Context,
843                                                      MDString &Identifier) {
844   assert(!Identifier.getString().empty() && "Expected valid identifier");
845   if (!Context.isODRUniquingDebugTypes())
846     return nullptr;
847   return Context.pImpl->DITypeMap->lookup(&Identifier);
848 }
849 DISubroutineType::DISubroutineType(LLVMContext &C, StorageType Storage,
850                                    DIFlags Flags, uint8_t CC,
851                                    ArrayRef<Metadata *> Ops)
852     : DIType(C, DISubroutineTypeKind, Storage, dwarf::DW_TAG_subroutine_type, 0,
853              0, 0, 0, Flags, Ops),
854       CC(CC) {}
855 
856 DISubroutineType *DISubroutineType::getImpl(LLVMContext &Context, DIFlags Flags,
857                                             uint8_t CC, Metadata *TypeArray,
858                                             StorageType Storage,
859                                             bool ShouldCreate) {
860   DEFINE_GETIMPL_LOOKUP(DISubroutineType, (Flags, CC, TypeArray));
861   Metadata *Ops[] = {nullptr, nullptr, nullptr, TypeArray};
862   DEFINE_GETIMPL_STORE(DISubroutineType, (Flags, CC), Ops);
863 }
864 
865 DIFile::DIFile(LLVMContext &C, StorageType Storage,
866                std::optional<ChecksumInfo<MDString *>> CS, MDString *Src,
867                ArrayRef<Metadata *> Ops)
868     : DIScope(C, DIFileKind, Storage, dwarf::DW_TAG_file_type, Ops),
869       Checksum(CS), Source(Src) {}
870 
871 // FIXME: Implement this string-enum correspondence with a .def file and macros,
872 // so that the association is explicit rather than implied.
873 static const char *ChecksumKindName[DIFile::CSK_Last] = {
874     "CSK_MD5",
875     "CSK_SHA1",
876     "CSK_SHA256",
877 };
878 
879 StringRef DIFile::getChecksumKindAsString(ChecksumKind CSKind) {
880   assert(CSKind <= DIFile::CSK_Last && "Invalid checksum kind");
881   // The first space was originally the CSK_None variant, which is now
882   // obsolete, but the space is still reserved in ChecksumKind, so we account
883   // for it here.
884   return ChecksumKindName[CSKind - 1];
885 }
886 
887 std::optional<DIFile::ChecksumKind>
888 DIFile::getChecksumKind(StringRef CSKindStr) {
889   return StringSwitch<std::optional<DIFile::ChecksumKind>>(CSKindStr)
890       .Case("CSK_MD5", DIFile::CSK_MD5)
891       .Case("CSK_SHA1", DIFile::CSK_SHA1)
892       .Case("CSK_SHA256", DIFile::CSK_SHA256)
893       .Default(std::nullopt);
894 }
895 
896 DIFile *DIFile::getImpl(LLVMContext &Context, MDString *Filename,
897                         MDString *Directory,
898                         std::optional<DIFile::ChecksumInfo<MDString *>> CS,
899                         MDString *Source, StorageType Storage,
900                         bool ShouldCreate) {
901   assert(isCanonical(Filename) && "Expected canonical MDString");
902   assert(isCanonical(Directory) && "Expected canonical MDString");
903   assert((!CS || isCanonical(CS->Value)) && "Expected canonical MDString");
904   // We do *NOT* expect Source to be a canonical MDString because nullptr
905   // means none, so we need something to represent the empty file.
906   DEFINE_GETIMPL_LOOKUP(DIFile, (Filename, Directory, CS, Source));
907   Metadata *Ops[] = {Filename, Directory, CS ? CS->Value : nullptr, Source};
908   DEFINE_GETIMPL_STORE(DIFile, (CS, Source), Ops);
909 }
910 DICompileUnit::DICompileUnit(LLVMContext &C, StorageType Storage,
911                              unsigned SourceLanguage, bool IsOptimized,
912                              unsigned RuntimeVersion, unsigned EmissionKind,
913                              uint64_t DWOId, bool SplitDebugInlining,
914                              bool DebugInfoForProfiling, unsigned NameTableKind,
915                              bool RangesBaseAddress, ArrayRef<Metadata *> Ops)
916     : DIScope(C, DICompileUnitKind, Storage, dwarf::DW_TAG_compile_unit, Ops),
917       SourceLanguage(SourceLanguage), IsOptimized(IsOptimized),
918       RuntimeVersion(RuntimeVersion), EmissionKind(EmissionKind), DWOId(DWOId),
919       SplitDebugInlining(SplitDebugInlining),
920       DebugInfoForProfiling(DebugInfoForProfiling),
921       NameTableKind(NameTableKind), RangesBaseAddress(RangesBaseAddress) {
922   assert(Storage != Uniqued);
923 }
924 
925 DICompileUnit *DICompileUnit::getImpl(
926     LLVMContext &Context, unsigned SourceLanguage, Metadata *File,
927     MDString *Producer, bool IsOptimized, MDString *Flags,
928     unsigned RuntimeVersion, MDString *SplitDebugFilename,
929     unsigned EmissionKind, Metadata *EnumTypes, Metadata *RetainedTypes,
930     Metadata *GlobalVariables, Metadata *ImportedEntities, Metadata *Macros,
931     uint64_t DWOId, bool SplitDebugInlining, bool DebugInfoForProfiling,
932     unsigned NameTableKind, bool RangesBaseAddress, MDString *SysRoot,
933     MDString *SDK, StorageType Storage, bool ShouldCreate) {
934   assert(Storage != Uniqued && "Cannot unique DICompileUnit");
935   assert(isCanonical(Producer) && "Expected canonical MDString");
936   assert(isCanonical(Flags) && "Expected canonical MDString");
937   assert(isCanonical(SplitDebugFilename) && "Expected canonical MDString");
938 
939   Metadata *Ops[] = {File,
940                      Producer,
941                      Flags,
942                      SplitDebugFilename,
943                      EnumTypes,
944                      RetainedTypes,
945                      GlobalVariables,
946                      ImportedEntities,
947                      Macros,
948                      SysRoot,
949                      SDK};
950   return storeImpl(new (std::size(Ops), Storage) DICompileUnit(
951                        Context, Storage, SourceLanguage, IsOptimized,
952                        RuntimeVersion, EmissionKind, DWOId, SplitDebugInlining,
953                        DebugInfoForProfiling, NameTableKind, RangesBaseAddress,
954                        Ops),
955                    Storage);
956 }
957 
958 std::optional<DICompileUnit::DebugEmissionKind>
959 DICompileUnit::getEmissionKind(StringRef Str) {
960   return StringSwitch<std::optional<DebugEmissionKind>>(Str)
961       .Case("NoDebug", NoDebug)
962       .Case("FullDebug", FullDebug)
963       .Case("LineTablesOnly", LineTablesOnly)
964       .Case("DebugDirectivesOnly", DebugDirectivesOnly)
965       .Default(std::nullopt);
966 }
967 
968 std::optional<DICompileUnit::DebugNameTableKind>
969 DICompileUnit::getNameTableKind(StringRef Str) {
970   return StringSwitch<std::optional<DebugNameTableKind>>(Str)
971       .Case("Default", DebugNameTableKind::Default)
972       .Case("GNU", DebugNameTableKind::GNU)
973       .Case("Apple", DebugNameTableKind::Apple)
974       .Case("None", DebugNameTableKind::None)
975       .Default(std::nullopt);
976 }
977 
978 const char *DICompileUnit::emissionKindString(DebugEmissionKind EK) {
979   switch (EK) {
980   case NoDebug:
981     return "NoDebug";
982   case FullDebug:
983     return "FullDebug";
984   case LineTablesOnly:
985     return "LineTablesOnly";
986   case DebugDirectivesOnly:
987     return "DebugDirectivesOnly";
988   }
989   return nullptr;
990 }
991 
992 const char *DICompileUnit::nameTableKindString(DebugNameTableKind NTK) {
993   switch (NTK) {
994   case DebugNameTableKind::Default:
995     return nullptr;
996   case DebugNameTableKind::GNU:
997     return "GNU";
998   case DebugNameTableKind::Apple:
999     return "Apple";
1000   case DebugNameTableKind::None:
1001     return "None";
1002   }
1003   return nullptr;
1004 }
1005 DISubprogram::DISubprogram(LLVMContext &C, StorageType Storage, unsigned Line,
1006                            unsigned ScopeLine, unsigned VirtualIndex,
1007                            int ThisAdjustment, DIFlags Flags, DISPFlags SPFlags,
1008                            ArrayRef<Metadata *> Ops)
1009     : DILocalScope(C, DISubprogramKind, Storage, dwarf::DW_TAG_subprogram, Ops),
1010       Line(Line), ScopeLine(ScopeLine), VirtualIndex(VirtualIndex),
1011       ThisAdjustment(ThisAdjustment), Flags(Flags), SPFlags(SPFlags) {
1012   static_assert(dwarf::DW_VIRTUALITY_max < 4, "Virtuality out of range");
1013 }
1014 DISubprogram::DISPFlags
1015 DISubprogram::toSPFlags(bool IsLocalToUnit, bool IsDefinition, bool IsOptimized,
1016                         unsigned Virtuality, bool IsMainSubprogram) {
1017   // We're assuming virtuality is the low-order field.
1018   static_assert(int(SPFlagVirtual) == int(dwarf::DW_VIRTUALITY_virtual) &&
1019                     int(SPFlagPureVirtual) ==
1020                         int(dwarf::DW_VIRTUALITY_pure_virtual),
1021                 "Virtuality constant mismatch");
1022   return static_cast<DISPFlags>(
1023       (Virtuality & SPFlagVirtuality) |
1024       (IsLocalToUnit ? SPFlagLocalToUnit : SPFlagZero) |
1025       (IsDefinition ? SPFlagDefinition : SPFlagZero) |
1026       (IsOptimized ? SPFlagOptimized : SPFlagZero) |
1027       (IsMainSubprogram ? SPFlagMainSubprogram : SPFlagZero));
1028 }
1029 
1030 DISubprogram *DILocalScope::getSubprogram() const {
1031   if (auto *Block = dyn_cast<DILexicalBlockBase>(this))
1032     return Block->getScope()->getSubprogram();
1033   return const_cast<DISubprogram *>(cast<DISubprogram>(this));
1034 }
1035 
1036 DILocalScope *DILocalScope::getNonLexicalBlockFileScope() const {
1037   if (auto *File = dyn_cast<DILexicalBlockFile>(this))
1038     return File->getScope()->getNonLexicalBlockFileScope();
1039   return const_cast<DILocalScope *>(this);
1040 }
1041 
1042 DILocalScope *DILocalScope::cloneScopeForSubprogram(
1043     DILocalScope &RootScope, DISubprogram &NewSP, LLVMContext &Ctx,
1044     DenseMap<const MDNode *, MDNode *> &Cache) {
1045   SmallVector<DIScope *> ScopeChain;
1046   DIScope *CachedResult = nullptr;
1047 
1048   for (DIScope *Scope = &RootScope; !isa<DISubprogram>(Scope);
1049        Scope = Scope->getScope()) {
1050     if (auto It = Cache.find(Scope); It != Cache.end()) {
1051       CachedResult = cast<DIScope>(It->second);
1052       break;
1053     }
1054     ScopeChain.push_back(Scope);
1055   }
1056 
1057   // Recreate the scope chain, bottom-up, starting at the new subprogram (or a
1058   // cached result).
1059   DIScope *UpdatedScope = CachedResult ? CachedResult : &NewSP;
1060   for (DIScope *ScopeToUpdate : reverse(ScopeChain)) {
1061     TempMDNode ClonedScope = ScopeToUpdate->clone();
1062     cast<DILexicalBlockBase>(*ClonedScope).replaceScope(UpdatedScope);
1063     UpdatedScope =
1064         cast<DIScope>(MDNode::replaceWithUniqued(std::move(ClonedScope)));
1065     Cache[ScopeToUpdate] = UpdatedScope;
1066   }
1067 
1068   return cast<DILocalScope>(UpdatedScope);
1069 }
1070 
1071 DISubprogram::DISPFlags DISubprogram::getFlag(StringRef Flag) {
1072   return StringSwitch<DISPFlags>(Flag)
1073 #define HANDLE_DISP_FLAG(ID, NAME) .Case("DISPFlag" #NAME, SPFlag##NAME)
1074 #include "llvm/IR/DebugInfoFlags.def"
1075       .Default(SPFlagZero);
1076 }
1077 
1078 StringRef DISubprogram::getFlagString(DISPFlags Flag) {
1079   switch (Flag) {
1080   // Appease a warning.
1081   case SPFlagVirtuality:
1082     return "";
1083 #define HANDLE_DISP_FLAG(ID, NAME)                                             \
1084   case SPFlag##NAME:                                                           \
1085     return "DISPFlag" #NAME;
1086 #include "llvm/IR/DebugInfoFlags.def"
1087   }
1088   return "";
1089 }
1090 
1091 DISubprogram::DISPFlags
1092 DISubprogram::splitFlags(DISPFlags Flags,
1093                          SmallVectorImpl<DISPFlags> &SplitFlags) {
1094   // Multi-bit fields can require special handling. In our case, however, the
1095   // only multi-bit field is virtuality, and all its values happen to be
1096   // single-bit values, so the right behavior just falls out.
1097 #define HANDLE_DISP_FLAG(ID, NAME)                                             \
1098   if (DISPFlags Bit = Flags & SPFlag##NAME) {                                  \
1099     SplitFlags.push_back(Bit);                                                 \
1100     Flags &= ~Bit;                                                             \
1101   }
1102 #include "llvm/IR/DebugInfoFlags.def"
1103   return Flags;
1104 }
1105 
1106 DISubprogram *DISubprogram::getImpl(
1107     LLVMContext &Context, Metadata *Scope, MDString *Name,
1108     MDString *LinkageName, Metadata *File, unsigned Line, Metadata *Type,
1109     unsigned ScopeLine, Metadata *ContainingType, unsigned VirtualIndex,
1110     int ThisAdjustment, DIFlags Flags, DISPFlags SPFlags, Metadata *Unit,
1111     Metadata *TemplateParams, Metadata *Declaration, Metadata *RetainedNodes,
1112     Metadata *ThrownTypes, Metadata *Annotations, MDString *TargetFuncName,
1113     StorageType Storage, bool ShouldCreate) {
1114   assert(isCanonical(Name) && "Expected canonical MDString");
1115   assert(isCanonical(LinkageName) && "Expected canonical MDString");
1116   assert(isCanonical(TargetFuncName) && "Expected canonical MDString");
1117   DEFINE_GETIMPL_LOOKUP(DISubprogram,
1118                         (Scope, Name, LinkageName, File, Line, Type, ScopeLine,
1119                          ContainingType, VirtualIndex, ThisAdjustment, Flags,
1120                          SPFlags, Unit, TemplateParams, Declaration,
1121                          RetainedNodes, ThrownTypes, Annotations,
1122                          TargetFuncName));
1123   SmallVector<Metadata *, 13> Ops = {
1124       File,           Scope,          Name,        LinkageName,
1125       Type,           Unit,           Declaration, RetainedNodes,
1126       ContainingType, TemplateParams, ThrownTypes, Annotations,
1127       TargetFuncName};
1128   if (!TargetFuncName) {
1129     Ops.pop_back();
1130     if (!Annotations) {
1131       Ops.pop_back();
1132       if (!ThrownTypes) {
1133         Ops.pop_back();
1134         if (!TemplateParams) {
1135           Ops.pop_back();
1136           if (!ContainingType)
1137             Ops.pop_back();
1138         }
1139       }
1140     }
1141   }
1142   DEFINE_GETIMPL_STORE_N(
1143       DISubprogram,
1144       (Line, ScopeLine, VirtualIndex, ThisAdjustment, Flags, SPFlags), Ops,
1145       Ops.size());
1146 }
1147 
1148 bool DISubprogram::describes(const Function *F) const {
1149   assert(F && "Invalid function");
1150   return F->getSubprogram() == this;
1151 }
1152 DILexicalBlockBase::DILexicalBlockBase(LLVMContext &C, unsigned ID,
1153                                        StorageType Storage,
1154                                        ArrayRef<Metadata *> Ops)
1155     : DILocalScope(C, ID, Storage, dwarf::DW_TAG_lexical_block, Ops) {}
1156 
1157 DILexicalBlock *DILexicalBlock::getImpl(LLVMContext &Context, Metadata *Scope,
1158                                         Metadata *File, unsigned Line,
1159                                         unsigned Column, StorageType Storage,
1160                                         bool ShouldCreate) {
1161   // Fixup column.
1162   adjustColumn(Column);
1163 
1164   assert(Scope && "Expected scope");
1165   DEFINE_GETIMPL_LOOKUP(DILexicalBlock, (Scope, File, Line, Column));
1166   Metadata *Ops[] = {File, Scope};
1167   DEFINE_GETIMPL_STORE(DILexicalBlock, (Line, Column), Ops);
1168 }
1169 
1170 DILexicalBlockFile *DILexicalBlockFile::getImpl(LLVMContext &Context,
1171                                                 Metadata *Scope, Metadata *File,
1172                                                 unsigned Discriminator,
1173                                                 StorageType Storage,
1174                                                 bool ShouldCreate) {
1175   assert(Scope && "Expected scope");
1176   DEFINE_GETIMPL_LOOKUP(DILexicalBlockFile, (Scope, File, Discriminator));
1177   Metadata *Ops[] = {File, Scope};
1178   DEFINE_GETIMPL_STORE(DILexicalBlockFile, (Discriminator), Ops);
1179 }
1180 
1181 DINamespace::DINamespace(LLVMContext &Context, StorageType Storage,
1182                          bool ExportSymbols, ArrayRef<Metadata *> Ops)
1183     : DIScope(Context, DINamespaceKind, Storage, dwarf::DW_TAG_namespace, Ops),
1184       ExportSymbols(ExportSymbols) {}
1185 DINamespace *DINamespace::getImpl(LLVMContext &Context, Metadata *Scope,
1186                                   MDString *Name, bool ExportSymbols,
1187                                   StorageType Storage, bool ShouldCreate) {
1188   assert(isCanonical(Name) && "Expected canonical MDString");
1189   DEFINE_GETIMPL_LOOKUP(DINamespace, (Scope, Name, ExportSymbols));
1190   // The nullptr is for DIScope's File operand. This should be refactored.
1191   Metadata *Ops[] = {nullptr, Scope, Name};
1192   DEFINE_GETIMPL_STORE(DINamespace, (ExportSymbols), Ops);
1193 }
1194 
1195 DICommonBlock::DICommonBlock(LLVMContext &Context, StorageType Storage,
1196                              unsigned LineNo, ArrayRef<Metadata *> Ops)
1197     : DIScope(Context, DICommonBlockKind, Storage, dwarf::DW_TAG_common_block,
1198               Ops),
1199       LineNo(LineNo) {}
1200 DICommonBlock *DICommonBlock::getImpl(LLVMContext &Context, Metadata *Scope,
1201                                       Metadata *Decl, MDString *Name,
1202                                       Metadata *File, unsigned LineNo,
1203                                       StorageType Storage, bool ShouldCreate) {
1204   assert(isCanonical(Name) && "Expected canonical MDString");
1205   DEFINE_GETIMPL_LOOKUP(DICommonBlock, (Scope, Decl, Name, File, LineNo));
1206   // The nullptr is for DIScope's File operand. This should be refactored.
1207   Metadata *Ops[] = {Scope, Decl, Name, File};
1208   DEFINE_GETIMPL_STORE(DICommonBlock, (LineNo), Ops);
1209 }
1210 
1211 DIModule::DIModule(LLVMContext &Context, StorageType Storage, unsigned LineNo,
1212                    bool IsDecl, ArrayRef<Metadata *> Ops)
1213     : DIScope(Context, DIModuleKind, Storage, dwarf::DW_TAG_module, Ops),
1214       LineNo(LineNo), IsDecl(IsDecl) {}
1215 DIModule *DIModule::getImpl(LLVMContext &Context, Metadata *File,
1216                             Metadata *Scope, MDString *Name,
1217                             MDString *ConfigurationMacros,
1218                             MDString *IncludePath, MDString *APINotesFile,
1219                             unsigned LineNo, bool IsDecl, StorageType Storage,
1220                             bool ShouldCreate) {
1221   assert(isCanonical(Name) && "Expected canonical MDString");
1222   DEFINE_GETIMPL_LOOKUP(DIModule, (File, Scope, Name, ConfigurationMacros,
1223                                    IncludePath, APINotesFile, LineNo, IsDecl));
1224   Metadata *Ops[] = {File,        Scope,       Name, ConfigurationMacros,
1225                      IncludePath, APINotesFile};
1226   DEFINE_GETIMPL_STORE(DIModule, (LineNo, IsDecl), Ops);
1227 }
1228 DITemplateTypeParameter::DITemplateTypeParameter(LLVMContext &Context,
1229                                                  StorageType Storage,
1230                                                  bool IsDefault,
1231                                                  ArrayRef<Metadata *> Ops)
1232     : DITemplateParameter(Context, DITemplateTypeParameterKind, Storage,
1233                           dwarf::DW_TAG_template_type_parameter, IsDefault,
1234                           Ops) {}
1235 
1236 DITemplateTypeParameter *
1237 DITemplateTypeParameter::getImpl(LLVMContext &Context, MDString *Name,
1238                                  Metadata *Type, bool isDefault,
1239                                  StorageType Storage, bool ShouldCreate) {
1240   assert(isCanonical(Name) && "Expected canonical MDString");
1241   DEFINE_GETIMPL_LOOKUP(DITemplateTypeParameter, (Name, Type, isDefault));
1242   Metadata *Ops[] = {Name, Type};
1243   DEFINE_GETIMPL_STORE(DITemplateTypeParameter, (isDefault), Ops);
1244 }
1245 
1246 DITemplateValueParameter *DITemplateValueParameter::getImpl(
1247     LLVMContext &Context, unsigned Tag, MDString *Name, Metadata *Type,
1248     bool isDefault, Metadata *Value, StorageType Storage, bool ShouldCreate) {
1249   assert(isCanonical(Name) && "Expected canonical MDString");
1250   DEFINE_GETIMPL_LOOKUP(DITemplateValueParameter,
1251                         (Tag, Name, Type, isDefault, Value));
1252   Metadata *Ops[] = {Name, Type, Value};
1253   DEFINE_GETIMPL_STORE(DITemplateValueParameter, (Tag, isDefault), Ops);
1254 }
1255 
1256 DIGlobalVariable *
1257 DIGlobalVariable::getImpl(LLVMContext &Context, Metadata *Scope, MDString *Name,
1258                           MDString *LinkageName, Metadata *File, unsigned Line,
1259                           Metadata *Type, bool IsLocalToUnit, bool IsDefinition,
1260                           Metadata *StaticDataMemberDeclaration,
1261                           Metadata *TemplateParams, uint32_t AlignInBits,
1262                           Metadata *Annotations, StorageType Storage,
1263                           bool ShouldCreate) {
1264   assert(isCanonical(Name) && "Expected canonical MDString");
1265   assert(isCanonical(LinkageName) && "Expected canonical MDString");
1266   DEFINE_GETIMPL_LOOKUP(
1267       DIGlobalVariable,
1268       (Scope, Name, LinkageName, File, Line, Type, IsLocalToUnit, IsDefinition,
1269        StaticDataMemberDeclaration, TemplateParams, AlignInBits, Annotations));
1270   Metadata *Ops[] = {Scope,
1271                      Name,
1272                      File,
1273                      Type,
1274                      Name,
1275                      LinkageName,
1276                      StaticDataMemberDeclaration,
1277                      TemplateParams,
1278                      Annotations};
1279   DEFINE_GETIMPL_STORE(DIGlobalVariable,
1280                        (Line, IsLocalToUnit, IsDefinition, AlignInBits), Ops);
1281 }
1282 
1283 DILocalVariable *
1284 DILocalVariable::getImpl(LLVMContext &Context, Metadata *Scope, MDString *Name,
1285                          Metadata *File, unsigned Line, Metadata *Type,
1286                          unsigned Arg, DIFlags Flags, uint32_t AlignInBits,
1287                          Metadata *Annotations, StorageType Storage,
1288                          bool ShouldCreate) {
1289   // 64K ought to be enough for any frontend.
1290   assert(Arg <= UINT16_MAX && "Expected argument number to fit in 16-bits");
1291 
1292   assert(Scope && "Expected scope");
1293   assert(isCanonical(Name) && "Expected canonical MDString");
1294   DEFINE_GETIMPL_LOOKUP(DILocalVariable, (Scope, Name, File, Line, Type, Arg,
1295                                           Flags, AlignInBits, Annotations));
1296   Metadata *Ops[] = {Scope, Name, File, Type, Annotations};
1297   DEFINE_GETIMPL_STORE(DILocalVariable, (Line, Arg, Flags, AlignInBits), Ops);
1298 }
1299 
1300 DIVariable::DIVariable(LLVMContext &C, unsigned ID, StorageType Storage,
1301                        signed Line, ArrayRef<Metadata *> Ops,
1302                        uint32_t AlignInBits)
1303     : DINode(C, ID, Storage, dwarf::DW_TAG_variable, Ops), Line(Line),
1304       AlignInBits(AlignInBits) {}
1305 std::optional<uint64_t> DIVariable::getSizeInBits() const {
1306   // This is used by the Verifier so be mindful of broken types.
1307   const Metadata *RawType = getRawType();
1308   while (RawType) {
1309     // Try to get the size directly.
1310     if (auto *T = dyn_cast<DIType>(RawType))
1311       if (uint64_t Size = T->getSizeInBits())
1312         return Size;
1313 
1314     if (auto *DT = dyn_cast<DIDerivedType>(RawType)) {
1315       // Look at the base type.
1316       RawType = DT->getRawBaseType();
1317       continue;
1318     }
1319 
1320     // Missing type or size.
1321     break;
1322   }
1323 
1324   // Fail gracefully.
1325   return std::nullopt;
1326 }
1327 
1328 DILabel::DILabel(LLVMContext &C, StorageType Storage, unsigned Line,
1329                  ArrayRef<Metadata *> Ops)
1330     : DINode(C, DILabelKind, Storage, dwarf::DW_TAG_label, Ops), Line(Line) {}
1331 DILabel *DILabel::getImpl(LLVMContext &Context, Metadata *Scope, MDString *Name,
1332                           Metadata *File, unsigned Line, StorageType Storage,
1333                           bool ShouldCreate) {
1334   assert(Scope && "Expected scope");
1335   assert(isCanonical(Name) && "Expected canonical MDString");
1336   DEFINE_GETIMPL_LOOKUP(DILabel, (Scope, Name, File, Line));
1337   Metadata *Ops[] = {Scope, Name, File};
1338   DEFINE_GETIMPL_STORE(DILabel, (Line), Ops);
1339 }
1340 
1341 DIExpression *DIExpression::getImpl(LLVMContext &Context,
1342                                     ArrayRef<uint64_t> Elements,
1343                                     StorageType Storage, bool ShouldCreate) {
1344   DEFINE_GETIMPL_LOOKUP(DIExpression, (Elements));
1345   DEFINE_GETIMPL_STORE_NO_OPS(DIExpression, (Elements));
1346 }
1347 bool DIExpression::isEntryValue() const {
1348   return getNumElements() > 0 && getElement(0) == dwarf::DW_OP_LLVM_entry_value;
1349 }
1350 bool DIExpression::startsWithDeref() const {
1351   return getNumElements() > 0 && getElement(0) == dwarf::DW_OP_deref;
1352 }
1353 bool DIExpression::isDeref() const {
1354   return getNumElements() == 1 && startsWithDeref();
1355 }
1356 
1357 DIAssignID *DIAssignID::getImpl(LLVMContext &Context, StorageType Storage,
1358                                 bool ShouldCreate) {
1359   // Uniqued DIAssignID are not supported as the instance address *is* the ID.
1360   assert(Storage != StorageType::Uniqued && "uniqued DIAssignID unsupported");
1361   return storeImpl(new (0u, Storage) DIAssignID(Context, Storage), Storage);
1362 }
1363 
1364 unsigned DIExpression::ExprOperand::getSize() const {
1365   uint64_t Op = getOp();
1366 
1367   if (Op >= dwarf::DW_OP_breg0 && Op <= dwarf::DW_OP_breg31)
1368     return 2;
1369 
1370   switch (Op) {
1371   case dwarf::DW_OP_LLVM_convert:
1372   case dwarf::DW_OP_LLVM_fragment:
1373   case dwarf::DW_OP_bregx:
1374     return 3;
1375   case dwarf::DW_OP_constu:
1376   case dwarf::DW_OP_consts:
1377   case dwarf::DW_OP_deref_size:
1378   case dwarf::DW_OP_plus_uconst:
1379   case dwarf::DW_OP_LLVM_tag_offset:
1380   case dwarf::DW_OP_LLVM_entry_value:
1381   case dwarf::DW_OP_LLVM_arg:
1382   case dwarf::DW_OP_regx:
1383     return 2;
1384   default:
1385     return 1;
1386   }
1387 }
1388 
1389 bool DIExpression::isValid() const {
1390   for (auto I = expr_op_begin(), E = expr_op_end(); I != E; ++I) {
1391     // Check that there's space for the operand.
1392     if (I->get() + I->getSize() > E->get())
1393       return false;
1394 
1395     uint64_t Op = I->getOp();
1396     if ((Op >= dwarf::DW_OP_reg0 && Op <= dwarf::DW_OP_reg31) ||
1397         (Op >= dwarf::DW_OP_breg0 && Op <= dwarf::DW_OP_breg31))
1398       return true;
1399 
1400     // Check that the operand is valid.
1401     switch (Op) {
1402     default:
1403       return false;
1404     case dwarf::DW_OP_LLVM_fragment:
1405       // A fragment operator must appear at the end.
1406       return I->get() + I->getSize() == E->get();
1407     case dwarf::DW_OP_stack_value: {
1408       // Must be the last one or followed by a DW_OP_LLVM_fragment.
1409       if (I->get() + I->getSize() == E->get())
1410         break;
1411       auto J = I;
1412       if ((++J)->getOp() != dwarf::DW_OP_LLVM_fragment)
1413         return false;
1414       break;
1415     }
1416     case dwarf::DW_OP_swap: {
1417       // Must be more than one implicit element on the stack.
1418 
1419       // FIXME: A better way to implement this would be to add a local variable
1420       // that keeps track of the stack depth and introduce something like a
1421       // DW_LLVM_OP_implicit_location as a placeholder for the location this
1422       // DIExpression is attached to, or else pass the number of implicit stack
1423       // elements into isValid.
1424       if (getNumElements() == 1)
1425         return false;
1426       break;
1427     }
1428     case dwarf::DW_OP_LLVM_entry_value: {
1429       // An entry value operator must appear at the beginning or immediately
1430       // following `DW_OP_LLVM_arg 0`, and the number of operations it cover can
1431       // currently only be 1, because we support only entry values of a simple
1432       // register location. One reason for this is that we currently can't
1433       // calculate the size of the resulting DWARF block for other expressions.
1434       auto FirstOp = expr_op_begin();
1435       if (FirstOp->getOp() == dwarf::DW_OP_LLVM_arg && FirstOp->getArg(0) == 0)
1436         ++FirstOp;
1437       return I->get() == FirstOp->get() && I->getArg(0) == 1;
1438     }
1439     case dwarf::DW_OP_LLVM_implicit_pointer:
1440     case dwarf::DW_OP_LLVM_convert:
1441     case dwarf::DW_OP_LLVM_arg:
1442     case dwarf::DW_OP_LLVM_tag_offset:
1443     case dwarf::DW_OP_constu:
1444     case dwarf::DW_OP_plus_uconst:
1445     case dwarf::DW_OP_plus:
1446     case dwarf::DW_OP_minus:
1447     case dwarf::DW_OP_mul:
1448     case dwarf::DW_OP_div:
1449     case dwarf::DW_OP_mod:
1450     case dwarf::DW_OP_or:
1451     case dwarf::DW_OP_and:
1452     case dwarf::DW_OP_xor:
1453     case dwarf::DW_OP_shl:
1454     case dwarf::DW_OP_shr:
1455     case dwarf::DW_OP_shra:
1456     case dwarf::DW_OP_deref:
1457     case dwarf::DW_OP_deref_size:
1458     case dwarf::DW_OP_xderef:
1459     case dwarf::DW_OP_lit0:
1460     case dwarf::DW_OP_not:
1461     case dwarf::DW_OP_dup:
1462     case dwarf::DW_OP_regx:
1463     case dwarf::DW_OP_bregx:
1464     case dwarf::DW_OP_push_object_address:
1465     case dwarf::DW_OP_over:
1466     case dwarf::DW_OP_consts:
1467     case dwarf::DW_OP_eq:
1468     case dwarf::DW_OP_ne:
1469     case dwarf::DW_OP_gt:
1470     case dwarf::DW_OP_ge:
1471     case dwarf::DW_OP_lt:
1472     case dwarf::DW_OP_le:
1473       break;
1474     }
1475   }
1476   return true;
1477 }
1478 
1479 bool DIExpression::isImplicit() const {
1480   if (!isValid())
1481     return false;
1482 
1483   if (getNumElements() == 0)
1484     return false;
1485 
1486   for (const auto &It : expr_ops()) {
1487     switch (It.getOp()) {
1488     default:
1489       break;
1490     case dwarf::DW_OP_stack_value:
1491     case dwarf::DW_OP_LLVM_tag_offset:
1492       return true;
1493     }
1494   }
1495 
1496   return false;
1497 }
1498 
1499 bool DIExpression::isComplex() const {
1500   if (!isValid())
1501     return false;
1502 
1503   if (getNumElements() == 0)
1504     return false;
1505 
1506   // If there are any elements other than fragment or tag_offset, then some
1507   // kind of complex computation occurs.
1508   for (const auto &It : expr_ops()) {
1509     switch (It.getOp()) {
1510     case dwarf::DW_OP_LLVM_tag_offset:
1511     case dwarf::DW_OP_LLVM_fragment:
1512     case dwarf::DW_OP_LLVM_arg:
1513       continue;
1514     default:
1515       return true;
1516     }
1517   }
1518 
1519   return false;
1520 }
1521 
1522 bool DIExpression::isSingleLocationExpression() const {
1523   if (!isValid())
1524     return false;
1525 
1526   if (getNumElements() == 0)
1527     return true;
1528 
1529   auto ExprOpBegin = expr_ops().begin();
1530   auto ExprOpEnd = expr_ops().end();
1531   if (ExprOpBegin->getOp() == dwarf::DW_OP_LLVM_arg)
1532     ++ExprOpBegin;
1533 
1534   return !std::any_of(ExprOpBegin, ExprOpEnd, [](auto Op) {
1535     return Op.getOp() == dwarf::DW_OP_LLVM_arg;
1536   });
1537 }
1538 
1539 const DIExpression *
1540 DIExpression::convertToUndefExpression(const DIExpression *Expr) {
1541   SmallVector<uint64_t, 3> UndefOps;
1542   if (auto FragmentInfo = Expr->getFragmentInfo()) {
1543     UndefOps.append({dwarf::DW_OP_LLVM_fragment, FragmentInfo->OffsetInBits,
1544                      FragmentInfo->SizeInBits});
1545   }
1546   return DIExpression::get(Expr->getContext(), UndefOps);
1547 }
1548 
1549 const DIExpression *
1550 DIExpression::convertToVariadicExpression(const DIExpression *Expr) {
1551   if (any_of(Expr->expr_ops(), [](auto ExprOp) {
1552         return ExprOp.getOp() == dwarf::DW_OP_LLVM_arg;
1553       }))
1554     return Expr;
1555   SmallVector<uint64_t> NewOps;
1556   NewOps.reserve(Expr->getNumElements() + 2);
1557   NewOps.append({dwarf::DW_OP_LLVM_arg, 0});
1558   NewOps.append(Expr->elements_begin(), Expr->elements_end());
1559   return DIExpression::get(Expr->getContext(), NewOps);
1560 }
1561 
1562 std::optional<const DIExpression *>
1563 DIExpression::convertToNonVariadicExpression(const DIExpression *Expr) {
1564   // Check for `isValid` covered by `isSingleLocationExpression`.
1565   if (!Expr->isSingleLocationExpression())
1566     return std::nullopt;
1567 
1568   // An empty expression is already non-variadic.
1569   if (!Expr->getNumElements())
1570     return Expr;
1571 
1572   auto ElementsBegin = Expr->elements_begin();
1573   // If Expr does not have a leading DW_OP_LLVM_arg then we don't need to do
1574   // anything.
1575   if (*ElementsBegin != dwarf::DW_OP_LLVM_arg)
1576     return Expr;
1577 
1578   SmallVector<uint64_t> NonVariadicOps(
1579       make_range(ElementsBegin + 2, Expr->elements_end()));
1580   return DIExpression::get(Expr->getContext(), NonVariadicOps);
1581 }
1582 
1583 void DIExpression::canonicalizeExpressionOps(SmallVectorImpl<uint64_t> &Ops,
1584                                              const DIExpression *Expr,
1585                                              bool IsIndirect) {
1586   // If Expr is not already variadic, insert the implied `DW_OP_LLVM_arg 0`
1587   // to the existing expression ops.
1588   if (none_of(Expr->expr_ops(), [](auto ExprOp) {
1589         return ExprOp.getOp() == dwarf::DW_OP_LLVM_arg;
1590       }))
1591     Ops.append({dwarf::DW_OP_LLVM_arg, 0});
1592   // If Expr is not indirect, we only need to insert the expression elements and
1593   // we're done.
1594   if (!IsIndirect) {
1595     Ops.append(Expr->elements_begin(), Expr->elements_end());
1596     return;
1597   }
1598   // If Expr is indirect, insert the implied DW_OP_deref at the end of the
1599   // expression but before DW_OP_{stack_value, LLVM_fragment} if they are
1600   // present.
1601   for (auto Op : Expr->expr_ops()) {
1602     if (Op.getOp() == dwarf::DW_OP_stack_value ||
1603         Op.getOp() == dwarf::DW_OP_LLVM_fragment) {
1604       Ops.push_back(dwarf::DW_OP_deref);
1605       IsIndirect = false;
1606     }
1607     Op.appendToVector(Ops);
1608   }
1609   if (IsIndirect)
1610     Ops.push_back(dwarf::DW_OP_deref);
1611 }
1612 
1613 bool DIExpression::isEqualExpression(const DIExpression *FirstExpr,
1614                                      bool FirstIndirect,
1615                                      const DIExpression *SecondExpr,
1616                                      bool SecondIndirect) {
1617   SmallVector<uint64_t> FirstOps;
1618   DIExpression::canonicalizeExpressionOps(FirstOps, FirstExpr, FirstIndirect);
1619   SmallVector<uint64_t> SecondOps;
1620   DIExpression::canonicalizeExpressionOps(SecondOps, SecondExpr,
1621                                           SecondIndirect);
1622   return FirstOps == SecondOps;
1623 }
1624 
1625 std::optional<DIExpression::FragmentInfo>
1626 DIExpression::getFragmentInfo(expr_op_iterator Start, expr_op_iterator End) {
1627   for (auto I = Start; I != End; ++I)
1628     if (I->getOp() == dwarf::DW_OP_LLVM_fragment) {
1629       DIExpression::FragmentInfo Info = {I->getArg(1), I->getArg(0)};
1630       return Info;
1631     }
1632   return std::nullopt;
1633 }
1634 
1635 void DIExpression::appendOffset(SmallVectorImpl<uint64_t> &Ops,
1636                                 int64_t Offset) {
1637   if (Offset > 0) {
1638     Ops.push_back(dwarf::DW_OP_plus_uconst);
1639     Ops.push_back(Offset);
1640   } else if (Offset < 0) {
1641     Ops.push_back(dwarf::DW_OP_constu);
1642     // Avoid UB when encountering LLONG_MIN, because in 2's complement
1643     // abs(LLONG_MIN) is LLONG_MAX+1.
1644     uint64_t AbsMinusOne = -(Offset+1);
1645     Ops.push_back(AbsMinusOne + 1);
1646     Ops.push_back(dwarf::DW_OP_minus);
1647   }
1648 }
1649 
1650 bool DIExpression::extractIfOffset(int64_t &Offset) const {
1651   if (getNumElements() == 0) {
1652     Offset = 0;
1653     return true;
1654   }
1655 
1656   if (getNumElements() == 2 && Elements[0] == dwarf::DW_OP_plus_uconst) {
1657     Offset = Elements[1];
1658     return true;
1659   }
1660 
1661   if (getNumElements() == 3 && Elements[0] == dwarf::DW_OP_constu) {
1662     if (Elements[2] == dwarf::DW_OP_plus) {
1663       Offset = Elements[1];
1664       return true;
1665     }
1666     if (Elements[2] == dwarf::DW_OP_minus) {
1667       Offset = -Elements[1];
1668       return true;
1669     }
1670   }
1671 
1672   return false;
1673 }
1674 
1675 bool DIExpression::hasAllLocationOps(unsigned N) const {
1676   SmallDenseSet<uint64_t, 4> SeenOps;
1677   for (auto ExprOp : expr_ops())
1678     if (ExprOp.getOp() == dwarf::DW_OP_LLVM_arg)
1679       SeenOps.insert(ExprOp.getArg(0));
1680   for (uint64_t Idx = 0; Idx < N; ++Idx)
1681     if (!SeenOps.contains(Idx))
1682       return false;
1683   return true;
1684 }
1685 
1686 const DIExpression *DIExpression::extractAddressClass(const DIExpression *Expr,
1687                                                       unsigned &AddrClass) {
1688   // FIXME: This seems fragile. Nothing that verifies that these elements
1689   // actually map to ops and not operands.
1690   const unsigned PatternSize = 4;
1691   if (Expr->Elements.size() >= PatternSize &&
1692       Expr->Elements[PatternSize - 4] == dwarf::DW_OP_constu &&
1693       Expr->Elements[PatternSize - 2] == dwarf::DW_OP_swap &&
1694       Expr->Elements[PatternSize - 1] == dwarf::DW_OP_xderef) {
1695     AddrClass = Expr->Elements[PatternSize - 3];
1696 
1697     if (Expr->Elements.size() == PatternSize)
1698       return nullptr;
1699     return DIExpression::get(Expr->getContext(),
1700                              ArrayRef(&*Expr->Elements.begin(),
1701                                       Expr->Elements.size() - PatternSize));
1702   }
1703   return Expr;
1704 }
1705 
1706 DIExpression *DIExpression::prepend(const DIExpression *Expr, uint8_t Flags,
1707                                     int64_t Offset) {
1708   SmallVector<uint64_t, 8> Ops;
1709   if (Flags & DIExpression::DerefBefore)
1710     Ops.push_back(dwarf::DW_OP_deref);
1711 
1712   appendOffset(Ops, Offset);
1713   if (Flags & DIExpression::DerefAfter)
1714     Ops.push_back(dwarf::DW_OP_deref);
1715 
1716   bool StackValue = Flags & DIExpression::StackValue;
1717   bool EntryValue = Flags & DIExpression::EntryValue;
1718 
1719   return prependOpcodes(Expr, Ops, StackValue, EntryValue);
1720 }
1721 
1722 DIExpression *DIExpression::appendOpsToArg(const DIExpression *Expr,
1723                                            ArrayRef<uint64_t> Ops,
1724                                            unsigned ArgNo, bool StackValue) {
1725   assert(Expr && "Can't add ops to this expression");
1726 
1727   // Handle non-variadic intrinsics by prepending the opcodes.
1728   if (!any_of(Expr->expr_ops(),
1729               [](auto Op) { return Op.getOp() == dwarf::DW_OP_LLVM_arg; })) {
1730     assert(ArgNo == 0 &&
1731            "Location Index must be 0 for a non-variadic expression.");
1732     SmallVector<uint64_t, 8> NewOps(Ops.begin(), Ops.end());
1733     return DIExpression::prependOpcodes(Expr, NewOps, StackValue);
1734   }
1735 
1736   SmallVector<uint64_t, 8> NewOps;
1737   for (auto Op : Expr->expr_ops()) {
1738     // A DW_OP_stack_value comes at the end, but before a DW_OP_LLVM_fragment.
1739     if (StackValue) {
1740       if (Op.getOp() == dwarf::DW_OP_stack_value)
1741         StackValue = false;
1742       else if (Op.getOp() == dwarf::DW_OP_LLVM_fragment) {
1743         NewOps.push_back(dwarf::DW_OP_stack_value);
1744         StackValue = false;
1745       }
1746     }
1747     Op.appendToVector(NewOps);
1748     if (Op.getOp() == dwarf::DW_OP_LLVM_arg && Op.getArg(0) == ArgNo)
1749       NewOps.insert(NewOps.end(), Ops.begin(), Ops.end());
1750   }
1751   if (StackValue)
1752     NewOps.push_back(dwarf::DW_OP_stack_value);
1753 
1754   return DIExpression::get(Expr->getContext(), NewOps);
1755 }
1756 
1757 DIExpression *DIExpression::replaceArg(const DIExpression *Expr,
1758                                        uint64_t OldArg, uint64_t NewArg) {
1759   assert(Expr && "Can't replace args in this expression");
1760 
1761   SmallVector<uint64_t, 8> NewOps;
1762 
1763   for (auto Op : Expr->expr_ops()) {
1764     if (Op.getOp() != dwarf::DW_OP_LLVM_arg || Op.getArg(0) < OldArg) {
1765       Op.appendToVector(NewOps);
1766       continue;
1767     }
1768     NewOps.push_back(dwarf::DW_OP_LLVM_arg);
1769     uint64_t Arg = Op.getArg(0) == OldArg ? NewArg : Op.getArg(0);
1770     // OldArg has been deleted from the Op list, so decrement all indices
1771     // greater than it.
1772     if (Arg > OldArg)
1773       --Arg;
1774     NewOps.push_back(Arg);
1775   }
1776   return DIExpression::get(Expr->getContext(), NewOps);
1777 }
1778 
1779 DIExpression *DIExpression::prependOpcodes(const DIExpression *Expr,
1780                                            SmallVectorImpl<uint64_t> &Ops,
1781                                            bool StackValue, bool EntryValue) {
1782   assert(Expr && "Can't prepend ops to this expression");
1783 
1784   if (EntryValue) {
1785     Ops.push_back(dwarf::DW_OP_LLVM_entry_value);
1786     // Use a block size of 1 for the target register operand.  The
1787     // DWARF backend currently cannot emit entry values with a block
1788     // size > 1.
1789     Ops.push_back(1);
1790   }
1791 
1792   // If there are no ops to prepend, do not even add the DW_OP_stack_value.
1793   if (Ops.empty())
1794     StackValue = false;
1795   for (auto Op : Expr->expr_ops()) {
1796     // A DW_OP_stack_value comes at the end, but before a DW_OP_LLVM_fragment.
1797     if (StackValue) {
1798       if (Op.getOp() == dwarf::DW_OP_stack_value)
1799         StackValue = false;
1800       else if (Op.getOp() == dwarf::DW_OP_LLVM_fragment) {
1801         Ops.push_back(dwarf::DW_OP_stack_value);
1802         StackValue = false;
1803       }
1804     }
1805     Op.appendToVector(Ops);
1806   }
1807   if (StackValue)
1808     Ops.push_back(dwarf::DW_OP_stack_value);
1809   return DIExpression::get(Expr->getContext(), Ops);
1810 }
1811 
1812 DIExpression *DIExpression::append(const DIExpression *Expr,
1813                                    ArrayRef<uint64_t> Ops) {
1814   assert(Expr && !Ops.empty() && "Can't append ops to this expression");
1815 
1816   // Copy Expr's current op list.
1817   SmallVector<uint64_t, 16> NewOps;
1818   for (auto Op : Expr->expr_ops()) {
1819     // Append new opcodes before DW_OP_{stack_value, LLVM_fragment}.
1820     if (Op.getOp() == dwarf::DW_OP_stack_value ||
1821         Op.getOp() == dwarf::DW_OP_LLVM_fragment) {
1822       NewOps.append(Ops.begin(), Ops.end());
1823 
1824       // Ensure that the new opcodes are only appended once.
1825       Ops = std::nullopt;
1826     }
1827     Op.appendToVector(NewOps);
1828   }
1829 
1830   NewOps.append(Ops.begin(), Ops.end());
1831   auto *result = DIExpression::get(Expr->getContext(), NewOps);
1832   assert(result->isValid() && "concatenated expression is not valid");
1833   return result;
1834 }
1835 
1836 DIExpression *DIExpression::appendToStack(const DIExpression *Expr,
1837                                           ArrayRef<uint64_t> Ops) {
1838   assert(Expr && !Ops.empty() && "Can't append ops to this expression");
1839   assert(none_of(Ops,
1840                  [](uint64_t Op) {
1841                    return Op == dwarf::DW_OP_stack_value ||
1842                           Op == dwarf::DW_OP_LLVM_fragment;
1843                  }) &&
1844          "Can't append this op");
1845 
1846   // Append a DW_OP_deref after Expr's current op list if it's non-empty and
1847   // has no DW_OP_stack_value.
1848   //
1849   // Match .* DW_OP_stack_value (DW_OP_LLVM_fragment A B)?.
1850   std::optional<FragmentInfo> FI = Expr->getFragmentInfo();
1851   unsigned DropUntilStackValue = FI ? 3 : 0;
1852   ArrayRef<uint64_t> ExprOpsBeforeFragment =
1853       Expr->getElements().drop_back(DropUntilStackValue);
1854   bool NeedsDeref = (Expr->getNumElements() > DropUntilStackValue) &&
1855                     (ExprOpsBeforeFragment.back() != dwarf::DW_OP_stack_value);
1856   bool NeedsStackValue = NeedsDeref || ExprOpsBeforeFragment.empty();
1857 
1858   // Append a DW_OP_deref after Expr's current op list if needed, then append
1859   // the new ops, and finally ensure that a single DW_OP_stack_value is present.
1860   SmallVector<uint64_t, 16> NewOps;
1861   if (NeedsDeref)
1862     NewOps.push_back(dwarf::DW_OP_deref);
1863   NewOps.append(Ops.begin(), Ops.end());
1864   if (NeedsStackValue)
1865     NewOps.push_back(dwarf::DW_OP_stack_value);
1866   return DIExpression::append(Expr, NewOps);
1867 }
1868 
1869 std::optional<DIExpression *> DIExpression::createFragmentExpression(
1870     const DIExpression *Expr, unsigned OffsetInBits, unsigned SizeInBits) {
1871   SmallVector<uint64_t, 8> Ops;
1872   // Track whether it's safe to split the value at the top of the DWARF stack,
1873   // assuming that it'll be used as an implicit location value.
1874   bool CanSplitValue = true;
1875   // Copy over the expression, but leave off any trailing DW_OP_LLVM_fragment.
1876   if (Expr) {
1877     for (auto Op : Expr->expr_ops()) {
1878       switch (Op.getOp()) {
1879       default:
1880         break;
1881       case dwarf::DW_OP_shr:
1882       case dwarf::DW_OP_shra:
1883       case dwarf::DW_OP_shl:
1884       case dwarf::DW_OP_plus:
1885       case dwarf::DW_OP_plus_uconst:
1886       case dwarf::DW_OP_minus:
1887         // We can't safely split arithmetic or shift operations into multiple
1888         // fragments because we can't express carry-over between fragments.
1889         //
1890         // FIXME: We *could* preserve the lowest fragment of a constant offset
1891         // operation if the offset fits into SizeInBits.
1892         CanSplitValue = false;
1893         break;
1894       case dwarf::DW_OP_deref:
1895       case dwarf::DW_OP_deref_size:
1896       case dwarf::DW_OP_deref_type:
1897       case dwarf::DW_OP_xderef:
1898       case dwarf::DW_OP_xderef_size:
1899       case dwarf::DW_OP_xderef_type:
1900         // Preceeding arithmetic operations have been applied to compute an
1901         // address. It's okay to split the value loaded from that address.
1902         CanSplitValue = true;
1903         break;
1904       case dwarf::DW_OP_stack_value:
1905         // Bail if this expression computes a value that cannot be split.
1906         if (!CanSplitValue)
1907           return std::nullopt;
1908         break;
1909       case dwarf::DW_OP_LLVM_fragment: {
1910         // Make the new offset point into the existing fragment.
1911         uint64_t FragmentOffsetInBits = Op.getArg(0);
1912         uint64_t FragmentSizeInBits = Op.getArg(1);
1913         (void)FragmentSizeInBits;
1914         assert((OffsetInBits + SizeInBits <= FragmentSizeInBits) &&
1915                "new fragment outside of original fragment");
1916         OffsetInBits += FragmentOffsetInBits;
1917         continue;
1918       }
1919       }
1920       Op.appendToVector(Ops);
1921     }
1922   }
1923   assert((!Expr->isImplicit() || CanSplitValue) && "Expr can't be split");
1924   assert(Expr && "Unknown DIExpression");
1925   Ops.push_back(dwarf::DW_OP_LLVM_fragment);
1926   Ops.push_back(OffsetInBits);
1927   Ops.push_back(SizeInBits);
1928   return DIExpression::get(Expr->getContext(), Ops);
1929 }
1930 
1931 std::pair<DIExpression *, const ConstantInt *>
1932 DIExpression::constantFold(const ConstantInt *CI) {
1933   // Copy the APInt so we can modify it.
1934   APInt NewInt = CI->getValue();
1935   SmallVector<uint64_t, 8> Ops;
1936 
1937   // Fold operators only at the beginning of the expression.
1938   bool First = true;
1939   bool Changed = false;
1940   for (auto Op : expr_ops()) {
1941     switch (Op.getOp()) {
1942     default:
1943       // We fold only the leading part of the expression; if we get to a part
1944       // that we're going to copy unchanged, and haven't done any folding,
1945       // then the entire expression is unchanged and we can return early.
1946       if (!Changed)
1947         return {this, CI};
1948       First = false;
1949       break;
1950     case dwarf::DW_OP_LLVM_convert:
1951       if (!First)
1952         break;
1953       Changed = true;
1954       if (Op.getArg(1) == dwarf::DW_ATE_signed)
1955         NewInt = NewInt.sextOrTrunc(Op.getArg(0));
1956       else {
1957         assert(Op.getArg(1) == dwarf::DW_ATE_unsigned && "Unexpected operand");
1958         NewInt = NewInt.zextOrTrunc(Op.getArg(0));
1959       }
1960       continue;
1961     }
1962     Op.appendToVector(Ops);
1963   }
1964   if (!Changed)
1965     return {this, CI};
1966   return {DIExpression::get(getContext(), Ops),
1967           ConstantInt::get(getContext(), NewInt)};
1968 }
1969 
1970 uint64_t DIExpression::getNumLocationOperands() const {
1971   uint64_t Result = 0;
1972   for (auto ExprOp : expr_ops())
1973     if (ExprOp.getOp() == dwarf::DW_OP_LLVM_arg)
1974       Result = std::max(Result, ExprOp.getArg(0) + 1);
1975   assert(hasAllLocationOps(Result) &&
1976          "Expression is missing one or more location operands.");
1977   return Result;
1978 }
1979 
1980 std::optional<DIExpression::SignedOrUnsignedConstant>
1981 DIExpression::isConstant() const {
1982 
1983   // Recognize signed and unsigned constants.
1984   // An signed constants can be represented as DW_OP_consts C DW_OP_stack_value
1985   // (DW_OP_LLVM_fragment of Len).
1986   // An unsigned constant can be represented as
1987   // DW_OP_constu C DW_OP_stack_value (DW_OP_LLVM_fragment of Len).
1988 
1989   if ((getNumElements() != 2 && getNumElements() != 3 &&
1990        getNumElements() != 6) ||
1991       (getElement(0) != dwarf::DW_OP_consts &&
1992        getElement(0) != dwarf::DW_OP_constu))
1993     return std::nullopt;
1994 
1995   if (getNumElements() == 2 && getElement(0) == dwarf::DW_OP_consts)
1996     return SignedOrUnsignedConstant::SignedConstant;
1997 
1998   if ((getNumElements() == 3 && getElement(2) != dwarf::DW_OP_stack_value) ||
1999       (getNumElements() == 6 && (getElement(2) != dwarf::DW_OP_stack_value ||
2000                                  getElement(3) != dwarf::DW_OP_LLVM_fragment)))
2001     return std::nullopt;
2002   return getElement(0) == dwarf::DW_OP_constu
2003              ? SignedOrUnsignedConstant::UnsignedConstant
2004              : SignedOrUnsignedConstant::SignedConstant;
2005 }
2006 
2007 DIExpression::ExtOps DIExpression::getExtOps(unsigned FromSize, unsigned ToSize,
2008                                              bool Signed) {
2009   dwarf::TypeKind TK = Signed ? dwarf::DW_ATE_signed : dwarf::DW_ATE_unsigned;
2010   DIExpression::ExtOps Ops{{dwarf::DW_OP_LLVM_convert, FromSize, TK,
2011                             dwarf::DW_OP_LLVM_convert, ToSize, TK}};
2012   return Ops;
2013 }
2014 
2015 DIExpression *DIExpression::appendExt(const DIExpression *Expr,
2016                                       unsigned FromSize, unsigned ToSize,
2017                                       bool Signed) {
2018   return appendToStack(Expr, getExtOps(FromSize, ToSize, Signed));
2019 }
2020 
2021 DIGlobalVariableExpression *
2022 DIGlobalVariableExpression::getImpl(LLVMContext &Context, Metadata *Variable,
2023                                     Metadata *Expression, StorageType Storage,
2024                                     bool ShouldCreate) {
2025   DEFINE_GETIMPL_LOOKUP(DIGlobalVariableExpression, (Variable, Expression));
2026   Metadata *Ops[] = {Variable, Expression};
2027   DEFINE_GETIMPL_STORE_NO_CONSTRUCTOR_ARGS(DIGlobalVariableExpression, Ops);
2028 }
2029 DIObjCProperty::DIObjCProperty(LLVMContext &C, StorageType Storage,
2030                                unsigned Line, unsigned Attributes,
2031                                ArrayRef<Metadata *> Ops)
2032     : DINode(C, DIObjCPropertyKind, Storage, dwarf::DW_TAG_APPLE_property, Ops),
2033       Line(Line), Attributes(Attributes) {}
2034 
2035 DIObjCProperty *DIObjCProperty::getImpl(
2036     LLVMContext &Context, MDString *Name, Metadata *File, unsigned Line,
2037     MDString *GetterName, MDString *SetterName, unsigned Attributes,
2038     Metadata *Type, StorageType Storage, bool ShouldCreate) {
2039   assert(isCanonical(Name) && "Expected canonical MDString");
2040   assert(isCanonical(GetterName) && "Expected canonical MDString");
2041   assert(isCanonical(SetterName) && "Expected canonical MDString");
2042   DEFINE_GETIMPL_LOOKUP(DIObjCProperty, (Name, File, Line, GetterName,
2043                                          SetterName, Attributes, Type));
2044   Metadata *Ops[] = {Name, File, GetterName, SetterName, Type};
2045   DEFINE_GETIMPL_STORE(DIObjCProperty, (Line, Attributes), Ops);
2046 }
2047 
2048 DIImportedEntity *DIImportedEntity::getImpl(LLVMContext &Context, unsigned Tag,
2049                                             Metadata *Scope, Metadata *Entity,
2050                                             Metadata *File, unsigned Line,
2051                                             MDString *Name, Metadata *Elements,
2052                                             StorageType Storage,
2053                                             bool ShouldCreate) {
2054   assert(isCanonical(Name) && "Expected canonical MDString");
2055   DEFINE_GETIMPL_LOOKUP(DIImportedEntity,
2056                         (Tag, Scope, Entity, File, Line, Name, Elements));
2057   Metadata *Ops[] = {Scope, Entity, Name, File, Elements};
2058   DEFINE_GETIMPL_STORE(DIImportedEntity, (Tag, Line), Ops);
2059 }
2060 
2061 DIMacro *DIMacro::getImpl(LLVMContext &Context, unsigned MIType, unsigned Line,
2062                           MDString *Name, MDString *Value, StorageType Storage,
2063                           bool ShouldCreate) {
2064   assert(isCanonical(Name) && "Expected canonical MDString");
2065   DEFINE_GETIMPL_LOOKUP(DIMacro, (MIType, Line, Name, Value));
2066   Metadata *Ops[] = {Name, Value};
2067   DEFINE_GETIMPL_STORE(DIMacro, (MIType, Line), Ops);
2068 }
2069 
2070 DIMacroFile *DIMacroFile::getImpl(LLVMContext &Context, unsigned MIType,
2071                                   unsigned Line, Metadata *File,
2072                                   Metadata *Elements, StorageType Storage,
2073                                   bool ShouldCreate) {
2074   DEFINE_GETIMPL_LOOKUP(DIMacroFile, (MIType, Line, File, Elements));
2075   Metadata *Ops[] = {File, Elements};
2076   DEFINE_GETIMPL_STORE(DIMacroFile, (MIType, Line), Ops);
2077 }
2078 
2079 DIArgList *DIArgList::getImpl(LLVMContext &Context,
2080                               ArrayRef<ValueAsMetadata *> Args,
2081                               StorageType Storage, bool ShouldCreate) {
2082   DEFINE_GETIMPL_LOOKUP(DIArgList, (Args));
2083   DEFINE_GETIMPL_STORE_NO_OPS(DIArgList, (Args));
2084 }
2085 
2086 void DIArgList::handleChangedOperand(void *Ref, Metadata *New) {
2087   ValueAsMetadata **OldVMPtr = static_cast<ValueAsMetadata **>(Ref);
2088   assert((!New || isa<ValueAsMetadata>(New)) &&
2089          "DIArgList must be passed a ValueAsMetadata");
2090   untrack();
2091   bool Uniq = isUniqued();
2092   if (Uniq) {
2093     // We need to update the uniqueness once the Args are updated since they
2094     // form the key to the DIArgLists store.
2095     eraseFromStore();
2096   }
2097   ValueAsMetadata *NewVM = cast_or_null<ValueAsMetadata>(New);
2098   for (ValueAsMetadata *&VM : Args) {
2099     if (&VM == OldVMPtr) {
2100       if (NewVM)
2101         VM = NewVM;
2102       else
2103         VM = ValueAsMetadata::get(PoisonValue::get(VM->getValue()->getType()));
2104     }
2105   }
2106   if (Uniq) {
2107     if (uniquify() != this)
2108       storeDistinctInContext();
2109   }
2110   track();
2111 }
2112 void DIArgList::track() {
2113   for (ValueAsMetadata *&VAM : Args)
2114     if (VAM)
2115       MetadataTracking::track(&VAM, *VAM, *this);
2116 }
2117 void DIArgList::untrack() {
2118   for (ValueAsMetadata *&VAM : Args)
2119     if (VAM)
2120       MetadataTracking::untrack(&VAM, *VAM);
2121 }
2122 void DIArgList::dropAllReferences() {
2123   untrack();
2124   Args.clear();
2125   MDNode::dropAllReferences();
2126 }
2127