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