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 (auto I = std::next(Locs.begin()), E = Locs.end(); I != E; ++I) {
86     Merged = getMergedLocation(Merged, *I);
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::CountType DISubrange::getCount() const {
363   if (!getRawCountNode())
364     return CountType();
365 
366   if (auto *MD = dyn_cast<ConstantAsMetadata>(getRawCountNode()))
367     return CountType(cast<ConstantInt>(MD->getValue()));
368 
369   if (auto *DV = dyn_cast<DIVariable>(getRawCountNode()))
370     return CountType(DV);
371 
372   return CountType();
373 }
374 
375 DISubrange::BoundType DISubrange::getLowerBound() const {
376   Metadata *LB = getRawLowerBound();
377   if (!LB)
378     return BoundType();
379 
380   assert((isa<ConstantAsMetadata>(LB) || isa<DIVariable>(LB) ||
381           isa<DIExpression>(LB)) &&
382          "LowerBound must be signed constant or DIVariable or DIExpression");
383 
384   if (auto *MD = dyn_cast<ConstantAsMetadata>(LB))
385     return BoundType(cast<ConstantInt>(MD->getValue()));
386 
387   if (auto *MD = dyn_cast<DIVariable>(LB))
388     return BoundType(MD);
389 
390   if (auto *MD = dyn_cast<DIExpression>(LB))
391     return BoundType(MD);
392 
393   return BoundType();
394 }
395 
396 DISubrange::BoundType DISubrange::getUpperBound() const {
397   Metadata *UB = getRawUpperBound();
398   if (!UB)
399     return BoundType();
400 
401   assert((isa<ConstantAsMetadata>(UB) || isa<DIVariable>(UB) ||
402           isa<DIExpression>(UB)) &&
403          "UpperBound must be signed constant or DIVariable or DIExpression");
404 
405   if (auto *MD = dyn_cast<ConstantAsMetadata>(UB))
406     return BoundType(cast<ConstantInt>(MD->getValue()));
407 
408   if (auto *MD = dyn_cast<DIVariable>(UB))
409     return BoundType(MD);
410 
411   if (auto *MD = dyn_cast<DIExpression>(UB))
412     return BoundType(MD);
413 
414   return BoundType();
415 }
416 
417 DISubrange::BoundType DISubrange::getStride() const {
418   Metadata *ST = getRawStride();
419   if (!ST)
420     return BoundType();
421 
422   assert((isa<ConstantAsMetadata>(ST) || isa<DIVariable>(ST) ||
423           isa<DIExpression>(ST)) &&
424          "Stride must be signed constant or DIVariable or DIExpression");
425 
426   if (auto *MD = dyn_cast<ConstantAsMetadata>(ST))
427     return BoundType(cast<ConstantInt>(MD->getValue()));
428 
429   if (auto *MD = dyn_cast<DIVariable>(ST))
430     return BoundType(MD);
431 
432   if (auto *MD = dyn_cast<DIExpression>(ST))
433     return BoundType(MD);
434 
435   return BoundType();
436 }
437 
438 DIEnumerator *DIEnumerator::getImpl(LLVMContext &Context, const APInt &Value,
439                                     bool IsUnsigned, MDString *Name,
440                                     StorageType Storage, bool ShouldCreate) {
441   assert(isCanonical(Name) && "Expected canonical MDString");
442   DEFINE_GETIMPL_LOOKUP(DIEnumerator, (Value, IsUnsigned, Name));
443   Metadata *Ops[] = {Name};
444   DEFINE_GETIMPL_STORE(DIEnumerator, (Value, IsUnsigned), Ops);
445 }
446 
447 DIBasicType *DIBasicType::getImpl(LLVMContext &Context, unsigned Tag,
448                                   MDString *Name, uint64_t SizeInBits,
449                                   uint32_t AlignInBits, unsigned Encoding,
450                                   DIFlags Flags, StorageType Storage,
451                                   bool ShouldCreate) {
452   assert(isCanonical(Name) && "Expected canonical MDString");
453   DEFINE_GETIMPL_LOOKUP(DIBasicType,
454                         (Tag, Name, SizeInBits, AlignInBits, Encoding, Flags));
455   Metadata *Ops[] = {nullptr, nullptr, Name};
456   DEFINE_GETIMPL_STORE(DIBasicType, (Tag, SizeInBits, AlignInBits, Encoding,
457                       Flags), Ops);
458 }
459 
460 Optional<DIBasicType::Signedness> DIBasicType::getSignedness() const {
461   switch (getEncoding()) {
462   case dwarf::DW_ATE_signed:
463   case dwarf::DW_ATE_signed_char:
464     return Signedness::Signed;
465   case dwarf::DW_ATE_unsigned:
466   case dwarf::DW_ATE_unsigned_char:
467     return Signedness::Unsigned;
468   default:
469     return None;
470   }
471 }
472 
473 DIStringType *DIStringType::getImpl(LLVMContext &Context, unsigned Tag,
474                                     MDString *Name, Metadata *StringLength,
475                                     Metadata *StringLengthExp,
476                                     uint64_t SizeInBits, uint32_t AlignInBits,
477                                     unsigned Encoding, StorageType Storage,
478                                     bool ShouldCreate) {
479   assert(isCanonical(Name) && "Expected canonical MDString");
480   DEFINE_GETIMPL_LOOKUP(DIStringType, (Tag, Name, StringLength, StringLengthExp,
481                                        SizeInBits, AlignInBits, Encoding));
482   Metadata *Ops[] = {nullptr, nullptr, Name, StringLength, StringLengthExp};
483   DEFINE_GETIMPL_STORE(DIStringType, (Tag, SizeInBits, AlignInBits, Encoding),
484                        Ops);
485 }
486 
487 DIDerivedType *DIDerivedType::getImpl(
488     LLVMContext &Context, unsigned Tag, MDString *Name, Metadata *File,
489     unsigned Line, Metadata *Scope, Metadata *BaseType, uint64_t SizeInBits,
490     uint32_t AlignInBits, uint64_t OffsetInBits,
491     Optional<unsigned> DWARFAddressSpace, DIFlags Flags, Metadata *ExtraData,
492     StorageType Storage, bool ShouldCreate) {
493   assert(isCanonical(Name) && "Expected canonical MDString");
494   DEFINE_GETIMPL_LOOKUP(DIDerivedType,
495                         (Tag, Name, File, Line, Scope, BaseType, SizeInBits,
496                          AlignInBits, OffsetInBits, DWARFAddressSpace, Flags,
497                          ExtraData));
498   Metadata *Ops[] = {File, Scope, Name, BaseType, ExtraData};
499   DEFINE_GETIMPL_STORE(
500       DIDerivedType, (Tag, Line, SizeInBits, AlignInBits, OffsetInBits,
501                       DWARFAddressSpace, Flags), Ops);
502 }
503 
504 DICompositeType *DICompositeType::getImpl(
505     LLVMContext &Context, unsigned Tag, MDString *Name, Metadata *File,
506     unsigned Line, Metadata *Scope, Metadata *BaseType, uint64_t SizeInBits,
507     uint32_t AlignInBits, uint64_t OffsetInBits, DIFlags Flags,
508     Metadata *Elements, unsigned RuntimeLang, Metadata *VTableHolder,
509     Metadata *TemplateParams, MDString *Identifier, Metadata *Discriminator,
510     Metadata *DataLocation, Metadata *Associated, Metadata *Allocated,
511     StorageType Storage, bool ShouldCreate) {
512   assert(isCanonical(Name) && "Expected canonical MDString");
513 
514   // Keep this in sync with buildODRType.
515   DEFINE_GETIMPL_LOOKUP(DICompositeType,
516                         (Tag, Name, File, Line, Scope, BaseType, SizeInBits,
517                          AlignInBits, OffsetInBits, Flags, Elements,
518                          RuntimeLang, VTableHolder, TemplateParams, Identifier,
519                          Discriminator, DataLocation, Associated, Allocated));
520   Metadata *Ops[] = {File,          Scope,        Name,           BaseType,
521                      Elements,      VTableHolder, TemplateParams, Identifier,
522                      Discriminator, DataLocation, Associated,     Allocated};
523   DEFINE_GETIMPL_STORE(DICompositeType, (Tag, Line, RuntimeLang, SizeInBits,
524                                          AlignInBits, OffsetInBits, Flags),
525                        Ops);
526 }
527 
528 DICompositeType *DICompositeType::buildODRType(
529     LLVMContext &Context, MDString &Identifier, unsigned Tag, MDString *Name,
530     Metadata *File, unsigned Line, Metadata *Scope, Metadata *BaseType,
531     uint64_t SizeInBits, uint32_t AlignInBits, uint64_t OffsetInBits,
532     DIFlags Flags, Metadata *Elements, unsigned RuntimeLang,
533     Metadata *VTableHolder, Metadata *TemplateParams, Metadata *Discriminator,
534     Metadata *DataLocation, Metadata *Associated, Metadata *Allocated) {
535   assert(!Identifier.getString().empty() && "Expected valid identifier");
536   if (!Context.isODRUniquingDebugTypes())
537     return nullptr;
538   auto *&CT = (*Context.pImpl->DITypeMap)[&Identifier];
539   if (!CT)
540     return CT = DICompositeType::getDistinct(
541                Context, Tag, Name, File, Line, Scope, BaseType, SizeInBits,
542                AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang,
543                VTableHolder, TemplateParams, &Identifier, Discriminator,
544                DataLocation, Associated, Allocated);
545 
546   // Only mutate CT if it's a forward declaration and the new operands aren't.
547   assert(CT->getRawIdentifier() == &Identifier && "Wrong ODR identifier?");
548   if (!CT->isForwardDecl() || (Flags & DINode::FlagFwdDecl))
549     return CT;
550 
551   // Mutate CT in place.  Keep this in sync with getImpl.
552   CT->mutate(Tag, Line, RuntimeLang, SizeInBits, AlignInBits, OffsetInBits,
553              Flags);
554   Metadata *Ops[] = {File,          Scope,        Name,           BaseType,
555                      Elements,      VTableHolder, TemplateParams, &Identifier,
556                      Discriminator, DataLocation, Associated,     Allocated};
557   assert((std::end(Ops) - std::begin(Ops)) == (int)CT->getNumOperands() &&
558          "Mismatched number of operands");
559   for (unsigned I = 0, E = CT->getNumOperands(); I != E; ++I)
560     if (Ops[I] != CT->getOperand(I))
561       CT->setOperand(I, Ops[I]);
562   return CT;
563 }
564 
565 DICompositeType *DICompositeType::getODRType(
566     LLVMContext &Context, MDString &Identifier, unsigned Tag, MDString *Name,
567     Metadata *File, unsigned Line, Metadata *Scope, Metadata *BaseType,
568     uint64_t SizeInBits, uint32_t AlignInBits, uint64_t OffsetInBits,
569     DIFlags Flags, Metadata *Elements, unsigned RuntimeLang,
570     Metadata *VTableHolder, Metadata *TemplateParams, Metadata *Discriminator,
571     Metadata *DataLocation, Metadata *Associated, Metadata *Allocated) {
572   assert(!Identifier.getString().empty() && "Expected valid identifier");
573   if (!Context.isODRUniquingDebugTypes())
574     return nullptr;
575   auto *&CT = (*Context.pImpl->DITypeMap)[&Identifier];
576   if (!CT)
577     CT = DICompositeType::getDistinct(
578         Context, Tag, Name, File, Line, Scope, BaseType, SizeInBits,
579         AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang, VTableHolder,
580         TemplateParams, &Identifier, Discriminator, DataLocation, Associated,
581         Allocated);
582   return CT;
583 }
584 
585 DICompositeType *DICompositeType::getODRTypeIfExists(LLVMContext &Context,
586                                                      MDString &Identifier) {
587   assert(!Identifier.getString().empty() && "Expected valid identifier");
588   if (!Context.isODRUniquingDebugTypes())
589     return nullptr;
590   return Context.pImpl->DITypeMap->lookup(&Identifier);
591 }
592 
593 DISubroutineType *DISubroutineType::getImpl(LLVMContext &Context, DIFlags Flags,
594                                             uint8_t CC, Metadata *TypeArray,
595                                             StorageType Storage,
596                                             bool ShouldCreate) {
597   DEFINE_GETIMPL_LOOKUP(DISubroutineType, (Flags, CC, TypeArray));
598   Metadata *Ops[] = {nullptr, nullptr, nullptr, TypeArray};
599   DEFINE_GETIMPL_STORE(DISubroutineType, (Flags, CC), Ops);
600 }
601 
602 // FIXME: Implement this string-enum correspondence with a .def file and macros,
603 // so that the association is explicit rather than implied.
604 static const char *ChecksumKindName[DIFile::CSK_Last] = {
605     "CSK_MD5",
606     "CSK_SHA1",
607     "CSK_SHA256",
608 };
609 
610 StringRef DIFile::getChecksumKindAsString(ChecksumKind CSKind) {
611   assert(CSKind <= DIFile::CSK_Last && "Invalid checksum kind");
612   // The first space was originally the CSK_None variant, which is now
613   // obsolete, but the space is still reserved in ChecksumKind, so we account
614   // for it here.
615   return ChecksumKindName[CSKind - 1];
616 }
617 
618 Optional<DIFile::ChecksumKind> DIFile::getChecksumKind(StringRef CSKindStr) {
619   return StringSwitch<Optional<DIFile::ChecksumKind>>(CSKindStr)
620       .Case("CSK_MD5", DIFile::CSK_MD5)
621       .Case("CSK_SHA1", DIFile::CSK_SHA1)
622       .Case("CSK_SHA256", DIFile::CSK_SHA256)
623       .Default(None);
624 }
625 
626 DIFile *DIFile::getImpl(LLVMContext &Context, MDString *Filename,
627                         MDString *Directory,
628                         Optional<DIFile::ChecksumInfo<MDString *>> CS,
629                         Optional<MDString *> Source, StorageType Storage,
630                         bool ShouldCreate) {
631   assert(isCanonical(Filename) && "Expected canonical MDString");
632   assert(isCanonical(Directory) && "Expected canonical MDString");
633   assert((!CS || isCanonical(CS->Value)) && "Expected canonical MDString");
634   assert((!Source || isCanonical(*Source)) && "Expected canonical MDString");
635   DEFINE_GETIMPL_LOOKUP(DIFile, (Filename, Directory, CS, Source));
636   Metadata *Ops[] = {Filename, Directory, CS ? CS->Value : nullptr,
637                      Source.getValueOr(nullptr)};
638   DEFINE_GETIMPL_STORE(DIFile, (CS, Source), Ops);
639 }
640 
641 DICompileUnit *DICompileUnit::getImpl(
642     LLVMContext &Context, unsigned SourceLanguage, Metadata *File,
643     MDString *Producer, bool IsOptimized, MDString *Flags,
644     unsigned RuntimeVersion, MDString *SplitDebugFilename,
645     unsigned EmissionKind, Metadata *EnumTypes, Metadata *RetainedTypes,
646     Metadata *GlobalVariables, Metadata *ImportedEntities, Metadata *Macros,
647     uint64_t DWOId, bool SplitDebugInlining, bool DebugInfoForProfiling,
648     unsigned NameTableKind, bool RangesBaseAddress, MDString *SysRoot,
649     MDString *SDK, StorageType Storage, bool ShouldCreate) {
650   assert(Storage != Uniqued && "Cannot unique DICompileUnit");
651   assert(isCanonical(Producer) && "Expected canonical MDString");
652   assert(isCanonical(Flags) && "Expected canonical MDString");
653   assert(isCanonical(SplitDebugFilename) && "Expected canonical MDString");
654 
655   Metadata *Ops[] = {File,
656                      Producer,
657                      Flags,
658                      SplitDebugFilename,
659                      EnumTypes,
660                      RetainedTypes,
661                      GlobalVariables,
662                      ImportedEntities,
663                      Macros,
664                      SysRoot,
665                      SDK};
666   return storeImpl(new (array_lengthof(Ops)) DICompileUnit(
667                        Context, Storage, SourceLanguage, IsOptimized,
668                        RuntimeVersion, EmissionKind, DWOId, SplitDebugInlining,
669                        DebugInfoForProfiling, NameTableKind, RangesBaseAddress,
670                        Ops),
671                    Storage);
672 }
673 
674 Optional<DICompileUnit::DebugEmissionKind>
675 DICompileUnit::getEmissionKind(StringRef Str) {
676   return StringSwitch<Optional<DebugEmissionKind>>(Str)
677       .Case("NoDebug", NoDebug)
678       .Case("FullDebug", FullDebug)
679       .Case("LineTablesOnly", LineTablesOnly)
680       .Case("DebugDirectivesOnly", DebugDirectivesOnly)
681       .Default(None);
682 }
683 
684 Optional<DICompileUnit::DebugNameTableKind>
685 DICompileUnit::getNameTableKind(StringRef Str) {
686   return StringSwitch<Optional<DebugNameTableKind>>(Str)
687       .Case("Default", DebugNameTableKind::Default)
688       .Case("GNU", DebugNameTableKind::GNU)
689       .Case("None", DebugNameTableKind::None)
690       .Default(None);
691 }
692 
693 const char *DICompileUnit::emissionKindString(DebugEmissionKind EK) {
694   switch (EK) {
695   case NoDebug:        return "NoDebug";
696   case FullDebug:      return "FullDebug";
697   case LineTablesOnly: return "LineTablesOnly";
698   case DebugDirectivesOnly: return "DebugDirectivesOnly";
699   }
700   return nullptr;
701 }
702 
703 const char *DICompileUnit::nameTableKindString(DebugNameTableKind NTK) {
704   switch (NTK) {
705   case DebugNameTableKind::Default:
706     return nullptr;
707   case DebugNameTableKind::GNU:
708     return "GNU";
709   case DebugNameTableKind::None:
710     return "None";
711   }
712   return nullptr;
713 }
714 
715 DISubprogram *DILocalScope::getSubprogram() const {
716   if (auto *Block = dyn_cast<DILexicalBlockBase>(this))
717     return Block->getScope()->getSubprogram();
718   return const_cast<DISubprogram *>(cast<DISubprogram>(this));
719 }
720 
721 DILocalScope *DILocalScope::getNonLexicalBlockFileScope() const {
722   if (auto *File = dyn_cast<DILexicalBlockFile>(this))
723     return File->getScope()->getNonLexicalBlockFileScope();
724   return const_cast<DILocalScope *>(this);
725 }
726 
727 DISubprogram::DISPFlags DISubprogram::getFlag(StringRef Flag) {
728   return StringSwitch<DISPFlags>(Flag)
729 #define HANDLE_DISP_FLAG(ID, NAME) .Case("DISPFlag" #NAME, SPFlag##NAME)
730 #include "llvm/IR/DebugInfoFlags.def"
731       .Default(SPFlagZero);
732 }
733 
734 StringRef DISubprogram::getFlagString(DISPFlags Flag) {
735   switch (Flag) {
736   // Appease a warning.
737   case SPFlagVirtuality:
738     return "";
739 #define HANDLE_DISP_FLAG(ID, NAME)                                             \
740   case SPFlag##NAME:                                                           \
741     return "DISPFlag" #NAME;
742 #include "llvm/IR/DebugInfoFlags.def"
743   }
744   return "";
745 }
746 
747 DISubprogram::DISPFlags
748 DISubprogram::splitFlags(DISPFlags Flags,
749                          SmallVectorImpl<DISPFlags> &SplitFlags) {
750   // Multi-bit fields can require special handling. In our case, however, the
751   // only multi-bit field is virtuality, and all its values happen to be
752   // single-bit values, so the right behavior just falls out.
753 #define HANDLE_DISP_FLAG(ID, NAME)                                             \
754   if (DISPFlags Bit = Flags & SPFlag##NAME) {                                  \
755     SplitFlags.push_back(Bit);                                                 \
756     Flags &= ~Bit;                                                             \
757   }
758 #include "llvm/IR/DebugInfoFlags.def"
759   return Flags;
760 }
761 
762 DISubprogram *DISubprogram::getImpl(
763     LLVMContext &Context, Metadata *Scope, MDString *Name,
764     MDString *LinkageName, Metadata *File, unsigned Line, Metadata *Type,
765     unsigned ScopeLine, Metadata *ContainingType, unsigned VirtualIndex,
766     int ThisAdjustment, DIFlags Flags, DISPFlags SPFlags, Metadata *Unit,
767     Metadata *TemplateParams, Metadata *Declaration, Metadata *RetainedNodes,
768     Metadata *ThrownTypes, StorageType Storage, bool ShouldCreate) {
769   assert(isCanonical(Name) && "Expected canonical MDString");
770   assert(isCanonical(LinkageName) && "Expected canonical MDString");
771   DEFINE_GETIMPL_LOOKUP(DISubprogram,
772                         (Scope, Name, LinkageName, File, Line, Type, ScopeLine,
773                          ContainingType, VirtualIndex, ThisAdjustment, Flags,
774                          SPFlags, Unit, TemplateParams, Declaration,
775                          RetainedNodes, ThrownTypes));
776   SmallVector<Metadata *, 11> Ops = {
777       File,        Scope,         Name,           LinkageName,    Type,       Unit,
778       Declaration, RetainedNodes, ContainingType, TemplateParams, ThrownTypes};
779   if (!ThrownTypes) {
780     Ops.pop_back();
781     if (!TemplateParams) {
782       Ops.pop_back();
783       if (!ContainingType)
784         Ops.pop_back();
785     }
786   }
787   DEFINE_GETIMPL_STORE_N(
788       DISubprogram,
789       (Line, ScopeLine, VirtualIndex, ThisAdjustment, Flags, SPFlags), Ops,
790       Ops.size());
791 }
792 
793 bool DISubprogram::describes(const Function *F) const {
794   assert(F && "Invalid function");
795   return F->getSubprogram() == this;
796 }
797 
798 DILexicalBlock *DILexicalBlock::getImpl(LLVMContext &Context, Metadata *Scope,
799                                         Metadata *File, unsigned Line,
800                                         unsigned Column, StorageType Storage,
801                                         bool ShouldCreate) {
802   // Fixup column.
803   adjustColumn(Column);
804 
805   assert(Scope && "Expected scope");
806   DEFINE_GETIMPL_LOOKUP(DILexicalBlock, (Scope, File, Line, Column));
807   Metadata *Ops[] = {File, Scope};
808   DEFINE_GETIMPL_STORE(DILexicalBlock, (Line, Column), Ops);
809 }
810 
811 DILexicalBlockFile *DILexicalBlockFile::getImpl(LLVMContext &Context,
812                                                 Metadata *Scope, Metadata *File,
813                                                 unsigned Discriminator,
814                                                 StorageType Storage,
815                                                 bool ShouldCreate) {
816   assert(Scope && "Expected scope");
817   DEFINE_GETIMPL_LOOKUP(DILexicalBlockFile, (Scope, File, Discriminator));
818   Metadata *Ops[] = {File, Scope};
819   DEFINE_GETIMPL_STORE(DILexicalBlockFile, (Discriminator), Ops);
820 }
821 
822 DINamespace *DINamespace::getImpl(LLVMContext &Context, Metadata *Scope,
823                                   MDString *Name, bool ExportSymbols,
824                                   StorageType Storage, bool ShouldCreate) {
825   assert(isCanonical(Name) && "Expected canonical MDString");
826   DEFINE_GETIMPL_LOOKUP(DINamespace, (Scope, Name, ExportSymbols));
827   // The nullptr is for DIScope's File operand. This should be refactored.
828   Metadata *Ops[] = {nullptr, Scope, Name};
829   DEFINE_GETIMPL_STORE(DINamespace, (ExportSymbols), Ops);
830 }
831 
832 DICommonBlock *DICommonBlock::getImpl(LLVMContext &Context, Metadata *Scope,
833                                       Metadata *Decl, MDString *Name,
834                                       Metadata *File, unsigned LineNo,
835                                       StorageType Storage, bool ShouldCreate) {
836   assert(isCanonical(Name) && "Expected canonical MDString");
837   DEFINE_GETIMPL_LOOKUP(DICommonBlock, (Scope, Decl, Name, File, LineNo));
838   // The nullptr is for DIScope's File operand. This should be refactored.
839   Metadata *Ops[] = {Scope, Decl, Name, File};
840   DEFINE_GETIMPL_STORE(DICommonBlock, (LineNo), Ops);
841 }
842 
843 DIModule *DIModule::getImpl(LLVMContext &Context, Metadata *File,
844                             Metadata *Scope, MDString *Name,
845                             MDString *ConfigurationMacros,
846                             MDString *IncludePath, MDString *APINotesFile,
847                             unsigned LineNo, StorageType Storage,
848                             bool ShouldCreate) {
849   assert(isCanonical(Name) && "Expected canonical MDString");
850   DEFINE_GETIMPL_LOOKUP(DIModule, (File, Scope, Name, ConfigurationMacros,
851                                    IncludePath, APINotesFile, LineNo));
852   Metadata *Ops[] = {File,        Scope,       Name, ConfigurationMacros,
853                      IncludePath, APINotesFile};
854   DEFINE_GETIMPL_STORE(DIModule, (LineNo), Ops);
855 }
856 
857 DITemplateTypeParameter *
858 DITemplateTypeParameter::getImpl(LLVMContext &Context, MDString *Name,
859                                  Metadata *Type, bool isDefault,
860                                  StorageType Storage, bool ShouldCreate) {
861   assert(isCanonical(Name) && "Expected canonical MDString");
862   DEFINE_GETIMPL_LOOKUP(DITemplateTypeParameter, (Name, Type, isDefault));
863   Metadata *Ops[] = {Name, Type};
864   DEFINE_GETIMPL_STORE(DITemplateTypeParameter, (isDefault), Ops);
865 }
866 
867 DITemplateValueParameter *DITemplateValueParameter::getImpl(
868     LLVMContext &Context, unsigned Tag, MDString *Name, Metadata *Type,
869     bool isDefault, Metadata *Value, StorageType Storage, bool ShouldCreate) {
870   assert(isCanonical(Name) && "Expected canonical MDString");
871   DEFINE_GETIMPL_LOOKUP(DITemplateValueParameter,
872                         (Tag, Name, Type, isDefault, Value));
873   Metadata *Ops[] = {Name, Type, Value};
874   DEFINE_GETIMPL_STORE(DITemplateValueParameter, (Tag, isDefault), Ops);
875 }
876 
877 DIGlobalVariable *
878 DIGlobalVariable::getImpl(LLVMContext &Context, Metadata *Scope, MDString *Name,
879                           MDString *LinkageName, Metadata *File, unsigned Line,
880                           Metadata *Type, bool IsLocalToUnit, bool IsDefinition,
881                           Metadata *StaticDataMemberDeclaration,
882                           Metadata *TemplateParams, uint32_t AlignInBits,
883                           StorageType Storage, bool ShouldCreate) {
884   assert(isCanonical(Name) && "Expected canonical MDString");
885   assert(isCanonical(LinkageName) && "Expected canonical MDString");
886   DEFINE_GETIMPL_LOOKUP(DIGlobalVariable, (Scope, Name, LinkageName, File, Line,
887                                            Type, IsLocalToUnit, IsDefinition,
888                                            StaticDataMemberDeclaration,
889                                            TemplateParams, AlignInBits));
890   Metadata *Ops[] = {Scope,
891                      Name,
892                      File,
893                      Type,
894                      Name,
895                      LinkageName,
896                      StaticDataMemberDeclaration,
897                      TemplateParams};
898   DEFINE_GETIMPL_STORE(DIGlobalVariable,
899                        (Line, IsLocalToUnit, IsDefinition, AlignInBits), Ops);
900 }
901 
902 DILocalVariable *DILocalVariable::getImpl(LLVMContext &Context, Metadata *Scope,
903                                           MDString *Name, Metadata *File,
904                                           unsigned Line, Metadata *Type,
905                                           unsigned Arg, DIFlags Flags,
906                                           uint32_t AlignInBits,
907                                           StorageType Storage,
908                                           bool ShouldCreate) {
909   // 64K ought to be enough for any frontend.
910   assert(Arg <= UINT16_MAX && "Expected argument number to fit in 16-bits");
911 
912   assert(Scope && "Expected scope");
913   assert(isCanonical(Name) && "Expected canonical MDString");
914   DEFINE_GETIMPL_LOOKUP(DILocalVariable,
915                         (Scope, Name, File, Line, Type, Arg, Flags,
916                          AlignInBits));
917   Metadata *Ops[] = {Scope, Name, File, Type};
918   DEFINE_GETIMPL_STORE(DILocalVariable, (Line, Arg, Flags, AlignInBits), Ops);
919 }
920 
921 Optional<uint64_t> DIVariable::getSizeInBits() const {
922   // This is used by the Verifier so be mindful of broken types.
923   const Metadata *RawType = getRawType();
924   while (RawType) {
925     // Try to get the size directly.
926     if (auto *T = dyn_cast<DIType>(RawType))
927       if (uint64_t Size = T->getSizeInBits())
928         return Size;
929 
930     if (auto *DT = dyn_cast<DIDerivedType>(RawType)) {
931       // Look at the base type.
932       RawType = DT->getRawBaseType();
933       continue;
934     }
935 
936     // Missing type or size.
937     break;
938   }
939 
940   // Fail gracefully.
941   return None;
942 }
943 
944 DILabel *DILabel::getImpl(LLVMContext &Context, Metadata *Scope,
945                           MDString *Name, Metadata *File, unsigned Line,
946                           StorageType Storage,
947                           bool ShouldCreate) {
948   assert(Scope && "Expected scope");
949   assert(isCanonical(Name) && "Expected canonical MDString");
950   DEFINE_GETIMPL_LOOKUP(DILabel,
951                         (Scope, Name, File, Line));
952   Metadata *Ops[] = {Scope, Name, File};
953   DEFINE_GETIMPL_STORE(DILabel, (Line), Ops);
954 }
955 
956 DIExpression *DIExpression::getImpl(LLVMContext &Context,
957                                     ArrayRef<uint64_t> Elements,
958                                     StorageType Storage, bool ShouldCreate) {
959   DEFINE_GETIMPL_LOOKUP(DIExpression, (Elements));
960   DEFINE_GETIMPL_STORE_NO_OPS(DIExpression, (Elements));
961 }
962 
963 unsigned DIExpression::ExprOperand::getSize() const {
964   uint64_t Op = getOp();
965 
966   if (Op >= dwarf::DW_OP_breg0 && Op <= dwarf::DW_OP_breg31)
967     return 2;
968 
969   switch (Op) {
970   case dwarf::DW_OP_LLVM_convert:
971   case dwarf::DW_OP_LLVM_fragment:
972   case dwarf::DW_OP_bregx:
973     return 3;
974   case dwarf::DW_OP_constu:
975   case dwarf::DW_OP_consts:
976   case dwarf::DW_OP_deref_size:
977   case dwarf::DW_OP_plus_uconst:
978   case dwarf::DW_OP_LLVM_tag_offset:
979   case dwarf::DW_OP_LLVM_entry_value:
980   case dwarf::DW_OP_regx:
981     return 2;
982   default:
983     return 1;
984   }
985 }
986 
987 bool DIExpression::isValid() const {
988   for (auto I = expr_op_begin(), E = expr_op_end(); I != E; ++I) {
989     // Check that there's space for the operand.
990     if (I->get() + I->getSize() > E->get())
991       return false;
992 
993     uint64_t Op = I->getOp();
994     if ((Op >= dwarf::DW_OP_reg0 && Op <= dwarf::DW_OP_reg31) ||
995         (Op >= dwarf::DW_OP_breg0 && Op <= dwarf::DW_OP_breg31))
996       return true;
997 
998     // Check that the operand is valid.
999     switch (Op) {
1000     default:
1001       return false;
1002     case dwarf::DW_OP_LLVM_fragment:
1003       // A fragment operator must appear at the end.
1004       return I->get() + I->getSize() == E->get();
1005     case dwarf::DW_OP_stack_value: {
1006       // Must be the last one or followed by a DW_OP_LLVM_fragment.
1007       if (I->get() + I->getSize() == E->get())
1008         break;
1009       auto J = I;
1010       if ((++J)->getOp() != dwarf::DW_OP_LLVM_fragment)
1011         return false;
1012       break;
1013     }
1014     case dwarf::DW_OP_swap: {
1015       // Must be more than one implicit element on the stack.
1016 
1017       // FIXME: A better way to implement this would be to add a local variable
1018       // that keeps track of the stack depth and introduce something like a
1019       // DW_LLVM_OP_implicit_location as a placeholder for the location this
1020       // DIExpression is attached to, or else pass the number of implicit stack
1021       // elements into isValid.
1022       if (getNumElements() == 1)
1023         return false;
1024       break;
1025     }
1026     case dwarf::DW_OP_LLVM_entry_value: {
1027       // An entry value operator must appear at the beginning and the number of
1028       // operations it cover can currently only be 1, because we support only
1029       // entry values of a simple register location. One reason for this is that
1030       // we currently can't calculate the size of the resulting DWARF block for
1031       // other expressions.
1032       return I->get() == expr_op_begin()->get() && I->getArg(0) == 1 &&
1033              getNumElements() == 2;
1034     }
1035     case dwarf::DW_OP_LLVM_convert:
1036     case dwarf::DW_OP_LLVM_tag_offset:
1037     case dwarf::DW_OP_constu:
1038     case dwarf::DW_OP_plus_uconst:
1039     case dwarf::DW_OP_plus:
1040     case dwarf::DW_OP_minus:
1041     case dwarf::DW_OP_mul:
1042     case dwarf::DW_OP_div:
1043     case dwarf::DW_OP_mod:
1044     case dwarf::DW_OP_or:
1045     case dwarf::DW_OP_and:
1046     case dwarf::DW_OP_xor:
1047     case dwarf::DW_OP_shl:
1048     case dwarf::DW_OP_shr:
1049     case dwarf::DW_OP_shra:
1050     case dwarf::DW_OP_deref:
1051     case dwarf::DW_OP_deref_size:
1052     case dwarf::DW_OP_xderef:
1053     case dwarf::DW_OP_lit0:
1054     case dwarf::DW_OP_not:
1055     case dwarf::DW_OP_dup:
1056     case dwarf::DW_OP_regx:
1057     case dwarf::DW_OP_bregx:
1058     case dwarf::DW_OP_push_object_address:
1059       break;
1060     }
1061   }
1062   return true;
1063 }
1064 
1065 bool DIExpression::isImplicit() const {
1066   if (!isValid())
1067     return false;
1068 
1069   if (getNumElements() == 0)
1070     return false;
1071 
1072   for (const auto &It : expr_ops()) {
1073     switch (It.getOp()) {
1074     default:
1075       break;
1076     case dwarf::DW_OP_stack_value:
1077     case dwarf::DW_OP_LLVM_tag_offset:
1078       return true;
1079     }
1080   }
1081 
1082   return false;
1083 }
1084 
1085 bool DIExpression::isComplex() const {
1086   if (!isValid())
1087     return false;
1088 
1089   if (getNumElements() == 0)
1090     return false;
1091 
1092   // If there are any elements other than fragment or tag_offset, then some
1093   // kind of complex computation occurs.
1094   for (const auto &It : expr_ops()) {
1095     switch (It.getOp()) {
1096       case dwarf::DW_OP_LLVM_tag_offset:
1097       case dwarf::DW_OP_LLVM_fragment:
1098         continue;
1099       default: return true;
1100     }
1101   }
1102 
1103   return false;
1104 }
1105 
1106 Optional<DIExpression::FragmentInfo>
1107 DIExpression::getFragmentInfo(expr_op_iterator Start, expr_op_iterator End) {
1108   for (auto I = Start; I != End; ++I)
1109     if (I->getOp() == dwarf::DW_OP_LLVM_fragment) {
1110       DIExpression::FragmentInfo Info = {I->getArg(1), I->getArg(0)};
1111       return Info;
1112     }
1113   return None;
1114 }
1115 
1116 void DIExpression::appendOffset(SmallVectorImpl<uint64_t> &Ops,
1117                                 int64_t Offset) {
1118   if (Offset > 0) {
1119     Ops.push_back(dwarf::DW_OP_plus_uconst);
1120     Ops.push_back(Offset);
1121   } else if (Offset < 0) {
1122     Ops.push_back(dwarf::DW_OP_constu);
1123     Ops.push_back(-Offset);
1124     Ops.push_back(dwarf::DW_OP_minus);
1125   }
1126 }
1127 
1128 bool DIExpression::extractIfOffset(int64_t &Offset) const {
1129   if (getNumElements() == 0) {
1130     Offset = 0;
1131     return true;
1132   }
1133 
1134   if (getNumElements() == 2 && Elements[0] == dwarf::DW_OP_plus_uconst) {
1135     Offset = Elements[1];
1136     return true;
1137   }
1138 
1139   if (getNumElements() == 3 && Elements[0] == dwarf::DW_OP_constu) {
1140     if (Elements[2] == dwarf::DW_OP_plus) {
1141       Offset = Elements[1];
1142       return true;
1143     }
1144     if (Elements[2] == dwarf::DW_OP_minus) {
1145       Offset = -Elements[1];
1146       return true;
1147     }
1148   }
1149 
1150   return false;
1151 }
1152 
1153 const DIExpression *DIExpression::extractAddressClass(const DIExpression *Expr,
1154                                                       unsigned &AddrClass) {
1155   // FIXME: This seems fragile. Nothing that verifies that these elements
1156   // actually map to ops and not operands.
1157   const unsigned PatternSize = 4;
1158   if (Expr->Elements.size() >= PatternSize &&
1159       Expr->Elements[PatternSize - 4] == dwarf::DW_OP_constu &&
1160       Expr->Elements[PatternSize - 2] == dwarf::DW_OP_swap &&
1161       Expr->Elements[PatternSize - 1] == dwarf::DW_OP_xderef) {
1162     AddrClass = Expr->Elements[PatternSize - 3];
1163 
1164     if (Expr->Elements.size() == PatternSize)
1165       return nullptr;
1166     return DIExpression::get(Expr->getContext(),
1167                              makeArrayRef(&*Expr->Elements.begin(),
1168                                           Expr->Elements.size() - PatternSize));
1169   }
1170   return Expr;
1171 }
1172 
1173 DIExpression *DIExpression::prepend(const DIExpression *Expr, uint8_t Flags,
1174                                     int64_t Offset) {
1175   SmallVector<uint64_t, 8> Ops;
1176   if (Flags & DIExpression::DerefBefore)
1177     Ops.push_back(dwarf::DW_OP_deref);
1178 
1179   appendOffset(Ops, Offset);
1180   if (Flags & DIExpression::DerefAfter)
1181     Ops.push_back(dwarf::DW_OP_deref);
1182 
1183   bool StackValue = Flags & DIExpression::StackValue;
1184   bool EntryValue = Flags & DIExpression::EntryValue;
1185 
1186   return prependOpcodes(Expr, Ops, StackValue, EntryValue);
1187 }
1188 
1189 DIExpression *DIExpression::prependOpcodes(const DIExpression *Expr,
1190                                            SmallVectorImpl<uint64_t> &Ops,
1191                                            bool StackValue,
1192                                            bool EntryValue) {
1193   assert(Expr && "Can't prepend ops to this expression");
1194 
1195   if (EntryValue) {
1196     Ops.push_back(dwarf::DW_OP_LLVM_entry_value);
1197     // Add size info needed for entry value expression.
1198     // Add plus one for target register operand.
1199     Ops.push_back(Expr->getNumElements() + 1);
1200   }
1201 
1202   // If there are no ops to prepend, do not even add the DW_OP_stack_value.
1203   if (Ops.empty())
1204     StackValue = false;
1205   for (auto Op : Expr->expr_ops()) {
1206     // A DW_OP_stack_value comes at the end, but before a DW_OP_LLVM_fragment.
1207     if (StackValue) {
1208       if (Op.getOp() == dwarf::DW_OP_stack_value)
1209         StackValue = false;
1210       else if (Op.getOp() == dwarf::DW_OP_LLVM_fragment) {
1211         Ops.push_back(dwarf::DW_OP_stack_value);
1212         StackValue = false;
1213       }
1214     }
1215     Op.appendToVector(Ops);
1216   }
1217   if (StackValue)
1218     Ops.push_back(dwarf::DW_OP_stack_value);
1219   return DIExpression::get(Expr->getContext(), Ops);
1220 }
1221 
1222 DIExpression *DIExpression::append(const DIExpression *Expr,
1223                                    ArrayRef<uint64_t> Ops) {
1224   assert(Expr && !Ops.empty() && "Can't append ops to this expression");
1225 
1226   // Copy Expr's current op list.
1227   SmallVector<uint64_t, 16> NewOps;
1228   for (auto Op : Expr->expr_ops()) {
1229     // Append new opcodes before DW_OP_{stack_value, LLVM_fragment}.
1230     if (Op.getOp() == dwarf::DW_OP_stack_value ||
1231         Op.getOp() == dwarf::DW_OP_LLVM_fragment) {
1232       NewOps.append(Ops.begin(), Ops.end());
1233 
1234       // Ensure that the new opcodes are only appended once.
1235       Ops = None;
1236     }
1237     Op.appendToVector(NewOps);
1238   }
1239 
1240   NewOps.append(Ops.begin(), Ops.end());
1241   auto *result = DIExpression::get(Expr->getContext(), NewOps);
1242   assert(result->isValid() && "concatenated expression is not valid");
1243   return result;
1244 }
1245 
1246 DIExpression *DIExpression::appendToStack(const DIExpression *Expr,
1247                                           ArrayRef<uint64_t> Ops) {
1248   assert(Expr && !Ops.empty() && "Can't append ops to this expression");
1249   assert(none_of(Ops,
1250                  [](uint64_t Op) {
1251                    return Op == dwarf::DW_OP_stack_value ||
1252                           Op == dwarf::DW_OP_LLVM_fragment;
1253                  }) &&
1254          "Can't append this op");
1255 
1256   // Append a DW_OP_deref after Expr's current op list if it's non-empty and
1257   // has no DW_OP_stack_value.
1258   //
1259   // Match .* DW_OP_stack_value (DW_OP_LLVM_fragment A B)?.
1260   Optional<FragmentInfo> FI = Expr->getFragmentInfo();
1261   unsigned DropUntilStackValue = FI.hasValue() ? 3 : 0;
1262   ArrayRef<uint64_t> ExprOpsBeforeFragment =
1263       Expr->getElements().drop_back(DropUntilStackValue);
1264   bool NeedsDeref = (Expr->getNumElements() > DropUntilStackValue) &&
1265                     (ExprOpsBeforeFragment.back() != dwarf::DW_OP_stack_value);
1266   bool NeedsStackValue = NeedsDeref || ExprOpsBeforeFragment.empty();
1267 
1268   // Append a DW_OP_deref after Expr's current op list if needed, then append
1269   // the new ops, and finally ensure that a single DW_OP_stack_value is present.
1270   SmallVector<uint64_t, 16> NewOps;
1271   if (NeedsDeref)
1272     NewOps.push_back(dwarf::DW_OP_deref);
1273   NewOps.append(Ops.begin(), Ops.end());
1274   if (NeedsStackValue)
1275     NewOps.push_back(dwarf::DW_OP_stack_value);
1276   return DIExpression::append(Expr, NewOps);
1277 }
1278 
1279 Optional<DIExpression *> DIExpression::createFragmentExpression(
1280     const DIExpression *Expr, unsigned OffsetInBits, unsigned SizeInBits) {
1281   SmallVector<uint64_t, 8> Ops;
1282   // Copy over the expression, but leave off any trailing DW_OP_LLVM_fragment.
1283   if (Expr) {
1284     for (auto Op : Expr->expr_ops()) {
1285       switch (Op.getOp()) {
1286       default: break;
1287       case dwarf::DW_OP_shr:
1288       case dwarf::DW_OP_shra:
1289       case dwarf::DW_OP_shl:
1290       case dwarf::DW_OP_plus:
1291       case dwarf::DW_OP_plus_uconst:
1292       case dwarf::DW_OP_minus:
1293         // We can't safely split arithmetic or shift operations into multiple
1294         // fragments because we can't express carry-over between fragments.
1295         //
1296         // FIXME: We *could* preserve the lowest fragment of a constant offset
1297         // operation if the offset fits into SizeInBits.
1298         return None;
1299       case dwarf::DW_OP_LLVM_fragment: {
1300         // Make the new offset point into the existing fragment.
1301         uint64_t FragmentOffsetInBits = Op.getArg(0);
1302         uint64_t FragmentSizeInBits = Op.getArg(1);
1303         (void)FragmentSizeInBits;
1304         assert((OffsetInBits + SizeInBits <= FragmentSizeInBits) &&
1305                "new fragment outside of original fragment");
1306         OffsetInBits += FragmentOffsetInBits;
1307         continue;
1308       }
1309       }
1310       Op.appendToVector(Ops);
1311     }
1312   }
1313   assert(Expr && "Unknown DIExpression");
1314   Ops.push_back(dwarf::DW_OP_LLVM_fragment);
1315   Ops.push_back(OffsetInBits);
1316   Ops.push_back(SizeInBits);
1317   return DIExpression::get(Expr->getContext(), Ops);
1318 }
1319 
1320 bool DIExpression::isConstant() const {
1321   // Recognize DW_OP_constu C DW_OP_stack_value (DW_OP_LLVM_fragment Len Ofs)?.
1322   if (getNumElements() != 3 && getNumElements() != 6)
1323     return false;
1324   if (getElement(0) != dwarf::DW_OP_constu ||
1325       getElement(2) != dwarf::DW_OP_stack_value)
1326     return false;
1327   if (getNumElements() == 6 && getElement(3) != dwarf::DW_OP_LLVM_fragment)
1328     return false;
1329   return true;
1330 }
1331 
1332 DIExpression::ExtOps DIExpression::getExtOps(unsigned FromSize, unsigned ToSize,
1333                                              bool Signed) {
1334   dwarf::TypeKind TK = Signed ? dwarf::DW_ATE_signed : dwarf::DW_ATE_unsigned;
1335   DIExpression::ExtOps Ops{{dwarf::DW_OP_LLVM_convert, FromSize, TK,
1336                             dwarf::DW_OP_LLVM_convert, ToSize, TK}};
1337   return Ops;
1338 }
1339 
1340 DIExpression *DIExpression::appendExt(const DIExpression *Expr,
1341                                       unsigned FromSize, unsigned ToSize,
1342                                       bool Signed) {
1343   return appendToStack(Expr, getExtOps(FromSize, ToSize, Signed));
1344 }
1345 
1346 DIGlobalVariableExpression *
1347 DIGlobalVariableExpression::getImpl(LLVMContext &Context, Metadata *Variable,
1348                                     Metadata *Expression, StorageType Storage,
1349                                     bool ShouldCreate) {
1350   DEFINE_GETIMPL_LOOKUP(DIGlobalVariableExpression, (Variable, Expression));
1351   Metadata *Ops[] = {Variable, Expression};
1352   DEFINE_GETIMPL_STORE_NO_CONSTRUCTOR_ARGS(DIGlobalVariableExpression, Ops);
1353 }
1354 
1355 DIObjCProperty *DIObjCProperty::getImpl(
1356     LLVMContext &Context, MDString *Name, Metadata *File, unsigned Line,
1357     MDString *GetterName, MDString *SetterName, unsigned Attributes,
1358     Metadata *Type, StorageType Storage, bool ShouldCreate) {
1359   assert(isCanonical(Name) && "Expected canonical MDString");
1360   assert(isCanonical(GetterName) && "Expected canonical MDString");
1361   assert(isCanonical(SetterName) && "Expected canonical MDString");
1362   DEFINE_GETIMPL_LOOKUP(DIObjCProperty, (Name, File, Line, GetterName,
1363                                          SetterName, Attributes, Type));
1364   Metadata *Ops[] = {Name, File, GetterName, SetterName, Type};
1365   DEFINE_GETIMPL_STORE(DIObjCProperty, (Line, Attributes), Ops);
1366 }
1367 
1368 DIImportedEntity *DIImportedEntity::getImpl(LLVMContext &Context, unsigned Tag,
1369                                             Metadata *Scope, Metadata *Entity,
1370                                             Metadata *File, unsigned Line,
1371                                             MDString *Name, StorageType Storage,
1372                                             bool ShouldCreate) {
1373   assert(isCanonical(Name) && "Expected canonical MDString");
1374   DEFINE_GETIMPL_LOOKUP(DIImportedEntity,
1375                         (Tag, Scope, Entity, File, Line, Name));
1376   Metadata *Ops[] = {Scope, Entity, Name, File};
1377   DEFINE_GETIMPL_STORE(DIImportedEntity, (Tag, Line), Ops);
1378 }
1379 
1380 DIMacro *DIMacro::getImpl(LLVMContext &Context, unsigned MIType,
1381                           unsigned Line, MDString *Name, MDString *Value,
1382                           StorageType Storage, bool ShouldCreate) {
1383   assert(isCanonical(Name) && "Expected canonical MDString");
1384   DEFINE_GETIMPL_LOOKUP(DIMacro, (MIType, Line, Name, Value));
1385   Metadata *Ops[] = { Name, Value };
1386   DEFINE_GETIMPL_STORE(DIMacro, (MIType, Line), Ops);
1387 }
1388 
1389 DIMacroFile *DIMacroFile::getImpl(LLVMContext &Context, unsigned MIType,
1390                                   unsigned Line, Metadata *File,
1391                                   Metadata *Elements, StorageType Storage,
1392                                   bool ShouldCreate) {
1393   DEFINE_GETIMPL_LOOKUP(DIMacroFile,
1394                         (MIType, Line, File, Elements));
1395   Metadata *Ops[] = { File, Elements };
1396   DEFINE_GETIMPL_STORE(DIMacroFile, (MIType, Line), Ops);
1397 }
1398