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/SmallString.h"
20 #include "llvm/ADT/StringMap.h"
21 #include "llvm/IR/Instruction.h"
22 #include "llvm/IR/LLVMContext.h"
23 #include "llvm/IR/Module.h"
24 #include "llvm/Support/ConstantRange.h"
25 #include "llvm/Support/LeakDetector.h"
26 #include "llvm/Support/ValueHandle.h"
29 //===----------------------------------------------------------------------===//
30 // MDString implementation.
33 void MDString::anchor() { }
35 MDString::MDString(LLVMContext &C)
36 : Value(Type::getMetadataTy(C), Value::MDStringVal) {}
38 MDString *MDString::get(LLVMContext &Context, StringRef Str) {
39 LLVMContextImpl *pImpl = Context.pImpl;
40 StringMapEntry<Value*> &Entry =
41 pImpl->MDStringCache.GetOrCreateValue(Str);
42 Value *&S = Entry.getValue();
43 if (!S) S = new MDString(Context);
44 S->setValueName(&Entry);
45 return cast<MDString>(S);
48 //===----------------------------------------------------------------------===//
49 // MDNodeOperand implementation.
52 // Use CallbackVH to hold MDNode operands.
54 class MDNodeOperand : public CallbackVH {
56 MDNodeOperand *Cur = this;
58 while (Cur->getValPtrInt() != 1)
61 assert(Cur->getValPtrInt() == 1 &&
62 "Couldn't find the beginning of the operand list!");
63 return reinterpret_cast<MDNode*>(Cur) - 1;
67 MDNodeOperand(Value *V) : CallbackVH(V) {}
68 virtual ~MDNodeOperand();
71 unsigned IsFirst = this->getValPtrInt();
73 this->setAsFirstOperand(IsFirst);
76 /// setAsFirstOperand - Accessor method to mark the operand as the first in
78 void setAsFirstOperand(unsigned V) { this->setValPtrInt(V); }
80 virtual void deleted();
81 virtual void allUsesReplacedWith(Value *NV);
83 } // end namespace llvm.
85 // Provide out-of-line definition to prevent weak vtable.
86 MDNodeOperand::~MDNodeOperand() {}
88 void MDNodeOperand::deleted() {
89 getParent()->replaceOperand(this, 0);
92 void MDNodeOperand::allUsesReplacedWith(Value *NV) {
93 getParent()->replaceOperand(this, NV);
96 //===----------------------------------------------------------------------===//
97 // MDNode implementation.
100 /// getOperandPtr - Helper function to get the MDNodeOperand's coallocated on
101 /// the end of the MDNode.
102 static MDNodeOperand *getOperandPtr(MDNode *N, unsigned Op) {
103 // Use <= instead of < to permit a one-past-the-end address.
104 assert(Op <= N->getNumOperands() && "Invalid operand number");
105 return reinterpret_cast<MDNodeOperand*>(N + 1) + Op;
108 void MDNode::replaceOperandWith(unsigned i, Value *Val) {
109 MDNodeOperand *Op = getOperandPtr(this, i);
110 replaceOperand(Op, Val);
113 MDNode::MDNode(LLVMContext &C, ArrayRef<Value*> Vals, bool isFunctionLocal)
114 : Value(Type::getMetadataTy(C), Value::MDNodeVal) {
115 NumOperands = Vals.size();
118 setValueSubclassData(getSubclassDataFromValue() | FunctionLocalBit);
120 // Initialize the operand list, which is co-allocated on the end of the node.
122 for (MDNodeOperand *Op = getOperandPtr(this, 0), *E = Op+NumOperands;
123 Op != E; ++Op, ++i) {
124 new (Op) MDNodeOperand(Vals[i]);
126 // Mark the first MDNodeOperand as being the first in the list of operands.
128 Op->setAsFirstOperand(1);
132 /// ~MDNode - Destroy MDNode.
134 assert((getSubclassDataFromValue() & DestroyFlag) != 0 &&
135 "Not being destroyed through destroy()?");
136 LLVMContextImpl *pImpl = getType()->getContext().pImpl;
137 if (isNotUniqued()) {
138 pImpl->NonUniquedMDNodes.erase(this);
140 pImpl->MDNodeSet.RemoveNode(this);
143 // Destroy the operands.
144 for (MDNodeOperand *Op = getOperandPtr(this, 0), *E = Op+NumOperands;
146 Op->~MDNodeOperand();
149 static const Function *getFunctionForValue(Value *V) {
151 if (Instruction *I = dyn_cast<Instruction>(V)) {
152 BasicBlock *BB = I->getParent();
153 return BB ? BB->getParent() : 0;
155 if (Argument *A = dyn_cast<Argument>(V))
156 return A->getParent();
157 if (BasicBlock *BB = dyn_cast<BasicBlock>(V))
158 return BB->getParent();
159 if (MDNode *MD = dyn_cast<MDNode>(V))
160 return MD->getFunction();
165 static const Function *assertLocalFunction(const MDNode *N) {
166 if (!N->isFunctionLocal()) return 0;
168 // FIXME: This does not handle cyclic function local metadata.
169 const Function *F = 0, *NewF = 0;
170 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
171 if (Value *V = N->getOperand(i)) {
172 if (MDNode *MD = dyn_cast<MDNode>(V))
173 NewF = assertLocalFunction(MD);
175 NewF = getFunctionForValue(V);
180 assert((NewF == 0 || F == NewF) &&"inconsistent function-local metadata");
186 // getFunction - If this metadata is function-local and recursively has a
187 // function-local operand, return the first such operand's parent function.
188 // Otherwise, return null. getFunction() should not be used for performance-
189 // critical code because it recursively visits all the MDNode's operands.
190 const Function *MDNode::getFunction() const {
192 return assertLocalFunction(this);
194 if (!isFunctionLocal()) return NULL;
195 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
196 if (const Function *F = getFunctionForValue(getOperand(i)))
202 // destroy - Delete this node. Only when there are no uses.
203 void MDNode::destroy() {
204 setValueSubclassData(getSubclassDataFromValue() | DestroyFlag);
205 // Placement delete, then free the memory.
210 /// isFunctionLocalValue - Return true if this is a value that would require a
211 /// function-local MDNode.
212 static bool isFunctionLocalValue(Value *V) {
213 return isa<Instruction>(V) || isa<Argument>(V) || isa<BasicBlock>(V) ||
214 (isa<MDNode>(V) && cast<MDNode>(V)->isFunctionLocal());
217 MDNode *MDNode::getMDNode(LLVMContext &Context, ArrayRef<Value*> Vals,
218 FunctionLocalness FL, bool Insert) {
219 LLVMContextImpl *pImpl = Context.pImpl;
221 // Add all the operand pointers. Note that we don't have to add the
222 // isFunctionLocal bit because that's implied by the operands.
223 // Note that if the operands are later nulled out, the node will be
224 // removed from the uniquing map.
226 for (unsigned i = 0; i != Vals.size(); ++i)
227 ID.AddPointer(Vals[i]);
230 MDNode *N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint);
235 bool isFunctionLocal = false;
238 for (unsigned i = 0; i != Vals.size(); ++i) {
241 if (isFunctionLocalValue(V)) {
242 isFunctionLocal = true;
248 isFunctionLocal = false;
251 isFunctionLocal = true;
255 // Coallocate space for the node and Operands together, then placement new.
256 void *Ptr = malloc(sizeof(MDNode) + Vals.size() * sizeof(MDNodeOperand));
257 N = new (Ptr) MDNode(Context, Vals, isFunctionLocal);
259 // Cache the operand hash.
260 N->Hash = ID.ComputeHash();
262 // InsertPoint will have been set by the FindNodeOrInsertPos call.
263 pImpl->MDNodeSet.InsertNode(N, InsertPoint);
268 MDNode *MDNode::get(LLVMContext &Context, ArrayRef<Value*> Vals) {
269 return getMDNode(Context, Vals, FL_Unknown);
272 MDNode *MDNode::getWhenValsUnresolved(LLVMContext &Context,
273 ArrayRef<Value*> Vals,
274 bool isFunctionLocal) {
275 return getMDNode(Context, Vals, isFunctionLocal ? FL_Yes : FL_No);
278 MDNode *MDNode::getIfExists(LLVMContext &Context, ArrayRef<Value*> Vals) {
279 return getMDNode(Context, Vals, FL_Unknown, false);
282 MDNode *MDNode::getTemporary(LLVMContext &Context, ArrayRef<Value*> Vals) {
284 (MDNode *)malloc(sizeof(MDNode) + Vals.size() * sizeof(MDNodeOperand));
285 N = new (N) MDNode(Context, Vals, FL_No);
286 N->setValueSubclassData(N->getSubclassDataFromValue() |
288 LeakDetector::addGarbageObject(N);
292 void MDNode::deleteTemporary(MDNode *N) {
293 assert(N->use_empty() && "Temporary MDNode has uses!");
294 assert(!N->getContext().pImpl->MDNodeSet.RemoveNode(N) &&
295 "Deleting a non-temporary uniqued node!");
296 assert(!N->getContext().pImpl->NonUniquedMDNodes.erase(N) &&
297 "Deleting a non-temporary non-uniqued node!");
298 assert((N->getSubclassDataFromValue() & NotUniquedBit) &&
299 "Temporary MDNode does not have NotUniquedBit set!");
300 assert((N->getSubclassDataFromValue() & DestroyFlag) == 0 &&
301 "Temporary MDNode has DestroyFlag set!");
302 LeakDetector::removeGarbageObject(N);
306 /// getOperand - Return specified operand.
307 Value *MDNode::getOperand(unsigned i) const {
308 assert(i < getNumOperands() && "Invalid operand number");
309 return *getOperandPtr(const_cast<MDNode*>(this), i);
312 void MDNode::Profile(FoldingSetNodeID &ID) const {
313 // Add all the operand pointers. Note that we don't have to add the
314 // isFunctionLocal bit because that's implied by the operands.
315 // Note that if the operands are later nulled out, the node will be
316 // removed from the uniquing map.
317 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
318 ID.AddPointer(getOperand(i));
321 void MDNode::setIsNotUniqued() {
322 setValueSubclassData(getSubclassDataFromValue() | NotUniquedBit);
323 LLVMContextImpl *pImpl = getType()->getContext().pImpl;
324 pImpl->NonUniquedMDNodes.insert(this);
327 // Replace value from this node's operand list.
328 void MDNode::replaceOperand(MDNodeOperand *Op, Value *To) {
331 // If is possible that someone did GV->RAUW(inst), replacing a global variable
332 // with an instruction or some other function-local object. If this is a
333 // non-function-local MDNode, it can't point to a function-local object.
334 // Handle this case by implicitly dropping the MDNode reference to null.
335 // Likewise if the MDNode is function-local but for a different function.
336 if (To && isFunctionLocalValue(To)) {
337 if (!isFunctionLocal())
340 const Function *F = getFunction();
341 const Function *FV = getFunctionForValue(To);
342 // Metadata can be function-local without having an associated function.
343 // So only consider functions to have changed if non-null.
344 if (F && FV && F != FV)
352 // Update the operand.
355 // If this node is already not being uniqued (because one of the operands
356 // already went to null), then there is nothing else to do here.
357 if (isNotUniqued()) return;
359 LLVMContextImpl *pImpl = getType()->getContext().pImpl;
361 // Remove "this" from the context map. FoldingSet doesn't have to reprofile
362 // this node to remove it, so we don't care what state the operands are in.
363 pImpl->MDNodeSet.RemoveNode(this);
365 // If we are dropping an argument to null, we choose to not unique the MDNode
366 // anymore. This commonly occurs during destruction, and uniquing these
367 // brings little reuse. Also, this means we don't need to include
368 // isFunctionLocal bits in FoldingSetNodeIDs for MDNodes.
374 // Now that the node is out of the folding set, get ready to reinsert it.
375 // First, check to see if another node with the same operands already exists
376 // in the set. If so, then this node is redundant.
380 if (MDNode *N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint)) {
381 replaceAllUsesWith(N);
386 // Cache the operand hash.
387 Hash = ID.ComputeHash();
388 // InsertPoint will have been set by the FindNodeOrInsertPos call.
389 pImpl->MDNodeSet.InsertNode(this, InsertPoint);
391 // If this MDValue was previously function-local but no longer is, clear
392 // its function-local flag.
393 if (isFunctionLocal() && !isFunctionLocalValue(To)) {
394 bool isStillFunctionLocal = false;
395 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
396 Value *V = getOperand(i);
398 if (isFunctionLocalValue(V)) {
399 isStillFunctionLocal = true;
403 if (!isStillFunctionLocal)
404 setValueSubclassData(getSubclassDataFromValue() & ~FunctionLocalBit);
408 MDNode *MDNode::getMostGenericFPMath(MDNode *A, MDNode *B) {
412 APFloat AVal = cast<ConstantFP>(A->getOperand(0))->getValueAPF();
413 APFloat BVal = cast<ConstantFP>(B->getOperand(0))->getValueAPF();
414 if (AVal.compare(BVal) == APFloat::cmpLessThan)
419 static bool isContiguous(const ConstantRange &A, const ConstantRange &B) {
420 return A.getUpper() == B.getLower() || A.getLower() == B.getUpper();
423 static bool canBeMerged(const ConstantRange &A, const ConstantRange &B) {
424 return !A.intersectWith(B).isEmptySet() || isContiguous(A, B);
427 static bool tryMergeRange(SmallVectorImpl<Value *> &EndPoints, ConstantInt *Low,
429 ConstantRange NewRange(Low->getValue(), High->getValue());
430 unsigned Size = EndPoints.size();
431 APInt LB = cast<ConstantInt>(EndPoints[Size - 2])->getValue();
432 APInt LE = cast<ConstantInt>(EndPoints[Size - 1])->getValue();
433 ConstantRange LastRange(LB, LE);
434 if (canBeMerged(NewRange, LastRange)) {
435 ConstantRange Union = LastRange.unionWith(NewRange);
436 Type *Ty = High->getType();
437 EndPoints[Size - 2] = ConstantInt::get(Ty, Union.getLower());
438 EndPoints[Size - 1] = ConstantInt::get(Ty, Union.getUpper());
444 static void addRange(SmallVectorImpl<Value *> &EndPoints, ConstantInt *Low,
446 if (!EndPoints.empty())
447 if (tryMergeRange(EndPoints, Low, High))
450 EndPoints.push_back(Low);
451 EndPoints.push_back(High);
454 MDNode *MDNode::getMostGenericRange(MDNode *A, MDNode *B) {
455 // Given two ranges, we want to compute the union of the ranges. This
456 // is slightly complitade by having to combine the intervals and merge
457 // the ones that overlap.
465 // First, walk both lists in older of the lower boundary of each interval.
466 // At each step, try to merge the new interval to the last one we adedd.
467 SmallVector<Value*, 4> EndPoints;
470 int AN = A->getNumOperands() / 2;
471 int BN = B->getNumOperands() / 2;
472 while (AI < AN && BI < BN) {
473 ConstantInt *ALow = cast<ConstantInt>(A->getOperand(2 * AI));
474 ConstantInt *BLow = cast<ConstantInt>(B->getOperand(2 * BI));
476 if (ALow->getValue().slt(BLow->getValue())) {
477 addRange(EndPoints, ALow, cast<ConstantInt>(A->getOperand(2 * AI + 1)));
480 addRange(EndPoints, BLow, cast<ConstantInt>(B->getOperand(2 * BI + 1)));
485 addRange(EndPoints, cast<ConstantInt>(A->getOperand(2 * AI)),
486 cast<ConstantInt>(A->getOperand(2 * AI + 1)));
490 addRange(EndPoints, cast<ConstantInt>(B->getOperand(2 * BI)),
491 cast<ConstantInt>(B->getOperand(2 * BI + 1)));
495 // If we have more than 2 ranges (4 endpoints) we have to try to merge
496 // the last and first ones.
497 unsigned Size = EndPoints.size();
499 ConstantInt *FB = cast<ConstantInt>(EndPoints[0]);
500 ConstantInt *FE = cast<ConstantInt>(EndPoints[1]);
501 if (tryMergeRange(EndPoints, FB, FE)) {
502 for (unsigned i = 0; i < Size - 2; ++i) {
503 EndPoints[i] = EndPoints[i + 2];
505 EndPoints.resize(Size - 2);
509 // If in the end we have a single range, it is possible that it is now the
510 // full range. Just drop the metadata in that case.
511 if (EndPoints.size() == 2) {
512 ConstantRange Range(cast<ConstantInt>(EndPoints[0])->getValue(),
513 cast<ConstantInt>(EndPoints[1])->getValue());
514 if (Range.isFullSet())
518 return MDNode::get(A->getContext(), EndPoints);
521 //===----------------------------------------------------------------------===//
522 // NamedMDNode implementation.
525 static SmallVector<TrackingVH<MDNode>, 4> &getNMDOps(void *Operands) {
526 return *(SmallVector<TrackingVH<MDNode>, 4>*)Operands;
529 NamedMDNode::NamedMDNode(const Twine &N)
530 : Name(N.str()), Parent(0),
531 Operands(new SmallVector<TrackingVH<MDNode>, 4>()) {
534 NamedMDNode::~NamedMDNode() {
536 delete &getNMDOps(Operands);
539 /// getNumOperands - Return number of NamedMDNode operands.
540 unsigned NamedMDNode::getNumOperands() const {
541 return (unsigned)getNMDOps(Operands).size();
544 /// getOperand - Return specified operand.
545 MDNode *NamedMDNode::getOperand(unsigned i) const {
546 assert(i < getNumOperands() && "Invalid Operand number!");
547 return dyn_cast<MDNode>(&*getNMDOps(Operands)[i]);
550 /// addOperand - Add metadata Operand.
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 /// eraseFromParent - Drop all references and remove the node from parent
559 void NamedMDNode::eraseFromParent() {
560 getParent()->eraseNamedMetadata(this);
563 /// dropAllReferences - Remove all uses and clear node vector.
564 void NamedMDNode::dropAllReferences() {
565 getNMDOps(Operands).clear();
568 /// getName - Return a constant reference to this named metadata's name.
569 StringRef NamedMDNode::getName() const {
570 return StringRef(Name);
573 //===----------------------------------------------------------------------===//
574 // Instruction Metadata method implementations.
577 void Instruction::setMetadata(StringRef Kind, MDNode *Node) {
578 if (Node == 0 && !hasMetadata()) return;
579 setMetadata(getContext().getMDKindID(Kind), Node);
582 MDNode *Instruction::getMetadataImpl(StringRef Kind) const {
583 return getMetadataImpl(getContext().getMDKindID(Kind));
586 /// setMetadata - Set the metadata of of the specified kind to the specified
587 /// node. This updates/replaces metadata if already present, or removes it if
589 void Instruction::setMetadata(unsigned KindID, MDNode *Node) {
590 if (Node == 0 && !hasMetadata()) return;
592 // Handle 'dbg' as a special case since it is not stored in the hash table.
593 if (KindID == LLVMContext::MD_dbg) {
594 DbgLoc = DebugLoc::getFromDILocation(Node);
598 // Handle the case when we're adding/updating metadata on an instruction.
600 LLVMContextImpl::MDMapTy &Info = getContext().pImpl->MetadataStore[this];
601 assert(!Info.empty() == hasMetadataHashEntry() &&
602 "HasMetadata bit is wonked");
604 setHasMetadataHashEntry(true);
606 // Handle replacement of an existing value.
607 for (unsigned i = 0, e = Info.size(); i != e; ++i)
608 if (Info[i].first == KindID) {
609 Info[i].second = Node;
614 // No replacement, just add it to the list.
615 Info.push_back(std::make_pair(KindID, Node));
619 // Otherwise, we're removing metadata from an instruction.
620 assert((hasMetadataHashEntry() ==
621 getContext().pImpl->MetadataStore.count(this)) &&
622 "HasMetadata bit out of date!");
623 if (!hasMetadataHashEntry())
624 return; // Nothing to remove!
625 LLVMContextImpl::MDMapTy &Info = getContext().pImpl->MetadataStore[this];
627 // Common case is removing the only entry.
628 if (Info.size() == 1 && Info[0].first == KindID) {
629 getContext().pImpl->MetadataStore.erase(this);
630 setHasMetadataHashEntry(false);
634 // Handle removal of an existing value.
635 for (unsigned i = 0, e = Info.size(); i != e; ++i)
636 if (Info[i].first == KindID) {
637 Info[i] = Info.back();
639 assert(!Info.empty() && "Removing last entry should be handled above");
642 // Otherwise, removing an entry that doesn't exist on the instruction.
645 MDNode *Instruction::getMetadataImpl(unsigned KindID) const {
646 // Handle 'dbg' as a special case since it is not stored in the hash table.
647 if (KindID == LLVMContext::MD_dbg)
648 return DbgLoc.getAsMDNode(getContext());
650 if (!hasMetadataHashEntry()) return 0;
652 LLVMContextImpl::MDMapTy &Info = getContext().pImpl->MetadataStore[this];
653 assert(!Info.empty() && "bit out of sync with hash table");
655 for (LLVMContextImpl::MDMapTy::iterator I = Info.begin(), E = Info.end();
657 if (I->first == KindID)
662 void Instruction::getAllMetadataImpl(SmallVectorImpl<std::pair<unsigned,
663 MDNode*> > &Result) const {
666 // Handle 'dbg' as a special case since it is not stored in the hash table.
667 if (!DbgLoc.isUnknown()) {
668 Result.push_back(std::make_pair((unsigned)LLVMContext::MD_dbg,
669 DbgLoc.getAsMDNode(getContext())));
670 if (!hasMetadataHashEntry()) return;
673 assert(hasMetadataHashEntry() &&
674 getContext().pImpl->MetadataStore.count(this) &&
675 "Shouldn't have called this");
676 const LLVMContextImpl::MDMapTy &Info =
677 getContext().pImpl->MetadataStore.find(this)->second;
678 assert(!Info.empty() && "Shouldn't have called this");
680 Result.append(Info.begin(), Info.end());
682 // Sort the resulting array so it is stable.
683 if (Result.size() > 1)
684 array_pod_sort(Result.begin(), Result.end());
688 getAllMetadataOtherThanDebugLocImpl(SmallVectorImpl<std::pair<unsigned,
689 MDNode*> > &Result) const {
691 assert(hasMetadataHashEntry() &&
692 getContext().pImpl->MetadataStore.count(this) &&
693 "Shouldn't have called this");
694 const LLVMContextImpl::MDMapTy &Info =
695 getContext().pImpl->MetadataStore.find(this)->second;
696 assert(!Info.empty() && "Shouldn't have called this");
697 Result.append(Info.begin(), Info.end());
699 // Sort the resulting array so it is stable.
700 if (Result.size() > 1)
701 array_pod_sort(Result.begin(), Result.end());
704 /// clearMetadataHashEntries - Clear all hashtable-based metadata from
705 /// this instruction.
706 void Instruction::clearMetadataHashEntries() {
707 assert(hasMetadataHashEntry() && "Caller should check");
708 getContext().pImpl->MetadataStore.erase(this);
709 setHasMetadataHashEntry(false);