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