61 :
Value(Ty, MetadataAsValueVal), MD(MD) {
88 auto *
N = dyn_cast<MDNode>(MD);
89 if (!
N ||
N->getNumOperands() != 1)
92 if (!
N->getOperand(0))
96 if (
auto *
C = dyn_cast<ConstantAsMetadata>(
N->getOperand(0)))
105 auto *&Entry =
Context.pImpl->MetadataAsValues[MD];
114 auto &Store =
Context.pImpl->MetadataAsValues;
115 return Store.lookup(MD);
118void MetadataAsValue::handleChangedMetadata(
Metadata *MD) {
121 auto &Store =
Context.pImpl->MetadataAsValues;
124 Store.erase(this->MD);
129 auto *&Entry = Store[MD];
141void MetadataAsValue::track() {
146void MetadataAsValue::untrack() {
161 auto OldMD =
static_cast<Metadata **
>(Old);
165 if (OldMD && isa<ValueAsMetadata>(*OldMD) && !New) {
166 auto *OldVAM = cast<ValueAsMetadata>(*OldMD);
172void DebugValueUser::trackDebugValue(
size_t Idx) {
173 assert(
Idx < 3 &&
"Invalid debug value index.");
179void DebugValueUser::trackDebugValues() {
185void DebugValueUser::untrackDebugValue(
size_t Idx) {
186 assert(
Idx < 3 &&
"Invalid debug value index.");
192void DebugValueUser::untrackDebugValues() {
199 assert(DebugValueUser::operator==(
X) &&
"Expected values to match");
203 X.DebugValues.fill(
nullptr);
207 assert(
Ref &&
"Expected live reference");
209 "Reference without owner must be direct");
210 if (
auto *R = ReplaceableMetadataImpl::getOrCreate(MD)) {
211 R->addRef(
Ref, Owner);
214 if (
auto *PH = dyn_cast<DistinctMDOperandPlaceholder>(&MD)) {
215 assert(!PH->Use &&
"Placeholders can only be used once");
216 assert(!Owner &&
"Unexpected callback to owner");
224 assert(
Ref &&
"Expected live reference");
225 if (
auto *R = ReplaceableMetadataImpl::getIfExists(MD))
227 else if (
auto *PH = dyn_cast<DistinctMDOperandPlaceholder>(&MD))
232 assert(
Ref &&
"Expected live reference");
233 assert(New &&
"Expected live reference");
235 if (
auto *R = ReplaceableMetadataImpl::getIfExists(MD)) {
236 R->moveRef(
Ref, New, MD);
239 assert(!isa<DistinctMDOperandPlaceholder>(MD) &&
240 "Unexpected move of an MDOperand");
242 "Expected un-replaceable metadata, since we didn't move a reference");
247 return ReplaceableMetadataImpl::isReplaceable(MD);
252 for (
auto Pair : UseMap) {
253 OwnerTy Owner = Pair.second.first;
256 if (!isa<Metadata *>(Owner))
258 Metadata *OwnerMD = cast<Metadata *>(Owner);
260 MDUsersWithID.
push_back(&UseMap[Pair.first]);
262 llvm::sort(MDUsersWithID, [](
auto UserA,
auto UserB) {
263 return UserA->second < UserB->second;
266 for (
auto *UserWithID : MDUsersWithID)
267 MDUsers.
push_back(cast<Metadata *>(UserWithID->first));
274 for (
auto Pair : UseMap) {
275 OwnerTy Owner = Pair.second.first;
278 if (!isa<DebugValueUser *>(Owner))
280 DVRUsersWithID.
push_back(&UseMap[Pair.first]);
287 llvm::sort(DVRUsersWithID, [](
auto UserA,
auto UserB) {
288 return UserA->second > UserB->second;
291 for (
auto UserWithID : DVRUsersWithID)
292 DVRUsers.
push_back(cast<DebugValueUser *>(UserWithID->first)->getUser());
296void ReplaceableMetadataImpl::addRef(
void *
Ref, OwnerTy Owner) {
298 UseMap.insert(std::make_pair(
Ref, std::make_pair(Owner, NextIndex)))
301 assert(WasInserted &&
"Expected to add a reference");
304 assert(NextIndex != 0 &&
"Unexpected overflow");
307void ReplaceableMetadataImpl::dropRef(
void *
Ref) {
308 bool WasErased = UseMap.erase(
Ref);
310 assert(WasErased &&
"Expected to drop a reference");
313void ReplaceableMetadataImpl::moveRef(
void *
Ref,
void *New,
315 auto I = UseMap.find(
Ref);
316 assert(
I != UseMap.end() &&
"Expected to move a reference");
317 auto OwnerAndIndex =
I->second;
319 bool WasInserted = UseMap.insert(std::make_pair(New, OwnerAndIndex)).second;
321 assert(WasInserted &&
"Expected to add a reference");
326 "Reference without owner must be direct");
327 assert((OwnerAndIndex.first || *
static_cast<Metadata **
>(New) == &MD) &&
328 "Reference without owner must be direct");
332 if (!
C.isUsedByMetadata()) {
337 auto &Store =
Context.pImpl->ValuesAsMetadata;
338 auto I = Store.find(&
C);
341 std::pair<void *, std::pair<MetadataTracking::OwnerTy, uint64_t>>;
346 for (
const auto &Pair :
Uses) {
351 if (isa<MetadataAsValue *>(Owner)) {
352 cast<MetadataAsValue *>(Owner)->handleChangedMetadata(
356 if (!isa<Metadata *>(Owner))
358 auto *OwnerMD = dyn_cast_if_present<MDNode>(cast<Metadata *>(Owner));
361 if (isa<DINode>(OwnerMD)) {
362 OwnerMD->handleChangedOperand(
373 using UseTy = std::pair<void *, std::pair<OwnerTy, uint64_t>>;
376 return L.second.second < R.second.second;
378 for (
const auto &Pair :
Uses) {
381 if (!UseMap.count(Pair.first))
384 OwnerTy Owner = Pair.second.first;
391 UseMap.erase(Pair.first);
396 if (isa<MetadataAsValue *>(Owner)) {
397 cast<MetadataAsValue *>(Owner)->handleChangedMetadata(MD);
401 if (
auto *DVU = dyn_cast<DebugValueUser *>(Owner)) {
402 DVU->handleChangedValue(Pair.first, MD);
407 Metadata *OwnerMD = cast<Metadata *>(Owner);
409#define HANDLE_METADATA_LEAF(CLASS) \
410 case Metadata::CLASS##Kind: \
411 cast<CLASS>(OwnerMD)->handleChangedOperand(Pair.first, MD); \
413#include "llvm/IR/Metadata.def"
418 assert(UseMap.empty() &&
"Expected all uses to be replaced");
431 using UseTy = std::pair<void *, std::pair<OwnerTy, uint64_t>>;
434 return L.second.second < R.second.second;
437 for (
const auto &Pair :
Uses) {
438 auto Owner = Pair.second.first;
441 if (!isa<Metadata *>(Owner))
445 auto *OwnerMD = dyn_cast_if_present<MDNode>(cast<Metadata *>(Owner));
448 if (OwnerMD->isResolved())
450 OwnerMD->decrementUnresolvedOperandCount();
458 if (
auto *
N = dyn_cast<MDNode>(&MD)) {
459 return !
N->isResolved() ||
N->isAlwaysReplaceable()
460 ?
N->Context.getOrCreateReplaceableUses()
463 if (
auto ArgList = dyn_cast<DIArgList>(&MD))
465 return dyn_cast<ValueAsMetadata>(&MD);
469 if (
auto *
N = dyn_cast<MDNode>(&MD)) {
470 return !
N->isResolved() ||
N->isAlwaysReplaceable()
471 ?
N->Context.getReplaceableUses()
474 if (
auto ArgList = dyn_cast<DIArgList>(&MD))
476 return dyn_cast<ValueAsMetadata>(&MD);
479bool ReplaceableMetadataImpl::isReplaceable(
const Metadata &MD) {
480 if (
auto *
N = dyn_cast<MDNode>(&MD))
481 return !
N->isResolved() ||
N->isAlwaysReplaceable();
482 return isa<ValueAsMetadata>(&MD) || isa<DIArgList>(&MD);
486 assert(V &&
"Expected value");
487 if (
auto *
A = dyn_cast<Argument>(V)) {
488 if (
auto *Fn =
A->getParent())
489 return Fn->getSubprogram();
494 if (
auto *Fn = BB->getParent())
495 return Fn->getSubprogram();
503 assert(V &&
"Unexpected null Value");
505 auto &
Context = V->getContext();
506 auto *&Entry =
Context.pImpl->ValuesAsMetadata[V];
508 assert((isa<Constant>(V) || isa<Argument>(V) || isa<Instruction>(V)) &&
509 "Expected constant or function-local value");
510 assert(!V->IsUsedByMD &&
"Expected this to be the only metadata use");
511 V->IsUsedByMD =
true;
512 if (
auto *
C = dyn_cast<Constant>(V))
522 assert(V &&
"Unexpected null Value");
523 return V->getContext().pImpl->ValuesAsMetadata.lookup(V);
527 assert(V &&
"Expected valid value");
529 auto &Store = V->getType()->getContext().pImpl->ValuesAsMetadata;
530 auto I = Store.find(V);
531 if (
I == Store.end())
536 assert(MD &&
"Expected valid metadata");
547 assert(To &&
"Expected valid value");
548 assert(
From != To &&
"Expected changed value");
552 auto &Store =
Context.pImpl->ValuesAsMetadata;
553 auto I = Store.find(
From);
554 if (
I == Store.end()) {
555 assert(!
From->IsUsedByMD &&
"Expected From not to be used by metadata");
560 assert(
From->IsUsedByMD &&
"Expected From to be used by metadata");
561 From->IsUsedByMD =
false;
563 assert(MD &&
"Expected valid metadata");
567 if (isa<LocalAsMetadata>(MD)) {
568 if (
auto *
C = dyn_cast<Constant>(To)) {
581 }
else if (!isa<Constant>(To)) {
588 auto *&Entry = Store[To];
608 auto &Store =
Context.pImpl->MDStringCache;
609 auto I = Store.try_emplace(Str);
610 auto &MapEntry =
I.first->getValue();
613 MapEntry.Entry = &*
I.first;
618 assert(Entry &&
"Expected to find string map entry");
619 return Entry->first();
628#define HANDLE_MDNODE_LEAF(CLASS) \
630 alignof(uint64_t) >= alignof(CLASS), \
631 "Alignment is insufficient after objects prepended to " #CLASS);
632#include "llvm/IR/Metadata.def"
639 char *Mem =
reinterpret_cast<char *
>(::operator
new(AllocSize +
Size));
640 Header *
H =
new (Mem + AllocSize -
sizeof(Header)) Header(NumOps, Storage);
641 return reinterpret_cast<void *
>(
H + 1);
644void MDNode::operator
delete(
void *
N) {
645 Header *
H =
reinterpret_cast<Header *
>(
N) - 1;
646 void *Mem =
H->getAllocation();
648 ::operator
delete(Mem);
665 countUnresolvedOperands();
672#define HANDLE_MDNODE_LEAF(CLASS) \
674 return cast<CLASS>(this)->cloneImpl();
675#include "llvm/IR/Metadata.def"
679MDNode::Header::Header(
size_t NumOps, StorageType Storage) {
680 IsLarge = isLarge(NumOps);
681 IsResizable = isResizable(Storage);
682 SmallSize = getSmallSize(NumOps, IsResizable, IsLarge);
685 new (getLargePtr()) LargeStorageVector();
686 getLarge().resize(NumOps);
689 SmallNumOps = NumOps;
691 for (
MDOperand *E = O + SmallSize; O != E;)
695MDNode::Header::~Header() {
697 getLarge().~LargeStorageVector();
702 (O - 1)->~MDOperand();
705void *MDNode::Header::getSmallPtr() {
706 static_assert(
alignof(
MDOperand) <=
alignof(Header),
707 "MDOperand too strongly aligned");
708 return reinterpret_cast<char *
>(
const_cast<Header *
>(
this)) -
712void MDNode::Header::resize(
size_t NumOps) {
713 assert(IsResizable &&
"Node is not resizable");
714 if (operands().
size() == NumOps)
718 getLarge().resize(NumOps);
719 else if (NumOps <= SmallSize)
722 resizeSmallToLarge(NumOps);
725void MDNode::Header::resizeSmall(
size_t NumOps) {
726 assert(!IsLarge &&
"Expected a small MDNode");
727 assert(NumOps <= SmallSize &&
"NumOps too large for small resize");
730 assert(NumOps != ExistingOps.
size() &&
"Expected a different size");
732 int NumNew = (int)NumOps - (
int)ExistingOps.
size();
734 for (
int I = 0, E = NumNew;
I < E; ++
I)
736 for (
int I = 0, E = NumNew;
I > E; --
I)
738 SmallNumOps = NumOps;
739 assert(O == operands().
end() &&
"Operands not (un)initialized until the end");
742void MDNode::Header::resizeSmallToLarge(
size_t NumOps) {
743 assert(!IsLarge &&
"Expected a small MDNode");
744 assert(NumOps > SmallSize &&
"Expected NumOps to be larger than allocation");
745 LargeStorageVector NewOps;
746 NewOps.resize(NumOps);
749 new (getLargePtr()) LargeStorageVector(std::move(NewOps));
754 if (
auto *
N = dyn_cast_or_null<MDNode>(
Op))
755 return !
N->isResolved();
759void MDNode::countUnresolvedOperands() {
765void MDNode::makeUniqued() {
771 Op.reset(
Op.get(),
this);
775 countUnresolvedOperands();
777 dropReplaceableUses();
784void MDNode::makeDistinct() {
789 dropReplaceableUses();
801 dropReplaceableUses();
806void MDNode::dropReplaceableUses() {
810 if (
Context.hasReplaceableUses())
811 Context.takeReplaceableUses()->resolveAllUses();
824 decrementUnresolvedOperandCount();
827void MDNode::decrementUnresolvedOperandCount() {
838 dropReplaceableUses();
851 auto *
N = dyn_cast_or_null<MDNode>(
Op);
856 "Expected all forward declarations to be resolved");
857 if (!
N->isResolved())
866MDNode *MDNode::replaceWithPermanentImpl() {
870 return replaceWithDistinctImpl();
872#define HANDLE_MDNODE_LEAF_UNIQUABLE(CLASS) \
875#include "llvm/IR/Metadata.def"
880 return replaceWithDistinctImpl();
881 return replaceWithUniquedImpl();
884MDNode *MDNode::replaceWithUniquedImpl() {
886 MDNode *UniquedNode = uniquify();
888 if (UniquedNode ==
this) {
899MDNode *MDNode::replaceWithDistinctImpl() {
904void MDTuple::recalculateHash() {
905 setHash(MDTupleInfo::KeyTy::calculateHash(
this));
911 if (
Context.hasReplaceableUses()) {
912 Context.getReplaceableUses()->resolveAllUses(
false);
913 (void)
Context.takeReplaceableUses();
917void MDNode::handleChangedOperand(
void *
Ref,
Metadata *New) {
934 if (New ==
this || (!New && Old && isa<ConstantAsMetadata>(Old))) {
945 resolveAfterOperandChange(Old, New);
957 if (
Context.hasReplaceableUses())
967void MDNode::deleteAsSubclass() {
971#define HANDLE_MDNODE_LEAF(CLASS) \
973 delete cast<CLASS>(this); \
975#include "llvm/IR/Metadata.def"
979template <
class T,
class InfoT>
988template <
class NodeTy>
struct MDNode::HasCachedHash {
991 template <
class U, U Val>
struct SFINAE {};
994 static Yes &
check(SFINAE<
void (U::*)(
unsigned), &U::setHash> *);
997 static const bool value =
sizeof(check<NodeTy>(
nullptr)) ==
sizeof(
Yes);
1000MDNode *MDNode::uniquify() {
1007#define HANDLE_MDNODE_LEAF_UNIQUABLE(CLASS) \
1008 case CLASS##Kind: { \
1009 CLASS *SubclassThis = cast<CLASS>(this); \
1010 std::integral_constant<bool, HasCachedHash<CLASS>::value> \
1011 ShouldRecalculateHash; \
1012 dispatchRecalculateHash(SubclassThis, ShouldRecalculateHash); \
1013 return uniquifyImpl(SubclassThis, getContext().pImpl->CLASS##s); \
1015#include "llvm/IR/Metadata.def"
1019void MDNode::eraseFromStore() {
1023#define HANDLE_MDNODE_LEAF_UNIQUABLE(CLASS) \
1025 getContext().pImpl->CLASS##s.erase(cast<CLASS>(this)); \
1027#include "llvm/IR/Metadata.def"
1032 StorageType Storage,
bool ShouldCreate) {
1035 MDTupleInfo::KeyTy
Key(MDs);
1040 Hash =
Key.getHash();
1042 assert(ShouldCreate &&
"Expected non-uniqued nodes to always be created");
1051 assert(
N->isTemporary() &&
"Expected temporary node");
1052 N->replaceAllUsesWith(
nullptr);
1053 N->deleteAsSubclass();
1057 assert(!
Context.hasReplaceableUses() &&
"Unexpected replaceable uses");
1066#define HANDLE_MDNODE_LEAF(CLASS) \
1067 case CLASS##Kind: { \
1068 std::integral_constant<bool, HasCachedHash<CLASS>::value> ShouldResetHash; \
1069 dispatchResetHash(cast<CLASS>(this), ShouldResetHash); \
1072#include "llvm/IR/Metadata.def"
1104 if (
MDNode *
N = dyn_cast_or_null<MDNode>(Ops[0]))
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))
1122 MDs.
insert(
B->op_begin(),
B->op_end());
1152 if (
const MDNode *NAMD = dyn_cast<MDNode>(MDOp))
1157 if (
const MDNode *NAMD = dyn_cast<MDNode>(MDOp))
1165 if (
const MDNode *NAMD = dyn_cast<MDNode>(MDOp))
1170 return MDs.
empty() ? nullptr
1178 APFloat AVal = mdconst::extract<ConstantFP>(
A->getOperand(0))->getValueAPF();
1179 APFloat BVal = mdconst::extract<ConstantFP>(
B->getOperand(0))->getValueAPF();
1191 assert(
A &&
B && AInstr && BInstr &&
"Caller should guarantee");
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));
1201 assert(AMDS !=
nullptr && BMDS !=
nullptr &&
1202 "first operand should be a non-null MDString");
1207 ConstantInt *AInstrWeight = mdconst::dyn_extract<ConstantInt>(
1209 ConstantInt *BInstrWeight = mdconst::dyn_extract<ConstantInt>(
1211 assert(AInstrWeight && BInstrWeight &&
"verified by LLVM verifier");
1214 MDHelper.createConstant(ConstantInt::get(
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:
1242 if (AInstr && !IsLegal(*AInstr))
1244 if (BInstr && !IsLegal(*BInstr))
1252 "Caller should guarantee");
1254 "Caller should guarantee");
1256 const CallInst *ACall = dyn_cast<CallInst>(AInstr);
1257 const CallInst *BCall = dyn_cast<CallInst>(BInstr);
1262 return mergeDirectCallProfMetadata(
A,
B, AInstr, BInstr);
1270 return A.getUpper() ==
B.getLower() ||
A.getLower() ==
B.getUpper();
1281 const APInt &LB = EndPoints[
Size - 2]->getValue();
1282 const APInt &LE = EndPoints[
Size - 1]->getValue();
1287 EndPoints[
Size - 2] =
1288 cast<ConstantInt>(ConstantInt::get(Ty, Union.getLower()));
1289 EndPoints[
Size - 1] =
1290 cast<ConstantInt>(ConstantInt::get(Ty, Union.getUpper()));
1298 if (!EndPoints.
empty())
1313 auto AddUniqueCallees = [&AB, &MergedCallees](
const MDNode *
N) {
1315 if (MergedCallees.
insert(MD).second)
1319 AddUniqueCallees(
A);
1320 AddUniqueCallees(
B);
1340 unsigned AN =
A->getNumOperands() / 2;
1341 unsigned BN =
B->getNumOperands() / 2;
1342 while (AI < AN && BI < BN) {
1343 ConstantInt *ALow = mdconst::extract<ConstantInt>(
A->getOperand(2 * AI));
1344 ConstantInt *BLow = mdconst::extract<ConstantInt>(
B->getOperand(2 * BI));
1348 mdconst::extract<ConstantInt>(
A->getOperand(2 * AI + 1)));
1352 mdconst::extract<ConstantInt>(
B->getOperand(2 * BI + 1)));
1357 addRange(EndPoints, mdconst::extract<ConstantInt>(
A->getOperand(2 * AI)),
1358 mdconst::extract<ConstantInt>(
A->getOperand(2 * AI + 1)));
1362 addRange(EndPoints, mdconst::extract<ConstantInt>(
B->getOperand(2 * BI)),
1363 mdconst::extract<ConstantInt>(
B->getOperand(2 * BI + 1)));
1375 for (
unsigned i = 0; i <
Size - 2; ++i) {
1376 EndPoints[i] = EndPoints[i + 2];
1384 if (EndPoints.
size() == 2) {
1392 for (
auto *
I : EndPoints)
1405 for (
unsigned I = 0, E =
A->getNumOperands() / 2;
I != E; ++
I) {
1406 auto *LowA = mdconst::extract<ConstantInt>(
A->getOperand(2 *
I + 0));
1407 auto *HighA = mdconst::extract<ConstantInt>(
A->getOperand(2 *
I + 1));
1411 for (
unsigned I = 0, E =
B->getNumOperands() / 2;
I != E; ++
I) {
1412 auto *LowB = mdconst::extract<ConstantInt>(
B->getOperand(2 *
I + 0));
1413 auto *HighB = mdconst::extract<ConstantInt>(
B->getOperand(2 *
I + 1));
1426 ConstantInt::get(
A->getContext(), CR.getLower())));
1428 ConstantInt::get(
A->getContext(), CR.getUpper())));
1438 ConstantInt *AVal = mdconst::extract<ConstantInt>(
A->getOperand(0));
1439 ConstantInt *BVal = mdconst::extract<ConstantInt>(
B->getOperand(0));
1453NamedMDNode::NamedMDNode(
const Twine &
N)
1462 return (
unsigned)
getNMDOps(Operands).size();
1468 return cast_or_null<MDNode>(
N);
1489 for (
const auto &
A : Attachments)
1496 for (
const auto &
A : Attachments)
1498 Result.push_back(
A.Node);
1503 for (
const auto &
A : Attachments)
1504 Result.emplace_back(
A.MDKind,
A.Node);
1508 if (Result.size() > 1)
1527 if (Attachments.size() == 1 && Attachments.back().MDKind ==
ID) {
1528 Attachments.pop_back();
1532 auto OldSize = Attachments.size();
1535 return OldSize != Attachments.size();
1548 return Attachements.
lookup(KindID);
1565 "bit out of sync with hash table");
1572 assert(isa<Instruction>(
this) || isa<GlobalObject>(
this));
1580 Info.set(KindID, Node);
1586 "bit out of sync with hash table");
1606 assert(isa<Instruction>(
this) || isa<GlobalObject>(
this));
1622 bool Changed = Store.erase(KindID);
1634 assert(!
Info.empty() &&
"bit out of sync with hash table");
1636 return Pred(
I.MDKind,
I.Node);
1647 "bit out of sync with hash table");
1661 if (KindID == LLVMContext::MD_dbg)
1667 if (DbgLoc && Pred(LLVMContext::MD_dbg, DbgLoc.
getAsMDNode()))
1680 KnownSet.
insert(LLVMContext::MD_DIAssignID);
1683 return !KnownSet.
count(MDKind);
1687void Instruction::updateDIAssignIDMapping(
DIAssignID *
ID) {
1690 cast_or_null<DIAssignID>(
getMetadata(LLVMContext::MD_DIAssignID))) {
1692 if (
ID == CurrentID)
1696 auto InstrsIt = IDToInstrs.find(CurrentID);
1697 assert(InstrsIt != IDToInstrs.end() &&
1698 "Expect existing attachment to be mapped");
1700 auto &InstVec = InstrsIt->second;
1702 assert(InstIt != InstVec.end() &&
1703 "Expect instruction to be mapped to attachment");
1707 if (InstVec.size() == 1)
1708 IDToInstrs.erase(InstrsIt);
1710 InstVec.erase(InstIt);
1715 IDToInstrs[
ID].push_back(
this);
1723 if (KindID == LLVMContext::MD_dbg) {
1729 if (KindID == LLVMContext::MD_DIAssignID) {
1733 assert((!Node || !Node->isTemporary()) &&
1734 "Temporary DIAssignIDs are invalid");
1735 updateDIAssignIDMapping(cast_or_null<DIAssignID>(Node));
1743 if (
auto *Existing =
getMetadata(LLVMContext::MD_annotation)) {
1746 auto *Tuple = cast<MDTuple>(Existing);
1747 for (
auto &
N : Tuple->operands()) {
1748 if (isa<MDString>(
N.get())) {
1752 auto *MDAnnotationTuple = cast<MDTuple>(
N);
1753 if (
any_of(MDAnnotationTuple->operands(), [&AnnotationsSet](
auto &
Op) {
1754 return AnnotationsSet.contains(cast<MDString>(Op)->getString());
1773 if (
auto *Existing =
getMetadata(LLVMContext::MD_annotation)) {
1774 auto *Tuple = cast<MDTuple>(Existing);
1775 for (
auto &
N : Tuple->operands()) {
1776 if (isa<MDString>(
N.get()) &&
1777 cast<MDString>(
N.get())->getString() ==
Name)
1795 Result.TBAA =
Info.lookup(LLVMContext::MD_tbaa);
1796 Result.TBAAStruct =
Info.lookup(LLVMContext::MD_tbaa_struct);
1797 Result.Scope =
Info.lookup(LLVMContext::MD_alias_scope);
1798 Result.NoAlias =
Info.lookup(LLVMContext::MD_noalias);
1799 Result.NoAliasAddrSpace =
Info.lookup(LLVMContext::MD_noalias_addrspace);
1806 setMetadata(LLVMContext::MD_tbaa_struct,
N.TBAAStruct);
1809 setMetadata(LLVMContext::MD_noalias_addrspace,
N.NoAliasAddrSpace);
1817void Instruction::getAllMetadataImpl(
1824 std::make_pair((
unsigned)LLVMContext::MD_dbg, DbgLoc.
getAsMDNode()));
1833 getOpcode() == Instruction::IndirectBr ||
1835 "Looking for branch weights on something besides branch");
1837 return ::extractProfTotalWeight(*
this, TotalVal);
1842 Other->getAllMetadata(MDs);
1843 for (
auto &MD : MDs) {
1845 if (
Offset != 0 && MD.first == LLVMContext::MD_type) {
1846 auto *OffsetConst = cast<ConstantInt>(
1847 cast<ConstantAsMetadata>(MD.second->getOperand(0))->getValue());
1848 Metadata *TypeId = MD.second->getOperand(1);
1850 OffsetConst->getType(), OffsetConst->getValue() +
Offset));
1858 auto *Attachment = MD.second;
1859 if (
Offset != 0 && MD.first == LLVMContext::MD_dbg) {
1863 auto *GVE = cast<DIGlobalVariableExpression>(Attachment);
1864 GV = GVE->getVariable();
1865 E = GVE->getExpression();
1870 std::vector<uint64_t> Elements(OrigElements.
size() + 2);
1871 Elements[0] = dwarf::DW_OP_plus_uconst;
1873 llvm::copy(OrigElements, Elements.begin() + 2);
1883 LLVMContext::MD_type,
1903 cast<ConstantAsMetadata>(MD->getOperand(0))->getValue())
1905 assert(Val <= 2 &&
"unknown vcall visibility!");
1916 return cast_or_null<DISubprogram>(
getMetadata(LLVMContext::MD_dbg));
1922 return CU->getDebugInfoForProfiling();
1937 GVs.
push_back(cast<DIGlobalVariableExpression>(MD));
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)
BlockVerifier::State From
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
Analysis containing CSE Info
This file contains the declarations for the subclasses of Constant, which represent the different fla...
Returns the sub type a function will return at a given Idx Should correspond to the result type of an ExtractValue instruction executed with just that one unsigned Idx
Given that RA is a live value
This file defines the DenseSet and SmallDenseSet classes.
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang", "erlang-compatible garbage collector")
Module.h This file contains the declarations for the Module class.
mir Rename Register Operands
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
This file contains the declarations for profiling metadata utility functions.
Remove Loads Into Fake Uses
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.
Class for arbitrary precision integers.
bool slt(const APInt &RHS) const
Signed less than comparison.
This is a simple wrapper around an MDNode which provides a higher-level interface by hiding the detai...
Annotations lets you mark points and ranges inside source code, for tests:
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
size_t size() const
size - Get the array size.
bool empty() const
empty - Check if the array is empty.
LLVM Basic Block Representation.
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.
This is the shared class of boolean and integer constants.
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
const APInt & getValue() const
Return the constant as an APInt value reference.
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 bool isFullSet() const
Return true if this set contains all of the elements possible for this data-type.
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.
ArrayRef< uint64_t > getElements() const
A pair of DIGlobalVariable and DIExpression.
Subprogram description. Uses SubclassData1.
This class represents an Operation in the Expression.
Record of a variable value-assignment, aka a non instruction representation of the dbg....
MDNode * getAsMDNode() const
Return this as a bar MDNode.
Base class for tracking ValueAsMetadata/DIArgLists with user lookups and Owner callbacks outside of V...
LLVM_ABI void handleChangedValue(void *Old, Metadata *NewDebugValue)
To be called by ReplaceableMetadataImpl::replaceAllUsesWith, where Old is a pointer to one of the poi...
std::array< Metadata *, 3 > DebugValues
void resetDebugValue(size_t Idx, Metadata *DebugValue)
LLVM_ABI DbgVariableRecord * getUser()
Implements a dense probed hash-table based set.
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.
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.
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.
LLVM_ABI unsigned getMDKindID(StringRef Name) const
getMDKindID - Return a unique non-zero ID for the specified metadata kind.
LLVMContextImpl *const pImpl
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.
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.
mutable_op_range mutable_operands()
static LLVM_ABI MDNode * getMergedCalleeTypeMetadata(const MDNode *A, const MDNode *B)
void replaceAllUsesWith(Metadata *MD)
RAUW a temporary.
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.
const MDOperand & getOperand(unsigned I) const
static LLVM_ABI MDNode * getMostGenericNoaliasAddrspace(MDNode *A, MDNode *B)
LLVM_ABI void storeDistinctInContext()
ArrayRef< MDOperand > operands() const
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
static LLVM_ABI MDNode * getMergedProfMetadata(MDNode *A, MDNode *B, const Instruction *AInstr, const Instruction *BInstr)
Merge !prof metadata from two instructions.
static LLVM_ABI MDNode * getMostGenericFPMath(MDNode *A, MDNode *B)
void setNumUnresolved(unsigned N)
unsigned getNumOperands() const
Return number of MDNode operands.
MDOperand * mutable_begin()
LLVM_ABI MDNode(LLVMContext &Context, unsigned ID, StorageType Storage, ArrayRef< Metadata * > Ops1, ArrayRef< Metadata * > Ops2={})
LLVM_ABI TempMDNode clone() const
Create a (temporary) clone of this.
static LLVM_ABI MDNode * getMostGenericRange(MDNode *A, MDNode *B)
LLVM_ABI void setOperand(unsigned I, Metadata *New)
Set an operand.
bool isResolved() const
Check if node is fully resolved.
op_iterator op_begin() const
static LLVM_ABI MDNode * intersect(MDNode *A, MDNode *B)
static T * storeImpl(T *N, StorageType Storage, StoreT &Store)
LLVMContext & getContext() const
LLVM_ABI void dropAllReferences()
static LLVM_ABI MDNode * getMostGenericAlignmentOrDereferenceable(MDNode *A, MDNode *B)
unsigned getNumUnresolved() const
Tracking metadata reference owned by Metadata.
LLVM_ABI StringRef getString() const
static LLVM_ABI MDString * get(LLVMContext &Context, StringRef Str)
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
void eraseNamedMetadata(NamedMDNode *NMD)
Remove the given NamedMDNode from this module and delete it.
MutableArrayRef - Represent a mutable reference to an array (0 or more elements consecutively in memo...
LLVM_ABI void setOperand(unsigned I, MDNode *New)
LLVM_ABI StringRef getName() const
void dropAllReferences()
Remove all uses and clear node vector.
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.
LLVM_ABI void addOperand(MDNode *M)
A discriminated union of two or more pointer types, with the discriminator in the low bit of the poin...
bool isNull() const
Test if the pointer held in the union is null, regardless of which type it is.
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
ArrayRef< value_type > getArrayRef() const
bool remove_if(UnaryPredicate P)
Remove items from the set vector based on a predicate function.
bool empty() const
Determine if the SetVector is empty or not.
bool insert(const value_type &X)
Insert a new element into the SetVector.
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.
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
size_type count(const T &V) const
count - Return 1 if the element is in the set, 0 otherwise.
std::pair< const_iterator, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void reserve(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.
Tracking metadata reference.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
The instances of the Type class are immutable: once they are created, they are never changed.
TypeID
Definitions of all of the base types for the Type system.
static LLVM_ABI IntegerType * getInt64Ty(LLVMContext &C)
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
static LLVM_ABI Type * getMetadataTy(LLVMContext &C)
LLVM Value Representation.
Type * getType() const
All values are typed, get the type of this value.
bool hasMetadata() const
Return true if this value has any metadata attached to it.
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.
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.
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.
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.
An efficient, type-erasing, non-owning reference to a callable.
#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.
@ C
The default llvm calling convention, compatible with C.
LLVM_ABI const_iterator end(StringRef path LLVM_LIFETIME_BOUND)
Get end iterator over path.
This is an optimization pass for GlobalISel generic memory operations.
@ Low
Lower the current thread's priority such that it does not affect foreground tasks significantly.
detail::zippy< detail::zip_shortest, T, U, Args... > zip(T &&t, U &&u, Args &&...args)
zip iterator for two or more iteratable types.
void stable_sort(R &&Range)
auto find(R &&Range, const T &Val)
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly.
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.
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)
constexpr from_range_t from_range
TypedTrackingMDRef< MDNode > TrackingMDNodeRef
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
void sort(IteratorTy Start, IteratorTy End)
@ Ref
The access may reference the value stored in memory.
uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
OutputIt copy(R &&Range, OutputIt Out)
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
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...
void erase_if(Container &C, UnaryPredicate P)
Provide a container algorithm similar to C++ Library Fundamentals v2's erase_if which is equivalent t...
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
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.
static Yes & check(SFINAE< void(U::*)(unsigned), &U::setHash > *)
A collection of metadata nodes that might be associated with a memory access used by the alias-analys...
static LLVM_ABI const char * BranchWeights
Function object to check whether the first component of a container supported by std::get (like std::...