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 "SymbolTableListTraitsImpl.h"
22 #include "llvm/Support/ValueHandle.h"
25 //===----------------------------------------------------------------------===//
26 // MDString implementation.
29 MDString::MDString(LLVMContext &C, StringRef S)
30 : MetadataBase(Type::getMetadataTy(C), Value::MDStringVal), Str(S) {}
32 MDString *MDString::get(LLVMContext &Context, StringRef Str) {
33 LLVMContextImpl *pImpl = Context.pImpl;
34 StringMapEntry<MDString *> &Entry =
35 pImpl->MDStringCache.GetOrCreateValue(Str);
36 MDString *&S = Entry.getValue();
37 if (!S) S = new MDString(Context, Entry.getKey());
41 MDString *MDString::get(LLVMContext &Context, const char *Str) {
42 LLVMContextImpl *pImpl = Context.pImpl;
43 StringMapEntry<MDString *> &Entry =
44 pImpl->MDStringCache.GetOrCreateValue(Str ? StringRef(Str) : StringRef());
45 MDString *&S = Entry.getValue();
46 if (!S) S = new MDString(Context, Entry.getKey());
50 //===----------------------------------------------------------------------===//
51 // MDNodeElement implementation.
54 // Use CallbackVH to hold MDNode elements.
56 class MDNodeElement : public CallbackVH {
60 MDNodeElement(Value *V, MDNode *P) : CallbackVH(V), Parent(P) {}
63 void set(Value *V, MDNode *P) {
68 virtual void deleted();
69 virtual void allUsesReplacedWith(Value *NV);
71 } // end namespace llvm.
74 void MDNodeElement::deleted() {
75 Parent->replaceElement(this, 0);
78 void MDNodeElement::allUsesReplacedWith(Value *NV) {
79 Parent->replaceElement(this, NV);
84 //===----------------------------------------------------------------------===//
85 // MDNode implementation.
88 /// ~MDNode - Destroy MDNode.
90 if (!isNotUniqued()) {
91 LLVMContextImpl *pImpl = getType()->getContext().pImpl;
92 pImpl->MDNodeSet.RemoveNode(this);
98 MDNode::MDNode(LLVMContext &C, Value *const *Vals, unsigned NumVals,
100 : MetadataBase(Type::getMetadataTy(C), Value::MDNodeVal) {
101 NumOperands = NumVals;
102 // FIXME: Coallocate the operand list. These have fixed arity.
103 Operands = new MDNodeElement[NumOperands];
105 for (unsigned i = 0; i != NumVals; ++i)
106 Operands[i].set(Vals[i], this);
109 setValueSubclassData(getSubclassDataFromValue() | FunctionLocalBit);
112 MDNode *MDNode::get(LLVMContext &Context, Value*const* Vals, unsigned NumVals,
113 bool isFunctionLocal) {
114 LLVMContextImpl *pImpl = Context.pImpl;
116 for (unsigned i = 0; i != NumVals; ++i)
117 ID.AddPointer(Vals[i]);
120 MDNode *N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint);
122 // InsertPoint will have been set by the FindNodeOrInsertPos call.
123 N = new MDNode(Context, Vals, NumVals, isFunctionLocal);
124 pImpl->MDNodeSet.InsertNode(N, InsertPoint);
129 void MDNode::Profile(FoldingSetNodeID &ID) const {
130 for (unsigned i = 0, e = getNumElements(); i != e; ++i)
131 ID.AddPointer(getElement(i));
132 // HASH TABLE COLLISIONS?
133 // DO NOT REINSERT AFTER AN OPERAND DROPS TO NULL!
137 /// getElement - Return specified element.
138 Value *MDNode::getElement(unsigned i) const {
139 assert(i < getNumElements() && "Invalid element number!");
145 // Replace value from this node's element list.
146 void MDNode::replaceElement(MDNodeElement *Op, Value *To) {
152 // Update the operand.
155 // If this node is already not being uniqued (because one of the operands
156 // already went to null), then there is nothing else to do here.
157 if (isNotUniqued()) return;
159 LLVMContextImpl *pImpl = getType()->getContext().pImpl;
161 // Remove "this" from the context map. FoldingSet doesn't have to reprofile
162 // this node to remove it, so we don't care what state the operands are in.
163 pImpl->MDNodeSet.RemoveNode(this);
165 // If we are dropping an argument to null, we choose to not unique the MDNode
166 // anymore. This commonly occurs during destruction, and uniquing these
167 // brings little reuse.
173 // Now that the node is out of the folding set, get ready to reinsert it.
174 // First, check to see if another node with the same operands already exists
175 // in the set. If it doesn't exist, this returns the position to insert it.
179 MDNode *N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint);
183 // If it already exists in the set, we don't reinsert it, we just claim it
186 N->replaceAllUsesWith(this);
188 N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint);
189 assert(N == 0 && "shouldn't be in the map now!"); (void)N;
192 // InsertPoint will have been set by the FindNodeOrInsertPos call.
193 pImpl->MDNodeSet.InsertNode(this, InsertPoint);
196 //===----------------------------------------------------------------------===//
197 // NamedMDNode implementation.
199 static SmallVector<TrackingVH<MetadataBase>, 4> &getNMDOps(void *Operands) {
200 return *(SmallVector<TrackingVH<MetadataBase>, 4>*)Operands;
203 NamedMDNode::NamedMDNode(LLVMContext &C, const Twine &N,
204 MetadataBase *const *MDs,
205 unsigned NumMDs, Module *ParentModule)
206 : MetadataBase(Type::getMetadataTy(C), Value::NamedMDNodeVal), Parent(0) {
209 Operands = new SmallVector<TrackingVH<MetadataBase>, 4>();
211 SmallVector<TrackingVH<MetadataBase>, 4> &Node = getNMDOps(Operands);
212 for (unsigned i = 0; i != NumMDs; ++i)
213 Node.push_back(TrackingVH<MetadataBase>(MDs[i]));
216 ParentModule->getNamedMDList().push_back(this);
219 NamedMDNode *NamedMDNode::Create(const NamedMDNode *NMD, Module *M) {
220 assert(NMD && "Invalid source NamedMDNode!");
221 SmallVector<MetadataBase *, 4> Elems;
222 Elems.reserve(NMD->getNumElements());
224 for (unsigned i = 0, e = NMD->getNumElements(); i != e; ++i)
225 Elems.push_back(NMD->getElement(i));
226 return new NamedMDNode(NMD->getContext(), NMD->getName().data(),
227 Elems.data(), Elems.size(), M);
230 NamedMDNode::~NamedMDNode() {
232 delete &getNMDOps(Operands);
235 /// getNumElements - Return number of NamedMDNode elements.
236 unsigned NamedMDNode::getNumElements() const {
237 return (unsigned)getNMDOps(Operands).size();
240 /// getElement - Return specified element.
241 MetadataBase *NamedMDNode::getElement(unsigned i) const {
242 assert(i < getNumElements() && "Invalid element number!");
243 return getNMDOps(Operands)[i];
246 /// addElement - Add metadata element.
247 void NamedMDNode::addElement(MetadataBase *M) {
248 getNMDOps(Operands).push_back(TrackingVH<MetadataBase>(M));
251 /// eraseFromParent - Drop all references and remove the node from parent
253 void NamedMDNode::eraseFromParent() {
254 getParent()->getNamedMDList().erase(this);
257 /// dropAllReferences - Remove all uses and clear node vector.
258 void NamedMDNode::dropAllReferences() {
259 getNMDOps(Operands).clear();
263 //===----------------------------------------------------------------------===//
264 // MetadataContext implementation.
268 /// isValidName - Return true if Name is a valid custom metadata handler name.
269 static bool isValidName(StringRef MDName) {
273 if (!isalpha(MDName[0]))
276 for (StringRef::iterator I = MDName.begin() + 1, E = MDName.end(); I != E;
278 if (!isalnum(*I) && *I != '_' && *I != '-' && *I != '.')
285 /// getMDKindID - Return a unique non-zero ID for the specified metadata kind.
286 unsigned LLVMContext::getMDKindID(StringRef Name) const {
287 assert(isValidName(Name) && "Invalid MDNode name");
289 unsigned &Entry = pImpl->CustomMDKindNames[Name];
291 // If this is new, assign it its ID.
292 if (Entry == 0) Entry = pImpl->CustomMDKindNames.size();
296 /// getHandlerNames - Populate client supplied smallvector using custome
297 /// metadata name and ID.
298 void LLVMContext::getMDKindNames(SmallVectorImpl<StringRef> &Names) const {
299 Names.resize(pImpl->CustomMDKindNames.size()+1);
301 for (StringMap<unsigned>::const_iterator I = pImpl->CustomMDKindNames.begin(),
302 E = pImpl->CustomMDKindNames.end(); I != E; ++I)
303 // MD Handlers are numbered from 1.
304 Names[I->second] = I->first();
307 //===----------------------------------------------------------------------===//
308 // Instruction Metadata method implementations.
311 void Instruction::setMetadata(const char *Kind, MDNode *Node) {
312 if (Node == 0 && !hasMetadata()) return;
313 setMetadata(getContext().getMDKindID(Kind), Node);
316 MDNode *Instruction::getMetadataImpl(const char *Kind) const {
317 return getMetadataImpl(getContext().getMDKindID(Kind));
320 /// setMetadata - Set the metadata of of the specified kind to the specified
321 /// node. This updates/replaces metadata if already present, or removes it if
323 void Instruction::setMetadata(unsigned KindID, MDNode *Node) {
324 if (Node == 0 && !hasMetadata()) return;
326 // Handle the case when we're adding/updating metadata on an instruction.
328 LLVMContextImpl::MDMapTy &Info = getContext().pImpl->MetadataStore[this];
329 assert(!Info.empty() == hasMetadata() && "HasMetadata bit is wonked");
331 setHasMetadata(true);
333 // Handle replacement of an existing value.
334 for (unsigned i = 0, e = Info.size(); i != e; ++i)
335 if (Info[i].first == KindID) {
336 Info[i].second = Node;
341 // No replacement, just add it to the list.
342 Info.push_back(std::make_pair(KindID, Node));
346 // Otherwise, we're removing metadata from an instruction.
347 assert(hasMetadata() && getContext().pImpl->MetadataStore.count(this) &&
348 "HasMetadata bit out of date!");
349 LLVMContextImpl::MDMapTy &Info = getContext().pImpl->MetadataStore[this];
351 // Common case is removing the only entry.
352 if (Info.size() == 1 && Info[0].first == KindID) {
353 getContext().pImpl->MetadataStore.erase(this);
354 setHasMetadata(false);
358 // Handle replacement of an existing value.
359 for (unsigned i = 0, e = Info.size(); i != e; ++i)
360 if (Info[i].first == KindID) {
361 Info[i] = Info.back();
363 assert(!Info.empty() && "Removing last entry should be handled above");
366 // Otherwise, removing an entry that doesn't exist on the instruction.
369 MDNode *Instruction::getMetadataImpl(unsigned KindID) const {
370 LLVMContextImpl::MDMapTy &Info = getContext().pImpl->MetadataStore[this];
371 assert(hasMetadata() && !Info.empty() && "Shouldn't have called this");
373 for (LLVMContextImpl::MDMapTy::iterator I = Info.begin(), E = Info.end();
375 if (I->first == KindID)
380 void Instruction::getAllMetadataImpl(SmallVectorImpl<std::pair<unsigned,
381 MDNode*> > &Result)const {
382 assert(hasMetadata() && getContext().pImpl->MetadataStore.count(this) &&
383 "Shouldn't have called this");
384 const LLVMContextImpl::MDMapTy &Info =
385 getContext().pImpl->MetadataStore.find(this)->second;
386 assert(!Info.empty() && "Shouldn't have called this");
389 Result.append(Info.begin(), Info.end());
391 // Sort the resulting array so it is stable.
392 if (Result.size() > 1)
393 array_pod_sort(Result.begin(), Result.end());
396 /// removeAllMetadata - Remove all metadata from this instruction.
397 void Instruction::removeAllMetadata() {
398 assert(hasMetadata() && "Caller should check");
399 getContext().pImpl->MetadataStore.erase(this);
400 setHasMetadata(false);