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 NamedMDNode::NamedMDNode(LLVMContext &C, const Twine &N,
230 MetadataBase *const *MDs,
231 unsigned NumMDs, Module *ParentModule)
232 : MetadataBase(Type::getMetadataTy(C), Value::NamedMDNodeVal), Parent(0) {
235 for (unsigned i = 0; i != NumMDs; ++i)
236 Node.push_back(TrackingVH<MetadataBase>(MDs[i]));
239 ParentModule->getNamedMDList().push_back(this);
242 NamedMDNode *NamedMDNode::Create(const NamedMDNode *NMD, Module *M) {
243 assert(NMD && "Invalid source NamedMDNode!");
244 SmallVector<MetadataBase *, 4> Elems;
245 for (unsigned i = 0, e = NMD->getNumElements(); i != e; ++i)
246 Elems.push_back(NMD->getElement(i));
247 return new NamedMDNode(NMD->getContext(), NMD->getName().data(),
248 Elems.data(), Elems.size(), 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() {
262 NamedMDNode::~NamedMDNode() {
266 //===----------------------------------------------------------------------===//
267 // MetadataContextImpl implementation.
270 class MetadataContextImpl {
272 typedef std::pair<unsigned, TrackingVH<MDNode> > MDPairTy;
273 typedef SmallVector<MDPairTy, 2> MDMapTy;
274 typedef DenseMap<const Instruction *, MDMapTy> MDStoreTy;
275 friend class BitcodeReader;
278 /// MetadataStore - Collection of metadata used in this context.
279 MDStoreTy MetadataStore;
281 /// MDHandlerNames - Map to hold metadata handler names.
282 StringMap<unsigned> MDHandlerNames;
285 /// registerMDKind - Register a new metadata kind and return its ID.
286 /// A metadata kind can be registered only once.
287 unsigned registerMDKind(StringRef Name);
289 /// getMDKind - Return metadata kind. If the requested metadata kind
290 /// is not registered then return 0.
291 unsigned getMDKind(StringRef Name) const;
293 /// getMD - Get the metadata of given kind attached to an Instruction.
294 /// If the metadata is not found then return 0.
295 MDNode *getMD(unsigned Kind, const Instruction *Inst);
297 /// getMDs - Get the metadata attached to an Instruction.
298 void getMDs(const Instruction *Inst, SmallVectorImpl<MDPairTy> &MDs) const;
300 /// addMD - Attach the metadata of given kind to an Instruction.
301 void addMD(unsigned Kind, MDNode *Node, Instruction *Inst);
303 /// removeMD - Remove metadata of given kind attached with an instruction.
304 void removeMD(unsigned Kind, Instruction *Inst);
306 /// removeAllMetadata - Remove all metadata attached with an instruction.
307 void removeAllMetadata(Instruction *Inst);
309 /// copyMD - If metadata is attached with Instruction In1 then attach
310 /// the same metadata to In2.
311 void copyMD(Instruction *In1, Instruction *In2);
313 /// getHandlerNames - Populate client-supplied smallvector using custom
314 /// metadata name and ID.
315 void getHandlerNames(SmallVectorImpl<std::pair<unsigned, StringRef> >&) const;
317 /// ValueIsDeleted - This handler is used to update metadata store
318 /// when a value is deleted.
319 void ValueIsDeleted(const Value *) {}
320 void ValueIsDeleted(Instruction *Inst) {
321 removeAllMetadata(Inst);
323 void ValueIsRAUWd(Value *V1, Value *V2);
325 /// ValueIsCloned - This handler is used to update metadata store
326 /// when In1 is cloned to create In2.
327 void ValueIsCloned(const Instruction *In1, Instruction *In2);
331 /// registerMDKind - Register a new metadata kind and return its ID.
332 /// A metadata kind can be registered only once.
333 unsigned MetadataContextImpl::registerMDKind(StringRef Name) {
334 unsigned Count = MDHandlerNames.size();
335 assert(MDHandlerNames.count(Name) == 0 && "Already registered MDKind!");
336 return MDHandlerNames[Name] = Count + 1;
339 /// getMDKind - Return metadata kind. If the requested metadata kind
340 /// is not registered then return 0.
341 unsigned MetadataContextImpl::getMDKind(StringRef Name) const {
342 StringMap<unsigned>::const_iterator I = MDHandlerNames.find(Name);
343 if (I == MDHandlerNames.end())
346 return I->getValue();
349 /// addMD - Attach the metadata of given kind to an Instruction.
350 void MetadataContextImpl::addMD(unsigned MDKind, MDNode *Node,
352 assert(Node && "Invalid null MDNode");
353 Inst->HasMetadata = true;
354 MDMapTy &Info = MetadataStore[Inst];
356 Info.push_back(std::make_pair(MDKind, Node));
357 MetadataStore.insert(std::make_pair(Inst, Info));
361 // If there is an entry for this MDKind then replace it.
362 for (unsigned i = 0, e = Info.size(); i != e; ++i) {
363 MDPairTy &P = Info[i];
364 if (P.first == MDKind) {
365 Info[i] = std::make_pair(MDKind, Node);
370 // Otherwise add a new entry.
371 Info.push_back(std::make_pair(MDKind, Node));
374 /// removeMD - Remove metadata of given kind attached with an instruction.
375 void MetadataContextImpl::removeMD(unsigned Kind, Instruction *Inst) {
376 MDStoreTy::iterator I = MetadataStore.find(Inst);
377 if (I == MetadataStore.end())
380 MDMapTy &Info = I->second;
381 for (MDMapTy::iterator MI = Info.begin(), ME = Info.end(); MI != ME; ++MI) {
383 if (P.first == Kind) {
390 /// removeAllMetadata - Remove all metadata attached with an instruction.
391 void MetadataContextImpl::removeAllMetadata(Instruction *Inst) {
392 MetadataStore.erase(Inst);
393 Inst->HasMetadata = false;
396 /// copyMD - If metadata is attached with Instruction In1 then attach
397 /// the same metadata to In2.
398 void MetadataContextImpl::copyMD(Instruction *In1, Instruction *In2) {
399 assert(In1 && In2 && "Invalid instruction!");
400 MDMapTy &In1Info = MetadataStore[In1];
404 for (MDMapTy::iterator I = In1Info.begin(), E = In1Info.end(); I != E; ++I)
405 addMD(I->first, I->second, In2);
408 /// getMD - Get the metadata of given kind attached to an Instruction.
409 /// If the metadata is not found then return 0.
410 MDNode *MetadataContextImpl::getMD(unsigned MDKind, const Instruction *Inst) {
411 MDMapTy &Info = MetadataStore[Inst];
415 for (MDMapTy::iterator I = Info.begin(), E = Info.end(); I != E; ++I)
416 if (I->first == MDKind)
421 /// getMDs - Get the metadata attached to an Instruction.
422 void MetadataContextImpl::
423 getMDs(const Instruction *Inst, SmallVectorImpl<MDPairTy> &MDs) const {
424 MDStoreTy::const_iterator I = MetadataStore.find(Inst);
425 if (I == MetadataStore.end())
427 MDs.resize(I->second.size());
428 for (MDMapTy::const_iterator MI = I->second.begin(), ME = I->second.end();
430 // MD kinds are numbered from 1.
431 MDs[MI->first - 1] = std::make_pair(MI->first, MI->second);
434 /// getHandlerNames - Populate client supplied smallvector using custome
435 /// metadata name and ID.
436 void MetadataContextImpl::
437 getHandlerNames(SmallVectorImpl<std::pair<unsigned, StringRef> >&Names) const {
438 Names.resize(MDHandlerNames.size());
439 for (StringMap<unsigned>::const_iterator I = MDHandlerNames.begin(),
440 E = MDHandlerNames.end(); I != E; ++I)
441 // MD Handlers are numbered from 1.
442 Names[I->second - 1] = std::make_pair(I->second, I->first());
445 /// ValueIsCloned - This handler is used to update metadata store
446 /// when In1 is cloned to create In2.
447 void MetadataContextImpl::ValueIsCloned(const Instruction *In1,
449 // Find Metadata handles for In1.
450 MDStoreTy::iterator I = MetadataStore.find(In1);
451 assert(I != MetadataStore.end() && "Invalid custom metadata info!");
453 // FIXME : Give all metadata handlers a chance to adjust.
455 MDMapTy &In1Info = I->second;
457 for (MDMapTy::iterator I = In1Info.begin(), E = In1Info.end(); I != E; ++I)
458 addMD(I->first, I->second, In2);
461 /// ValueIsRAUWd - This handler is used when V1's all uses are replaced by
463 void MetadataContextImpl::ValueIsRAUWd(Value *V1, Value *V2) {
464 Instruction *I1 = dyn_cast<Instruction>(V1);
465 Instruction *I2 = dyn_cast<Instruction>(V2);
469 // FIXME : Give custom handlers a chance to override this.
470 ValueIsCloned(I1, I2);
473 //===----------------------------------------------------------------------===//
474 // MetadataContext implementation.
476 MetadataContext::MetadataContext()
477 : pImpl(new MetadataContextImpl()) { }
478 MetadataContext::~MetadataContext() { delete pImpl; }
480 /// isValidName - Return true if Name is a valid custom metadata handler name.
481 bool MetadataContext::isValidName(StringRef MDName) {
485 if (!isalpha(MDName[0]))
488 for (StringRef::iterator I = MDName.begin() + 1, E = MDName.end(); I != E;
490 if (!isalnum(*I) && *I != '_' && *I != '-' && *I != '.')
496 /// registerMDKind - Register a new metadata kind and return its ID.
497 /// A metadata kind can be registered only once.
498 unsigned MetadataContext::registerMDKind(StringRef Name) {
499 assert(isValidName(Name) && "Invalid custome metadata name!");
500 return pImpl->registerMDKind(Name);
503 /// getMDKind - Return metadata kind. If the requested metadata kind
504 /// is not registered then return 0.
505 unsigned MetadataContext::getMDKind(StringRef Name) const {
506 return pImpl->getMDKind(Name);
509 /// getMD - Get the metadata of given kind attached to an Instruction.
510 /// If the metadata is not found then return 0.
511 MDNode *MetadataContext::getMD(unsigned Kind, const Instruction *Inst) {
512 return pImpl->getMD(Kind, Inst);
515 /// getMDs - Get the metadata attached to an Instruction.
516 void MetadataContext::
517 getMDs(const Instruction *Inst,
518 SmallVectorImpl<std::pair<unsigned, TrackingVH<MDNode> > > &MDs) const {
519 return pImpl->getMDs(Inst, MDs);
522 /// addMD - Attach the metadata of given kind to an Instruction.
523 void MetadataContext::addMD(unsigned Kind, MDNode *Node, Instruction *Inst) {
524 pImpl->addMD(Kind, Node, Inst);
527 /// removeMD - Remove metadata of given kind attached with an instruction.
528 void MetadataContext::removeMD(unsigned Kind, Instruction *Inst) {
529 pImpl->removeMD(Kind, Inst);
532 /// removeAllMetadata - Remove all metadata attached with an instruction.
533 void MetadataContext::removeAllMetadata(Instruction *Inst) {
534 pImpl->removeAllMetadata(Inst);
537 /// copyMD - If metadata is attached with Instruction In1 then attach
538 /// the same metadata to In2.
539 void MetadataContext::copyMD(Instruction *In1, Instruction *In2) {
540 pImpl->copyMD(In1, In2);
543 /// getHandlerNames - Populate client supplied smallvector using custome
544 /// metadata name and ID.
545 void MetadataContext::
546 getHandlerNames(SmallVectorImpl<std::pair<unsigned, StringRef> >&N) const {
547 pImpl->getHandlerNames(N);
550 /// ValueIsDeleted - This handler is used to update metadata store
551 /// when a value is deleted.
552 void MetadataContext::ValueIsDeleted(Instruction *Inst) {
553 pImpl->ValueIsDeleted(Inst);
555 void MetadataContext::ValueIsRAUWd(Value *V1, Value *V2) {
556 pImpl->ValueIsRAUWd(V1, V2);
559 /// ValueIsCloned - This handler is used to update metadata store
560 /// when In1 is cloned to create In2.
561 void MetadataContext::ValueIsCloned(const Instruction *In1, Instruction *In2) {
562 pImpl->ValueIsCloned(In1, In2);