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 // MetadataBase implementation.
29 //===----------------------------------------------------------------------===//
30 // MDString implementation.
33 MDString::MDString(LLVMContext &C, StringRef S)
34 : MetadataBase(Type::getMetadataTy(C), Value::MDStringVal), Str(S) {}
36 MDString *MDString::get(LLVMContext &Context, StringRef Str) {
37 LLVMContextImpl *pImpl = Context.pImpl;
38 StringMapEntry<MDString *> &Entry =
39 pImpl->MDStringCache.GetOrCreateValue(Str);
40 MDString *&S = Entry.getValue();
41 if (!S) S = new MDString(Context, Entry.getKey());
45 MDString *MDString::get(LLVMContext &Context, const char *Str) {
46 LLVMContextImpl *pImpl = Context.pImpl;
47 StringMapEntry<MDString *> &Entry =
48 pImpl->MDStringCache.GetOrCreateValue(Str ? StringRef(Str) : StringRef());
49 MDString *&S = Entry.getValue();
50 if (!S) S = new MDString(Context, Entry.getKey());
54 //===----------------------------------------------------------------------===//
55 // MDNodeElement implementation.
58 // Use CallbackVH to hold MDNode elements.
60 class MDNodeElement : public CallbackVH {
64 MDNodeElement(Value *V, MDNode *P) : CallbackVH(V), Parent(P) {}
67 virtual void deleted();
68 virtual void allUsesReplacedWith(Value *NV);
70 } // end namespace llvm.
73 void MDNodeElement::deleted() {
74 Parent->replaceElement(this->operator Value*(), 0);
77 void MDNodeElement::allUsesReplacedWith(Value *NV) {
78 Parent->replaceElement(this->operator Value*(), NV);
83 //===----------------------------------------------------------------------===//
84 // MDNode implementation.
87 MDNode::MDNode(LLVMContext &C, Value *const *Vals, unsigned NumVals,
89 : MetadataBase(Type::getMetadataTy(C), Value::MDNodeVal) {
90 NumOperands = NumVals;
91 Operands = new MDNodeElement[NumOperands];
92 MDNodeElement *Ptr = Operands;
93 for (unsigned i = 0; i != NumVals; ++i)
94 Ptr[i] = MDNodeElement(Vals[i], this);
97 SubclassData |= FunctionLocalBit;
100 void MDNode::Profile(FoldingSetNodeID &ID) const {
101 for (unsigned i = 0, e = getNumElements(); i != e; ++i)
102 ID.AddPointer(getElement(i));
105 MDNode *MDNode::get(LLVMContext &Context, Value*const* Vals, unsigned NumVals,
106 bool isFunctionLocal) {
107 LLVMContextImpl *pImpl = Context.pImpl;
109 for (unsigned i = 0; i != NumVals; ++i)
110 ID.AddPointer(Vals[i]);
113 MDNode *N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint);
115 // InsertPoint will have been set by the FindNodeOrInsertPos call.
116 N = new MDNode(Context, Vals, NumVals, isFunctionLocal);
117 pImpl->MDNodeSet.InsertNode(N, InsertPoint);
122 /// ~MDNode - Destroy MDNode.
124 LLVMContextImpl *pImpl = getType()->getContext().pImpl;
125 pImpl->MDNodeSet.RemoveNode(this);
130 /// getElement - Return specified element.
131 Value *MDNode::getElement(unsigned i) const {
132 assert(i < getNumElements() && "Invalid element number!");
138 // Replace value from this node's element list.
139 void MDNode::replaceElement(Value *From, Value *To) {
140 if (From == To || !getType())
142 LLVMContext &Context = getType()->getContext();
143 LLVMContextImpl *pImpl = Context.pImpl;
145 // Find value. This is a linear search, do something if it consumes
146 // lot of time. It is possible that to have multiple instances of
147 // From in this MDNode's element list.
148 SmallVector<unsigned, 4> Indexes;
150 for (unsigned i = 0, e = getNumElements(); i != e; ++i, ++Index) {
151 Value *V = getElement(i);
153 Indexes.push_back(Index);
159 // Remove "this" from the context map.
160 pImpl->MDNodeSet.RemoveNode(this);
162 // Replace From element(s) in place.
163 for (SmallVector<unsigned, 4>::iterator I = Indexes.begin(), E = Indexes.end();
165 Operands[*I] = MDNodeElement(To, this);
168 // Insert updated "this" into the context's folding node set.
169 // If a node with same element list already exist then before inserting
170 // updated "this" into the folding node set, replace all uses of existing
171 // node with updated "this" node.
175 MDNode *N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint);
178 N->replaceAllUsesWith(this);
183 N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint);
185 // InsertPoint will have been set by the FindNodeOrInsertPos call.
187 pImpl->MDNodeSet.InsertNode(N, InsertPoint);
191 //===----------------------------------------------------------------------===//
192 // NamedMDNode implementation.
194 static SmallVector<TrackingVH<MetadataBase>, 4> &getNMDOps(void *Operands) {
195 return *(SmallVector<TrackingVH<MetadataBase>, 4>*)Operands;
198 NamedMDNode::NamedMDNode(LLVMContext &C, const Twine &N,
199 MetadataBase *const *MDs,
200 unsigned NumMDs, Module *ParentModule)
201 : MetadataBase(Type::getMetadataTy(C), Value::NamedMDNodeVal), Parent(0) {
204 Operands = new SmallVector<TrackingVH<MetadataBase>, 4>();
206 SmallVector<TrackingVH<MetadataBase>, 4> &Node = getNMDOps(Operands);
207 for (unsigned i = 0; i != NumMDs; ++i)
208 Node.push_back(TrackingVH<MetadataBase>(MDs[i]));
211 ParentModule->getNamedMDList().push_back(this);
214 NamedMDNode *NamedMDNode::Create(const NamedMDNode *NMD, Module *M) {
215 assert(NMD && "Invalid source NamedMDNode!");
216 SmallVector<MetadataBase *, 4> Elems;
217 Elems.reserve(NMD->getNumElements());
219 for (unsigned i = 0, e = NMD->getNumElements(); i != e; ++i)
220 Elems.push_back(NMD->getElement(i));
221 return new NamedMDNode(NMD->getContext(), NMD->getName().data(),
222 Elems.data(), Elems.size(), M);
225 NamedMDNode::~NamedMDNode() {
227 delete &getNMDOps(Operands);
230 /// getNumElements - Return number of NamedMDNode elements.
231 unsigned NamedMDNode::getNumElements() const {
232 return (unsigned)getNMDOps(Operands).size();
235 /// getElement - Return specified element.
236 MetadataBase *NamedMDNode::getElement(unsigned i) const {
237 assert(i < getNumElements() && "Invalid element number!");
238 return getNMDOps(Operands)[i];
241 /// addElement - Add metadata element.
242 void NamedMDNode::addElement(MetadataBase *M) {
243 getNMDOps(Operands).push_back(TrackingVH<MetadataBase>(M));
246 /// eraseFromParent - Drop all references and remove the node from parent
248 void NamedMDNode::eraseFromParent() {
249 getParent()->getNamedMDList().erase(this);
252 /// dropAllReferences - Remove all uses and clear node vector.
253 void NamedMDNode::dropAllReferences() {
254 getNMDOps(Operands).clear();
258 //===----------------------------------------------------------------------===//
259 // MetadataContextImpl implementation.
262 class MetadataContextImpl {
264 typedef std::pair<unsigned, TrackingVH<MDNode> > MDPairTy;
265 typedef SmallVector<MDPairTy, 2> MDMapTy;
266 typedef DenseMap<const Instruction *, MDMapTy> MDStoreTy;
267 friend class BitcodeReader;
270 /// MetadataStore - Collection of metadata used in this context.
271 MDStoreTy MetadataStore;
273 /// MDHandlerNames - Map to hold metadata handler names.
274 StringMap<unsigned> MDHandlerNames;
277 /// registerMDKind - Register a new metadata kind and return its ID.
278 /// A metadata kind can be registered only once.
279 unsigned registerMDKind(StringRef Name);
281 /// getMDKind - Return metadata kind. If the requested metadata kind
282 /// is not registered then return 0.
283 unsigned getMDKind(StringRef Name) const;
285 /// getMD - Get the metadata of given kind attached to an Instruction.
286 /// If the metadata is not found then return 0.
287 MDNode *getMD(unsigned Kind, const Instruction *Inst);
289 /// getMDs - Get the metadata attached to an Instruction.
290 void getMDs(const Instruction *Inst,
291 SmallVectorImpl<std::pair<unsigned, MDNode*> > &MDs) const;
293 /// addMD - Attach the metadata of given kind to an Instruction.
294 void addMD(unsigned Kind, MDNode *Node, Instruction *Inst);
296 /// removeMD - Remove metadata of given kind attached with an instruction.
297 void removeMD(unsigned Kind, Instruction *Inst);
299 /// removeAllMetadata - Remove all metadata attached with an instruction.
300 void removeAllMetadata(Instruction *Inst);
302 /// copyMD - If metadata is attached with Instruction In1 then attach
303 /// the same metadata to In2.
304 void copyMD(Instruction *In1, Instruction *In2);
306 /// getHandlerNames - Populate client-supplied smallvector using custom
307 /// metadata name and ID.
308 void getHandlerNames(SmallVectorImpl<std::pair<unsigned, StringRef> >&) const;
310 /// ValueIsDeleted - This handler is used to update metadata store
311 /// when a value is deleted.
312 void ValueIsDeleted(const Value *) {}
313 void ValueIsDeleted(Instruction *Inst) {
314 removeAllMetadata(Inst);
316 void ValueIsRAUWd(Value *V1, Value *V2);
318 /// ValueIsCloned - This handler is used to update metadata store
319 /// when In1 is cloned to create In2.
320 void ValueIsCloned(const Instruction *In1, Instruction *In2);
324 /// registerMDKind - Register a new metadata kind and return its ID.
325 /// A metadata kind can be registered only once.
326 unsigned MetadataContextImpl::registerMDKind(StringRef Name) {
327 unsigned Count = MDHandlerNames.size();
328 assert(MDHandlerNames.count(Name) == 0 && "Already registered MDKind!");
329 return MDHandlerNames[Name] = Count + 1;
332 /// getMDKind - Return metadata kind. If the requested metadata kind
333 /// is not registered then return 0.
334 unsigned MetadataContextImpl::getMDKind(StringRef Name) const {
335 StringMap<unsigned>::const_iterator I = MDHandlerNames.find(Name);
336 if (I == MDHandlerNames.end())
339 return I->getValue();
342 /// addMD - Attach the metadata of given kind to an Instruction.
343 void MetadataContextImpl::addMD(unsigned MDKind, MDNode *Node,
345 assert(Node && "Invalid null MDNode");
346 Inst->HasMetadata = true;
347 MDMapTy &Info = MetadataStore[Inst];
349 Info.push_back(std::make_pair(MDKind, Node));
350 MetadataStore.insert(std::make_pair(Inst, Info));
354 // If there is an entry for this MDKind then replace it.
355 for (unsigned i = 0, e = Info.size(); i != e; ++i) {
356 MDPairTy &P = Info[i];
357 if (P.first == MDKind) {
358 Info[i] = std::make_pair(MDKind, Node);
363 // Otherwise add a new entry.
364 Info.push_back(std::make_pair(MDKind, Node));
367 /// removeMD - Remove metadata of given kind attached with an instruction.
368 void MetadataContextImpl::removeMD(unsigned Kind, Instruction *Inst) {
369 MDStoreTy::iterator I = MetadataStore.find(Inst);
370 if (I == MetadataStore.end())
373 MDMapTy &Info = I->second;
374 for (MDMapTy::iterator MI = Info.begin(), ME = Info.end(); MI != ME; ++MI) {
376 if (P.first == Kind) {
383 /// removeAllMetadata - Remove all metadata attached with an instruction.
384 void MetadataContextImpl::removeAllMetadata(Instruction *Inst) {
385 MetadataStore.erase(Inst);
386 Inst->HasMetadata = false;
389 /// copyMD - If metadata is attached with Instruction In1 then attach
390 /// the same metadata to In2.
391 void MetadataContextImpl::copyMD(Instruction *In1, Instruction *In2) {
392 assert(In1 && In2 && "Invalid instruction!");
393 MDMapTy &In1Info = MetadataStore[In1];
397 for (MDMapTy::iterator I = In1Info.begin(), E = In1Info.end(); I != E; ++I)
398 addMD(I->first, I->second, In2);
401 /// getMD - Get the metadata of given kind attached to an Instruction.
402 /// If the metadata is not found then return 0.
403 MDNode *MetadataContextImpl::getMD(unsigned MDKind, const Instruction *Inst) {
404 MDMapTy &Info = MetadataStore[Inst];
408 for (MDMapTy::iterator I = Info.begin(), E = Info.end(); I != E; ++I)
409 if (I->first == MDKind)
414 /// getMDs - Get the metadata attached to an Instruction.
415 void MetadataContextImpl::
416 getMDs(const Instruction *Inst,
417 SmallVectorImpl<std::pair<unsigned, MDNode*> > &MDs) const {
418 MDStoreTy::const_iterator I = MetadataStore.find(Inst);
419 if (I == MetadataStore.end())
421 MDs.resize(I->second.size());
422 for (MDMapTy::const_iterator MI = I->second.begin(), ME = I->second.end();
424 // MD kinds are numbered from 1.
425 MDs[MI->first - 1] = std::make_pair(MI->first, MI->second);
428 /// getHandlerNames - Populate client supplied smallvector using custome
429 /// metadata name and ID.
430 void MetadataContextImpl::
431 getHandlerNames(SmallVectorImpl<std::pair<unsigned, StringRef> >&Names) const {
432 Names.resize(MDHandlerNames.size());
433 for (StringMap<unsigned>::const_iterator I = MDHandlerNames.begin(),
434 E = MDHandlerNames.end(); I != E; ++I)
435 // MD Handlers are numbered from 1.
436 Names[I->second - 1] = std::make_pair(I->second, I->first());
439 /// ValueIsCloned - This handler is used to update metadata store
440 /// when In1 is cloned to create In2.
441 void MetadataContextImpl::ValueIsCloned(const Instruction *In1,
443 // Find Metadata handles for In1.
444 MDStoreTy::iterator I = MetadataStore.find(In1);
445 assert(I != MetadataStore.end() && "Invalid custom metadata info!");
447 // FIXME : Give all metadata handlers a chance to adjust.
449 MDMapTy &In1Info = I->second;
451 for (MDMapTy::iterator I = In1Info.begin(), E = In1Info.end(); I != E; ++I)
452 addMD(I->first, I->second, In2);
455 /// ValueIsRAUWd - This handler is used when V1's all uses are replaced by
457 void MetadataContextImpl::ValueIsRAUWd(Value *V1, Value *V2) {
458 Instruction *I1 = dyn_cast<Instruction>(V1);
459 Instruction *I2 = dyn_cast<Instruction>(V2);
463 // FIXME : Give custom handlers a chance to override this.
464 ValueIsCloned(I1, I2);
467 //===----------------------------------------------------------------------===//
468 // MetadataContext implementation.
470 MetadataContext::MetadataContext()
471 : pImpl(new MetadataContextImpl()) { }
472 MetadataContext::~MetadataContext() { delete pImpl; }
474 /// isValidName - Return true if Name is a valid custom metadata handler name.
475 bool MetadataContext::isValidName(StringRef MDName) {
479 if (!isalpha(MDName[0]))
482 for (StringRef::iterator I = MDName.begin() + 1, E = MDName.end(); I != E;
484 if (!isalnum(*I) && *I != '_' && *I != '-' && *I != '.')
490 /// registerMDKind - Register a new metadata kind and return its ID.
491 /// A metadata kind can be registered only once.
492 unsigned MetadataContext::registerMDKind(StringRef Name) {
493 assert(isValidName(Name) && "Invalid custome metadata name!");
494 return pImpl->registerMDKind(Name);
497 /// getMDKind - Return metadata kind. If the requested metadata kind
498 /// is not registered then return 0.
499 unsigned MetadataContext::getMDKind(StringRef Name) const {
500 return pImpl->getMDKind(Name);
503 /// getMD - Get the metadata of given kind attached to an Instruction.
504 /// If the metadata is not found then return 0.
505 MDNode *MetadataContext::getMD(unsigned Kind, const Instruction *Inst) {
506 return pImpl->getMD(Kind, Inst);
509 /// getMDs - Get the metadata attached to an Instruction.
510 void MetadataContext::
511 getMDs(const Instruction *Inst,
512 SmallVectorImpl<std::pair<unsigned, MDNode*> > &MDs) const {
513 return pImpl->getMDs(Inst, MDs);
516 /// addMD - Attach the metadata of given kind to an Instruction.
517 void MetadataContext::addMD(unsigned Kind, MDNode *Node, Instruction *Inst) {
518 pImpl->addMD(Kind, Node, Inst);
521 /// removeMD - Remove metadata of given kind attached with an instruction.
522 void MetadataContext::removeMD(unsigned Kind, Instruction *Inst) {
523 pImpl->removeMD(Kind, Inst);
526 /// removeAllMetadata - Remove all metadata attached with an instruction.
527 void MetadataContext::removeAllMetadata(Instruction *Inst) {
528 pImpl->removeAllMetadata(Inst);
531 /// copyMD - If metadata is attached with Instruction In1 then attach
532 /// the same metadata to In2.
533 void MetadataContext::copyMD(Instruction *In1, Instruction *In2) {
534 pImpl->copyMD(In1, In2);
537 /// getHandlerNames - Populate client supplied smallvector using custome
538 /// metadata name and ID.
539 void MetadataContext::
540 getHandlerNames(SmallVectorImpl<std::pair<unsigned, StringRef> >&N) const {
541 pImpl->getHandlerNames(N);
544 /// ValueIsDeleted - This handler is used to update metadata store
545 /// when a value is deleted.
546 void MetadataContext::ValueIsDeleted(Instruction *Inst) {
547 pImpl->ValueIsDeleted(Inst);
549 void MetadataContext::ValueIsRAUWd(Value *V1, Value *V2) {
550 pImpl->ValueIsRAUWd(V1, V2);
553 /// ValueIsCloned - This handler is used to update metadata store
554 /// when In1 is cloned to create In2.
555 void MetadataContext::ValueIsCloned(const Instruction *In1, Instruction *In2) {
556 pImpl->ValueIsCloned(In1, In2);