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 "SymbolTableListTraitsImpl.h"
22 //===----------------------------------------------------------------------===//
23 // MetadataBase implementation.
26 /// resizeOperands - Metadata keeps track of other metadata uses using
27 /// OperandList. Resize this list to hold anticipated number of metadata
29 void MetadataBase::resizeOperands(unsigned NumOps) {
30 unsigned e = getNumOperands();
33 if (NumOps < 2) NumOps = 2;
34 } else if (NumOps > NumOperands) {
36 if (ReservedSpace >= NumOps) return;
37 } else if (NumOps == NumOperands) {
38 if (ReservedSpace == NumOps) return;
43 ReservedSpace = NumOps;
44 Use *OldOps = OperandList;
45 Use *NewOps = allocHungoffUses(NumOps);
46 std::copy(OldOps, OldOps + e, NewOps);
48 if (OldOps) Use::zap(OldOps, OldOps + e, true);
50 //===----------------------------------------------------------------------===//
51 // MDString implementation.
53 MDString *MDString::get(LLVMContext &Context, const StringRef &Str) {
54 LLVMContextImpl *pImpl = Context.pImpl;
55 StringMapEntry<MDString *> &Entry =
56 pImpl->MDStringCache.GetOrCreateValue(Str);
57 MDString *&S = Entry.getValue();
60 return S = new MDString(Context, Entry.getKeyData(), Entry.getKeyLength());
63 //===----------------------------------------------------------------------===//
64 // MDNode implementation.
66 MDNode::MDNode(LLVMContext &C, Value *const *Vals, unsigned NumVals)
67 : MetadataBase(Type::getMetadataTy(C), Value::MDNodeVal) {
69 resizeOperands(NumVals);
71 Node = new ElementVH[NodeSize];
72 ElementVH *Ptr = Node;
73 for (unsigned i = 0; i != NumVals; ++i) {
74 // Only record metadata uses.
75 if (MetadataBase *MB = dyn_cast_or_null<MetadataBase>(Vals[i]))
76 OperandList[NumOperands++] = MB;
78 Vals[i]->getType()->getTypeID() == Type::MetadataTyID)
79 OperandList[NumOperands++] = Vals[i];
80 *Ptr++ = ElementVH(Vals[i], this);
84 void MDNode::Profile(FoldingSetNodeID &ID) const {
85 for (unsigned i = 0, e = getNumElements(); i != e; ++i)
86 ID.AddPointer(getElement(i));
89 MDNode *MDNode::get(LLVMContext &Context, Value*const* Vals, unsigned NumVals) {
90 LLVMContextImpl *pImpl = Context.pImpl;
92 for (unsigned i = 0; i != NumVals; ++i)
93 ID.AddPointer(Vals[i]);
98 N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint);
102 N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint);
104 // InsertPoint will have been set by the FindNodeOrInsertPos call.
105 N = new MDNode(Context, Vals, NumVals);
106 pImpl->MDNodeSet.InsertNode(N, InsertPoint);
112 /// dropAllReferences - Remove all uses and clear node vector.
113 void MDNode::dropAllReferences() {
114 User::dropAllReferences();
121 LLVMContextImpl *pImpl = getType()->getContext().pImpl;
122 pImpl->MDNodeSet.RemoveNode(this);
127 // Replace value from this node's element list.
128 void MDNode::replaceElement(Value *From, Value *To) {
129 if (From == To || !getType())
131 LLVMContext &Context = getType()->getContext();
132 LLVMContextImpl *pImpl = Context.pImpl;
134 // Find value. This is a linear search, do something if it consumes
135 // lot of time. It is possible that to have multiple instances of
136 // From in this MDNode's element list.
137 SmallVector<unsigned, 4> Indexes;
139 for (unsigned i = 0, e = getNumElements(); i != e; ++i, ++Index) {
140 Value *V = getElement(i);
142 Indexes.push_back(Index);
148 // Remove "this" from the context map.
149 pImpl->MDNodeSet.RemoveNode(this);
151 // MDNode only lists metadata elements in operand list, because MDNode
152 // used by MDNode is considered a valid use. However on the side, MDNode
153 // using a non-metadata value is not considered a "use" of non-metadata
155 SmallVector<unsigned, 4> OpIndexes;
156 unsigned OpIndex = 0;
157 for (User::op_iterator OI = op_begin(), OE = op_end();
158 OI != OE; ++OI, OpIndex++) {
160 OpIndexes.push_back(OpIndex);
162 if (MetadataBase *MDTo = dyn_cast_or_null<MetadataBase>(To)) {
163 for (SmallVector<unsigned, 4>::iterator OI = OpIndexes.begin(),
164 OE = OpIndexes.end(); OI != OE; ++OI)
165 setOperand(*OI, MDTo);
167 for (SmallVector<unsigned, 4>::iterator OI = OpIndexes.begin(),
168 OE = OpIndexes.end(); OI != OE; ++OI)
172 // Replace From element(s) in place.
173 for (SmallVector<unsigned, 4>::iterator I = Indexes.begin(), E = Indexes.end();
176 Node[Index] = ElementVH(To, this);
179 // Insert updated "this" into the context's folding node set.
180 // If a node with same element list already exist then before inserting
181 // updated "this" into the folding node set, replace all uses of existing
182 // node with updated "this" node.
186 MDNode *N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint);
189 N->replaceAllUsesWith(this);
194 N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint);
196 // InsertPoint will have been set by the FindNodeOrInsertPos call.
198 pImpl->MDNodeSet.InsertNode(N, InsertPoint);
202 //===----------------------------------------------------------------------===//
203 // NamedMDNode implementation.
205 NamedMDNode::NamedMDNode(LLVMContext &C, const Twine &N,
206 MetadataBase *const *MDs,
207 unsigned NumMDs, Module *ParentModule)
208 : MetadataBase(Type::getMetadataTy(C), Value::NamedMDNodeVal), Parent(0) {
211 resizeOperands(NumMDs);
213 for (unsigned i = 0; i != NumMDs; ++i) {
215 OperandList[NumOperands++] = MDs[i];
216 Node.push_back(WeakMetadataVH(MDs[i]));
219 ParentModule->getNamedMDList().push_back(this);
222 NamedMDNode *NamedMDNode::Create(const NamedMDNode *NMD, Module *M) {
223 assert(NMD && "Invalid source NamedMDNode!");
224 SmallVector<MetadataBase *, 4> Elems;
225 for (unsigned i = 0, e = NMD->getNumElements(); i != e; ++i)
226 Elems.push_back(NMD->getElement(i));
227 return new NamedMDNode(NMD->getContext(), NMD->getName().data(),
228 Elems.data(), Elems.size(), M);
231 /// eraseFromParent - Drop all references and remove the node from parent
233 void NamedMDNode::eraseFromParent() {
234 getParent()->getNamedMDList().erase(this);
237 /// dropAllReferences - Remove all uses and clear node vector.
238 void NamedMDNode::dropAllReferences() {
239 User::dropAllReferences();
243 NamedMDNode::~NamedMDNode() {
247 //===----------------------------------------------------------------------===//
248 // MetadataContext implementation.
251 /// registerMDKind - Register a new metadata kind and return its ID.
252 /// A metadata kind can be registered only once.
253 unsigned MetadataContext::registerMDKind(const char *Name) {
254 assert(isValidName(Name) && "Invalid custome metadata name!");
255 unsigned Count = MDHandlerNames.size();
256 assert(MDHandlerNames.count(Name) == 0 && "Already registered MDKind!");
257 return MDHandlerNames[Name] = Count + 1;
260 /// isValidName - Return true if Name is a valid custom metadata handler name.
261 bool MetadataContext::isValidName(const char *Name) {
268 unsigned Length = strlen(Name);
272 (isalnum(*Name) || *Name == '_' || *Name == '-' || *Name == '.')) {
281 /// getMDKind - Return metadata kind. If the requested metadata kind
282 /// is not registered then return 0.
283 unsigned MetadataContext::getMDKind(const char *Name) {
284 StringMap<unsigned>::iterator I = MDHandlerNames.find(Name);
285 if (I == MDHandlerNames.end()) {
286 assert(isValidName(Name) && "Invalid custome metadata name!");
290 return I->getValue();
293 /// addMD - Attach the metadata of given kind to an Instruction.
294 void MetadataContext::addMD(unsigned MDKind, MDNode *Node, Instruction *Inst) {
295 assert(Node && "Invalid null MDNode");
296 Inst->HasMetadata = true;
297 MDMapTy &Info = MetadataStore[Inst];
299 Info.push_back(std::make_pair(MDKind, Node));
300 MetadataStore.insert(std::make_pair(Inst, Info));
304 // If there is an entry for this MDKind then replace it.
305 for (unsigned i = 0, e = Info.size(); i != e; ++i) {
306 MDPairTy &P = Info[i];
307 if (P.first == MDKind) {
308 Info[i] = std::make_pair(MDKind, Node);
313 // Otherwise add a new entry.
314 Info.push_back(std::make_pair(MDKind, Node));
318 /// removeMD - Remove metadata of given kind attached with an instuction.
319 void MetadataContext::removeMD(unsigned Kind, Instruction *Inst) {
320 MDStoreTy::iterator I = MetadataStore.find(Inst);
321 if (I == MetadataStore.end())
324 MDMapTy &Info = I->second;
325 for (MDMapTy::iterator MI = Info.begin(), ME = Info.end(); MI != ME; ++MI) {
327 if (P.first == Kind) {
336 /// removeAllMetadata - Remove all metadata attached with an instruction.
337 void MetadataContext::removeAllMetadata(Instruction *Inst) {
338 MetadataStore.erase(Inst);
339 Inst->HasMetadata = false;
342 /// copyMD - If metadata is attached with Instruction In1 then attach
343 /// the same metadata to In2.
344 void MetadataContext::copyMD(Instruction *In1, Instruction *In2) {
345 assert(In1 && In2 && "Invalid instruction!");
346 MDMapTy &In1Info = MetadataStore[In1];
350 for (MDMapTy::iterator I = In1Info.begin(), E = In1Info.end(); I != E; ++I)
351 if (MDNode *MD = dyn_cast_or_null<MDNode>(I->second))
352 addMD(I->first, MD, In2);
355 /// getMD - Get the metadata of given kind attached to an Instruction.
356 /// If the metadata is not found then return 0.
357 MDNode *MetadataContext::getMD(unsigned MDKind, const Instruction *Inst) {
358 MDMapTy &Info = MetadataStore[Inst];
362 for (MDMapTy::iterator I = Info.begin(), E = Info.end(); I != E; ++I)
363 if (I->first == MDKind)
364 return dyn_cast_or_null<MDNode>(I->second);
368 /// getMDs - Get the metadata attached to an Instruction.
369 const MetadataContext::MDMapTy *
370 MetadataContext::getMDs(const Instruction *Inst) {
371 MDStoreTy::iterator I = MetadataStore.find(Inst);
372 if (I == MetadataStore.end())
378 /// getHandlerNames - Get handler names. This is used by bitcode
380 const StringMap<unsigned> *MetadataContext::getHandlerNames() {
381 return &MDHandlerNames;
384 /// ValueIsCloned - This handler is used to update metadata store
385 /// when In1 is cloned to create In2.
386 void MetadataContext::ValueIsCloned(const Instruction *In1, Instruction *In2) {
387 // Find Metadata handles for In1.
388 MDStoreTy::iterator I = MetadataStore.find(In1);
389 assert(I != MetadataStore.end() && "Invalid custom metadata info!");
391 // FIXME : Give all metadata handlers a chance to adjust.
393 MDMapTy &In1Info = I->second;
395 for (MDMapTy::iterator I = In1Info.begin(), E = In1Info.end(); I != E; ++I)
396 if (MDNode *MD = dyn_cast_or_null<MDNode>(I->second))
397 addMD(I->first, MD, In2);
400 /// ValueIsRAUWd - This handler is used when V1's all uses are replaced by
402 void MetadataContext::ValueIsRAUWd(Value *V1, Value *V2) {
403 Instruction *I1 = dyn_cast<Instruction>(V1);
404 Instruction *I2 = dyn_cast<Instruction>(V2);
408 // FIXME : Give custom handlers a chance to override this.
409 ValueIsCloned(I1, I2);