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 "SymbolTableListTraitsImpl.h"
23 #include "llvm/Support/ValueHandle.h"
26 //===----------------------------------------------------------------------===//
27 // MDString implementation.
30 MDString::MDString(LLVMContext &C, StringRef S)
31 : Value(Type::getMetadataTy(C), Value::MDStringVal), Str(S) {}
33 MDString *MDString::get(LLVMContext &Context, StringRef Str) {
34 LLVMContextImpl *pImpl = Context.pImpl;
35 StringMapEntry<MDString *> &Entry =
36 pImpl->MDStringCache.GetOrCreateValue(Str);
37 MDString *&S = Entry.getValue();
38 if (!S) S = new MDString(Context, Entry.getKey());
42 //===----------------------------------------------------------------------===//
43 // MDNodeOperand implementation.
46 // Use CallbackVH to hold MDNode operands.
48 class MDNodeOperand : public CallbackVH {
51 MDNodeOperand(Value *V, MDNode *P) : CallbackVH(V), Parent(P) {}
58 virtual void deleted();
59 virtual void allUsesReplacedWith(Value *NV);
61 } // end namespace llvm.
64 void MDNodeOperand::deleted() {
65 Parent->replaceOperand(this, 0);
68 void MDNodeOperand::allUsesReplacedWith(Value *NV) {
69 Parent->replaceOperand(this, NV);
74 //===----------------------------------------------------------------------===//
75 // MDNode implementation.
78 /// getOperandPtr - Helper function to get the MDNodeOperand's coallocated on
79 /// the end of the MDNode.
80 static MDNodeOperand *getOperandPtr(MDNode *N, unsigned Op) {
81 assert(Op < N->getNumOperands() && "Invalid operand number");
82 return reinterpret_cast<MDNodeOperand*>(N+1)+Op;
85 MDNode::MDNode(LLVMContext &C, Value *const *Vals, unsigned NumVals,
87 : Value(Type::getMetadataTy(C), Value::MDNodeVal) {
88 NumOperands = NumVals;
91 setValueSubclassData(getSubclassDataFromValue() | FunctionLocalBit);
93 // Initialize the operand list, which is co-allocated on the end of the node.
94 for (MDNodeOperand *Op = getOperandPtr(this, 0), *E = Op+NumOperands;
95 Op != E; ++Op, ++Vals)
96 new (Op) MDNodeOperand(*Vals, this);
100 /// ~MDNode - Destroy MDNode.
102 assert((getSubclassDataFromValue() & DestroyFlag) != 0 &&
103 "Not being destroyed through destroy()?");
104 LLVMContextImpl *pImpl = getType()->getContext().pImpl;
105 if (isNotUniqued()) {
106 pImpl->NonUniquedMDNodes.erase(this);
108 pImpl->MDNodeSet.RemoveNode(this);
111 // Destroy the operands.
112 for (MDNodeOperand *Op = getOperandPtr(this, 0), *E = Op+NumOperands;
114 Op->~MDNodeOperand();
117 static const Function *getFunctionForValue(Value *V) {
119 if (Instruction *I = dyn_cast<Instruction>(V)) {
120 BasicBlock *BB = I->getParent();
121 return BB ? BB->getParent() : 0;
123 if (Argument *A = dyn_cast<Argument>(V))
124 return A->getParent();
125 if (BasicBlock *BB = dyn_cast<BasicBlock>(V))
126 return BB->getParent();
127 if (MDNode *MD = dyn_cast<MDNode>(V))
128 return MD->getFunction();
133 static const Function *assertLocalFunction(const MDNode *N) {
134 if (!N->isFunctionLocal()) return 0;
136 const Function *F = 0, *NewF = 0;
137 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
138 if (Value *V = N->getOperand(i)) {
139 if (MDNode *MD = dyn_cast<MDNode>(V))
140 NewF = assertLocalFunction(MD);
142 NewF = getFunctionForValue(V);
147 assert((NewF == 0 || F == NewF) &&"inconsistent function-local metadata");
153 // getFunction - If this metadata is function-local and recursively has a
154 // function-local operand, return the first such operand's parent function.
155 // Otherwise, return null. getFunction() should not be used for performance-
156 // critical code because it recursively visits all the MDNode's operands.
157 const Function *MDNode::getFunction() const {
159 return assertLocalFunction(this);
161 if (!isFunctionLocal()) return NULL;
163 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
164 if (Value *V = getOperand(i)) {
165 if (MDNode *MD = dyn_cast<MDNode>(V)) {
166 if (const Function *F = MD->getFunction())
169 return getFunctionForValue(V);
176 // destroy - Delete this node. Only when there are no uses.
177 void MDNode::destroy() {
178 setValueSubclassData(getSubclassDataFromValue() | DestroyFlag);
179 // Placement delete, the free the memory.
184 /// isFunctionLocalValue - Return true if this is a value that would require a
185 /// function-local MDNode.
186 static bool isFunctionLocalValue(Value *V) {
187 return isa<Instruction>(V) || isa<Argument>(V) || isa<BasicBlock>(V) ||
188 (isa<MDNode>(V) && cast<MDNode>(V)->isFunctionLocal());
191 MDNode *MDNode::getMDNode(LLVMContext &Context, Value *const *Vals,
192 unsigned NumVals, FunctionLocalness FL,
194 LLVMContextImpl *pImpl = Context.pImpl;
195 bool isFunctionLocal = false;
198 for (unsigned i = 0; i != NumVals; ++i) {
201 if (isFunctionLocalValue(V)) {
202 isFunctionLocal = true;
208 isFunctionLocal = false;
211 isFunctionLocal = true;
216 for (unsigned i = 0; i != NumVals; ++i)
217 ID.AddPointer(Vals[i]);
218 ID.AddBoolean(isFunctionLocal);
223 if ((N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint)))
229 // Coallocate space for the node and Operands together, then placement new.
230 void *Ptr = malloc(sizeof(MDNode)+NumVals*sizeof(MDNodeOperand));
231 N = new (Ptr) MDNode(Context, Vals, NumVals, isFunctionLocal);
233 // InsertPoint will have been set by the FindNodeOrInsertPos call.
234 pImpl->MDNodeSet.InsertNode(N, InsertPoint);
239 MDNode *MDNode::get(LLVMContext &Context, Value*const* Vals, unsigned NumVals) {
240 return getMDNode(Context, Vals, NumVals, FL_Unknown);
243 MDNode *MDNode::getWhenValsUnresolved(LLVMContext &Context, Value *const *Vals,
244 unsigned NumVals, bool isFunctionLocal) {
245 return getMDNode(Context, Vals, NumVals, isFunctionLocal ? FL_Yes : FL_No);
248 MDNode *MDNode::getIfExists(LLVMContext &Context, Value *const *Vals,
250 return getMDNode(Context, Vals, NumVals, FL_Unknown, false);
253 /// getOperand - Return specified operand.
254 Value *MDNode::getOperand(unsigned i) const {
255 return *getOperandPtr(const_cast<MDNode*>(this), i);
258 void MDNode::Profile(FoldingSetNodeID &ID) const {
259 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
260 ID.AddPointer(getOperand(i));
261 ID.AddBoolean(isFunctionLocal());
264 void MDNode::setIsNotUniqued() {
265 setValueSubclassData(getSubclassDataFromValue() | NotUniquedBit);
266 LLVMContextImpl *pImpl = getType()->getContext().pImpl;
267 pImpl->NonUniquedMDNodes.insert(this);
270 // Replace value from this node's operand list.
271 void MDNode::replaceOperand(MDNodeOperand *Op, Value *To) {
274 // If is possible that someone did GV->RAUW(inst), replacing a global variable
275 // with an instruction or some other function-local object. If this is a
276 // non-function-local MDNode, it can't point to a function-local object.
277 // Handle this case by implicitly dropping the MDNode reference to null.
278 // Likewise if the MDNode is function-local but for a different function.
279 if (To && isFunctionLocalValue(To)) {
280 if (!isFunctionLocal())
283 const Function *F = getFunction();
284 const Function *FV = getFunctionForValue(To);
285 // Metadata can be function-local without having an associated function.
286 // So only consider functions to have changed if non-null.
287 if (F && FV && F != FV)
295 // Update the operand.
298 // If this node is already not being uniqued (because one of the operands
299 // already went to null), then there is nothing else to do here.
300 if (isNotUniqued()) return;
302 LLVMContextImpl *pImpl = getType()->getContext().pImpl;
304 // Remove "this" from the context map. FoldingSet doesn't have to reprofile
305 // this node to remove it, so we don't care what state the operands are in.
306 pImpl->MDNodeSet.RemoveNode(this);
308 // If we are dropping an argument to null, we choose to not unique the MDNode
309 // anymore. This commonly occurs during destruction, and uniquing these
310 // brings little reuse.
316 // Now that the node is out of the folding set, get ready to reinsert it.
317 // First, check to see if another node with the same operands already exists
318 // in the set. If it doesn't exist, this returns the position to insert it.
322 MDNode *N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint);
325 N->replaceAllUsesWith(this);
327 N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint);
328 assert(N == 0 && "shouldn't be in the map now!"); (void)N;
331 // InsertPoint will have been set by the FindNodeOrInsertPos call.
332 pImpl->MDNodeSet.InsertNode(this, InsertPoint);
335 //===----------------------------------------------------------------------===//
336 // NamedMDNode implementation.
340 // SymbolTableListTraits specialization for MDSymbolTable.
341 void ilist_traits<NamedMDNode>
342 ::addNodeToList(NamedMDNode *N) {
343 assert(N->getParent() == 0 && "Value already in a container!!");
344 Module *Owner = getListOwner();
346 MDSymbolTable &ST = Owner->getMDSymbolTable();
347 ST.insert(N->getName(), N);
350 void ilist_traits<NamedMDNode>::removeNodeFromList(NamedMDNode *N) {
352 Module *Owner = getListOwner();
353 MDSymbolTable &ST = Owner->getMDSymbolTable();
354 ST.remove(N->getName());
358 static SmallVector<WeakVH, 4> &getNMDOps(void *Operands) {
359 return *(SmallVector<WeakVH, 4>*)Operands;
362 NamedMDNode::NamedMDNode(LLVMContext &C, const Twine &N,
364 unsigned NumMDs, Module *ParentModule)
365 : Value(Type::getMetadataTy(C), Value::NamedMDNodeVal), Parent(0) {
367 Operands = new SmallVector<WeakVH, 4>();
369 SmallVector<WeakVH, 4> &Node = getNMDOps(Operands);
370 for (unsigned i = 0; i != NumMDs; ++i)
371 Node.push_back(WeakVH(MDs[i]));
374 ParentModule->getNamedMDList().push_back(this);
377 NamedMDNode *NamedMDNode::Create(const NamedMDNode *NMD, Module *M) {
378 assert(NMD && "Invalid source NamedMDNode!");
379 SmallVector<MDNode *, 4> Elems;
380 Elems.reserve(NMD->getNumOperands());
382 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i)
383 Elems.push_back(NMD->getOperand(i));
384 return new NamedMDNode(NMD->getContext(), NMD->getName().data(),
385 Elems.data(), Elems.size(), M);
388 NamedMDNode::~NamedMDNode() {
390 delete &getNMDOps(Operands);
393 /// getNumOperands - Return number of NamedMDNode operands.
394 unsigned NamedMDNode::getNumOperands() const {
395 return (unsigned)getNMDOps(Operands).size();
398 /// getOperand - Return specified operand.
399 MDNode *NamedMDNode::getOperand(unsigned i) const {
400 assert(i < getNumOperands() && "Invalid Operand number!");
401 return dyn_cast_or_null<MDNode>(getNMDOps(Operands)[i]);
404 /// addOperand - Add metadata Operand.
405 void NamedMDNode::addOperand(MDNode *M) {
406 getNMDOps(Operands).push_back(WeakVH(M));
409 /// eraseFromParent - Drop all references and remove the node from parent
411 void NamedMDNode::eraseFromParent() {
412 getParent()->getNamedMDList().erase(this);
415 /// dropAllReferences - Remove all uses and clear node vector.
416 void NamedMDNode::dropAllReferences() {
417 getNMDOps(Operands).clear();
420 /// setName - Set the name of this named metadata.
421 void NamedMDNode::setName(const Twine &NewName) {
422 assert (!NewName.isTriviallyEmpty() && "Invalid named metadata name!");
424 SmallString<256> NameData;
425 StringRef NameRef = NewName.toStringRef(NameData);
427 // Name isn't changing?
428 if (getName() == NameRef)
431 Name = NameRef.str();
433 Parent->getMDSymbolTable().insert(NameRef, this);
436 /// getName - Return a constant reference to this named metadata's name.
437 StringRef NamedMDNode::getName() const {
438 return StringRef(Name);
441 //===----------------------------------------------------------------------===//
442 // Instruction Metadata method implementations.
445 void Instruction::setMetadata(const char *Kind, MDNode *Node) {
446 if (Node == 0 && !hasMetadata()) return;
447 setMetadata(getContext().getMDKindID(Kind), Node);
450 MDNode *Instruction::getMetadataImpl(const char *Kind) const {
451 return getMetadataImpl(getContext().getMDKindID(Kind));
454 void Instruction::setDbgMetadata(MDNode *Node) {
455 DbgLoc = DebugLoc::getFromDILocation(Node);
458 /// setMetadata - Set the metadata of of the specified kind to the specified
459 /// node. This updates/replaces metadata if already present, or removes it if
461 void Instruction::setMetadata(unsigned KindID, MDNode *Node) {
462 if (Node == 0 && !hasMetadata()) return;
464 // Handle 'dbg' as a special case since it is not stored in the hash table.
465 if (KindID == LLVMContext::MD_dbg) {
466 DbgLoc = DebugLoc::getFromDILocation(Node);
470 // Handle the case when we're adding/updating metadata on an instruction.
472 LLVMContextImpl::MDMapTy &Info = getContext().pImpl->MetadataStore[this];
473 assert(!Info.empty() == hasMetadataHashEntry() &&
474 "HasMetadata bit is wonked");
476 setHasMetadataHashEntry(true);
478 // Handle replacement of an existing value.
479 for (unsigned i = 0, e = Info.size(); i != e; ++i)
480 if (Info[i].first == KindID) {
481 Info[i].second = Node;
486 // No replacement, just add it to the list.
487 Info.push_back(std::make_pair(KindID, Node));
491 // Otherwise, we're removing metadata from an instruction.
492 assert(hasMetadataHashEntry() &&
493 getContext().pImpl->MetadataStore.count(this) &&
494 "HasMetadata bit out of date!");
495 LLVMContextImpl::MDMapTy &Info = getContext().pImpl->MetadataStore[this];
497 // Common case is removing the only entry.
498 if (Info.size() == 1 && Info[0].first == KindID) {
499 getContext().pImpl->MetadataStore.erase(this);
500 setHasMetadataHashEntry(false);
504 // Handle removal of an existing value.
505 for (unsigned i = 0, e = Info.size(); i != e; ++i)
506 if (Info[i].first == KindID) {
507 Info[i] = Info.back();
509 assert(!Info.empty() && "Removing last entry should be handled above");
512 // Otherwise, removing an entry that doesn't exist on the instruction.
515 MDNode *Instruction::getMetadataImpl(unsigned KindID) const {
516 // Handle 'dbg' as a special case since it is not stored in the hash table.
517 if (KindID == LLVMContext::MD_dbg)
518 return DbgLoc.getAsMDNode(getContext());
520 if (!hasMetadataHashEntry()) return 0;
522 LLVMContextImpl::MDMapTy &Info = getContext().pImpl->MetadataStore[this];
523 assert(!Info.empty() && "bit out of sync with hash table");
525 for (LLVMContextImpl::MDMapTy::iterator I = Info.begin(), E = Info.end();
527 if (I->first == KindID)
532 void Instruction::getAllMetadataImpl(SmallVectorImpl<std::pair<unsigned,
533 MDNode*> > &Result) const {
536 // Handle 'dbg' as a special case since it is not stored in the hash table.
537 if (!DbgLoc.isUnknown()) {
538 Result.push_back(std::make_pair((unsigned)LLVMContext::MD_dbg,
539 DbgLoc.getAsMDNode(getContext())));
540 if (!hasMetadataHashEntry()) return;
543 assert(hasMetadataHashEntry() &&
544 getContext().pImpl->MetadataStore.count(this) &&
545 "Shouldn't have called this");
546 const LLVMContextImpl::MDMapTy &Info =
547 getContext().pImpl->MetadataStore.find(this)->second;
548 assert(!Info.empty() && "Shouldn't have called this");
550 Result.append(Info.begin(), Info.end());
552 // Sort the resulting array so it is stable.
553 if (Result.size() > 1)
554 array_pod_sort(Result.begin(), Result.end());
558 getAllMetadataOtherThanDebugLocImpl(SmallVectorImpl<std::pair<unsigned,
559 MDNode*> > &Result) const {
561 assert(hasMetadataHashEntry() &&
562 getContext().pImpl->MetadataStore.count(this) &&
563 "Shouldn't have called this");
564 const LLVMContextImpl::MDMapTy &Info =
565 getContext().pImpl->MetadataStore.find(this)->second;
566 assert(!Info.empty() && "Shouldn't have called this");
568 Result.append(Info.begin(), Info.end());
570 // Sort the resulting array so it is stable.
571 if (Result.size() > 1)
572 array_pod_sort(Result.begin(), Result.end());
576 /// removeAllMetadata - Remove all metadata from this instruction.
577 void Instruction::removeAllMetadata() {
578 assert(hasMetadata() && "Caller should check");
580 if (hasMetadataHashEntry()) {
581 getContext().pImpl->MetadataStore.erase(this);
582 setHasMetadataHashEntry(false);