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/Metadata.h"
15 #include "LLVMContextImpl.h"
16 #include "llvm/LLVMContext.h"
17 #include "llvm/Module.h"
18 #include "llvm/Instruction.h"
19 #include "llvm/ADT/DenseMap.h"
20 #include "llvm/ADT/StringMap.h"
21 #include "llvm/ADT/SmallString.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "SymbolTableListTraitsImpl.h"
24 #include "llvm/Support/LeakDetector.h"
25 #include "llvm/Support/ValueHandle.h"
28 //===----------------------------------------------------------------------===//
29 // MDString implementation.
32 void MDString::anchor() { }
34 MDString::MDString(LLVMContext &C, StringRef S)
35 : Value(Type::getMetadataTy(C), Value::MDStringVal), Str(S) {}
37 MDString *MDString::get(LLVMContext &Context, StringRef Str) {
38 LLVMContextImpl *pImpl = Context.pImpl;
39 StringMapEntry<MDString *> &Entry =
40 pImpl->MDStringCache.GetOrCreateValue(Str);
41 MDString *&S = Entry.getValue();
42 if (!S) S = new MDString(Context, Entry.getKey());
46 //===----------------------------------------------------------------------===//
47 // MDNodeOperand implementation.
50 // Use CallbackVH to hold MDNode operands.
52 class MDNodeOperand : public CallbackVH {
55 MDNodeOperand(Value *V, MDNode *P) : CallbackVH(V), Parent(P) {}
62 virtual void deleted();
63 virtual void allUsesReplacedWith(Value *NV);
65 } // end namespace llvm.
68 void MDNodeOperand::deleted() {
69 Parent->replaceOperand(this, 0);
72 void MDNodeOperand::allUsesReplacedWith(Value *NV) {
73 Parent->replaceOperand(this, NV);
78 //===----------------------------------------------------------------------===//
79 // MDNode implementation.
82 /// getOperandPtr - Helper function to get the MDNodeOperand's coallocated on
83 /// the end of the MDNode.
84 static MDNodeOperand *getOperandPtr(MDNode *N, unsigned Op) {
85 // Use <= instead of < to permit a one-past-the-end address.
86 assert(Op <= N->getNumOperands() && "Invalid operand number");
87 return reinterpret_cast<MDNodeOperand*>(N+1)+Op;
90 void MDNode::replaceOperandWith(unsigned i, Value *Val) {
91 MDNodeOperand *Op = getOperandPtr(this, i);
92 replaceOperand(Op, Val);
95 MDNode::MDNode(LLVMContext &C, ArrayRef<Value*> Vals, bool isFunctionLocal)
96 : Value(Type::getMetadataTy(C), Value::MDNodeVal) {
97 NumOperands = Vals.size();
100 setValueSubclassData(getSubclassDataFromValue() | FunctionLocalBit);
102 // Initialize the operand list, which is co-allocated on the end of the node.
104 for (MDNodeOperand *Op = getOperandPtr(this, 0), *E = Op+NumOperands;
106 new (Op) MDNodeOperand(Vals[i], this);
110 /// ~MDNode - Destroy MDNode.
112 assert((getSubclassDataFromValue() & DestroyFlag) != 0 &&
113 "Not being destroyed through destroy()?");
114 LLVMContextImpl *pImpl = getType()->getContext().pImpl;
115 if (isNotUniqued()) {
116 pImpl->NonUniquedMDNodes.erase(this);
118 pImpl->MDNodeSet.RemoveNode(this);
121 // Destroy the operands.
122 for (MDNodeOperand *Op = getOperandPtr(this, 0), *E = Op+NumOperands;
124 Op->~MDNodeOperand();
127 static const Function *getFunctionForValue(Value *V) {
129 if (Instruction *I = dyn_cast<Instruction>(V)) {
130 BasicBlock *BB = I->getParent();
131 return BB ? BB->getParent() : 0;
133 if (Argument *A = dyn_cast<Argument>(V))
134 return A->getParent();
135 if (BasicBlock *BB = dyn_cast<BasicBlock>(V))
136 return BB->getParent();
137 if (MDNode *MD = dyn_cast<MDNode>(V))
138 return MD->getFunction();
143 static const Function *assertLocalFunction(const MDNode *N) {
144 if (!N->isFunctionLocal()) return 0;
146 // FIXME: This does not handle cyclic function local metadata.
147 const Function *F = 0, *NewF = 0;
148 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
149 if (Value *V = N->getOperand(i)) {
150 if (MDNode *MD = dyn_cast<MDNode>(V))
151 NewF = assertLocalFunction(MD);
153 NewF = getFunctionForValue(V);
158 assert((NewF == 0 || F == NewF) &&"inconsistent function-local metadata");
164 // getFunction - If this metadata is function-local and recursively has a
165 // function-local operand, return the first such operand's parent function.
166 // Otherwise, return null. getFunction() should not be used for performance-
167 // critical code because it recursively visits all the MDNode's operands.
168 const Function *MDNode::getFunction() const {
170 return assertLocalFunction(this);
172 if (!isFunctionLocal()) return NULL;
173 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
174 if (const Function *F = getFunctionForValue(getOperand(i)))
180 // destroy - Delete this node. Only when there are no uses.
181 void MDNode::destroy() {
182 setValueSubclassData(getSubclassDataFromValue() | DestroyFlag);
183 // Placement delete, the free the memory.
188 /// isFunctionLocalValue - Return true if this is a value that would require a
189 /// function-local MDNode.
190 static bool isFunctionLocalValue(Value *V) {
191 return isa<Instruction>(V) || isa<Argument>(V) || isa<BasicBlock>(V) ||
192 (isa<MDNode>(V) && cast<MDNode>(V)->isFunctionLocal());
195 MDNode *MDNode::getMDNode(LLVMContext &Context, ArrayRef<Value*> Vals,
196 FunctionLocalness FL, bool Insert) {
197 LLVMContextImpl *pImpl = Context.pImpl;
199 // Add all the operand pointers. Note that we don't have to add the
200 // isFunctionLocal bit because that's implied by the operands.
201 // Note that if the operands are later nulled out, the node will be
202 // removed from the uniquing map.
204 for (unsigned i = 0; i != Vals.size(); ++i)
205 ID.AddPointer(Vals[i]);
210 if ((N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint)))
213 bool isFunctionLocal = false;
216 for (unsigned i = 0; i != Vals.size(); ++i) {
219 if (isFunctionLocalValue(V)) {
220 isFunctionLocal = true;
226 isFunctionLocal = false;
229 isFunctionLocal = true;
233 // Coallocate space for the node and Operands together, then placement new.
234 void *Ptr = malloc(sizeof(MDNode)+Vals.size()*sizeof(MDNodeOperand));
235 N = new (Ptr) MDNode(Context, Vals, isFunctionLocal);
237 // InsertPoint will have been set by the FindNodeOrInsertPos call.
238 pImpl->MDNodeSet.InsertNode(N, InsertPoint);
243 MDNode *MDNode::get(LLVMContext &Context, ArrayRef<Value*> Vals) {
244 return getMDNode(Context, Vals, FL_Unknown);
247 MDNode *MDNode::getWhenValsUnresolved(LLVMContext &Context,
248 ArrayRef<Value*> Vals,
249 bool isFunctionLocal) {
250 return getMDNode(Context, Vals, isFunctionLocal ? FL_Yes : FL_No);
253 MDNode *MDNode::getIfExists(LLVMContext &Context, ArrayRef<Value*> Vals) {
254 return getMDNode(Context, Vals, FL_Unknown, false);
257 MDNode *MDNode::getTemporary(LLVMContext &Context, ArrayRef<Value*> Vals) {
259 (MDNode *)malloc(sizeof(MDNode)+Vals.size()*sizeof(MDNodeOperand));
260 N = new (N) MDNode(Context, Vals, FL_No);
261 N->setValueSubclassData(N->getSubclassDataFromValue() |
263 LeakDetector::addGarbageObject(N);
267 void MDNode::deleteTemporary(MDNode *N) {
268 assert(N->use_empty() && "Temporary MDNode has uses!");
269 assert(!N->getContext().pImpl->MDNodeSet.RemoveNode(N) &&
270 "Deleting a non-temporary uniqued node!");
271 assert(!N->getContext().pImpl->NonUniquedMDNodes.erase(N) &&
272 "Deleting a non-temporary non-uniqued node!");
273 assert((N->getSubclassDataFromValue() & NotUniquedBit) &&
274 "Temporary MDNode does not have NotUniquedBit set!");
275 assert((N->getSubclassDataFromValue() & DestroyFlag) == 0 &&
276 "Temporary MDNode has DestroyFlag set!");
277 LeakDetector::removeGarbageObject(N);
281 /// getOperand - Return specified operand.
282 Value *MDNode::getOperand(unsigned i) const {
283 return *getOperandPtr(const_cast<MDNode*>(this), i);
286 void MDNode::Profile(FoldingSetNodeID &ID) const {
287 // Add all the operand pointers. Note that we don't have to add the
288 // isFunctionLocal bit because that's implied by the operands.
289 // Note that if the operands are later nulled out, the node will be
290 // removed from the uniquing map.
291 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
292 ID.AddPointer(getOperand(i));
295 void MDNode::setIsNotUniqued() {
296 setValueSubclassData(getSubclassDataFromValue() | NotUniquedBit);
297 LLVMContextImpl *pImpl = getType()->getContext().pImpl;
298 pImpl->NonUniquedMDNodes.insert(this);
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 if (!isFunctionLocal())
314 const Function *F = getFunction();
315 const Function *FV = getFunctionForValue(To);
316 // Metadata can be function-local without having an associated function.
317 // So only consider functions to have changed if non-null.
318 if (F && FV && F != FV)
326 // Update the operand.
329 // If this node is already not being uniqued (because one of the operands
330 // already went to null), then there is nothing else to do here.
331 if (isNotUniqued()) return;
333 LLVMContextImpl *pImpl = getType()->getContext().pImpl;
335 // Remove "this" from the context map. FoldingSet doesn't have to reprofile
336 // this node to remove it, so we don't care what state the operands are in.
337 pImpl->MDNodeSet.RemoveNode(this);
339 // If we are dropping an argument to null, we choose to not unique the MDNode
340 // anymore. This commonly occurs during destruction, and uniquing these
341 // brings little reuse. Also, this means we don't need to include
342 // isFunctionLocal bits in FoldingSetNodeIDs for MDNodes.
348 // Now that the node is out of the folding set, get ready to reinsert it.
349 // First, check to see if another node with the same operands already exists
350 // in the set. If so, then this node is redundant.
354 if (MDNode *N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint)) {
355 replaceAllUsesWith(N);
360 // InsertPoint will have been set by the FindNodeOrInsertPos call.
361 pImpl->MDNodeSet.InsertNode(this, InsertPoint);
363 // If this MDValue was previously function-local but no longer is, clear
364 // its function-local flag.
365 if (isFunctionLocal() && !isFunctionLocalValue(To)) {
366 bool isStillFunctionLocal = false;
367 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
368 Value *V = getOperand(i);
370 if (isFunctionLocalValue(V)) {
371 isStillFunctionLocal = true;
375 if (!isStillFunctionLocal)
376 setValueSubclassData(getSubclassDataFromValue() & ~FunctionLocalBit);
380 //===----------------------------------------------------------------------===//
381 // NamedMDNode implementation.
384 static SmallVector<TrackingVH<MDNode>, 4> &getNMDOps(void *Operands) {
385 return *(SmallVector<TrackingVH<MDNode>, 4>*)Operands;
388 NamedMDNode::NamedMDNode(const Twine &N)
389 : Name(N.str()), Parent(0),
390 Operands(new SmallVector<TrackingVH<MDNode>, 4>()) {
393 NamedMDNode::~NamedMDNode() {
395 delete &getNMDOps(Operands);
398 /// getNumOperands - Return number of NamedMDNode operands.
399 unsigned NamedMDNode::getNumOperands() const {
400 return (unsigned)getNMDOps(Operands).size();
403 /// getOperand - Return specified operand.
404 MDNode *NamedMDNode::getOperand(unsigned i) const {
405 assert(i < getNumOperands() && "Invalid Operand number!");
406 return dyn_cast<MDNode>(&*getNMDOps(Operands)[i]);
409 /// addOperand - Add metadata Operand.
410 void NamedMDNode::addOperand(MDNode *M) {
411 assert(!M->isFunctionLocal() &&
412 "NamedMDNode operands must not be function-local!");
413 getNMDOps(Operands).push_back(TrackingVH<MDNode>(M));
416 /// eraseFromParent - Drop all references and remove the node from parent
418 void NamedMDNode::eraseFromParent() {
419 getParent()->eraseNamedMetadata(this);
422 /// dropAllReferences - Remove all uses and clear node vector.
423 void NamedMDNode::dropAllReferences() {
424 getNMDOps(Operands).clear();
427 /// getName - Return a constant reference to this named metadata's name.
428 StringRef NamedMDNode::getName() const {
429 return StringRef(Name);
432 //===----------------------------------------------------------------------===//
433 // Instruction Metadata method implementations.
436 void Instruction::setMetadata(StringRef Kind, MDNode *Node) {
437 if (Node == 0 && !hasMetadata()) return;
438 setMetadata(getContext().getMDKindID(Kind), Node);
441 MDNode *Instruction::getMetadataImpl(StringRef Kind) const {
442 return getMetadataImpl(getContext().getMDKindID(Kind));
445 /// setMetadata - Set the metadata of of the specified kind to the specified
446 /// node. This updates/replaces metadata if already present, or removes it if
448 void Instruction::setMetadata(unsigned KindID, MDNode *Node) {
449 if (Node == 0 && !hasMetadata()) return;
451 // Handle 'dbg' as a special case since it is not stored in the hash table.
452 if (KindID == LLVMContext::MD_dbg) {
453 DbgLoc = DebugLoc::getFromDILocation(Node);
457 // Handle the case when we're adding/updating metadata on an instruction.
459 LLVMContextImpl::MDMapTy &Info = getContext().pImpl->MetadataStore[this];
460 assert(!Info.empty() == hasMetadataHashEntry() &&
461 "HasMetadata bit is wonked");
463 setHasMetadataHashEntry(true);
465 // Handle replacement of an existing value.
466 for (unsigned i = 0, e = Info.size(); i != e; ++i)
467 if (Info[i].first == KindID) {
468 Info[i].second = Node;
473 // No replacement, just add it to the list.
474 Info.push_back(std::make_pair(KindID, Node));
478 // Otherwise, we're removing metadata from an instruction.
479 assert((hasMetadataHashEntry() ==
480 getContext().pImpl->MetadataStore.count(this)) &&
481 "HasMetadata bit out of date!");
482 if (!hasMetadataHashEntry())
483 return; // Nothing to remove!
484 LLVMContextImpl::MDMapTy &Info = getContext().pImpl->MetadataStore[this];
486 // Common case is removing the only entry.
487 if (Info.size() == 1 && Info[0].first == KindID) {
488 getContext().pImpl->MetadataStore.erase(this);
489 setHasMetadataHashEntry(false);
493 // Handle removal of an existing value.
494 for (unsigned i = 0, e = Info.size(); i != e; ++i)
495 if (Info[i].first == KindID) {
496 Info[i] = Info.back();
498 assert(!Info.empty() && "Removing last entry should be handled above");
501 // Otherwise, removing an entry that doesn't exist on the instruction.
504 MDNode *Instruction::getMetadataImpl(unsigned KindID) const {
505 // Handle 'dbg' as a special case since it is not stored in the hash table.
506 if (KindID == LLVMContext::MD_dbg)
507 return DbgLoc.getAsMDNode(getContext());
509 if (!hasMetadataHashEntry()) return 0;
511 LLVMContextImpl::MDMapTy &Info = getContext().pImpl->MetadataStore[this];
512 assert(!Info.empty() && "bit out of sync with hash table");
514 for (LLVMContextImpl::MDMapTy::iterator I = Info.begin(), E = Info.end();
516 if (I->first == KindID)
521 void Instruction::getAllMetadataImpl(SmallVectorImpl<std::pair<unsigned,
522 MDNode*> > &Result) const {
525 // Handle 'dbg' as a special case since it is not stored in the hash table.
526 if (!DbgLoc.isUnknown()) {
527 Result.push_back(std::make_pair((unsigned)LLVMContext::MD_dbg,
528 DbgLoc.getAsMDNode(getContext())));
529 if (!hasMetadataHashEntry()) return;
532 assert(hasMetadataHashEntry() &&
533 getContext().pImpl->MetadataStore.count(this) &&
534 "Shouldn't have called this");
535 const LLVMContextImpl::MDMapTy &Info =
536 getContext().pImpl->MetadataStore.find(this)->second;
537 assert(!Info.empty() && "Shouldn't have called this");
539 Result.append(Info.begin(), Info.end());
541 // Sort the resulting array so it is stable.
542 if (Result.size() > 1)
543 array_pod_sort(Result.begin(), Result.end());
547 getAllMetadataOtherThanDebugLocImpl(SmallVectorImpl<std::pair<unsigned,
548 MDNode*> > &Result) const {
550 assert(hasMetadataHashEntry() &&
551 getContext().pImpl->MetadataStore.count(this) &&
552 "Shouldn't have called this");
553 const LLVMContextImpl::MDMapTy &Info =
554 getContext().pImpl->MetadataStore.find(this)->second;
555 assert(!Info.empty() && "Shouldn't have called this");
557 Result.append(Info.begin(), Info.end());
559 // Sort the resulting array so it is stable.
560 if (Result.size() > 1)
561 array_pod_sort(Result.begin(), Result.end());
565 /// clearMetadataHashEntries - Clear all hashtable-based metadata from
566 /// this instruction.
567 void Instruction::clearMetadataHashEntries() {
568 assert(hasMetadataHashEntry() && "Caller should check");
569 getContext().pImpl->MetadataStore.erase(this);
570 setHasMetadataHashEntry(false);