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 // getLocalFunction - Return false if MDNode's recursive function-localness is
192 // invalid (local to more than one function). Return true otherwise. If MDNode
193 // has one function to which it is local, set LocalFunction to that function.
194 bool MDNode::getLocalFunction(Function *LocalFunction,
195 SmallPtrSet<MDNode *, 32> *VisitedMDNodes) {
196 if (!isFunctionLocal())
200 VisitedMDNodes = new SmallPtrSet<MDNode *, 32>();
202 if (!VisitedMDNodes->insert(this))
203 // MDNode has already been visited, nothing to do.
206 for (unsigned i = 0, e = getNumElements(); i != e; ++i) {
207 Value *V = getElement(i);
210 Function *LocalFunctionTemp = NULL;
211 if (Instruction *I = dyn_cast<Instruction>(V))
212 LocalFunctionTemp = I->getParent()->getParent();
213 else if (MDNode *MD = dyn_cast<MDNode>(V))
214 if (!MD->getLocalFunction(LocalFunctionTemp, VisitedMDNodes))
215 // This MDNode's operand is function-locally invalid or local to a
216 // different function.
219 if (LocalFunctionTemp) {
221 LocalFunction = LocalFunctionTemp;
222 else if (LocalFunction != LocalFunctionTemp)
223 // This MDNode contains operands that are local to different functions.
231 //===----------------------------------------------------------------------===//
232 // NamedMDNode implementation.
234 static SmallVector<TrackingVH<MetadataBase>, 4> &getNMDOps(void *Operands) {
235 return *(SmallVector<TrackingVH<MetadataBase>, 4>*)Operands;
238 NamedMDNode::NamedMDNode(LLVMContext &C, const Twine &N,
239 MetadataBase *const *MDs,
240 unsigned NumMDs, Module *ParentModule)
241 : MetadataBase(Type::getMetadataTy(C), Value::NamedMDNodeVal), Parent(0) {
244 Operands = new SmallVector<TrackingVH<MetadataBase>, 4>();
246 SmallVector<TrackingVH<MetadataBase>, 4> &Node = getNMDOps(Operands);
247 for (unsigned i = 0; i != NumMDs; ++i)
248 Node.push_back(TrackingVH<MetadataBase>(MDs[i]));
251 ParentModule->getNamedMDList().push_back(this);
254 NamedMDNode *NamedMDNode::Create(const NamedMDNode *NMD, Module *M) {
255 assert(NMD && "Invalid source NamedMDNode!");
256 SmallVector<MetadataBase *, 4> Elems;
257 Elems.reserve(NMD->getNumElements());
259 for (unsigned i = 0, e = NMD->getNumElements(); i != e; ++i)
260 Elems.push_back(NMD->getElement(i));
261 return new NamedMDNode(NMD->getContext(), NMD->getName().data(),
262 Elems.data(), Elems.size(), M);
265 NamedMDNode::~NamedMDNode() {
267 delete &getNMDOps(Operands);
270 /// getNumElements - Return number of NamedMDNode elements.
271 unsigned NamedMDNode::getNumElements() const {
272 return (unsigned)getNMDOps(Operands).size();
275 /// getElement - Return specified element.
276 MetadataBase *NamedMDNode::getElement(unsigned i) const {
277 assert(i < getNumElements() && "Invalid element number!");
278 return getNMDOps(Operands)[i];
281 /// addElement - Add metadata element.
282 void NamedMDNode::addElement(MetadataBase *M) {
283 getNMDOps(Operands).push_back(TrackingVH<MetadataBase>(M));
286 /// eraseFromParent - Drop all references and remove the node from parent
288 void NamedMDNode::eraseFromParent() {
289 getParent()->getNamedMDList().erase(this);
292 /// dropAllReferences - Remove all uses and clear node vector.
293 void NamedMDNode::dropAllReferences() {
294 getNMDOps(Operands).clear();
298 //===----------------------------------------------------------------------===//
299 // MetadataContextImpl implementation.
302 class MetadataContextImpl {
304 typedef std::pair<unsigned, TrackingVH<MDNode> > MDPairTy;
305 typedef SmallVector<MDPairTy, 2> MDMapTy;
306 typedef DenseMap<const Instruction *, MDMapTy> MDStoreTy;
307 friend class BitcodeReader;
310 /// MetadataStore - Collection of metadata used in this context.
311 MDStoreTy MetadataStore;
313 /// MDHandlerNames - Map to hold metadata handler names.
314 StringMap<unsigned> MDHandlerNames;
317 /// registerMDKind - Register a new metadata kind and return its ID.
318 /// A metadata kind can be registered only once.
319 unsigned registerMDKind(StringRef Name);
321 /// getMDKind - Return metadata kind. If the requested metadata kind
322 /// is not registered then return 0.
323 unsigned getMDKind(StringRef Name) const;
325 /// getMD - Get the metadata of given kind attached to an Instruction.
326 /// If the metadata is not found then return 0.
327 MDNode *getMD(unsigned Kind, const Instruction *Inst);
329 /// getMDs - Get the metadata attached to an Instruction.
330 void getMDs(const Instruction *Inst,
331 SmallVectorImpl<std::pair<unsigned, MDNode*> > &MDs) const;
333 /// addMD - Attach the metadata of given kind to an Instruction.
334 void addMD(unsigned Kind, MDNode *Node, Instruction *Inst);
336 /// removeMD - Remove metadata of given kind attached with an instruction.
337 void removeMD(unsigned Kind, Instruction *Inst);
339 /// removeAllMetadata - Remove all metadata attached with an instruction.
340 void removeAllMetadata(Instruction *Inst);
342 /// copyMD - If metadata is attached with Instruction In1 then attach
343 /// the same metadata to In2.
344 void copyMD(Instruction *In1, Instruction *In2);
346 /// getHandlerNames - Populate client-supplied smallvector using custom
347 /// metadata name and ID.
348 void getHandlerNames(SmallVectorImpl<std::pair<unsigned, StringRef> >&) const;
350 /// ValueIsDeleted - This handler is used to update metadata store
351 /// when a value is deleted.
352 void ValueIsDeleted(const Value *) {}
353 void ValueIsDeleted(Instruction *Inst) {
354 removeAllMetadata(Inst);
356 void ValueIsRAUWd(Value *V1, Value *V2);
358 /// ValueIsCloned - This handler is used to update metadata store
359 /// when In1 is cloned to create In2.
360 void ValueIsCloned(const Instruction *In1, Instruction *In2);
364 /// registerMDKind - Register a new metadata kind and return its ID.
365 /// A metadata kind can be registered only once.
366 unsigned MetadataContextImpl::registerMDKind(StringRef Name) {
367 unsigned Count = MDHandlerNames.size();
368 assert(MDHandlerNames.count(Name) == 0 && "Already registered MDKind!");
369 return MDHandlerNames[Name] = Count + 1;
372 /// getMDKind - Return metadata kind. If the requested metadata kind
373 /// is not registered then return 0.
374 unsigned MetadataContextImpl::getMDKind(StringRef Name) const {
375 StringMap<unsigned>::const_iterator I = MDHandlerNames.find(Name);
376 if (I == MDHandlerNames.end())
379 return I->getValue();
382 /// addMD - Attach the metadata of given kind to an Instruction.
383 void MetadataContextImpl::addMD(unsigned MDKind, MDNode *Node,
385 assert(Node && "Invalid null MDNode");
386 Inst->HasMetadata = true;
387 MDMapTy &Info = MetadataStore[Inst];
389 Info.push_back(std::make_pair(MDKind, Node));
390 MetadataStore.insert(std::make_pair(Inst, Info));
394 // If there is an entry for this MDKind then replace it.
395 for (unsigned i = 0, e = Info.size(); i != e; ++i) {
396 MDPairTy &P = Info[i];
397 if (P.first == MDKind) {
398 Info[i] = std::make_pair(MDKind, Node);
403 // Otherwise add a new entry.
404 Info.push_back(std::make_pair(MDKind, Node));
407 /// removeMD - Remove metadata of given kind attached with an instruction.
408 void MetadataContextImpl::removeMD(unsigned Kind, Instruction *Inst) {
409 MDStoreTy::iterator I = MetadataStore.find(Inst);
410 if (I == MetadataStore.end())
413 MDMapTy &Info = I->second;
414 for (MDMapTy::iterator MI = Info.begin(), ME = Info.end(); MI != ME; ++MI) {
416 if (P.first == Kind) {
423 /// removeAllMetadata - Remove all metadata attached with an instruction.
424 void MetadataContextImpl::removeAllMetadata(Instruction *Inst) {
425 MetadataStore.erase(Inst);
426 Inst->HasMetadata = false;
429 /// copyMD - If metadata is attached with Instruction In1 then attach
430 /// the same metadata to In2.
431 void MetadataContextImpl::copyMD(Instruction *In1, Instruction *In2) {
432 assert(In1 && In2 && "Invalid instruction!");
433 MDMapTy &In1Info = MetadataStore[In1];
437 for (MDMapTy::iterator I = In1Info.begin(), E = In1Info.end(); I != E; ++I)
438 addMD(I->first, I->second, In2);
441 /// getMD - Get the metadata of given kind attached to an Instruction.
442 /// If the metadata is not found then return 0.
443 MDNode *MetadataContextImpl::getMD(unsigned MDKind, const Instruction *Inst) {
444 MDMapTy &Info = MetadataStore[Inst];
448 for (MDMapTy::iterator I = Info.begin(), E = Info.end(); I != E; ++I)
449 if (I->first == MDKind)
454 /// getMDs - Get the metadata attached to an Instruction.
455 void MetadataContextImpl::
456 getMDs(const Instruction *Inst,
457 SmallVectorImpl<std::pair<unsigned, MDNode*> > &MDs) const {
458 MDStoreTy::const_iterator I = MetadataStore.find(Inst);
459 if (I == MetadataStore.end())
461 MDs.resize(I->second.size());
462 for (MDMapTy::const_iterator MI = I->second.begin(), ME = I->second.end();
464 // MD kinds are numbered from 1.
465 MDs[MI->first - 1] = std::make_pair(MI->first, MI->second);
468 /// getHandlerNames - Populate client supplied smallvector using custome
469 /// metadata name and ID.
470 void MetadataContextImpl::
471 getHandlerNames(SmallVectorImpl<std::pair<unsigned, StringRef> >&Names) const {
472 Names.resize(MDHandlerNames.size());
473 for (StringMap<unsigned>::const_iterator I = MDHandlerNames.begin(),
474 E = MDHandlerNames.end(); I != E; ++I)
475 // MD Handlers are numbered from 1.
476 Names[I->second - 1] = std::make_pair(I->second, I->first());
479 /// ValueIsCloned - This handler is used to update metadata store
480 /// when In1 is cloned to create In2.
481 void MetadataContextImpl::ValueIsCloned(const Instruction *In1,
483 // Find Metadata handles for In1.
484 MDStoreTy::iterator I = MetadataStore.find(In1);
485 assert(I != MetadataStore.end() && "Invalid custom metadata info!");
487 // FIXME : Give all metadata handlers a chance to adjust.
489 MDMapTy &In1Info = I->second;
491 for (MDMapTy::iterator I = In1Info.begin(), E = In1Info.end(); I != E; ++I)
492 addMD(I->first, I->second, In2);
495 /// ValueIsRAUWd - This handler is used when V1's all uses are replaced by
497 void MetadataContextImpl::ValueIsRAUWd(Value *V1, Value *V2) {
498 Instruction *I1 = dyn_cast<Instruction>(V1);
499 Instruction *I2 = dyn_cast<Instruction>(V2);
503 // FIXME : Give custom handlers a chance to override this.
504 ValueIsCloned(I1, I2);
507 //===----------------------------------------------------------------------===//
508 // MetadataContext implementation.
510 MetadataContext::MetadataContext()
511 : pImpl(new MetadataContextImpl()) { }
512 MetadataContext::~MetadataContext() { delete pImpl; }
514 /// isValidName - Return true if Name is a valid custom metadata handler name.
515 bool MetadataContext::isValidName(StringRef MDName) {
519 if (!isalpha(MDName[0]))
522 for (StringRef::iterator I = MDName.begin() + 1, E = MDName.end(); I != E;
524 if (!isalnum(*I) && *I != '_' && *I != '-' && *I != '.')
530 /// registerMDKind - Register a new metadata kind and return its ID.
531 /// A metadata kind can be registered only once.
532 unsigned MetadataContext::registerMDKind(StringRef Name) {
533 assert(isValidName(Name) && "Invalid custome metadata name!");
534 return pImpl->registerMDKind(Name);
537 /// getMDKind - Return metadata kind. If the requested metadata kind
538 /// is not registered then return 0.
539 unsigned MetadataContext::getMDKind(StringRef Name) const {
540 return pImpl->getMDKind(Name);
543 /// getMD - Get the metadata of given kind attached to an Instruction.
544 /// If the metadata is not found then return 0.
545 MDNode *MetadataContext::getMD(unsigned Kind, const Instruction *Inst) {
546 return pImpl->getMD(Kind, Inst);
549 /// getMDs - Get the metadata attached to an Instruction.
550 void MetadataContext::
551 getMDs(const Instruction *Inst,
552 SmallVectorImpl<std::pair<unsigned, MDNode*> > &MDs) const {
553 return pImpl->getMDs(Inst, MDs);
556 /// addMD - Attach the metadata of given kind to an Instruction.
557 void MetadataContext::addMD(unsigned Kind, MDNode *Node, Instruction *Inst) {
558 pImpl->addMD(Kind, Node, Inst);
561 /// removeMD - Remove metadata of given kind attached with an instruction.
562 void MetadataContext::removeMD(unsigned Kind, Instruction *Inst) {
563 pImpl->removeMD(Kind, Inst);
566 /// removeAllMetadata - Remove all metadata attached with an instruction.
567 void MetadataContext::removeAllMetadata(Instruction *Inst) {
568 pImpl->removeAllMetadata(Inst);
571 /// copyMD - If metadata is attached with Instruction In1 then attach
572 /// the same metadata to In2.
573 void MetadataContext::copyMD(Instruction *In1, Instruction *In2) {
574 pImpl->copyMD(In1, In2);
577 /// getHandlerNames - Populate client supplied smallvector using custome
578 /// metadata name and ID.
579 void MetadataContext::
580 getHandlerNames(SmallVectorImpl<std::pair<unsigned, StringRef> >&N) const {
581 pImpl->getHandlerNames(N);
584 /// ValueIsDeleted - This handler is used to update metadata store
585 /// when a value is deleted.
586 void MetadataContext::ValueIsDeleted(Instruction *Inst) {
587 pImpl->ValueIsDeleted(Inst);
589 void MetadataContext::ValueIsRAUWd(Value *V1, Value *V2) {
590 pImpl->ValueIsRAUWd(V1, V2);
593 /// ValueIsCloned - This handler is used to update metadata store
594 /// when In1 is cloned to create In2.
595 void MetadataContext::ValueIsCloned(const Instruction *In1, Instruction *In2) {
596 pImpl->ValueIsCloned(In1, In2);