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();
124 // destroy - Delete this node. Only when there are no uses.
125 void MDNode::destroy() {
126 setValueSubclassData(getSubclassDataFromValue() | DestroyFlag);
127 // Placement delete, the free the memory.
132 MDNode *MDNode::getMDNode(LLVMContext &Context, Value *const *Vals,
133 unsigned NumVals, FunctionLocalness FL) {
134 LLVMContextImpl *pImpl = Context.pImpl;
136 for (unsigned i = 0; i != NumVals; ++i)
137 ID.AddPointer(Vals[i]);
140 MDNode *N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint);
142 bool isFunctionLocal = false;
145 for (unsigned i = 0; i != NumVals; ++i) {
148 if (isa<Instruction>(V) || isa<Argument>(V) || isa<BasicBlock>(V) ||
149 (isa<MDNode>(V) && cast<MDNode>(V)->isFunctionLocal())) {
150 isFunctionLocal = true;
156 isFunctionLocal = false;
159 isFunctionLocal = true;
163 // Coallocate space for the node and Operands together, then placement new.
164 void *Ptr = malloc(sizeof(MDNode)+NumVals*sizeof(MDNodeOperand));
165 N = new (Ptr) MDNode(Context, Vals, NumVals, isFunctionLocal);
167 // InsertPoint will have been set by the FindNodeOrInsertPos call.
168 pImpl->MDNodeSet.InsertNode(N, InsertPoint);
173 MDNode *MDNode::get(LLVMContext &Context, Value*const* Vals, unsigned NumVals) {
174 return getMDNode(Context, Vals, NumVals, FL_Unknown);
177 MDNode *MDNode::getWhenValsUnresolved(LLVMContext &Context, Value*const* Vals,
178 unsigned NumVals, bool isFunctionLocal) {
179 return getMDNode(Context, Vals, NumVals, isFunctionLocal ? FL_Yes : FL_No);
182 /// getOperand - Return specified operand.
183 Value *MDNode::getOperand(unsigned i) const {
184 return *getOperandPtr(const_cast<MDNode*>(this), i);
187 void MDNode::Profile(FoldingSetNodeID &ID) const {
188 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
189 ID.AddPointer(getOperand(i));
193 // Replace value from this node's operand list.
194 void MDNode::replaceOperand(MDNodeOperand *Op, Value *To) {
200 // Update the operand.
203 // If this node is already not being uniqued (because one of the operands
204 // already went to null), then there is nothing else to do here.
205 if (isNotUniqued()) return;
207 LLVMContextImpl *pImpl = getType()->getContext().pImpl;
209 // Remove "this" from the context map. FoldingSet doesn't have to reprofile
210 // this node to remove it, so we don't care what state the operands are in.
211 pImpl->MDNodeSet.RemoveNode(this);
213 // If we are dropping an argument to null, we choose to not unique the MDNode
214 // anymore. This commonly occurs during destruction, and uniquing these
215 // brings little reuse.
221 // Now that the node is out of the folding set, get ready to reinsert it.
222 // First, check to see if another node with the same operands already exists
223 // in the set. If it doesn't exist, this returns the position to insert it.
227 MDNode *N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint);
230 N->replaceAllUsesWith(this);
232 N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint);
233 assert(N == 0 && "shouldn't be in the map now!"); (void)N;
236 // InsertPoint will have been set by the FindNodeOrInsertPos call.
237 pImpl->MDNodeSet.InsertNode(this, InsertPoint);
240 //===----------------------------------------------------------------------===//
241 // NamedMDNode implementation.
245 // SymbolTableListTraits specialization for MDSymbolTable.
246 void ilist_traits<NamedMDNode>
247 ::addNodeToList(NamedMDNode *N) {
248 assert(N->getParent() == 0 && "Value already in a container!!");
249 Module *Owner = getListOwner();
251 MDSymbolTable &ST = Owner->getMDSymbolTable();
252 ST.insert(N->getName(), N);
255 void ilist_traits<NamedMDNode>::removeNodeFromList(NamedMDNode *N) {
257 Module *Owner = getListOwner();
258 MDSymbolTable &ST = Owner->getMDSymbolTable();
259 ST.remove(N->getName());
263 static SmallVector<WeakVH, 4> &getNMDOps(void *Operands) {
264 return *(SmallVector<WeakVH, 4>*)Operands;
267 NamedMDNode::NamedMDNode(LLVMContext &C, const Twine &N,
269 unsigned NumMDs, Module *ParentModule)
270 : Value(Type::getMetadataTy(C), Value::NamedMDNodeVal), Parent(0) {
272 Operands = new SmallVector<WeakVH, 4>();
274 SmallVector<WeakVH, 4> &Node = getNMDOps(Operands);
275 for (unsigned i = 0; i != NumMDs; ++i)
276 Node.push_back(WeakVH(MDs[i]));
279 ParentModule->getNamedMDList().push_back(this);
282 NamedMDNode *NamedMDNode::Create(const NamedMDNode *NMD, Module *M) {
283 assert(NMD && "Invalid source NamedMDNode!");
284 SmallVector<MDNode *, 4> Elems;
285 Elems.reserve(NMD->getNumOperands());
287 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i)
288 Elems.push_back(NMD->getOperand(i));
289 return new NamedMDNode(NMD->getContext(), NMD->getName().data(),
290 Elems.data(), Elems.size(), M);
293 NamedMDNode::~NamedMDNode() {
295 delete &getNMDOps(Operands);
298 /// getNumOperands - Return number of NamedMDNode operands.
299 unsigned NamedMDNode::getNumOperands() const {
300 return (unsigned)getNMDOps(Operands).size();
303 /// getOperand - Return specified operand.
304 MDNode *NamedMDNode::getOperand(unsigned i) const {
305 assert(i < getNumOperands() && "Invalid Operand number!");
306 return dyn_cast_or_null<MDNode>(getNMDOps(Operands)[i]);
309 /// addOperand - Add metadata Operand.
310 void NamedMDNode::addOperand(MDNode *M) {
311 getNMDOps(Operands).push_back(WeakVH(M));
314 /// eraseFromParent - Drop all references and remove the node from parent
316 void NamedMDNode::eraseFromParent() {
317 getParent()->getNamedMDList().erase(this);
320 /// dropAllReferences - Remove all uses and clear node vector.
321 void NamedMDNode::dropAllReferences() {
322 getNMDOps(Operands).clear();
325 /// setName - Set the name of this named metadata.
326 void NamedMDNode::setName(const Twine &NewName) {
327 assert (!NewName.isTriviallyEmpty() && "Invalid named metadata name!");
329 SmallString<256> NameData;
330 StringRef NameRef = NewName.toStringRef(NameData);
332 // Name isn't changing?
333 if (getName() == NameRef)
336 Name = NameRef.str();
338 Parent->getMDSymbolTable().insert(NameRef, this);
341 /// getName - Return a constant reference to this named metadata's name.
342 StringRef NamedMDNode::getName() const {
343 return StringRef(Name);
346 //===----------------------------------------------------------------------===//
347 // LLVMContext MDKind naming implementation.
351 /// isValidName - Return true if Name is a valid custom metadata handler name.
352 static bool isValidName(StringRef MDName) {
356 if (!isalpha(MDName[0]))
359 for (StringRef::iterator I = MDName.begin() + 1, E = MDName.end(); I != E;
361 if (!isalnum(*I) && *I != '_' && *I != '-' && *I != '.')
368 /// getMDKindID - Return a unique non-zero ID for the specified metadata kind.
369 unsigned LLVMContext::getMDKindID(StringRef Name) const {
370 assert(isValidName(Name) && "Invalid MDNode name");
372 unsigned &Entry = pImpl->CustomMDKindNames[Name];
374 // If this is new, assign it its ID.
375 if (Entry == 0) Entry = pImpl->CustomMDKindNames.size();
379 /// getHandlerNames - Populate client supplied smallvector using custome
380 /// metadata name and ID.
381 void LLVMContext::getMDKindNames(SmallVectorImpl<StringRef> &Names) const {
382 Names.resize(pImpl->CustomMDKindNames.size()+1);
384 for (StringMap<unsigned>::const_iterator I = pImpl->CustomMDKindNames.begin(),
385 E = pImpl->CustomMDKindNames.end(); I != E; ++I)
386 // MD Handlers are numbered from 1.
387 Names[I->second] = I->first();
390 //===----------------------------------------------------------------------===//
391 // Instruction Metadata method implementations.
394 void Instruction::setMetadata(const char *Kind, MDNode *Node) {
395 if (Node == 0 && !hasMetadata()) return;
396 setMetadata(getContext().getMDKindID(Kind), Node);
399 MDNode *Instruction::getMetadataImpl(const char *Kind) const {
400 return getMetadataImpl(getContext().getMDKindID(Kind));
403 /// setMetadata - Set the metadata of of the specified kind to the specified
404 /// node. This updates/replaces metadata if already present, or removes it if
406 void Instruction::setMetadata(unsigned KindID, MDNode *Node) {
407 if (Node == 0 && !hasMetadata()) return;
409 // Handle the case when we're adding/updating metadata on an instruction.
411 LLVMContextImpl::MDMapTy &Info = getContext().pImpl->MetadataStore[this];
412 assert(!Info.empty() == hasMetadata() && "HasMetadata bit is wonked");
414 setHasMetadata(true);
416 // Handle replacement of an existing value.
417 for (unsigned i = 0, e = Info.size(); i != e; ++i)
418 if (Info[i].first == KindID) {
419 Info[i].second = Node;
424 // No replacement, just add it to the list.
425 Info.push_back(std::make_pair(KindID, Node));
429 // Otherwise, we're removing metadata from an instruction.
430 assert(hasMetadata() && getContext().pImpl->MetadataStore.count(this) &&
431 "HasMetadata bit out of date!");
432 LLVMContextImpl::MDMapTy &Info = getContext().pImpl->MetadataStore[this];
434 // Common case is removing the only entry.
435 if (Info.size() == 1 && Info[0].first == KindID) {
436 getContext().pImpl->MetadataStore.erase(this);
437 setHasMetadata(false);
441 // Handle replacement of an existing value.
442 for (unsigned i = 0, e = Info.size(); i != e; ++i)
443 if (Info[i].first == KindID) {
444 Info[i] = Info.back();
446 assert(!Info.empty() && "Removing last entry should be handled above");
449 // Otherwise, removing an entry that doesn't exist on the instruction.
452 MDNode *Instruction::getMetadataImpl(unsigned KindID) const {
453 LLVMContextImpl::MDMapTy &Info = getContext().pImpl->MetadataStore[this];
454 assert(hasMetadata() && !Info.empty() && "Shouldn't have called this");
456 for (LLVMContextImpl::MDMapTy::iterator I = Info.begin(), E = Info.end();
458 if (I->first == KindID)
463 void Instruction::getAllMetadataImpl(SmallVectorImpl<std::pair<unsigned,
464 MDNode*> > &Result)const {
465 assert(hasMetadata() && getContext().pImpl->MetadataStore.count(this) &&
466 "Shouldn't have called this");
467 const LLVMContextImpl::MDMapTy &Info =
468 getContext().pImpl->MetadataStore.find(this)->second;
469 assert(!Info.empty() && "Shouldn't have called this");
472 Result.append(Info.begin(), Info.end());
474 // Sort the resulting array so it is stable.
475 if (Result.size() > 1)
476 array_pod_sort(Result.begin(), Result.end());
479 /// removeAllMetadata - Remove all metadata from this instruction.
480 void Instruction::removeAllMetadata() {
481 assert(hasMetadata() && "Caller should check");
482 getContext().pImpl->MetadataStore.erase(this);
483 setHasMetadata(false);