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 : MetadataBase(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 MDString *MDString::get(LLVMContext &Context, const char *Str) {
43 LLVMContextImpl *pImpl = Context.pImpl;
44 StringMapEntry<MDString *> &Entry =
45 pImpl->MDStringCache.GetOrCreateValue(Str ? StringRef(Str) : StringRef());
46 MDString *&S = Entry.getValue();
47 if (!S) S = new MDString(Context, Entry.getKey());
51 //===----------------------------------------------------------------------===//
52 // MDNodeOperand implementation.
55 // Use CallbackVH to hold MDNode operands.
57 class MDNodeOperand : public CallbackVH {
60 MDNodeOperand(Value *V, MDNode *P) : CallbackVH(V), Parent(P) {}
67 virtual void deleted();
68 virtual void allUsesReplacedWith(Value *NV);
70 } // end namespace llvm.
73 void MDNodeOperand::deleted() {
74 Parent->replaceOperand(this, 0);
77 void MDNodeOperand::allUsesReplacedWith(Value *NV) {
78 Parent->replaceOperand(this, NV);
83 //===----------------------------------------------------------------------===//
84 // MDNode implementation.
87 /// getOperandPtr - Helper function to get the MDNodeOperand's coallocated on
88 /// the end of the MDNode.
89 static MDNodeOperand *getOperandPtr(MDNode *N, unsigned Op) {
90 assert(Op < N->getNumOperands() && "Invalid operand number");
91 return reinterpret_cast<MDNodeOperand*>(N+1)+Op;
94 MDNode::MDNode(LLVMContext &C, Value *const *Vals, unsigned NumVals,
96 : MetadataBase(Type::getMetadataTy(C), Value::MDNodeVal) {
97 NumOperands = NumVals;
100 setValueSubclassData(getSubclassDataFromValue() | FunctionLocalBit);
102 // Initialize the operand list, which is co-allocated on the end of the node.
103 for (MDNodeOperand *Op = getOperandPtr(this, 0), *E = Op+NumOperands;
104 Op != E; ++Op, ++Vals)
105 new (Op) MDNodeOperand(*Vals, this);
109 /// ~MDNode - Destroy MDNode.
111 assert((getSubclassDataFromValue() & DestroyFlag) != 0 &&
112 "Not being destroyed through destroy()?");
113 if (!isNotUniqued()) {
114 LLVMContextImpl *pImpl = getType()->getContext().pImpl;
115 pImpl->MDNodeSet.RemoveNode(this);
118 // Destroy the operands.
119 for (MDNodeOperand *Op = getOperandPtr(this, 0), *E = Op+NumOperands;
121 Op->~MDNodeOperand();
125 static Function *assertLocalFunction(const MDNode *N) {
126 if (!N->isFunctionLocal()) return NULL;
129 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
130 Value *V = N->getOperand(i);
132 if (Instruction *I = dyn_cast<Instruction>(V)) {
133 if (F) assert(F == I->getParent()->getParent() &&
134 "inconsistent function-local metadata");
135 else F = I->getParent()->getParent();
136 } else if (BasicBlock *BB = dyn_cast<BasicBlock>(V)) {
137 if (F) assert(F == BB->getParent() &&
138 "inconsistent function-local metadata");
139 else F = BB->getParent();
140 } else if (Argument *A = dyn_cast<Argument>(V)) {
141 if (F) assert(F == A->getParent() &&
142 "inconsistent function-local metadata");
143 else F = A->getParent();
144 } else if (MDNode *MD = dyn_cast<MDNode>(V)) {
145 if (Function *NewF = assertLocalFunction(MD)) {
146 if (F) assert(F == NewF && "inconsistent function-local metadata");
155 // getFunction - If this metadata is function-local and recursively has a
156 // function-local operand, return the first such operand's parent function.
157 // Otherwise, return null. getFunction() should not be used for performance-
158 // critical code because it recursively visits all the MDNode's operands.
159 Function *MDNode::getFunction() const {
161 return assertLocalFunction(this);
164 if (!isFunctionLocal()) return NULL;
166 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
167 Value *V = getOperand(i);
169 if (Instruction *I = dyn_cast<Instruction>(V))
170 return I->getParent()->getParent();
171 if (BasicBlock *BB = dyn_cast<BasicBlock>(V))
172 return BB->getParent();
173 if (Argument *A = dyn_cast<Argument>(V))
174 return A->getParent();
175 if (MDNode *MD = dyn_cast<MDNode>(V))
176 if (Function *F = MD->getFunction()) return F;
181 // destroy - Delete this node. Only when there are no uses.
182 void MDNode::destroy() {
183 setValueSubclassData(getSubclassDataFromValue() | DestroyFlag);
184 // Placement delete, the free the memory.
189 MDNode *MDNode::getMDNode(LLVMContext &Context, Value *const *Vals,
190 unsigned NumVals, FunctionLocalness FL) {
191 LLVMContextImpl *pImpl = Context.pImpl;
193 for (unsigned i = 0; i != NumVals; ++i)
194 ID.AddPointer(Vals[i]);
197 MDNode *N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint);
199 bool isFunctionLocal = false;
202 for (unsigned i = 0; i != NumVals; ++i) {
205 if (isa<Instruction>(V) || isa<Argument>(V) || isa<BasicBlock>(V) ||
206 (isa<MDNode>(V) && cast<MDNode>(V)->isFunctionLocal())) {
207 isFunctionLocal = true;
213 isFunctionLocal = false;
216 isFunctionLocal = true;
220 // Coallocate space for the node and Operands together, then placement new.
221 void *Ptr = malloc(sizeof(MDNode)+NumVals*sizeof(MDNodeOperand));
222 N = new (Ptr) MDNode(Context, Vals, NumVals, isFunctionLocal);
224 // InsertPoint will have been set by the FindNodeOrInsertPos call.
225 pImpl->MDNodeSet.InsertNode(N, InsertPoint);
230 MDNode *MDNode::get(LLVMContext &Context, Value*const* Vals, unsigned NumVals) {
231 return getMDNode(Context, Vals, NumVals, FL_Unknown);
234 MDNode *MDNode::getWhenValsUnresolved(LLVMContext &Context, Value*const* Vals,
235 unsigned NumVals, bool isFunctionLocal) {
236 return getMDNode(Context, Vals, NumVals, isFunctionLocal ? FL_Yes : FL_No);
239 /// getOperand - Return specified operand.
240 Value *MDNode::getOperand(unsigned i) const {
241 return *getOperandPtr(const_cast<MDNode*>(this), i);
244 void MDNode::Profile(FoldingSetNodeID &ID) const {
245 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
246 ID.AddPointer(getOperand(i));
250 // Replace value from this node's operand list.
251 void MDNode::replaceOperand(MDNodeOperand *Op, Value *To) {
257 // Update the operand.
260 // If this node is already not being uniqued (because one of the operands
261 // already went to null), then there is nothing else to do here.
262 if (isNotUniqued()) return;
264 LLVMContextImpl *pImpl = getType()->getContext().pImpl;
266 // Remove "this" from the context map. FoldingSet doesn't have to reprofile
267 // this node to remove it, so we don't care what state the operands are in.
268 pImpl->MDNodeSet.RemoveNode(this);
270 // If we are dropping an argument to null, we choose to not unique the MDNode
271 // anymore. This commonly occurs during destruction, and uniquing these
272 // brings little reuse.
278 // Now that the node is out of the folding set, get ready to reinsert it.
279 // First, check to see if another node with the same operands already exists
280 // in the set. If it doesn't exist, this returns the position to insert it.
284 MDNode *N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint);
287 N->replaceAllUsesWith(this);
289 N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint);
290 assert(N == 0 && "shouldn't be in the map now!"); (void)N;
293 // InsertPoint will have been set by the FindNodeOrInsertPos call.
294 pImpl->MDNodeSet.InsertNode(this, InsertPoint);
297 //===----------------------------------------------------------------------===//
298 // NamedMDNode implementation.
302 // SymbolTableListTraits specialization for MDSymbolTable.
303 void ilist_traits<NamedMDNode>
304 ::addNodeToList(NamedMDNode *N) {
305 assert(N->getParent() == 0 && "Value already in a container!!");
306 Module *Owner = getListOwner();
308 MDSymbolTable &ST = Owner->getMDSymbolTable();
309 ST.insert(N->getName(), N);
312 void ilist_traits<NamedMDNode>::removeNodeFromList(NamedMDNode *N) {
314 Module *Owner = getListOwner();
315 MDSymbolTable &ST = Owner->getMDSymbolTable();
316 ST.remove(N->getName());
320 static SmallVector<WeakVH, 4> &getNMDOps(void *Operands) {
321 return *(SmallVector<WeakVH, 4>*)Operands;
324 NamedMDNode::NamedMDNode(LLVMContext &C, const Twine &N,
326 unsigned NumMDs, Module *ParentModule)
327 : Value(Type::getMetadataTy(C), Value::NamedMDNodeVal), Parent(0) {
329 Operands = new SmallVector<WeakVH, 4>();
331 SmallVector<WeakVH, 4> &Node = getNMDOps(Operands);
332 for (unsigned i = 0; i != NumMDs; ++i)
333 Node.push_back(WeakVH(MDs[i]));
336 ParentModule->getNamedMDList().push_back(this);
339 NamedMDNode *NamedMDNode::Create(const NamedMDNode *NMD, Module *M) {
340 assert(NMD && "Invalid source NamedMDNode!");
341 SmallVector<MDNode *, 4> Elems;
342 Elems.reserve(NMD->getNumOperands());
344 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i)
345 Elems.push_back(NMD->getOperand(i));
346 return new NamedMDNode(NMD->getContext(), NMD->getName().data(),
347 Elems.data(), Elems.size(), M);
350 NamedMDNode::~NamedMDNode() {
352 delete &getNMDOps(Operands);
355 /// getNumOperands - Return number of NamedMDNode operands.
356 unsigned NamedMDNode::getNumOperands() const {
357 return (unsigned)getNMDOps(Operands).size();
360 /// getOperand - Return specified operand.
361 MDNode *NamedMDNode::getOperand(unsigned i) const {
362 assert(i < getNumOperands() && "Invalid Operand number!");
363 return dyn_cast_or_null<MDNode>(getNMDOps(Operands)[i]);
366 /// addOperand - Add metadata Operand.
367 void NamedMDNode::addOperand(MDNode *M) {
368 getNMDOps(Operands).push_back(WeakVH(M));
371 /// eraseFromParent - Drop all references and remove the node from parent
373 void NamedMDNode::eraseFromParent() {
374 getParent()->getNamedMDList().erase(this);
377 /// dropAllReferences - Remove all uses and clear node vector.
378 void NamedMDNode::dropAllReferences() {
379 getNMDOps(Operands).clear();
382 /// setName - Set the name of this named metadata.
383 void NamedMDNode::setName(const Twine &NewName) {
384 assert (!NewName.isTriviallyEmpty() && "Invalid named metadata name!");
386 SmallString<256> NameData;
387 StringRef NameRef = NewName.toStringRef(NameData);
389 // Name isn't changing?
390 if (getName() == NameRef)
393 Name = NameRef.str();
395 Parent->getMDSymbolTable().insert(NameRef, this);
398 /// getName - Return a constant reference to this named metadata's name.
399 StringRef NamedMDNode::getName() const {
400 return StringRef(Name);
403 //===----------------------------------------------------------------------===//
404 // LLVMContext MDKind naming implementation.
408 /// isValidName - Return true if Name is a valid custom metadata handler name.
409 static bool isValidName(StringRef MDName) {
413 if (!isalpha(MDName[0]))
416 for (StringRef::iterator I = MDName.begin() + 1, E = MDName.end(); I != E;
418 if (!isalnum(*I) && *I != '_' && *I != '-' && *I != '.')
425 /// getMDKindID - Return a unique non-zero ID for the specified metadata kind.
426 unsigned LLVMContext::getMDKindID(StringRef Name) const {
427 assert(isValidName(Name) && "Invalid MDNode name");
429 unsigned &Entry = pImpl->CustomMDKindNames[Name];
431 // If this is new, assign it its ID.
432 if (Entry == 0) Entry = pImpl->CustomMDKindNames.size();
436 /// getHandlerNames - Populate client supplied smallvector using custome
437 /// metadata name and ID.
438 void LLVMContext::getMDKindNames(SmallVectorImpl<StringRef> &Names) const {
439 Names.resize(pImpl->CustomMDKindNames.size()+1);
441 for (StringMap<unsigned>::const_iterator I = pImpl->CustomMDKindNames.begin(),
442 E = pImpl->CustomMDKindNames.end(); I != E; ++I)
443 // MD Handlers are numbered from 1.
444 Names[I->second] = I->first();
447 //===----------------------------------------------------------------------===//
448 // Instruction Metadata method implementations.
451 void Instruction::setMetadata(const char *Kind, MDNode *Node) {
452 if (Node == 0 && !hasMetadata()) return;
453 setMetadata(getContext().getMDKindID(Kind), Node);
456 MDNode *Instruction::getMetadataImpl(const char *Kind) const {
457 return getMetadataImpl(getContext().getMDKindID(Kind));
460 /// setMetadata - Set the metadata of of the specified kind to the specified
461 /// node. This updates/replaces metadata if already present, or removes it if
463 void Instruction::setMetadata(unsigned KindID, MDNode *Node) {
464 if (Node == 0 && !hasMetadata()) return;
466 // Handle the case when we're adding/updating metadata on an instruction.
468 LLVMContextImpl::MDMapTy &Info = getContext().pImpl->MetadataStore[this];
469 assert(!Info.empty() == hasMetadata() && "HasMetadata bit is wonked");
471 setHasMetadata(true);
473 // Handle replacement of an existing value.
474 for (unsigned i = 0, e = Info.size(); i != e; ++i)
475 if (Info[i].first == KindID) {
476 Info[i].second = Node;
481 // No replacement, just add it to the list.
482 Info.push_back(std::make_pair(KindID, Node));
486 // Otherwise, we're removing metadata from an instruction.
487 assert(hasMetadata() && getContext().pImpl->MetadataStore.count(this) &&
488 "HasMetadata bit out of date!");
489 LLVMContextImpl::MDMapTy &Info = getContext().pImpl->MetadataStore[this];
491 // Common case is removing the only entry.
492 if (Info.size() == 1 && Info[0].first == KindID) {
493 getContext().pImpl->MetadataStore.erase(this);
494 setHasMetadata(false);
498 // Handle replacement of an existing value.
499 for (unsigned i = 0, e = Info.size(); i != e; ++i)
500 if (Info[i].first == KindID) {
501 Info[i] = Info.back();
503 assert(!Info.empty() && "Removing last entry should be handled above");
506 // Otherwise, removing an entry that doesn't exist on the instruction.
509 MDNode *Instruction::getMetadataImpl(unsigned KindID) const {
510 LLVMContextImpl::MDMapTy &Info = getContext().pImpl->MetadataStore[this];
511 assert(hasMetadata() && !Info.empty() && "Shouldn't have called this");
513 for (LLVMContextImpl::MDMapTy::iterator I = Info.begin(), E = Info.end();
515 if (I->first == KindID)
520 void Instruction::getAllMetadataImpl(SmallVectorImpl<std::pair<unsigned,
521 MDNode*> > &Result)const {
522 assert(hasMetadata() && getContext().pImpl->MetadataStore.count(this) &&
523 "Shouldn't have called this");
524 const LLVMContextImpl::MDMapTy &Info =
525 getContext().pImpl->MetadataStore.find(this)->second;
526 assert(!Info.empty() && "Shouldn't have called this");
529 Result.append(Info.begin(), Info.end());
531 // Sort the resulting array so it is stable.
532 if (Result.size() > 1)
533 array_pod_sort(Result.begin(), Result.end());
536 /// removeAllMetadata - Remove all metadata from this instruction.
537 void Instruction::removeAllMetadata() {
538 assert(hasMetadata() && "Caller should check");
539 getContext().pImpl->MetadataStore.erase(this);
540 setHasMetadata(false);