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 "LLVMContextImpl.h"
15 #include "llvm/Metadata.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"
24 //===----------------------------------------------------------------------===//
25 // MetadataBase implementation.
28 //===----------------------------------------------------------------------===//
29 // MDString implementation.
31 MDString *MDString::get(LLVMContext &Context, StringRef Str) {
32 LLVMContextImpl *pImpl = Context.pImpl;
33 StringMapEntry<MDString *> &Entry =
34 pImpl->MDStringCache.GetOrCreateValue(Str);
35 MDString *&S = Entry.getValue();
36 if (!S) S = new MDString(Context, Entry.getKey());
40 MDString *MDString::get(LLVMContext &Context, const char *Str) {
41 LLVMContextImpl *pImpl = Context.pImpl;
42 StringMapEntry<MDString *> &Entry =
43 pImpl->MDStringCache.GetOrCreateValue(Str ? StringRef(Str) : StringRef());
44 MDString *&S = Entry.getValue();
45 if (!S) S = new MDString(Context, Entry.getKey());
49 //===----------------------------------------------------------------------===//
50 // MDNodeElement implementation.
53 // Use CallbackVH to hold MDNode elements.
55 class MDNodeElement : public CallbackVH {
59 MDNodeElement(Value *V, MDNode *P) : CallbackVH(V), Parent(P) {}
62 virtual void deleted();
63 virtual void allUsesReplacedWith(Value *NV);
65 } // end namespace llvm.
68 void MDNodeElement::deleted() {
69 Parent->replaceElement(this->operator Value*(), 0);
72 void MDNodeElement::allUsesReplacedWith(Value *NV) {
73 Parent->replaceElement(this->operator Value*(), NV);
78 //===----------------------------------------------------------------------===//
79 // MDNode implementation.
82 MDNode::MDNode(LLVMContext &C, Value *const *Vals, unsigned NumVals,
84 : MetadataBase(Type::getMetadataTy(C), Value::MDNodeVal) {
86 Node = new MDNodeElement[NodeSize];
87 MDNodeElement *Ptr = Node;
88 for (unsigned i = 0; i != NumVals; ++i)
89 *Ptr++ = MDNodeElement(Vals[i], this);
91 SubclassData |= FunctionLocalBit;
94 void MDNode::Profile(FoldingSetNodeID &ID) const {
95 for (unsigned i = 0, e = getNumElements(); i != e; ++i)
96 ID.AddPointer(getElement(i));
99 MDNode *MDNode::get(LLVMContext &Context, Value*const* Vals, unsigned NumVals,
100 bool isFunctionLocal) {
101 LLVMContextImpl *pImpl = Context.pImpl;
103 for (unsigned i = 0; i != NumVals; ++i)
104 ID.AddPointer(Vals[i]);
107 MDNode *N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint);
109 // InsertPoint will have been set by the FindNodeOrInsertPos call.
110 N = new MDNode(Context, Vals, NumVals, isFunctionLocal);
111 pImpl->MDNodeSet.InsertNode(N, InsertPoint);
116 /// ~MDNode - Destroy MDNode.
118 LLVMContextImpl *pImpl = getType()->getContext().pImpl;
119 pImpl->MDNodeSet.RemoveNode(this);
124 /// getElement - Return specified element.
125 Value *MDNode::getElement(unsigned i) const {
126 assert(i < getNumElements() && "Invalid element number!");
132 // Replace value from this node's element list.
133 void MDNode::replaceElement(Value *From, Value *To) {
134 if (From == To || !getType())
136 LLVMContext &Context = getType()->getContext();
137 LLVMContextImpl *pImpl = Context.pImpl;
139 // Find value. This is a linear search, do something if it consumes
140 // lot of time. It is possible that to have multiple instances of
141 // From in this MDNode's element list.
142 SmallVector<unsigned, 4> Indexes;
144 for (unsigned i = 0, e = getNumElements(); i != e; ++i, ++Index) {
145 Value *V = getElement(i);
147 Indexes.push_back(Index);
153 // Remove "this" from the context map.
154 pImpl->MDNodeSet.RemoveNode(this);
156 // Replace From element(s) in place.
157 for (SmallVector<unsigned, 4>::iterator I = Indexes.begin(), E = Indexes.end();
160 Node[Index] = MDNodeElement(To, this);
163 // Insert updated "this" into the context's folding node set.
164 // If a node with same element list already exist then before inserting
165 // updated "this" into the folding node set, replace all uses of existing
166 // node with updated "this" node.
170 MDNode *N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint);
173 N->replaceAllUsesWith(this);
178 N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint);
180 // InsertPoint will have been set by the FindNodeOrInsertPos call.
182 pImpl->MDNodeSet.InsertNode(N, InsertPoint);
186 // getLocalFunction - Return false if MDNode's recursive function-localness is
187 // invalid (local to more than one function). Return true otherwise. If MDNode
188 // has one function to which it is local, set LocalFunction to that function.
189 bool MDNode::getLocalFunction(Function *LocalFunction,
190 SmallPtrSet<MDNode *, 32> *VisitedMDNodes) {
191 if (!isFunctionLocal())
195 VisitedMDNodes = new SmallPtrSet<MDNode *, 32>();
197 if (!VisitedMDNodes->insert(this))
198 // MDNode has already been visited, nothing to do.
201 for (unsigned i = 0, e = getNumElements(); i != e; ++i) {
202 Value *V = getElement(i);
205 Function *LocalFunctionTemp = NULL;
206 if (Instruction *I = dyn_cast<Instruction>(V))
207 LocalFunctionTemp = I->getParent()->getParent();
208 else if (MDNode *MD = dyn_cast<MDNode>(V))
209 if (!MD->getLocalFunction(LocalFunctionTemp, VisitedMDNodes))
210 // This MDNode's operand is function-locally invalid or local to a
211 // different function.
214 if (LocalFunctionTemp) {
216 LocalFunction = LocalFunctionTemp;
217 else if (LocalFunction != LocalFunctionTemp)
218 // This MDNode contains operands that are local to different functions.
226 //===----------------------------------------------------------------------===//
227 // NamedMDNode implementation.
229 static SmallVector<TrackingVH<MetadataBase>, 4> &getNMDOps(void *Operands) {
230 return *(SmallVector<TrackingVH<MetadataBase>, 4>*)Operands;
233 NamedMDNode::NamedMDNode(LLVMContext &C, const Twine &N,
234 MetadataBase *const *MDs,
235 unsigned NumMDs, Module *ParentModule)
236 : MetadataBase(Type::getMetadataTy(C), Value::NamedMDNodeVal), Parent(0) {
239 Operands = new SmallVector<TrackingVH<MetadataBase>, 4>();
241 SmallVector<TrackingVH<MetadataBase>, 4> &Node = getNMDOps(Operands);
242 for (unsigned i = 0; i != NumMDs; ++i)
243 Node.push_back(TrackingVH<MetadataBase>(MDs[i]));
246 ParentModule->getNamedMDList().push_back(this);
249 NamedMDNode *NamedMDNode::Create(const NamedMDNode *NMD, Module *M) {
250 assert(NMD && "Invalid source NamedMDNode!");
251 SmallVector<MetadataBase *, 4> Elems;
252 Elems.reserve(NMD->getNumElements());
254 for (unsigned i = 0, e = NMD->getNumElements(); i != e; ++i)
255 Elems.push_back(NMD->getElement(i));
256 return new NamedMDNode(NMD->getContext(), NMD->getName().data(),
257 Elems.data(), Elems.size(), M);
260 NamedMDNode::~NamedMDNode() {
262 delete &getNMDOps(Operands);
265 /// getNumElements - Return number of NamedMDNode elements.
266 unsigned NamedMDNode::getNumElements() const {
267 return (unsigned)getNMDOps(Operands).size();
270 /// getElement - Return specified element.
271 MetadataBase *NamedMDNode::getElement(unsigned i) const {
272 assert(i < getNumElements() && "Invalid element number!");
273 return getNMDOps(Operands)[i];
276 /// addElement - Add metadata element.
277 void NamedMDNode::addElement(MetadataBase *M) {
278 getNMDOps(Operands).push_back(TrackingVH<MetadataBase>(M));
281 /// eraseFromParent - Drop all references and remove the node from parent
283 void NamedMDNode::eraseFromParent() {
284 getParent()->getNamedMDList().erase(this);
287 /// dropAllReferences - Remove all uses and clear node vector.
288 void NamedMDNode::dropAllReferences() {
289 getNMDOps(Operands).clear();
293 //===----------------------------------------------------------------------===//
294 // MetadataContextImpl implementation.
297 class MetadataContextImpl {
299 typedef std::pair<unsigned, TrackingVH<MDNode> > MDPairTy;
300 typedef SmallVector<MDPairTy, 2> MDMapTy;
301 typedef DenseMap<const Instruction *, MDMapTy> MDStoreTy;
302 friend class BitcodeReader;
305 /// MetadataStore - Collection of metadata used in this context.
306 MDStoreTy MetadataStore;
308 /// MDHandlerNames - Map to hold metadata handler names.
309 StringMap<unsigned> MDHandlerNames;
312 /// registerMDKind - Register a new metadata kind and return its ID.
313 /// A metadata kind can be registered only once.
314 unsigned registerMDKind(StringRef Name);
316 /// getMDKind - Return metadata kind. If the requested metadata kind
317 /// is not registered then return 0.
318 unsigned getMDKind(StringRef Name) const;
320 /// getMD - Get the metadata of given kind attached to an Instruction.
321 /// If the metadata is not found then return 0.
322 MDNode *getMD(unsigned Kind, const Instruction *Inst);
324 /// getMDs - Get the metadata attached to an Instruction.
325 void getMDs(const Instruction *Inst, SmallVectorImpl<MDPairTy> &MDs) const;
327 /// addMD - Attach the metadata of given kind to an Instruction.
328 void addMD(unsigned Kind, MDNode *Node, Instruction *Inst);
330 /// removeMD - Remove metadata of given kind attached with an instruction.
331 void removeMD(unsigned Kind, Instruction *Inst);
333 /// removeAllMetadata - Remove all metadata attached with an instruction.
334 void removeAllMetadata(Instruction *Inst);
336 /// copyMD - If metadata is attached with Instruction In1 then attach
337 /// the same metadata to In2.
338 void copyMD(Instruction *In1, Instruction *In2);
340 /// getHandlerNames - Populate client-supplied smallvector using custom
341 /// metadata name and ID.
342 void getHandlerNames(SmallVectorImpl<std::pair<unsigned, StringRef> >&) const;
344 /// ValueIsDeleted - This handler is used to update metadata store
345 /// when a value is deleted.
346 void ValueIsDeleted(const Value *) {}
347 void ValueIsDeleted(Instruction *Inst) {
348 removeAllMetadata(Inst);
350 void ValueIsRAUWd(Value *V1, Value *V2);
352 /// ValueIsCloned - This handler is used to update metadata store
353 /// when In1 is cloned to create In2.
354 void ValueIsCloned(const Instruction *In1, Instruction *In2);
358 /// registerMDKind - Register a new metadata kind and return its ID.
359 /// A metadata kind can be registered only once.
360 unsigned MetadataContextImpl::registerMDKind(StringRef Name) {
361 unsigned Count = MDHandlerNames.size();
362 assert(MDHandlerNames.count(Name) == 0 && "Already registered MDKind!");
363 return MDHandlerNames[Name] = Count + 1;
366 /// getMDKind - Return metadata kind. If the requested metadata kind
367 /// is not registered then return 0.
368 unsigned MetadataContextImpl::getMDKind(StringRef Name) const {
369 StringMap<unsigned>::const_iterator I = MDHandlerNames.find(Name);
370 if (I == MDHandlerNames.end())
373 return I->getValue();
376 /// addMD - Attach the metadata of given kind to an Instruction.
377 void MetadataContextImpl::addMD(unsigned MDKind, MDNode *Node,
379 assert(Node && "Invalid null MDNode");
380 Inst->HasMetadata = true;
381 MDMapTy &Info = MetadataStore[Inst];
383 Info.push_back(std::make_pair(MDKind, Node));
384 MetadataStore.insert(std::make_pair(Inst, Info));
388 // If there is an entry for this MDKind then replace it.
389 for (unsigned i = 0, e = Info.size(); i != e; ++i) {
390 MDPairTy &P = Info[i];
391 if (P.first == MDKind) {
392 Info[i] = std::make_pair(MDKind, Node);
397 // Otherwise add a new entry.
398 Info.push_back(std::make_pair(MDKind, Node));
401 /// removeMD - Remove metadata of given kind attached with an instruction.
402 void MetadataContextImpl::removeMD(unsigned Kind, Instruction *Inst) {
403 MDStoreTy::iterator I = MetadataStore.find(Inst);
404 if (I == MetadataStore.end())
407 MDMapTy &Info = I->second;
408 for (MDMapTy::iterator MI = Info.begin(), ME = Info.end(); MI != ME; ++MI) {
410 if (P.first == Kind) {
417 /// removeAllMetadata - Remove all metadata attached with an instruction.
418 void MetadataContextImpl::removeAllMetadata(Instruction *Inst) {
419 MetadataStore.erase(Inst);
420 Inst->HasMetadata = false;
423 /// copyMD - If metadata is attached with Instruction In1 then attach
424 /// the same metadata to In2.
425 void MetadataContextImpl::copyMD(Instruction *In1, Instruction *In2) {
426 assert(In1 && In2 && "Invalid instruction!");
427 MDMapTy &In1Info = MetadataStore[In1];
431 for (MDMapTy::iterator I = In1Info.begin(), E = In1Info.end(); I != E; ++I)
432 addMD(I->first, I->second, In2);
435 /// getMD - Get the metadata of given kind attached to an Instruction.
436 /// If the metadata is not found then return 0.
437 MDNode *MetadataContextImpl::getMD(unsigned MDKind, const Instruction *Inst) {
438 MDMapTy &Info = MetadataStore[Inst];
442 for (MDMapTy::iterator I = Info.begin(), E = Info.end(); I != E; ++I)
443 if (I->first == MDKind)
448 /// getMDs - Get the metadata attached to an Instruction.
449 void MetadataContextImpl::
450 getMDs(const Instruction *Inst, SmallVectorImpl<MDPairTy> &MDs) const {
451 MDStoreTy::const_iterator I = MetadataStore.find(Inst);
452 if (I == MetadataStore.end())
454 MDs.resize(I->second.size());
455 for (MDMapTy::const_iterator MI = I->second.begin(), ME = I->second.end();
457 // MD kinds are numbered from 1.
458 MDs[MI->first - 1] = std::make_pair(MI->first, MI->second);
461 /// getHandlerNames - Populate client supplied smallvector using custome
462 /// metadata name and ID.
463 void MetadataContextImpl::
464 getHandlerNames(SmallVectorImpl<std::pair<unsigned, StringRef> >&Names) const {
465 Names.resize(MDHandlerNames.size());
466 for (StringMap<unsigned>::const_iterator I = MDHandlerNames.begin(),
467 E = MDHandlerNames.end(); I != E; ++I)
468 // MD Handlers are numbered from 1.
469 Names[I->second - 1] = std::make_pair(I->second, I->first());
472 /// ValueIsCloned - This handler is used to update metadata store
473 /// when In1 is cloned to create In2.
474 void MetadataContextImpl::ValueIsCloned(const Instruction *In1,
476 // Find Metadata handles for In1.
477 MDStoreTy::iterator I = MetadataStore.find(In1);
478 assert(I != MetadataStore.end() && "Invalid custom metadata info!");
480 // FIXME : Give all metadata handlers a chance to adjust.
482 MDMapTy &In1Info = I->second;
484 for (MDMapTy::iterator I = In1Info.begin(), E = In1Info.end(); I != E; ++I)
485 addMD(I->first, I->second, In2);
488 /// ValueIsRAUWd - This handler is used when V1's all uses are replaced by
490 void MetadataContextImpl::ValueIsRAUWd(Value *V1, Value *V2) {
491 Instruction *I1 = dyn_cast<Instruction>(V1);
492 Instruction *I2 = dyn_cast<Instruction>(V2);
496 // FIXME : Give custom handlers a chance to override this.
497 ValueIsCloned(I1, I2);
500 //===----------------------------------------------------------------------===//
501 // MetadataContext implementation.
503 MetadataContext::MetadataContext()
504 : pImpl(new MetadataContextImpl()) { }
505 MetadataContext::~MetadataContext() { delete pImpl; }
507 /// isValidName - Return true if Name is a valid custom metadata handler name.
508 bool MetadataContext::isValidName(StringRef MDName) {
512 if (!isalpha(MDName[0]))
515 for (StringRef::iterator I = MDName.begin() + 1, E = MDName.end(); I != E;
517 if (!isalnum(*I) && *I != '_' && *I != '-' && *I != '.')
523 /// registerMDKind - Register a new metadata kind and return its ID.
524 /// A metadata kind can be registered only once.
525 unsigned MetadataContext::registerMDKind(StringRef Name) {
526 assert(isValidName(Name) && "Invalid custome metadata name!");
527 return pImpl->registerMDKind(Name);
530 /// getMDKind - Return metadata kind. If the requested metadata kind
531 /// is not registered then return 0.
532 unsigned MetadataContext::getMDKind(StringRef Name) const {
533 return pImpl->getMDKind(Name);
536 /// getMD - Get the metadata of given kind attached to an Instruction.
537 /// If the metadata is not found then return 0.
538 MDNode *MetadataContext::getMD(unsigned Kind, const Instruction *Inst) {
539 return pImpl->getMD(Kind, Inst);
542 /// getMDs - Get the metadata attached to an Instruction.
543 void MetadataContext::
544 getMDs(const Instruction *Inst,
545 SmallVectorImpl<std::pair<unsigned, TrackingVH<MDNode> > > &MDs) const {
546 return pImpl->getMDs(Inst, MDs);
549 /// addMD - Attach the metadata of given kind to an Instruction.
550 void MetadataContext::addMD(unsigned Kind, MDNode *Node, Instruction *Inst) {
551 pImpl->addMD(Kind, Node, Inst);
554 /// removeMD - Remove metadata of given kind attached with an instruction.
555 void MetadataContext::removeMD(unsigned Kind, Instruction *Inst) {
556 pImpl->removeMD(Kind, Inst);
559 /// removeAllMetadata - Remove all metadata attached with an instruction.
560 void MetadataContext::removeAllMetadata(Instruction *Inst) {
561 pImpl->removeAllMetadata(Inst);
564 /// copyMD - If metadata is attached with Instruction In1 then attach
565 /// the same metadata to In2.
566 void MetadataContext::copyMD(Instruction *In1, Instruction *In2) {
567 pImpl->copyMD(In1, In2);
570 /// getHandlerNames - Populate client supplied smallvector using custome
571 /// metadata name and ID.
572 void MetadataContext::
573 getHandlerNames(SmallVectorImpl<std::pair<unsigned, StringRef> >&N) const {
574 pImpl->getHandlerNames(N);
577 /// ValueIsDeleted - This handler is used to update metadata store
578 /// when a value is deleted.
579 void MetadataContext::ValueIsDeleted(Instruction *Inst) {
580 pImpl->ValueIsDeleted(Inst);
582 void MetadataContext::ValueIsRAUWd(Value *V1, Value *V2) {
583 pImpl->ValueIsRAUWd(V1, V2);
586 /// ValueIsCloned - This handler is used to update metadata store
587 /// when In1 is cloned to create In2.
588 void MetadataContext::ValueIsCloned(const Instruction *In1, Instruction *In2) {
589 pImpl->ValueIsCloned(In1, In2);