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 // MDNodeOperand implementation.
54 // Use CallbackVH to hold MDNode operands.
56 class MDNodeOperand : public CallbackVH {
59 MDNodeOperand(Value *V, MDNode *P) : CallbackVH(V), Parent(P) {}
66 virtual void deleted();
67 virtual void allUsesReplacedWith(Value *NV);
69 } // end namespace llvm.
72 void MDNodeOperand::deleted() {
73 Parent->replaceOperand(this, 0);
76 void MDNodeOperand::allUsesReplacedWith(Value *NV) {
77 Parent->replaceOperand(this, NV);
82 //===----------------------------------------------------------------------===//
83 // MDNode implementation.
86 /// getOperandPtr - Helper function to get the MDNodeOperand's coallocated on
87 /// the end of the MDNode.
88 static MDNodeOperand *getOperandPtr(MDNode *N, unsigned Op) {
89 assert(Op < N->getNumOperands() && "Invalid operand number");
90 return reinterpret_cast<MDNodeOperand*>(N+1)+Op;
93 MDNode::MDNode(LLVMContext &C, Value *const *Vals, unsigned NumVals,
95 : MetadataBase(Type::getMetadataTy(C), Value::MDNodeVal) {
96 NumOperands = NumVals;
99 setValueSubclassData(getSubclassDataFromValue() | FunctionLocalBit);
101 // Initialize the operand list, which is co-allocated on the end of the node.
102 for (MDNodeOperand *Op = getOperandPtr(this, 0), *E = Op+NumOperands;
103 Op != E; ++Op, ++Vals)
104 new (Op) MDNodeOperand(*Vals, this);
108 /// ~MDNode - Destroy MDNode.
110 assert((getSubclassDataFromValue() & DestroyFlag) != 0 &&
111 "Not being destroyed through destroy()?");
112 if (!isNotUniqued()) {
113 LLVMContextImpl *pImpl = getType()->getContext().pImpl;
114 pImpl->MDNodeSet.RemoveNode(this);
117 // Destroy the operands.
118 for (MDNodeOperand *Op = getOperandPtr(this, 0), *E = Op+NumOperands;
120 Op->~MDNodeOperand();
123 // destroy - Delete this node. Only when there are no uses.
124 void MDNode::destroy() {
125 setValueSubclassData(getSubclassDataFromValue() | DestroyFlag);
126 // Placement delete, the free the memory.
132 MDNode *MDNode::get(LLVMContext &Context, Value*const* Vals, unsigned NumVals,
133 bool isFunctionLocal) {
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 // Coallocate space for the node and Operands together, then placement new.
143 void *Ptr = malloc(sizeof(MDNode)+NumVals*sizeof(MDNodeOperand));
144 N = new (Ptr) MDNode(Context, Vals, NumVals, isFunctionLocal);
146 // InsertPoint will have been set by the FindNodeOrInsertPos call.
147 pImpl->MDNodeSet.InsertNode(N, InsertPoint);
152 /// getOperand - Return specified operand.
153 Value *MDNode::getOperand(unsigned i) const {
154 return *getOperandPtr(const_cast<MDNode*>(this), i);
157 void MDNode::Profile(FoldingSetNodeID &ID) const {
158 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
159 ID.AddPointer(getOperand(i));
163 // Replace value from this node's operand list.
164 void MDNode::replaceOperand(MDNodeOperand *Op, Value *To) {
170 // Update the operand.
173 // If this node is already not being uniqued (because one of the operands
174 // already went to null), then there is nothing else to do here.
175 if (isNotUniqued()) return;
177 LLVMContextImpl *pImpl = getType()->getContext().pImpl;
179 // Remove "this" from the context map. FoldingSet doesn't have to reprofile
180 // this node to remove it, so we don't care what state the operands are in.
181 pImpl->MDNodeSet.RemoveNode(this);
183 // If we are dropping an argument to null, we choose to not unique the MDNode
184 // anymore. This commonly occurs during destruction, and uniquing these
185 // brings little reuse.
191 // Now that the node is out of the folding set, get ready to reinsert it.
192 // First, check to see if another node with the same operands already exists
193 // in the set. If it doesn't exist, this returns the position to insert it.
197 MDNode *N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint);
200 N->replaceAllUsesWith(this);
202 N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint);
203 assert(N == 0 && "shouldn't be in the map now!"); (void)N;
206 // InsertPoint will have been set by the FindNodeOrInsertPos call.
207 pImpl->MDNodeSet.InsertNode(this, InsertPoint);
210 //===----------------------------------------------------------------------===//
211 // NamedMDNode implementation.
213 static SmallVector<WeakVH, 4> &getNMDOps(void *Operands) {
214 return *(SmallVector<WeakVH, 4>*)Operands;
217 NamedMDNode::NamedMDNode(LLVMContext &C, StringRef N,
219 unsigned NumMDs, Module *ParentModule)
220 : MetadataBase(Type::getMetadataTy(C), Value::NamedMDNodeVal), Parent(0) {
222 Operands = new SmallVector<WeakVH, 4>();
224 SmallVector<WeakVH, 4> &Node = getNMDOps(Operands);
225 for (unsigned i = 0; i != NumMDs; ++i)
226 Node.push_back(WeakVH(MDs[i]));
229 ParentModule->getNamedMDList().push_back(this);
230 ParentModule->addMDNodeName(N, this);
234 NamedMDNode *NamedMDNode::Create(const NamedMDNode *NMD, Module *M) {
235 assert(NMD && "Invalid source NamedMDNode!");
236 SmallVector<MDNode *, 4> Elems;
237 Elems.reserve(NMD->getNumOperands());
239 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i)
240 Elems.push_back(NMD->getOperand(i));
241 return new NamedMDNode(NMD->getContext(), NMD->getName().data(),
242 Elems.data(), Elems.size(), M);
245 NamedMDNode::~NamedMDNode() {
247 delete &getNMDOps(Operands);
250 /// getNumOperands - Return number of NamedMDNode operands.
251 unsigned NamedMDNode::getNumOperands() const {
252 return (unsigned)getNMDOps(Operands).size();
255 /// getOperand - Return specified operand.
256 MDNode *NamedMDNode::getOperand(unsigned i) const {
257 assert(i < getNumOperands() && "Invalid Operand number!");
258 return dyn_cast_or_null<MDNode>(getNMDOps(Operands)[i]);
261 /// addOperand - Add metadata Operand.
262 void NamedMDNode::addOperand(MDNode *M) {
263 getNMDOps(Operands).push_back(WeakVH(M));
266 /// eraseFromParent - Drop all references and remove the node from parent
268 void NamedMDNode::eraseFromParent() {
269 getParent()->getMDSymbolTable().remove(getName());
270 getParent()->getNamedMDList().erase(this);
273 /// dropAllReferences - Remove all uses and clear node vector.
274 void NamedMDNode::dropAllReferences() {
275 getNMDOps(Operands).clear();
278 /// setName - Set the name of this named metadata.
279 void NamedMDNode::setName(StringRef N) {
284 /// getName - Return a constant reference to this named metadata's name.
285 StringRef NamedMDNode::getName() const {
286 return StringRef(Name);
289 //===----------------------------------------------------------------------===//
290 // LLVMContext MDKind naming implementation.
294 /// isValidName - Return true if Name is a valid custom metadata handler name.
295 static bool isValidName(StringRef MDName) {
299 if (!isalpha(MDName[0]))
302 for (StringRef::iterator I = MDName.begin() + 1, E = MDName.end(); I != E;
304 if (!isalnum(*I) && *I != '_' && *I != '-' && *I != '.')
311 /// getMDKindID - Return a unique non-zero ID for the specified metadata kind.
312 unsigned LLVMContext::getMDKindID(StringRef Name) const {
313 assert(isValidName(Name) && "Invalid MDNode name");
315 unsigned &Entry = pImpl->CustomMDKindNames[Name];
317 // If this is new, assign it its ID.
318 if (Entry == 0) Entry = pImpl->CustomMDKindNames.size();
322 /// getHandlerNames - Populate client supplied smallvector using custome
323 /// metadata name and ID.
324 void LLVMContext::getMDKindNames(SmallVectorImpl<StringRef> &Names) const {
325 Names.resize(pImpl->CustomMDKindNames.size()+1);
327 for (StringMap<unsigned>::const_iterator I = pImpl->CustomMDKindNames.begin(),
328 E = pImpl->CustomMDKindNames.end(); I != E; ++I)
329 // MD Handlers are numbered from 1.
330 Names[I->second] = I->first();
333 //===----------------------------------------------------------------------===//
334 // Instruction Metadata method implementations.
337 void Instruction::setMetadata(const char *Kind, MDNode *Node) {
338 if (Node == 0 && !hasMetadata()) return;
339 setMetadata(getContext().getMDKindID(Kind), Node);
342 MDNode *Instruction::getMetadataImpl(const char *Kind) const {
343 return getMetadataImpl(getContext().getMDKindID(Kind));
346 /// setMetadata - Set the metadata of of the specified kind to the specified
347 /// node. This updates/replaces metadata if already present, or removes it if
349 void Instruction::setMetadata(unsigned KindID, MDNode *Node) {
350 if (Node == 0 && !hasMetadata()) return;
352 // Handle the case when we're adding/updating metadata on an instruction.
354 LLVMContextImpl::MDMapTy &Info = getContext().pImpl->MetadataStore[this];
355 assert(!Info.empty() == hasMetadata() && "HasMetadata bit is wonked");
357 setHasMetadata(true);
359 // Handle replacement of an existing value.
360 for (unsigned i = 0, e = Info.size(); i != e; ++i)
361 if (Info[i].first == KindID) {
362 Info[i].second = Node;
367 // No replacement, just add it to the list.
368 Info.push_back(std::make_pair(KindID, Node));
372 // Otherwise, we're removing metadata from an instruction.
373 assert(hasMetadata() && getContext().pImpl->MetadataStore.count(this) &&
374 "HasMetadata bit out of date!");
375 LLVMContextImpl::MDMapTy &Info = getContext().pImpl->MetadataStore[this];
377 // Common case is removing the only entry.
378 if (Info.size() == 1 && Info[0].first == KindID) {
379 getContext().pImpl->MetadataStore.erase(this);
380 setHasMetadata(false);
384 // Handle replacement of an existing value.
385 for (unsigned i = 0, e = Info.size(); i != e; ++i)
386 if (Info[i].first == KindID) {
387 Info[i] = Info.back();
389 assert(!Info.empty() && "Removing last entry should be handled above");
392 // Otherwise, removing an entry that doesn't exist on the instruction.
395 MDNode *Instruction::getMetadataImpl(unsigned KindID) const {
396 LLVMContextImpl::MDMapTy &Info = getContext().pImpl->MetadataStore[this];
397 assert(hasMetadata() && !Info.empty() && "Shouldn't have called this");
399 for (LLVMContextImpl::MDMapTy::iterator I = Info.begin(), E = Info.end();
401 if (I->first == KindID)
406 void Instruction::getAllMetadataImpl(SmallVectorImpl<std::pair<unsigned,
407 MDNode*> > &Result)const {
408 assert(hasMetadata() && getContext().pImpl->MetadataStore.count(this) &&
409 "Shouldn't have called this");
410 const LLVMContextImpl::MDMapTy &Info =
411 getContext().pImpl->MetadataStore.find(this)->second;
412 assert(!Info.empty() && "Shouldn't have called this");
415 Result.append(Info.begin(), Info.end());
417 // Sort the resulting array so it is stable.
418 if (Result.size() > 1)
419 array_pod_sort(Result.begin(), Result.end());
422 /// removeAllMetadata - Remove all metadata from this instruction.
423 void Instruction::removeAllMetadata() {
424 assert(hasMetadata() && "Caller should check");
425 getContext().pImpl->MetadataStore.erase(this);
426 setHasMetadata(false);