LLVM 23.0.0git
Metadata.cpp
Go to the documentation of this file.
1//===- Metadata.cpp - Implement Metadata classes --------------------------===//
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 Metadata classes.
10//
11//===----------------------------------------------------------------------===//
12
13#include "llvm/IR/Metadata.h"
14#include "LLVMContextImpl.h"
15#include "MetadataImpl.h"
16#include "llvm/ADT/APFloat.h"
17#include "llvm/ADT/APInt.h"
18#include "llvm/ADT/ArrayRef.h"
19#include "llvm/ADT/DenseSet.h"
20#include "llvm/ADT/STLExtras.h"
21#include "llvm/ADT/SetVector.h"
23#include "llvm/ADT/SmallSet.h"
25#include "llvm/ADT/StringMap.h"
26#include "llvm/ADT/StringRef.h"
27#include "llvm/ADT/Twine.h"
28#include "llvm/IR/Argument.h"
29#include "llvm/IR/BasicBlock.h"
30#include "llvm/IR/Constant.h"
33#include "llvm/IR/Constants.h"
35#include "llvm/IR/DebugLoc.h"
37#include "llvm/IR/Function.h"
40#include "llvm/IR/Instruction.h"
41#include "llvm/IR/LLVMContext.h"
42#include "llvm/IR/MDBuilder.h"
43#include "llvm/IR/Module.h"
46#include "llvm/IR/Type.h"
47#include "llvm/IR/Value.h"
50
53#include "llvm/Support/ModRef.h"
54#include <cassert>
55#include <cstddef>
56#include <cstdint>
57#include <type_traits>
58#include <utility>
59#include <vector>
60
61using namespace llvm;
62
63namespace llvm {
65}
66
67MetadataAsValue::MetadataAsValue(Type *Ty, Metadata *MD)
68 : Value(Ty, MetadataAsValueVal), MD(MD) {
69 track();
70}
71
76
77/// Canonicalize metadata arguments to intrinsics.
78///
79/// To support bitcode upgrades (and assembly semantic sugar) for \a
80/// MetadataAsValue, we need to canonicalize certain metadata.
81///
82/// - nullptr is replaced by an empty MDNode.
83/// - An MDNode with a single null operand is replaced by an empty MDNode.
84/// - An MDNode whose only operand is a \a ConstantAsMetadata gets skipped.
85///
86/// This maintains readability of bitcode from when metadata was a type of
87/// value, and these bridges were unnecessary.
89 Metadata *MD) {
90 if (!MD)
91 // !{}
92 return MDNode::get(Context, {});
93
94 // Return early if this isn't a single-operand MDNode.
95 auto *N = dyn_cast<MDNode>(MD);
96 if (!N || N->getNumOperands() != 1)
97 return MD;
98
99 if (!N->getOperand(0))
100 // !{}
101 return MDNode::get(Context, {});
102
103 if (auto *C = dyn_cast<ConstantAsMetadata>(N->getOperand(0)))
104 // Look through the MDNode.
105 return C;
106
107 return MD;
108}
109
110MetadataAsValue *MetadataAsValue::get(LLVMContext &Context, Metadata *MD) {
111 MD = canonicalizeMetadataForValue(Context, MD);
112 auto *&Entry = Context.pImpl->MetadataAsValues[MD];
113 if (!Entry)
114 Entry = new MetadataAsValue(Type::getMetadataTy(Context), MD);
115 return Entry;
116}
117
119 Metadata *MD) {
120 MD = canonicalizeMetadataForValue(Context, MD);
121 auto &Store = Context.pImpl->MetadataAsValues;
122 return Store.lookup(MD);
123}
124
125void MetadataAsValue::handleChangedMetadata(Metadata *MD) {
126 LLVMContext &Context = getContext();
127 MD = canonicalizeMetadataForValue(Context, MD);
128 auto &Store = Context.pImpl->MetadataAsValues;
129
130 // Stop tracking the old metadata.
131 Store.erase(this->MD);
132 untrack();
133 this->MD = nullptr;
134
135 // Start tracking MD, or RAUW if necessary.
136 auto *&Entry = Store[MD];
137 if (Entry) {
138 replaceAllUsesWith(Entry);
139 delete this;
140 return;
141 }
142
143 this->MD = MD;
144 track();
145 Entry = this;
146}
147
148void MetadataAsValue::track() {
149 if (MD)
150 MetadataTracking::track(&MD, *MD, *this);
151}
152
153void MetadataAsValue::untrack() {
154 if (MD)
156}
157
159 return static_cast<DbgVariableRecord *>(this);
160}
162 return static_cast<const DbgVariableRecord *>(this);
163}
164
166 // NOTE: We could inform the "owner" that a value has changed through
167 // getOwner, if needed.
168 auto OldMD = static_cast<Metadata **>(Old);
169 ptrdiff_t Idx = std::distance(&*DebugValues.begin(), OldMD);
170 // If replacing a ValueAsMetadata with a nullptr, replace it with a
171 // PoisonValue instead.
172 if (OldMD && isa<ValueAsMetadata>(*OldMD) && !New) {
173 auto *OldVAM = cast<ValueAsMetadata>(*OldMD);
174 New = ValueAsMetadata::get(PoisonValue::get(OldVAM->getValue()->getType()));
175 }
176 resetDebugValue(Idx, New);
177}
178
179void DebugValueUser::trackDebugValue(size_t Idx) {
180 assert(Idx < 3 && "Invalid debug value index.");
181 Metadata *&MD = DebugValues[Idx];
182 if (MD)
183 MetadataTracking::track(&MD, *MD, *this);
184}
185
186void DebugValueUser::trackDebugValues() {
187 for (Metadata *&MD : DebugValues)
188 if (MD)
189 MetadataTracking::track(&MD, *MD, *this);
190}
191
192void DebugValueUser::untrackDebugValue(size_t Idx) {
193 assert(Idx < 3 && "Invalid debug value index.");
194 Metadata *&MD = DebugValues[Idx];
195 if (MD)
197}
198
199void DebugValueUser::untrackDebugValues() {
200 for (Metadata *&MD : DebugValues)
201 if (MD)
203}
204
205void DebugValueUser::retrackDebugValues(DebugValueUser &X) {
206 assert(DebugValueUser::operator==(X) && "Expected values to match");
207 for (const auto &[MD, XMD] : zip(DebugValues, X.DebugValues))
208 if (XMD)
210 X.DebugValues.fill(nullptr);
211}
212
213bool MetadataTracking::track(void *Ref, Metadata &MD, OwnerTy Owner) {
214 assert(Ref && "Expected live reference");
215 assert((Owner || *static_cast<Metadata **>(Ref) == &MD) &&
216 "Reference without owner must be direct");
217 if (auto *R = ReplaceableMetadataImpl::getOrCreate(MD)) {
218 R->addRef(Ref, Owner);
219 return true;
220 }
221 if (auto *PH = dyn_cast<DistinctMDOperandPlaceholder>(&MD)) {
222 assert(!PH->Use && "Placeholders can only be used once");
223 assert(!Owner && "Unexpected callback to owner");
224 PH->Use = static_cast<Metadata **>(Ref);
225 return true;
226 }
227 return false;
228}
229
231 assert(Ref && "Expected live reference");
232 if (auto *R = ReplaceableMetadataImpl::getIfExists(MD))
233 R->dropRef(Ref);
234 else if (auto *PH = dyn_cast<DistinctMDOperandPlaceholder>(&MD))
235 PH->Use = nullptr;
236}
237
238bool MetadataTracking::retrack(void *Ref, Metadata &MD, void *New) {
239 assert(Ref && "Expected live reference");
240 assert(New && "Expected live reference");
241 assert(Ref != New && "Expected change");
242 if (auto *R = ReplaceableMetadataImpl::getIfExists(MD)) {
243 R->moveRef(Ref, New, MD);
244 return true;
245 }
247 "Unexpected move of an MDOperand");
248 assert(!isReplaceable(MD) &&
249 "Expected un-replaceable metadata, since we didn't move a reference");
250 return false;
251}
252
254 return ReplaceableMetadataImpl::isReplaceable(MD);
255}
256
259 for (auto Pair : UseMap) {
260 OwnerTy Owner = Pair.second.first;
261 if (Owner.isNull())
262 continue;
264 continue;
265 Metadata *OwnerMD = cast<Metadata *>(Owner);
266 if (OwnerMD->getMetadataID() == Metadata::DIArgListKind)
267 MDUsersWithID.push_back(&UseMap[Pair.first]);
268 }
269 llvm::sort(MDUsersWithID, [](auto UserA, auto UserB) {
270 return UserA->second < UserB->second;
271 });
273 for (auto *UserWithID : MDUsersWithID)
274 MDUsers.push_back(cast<Metadata *>(UserWithID->first));
275 return MDUsers;
276}
277
281 for (auto Pair : UseMap) {
282 OwnerTy Owner = Pair.second.first;
283 if (Owner.isNull())
284 continue;
286 continue;
287 DVRUsersWithID.push_back(&UseMap[Pair.first]);
288 }
289 // Order DbgVariableRecord users in reverse-creation order. Normal dbg.value
290 // users of MetadataAsValues are ordered by their UseList, i.e. reverse order
291 // of when they were added: we need to replicate that here. The structure of
292 // debug-info output depends on the ordering of intrinsics, thus we need
293 // to keep them consistent for comparisons sake.
294 llvm::sort(DVRUsersWithID, [](auto UserA, auto UserB) {
295 return UserA->second > UserB->second;
296 });
298 for (auto UserWithID : DVRUsersWithID)
299 DVRUsers.push_back(cast<DebugValueUser *>(UserWithID->first)->getUser());
300 return DVRUsers;
301}
302
303void ReplaceableMetadataImpl::addRef(void *Ref, OwnerTy Owner) {
304 bool WasInserted =
305 UseMap.insert(std::make_pair(Ref, std::make_pair(Owner, NextIndex)))
306 .second;
307 (void)WasInserted;
308 assert(WasInserted && "Expected to add a reference");
309
310 ++NextIndex;
311 assert(NextIndex != 0 && "Unexpected overflow");
312}
313
314void ReplaceableMetadataImpl::dropRef(void *Ref) {
315 bool WasErased = UseMap.erase(Ref);
316 (void)WasErased;
317 assert(WasErased && "Expected to drop a reference");
318}
319
320void ReplaceableMetadataImpl::moveRef(void *Ref, void *New,
321 const Metadata &MD) {
322 auto I = UseMap.find(Ref);
323 assert(I != UseMap.end() && "Expected to move a reference");
324 auto OwnerAndIndex = I->second;
325 UseMap.erase(I);
326 bool WasInserted = UseMap.insert(std::make_pair(New, OwnerAndIndex)).second;
327 (void)WasInserted;
328 assert(WasInserted && "Expected to add a reference");
329
330 // Check that the references are direct if there's no owner.
331 (void)MD;
332 assert((OwnerAndIndex.first || *static_cast<Metadata **>(Ref) == &MD) &&
333 "Reference without owner must be direct");
334 assert((OwnerAndIndex.first || *static_cast<Metadata **>(New) == &MD) &&
335 "Reference without owner must be direct");
336}
337
339 if (!C.isUsedByMetadata()) {
340 return;
341 }
342
343 LLVMContext &Context = C.getType()->getContext();
344 auto &Store = Context.pImpl->ValuesAsMetadata;
345 auto I = Store.find(&C);
346 ValueAsMetadata *MD = I->second;
347 using UseTy =
348 std::pair<void *, std::pair<MetadataTracking::OwnerTy, uint64_t>>;
349 // Copy out uses and update value of Constant used by debug info metadata with
350 // poison below
351 SmallVector<UseTy, 8> Uses(MD->UseMap.begin(), MD->UseMap.end());
352
353 for (const auto &Pair : Uses) {
354 MetadataTracking::OwnerTy Owner = Pair.second.first;
355 if (!Owner)
356 continue;
357 // Check for MetadataAsValue.
359 cast<MetadataAsValue *>(Owner)->handleChangedMetadata(
361 continue;
362 }
364 continue;
366 if (!OwnerMD)
367 continue;
368 if (isa<DINode>(OwnerMD)) {
369 OwnerMD->handleChangedOperand(
370 Pair.first, ValueAsMetadata::get(PoisonValue::get(C.getType())));
371 }
372 }
373}
374
376 if (UseMap.empty())
377 return;
378
379 // Copy out uses since UseMap will get touched below.
380 using UseTy = std::pair<void *, std::pair<OwnerTy, uint64_t>>;
381 SmallVector<UseTy, 8> Uses(UseMap.begin(), UseMap.end());
382 llvm::sort(Uses, [](const UseTy &L, const UseTy &R) {
383 return L.second.second < R.second.second;
384 });
385 for (const auto &Pair : Uses) {
386 // Check that this Ref hasn't disappeared after RAUW (when updating a
387 // previous Ref).
388 if (!UseMap.count(Pair.first))
389 continue;
390
391 OwnerTy Owner = Pair.second.first;
392 if (!Owner) {
393 // Update unowned tracking references directly.
394 Metadata *&Ref = *static_cast<Metadata **>(Pair.first);
395 Ref = MD;
396 if (MD)
398 UseMap.erase(Pair.first);
399 continue;
400 }
401
402 // Check for MetadataAsValue.
404 cast<MetadataAsValue *>(Owner)->handleChangedMetadata(MD);
405 continue;
406 }
407
408 if (auto *DVU = dyn_cast<DebugValueUser *>(Owner)) {
409 DVU->handleChangedValue(Pair.first, MD);
410 continue;
411 }
412
413 // There's a Metadata owner -- dispatch.
414 Metadata *OwnerMD = cast<Metadata *>(Owner);
415 switch (OwnerMD->getMetadataID()) {
416#define HANDLE_METADATA_LEAF(CLASS) \
417 case Metadata::CLASS##Kind: \
418 cast<CLASS>(OwnerMD)->handleChangedOperand(Pair.first, MD); \
419 continue;
420#include "llvm/IR/Metadata.def"
421 default:
422 llvm_unreachable("Invalid metadata subclass");
423 }
424 }
425 assert(UseMap.empty() && "Expected all uses to be replaced");
426}
427
429 if (UseMap.empty())
430 return;
431
432 if (!ResolveUsers) {
433 UseMap.clear();
434 return;
435 }
436
437 // Copy out uses since UseMap could get touched below.
438 using UseTy = std::pair<void *, std::pair<OwnerTy, uint64_t>>;
439 SmallVector<UseTy, 8> Uses(UseMap.begin(), UseMap.end());
440 llvm::sort(Uses, [](const UseTy &L, const UseTy &R) {
441 return L.second.second < R.second.second;
442 });
443 UseMap.clear();
444 for (const auto &Pair : Uses) {
445 auto Owner = Pair.second.first;
446 if (!Owner)
447 continue;
449 continue;
450
451 // Resolve MDNodes that point at this.
453 if (!OwnerMD)
454 continue;
455 if (OwnerMD->isResolved())
456 continue;
457 OwnerMD->decrementUnresolvedOperandCount();
458 }
459}
460
461// Special handing of DIArgList is required in the RemoveDIs project, see
462// commentry in DIArgList::handleChangedOperand for details. Hidden behind
463// conditional compilation to avoid a compile time regression.
464ReplaceableMetadataImpl *ReplaceableMetadataImpl::getOrCreate(Metadata &MD) {
465 if (auto *N = dyn_cast<MDNode>(&MD)) {
466 return !N->isResolved() || N->isAlwaysReplaceable()
467 ? N->Context.getOrCreateReplaceableUses()
468 : nullptr;
469 }
470 if (auto ArgList = dyn_cast<DIArgList>(&MD))
471 return ArgList;
472 return dyn_cast<ValueAsMetadata>(&MD);
473}
474
475ReplaceableMetadataImpl *ReplaceableMetadataImpl::getIfExists(Metadata &MD) {
476 if (auto *N = dyn_cast<MDNode>(&MD)) {
477 return !N->isResolved() || N->isAlwaysReplaceable()
478 ? N->Context.getReplaceableUses()
479 : nullptr;
480 }
481 if (auto ArgList = dyn_cast<DIArgList>(&MD))
482 return ArgList;
483 return dyn_cast<ValueAsMetadata>(&MD);
484}
485
486bool ReplaceableMetadataImpl::isReplaceable(const Metadata &MD) {
487 if (auto *N = dyn_cast<MDNode>(&MD))
488 return !N->isResolved() || N->isAlwaysReplaceable();
489 return isa<ValueAsMetadata>(&MD) || isa<DIArgList>(&MD);
490}
491
493 assert(V && "Expected value");
494 if (auto *A = dyn_cast<Argument>(V)) {
495 if (auto *Fn = A->getParent())
496 return Fn->getSubprogram();
497 return nullptr;
498 }
499
500 if (BasicBlock *BB = cast<Instruction>(V)->getParent()) {
501 if (auto *Fn = BB->getParent())
502 return Fn->getSubprogram();
503 return nullptr;
504 }
505
506 return nullptr;
507}
508
510 assert(V && "Unexpected null Value");
511
512 auto &Context = V->getContext();
513 auto *&Entry = Context.pImpl->ValuesAsMetadata[V];
514 if (!Entry) {
516 "Expected constant or function-local value");
517 assert(!V->IsUsedByMD && "Expected this to be the only metadata use");
518 V->IsUsedByMD = true;
519 if (auto *C = dyn_cast<Constant>(V))
520 Entry = new ConstantAsMetadata(C);
521 else
522 Entry = new LocalAsMetadata(V);
523 }
524
525 return Entry;
526}
527
529 assert(V && "Unexpected null Value");
530 return V->getContext().pImpl->ValuesAsMetadata.lookup(V);
531}
532
534 assert(V && "Expected valid value");
535
536 auto &Store = V->getType()->getContext().pImpl->ValuesAsMetadata;
537 auto I = Store.find(V);
538 if (I == Store.end())
539 return;
540
541 // Remove old entry from the map.
542 ValueAsMetadata *MD = I->second;
543 assert(MD && "Expected valid metadata");
544 assert(MD->getValue() == V && "Expected valid mapping");
545 Store.erase(I);
546
547 // Delete the metadata.
548 MD->replaceAllUsesWith(nullptr);
549 delete MD;
550}
551
553 assert(From && "Expected valid value");
554 assert(To && "Expected valid value");
555 assert(From != To && "Expected changed value");
556 assert(&From->getContext() == &To->getContext() && "Expected same context");
557
558 LLVMContext &Context = From->getType()->getContext();
559 auto &Store = Context.pImpl->ValuesAsMetadata;
560 auto I = Store.find(From);
561 if (I == Store.end()) {
562 assert(!From->IsUsedByMD && "Expected From not to be used by metadata");
563 return;
564 }
565
566 // Remove old entry from the map.
567 assert(From->IsUsedByMD && "Expected From to be used by metadata");
568 From->IsUsedByMD = false;
569 ValueAsMetadata *MD = I->second;
570 assert(MD && "Expected valid metadata");
571 assert(MD->getValue() == From && "Expected valid mapping");
572 Store.erase(I);
573
574 if (isa<LocalAsMetadata>(MD)) {
575 if (auto *C = dyn_cast<Constant>(To)) {
576 // Local became a constant.
578 delete MD;
579 return;
580 }
583 // DISubprogram changed.
584 MD->replaceAllUsesWith(nullptr);
585 delete MD;
586 return;
587 }
588 } else if (!isa<Constant>(To)) {
589 // Changed to function-local value.
590 MD->replaceAllUsesWith(nullptr);
591 delete MD;
592 return;
593 }
594
595 auto *&Entry = Store[To];
596 if (Entry) {
597 // The target already exists.
598 MD->replaceAllUsesWith(Entry);
599 delete MD;
600 return;
601 }
602
603 // Update MD in place (and update the map entry).
604 assert(!To->IsUsedByMD && "Expected this to be the only metadata use");
605 To->IsUsedByMD = true;
606 MD->V = To;
607 Entry = MD;
608}
609
610//===----------------------------------------------------------------------===//
611// MDString implementation.
612//
613
614MDString *MDString::get(LLVMContext &Context, StringRef Str) {
615 auto &Store = Context.pImpl->MDStringCache;
616 auto I = Store.try_emplace(Str);
617 auto &MapEntry = I.first->getValue();
618 if (!I.second)
619 return &MapEntry;
620 MapEntry.Entry = &*I.first;
621 return &MapEntry;
622}
623
625 assert(Entry && "Expected to find string map entry");
626 return Entry->first();
627}
628
629//===----------------------------------------------------------------------===//
630// MDNode implementation.
631//
633// Assert that the MDNode types will not be unaligned by the objects
634// prepended to them.
635#define HANDLE_MDNODE_LEAF(CLASS) \
636 static_assert( \
637 alignof(uint64_t) >= alignof(CLASS), \
638 "Alignment is insufficient after objects prepended to " #CLASS);
639#include "llvm/IR/Metadata.def"
640
641void *MDNode::operator new(size_t Size, size_t NumOps, StorageType Storage) {
642 // uint64_t is the most aligned type we need support (ensured by static_assert
643 // above)
644 size_t AllocSize =
645 alignTo(Header::getAllocSize(Storage, NumOps), alignof(uint64_t));
646 char *Mem = reinterpret_cast<char *>(::operator new(AllocSize + Size));
647 Header *H = new (Mem + AllocSize - sizeof(Header)) Header(NumOps, Storage);
648 return reinterpret_cast<void *>(H + 1);
649}
650
651void MDNode::operator delete(void *N) {
652 Header *H = reinterpret_cast<Header *>(N) - 1;
653 void *Mem = H->getAllocation();
654 H->~Header();
655 ::operator delete(Mem);
656}
657
660 : Metadata(ID, Storage), Context(Context) {
661 unsigned Op = 0;
662 for (Metadata *MD : Ops1)
663 setOperand(Op++, MD);
664 for (Metadata *MD : Ops2)
665 setOperand(Op++, MD);
666
667 if (!isUniqued())
668 return;
669
670 // Count the unresolved operands. If there are any, RAUW support will be
671 // added lazily on first reference.
672 countUnresolvedOperands();
673}
674
675TempMDNode MDNode::clone() const {
676 switch (getMetadataID()) {
677 default:
678 llvm_unreachable("Invalid MDNode subclass");
679#define HANDLE_MDNODE_LEAF(CLASS) \
680 case CLASS##Kind: \
681 return cast<CLASS>(this)->cloneImpl();
682#include "llvm/IR/Metadata.def"
683 }
684}
685
686MDNode::Header::Header(size_t NumOps, StorageType Storage) {
687 IsLarge = isLarge(NumOps);
688 IsResizable = isResizable(Storage);
689 SmallSize = getSmallSize(NumOps, IsResizable, IsLarge);
690 if (IsLarge) {
691 SmallNumOps = 0;
692 new (getLargePtr()) LargeStorageVector();
693 getLarge().resize(NumOps);
694 return;
695 }
696 SmallNumOps = NumOps;
697 MDOperand *O = reinterpret_cast<MDOperand *>(this) - SmallSize;
698 for (MDOperand *E = O + SmallSize; O != E;)
699 (void)new (O++) MDOperand();
700}
701
702MDNode::Header::~Header() {
703 if (IsLarge) {
704 getLarge().~LargeStorageVector();
705 return;
706 }
707 MDOperand *O = reinterpret_cast<MDOperand *>(this);
708 for (MDOperand *E = O - SmallSize; O != E; --O)
709 (O - 1)->~MDOperand();
710}
711
712void *MDNode::Header::getSmallPtr() {
713 static_assert(alignof(MDOperand) <= alignof(Header),
714 "MDOperand too strongly aligned");
715 return reinterpret_cast<char *>(const_cast<Header *>(this)) -
716 sizeof(MDOperand) * SmallSize;
717}
718
719void MDNode::Header::resize(size_t NumOps) {
720 assert(IsResizable && "Node is not resizable");
721 if (operands().size() == NumOps)
722 return;
723
724 if (IsLarge)
725 getLarge().resize(NumOps);
726 else if (NumOps <= SmallSize)
727 resizeSmall(NumOps);
728 else
729 resizeSmallToLarge(NumOps);
730}
731
732void MDNode::Header::resizeSmall(size_t NumOps) {
733 assert(!IsLarge && "Expected a small MDNode");
734 assert(NumOps <= SmallSize && "NumOps too large for small resize");
735
736 MutableArrayRef<MDOperand> ExistingOps = operands();
737 assert(NumOps != ExistingOps.size() && "Expected a different size");
738
739 int NumNew = (int)NumOps - (int)ExistingOps.size();
740 MDOperand *O = ExistingOps.end();
741 for (int I = 0, E = NumNew; I < E; ++I)
742 (O++)->reset();
743 for (int I = 0, E = NumNew; I > E; --I)
744 (--O)->reset();
745 SmallNumOps = NumOps;
746 assert(O == operands().end() && "Operands not (un)initialized until the end");
747}
748
749void MDNode::Header::resizeSmallToLarge(size_t NumOps) {
750 assert(!IsLarge && "Expected a small MDNode");
751 assert(NumOps > SmallSize && "Expected NumOps to be larger than allocation");
752 LargeStorageVector NewOps;
753 NewOps.resize(NumOps);
754 llvm::move(operands(), NewOps.begin());
755 resizeSmall(0);
756 new (getLargePtr()) LargeStorageVector(std::move(NewOps));
757 IsLarge = true;
758}
759
761 if (auto *N = dyn_cast_or_null<MDNode>(Op))
762 return !N->isResolved();
763 return false;
764}
765
766void MDNode::countUnresolvedOperands() {
767 assert(getNumUnresolved() == 0 && "Expected unresolved ops to be uncounted");
768 assert(isUniqued() && "Expected this to be uniqued");
770}
771
772void MDNode::makeUniqued() {
773 assert(isTemporary() && "Expected this to be temporary");
774 assert(!isResolved() && "Expected this to be unresolved");
775
776 // Enable uniquing callbacks.
777 for (auto &Op : mutable_operands())
778 Op.reset(Op.get(), this);
779
780 // Make this 'uniqued'.
782 countUnresolvedOperands();
783 if (!getNumUnresolved()) {
784 dropReplaceableUses();
785 assert(isResolved() && "Expected this to be resolved");
786 }
787
788 assert(isUniqued() && "Expected this to be uniqued");
789}
790
791void MDNode::makeDistinct() {
792 assert(isTemporary() && "Expected this to be temporary");
793 assert(!isResolved() && "Expected this to be unresolved");
794
795 // Drop RAUW support and store as a distinct node.
796 dropReplaceableUses();
798
799 assert(isDistinct() && "Expected this to be distinct");
800 assert(isResolved() && "Expected this to be resolved");
801}
802
804 assert(isUniqued() && "Expected this to be uniqued");
805 assert(!isResolved() && "Expected this to be unresolved");
806
808 dropReplaceableUses();
809
810 assert(isResolved() && "Expected this to be resolved");
811}
812
813void MDNode::dropReplaceableUses() {
814 assert(!getNumUnresolved() && "Unexpected unresolved operand");
815
816 // Drop any RAUW support.
817 if (Context.hasReplaceableUses())
818 Context.takeReplaceableUses()->resolveAllUses();
819}
820
821void MDNode::resolveAfterOperandChange(Metadata *Old, Metadata *New) {
822 assert(isUniqued() && "Expected this to be uniqued");
823 assert(getNumUnresolved() != 0 && "Expected unresolved operands");
824
825 // Check if an operand was resolved.
826 if (!isOperandUnresolved(Old)) {
827 if (isOperandUnresolved(New))
828 // An operand was un-resolved!
830 } else if (!isOperandUnresolved(New))
831 decrementUnresolvedOperandCount();
832}
833
834void MDNode::decrementUnresolvedOperandCount() {
835 assert(!isResolved() && "Expected this to be unresolved");
836 if (isTemporary())
837 return;
838
839 assert(isUniqued() && "Expected this to be uniqued");
841 if (getNumUnresolved())
842 return;
843
844 // Last unresolved operand has just been resolved.
845 dropReplaceableUses();
846 assert(isResolved() && "Expected this to become resolved");
847}
848
850 if (isResolved())
851 return;
852
853 // Resolve this node immediately.
854 resolve();
855
856 // Resolve all operands.
857 for (const auto &Op : operands()) {
859 if (!N)
860 continue;
861
862 assert(!N->isTemporary() &&
863 "Expected all forward declarations to be resolved");
864 if (!N->isResolved())
865 N->resolveCycles();
866 }
867}
868
869static bool hasSelfReference(MDNode *N) {
870 return llvm::is_contained(N->operands(), N);
871}
872
873MDNode *MDNode::replaceWithPermanentImpl() {
874 switch (getMetadataID()) {
875 default:
876 // If this type isn't uniquable, replace with a distinct node.
877 return replaceWithDistinctImpl();
878
879#define HANDLE_MDNODE_LEAF_UNIQUABLE(CLASS) \
880 case CLASS##Kind: \
881 break;
882#include "llvm/IR/Metadata.def"
883 }
884
885 // Even if this type is uniquable, self-references have to be distinct.
886 if (hasSelfReference(this))
887 return replaceWithDistinctImpl();
888 return replaceWithUniquedImpl();
889}
890
891MDNode *MDNode::replaceWithUniquedImpl() {
892 // Try to uniquify in place.
893 MDNode *UniquedNode = uniquify();
894
895 if (UniquedNode == this) {
896 makeUniqued();
897 return this;
898 }
899
900 // Collision, so RAUW instead.
901 replaceAllUsesWith(UniquedNode);
902 deleteAsSubclass();
903 return UniquedNode;
904}
905
906MDNode *MDNode::replaceWithDistinctImpl() {
907 makeDistinct();
908 return this;
909}
910
911void MDTuple::recalculateHash() {
912 setHash(MDTupleInfo::KeyTy::calculateHash(this));
913}
914
916 for (unsigned I = 0, E = getNumOperands(); I != E; ++I)
917 setOperand(I, nullptr);
918 if (Context.hasReplaceableUses()) {
919 Context.getReplaceableUses()->resolveAllUses(/* ResolveUsers */ false);
920 (void)Context.takeReplaceableUses();
921 }
922}
923
924void MDNode::handleChangedOperand(void *Ref, Metadata *New) {
925 unsigned Op = static_cast<MDOperand *>(Ref) - op_begin();
926 assert(Op < getNumOperands() && "Expected valid operand");
927
928 if (!isUniqued()) {
929 // This node is not uniqued. Just set the operand and be done with it.
930 setOperand(Op, New);
931 return;
932 }
933
934 // This node is uniqued.
935 eraseFromStore();
936
937 Metadata *Old = getOperand(Op);
938 setOperand(Op, New);
939
940 // Drop uniquing for self-reference cycles and deleted constants.
941 if (New == this || (!New && Old && isa<ConstantAsMetadata>(Old))) {
942 if (!isResolved())
943 resolve();
945 return;
946 }
947
948 // Re-unique the node.
949 auto *Uniqued = uniquify();
950 if (Uniqued == this) {
951 if (!isResolved())
952 resolveAfterOperandChange(Old, New);
953 return;
954 }
955
956 // Collision.
957 if (!isResolved()) {
958 // Still unresolved, so RAUW.
959 //
960 // First, clear out all operands to prevent any recursion (similar to
961 // dropAllReferences(), but we still need the use-list).
962 for (unsigned O = 0, E = getNumOperands(); O != E; ++O)
963 setOperand(O, nullptr);
964 if (Context.hasReplaceableUses())
965 Context.getReplaceableUses()->replaceAllUsesWith(Uniqued);
966 deleteAsSubclass();
967 return;
968 }
969
970 // Store in non-uniqued form if RAUW isn't possible.
972}
973
974void MDNode::deleteAsSubclass() {
975 switch (getMetadataID()) {
976 default:
977 llvm_unreachable("Invalid subclass of MDNode");
978#define HANDLE_MDNODE_LEAF(CLASS) \
979 case CLASS##Kind: \
980 delete cast<CLASS>(this); \
981 break;
982#include "llvm/IR/Metadata.def"
983 }
984}
985
986template <class T, class InfoT>
988 if (T *U = getUniqued(Store, N))
989 return U;
990
991 Store.insert(N);
992 return N;
993}
994
995template <class NodeTy> struct MDNode::HasCachedHash {
996 template <class U>
997 static std::true_type check(SameType<void (U::*)(unsigned), &U::setHash> *);
998 template <class U> static std::false_type check(...);
999
1000 static constexpr bool value = decltype(check<NodeTy>(nullptr))::value;
1001};
1002
1003MDNode *MDNode::uniquify() {
1004 assert(!hasSelfReference(this) && "Cannot uniquify a self-referencing node");
1005
1006 // Try to insert into uniquing store.
1007 switch (getMetadataID()) {
1008 default:
1009 llvm_unreachable("Invalid or non-uniquable subclass of MDNode");
1010#define HANDLE_MDNODE_LEAF_UNIQUABLE(CLASS) \
1011 case CLASS##Kind: { \
1012 CLASS *SubclassThis = cast<CLASS>(this); \
1013 dispatchRecalculateHash(SubclassThis); \
1014 return uniquifyImpl(SubclassThis, getContext().pImpl->CLASS##s); \
1015 }
1016#include "llvm/IR/Metadata.def"
1017 }
1018}
1019
1020void MDNode::eraseFromStore() {
1021 switch (getMetadataID()) {
1022 default:
1023 llvm_unreachable("Invalid or non-uniquable subclass of MDNode");
1024#define HANDLE_MDNODE_LEAF_UNIQUABLE(CLASS) \
1025 case CLASS##Kind: \
1026 getContext().pImpl->CLASS##s.erase(cast<CLASS>(this)); \
1027 break;
1028#include "llvm/IR/Metadata.def"
1029 }
1030}
1031
1032MDTuple *MDTuple::getImpl(LLVMContext &Context, ArrayRef<Metadata *> MDs,
1033 StorageType Storage, bool ShouldCreate) {
1034 unsigned Hash = 0;
1035 if (Storage == Uniqued) {
1036 MDTupleInfo::KeyTy Key(MDs);
1037 if (auto *N = getUniqued(Context.pImpl->MDTuples, Key))
1038 return N;
1039 if (!ShouldCreate)
1040 return nullptr;
1041 Hash = Key.getHash();
1042 } else {
1043 assert(ShouldCreate && "Expected non-uniqued nodes to always be created");
1044 }
1045
1046 return storeImpl(new (MDs.size(), Storage)
1047 MDTuple(Context, Storage, Hash, MDs),
1048 Storage, Context.pImpl->MDTuples);
1049}
1050
1052 assert(N->isTemporary() && "Expected temporary node");
1053 N->replaceAllUsesWith(nullptr);
1054 N->deleteAsSubclass();
1055}
1056
1058 assert(!Context.hasReplaceableUses() && "Unexpected replaceable uses");
1059 assert(!getNumUnresolved() && "Unexpected unresolved nodes");
1060 Storage = Distinct;
1061 assert(isResolved() && "Expected this to be resolved");
1062
1063 // Reset the hash.
1064 switch (getMetadataID()) {
1065 default:
1066 llvm_unreachable("Invalid subclass of MDNode");
1067#define HANDLE_MDNODE_LEAF(CLASS) \
1068 case CLASS##Kind: { \
1069 dispatchResetHash(cast<CLASS>(this)); \
1070 break; \
1071 }
1072#include "llvm/IR/Metadata.def"
1073 }
1074
1075 getContext().pImpl->DistinctMDNodes.push_back(this);
1076}
1077
1079 if (getOperand(I) == New)
1080 return;
1081
1082 if (!isUniqued()) {
1083 setOperand(I, New);
1084 return;
1085 }
1086
1087 handleChangedOperand(mutable_begin() + I, New);
1088}
1089
1090void MDNode::setOperand(unsigned I, Metadata *New) {
1091 assert(I < getNumOperands());
1092 mutable_begin()[I].reset(New, isUniqued() ? this : nullptr);
1093}
1094
1095/// Get a node or a self-reference that looks like it.
1096///
1097/// Special handling for finding self-references, for use by \a
1098/// MDNode::concatenate() and \a MDNode::intersect() to maintain behaviour from
1099/// when self-referencing nodes were still uniqued. If the first operand has
1100/// the same operands as \c Ops, return the first operand instead.
1103 if (!Ops.empty())
1105 if (N->getNumOperands() == Ops.size() && N == N->getOperand(0)) {
1106 for (unsigned I = 1, E = Ops.size(); I != E; ++I)
1107 if (Ops[I] != N->getOperand(I))
1108 return MDNode::get(Context, Ops);
1109 return N;
1110 }
1111
1112 return MDNode::get(Context, Ops);
1113}
1114
1116 if (!A)
1117 return B;
1118 if (!B)
1119 return A;
1120
1121 SmallSetVector<Metadata *, 4> MDs(A->op_begin(), A->op_end());
1122 MDs.insert(B->op_begin(), B->op_end());
1123
1124 // FIXME: This preserves long-standing behaviour, but is it really the right
1125 // behaviour? Or was that an unintended side-effect of node uniquing?
1126 return getOrSelfReference(A->getContext(), MDs.getArrayRef());
1127}
1128
1130 if (!A || !B)
1131 return nullptr;
1132
1133 SmallSetVector<Metadata *, 4> MDs(A->op_begin(), A->op_end());
1134 SmallPtrSet<Metadata *, 4> BSet(B->op_begin(), B->op_end());
1135 MDs.remove_if([&](Metadata *MD) { return !BSet.count(MD); });
1136
1137 // FIXME: This preserves long-standing behaviour, but is it really the right
1138 // behaviour? Or was that an unintended side-effect of node uniquing?
1139 return getOrSelfReference(A->getContext(), MDs.getArrayRef());
1140}
1141
1143 if (!A || !B)
1144 return nullptr;
1145
1146 // Take the intersection of domains then union the scopes
1147 // within those domains
1149 SmallPtrSet<const MDNode *, 16> IntersectDomains;
1151 for (const MDOperand &MDOp : A->operands())
1152 if (const MDNode *NAMD = dyn_cast<MDNode>(MDOp))
1153 if (const MDNode *Domain = AliasScopeNode(NAMD).getDomain())
1154 ADomains.insert(Domain);
1155
1156 for (const MDOperand &MDOp : B->operands())
1157 if (const MDNode *NAMD = dyn_cast<MDNode>(MDOp))
1158 if (const MDNode *Domain = AliasScopeNode(NAMD).getDomain())
1159 if (ADomains.contains(Domain)) {
1160 IntersectDomains.insert(Domain);
1161 MDs.insert(MDOp);
1162 }
1163
1164 for (const MDOperand &MDOp : A->operands())
1165 if (const MDNode *NAMD = dyn_cast<MDNode>(MDOp))
1166 if (const MDNode *Domain = AliasScopeNode(NAMD).getDomain())
1167 if (IntersectDomains.contains(Domain))
1168 MDs.insert(MDOp);
1169
1170 return MDs.empty() ? nullptr
1171 : getOrSelfReference(A->getContext(), MDs.getArrayRef());
1172}
1173
1175 if (!A || !B)
1176 return nullptr;
1177
1178 APFloat AVal = mdconst::extract<ConstantFP>(A->getOperand(0))->getValueAPF();
1179 APFloat BVal = mdconst::extract<ConstantFP>(B->getOperand(0))->getValueAPF();
1180 if (AVal < BVal)
1181 return A;
1182 return B;
1183}
1184
1185// Call instructions with branch weights are only used in SamplePGO as
1186// documented in
1187/// https://llvm.org/docs/BranchWeightMetadata.html#callinst).
1188MDNode *MDNode::mergeDirectCallProfMetadata(MDNode *A, MDNode *B,
1189 const Instruction *AInstr,
1190 const Instruction *BInstr) {
1191 assert(A && B && AInstr && BInstr && "Caller should guarantee");
1192 auto &Ctx = AInstr->getContext();
1193 MDBuilder MDHelper(Ctx);
1194
1195 // LLVM IR verifier verifies !prof metadata has at least 2 operands.
1196 assert(A->getNumOperands() >= 2 && B->getNumOperands() >= 2 &&
1197 "!prof annotations should have no less than 2 operands");
1198 MDString *AMDS = dyn_cast<MDString>(A->getOperand(0));
1199 MDString *BMDS = dyn_cast<MDString>(B->getOperand(0));
1200 // LLVM IR verfier verifies first operand is MDString.
1201 assert(AMDS != nullptr && BMDS != nullptr &&
1202 "first operand should be a non-null MDString");
1203 StringRef AProfName = AMDS->getString();
1204 StringRef BProfName = BMDS->getString();
1205 if (AProfName == MDProfLabels::BranchWeights &&
1206 BProfName == MDProfLabels::BranchWeights) {
1208 A->getOperand(getBranchWeightOffset(A)));
1210 B->getOperand(getBranchWeightOffset(B)));
1211 assert(AInstrWeight && BInstrWeight && "verified by LLVM verifier");
1212 return MDNode::get(Ctx,
1213 {MDHelper.createString(MDProfLabels::BranchWeights),
1214 MDHelper.createConstant(ConstantInt::get(
1215 Type::getInt64Ty(Ctx),
1216 SaturatingAdd(AInstrWeight->getZExtValue(),
1217 BInstrWeight->getZExtValue())))});
1218 }
1219 return nullptr;
1220}
1221
1222// Pass in both instructions and nodes. Instruction information (e.g.,
1223// instruction type) helps interpret profiles and make implementation clearer.
1225 const Instruction *AInstr,
1226 const Instruction *BInstr) {
1227 // Check that it is legal to merge prof metadata based on the opcode.
1228 auto IsLegal = [](const Instruction &I) -> bool {
1229 switch (I.getOpcode()) {
1230 case Instruction::Invoke:
1231 case Instruction::Br:
1232 case Instruction::Switch:
1233 case Instruction::Call:
1234 case Instruction::IndirectBr:
1235 case Instruction::Select:
1236 case Instruction::CallBr:
1237 return true;
1238 default:
1239 return false;
1240 }
1241 };
1242 if (AInstr && !IsLegal(*AInstr))
1243 return nullptr;
1244 if (BInstr && !IsLegal(*BInstr))
1245 return nullptr;
1246
1247 if (!(A && B)) {
1248 return A ? A : B;
1249 }
1250
1251 assert(AInstr->getMetadata(LLVMContext::MD_prof) == A &&
1252 "Caller should guarantee");
1253 assert(BInstr->getMetadata(LLVMContext::MD_prof) == B &&
1254 "Caller should guarantee");
1255
1256 const CallInst *ACall = dyn_cast<CallInst>(AInstr);
1257 const CallInst *BCall = dyn_cast<CallInst>(BInstr);
1258
1259 // Both ACall and BCall are direct callsites.
1260 if (ACall && BCall && ACall->getCalledFunction() &&
1261 BCall->getCalledFunction())
1262 return mergeDirectCallProfMetadata(A, B, AInstr, BInstr);
1263
1265 return A;
1266
1267 // The rest of the cases are not implemented but could be added
1268 // when there are use cases.
1269 return nullptr;
1270}
1271
1272static bool isContiguous(const ConstantRange &A, const ConstantRange &B) {
1273 return A.getUpper() == B.getLower() || A.getLower() == B.getUpper();
1274}
1275
1276static bool canBeMerged(const ConstantRange &A, const ConstantRange &B) {
1277 return !A.intersectWith(B).isEmptySet() || isContiguous(A, B);
1278}
1279
1282 ConstantRange NewRange(Low->getValue(), High->getValue());
1283 unsigned Size = EndPoints.size();
1284 const APInt &LB = EndPoints[Size - 2]->getValue();
1285 const APInt &LE = EndPoints[Size - 1]->getValue();
1286 ConstantRange LastRange(LB, LE);
1287 if (canBeMerged(NewRange, LastRange)) {
1288 ConstantRange Union = LastRange.unionWith(NewRange);
1289 Type *Ty = High->getType();
1290 EndPoints[Size - 2] =
1291 cast<ConstantInt>(ConstantInt::get(Ty, Union.getLower()));
1292 EndPoints[Size - 1] =
1293 cast<ConstantInt>(ConstantInt::get(Ty, Union.getUpper()));
1294 return true;
1295 }
1296 return false;
1297}
1298
1301 if (!EndPoints.empty())
1302 if (tryMergeRange(EndPoints, Low, High))
1303 return;
1304
1305 EndPoints.push_back(Low);
1306 EndPoints.push_back(High);
1307}
1308
1310 // Drop the callee_type metadata if either of the call instructions do not
1311 // have it.
1312 if (!A || !B)
1313 return nullptr;
1315 SmallPtrSet<Metadata *, 8> MergedCallees;
1316 auto AddUniqueCallees = [&AB, &MergedCallees](const MDNode *N) {
1317 for (Metadata *MD : N->operands()) {
1318 if (MergedCallees.insert(MD).second)
1319 AB.push_back(MD);
1320 }
1321 };
1322 AddUniqueCallees(A);
1323 AddUniqueCallees(B);
1324 return MDNode::get(A->getContext(), AB);
1325}
1326
1328 // Given two ranges, we want to compute the union of the ranges. This
1329 // is slightly complicated by having to combine the intervals and merge
1330 // the ones that overlap.
1331
1332 if (!A || !B)
1333 return nullptr;
1334
1335 if (A == B)
1336 return A;
1337
1338 // First, walk both lists in order of the lower boundary of each interval.
1339 // At each step, try to merge the new interval to the last one we added.
1341 unsigned AI = 0;
1342 unsigned BI = 0;
1343 unsigned AN = A->getNumOperands() / 2;
1344 unsigned BN = B->getNumOperands() / 2;
1345 while (AI < AN && BI < BN) {
1346 ConstantInt *ALow = mdconst::extract<ConstantInt>(A->getOperand(2 * AI));
1347 ConstantInt *BLow = mdconst::extract<ConstantInt>(B->getOperand(2 * BI));
1348
1349 if (ALow->getValue().slt(BLow->getValue())) {
1350 addRange(EndPoints, ALow,
1351 mdconst::extract<ConstantInt>(A->getOperand(2 * AI + 1)));
1352 ++AI;
1353 } else {
1354 addRange(EndPoints, BLow,
1355 mdconst::extract<ConstantInt>(B->getOperand(2 * BI + 1)));
1356 ++BI;
1357 }
1358 }
1359 while (AI < AN) {
1360 addRange(EndPoints, mdconst::extract<ConstantInt>(A->getOperand(2 * AI)),
1361 mdconst::extract<ConstantInt>(A->getOperand(2 * AI + 1)));
1362 ++AI;
1363 }
1364 while (BI < BN) {
1365 addRange(EndPoints, mdconst::extract<ConstantInt>(B->getOperand(2 * BI)),
1366 mdconst::extract<ConstantInt>(B->getOperand(2 * BI + 1)));
1367 ++BI;
1368 }
1369
1370 // We haven't handled wrap in the previous merge,
1371 // if we have at least 2 ranges (4 endpoints) we have to try to merge
1372 // the last and first ones.
1373 unsigned Size = EndPoints.size();
1374 if (Size > 2) {
1375 ConstantInt *FB = EndPoints[0];
1376 ConstantInt *FE = EndPoints[1];
1377 if (tryMergeRange(EndPoints, FB, FE)) {
1378 for (unsigned i = 0; i < Size - 2; ++i) {
1379 EndPoints[i] = EndPoints[i + 2];
1380 }
1381 EndPoints.resize(Size - 2);
1382 }
1383 }
1384
1385 // If in the end we have a single range, it is possible that it is now the
1386 // full range. Just drop the metadata in that case.
1387 if (EndPoints.size() == 2) {
1388 ConstantRange Range(EndPoints[0]->getValue(), EndPoints[1]->getValue());
1389 if (Range.isFullSet())
1390 return nullptr;
1391 }
1392
1394 MDs.reserve(EndPoints.size());
1395 for (auto *I : EndPoints)
1397 return MDNode::get(A->getContext(), MDs);
1398}
1399
1401 if (!A || !B)
1402 return nullptr;
1403
1404 if (A == B)
1405 return A;
1406
1407 SmallVector<ConstantRange> RangeListA, RangeListB;
1408 for (unsigned I = 0, E = A->getNumOperands() / 2; I != E; ++I) {
1409 auto *LowA = mdconst::extract<ConstantInt>(A->getOperand(2 * I + 0));
1410 auto *HighA = mdconst::extract<ConstantInt>(A->getOperand(2 * I + 1));
1411 RangeListA.push_back(ConstantRange(LowA->getValue(), HighA->getValue()));
1412 }
1413
1414 for (unsigned I = 0, E = B->getNumOperands() / 2; I != E; ++I) {
1415 auto *LowB = mdconst::extract<ConstantInt>(B->getOperand(2 * I + 0));
1416 auto *HighB = mdconst::extract<ConstantInt>(B->getOperand(2 * I + 1));
1417 RangeListB.push_back(ConstantRange(LowB->getValue(), HighB->getValue()));
1418 }
1419
1420 ConstantRangeList CRLA(RangeListA);
1421 ConstantRangeList CRLB(RangeListB);
1422 ConstantRangeList Result = CRLA.intersectWith(CRLB);
1423 if (Result.empty())
1424 return nullptr;
1425
1427 for (const ConstantRange &CR : Result) {
1429 ConstantInt::get(A->getContext(), CR.getLower())));
1431 ConstantInt::get(A->getContext(), CR.getUpper())));
1432 }
1433
1434 return MDNode::get(A->getContext(), MDs);
1435}
1436
1438 if (!A || !B)
1439 return nullptr;
1440
1441 ConstantInt *AVal = mdconst::extract<ConstantInt>(A->getOperand(0));
1442 ConstantInt *BVal = mdconst::extract<ConstantInt>(B->getOperand(0));
1443 if (AVal->getZExtValue() < BVal->getZExtValue())
1444 return A;
1445 return B;
1446}
1447
1449 if (!MD)
1451
1453 for (Metadata *Op : MD->operands()) {
1454 CaptureComponents Component =
1456 .Case("address", CaptureComponents::Address)
1457 .Case("address_is_null", CaptureComponents::AddressIsNull)
1458 .Case("provenance", CaptureComponents::Provenance)
1459 .Case("read_provenance", CaptureComponents::ReadProvenance);
1460 CC |= Component;
1461 }
1462 return CC;
1463}
1464
1466 assert(!capturesNothing(CC) && "Can't encode captures(none)");
1467 if (capturesAll(CC))
1468 return nullptr;
1469
1470 SmallVector<Metadata *> Components;
1472 Components.push_back(MDString::get(Ctx, "address_is_null"));
1473 else if (capturesAddress(CC))
1474 Components.push_back(MDString::get(Ctx, "address"));
1476 Components.push_back(MDString::get(Ctx, "read_provenance"));
1477 else if (capturesFullProvenance(CC))
1478 Components.push_back(MDString::get(Ctx, "provenance"));
1479 return MDNode::get(Ctx, Components);
1480}
1481
1482//===----------------------------------------------------------------------===//
1483// NamedMDNode implementation.
1484//
1485
1487 return *(SmallVector<TrackingMDRef, 4> *)Operands;
1488}
1489
1490NamedMDNode::NamedMDNode(const Twine &N)
1491 : Name(N.str()), Operands(new SmallVector<TrackingMDRef, 4>()) {}
1492
1495 delete &getNMDOps(Operands);
1496}
1497
1499 return (unsigned)getNMDOps(Operands).size();
1500}
1501
1503 assert(i < getNumOperands() && "Invalid Operand number!");
1504 auto *N = getNMDOps(Operands)[i].get();
1505 return cast_or_null<MDNode>(N);
1506}
1507
1508void NamedMDNode::addOperand(MDNode *M) { getNMDOps(Operands).emplace_back(M); }
1509
1510void NamedMDNode::setOperand(unsigned I, MDNode *New) {
1511 assert(I < getNumOperands() && "Invalid operand number");
1512 getNMDOps(Operands)[I].reset(New);
1513}
1514
1516
1517void NamedMDNode::clearOperands() { getNMDOps(Operands).clear(); }
1518
1520
1521//===----------------------------------------------------------------------===//
1522// Instruction Metadata method implementations.
1523//
1524
1526 for (const auto &A : Attachments)
1527 if (A.MDKind == ID)
1528 return A.Node;
1529 return nullptr;
1530}
1531
1532void MDAttachments::get(unsigned ID, SmallVectorImpl<MDNode *> &Result) const {
1533 for (const auto &A : Attachments)
1534 if (A.MDKind == ID)
1535 Result.push_back(A.Node);
1536}
1537
1539 SmallVectorImpl<std::pair<unsigned, MDNode *>> &Result) const {
1540 for (const auto &A : Attachments)
1541 Result.emplace_back(A.MDKind, A.Node);
1542
1543 // Sort the resulting array so it is stable with respect to metadata IDs. We
1544 // need to preserve the original insertion order though.
1545 if (Result.size() > 1)
1546 llvm::stable_sort(Result, less_first());
1547}
1548
1549void MDAttachments::set(unsigned ID, MDNode *MD) {
1550 erase(ID);
1551 if (MD)
1552 insert(ID, *MD);
1553}
1554
1555void MDAttachments::insert(unsigned ID, MDNode &MD) {
1556 Attachments.push_back({ID, TrackingMDNodeRef(&MD)});
1557}
1558
1559bool MDAttachments::erase(unsigned ID) {
1560 if (empty())
1561 return false;
1562
1563 // Common case is one value.
1564 if (Attachments.size() == 1 && Attachments.back().MDKind == ID) {
1565 Attachments.pop_back();
1566 return true;
1567 }
1568
1569 auto OldSize = Attachments.size();
1570 llvm::erase_if(Attachments,
1571 [ID](const Attachment &A) { return A.MDKind == ID; });
1572 return OldSize != Attachments.size();
1573}
1574
1576 if (!hasMetadata())
1577 return nullptr;
1578 unsigned KindID = getContext().getMDKindID(Kind);
1579 return getMetadataImpl(KindID);
1580}
1581
1582MDNode *Value::getMetadataImpl(unsigned KindID) const {
1583 const LLVMContext &Ctx = getContext();
1584 const MDAttachments &Attachements = Ctx.pImpl->ValueMetadata.at(this);
1585 return Attachements.lookup(KindID);
1586}
1587
1588void Value::getMetadata(unsigned KindID, SmallVectorImpl<MDNode *> &MDs) const {
1589 if (hasMetadata())
1590 getContext().pImpl->ValueMetadata.at(this).get(KindID, MDs);
1591}
1592
1594 if (hasMetadata())
1595 getMetadata(getContext().getMDKindID(Kind), MDs);
1596}
1597
1599 SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs) const {
1600 if (hasMetadata()) {
1601 assert(getContext().pImpl->ValueMetadata.count(this) &&
1602 "bit out of sync with hash table");
1603 const MDAttachments &Info = getContext().pImpl->ValueMetadata.at(this);
1604 Info.getAll(MDs);
1605 }
1606}
1607
1608void Value::setMetadata(unsigned KindID, MDNode *Node) {
1610
1611 // Handle the case when we're adding/updating metadata on a value.
1612 if (Node) {
1614 assert(!Info.empty() == HasMetadata && "bit out of sync with hash table");
1615 if (Info.empty())
1616 HasMetadata = true;
1617 Info.set(KindID, Node);
1618 return;
1619 }
1620
1621 // Otherwise, we're removing metadata from an instruction.
1622 assert((HasMetadata == (getContext().pImpl->ValueMetadata.count(this) > 0)) &&
1623 "bit out of sync with hash table");
1624 if (!HasMetadata)
1625 return; // Nothing to remove!
1626 MDAttachments &Info = getContext().pImpl->ValueMetadata.find(this)->second;
1627
1628 // Handle removal of an existing value.
1629 Info.erase(KindID);
1630 if (!Info.empty())
1631 return;
1632 getContext().pImpl->ValueMetadata.erase(this);
1633 HasMetadata = false;
1634}
1635
1637 if (!Node && !HasMetadata)
1638 return;
1639 setMetadata(getContext().getMDKindID(Kind), Node);
1640}
1641
1642void Value::addMetadata(unsigned KindID, MDNode &MD) {
1644 if (!HasMetadata)
1645 HasMetadata = true;
1646 getContext().pImpl->ValueMetadata[this].insert(KindID, MD);
1647}
1648
1650 addMetadata(getContext().getMDKindID(Kind), MD);
1651}
1652
1653bool Value::eraseMetadata(unsigned KindID) {
1654 // Nothing to unset.
1655 if (!HasMetadata)
1656 return false;
1657
1658 MDAttachments &Store = getContext().pImpl->ValueMetadata.find(this)->second;
1659 bool Changed = Store.erase(KindID);
1660 if (Store.empty())
1661 clearMetadata();
1662 return Changed;
1663}
1664
1665void Value::eraseMetadataIf(function_ref<bool(unsigned, MDNode *)> Pred) {
1666 if (!HasMetadata)
1667 return;
1668
1669 auto &MetadataStore = getContext().pImpl->ValueMetadata;
1670 MDAttachments &Info = MetadataStore.find(this)->second;
1671 assert(!Info.empty() && "bit out of sync with hash table");
1672 Info.remove_if([Pred](const MDAttachments::Attachment &I) {
1673 return Pred(I.MDKind, I.Node);
1674 });
1675
1676 if (Info.empty())
1677 clearMetadata();
1678}
1679
1681 if (!HasMetadata)
1682 return;
1683 assert(getContext().pImpl->ValueMetadata.count(this) &&
1684 "bit out of sync with hash table");
1685 getContext().pImpl->ValueMetadata.erase(this);
1686 HasMetadata = false;
1687}
1688
1690 if (!Node && !hasMetadata())
1691 return;
1692 setMetadata(getContext().getMDKindID(Kind), Node);
1693}
1694
1695MDNode *Instruction::getMetadataImpl(StringRef Kind) const {
1696 const LLVMContext &Ctx = getContext();
1697 unsigned KindID = Ctx.getMDKindID(Kind);
1698 if (KindID == LLVMContext::MD_dbg)
1699 return DbgLoc.getAsMDNode();
1700 return Value::getMetadata(KindID);
1701}
1702
1703void Instruction::eraseMetadataIf(function_ref<bool(unsigned, MDNode *)> Pred) {
1704 if (DbgLoc && Pred(LLVMContext::MD_dbg, DbgLoc.getAsMDNode()))
1705 DbgLoc = {};
1706
1708}
1709
1711 if (!Value::hasMetadata())
1712 return; // Nothing to remove!
1713
1714 SmallSet<unsigned, 32> KnownSet(llvm::from_range, KnownIDs);
1715
1716 // A DIAssignID attachment is debug metadata, don't drop it.
1717 KnownSet.insert(LLVMContext::MD_DIAssignID);
1718
1719 Value::eraseMetadataIf([&KnownSet](unsigned MDKind, MDNode *Node) {
1720 return !KnownSet.count(MDKind);
1721 });
1722}
1723
1724void Instruction::updateDIAssignIDMapping(DIAssignID *ID) {
1725 auto &IDToInstrs = getContext().pImpl->AssignmentIDToInstrs;
1726 if (const DIAssignID *CurrentID =
1727 cast_or_null<DIAssignID>(getMetadata(LLVMContext::MD_DIAssignID))) {
1728 // Nothing to do if the ID isn't changing.
1729 if (ID == CurrentID)
1730 return;
1731
1732 // Unmap this instruction from its current ID.
1733 auto InstrsIt = IDToInstrs.find(CurrentID);
1734 assert(InstrsIt != IDToInstrs.end() &&
1735 "Expect existing attachment to be mapped");
1736
1737 auto &InstVec = InstrsIt->second;
1738 auto *InstIt = llvm::find(InstVec, this);
1739 assert(InstIt != InstVec.end() &&
1740 "Expect instruction to be mapped to attachment");
1741 // The vector contains a ptr to this. If this is the only element in the
1742 // vector, remove the ID:vector entry, otherwise just remove the
1743 // instruction from the vector.
1744 if (InstVec.size() == 1)
1745 IDToInstrs.erase(InstrsIt);
1746 else
1747 InstVec.erase(InstIt);
1748 }
1749
1750 // Map this instruction to the new ID.
1751 if (ID)
1752 IDToInstrs[ID].push_back(this);
1753}
1754
1755void Instruction::setMetadata(unsigned KindID, MDNode *Node) {
1756 if (!Node && !hasMetadata())
1757 return;
1758
1759 // Handle 'dbg' as a special case since it is not stored in the hash table.
1760 if (KindID == LLVMContext::MD_dbg) {
1761 DbgLoc = DebugLoc(Node);
1762 return;
1763 }
1764
1765 // Update DIAssignID to Instruction(s) mapping.
1766 if (KindID == LLVMContext::MD_DIAssignID) {
1767 // The DIAssignID tracking infrastructure doesn't support RAUWing temporary
1768 // nodes with DIAssignIDs. The cast_or_null below would also catch this, but
1769 // having a dedicated assert helps make this obvious.
1770 assert((!Node || !Node->isTemporary()) &&
1771 "Temporary DIAssignIDs are invalid");
1772 updateDIAssignIDMapping(cast_or_null<DIAssignID>(Node));
1773 }
1774
1775 Value::setMetadata(KindID, Node);
1776}
1777
1780 if (auto *Existing = getMetadata(LLVMContext::MD_annotation)) {
1781 SmallSetVector<StringRef, 2> AnnotationsSet(Annotations.begin(),
1782 Annotations.end());
1783 auto *Tuple = cast<MDTuple>(Existing);
1784 for (auto &N : Tuple->operands()) {
1785 if (isa<MDString>(N.get())) {
1786 Names.push_back(N);
1787 continue;
1788 }
1789 auto *MDAnnotationTuple = cast<MDTuple>(N);
1790 if (any_of(MDAnnotationTuple->operands(), [&AnnotationsSet](auto &Op) {
1791 return AnnotationsSet.contains(cast<MDString>(Op)->getString());
1792 }))
1793 return;
1794 Names.push_back(N);
1795 }
1796 }
1797
1798 MDBuilder MDB(getContext());
1799 SmallVector<Metadata *> MDAnnotationStrings;
1800 for (StringRef Annotation : Annotations)
1801 MDAnnotationStrings.push_back(MDB.createString(Annotation));
1802 MDNode *InfoTuple = MDTuple::get(getContext(), MDAnnotationStrings);
1803 Names.push_back(InfoTuple);
1804 MDNode *MD = MDTuple::get(getContext(), Names);
1805 setMetadata(LLVMContext::MD_annotation, MD);
1806}
1807
1810 if (auto *Existing = getMetadata(LLVMContext::MD_annotation)) {
1811 auto *Tuple = cast<MDTuple>(Existing);
1812 for (auto &N : Tuple->operands()) {
1813 if (isa<MDString>(N.get()) &&
1814 cast<MDString>(N.get())->getString() == Name)
1815 return;
1816 Names.push_back(N.get());
1817 }
1818 }
1819
1820 MDBuilder MDB(getContext());
1821 Names.push_back(MDB.createString(Name));
1822 MDNode *MD = MDTuple::get(getContext(), Names);
1823 setMetadata(LLVMContext::MD_annotation, MD);
1824}
1825
1827 AAMDNodes Result;
1828 // Not using Instruction::hasMetadata() because we're not interested in
1829 // DebugInfoMetadata.
1830 if (Value::hasMetadata()) {
1831 const MDAttachments &Info = getContext().pImpl->ValueMetadata.at(this);
1832 Result.TBAA = Info.lookup(LLVMContext::MD_tbaa);
1833 Result.TBAAStruct = Info.lookup(LLVMContext::MD_tbaa_struct);
1834 Result.Scope = Info.lookup(LLVMContext::MD_alias_scope);
1835 Result.NoAlias = Info.lookup(LLVMContext::MD_noalias);
1836 Result.NoAliasAddrSpace = Info.lookup(LLVMContext::MD_noalias_addrspace);
1837 }
1838 return Result;
1839}
1840
1842 setMetadata(LLVMContext::MD_tbaa, N.TBAA);
1843 setMetadata(LLVMContext::MD_tbaa_struct, N.TBAAStruct);
1844 setMetadata(LLVMContext::MD_alias_scope, N.Scope);
1845 setMetadata(LLVMContext::MD_noalias, N.NoAlias);
1846 setMetadata(LLVMContext::MD_noalias_addrspace, N.NoAliasAddrSpace);
1847}
1848
1850 setMetadata(llvm::LLVMContext::MD_nosanitize,
1852}
1853
1854void Instruction::getAllMetadataImpl(
1855 SmallVectorImpl<std::pair<unsigned, MDNode *>> &Result) const {
1856 Result.clear();
1857
1858 // Handle 'dbg' as a special case since it is not stored in the hash table.
1859 if (DbgLoc) {
1860 Result.push_back(
1861 std::make_pair((unsigned)LLVMContext::MD_dbg, DbgLoc.getAsMDNode()));
1862 }
1863 Value::getAllMetadata(Result);
1864}
1865
1867 assert(
1868 (getOpcode() == Instruction::Br || getOpcode() == Instruction::Select ||
1869 getOpcode() == Instruction::Call || getOpcode() == Instruction::Invoke ||
1870 getOpcode() == Instruction::IndirectBr ||
1871 getOpcode() == Instruction::Switch) &&
1872 "Looking for branch weights on something besides branch");
1873
1874 return ::extractProfTotalWeight(*this, TotalVal);
1875}
1876
1879 Other->getAllMetadata(MDs);
1880 for (auto &MD : MDs) {
1881 // We need to adjust the type metadata offset.
1882 if (Offset != 0 && MD.first == LLVMContext::MD_type) {
1883 auto *OffsetConst = cast<ConstantInt>(
1884 cast<ConstantAsMetadata>(MD.second->getOperand(0))->getValue());
1885 Metadata *TypeId = MD.second->getOperand(1);
1886 auto *NewOffsetMD = ConstantAsMetadata::get(ConstantInt::get(
1887 OffsetConst->getType(), OffsetConst->getValue() + Offset));
1888 addMetadata(LLVMContext::MD_type,
1889 *MDNode::get(getContext(), {NewOffsetMD, TypeId}));
1890 continue;
1891 }
1892 // If an offset adjustment was specified we need to modify the DIExpression
1893 // to prepend the adjustment:
1894 // !DIExpression(DW_OP_plus, Offset, [original expr])
1895 auto *Attachment = MD.second;
1896 if (Offset != 0 && MD.first == LLVMContext::MD_dbg) {
1898 DIExpression *E = nullptr;
1899 if (!GV) {
1900 auto *GVE = cast<DIGlobalVariableExpression>(Attachment);
1901 GV = GVE->getVariable();
1902 E = GVE->getExpression();
1903 }
1904 ArrayRef<uint64_t> OrigElements;
1905 if (E)
1906 OrigElements = E->getElements();
1907 std::vector<uint64_t> Elements(OrigElements.size() + 2);
1908 Elements[0] = dwarf::DW_OP_plus_uconst;
1909 Elements[1] = Offset;
1910 llvm::copy(OrigElements, Elements.begin() + 2);
1911 E = DIExpression::get(getContext(), Elements);
1912 Attachment = DIGlobalVariableExpression::get(getContext(), GV, E);
1913 }
1914 addMetadata(MD.first, *Attachment);
1915 }
1916}
1917
1920 LLVMContext::MD_type,
1922 {ConstantAsMetadata::get(ConstantInt::get(
1924 TypeID}));
1925}
1926
1928 // Remove any existing vcall visibility metadata first in case we are
1929 // updating.
1930 eraseMetadata(LLVMContext::MD_vcall_visibility);
1931 addMetadata(LLVMContext::MD_vcall_visibility,
1933 {ConstantAsMetadata::get(ConstantInt::get(
1935}
1936
1938 if (MDNode *MD = getMetadata(LLVMContext::MD_vcall_visibility)) {
1940 cast<ConstantAsMetadata>(MD->getOperand(0))->getValue())
1941 ->getZExtValue();
1942 assert(Val <= 2 && "unknown vcall visibility!");
1943 return (VCallVisibility)Val;
1944 }
1946}
1947
1949 setMetadata(LLVMContext::MD_dbg, SP);
1950}
1951
1953 return cast_or_null<DISubprogram>(getMetadata(LLVMContext::MD_dbg));
1954}
1955
1957 if (DISubprogram *SP = getSubprogram()) {
1958 if (DICompileUnit *CU = SP->getUnit()) {
1959 return CU->getDebugInfoForProfiling();
1960 }
1961 }
1962 return false;
1963}
1964
1966 addMetadata(LLVMContext::MD_dbg, *GV);
1967}
1968
1972 getMetadata(LLVMContext::MD_dbg, MDs);
1973 for (MDNode *MD : MDs)
1975}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file defines the StringMap class.
This file declares a class to represent arbitrary precision floating point values and provide a varie...
This file implements a class to represent arbitrary precision integral constant values and operations...
static const Function * getParent(const Value *V)
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static Domain getDomain(const ConstantRange &CR)
dxil translate DXIL Translate Metadata
static ManagedStatic< DebugCounterOwner > Owner
This file defines the DenseSet and SmallDenseSet classes.
Module.h This file contains the declarations for the Module class.
const size_t AbstractManglingParser< Derived, Alloc >::NumOps
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
#define I(x, y, z)
Definition MD5.cpp:57
#define H(x, y, z)
Definition MD5.cpp:56
static DISubprogram * getLocalFunctionMetadata(Value *V)
Definition Metadata.cpp:492
static Metadata * canonicalizeMetadataForValue(LLVMContext &Context, Metadata *MD)
Canonicalize metadata arguments to intrinsics.
Definition Metadata.cpp:88
static bool isOperandUnresolved(Metadata *Op)
Definition Metadata.cpp:760
static bool hasSelfReference(MDNode *N)
Definition Metadata.cpp:869
static void addRange(SmallVectorImpl< ConstantInt * > &EndPoints, ConstantInt *Low, ConstantInt *High)
static SmallVector< TrackingMDRef, 4 > & getNMDOps(void *Operands)
static bool canBeMerged(const ConstantRange &A, const ConstantRange &B)
static T * uniquifyImpl(T *N, DenseSet< T *, InfoT > &Store)
Definition Metadata.cpp:987
static bool isContiguous(const ConstantRange &A, const ConstantRange &B)
static MDNode * getOrSelfReference(LLVMContext &Context, ArrayRef< Metadata * > Ops)
Get a node or a self-reference that looks like it.
static bool tryMergeRange(SmallVectorImpl< ConstantInt * > &EndPoints, ConstantInt *Low, ConstantInt *High)
This file contains the declarations for metadata subclasses.
#define T
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
uint64_t High
This file contains the declarations for profiling metadata utility functions.
Remove Loads Into Fake Uses
This file contains some templates that are useful if you are working with the STL at all.
This file implements a set that has insertion order iteration characteristics.
This file defines the SmallPtrSet class.
This file defines the SmallSet class.
This file defines the SmallVector class.
static TableGen::Emitter::OptClass< SkeletonEmitter > X("gen-skeleton-class", "Generate example skeleton class")
Class for arbitrary precision integers.
Definition APInt.h:78
bool slt(const APInt &RHS) const
Signed less than comparison.
Definition APInt.h:1131
This is a simple wrapper around an MDNode which provides a higher-level interface by hiding the detai...
Definition Metadata.h:1593
Annotations lets you mark points and ranges inside source code, for tests:
Definition Annotations.h:53
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
size - Get the array size.
Definition ArrayRef.h:142
LLVM Basic Block Representation.
Definition BasicBlock.h:62
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
This class represents a function call, abstracting a target machine's calling convention.
static ConstantAsMetadata * get(Constant *C)
Definition Metadata.h:536
This is the shared class of boolean and integer constants.
Definition Constants.h:87
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
Definition Constants.h:168
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition Constants.h:159
This class represents a list of constant ranges.
LLVM_ABI ConstantRangeList intersectWith(const ConstantRangeList &CRL) const
Return the range list that results from the intersection of this ConstantRangeList with another Const...
This class represents a range of values.
LLVM_ABI ConstantRange unionWith(const ConstantRange &CR, PreferredRangeType Type=Smallest) const
Return the range that results from the union of this range with another range.
This is an important base class in LLVM.
Definition Constant.h:43
DWARF expression.
A pair of DIGlobalVariable and DIExpression.
Subprogram description. Uses SubclassData1.
Record of a variable value-assignment, aka a non instruction representation of the dbg....
MDNode * getAsMDNode() const
Return this as a bar MDNode.
Definition DebugLoc.h:290
Base class for tracking ValueAsMetadata/DIArgLists with user lookups and Owner callbacks outside of V...
Definition Metadata.h:220
LLVM_ABI void handleChangedValue(void *Old, Metadata *NewDebugValue)
To be called by ReplaceableMetadataImpl::replaceAllUsesWith, where Old is a pointer to one of the poi...
Definition Metadata.cpp:165
std::array< Metadata *, 3 > DebugValues
Definition Metadata.h:226
void resetDebugValue(size_t Idx, Metadata *DebugValue)
Definition Metadata.h:281
LLVM_ABI DbgVariableRecord * getUser()
Definition Metadata.cpp:158
Implements a dense probed hash-table based set.
Definition DenseSet.h:279
void setSubprogram(DISubprogram *SP)
Set the attached subprogram.
DISubprogram * getSubprogram() const
Get the attached subprogram.
bool shouldEmitDebugInfoForProfiling() const
Returns true if we should emit debug info for profiling.
LLVM_ABI void addTypeMetadata(unsigned Offset, Metadata *TypeID)
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set a particular kind of metadata attachment.
GlobalObject(Type *Ty, ValueTy VTy, AllocInfo AllocInfo, LinkageTypes Linkage, const Twine &Name, unsigned AddressSpace=0)
LLVM_ABI void copyMetadata(const GlobalObject *Src, unsigned Offset)
Copy metadata from Src, adjusting offsets by Offset.
LLVM_ABI VCallVisibility getVCallVisibility() const
LLVM_ABI bool eraseMetadata(unsigned KindID)
Erase all metadata attachments with the given kind.
LLVM_ABI void addMetadata(unsigned KindID, MDNode &MD)
Add a metadata attachment.
MDNode * getMetadata(unsigned KindID) const
Get the current metadata attachments for the given kind, if any.
Definition Value.h:576
LLVM_ABI void setVCallVisibilityMetadata(VCallVisibility Visibility)
LLVM_ABI void getDebugInfo(SmallVectorImpl< DIGlobalVariableExpression * > &GVs) const
Fill the vector with all debug info attachements.
LLVM_ABI void addDebugInfo(DIGlobalVariableExpression *GV)
Attach a DIGlobalVariableExpression.
LLVM_ABI void setAAMetadata(const AAMDNodes &N)
Sets the AA metadata on this instruction from the AAMDNodes structure.
LLVM_ABI bool extractProfTotalWeight(uint64_t &TotalVal) const
Retrieve total raw weight values of a branch.
bool hasMetadata() const
Return true if this instruction has any metadata attached to it.
LLVM_ABI void addAnnotationMetadata(StringRef Annotation)
Adds an !annotation metadata node with Annotation to this instruction.
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
LLVM_ABI void setNoSanitizeMetadata()
Sets the nosanitize metadata on this instruction.
LLVM_ABI void dropUnknownNonDebugMetadata(ArrayRef< unsigned > KnownIDs={})
Drop all unknown metadata except for debug locations.
LLVM_ABI AAMDNodes getAAMetadata() const
Returns the AA metadata for this instruction.
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
LLVM_ABI void eraseMetadataIf(function_ref< bool(unsigned, MDNode *)> Pred)
Erase all metadata that matches the predicate.
DenseMap< Metadata *, MetadataAsValue * > MetadataAsValues
DenseMap< DIAssignID *, SmallVector< Instruction *, 1 > > AssignmentIDToInstrs
Map DIAssignID -> Instructions with that attachment.
std::vector< MDNode * > DistinctMDNodes
DenseMap< const Value *, MDAttachments > ValueMetadata
Collection of metadata used in this context.
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:68
LLVM_ABI unsigned getMDKindID(StringRef Name) const
getMDKindID - Return a unique non-zero ID for the specified metadata kind.
LLVMContextImpl *const pImpl
Definition LLVMContext.h:70
Multimap-like storage for metadata attachments.
void insert(unsigned ID, MDNode &MD)
Adds an attachment to a particular node.
void get(unsigned ID, SmallVectorImpl< MDNode * > &Result) const
Appends all attachments with the given ID to Result in insertion order.
void getAll(SmallVectorImpl< std::pair< unsigned, MDNode * > > &Result) const
Appends all attachments for the global to Result, sorting by attachment ID.
void set(unsigned ID, MDNode *MD)
Set an attachment to a particular node.
MDNode * lookup(unsigned ID) const
Returns the first attachment with the given ID or nullptr if no such attachment exists.
bool erase(unsigned ID)
Remove attachments with the given ID.
LLVM_ABI MDString * createString(StringRef Str)
Return the given string as metadata.
Definition MDBuilder.cpp:21
Metadata node.
Definition Metadata.h:1078
static LLVM_ABI MDNode * getMostGenericAliasScope(MDNode *A, MDNode *B)
LLVM_ABI void replaceOperandWith(unsigned I, Metadata *New)
Replace a specific operand.
LLVM_ABI void resolveCycles()
Resolve cycles.
Definition Metadata.cpp:849
static LLVM_ABI CaptureComponents toCaptureComponents(const MDNode *MD)
Convert !captures metadata to CaptureComponents. MD may be nullptr.
mutable_op_range mutable_operands()
Definition Metadata.h:1216
static LLVM_ABI MDNode * getMergedCalleeTypeMetadata(const MDNode *A, const MDNode *B)
void replaceAllUsesWith(Metadata *MD)
RAUW a temporary.
Definition Metadata.h:1282
static LLVM_ABI MDNode * concatenate(MDNode *A, MDNode *B)
Methods for metadata merging.
static LLVM_ABI void deleteTemporary(MDNode *N)
Deallocate a node created by getTemporary.
LLVM_ABI void resolve()
Resolve a unique, unresolved node.
Definition Metadata.cpp:803
const MDOperand & getOperand(unsigned I) const
Definition Metadata.h:1442
static LLVM_ABI MDNode * getMostGenericNoaliasAddrspace(MDNode *A, MDNode *B)
LLVM_ABI void storeDistinctInContext()
bool isTemporary() const
Definition Metadata.h:1262
ArrayRef< MDOperand > operands() const
Definition Metadata.h:1440
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1569
static LLVM_ABI MDNode * getMergedProfMetadata(MDNode *A, MDNode *B, const Instruction *AInstr, const Instruction *BInstr)
Merge !prof metadata from two instructions.
bool isUniqued() const
Definition Metadata.h:1260
static LLVM_ABI MDNode * getMostGenericFPMath(MDNode *A, MDNode *B)
void setNumUnresolved(unsigned N)
Definition Metadata.h:1369
unsigned getNumOperands() const
Return number of MDNode operands.
Definition Metadata.h:1448
MDOperand * mutable_begin()
Definition Metadata.h:1211
LLVM_ABI MDNode(LLVMContext &Context, unsigned ID, StorageType Storage, ArrayRef< Metadata * > Ops1, ArrayRef< Metadata * > Ops2={})
Definition Metadata.cpp:658
LLVM_ABI TempMDNode clone() const
Create a (temporary) clone of this.
Definition Metadata.cpp:675
static LLVM_ABI MDNode * getMostGenericRange(MDNode *A, MDNode *B)
bool isDistinct() const
Definition Metadata.h:1261
LLVM_ABI void setOperand(unsigned I, Metadata *New)
Set an operand.
bool isResolved() const
Check if node is fully resolved.
Definition Metadata.h:1258
op_iterator op_begin() const
Definition Metadata.h:1432
static LLVM_ABI MDNode * intersect(MDNode *A, MDNode *B)
static T * storeImpl(T *N, StorageType Storage, StoreT &Store)
LLVMContext & getContext() const
Definition Metadata.h:1242
static LLVM_ABI MDNode * fromCaptureComponents(LLVMContext &Ctx, CaptureComponents CC)
Convert CaptureComponents to !captures metadata.
LLVM_ABI void dropAllReferences()
Definition Metadata.cpp:915
static LLVM_ABI MDNode * getMostGenericAlignmentOrDereferenceable(MDNode *A, MDNode *B)
unsigned getNumUnresolved() const
Definition Metadata.h:1367
Tracking metadata reference owned by Metadata.
Definition Metadata.h:900
A single uniqued string.
Definition Metadata.h:721
LLVM_ABI StringRef getString() const
Definition Metadata.cpp:624
static LLVM_ABI MDString * get(LLVMContext &Context, StringRef Str)
Definition Metadata.cpp:614
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1526
static LLVM_ABI MetadataAsValue * get(LLVMContext &Context, Metadata *MD)
Definition Metadata.cpp:110
static LLVM_ABI MetadataAsValue * getIfExists(LLVMContext &Context, Metadata *MD)
Definition Metadata.cpp:118
LLVM_ABI ~MetadataAsValue()
Definition Metadata.cpp:72
static LLVM_ABI bool isReplaceable(const Metadata &MD)
Check whether metadata is replaceable.
Definition Metadata.cpp:253
static void untrack(Metadata *&MD)
Stop tracking a reference to metadata.
Definition Metadata.h:357
PointerUnion< MetadataAsValue *, Metadata *, DebugValueUser * > OwnerTy
Definition Metadata.h:376
static bool retrack(Metadata *&MD, Metadata *&New)
Move tracking from one reference to another.
Definition Metadata.h:368
static bool track(Metadata *&MD)
Track the reference to metadata.
Definition Metadata.h:323
Root of the metadata hierarchy.
Definition Metadata.h:64
StorageType
Active type of storage.
Definition Metadata.h:72
unsigned char Storage
Storage flag for non-uniqued, otherwise unowned, metadata.
Definition Metadata.h:75
unsigned getMetadataID() const
Definition Metadata.h:104
Metadata(unsigned ID, StorageType Storage)
Definition Metadata.h:88
void eraseNamedMetadata(NamedMDNode *NMD)
Remove the given NamedMDNode from this module and delete it.
Definition Module.cpp:322
iterator end() const
Definition ArrayRef.h:343
LLVM_ABI void setOperand(unsigned I, MDNode *New)
LLVM_ABI ~NamedMDNode()
LLVM_ABI StringRef getName() const
void dropAllReferences()
Remove all uses and clear node vector.
Definition Metadata.h:1822
LLVM_ABI void eraseFromParent()
Drop all references and remove the node from parent module.
LLVM_ABI MDNode * getOperand(unsigned i) const
LLVM_ABI unsigned getNumOperands() const
LLVM_ABI void clearOperands()
Drop all references to this node's operands.
Module * getParent()
Get the module that holds this named metadata collection.
Definition Metadata.h:1827
LLVM_ABI void addOperand(MDNode *M)
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
Shared implementation of use-lists for replaceable metadata.
Definition Metadata.h:390
static LLVM_ABI void SalvageDebugInfo(const Constant &C)
Replace all uses of the constant with Undef in debug info metadata.
Definition Metadata.cpp:338
LLVM_ABI void replaceAllUsesWith(Metadata *MD)
Replace all uses of this with MD.
Definition Metadata.cpp:375
LLVM_ABI SmallVector< DbgVariableRecord * > getAllDbgVariableRecordUsers()
Returns the list of all DbgVariableRecord users of this.
Definition Metadata.cpp:279
LLVM_ABI void resolveAllUses(bool ResolveUsers=true)
Resolve all uses of this.
Definition Metadata.cpp:428
LLVM_ABI SmallVector< Metadata * > getAllArgListUsers()
Returns the list of all DIArgList users of this.
Definition Metadata.cpp:257
MetadataTracking::OwnerTy OwnerTy
Definition Metadata.h:394
ArrayRef< value_type > getArrayRef() const
Definition SetVector.h:91
bool remove_if(UnaryPredicate P)
Remove items from the set vector based on a predicate function.
Definition SetVector.h:230
bool empty() const
Determine if the SetVector is empty or not.
Definition SetVector.h:100
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition SetVector.h:151
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
A SetVector that performs no allocations if smaller than a certain size.
Definition SetVector.h:339
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
Definition SmallSet.h:133
size_type count(const T &V) const
count - Return 1 if the element is in the set, 0 otherwise.
Definition SmallSet.h:175
std::pair< const_iterator, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
Definition SmallSet.h:183
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void reserve(size_type N)
void resize(size_type N)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
A switch()-like statement whose cases are string literals.
StringSwitch & Case(StringLiteral S, T Value)
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:45
static LLVM_ABI IntegerType * getInt64Ty(LLVMContext &C)
Definition Type.cpp:297
static LLVM_ABI Type * getMetadataTy(LLVMContext &C)
Definition Type.cpp:286
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
Definition Type.h:128
Use & Op()
Definition User.h:197
Value wrapper in the Metadata hierarchy.
Definition Metadata.h:458
void replaceAllUsesWith(Metadata *MD)
Handle collisions after Value::replaceAllUsesWith().
Definition Metadata.h:518
static LLVM_ABI void handleDeletion(Value *V)
Definition Metadata.cpp:533
static LLVM_ABI ValueAsMetadata * get(Value *V)
Definition Metadata.cpp:509
static LLVM_ABI ValueAsMetadata * getIfExists(Value *V)
Definition Metadata.cpp:528
static LLVM_ABI void handleRAUW(Value *From, Value *To)
Definition Metadata.cpp:552
ValueAsMetadata(unsigned ID, Value *V)
Definition Metadata.h:470
Value * getValue() const
Definition Metadata.h:498
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:256
unsigned IsUsedByMD
Definition Value.h:112
bool hasMetadata() const
Return true if this value has any metadata attached to it.
Definition Value.h:602
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set a particular kind of metadata attachment.
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:553
LLVM_ABI void getAllMetadata(SmallVectorImpl< std::pair< unsigned, MDNode * > > &MDs) const
Appends all metadata attached to this value to MDs, sorting by KindID.
LLVM_ABI MDNode * getMetadataImpl(unsigned KindID) const
Get metadata for the given kind, if any.
LLVM_ABI bool eraseMetadata(unsigned KindID)
Erase all metadata attachments with the given kind.
unsigned HasMetadata
Definition Value.h:114
LLVM_ABI void addMetadata(unsigned KindID, MDNode &MD)
Add a metadata attachment.
LLVM_ABI void eraseMetadataIf(function_ref< bool(unsigned, MDNode *)> Pred)
Erase all metadata attachments matching the given predicate.
LLVM_ABI LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.cpp:1106
LLVM_ABI void clearMetadata()
Erase all metadata attached to this Value.
MDNode * getMetadata(unsigned KindID) const
Get the current metadata attachments for the given kind, if any.
Definition Value.h:576
An efficient, type-erasing, non-owning reference to a callable.
Changed
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > dyn_extract(Y &&MD)
Extract a Value from Metadata, if any.
Definition Metadata.h:695
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > extract(Y &&MD)
Extract a Value from Metadata.
Definition Metadata.h:667
iterator end() const
Definition BasicBlock.h:89
This is an optimization pass for GlobalISel generic memory operations.
Definition Types.h:26
@ Low
Lower the current thread's priority such that it does not affect foreground tasks significantly.
Definition Threading.h:280
@ Offset
Definition DWP.cpp:532
detail::zippy< detail::zip_shortest, T, U, Args... > zip(T &&t, U &&u, Args &&...args)
zip iterator for two or more iteratable types.
Definition STLExtras.h:829
bool capturesReadProvenanceOnly(CaptureComponents CC)
Definition ModRef.h:336
void stable_sort(R &&Range)
Definition STLExtras.h:2106
auto find(R &&Range, const T &Val)
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1763
bool capturesAddressIsNullOnly(CaptureComponents CC)
Definition ModRef.h:328
TypedTrackingMDRef< MDNode > TrackingMDNodeRef
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition STLExtras.h:1667
LLVM_ABI unsigned getBranchWeightOffset(const MDNode *ProfileData)
Return the offset to the first branch weight data.
static T * getUniqued(DenseSet< T *, InfoT > &Store, const typename InfoT::KeyTy &Key)
bool capturesAddress(CaptureComponents CC)
Definition ModRef.h:332
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
constexpr from_range_t from_range
auto dyn_cast_if_present(const Y &Val)
dyn_cast_if_present<X> - Functionally identical to dyn_cast, except that a null (or none in the case ...
Definition Casting.h:732
auto cast_or_null(const Y &Val)
Definition Casting.h:714
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1744
bool capturesFullProvenance(CaptureComponents CC)
Definition ModRef.h:341
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1634
CaptureComponents
Components of the pointer that may be captured.
Definition ModRef.h:310
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
MutableArrayRef(T &OneElt) -> MutableArrayRef< T >
@ Ref
The access may reference the value stored in memory.
Definition ModRef.h:32
@ Other
Any other memory.
Definition ModRef.h:68
uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition Alignment.h:144
DWARFExpression::Operation Op
ArrayRef(const T &OneElt) -> ArrayRef< T >
OutputIt copy(R &&Range, OutputIt Out)
Definition STLExtras.h:1883
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1915
auto count_if(R &&Range, UnaryPredicate P)
Wrapper function around std::count_if to count the number of times an element satisfying a given pred...
Definition STLExtras.h:2009
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
void erase_if(Container &C, UnaryPredicate P)
Provide a container algorithm similar to C++ Library Fundamentals v2's erase_if which is equivalent t...
Definition STLExtras.h:2182
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1945
cl::opt< bool > ProfcheckDisableMetadataFixes("profcheck-disable-metadata-fixes", cl::Hidden, cl::init(false), cl::desc("Disable metadata propagation fixes discovered through Issue #147390"))
Definition Metadata.cpp:64
bool capturesAll(CaptureComponents CC)
Definition ModRef.h:349
std::enable_if_t< std::is_unsigned_v< T >, T > SaturatingAdd(T X, T Y, bool *ResultOverflowed=nullptr)
Add two unsigned integers, X and Y, of type T.
Definition MathExtras.h:609
bool capturesNothing(CaptureComponents CC)
Definition ModRef.h:320
#define N
static constexpr bool value
static std::false_type check(...)
static std::true_type check(SameType< void(U::*)(unsigned), &U::setHash > *)
A collection of metadata nodes that might be associated with a memory access used by the alias-analys...
Definition Metadata.h:761
static LLVM_ABI const char * BranchWeights
Function object to check whether the first component of a container supported by std::get (like std::...
Definition STLExtras.h:1437