1 //===-- Metadata.cpp - Implement Metadata classes -------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the Metadata classes.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/IR/Metadata.h"
15 #include "LLVMContextImpl.h"
16 #include "SymbolTableListTraitsImpl.h"
17 #include "llvm/ADT/DenseMap.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/ADT/SmallSet.h"
20 #include "llvm/ADT/SmallString.h"
21 #include "llvm/ADT/StringMap.h"
22 #include "llvm/IR/ConstantRange.h"
23 #include "llvm/IR/Instruction.h"
24 #include "llvm/IR/LLVMContext.h"
25 #include "llvm/IR/LeakDetector.h"
26 #include "llvm/IR/Module.h"
27 #include "llvm/IR/ValueHandle.h"
31 Metadata::Metadata(LLVMContext &Context, unsigned ID)
32 : Value(Type::getMetadataTy(Context), ID) {}
34 //===----------------------------------------------------------------------===//
35 // MDString implementation.
38 void MDString::anchor() { }
40 MDString *MDString::get(LLVMContext &Context, StringRef Str) {
41 auto &Store = Context.pImpl->MDStringCache;
42 auto I = Store.find(Str);
47 StringMapEntry<MDString>::Create(Str, Store.getAllocator(), Context);
48 bool WasInserted = Store.insert(Entry);
50 assert(WasInserted && "Expected entry to be inserted");
51 Entry->second.Entry = Entry;
52 return &Entry->second;
55 StringRef MDString::getString() const {
56 assert(Entry && "Expected to find string map entry");
57 return Entry->first();
60 //===----------------------------------------------------------------------===//
61 // MDNodeOperand implementation.
64 // Use CallbackVH to hold MDNode operands.
66 class MDNodeOperand : public CallbackVH {
68 MDNodeOperand *Cur = this;
70 while (Cur->getValPtrInt() != 1)
73 assert(Cur->getValPtrInt() == 1 &&
74 "Couldn't find the end of the operand list!");
75 return reinterpret_cast<MDNode *>(Cur + 1);
80 virtual ~MDNodeOperand();
83 unsigned IsLast = this->getValPtrInt();
85 this->setAsLastOperand(IsLast);
88 /// \brief Accessor method to mark the operand as the first in the list.
89 void setAsLastOperand(unsigned I) { this->setValPtrInt(I); }
91 void deleted() override;
92 void allUsesReplacedWith(Value *NV) override;
94 } // end namespace llvm.
96 // Provide out-of-line definition to prevent weak vtable.
97 MDNodeOperand::~MDNodeOperand() {}
99 void MDNodeOperand::deleted() {
100 getParent()->replaceOperand(this, nullptr);
103 void MDNodeOperand::allUsesReplacedWith(Value *NV) {
104 getParent()->replaceOperand(this, NV);
107 //===----------------------------------------------------------------------===//
108 // MDNode implementation.
111 /// \brief Get the MDNodeOperand's coallocated on the end of the MDNode.
112 static MDNodeOperand *getOperandPtr(MDNode *N, unsigned Op) {
113 // Use <= instead of < to permit a one-past-the-end address.
114 assert(Op <= N->getNumOperands() && "Invalid operand number");
115 return reinterpret_cast<MDNodeOperand *>(N) - N->getNumOperands() + Op;
118 void MDNode::replaceOperandWith(unsigned i, Value *Val) {
119 MDNodeOperand *Op = getOperandPtr(this, i);
120 replaceOperand(Op, Val);
123 void *MDNode::operator new(size_t Size, unsigned NumOps) {
124 void *Ptr = ::operator new(Size + NumOps * sizeof(MDNodeOperand));
125 MDNodeOperand *Op = static_cast<MDNodeOperand *>(Ptr);
127 MDNodeOperand *Last = Op + NumOps;
128 for (; Op != Last; ++Op)
129 new (Op) MDNodeOperand();
130 (Op - 1)->setAsLastOperand(1);
135 void MDNode::operator delete(void *Mem) {
136 MDNode *N = static_cast<MDNode *>(Mem);
137 MDNodeOperand *Op = static_cast<MDNodeOperand *>(Mem);
138 for (unsigned I = 0, E = N->NumOperands; I != E; ++I)
139 (--Op)->~MDNodeOperand();
140 ::operator delete(Op);
143 MDNode::MDNode(LLVMContext &C, unsigned ID, ArrayRef<Value *> Vals,
144 bool isFunctionLocal)
146 NumOperands = Vals.size();
149 setValueSubclassData(getSubclassDataFromValue() | FunctionLocalBit);
151 // Initialize the operand list.
153 for (MDNodeOperand *Op = getOperandPtr(this, 0), *E = Op + NumOperands;
158 GenericMDNode::~GenericMDNode() {
159 LLVMContextImpl *pImpl = getType()->getContext().pImpl;
160 if (isNotUniqued()) {
161 pImpl->NonUniquedMDNodes.erase(this);
163 pImpl->MDNodeSet.erase(this);
167 void GenericMDNode::dropAllReferences() {
168 for (MDNodeOperand *Op = getOperandPtr(this, 0), *E = Op + NumOperands;
173 static const Function *getFunctionForValue(Value *V) {
174 if (!V) return nullptr;
175 if (Instruction *I = dyn_cast<Instruction>(V)) {
176 BasicBlock *BB = I->getParent();
177 return BB ? BB->getParent() : nullptr;
179 if (Argument *A = dyn_cast<Argument>(V))
180 return A->getParent();
181 if (BasicBlock *BB = dyn_cast<BasicBlock>(V))
182 return BB->getParent();
183 if (MDNode *MD = dyn_cast<MDNode>(V))
184 return MD->getFunction();
188 // getFunction - If this metadata is function-local and recursively has a
189 // function-local operand, return the first such operand's parent function.
190 // Otherwise, return null. getFunction() should not be used for performance-
191 // critical code because it recursively visits all the MDNode's operands.
192 const Function *MDNode::getFunction() const {
193 if (!isFunctionLocal())
195 assert(getNumOperands() == 1 &&
196 "Expected one operand for function-local metadata");
197 assert(getOperand(0) &&
198 "Expected non-null operand for function-local metadata");
199 assert(!getOperand(0)->getType()->isMetadataTy() &&
200 "Expected non-metadata as operand of function-local metadata");
201 return getFunctionForValue(getOperand(0));
204 /// \brief Check if the Value would require a function-local MDNode.
205 static bool isFunctionLocalValue(Value *V) {
206 return isa<Instruction>(V) || isa<Argument>(V) || isa<BasicBlock>(V) ||
207 (isa<MDNode>(V) && cast<MDNode>(V)->isFunctionLocal());
210 MDNode *MDNode::getMDNode(LLVMContext &Context, ArrayRef<Value*> Vals,
211 FunctionLocalness FL, bool Insert) {
212 auto &Store = Context.pImpl->MDNodeSet;
214 GenericMDNodeInfo::KeyTy Key(Vals);
215 auto I = Store.find_as(Key);
216 if (I != Store.end())
221 bool isFunctionLocal = false;
224 for (Value *V : Vals) {
226 if (isFunctionLocalValue(V)) {
227 isFunctionLocal = true;
233 isFunctionLocal = false;
236 isFunctionLocal = true;
240 if (isFunctionLocal) {
241 assert(Vals.size() == 1 &&
242 "Expected exactly one operand for function-local metadata");
243 assert(Vals[0] && "Expected non-null operand for function-local metadata");
244 assert(!Vals[0]->getType()->isMetadataTy() &&
245 "Expected non-metadata as operand of function-local metadata");
248 // Coallocate space for the node and Operands together, then placement new.
250 new (Vals.size()) GenericMDNode(Context, Vals, isFunctionLocal);
257 MDNode *MDNode::get(LLVMContext &Context, ArrayRef<Value*> Vals) {
258 return getMDNode(Context, Vals, FL_Unknown);
261 MDNode *MDNode::getWhenValsUnresolved(LLVMContext &Context,
262 ArrayRef<Value*> Vals,
263 bool isFunctionLocal) {
264 return getMDNode(Context, Vals, isFunctionLocal ? FL_Yes : FL_No);
267 MDNode *MDNode::getIfExists(LLVMContext &Context, ArrayRef<Value*> Vals) {
268 return getMDNode(Context, Vals, FL_Unknown, false);
271 MDNode *MDNode::getTemporary(LLVMContext &Context, ArrayRef<Value*> Vals) {
272 MDNode *N = new (Vals.size()) MDNodeFwdDecl(Context, Vals, FL_No);
273 N->setValueSubclassData(N->getSubclassDataFromValue() | NotUniquedBit);
274 LeakDetector::addGarbageObject(N);
278 void MDNode::deleteTemporary(MDNode *N) {
279 assert(N->use_empty() && "Temporary MDNode has uses!");
280 assert(isa<MDNodeFwdDecl>(N) && "Expected forward declaration");
281 assert((N->getSubclassDataFromValue() & NotUniquedBit) &&
282 "Temporary MDNode does not have NotUniquedBit set!");
283 LeakDetector::removeGarbageObject(N);
284 delete cast<MDNodeFwdDecl>(N);
287 /// \brief Return specified operand.
288 Value *MDNode::getOperand(unsigned i) const {
289 assert(i < getNumOperands() && "Invalid operand number");
290 return *getOperandPtr(const_cast<MDNode*>(this), i);
293 void MDNode::setIsNotUniqued() {
294 setValueSubclassData(getSubclassDataFromValue() | NotUniquedBit);
295 LLVMContextImpl *pImpl = getType()->getContext().pImpl;
296 auto *G = cast<GenericMDNode>(this);
298 pImpl->NonUniquedMDNodes.insert(G);
301 // Replace value from this node's operand list.
302 void MDNode::replaceOperand(MDNodeOperand *Op, Value *To) {
305 // If is possible that someone did GV->RAUW(inst), replacing a global variable
306 // with an instruction or some other function-local object. If this is a
307 // non-function-local MDNode, it can't point to a function-local object.
308 // Handle this case by implicitly dropping the MDNode reference to null.
309 // Likewise if the MDNode is function-local but for a different function.
310 if (To && isFunctionLocalValue(To)) {
311 assert(!To->getType()->isMetadataTy() &&
312 "Expected non-metadata as operand of function-local metadata");
313 if (!isFunctionLocal())
316 const Function *F = getFunction();
317 const Function *FV = getFunctionForValue(To);
318 // Metadata can be function-local without having an associated function.
319 // So only consider functions to have changed if non-null.
320 if (F && FV && F != FV)
328 // If this MDValue was previously function-local but no longer is, clear
329 // its function-local flag.
330 if (isFunctionLocal() && !(To && isFunctionLocalValue(To))) {
331 assert(getNumOperands() == 1 &&
332 "Expected function-local metadata to have exactly one operand");
333 setValueSubclassData(getSubclassDataFromValue() & ~FunctionLocalBit);
336 // If this node is already not being uniqued (because one of the operands
337 // already went to null), then there is nothing else to do here.
338 if (isNotUniqued()) {
343 auto &Store = getContext().pImpl->MDNodeSet;
344 auto *N = cast<GenericMDNode>(this);
346 // Remove "this" from the context map.
349 // Update the operand.
352 // If we are dropping an argument to null, we choose to not unique the MDNode
353 // anymore. This commonly occurs during destruction, and uniquing these
354 // brings little reuse. Also, this means we don't need to include
355 // isFunctionLocal bits in the hash for MDNodes.
361 // Now that the node is out of the table, get ready to reinsert it. First,
362 // check to see if another node with the same operands already exists in the
363 // set. If so, then this node is redundant.
364 SmallVector<Value *, 8> Vals;
365 GenericMDNodeInfo::KeyTy Key(N, Vals);
366 auto I = Store.find_as(Key);
367 if (I != Store.end()) {
368 N->replaceAllUsesWith(*I);
377 MDNode *MDNode::concatenate(MDNode *A, MDNode *B) {
383 SmallVector<Value *, 4> Vals(A->getNumOperands() +
384 B->getNumOperands());
387 for (unsigned i = 0, ie = A->getNumOperands(); i != ie; ++i)
388 Vals[j++] = A->getOperand(i);
389 for (unsigned i = 0, ie = B->getNumOperands(); i != ie; ++i)
390 Vals[j++] = B->getOperand(i);
392 return MDNode::get(A->getContext(), Vals);
395 MDNode *MDNode::intersect(MDNode *A, MDNode *B) {
399 SmallVector<Value *, 4> Vals;
400 for (unsigned i = 0, ie = A->getNumOperands(); i != ie; ++i) {
401 Value *V = A->getOperand(i);
402 for (unsigned j = 0, je = B->getNumOperands(); j != je; ++j)
403 if (V == B->getOperand(j)) {
409 return MDNode::get(A->getContext(), Vals);
412 MDNode *MDNode::getMostGenericFPMath(MDNode *A, MDNode *B) {
416 APFloat AVal = cast<ConstantFP>(A->getOperand(0))->getValueAPF();
417 APFloat BVal = cast<ConstantFP>(B->getOperand(0))->getValueAPF();
418 if (AVal.compare(BVal) == APFloat::cmpLessThan)
423 static bool isContiguous(const ConstantRange &A, const ConstantRange &B) {
424 return A.getUpper() == B.getLower() || A.getLower() == B.getUpper();
427 static bool canBeMerged(const ConstantRange &A, const ConstantRange &B) {
428 return !A.intersectWith(B).isEmptySet() || isContiguous(A, B);
431 static bool tryMergeRange(SmallVectorImpl<Value *> &EndPoints, ConstantInt *Low,
433 ConstantRange NewRange(Low->getValue(), High->getValue());
434 unsigned Size = EndPoints.size();
435 APInt LB = cast<ConstantInt>(EndPoints[Size - 2])->getValue();
436 APInt LE = cast<ConstantInt>(EndPoints[Size - 1])->getValue();
437 ConstantRange LastRange(LB, LE);
438 if (canBeMerged(NewRange, LastRange)) {
439 ConstantRange Union = LastRange.unionWith(NewRange);
440 Type *Ty = High->getType();
441 EndPoints[Size - 2] = ConstantInt::get(Ty, Union.getLower());
442 EndPoints[Size - 1] = ConstantInt::get(Ty, Union.getUpper());
448 static void addRange(SmallVectorImpl<Value *> &EndPoints, ConstantInt *Low,
450 if (!EndPoints.empty())
451 if (tryMergeRange(EndPoints, Low, High))
454 EndPoints.push_back(Low);
455 EndPoints.push_back(High);
458 MDNode *MDNode::getMostGenericRange(MDNode *A, MDNode *B) {
459 // Given two ranges, we want to compute the union of the ranges. This
460 // is slightly complitade by having to combine the intervals and merge
461 // the ones that overlap.
469 // First, walk both lists in older of the lower boundary of each interval.
470 // At each step, try to merge the new interval to the last one we adedd.
471 SmallVector<Value*, 4> EndPoints;
474 int AN = A->getNumOperands() / 2;
475 int BN = B->getNumOperands() / 2;
476 while (AI < AN && BI < BN) {
477 ConstantInt *ALow = cast<ConstantInt>(A->getOperand(2 * AI));
478 ConstantInt *BLow = cast<ConstantInt>(B->getOperand(2 * BI));
480 if (ALow->getValue().slt(BLow->getValue())) {
481 addRange(EndPoints, ALow, cast<ConstantInt>(A->getOperand(2 * AI + 1)));
484 addRange(EndPoints, BLow, cast<ConstantInt>(B->getOperand(2 * BI + 1)));
489 addRange(EndPoints, cast<ConstantInt>(A->getOperand(2 * AI)),
490 cast<ConstantInt>(A->getOperand(2 * AI + 1)));
494 addRange(EndPoints, cast<ConstantInt>(B->getOperand(2 * BI)),
495 cast<ConstantInt>(B->getOperand(2 * BI + 1)));
499 // If we have more than 2 ranges (4 endpoints) we have to try to merge
500 // the last and first ones.
501 unsigned Size = EndPoints.size();
503 ConstantInt *FB = cast<ConstantInt>(EndPoints[0]);
504 ConstantInt *FE = cast<ConstantInt>(EndPoints[1]);
505 if (tryMergeRange(EndPoints, FB, FE)) {
506 for (unsigned i = 0; i < Size - 2; ++i) {
507 EndPoints[i] = EndPoints[i + 2];
509 EndPoints.resize(Size - 2);
513 // If in the end we have a single range, it is possible that it is now the
514 // full range. Just drop the metadata in that case.
515 if (EndPoints.size() == 2) {
516 ConstantRange Range(cast<ConstantInt>(EndPoints[0])->getValue(),
517 cast<ConstantInt>(EndPoints[1])->getValue());
518 if (Range.isFullSet())
522 return MDNode::get(A->getContext(), EndPoints);
525 //===----------------------------------------------------------------------===//
526 // NamedMDNode implementation.
529 static SmallVector<TrackingVH<MDNode>, 4> &getNMDOps(void *Operands) {
530 return *(SmallVector<TrackingVH<MDNode>, 4> *)Operands;
533 NamedMDNode::NamedMDNode(const Twine &N)
534 : Name(N.str()), Parent(nullptr),
535 Operands(new SmallVector<TrackingVH<MDNode>, 4>()) {}
537 NamedMDNode::~NamedMDNode() {
539 delete &getNMDOps(Operands);
542 unsigned NamedMDNode::getNumOperands() const {
543 return (unsigned)getNMDOps(Operands).size();
546 MDNode *NamedMDNode::getOperand(unsigned i) const {
547 assert(i < getNumOperands() && "Invalid Operand number!");
548 return &*getNMDOps(Operands)[i];
551 void NamedMDNode::addOperand(MDNode *M) {
552 assert(!M->isFunctionLocal() &&
553 "NamedMDNode operands must not be function-local!");
554 getNMDOps(Operands).push_back(TrackingVH<MDNode>(M));
557 void NamedMDNode::eraseFromParent() {
558 getParent()->eraseNamedMetadata(this);
561 void NamedMDNode::dropAllReferences() {
562 getNMDOps(Operands).clear();
565 StringRef NamedMDNode::getName() const {
566 return StringRef(Name);
569 //===----------------------------------------------------------------------===//
570 // Instruction Metadata method implementations.
573 void Instruction::setMetadata(StringRef Kind, MDNode *Node) {
574 if (!Node && !hasMetadata())
576 setMetadata(getContext().getMDKindID(Kind), Node);
579 MDNode *Instruction::getMetadataImpl(StringRef Kind) const {
580 return getMetadataImpl(getContext().getMDKindID(Kind));
583 void Instruction::dropUnknownMetadata(ArrayRef<unsigned> KnownIDs) {
584 SmallSet<unsigned, 5> KnownSet;
585 KnownSet.insert(KnownIDs.begin(), KnownIDs.end());
587 // Drop debug if needed
588 if (KnownSet.erase(LLVMContext::MD_dbg))
591 if (!hasMetadataHashEntry())
592 return; // Nothing to remove!
594 DenseMap<const Instruction *, LLVMContextImpl::MDMapTy> &MetadataStore =
595 getContext().pImpl->MetadataStore;
597 if (KnownSet.empty()) {
598 // Just drop our entry at the store.
599 MetadataStore.erase(this);
600 setHasMetadataHashEntry(false);
604 LLVMContextImpl::MDMapTy &Info = MetadataStore[this];
607 // Walk the array and drop any metadata we don't know.
608 for (I = 0, E = Info.size(); I != E;) {
609 if (KnownSet.count(Info[I].first)) {
614 Info[I] = Info.back();
618 assert(E == Info.size());
621 // Drop our entry at the store.
622 MetadataStore.erase(this);
623 setHasMetadataHashEntry(false);
627 /// setMetadata - Set the metadata of of the specified kind to the specified
628 /// node. This updates/replaces metadata if already present, or removes it if
630 void Instruction::setMetadata(unsigned KindID, MDNode *Node) {
631 if (!Node && !hasMetadata())
634 // Handle 'dbg' as a special case since it is not stored in the hash table.
635 if (KindID == LLVMContext::MD_dbg) {
636 DbgLoc = DebugLoc::getFromDILocation(Node);
640 // Handle the case when we're adding/updating metadata on an instruction.
642 assert(!Node->isFunctionLocal() &&
643 "Function-local metadata cannot be attached to instructions");
644 LLVMContextImpl::MDMapTy &Info = getContext().pImpl->MetadataStore[this];
645 assert(!Info.empty() == hasMetadataHashEntry() &&
646 "HasMetadata bit is wonked");
648 setHasMetadataHashEntry(true);
650 // Handle replacement of an existing value.
652 if (P.first == KindID) {
658 // No replacement, just add it to the list.
659 Info.push_back(std::make_pair(KindID, Node));
663 // Otherwise, we're removing metadata from an instruction.
664 assert((hasMetadataHashEntry() ==
665 (getContext().pImpl->MetadataStore.count(this) > 0)) &&
666 "HasMetadata bit out of date!");
667 if (!hasMetadataHashEntry())
668 return; // Nothing to remove!
669 LLVMContextImpl::MDMapTy &Info = getContext().pImpl->MetadataStore[this];
671 // Common case is removing the only entry.
672 if (Info.size() == 1 && Info[0].first == KindID) {
673 getContext().pImpl->MetadataStore.erase(this);
674 setHasMetadataHashEntry(false);
678 // Handle removal of an existing value.
679 for (unsigned i = 0, e = Info.size(); i != e; ++i)
680 if (Info[i].first == KindID) {
681 Info[i] = Info.back();
683 assert(!Info.empty() && "Removing last entry should be handled above");
686 // Otherwise, removing an entry that doesn't exist on the instruction.
689 void Instruction::setAAMetadata(const AAMDNodes &N) {
690 setMetadata(LLVMContext::MD_tbaa, N.TBAA);
691 setMetadata(LLVMContext::MD_alias_scope, N.Scope);
692 setMetadata(LLVMContext::MD_noalias, N.NoAlias);
695 MDNode *Instruction::getMetadataImpl(unsigned KindID) const {
696 // Handle 'dbg' as a special case since it is not stored in the hash table.
697 if (KindID == LLVMContext::MD_dbg)
698 return DbgLoc.getAsMDNode(getContext());
700 if (!hasMetadataHashEntry()) return nullptr;
702 LLVMContextImpl::MDMapTy &Info = getContext().pImpl->MetadataStore[this];
703 assert(!Info.empty() && "bit out of sync with hash table");
705 for (const auto &I : Info)
706 if (I.first == KindID)
711 void Instruction::getAllMetadataImpl(
712 SmallVectorImpl<std::pair<unsigned, MDNode *>> &Result) const {
715 // Handle 'dbg' as a special case since it is not stored in the hash table.
716 if (!DbgLoc.isUnknown()) {
717 Result.push_back(std::make_pair((unsigned)LLVMContext::MD_dbg,
718 DbgLoc.getAsMDNode(getContext())));
719 if (!hasMetadataHashEntry()) return;
722 assert(hasMetadataHashEntry() &&
723 getContext().pImpl->MetadataStore.count(this) &&
724 "Shouldn't have called this");
725 const LLVMContextImpl::MDMapTy &Info =
726 getContext().pImpl->MetadataStore.find(this)->second;
727 assert(!Info.empty() && "Shouldn't have called this");
729 Result.append(Info.begin(), Info.end());
731 // Sort the resulting array so it is stable.
732 if (Result.size() > 1)
733 array_pod_sort(Result.begin(), Result.end());
736 void Instruction::getAllMetadataOtherThanDebugLocImpl(
737 SmallVectorImpl<std::pair<unsigned, MDNode *>> &Result) const {
739 assert(hasMetadataHashEntry() &&
740 getContext().pImpl->MetadataStore.count(this) &&
741 "Shouldn't have called this");
742 const LLVMContextImpl::MDMapTy &Info =
743 getContext().pImpl->MetadataStore.find(this)->second;
744 assert(!Info.empty() && "Shouldn't have called this");
745 Result.append(Info.begin(), Info.end());
747 // Sort the resulting array so it is stable.
748 if (Result.size() > 1)
749 array_pod_sort(Result.begin(), Result.end());
752 /// clearMetadataHashEntries - Clear all hashtable-based metadata from
753 /// this instruction.
754 void Instruction::clearMetadataHashEntries() {
755 assert(hasMetadataHashEntry() && "Caller should check");
756 getContext().pImpl->MetadataStore.erase(this);
757 setHasMetadataHashEntry(false);