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