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