Fix getHandlerNames() interface. Now it populate clinet supplied small vector with...
[oota-llvm.git] / lib / VMCore / Metadata.cpp
1 //===-- Metadata.cpp - Implement Metadata classes -------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the Metadata classes.
11 //
12 //===----------------------------------------------------------------------===//
13
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"
20 using namespace llvm;
21
22 //===----------------------------------------------------------------------===//
23 // MetadataBase implementation.
24 //
25
26 //===----------------------------------------------------------------------===//
27 // MDString implementation.
28 //
29 MDString *MDString::get(LLVMContext &Context, StringRef Str) {
30   LLVMContextImpl *pImpl = Context.pImpl;
31   StringMapEntry<MDString *> &Entry = 
32     pImpl->MDStringCache.GetOrCreateValue(Str);
33   MDString *&S = Entry.getValue();
34   if (S) return S;
35   
36   return S = 
37     new MDString(Context, StringRef(Entry.getKeyData(), Entry.getKeyLength()));
38 }
39
40 //===----------------------------------------------------------------------===//
41 // MDNode implementation.
42 //
43 MDNode::MDNode(LLVMContext &C, Value *const *Vals, unsigned NumVals)
44   : MetadataBase(Type::getMetadataTy(C), Value::MDNodeVal) {
45   NodeSize = NumVals;
46   Node = new ElementVH[NodeSize];
47   ElementVH *Ptr = Node;
48   for (unsigned i = 0; i != NumVals; ++i) 
49     *Ptr++ = ElementVH(Vals[i], this);
50 }
51
52 void MDNode::Profile(FoldingSetNodeID &ID) const {
53   for (unsigned i = 0, e = getNumElements(); i != e; ++i)
54     ID.AddPointer(getElement(i));
55 }
56
57 MDNode *MDNode::get(LLVMContext &Context, Value*const* Vals, unsigned NumVals) {
58   LLVMContextImpl *pImpl = Context.pImpl;
59   FoldingSetNodeID ID;
60   for (unsigned i = 0; i != NumVals; ++i)
61     ID.AddPointer(Vals[i]);
62
63   void *InsertPoint;
64   MDNode *N;
65   {
66     N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint);
67   }  
68   if (N) return N;
69   
70   N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint);
71   if (!N) {
72     // InsertPoint will have been set by the FindNodeOrInsertPos call.
73     N = new MDNode(Context, Vals, NumVals);
74     pImpl->MDNodeSet.InsertNode(N, InsertPoint);
75   }
76
77   return N;
78 }
79
80 /// ~MDNode - Destroy MDNode.
81 MDNode::~MDNode() {
82   {
83     LLVMContextImpl *pImpl = getType()->getContext().pImpl;
84     pImpl->MDNodeSet.RemoveNode(this);
85   }
86   delete [] Node;
87   Node = NULL;
88 }
89
90 // Replace value from this node's element list.
91 void MDNode::replaceElement(Value *From, Value *To) {
92   if (From == To || !getType())
93     return;
94   LLVMContext &Context = getType()->getContext();
95   LLVMContextImpl *pImpl = Context.pImpl;
96
97   // Find value. This is a linear search, do something if it consumes 
98   // lot of time. It is possible that to have multiple instances of
99   // From in this MDNode's element list.
100   SmallVector<unsigned, 4> Indexes;
101   unsigned Index = 0;
102   for (unsigned i = 0, e = getNumElements(); i != e; ++i, ++Index) {
103     Value *V = getElement(i);
104     if (V && V == From) 
105       Indexes.push_back(Index);
106   }
107
108   if (Indexes.empty())
109     return;
110
111   // Remove "this" from the context map. 
112   pImpl->MDNodeSet.RemoveNode(this);
113
114   // Replace From element(s) in place.
115   for (SmallVector<unsigned, 4>::iterator I = Indexes.begin(), E = Indexes.end(); 
116        I != E; ++I) {
117     unsigned Index = *I;
118     Node[Index] = ElementVH(To, this);
119   }
120
121   // Insert updated "this" into the context's folding node set.
122   // If a node with same element list already exist then before inserting 
123   // updated "this" into the folding node set, replace all uses of existing 
124   // node with updated "this" node.
125   FoldingSetNodeID ID;
126   Profile(ID);
127   void *InsertPoint;
128   MDNode *N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint);
129
130   if (N) {
131     N->replaceAllUsesWith(this);
132     delete N;
133     N = 0;
134   }
135
136   N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint);
137   if (!N) {
138     // InsertPoint will have been set by the FindNodeOrInsertPos call.
139     N = this;
140     pImpl->MDNodeSet.InsertNode(N, InsertPoint);
141   }
142 }
143
144 //===----------------------------------------------------------------------===//
145 // NamedMDNode implementation.
146 //
147 NamedMDNode::NamedMDNode(LLVMContext &C, const Twine &N,
148                          MetadataBase *const *MDs, 
149                          unsigned NumMDs, Module *ParentModule)
150   : MetadataBase(Type::getMetadataTy(C), Value::NamedMDNodeVal), Parent(0) {
151   setName(N);
152
153   for (unsigned i = 0; i != NumMDs; ++i)
154     Node.push_back(WeakMetadataVH(MDs[i]));
155
156   if (ParentModule)
157     ParentModule->getNamedMDList().push_back(this);
158 }
159
160 NamedMDNode *NamedMDNode::Create(const NamedMDNode *NMD, Module *M) {
161   assert(NMD && "Invalid source NamedMDNode!");
162   SmallVector<MetadataBase *, 4> Elems;
163   for (unsigned i = 0, e = NMD->getNumElements(); i != e; ++i)
164     Elems.push_back(NMD->getElement(i));
165   return new NamedMDNode(NMD->getContext(), NMD->getName().data(),
166                          Elems.data(), Elems.size(), M);
167 }
168
169 /// eraseFromParent - Drop all references and remove the node from parent
170 /// module.
171 void NamedMDNode::eraseFromParent() {
172   getParent()->getNamedMDList().erase(this);
173 }
174
175 /// dropAllReferences - Remove all uses and clear node vector.
176 void NamedMDNode::dropAllReferences() {
177   Node.clear();
178 }
179
180 NamedMDNode::~NamedMDNode() {
181   dropAllReferences();
182 }
183
184 //===----------------------------------------------------------------------===//
185 // MetadataContext implementation.
186 //
187
188 /// registerMDKind - Register a new metadata kind and return its ID.
189 /// A metadata kind can be registered only once. 
190 unsigned MetadataContext::registerMDKind(StringRef Name) {
191   assert(isValidName(Name) && "Invalid custome metadata name!");
192   unsigned Count = MDHandlerNames.size();
193   assert(MDHandlerNames.count(Name) == 0 && "Already registered MDKind!");
194   return MDHandlerNames[Name] = Count + 1;
195 }
196
197 /// isValidName - Return true if Name is a valid custom metadata handler name.
198 bool MetadataContext::isValidName(StringRef MDName) {
199   if (MDName.empty())
200     return false;
201
202   if (!isalpha(MDName[0]))
203     return false;
204
205   for (StringRef::iterator I = MDName.begin() + 1, E = MDName.end(); I != E;
206        ++I) {
207     if (!isalnum(*I) && *I != '_' && *I != '-' && *I != '.')
208         return false;
209   }
210   return true;
211 }
212
213 /// getMDKind - Return metadata kind. If the requested metadata kind
214 /// is not registered then return 0.
215 unsigned MetadataContext::getMDKind(StringRef Name) const {
216   StringMap<unsigned>::const_iterator I = MDHandlerNames.find(Name);
217   if (I == MDHandlerNames.end()) {
218     assert(isValidName(Name) && "Invalid custome metadata name!");
219     return 0;
220   }
221
222   return I->getValue();
223 }
224
225 /// addMD - Attach the metadata of given kind to an Instruction.
226 void MetadataContext::addMD(unsigned MDKind, MDNode *Node, Instruction *Inst) {
227   assert(Node && "Invalid null MDNode");
228   Inst->HasMetadata = true;
229   MDMapTy &Info = MetadataStore[Inst];
230   if (Info.empty()) {
231     Info.push_back(std::make_pair(MDKind, Node));
232     MetadataStore.insert(std::make_pair(Inst, Info));
233     return;
234   }
235
236   // If there is an entry for this MDKind then replace it.
237   for (unsigned i = 0, e = Info.size(); i != e; ++i) {
238     MDPairTy &P = Info[i];
239     if (P.first == MDKind) {
240       Info[i] = std::make_pair(MDKind, Node);
241       return;
242     }
243   }
244
245   // Otherwise add a new entry.
246   Info.push_back(std::make_pair(MDKind, Node));
247 }
248
249 /// removeMD - Remove metadata of given kind attached with an instuction.
250 void MetadataContext::removeMD(unsigned Kind, Instruction *Inst) {
251   MDStoreTy::iterator I = MetadataStore.find(Inst);
252   if (I == MetadataStore.end())
253     return;
254
255   MDMapTy &Info = I->second;
256   for (MDMapTy::iterator MI = Info.begin(), ME = Info.end(); MI != ME; ++MI) {
257     MDPairTy &P = *MI;
258     if (P.first == Kind) {
259       Info.erase(MI);
260       return;
261     }
262   }
263 }
264   
265 /// removeAllMetadata - Remove all metadata attached with an instruction.
266 void MetadataContext::removeAllMetadata(Instruction *Inst) {
267   MetadataStore.erase(Inst);
268   Inst->HasMetadata = false;
269 }
270
271 /// copyMD - If metadata is attached with Instruction In1 then attach
272 /// the same metadata to In2.
273 void MetadataContext::copyMD(Instruction *In1, Instruction *In2) {
274   assert(In1 && In2 && "Invalid instruction!");
275   MDMapTy &In1Info = MetadataStore[In1];
276   if (In1Info.empty())
277     return;
278
279   for (MDMapTy::iterator I = In1Info.begin(), E = In1Info.end(); I != E; ++I)
280     if (MDNode *MD = dyn_cast_or_null<MDNode>(I->second))
281       addMD(I->first, MD, In2);
282 }
283
284 /// getMD - Get the metadata of given kind attached to an Instruction.
285 /// If the metadata is not found then return 0.
286 MDNode *MetadataContext::getMD(unsigned MDKind, const Instruction *Inst) {
287   MDMapTy &Info = MetadataStore[Inst];
288   if (Info.empty())
289     return NULL;
290
291   for (MDMapTy::iterator I = Info.begin(), E = Info.end(); I != E; ++I)
292     if (I->first == MDKind)
293       return dyn_cast_or_null<MDNode>(I->second);
294   return NULL;
295 }
296
297 /// getMDs - Get the metadata attached to an Instruction.
298 const MetadataContext::MDMapTy *
299 MetadataContext::getMDs(const Instruction *Inst) {
300   MDStoreTy::iterator I = MetadataStore.find(Inst);
301   if (I == MetadataStore.end())
302     return NULL;
303   
304   return &I->second;
305 }
306
307 /// getHandlerNames - Get handler names. This is used by bitcode
308 /// writer and aswm writer.
309 void MetadataContext::
310 getHandlerNames(SmallVectorImpl<std::pair<unsigned, StringRef> >&Names) const {
311   for (StringMap<unsigned>::const_iterator I = MDHandlerNames.begin(),
312          E = MDHandlerNames.end(); I != E; ++I) 
313     Names.push_back(std::make_pair(I->second, I->first()));
314 }
315
316 /// ValueIsCloned - This handler is used to update metadata store
317 /// when In1 is cloned to create In2.
318 void MetadataContext::ValueIsCloned(const Instruction *In1, Instruction *In2) {
319   // Find Metadata handles for In1.
320   MDStoreTy::iterator I = MetadataStore.find(In1);
321   assert(I != MetadataStore.end() && "Invalid custom metadata info!");
322
323   // FIXME : Give all metadata handlers a chance to adjust.
324
325   MDMapTy &In1Info = I->second;
326   MDMapTy In2Info;
327   for (MDMapTy::iterator I = In1Info.begin(), E = In1Info.end(); I != E; ++I)
328     if (MDNode *MD = dyn_cast_or_null<MDNode>(I->second))
329       addMD(I->first, MD, In2);
330 }
331
332 /// ValueIsRAUWd - This handler is used when V1's all uses are replaced by
333 /// V2.
334 void MetadataContext::ValueIsRAUWd(Value *V1, Value *V2) {
335   Instruction *I1 = dyn_cast<Instruction>(V1);
336   Instruction *I2 = dyn_cast<Instruction>(V2);
337   if (!I1 || !I2)
338     return;
339
340   // FIXME : Give custom handlers a chance to override this.
341   ValueIsCloned(I1, I2);
342 }
343