Fix DenseMap iterator constness.
[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 "llvm/ADT/DenseMap.h"
20 #include "llvm/ADT/StringMap.h"
21 #include "SymbolTableListTraitsImpl.h"
22 using namespace llvm;
23
24 //===----------------------------------------------------------------------===//
25 // MetadataBase implementation.
26 //
27
28 //===----------------------------------------------------------------------===//
29 // MDString implementation.
30 //
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) return S;
37   
38   return S = 
39     new MDString(Context, Entry.getKey());
40 }
41
42 //===----------------------------------------------------------------------===//
43 // MDNode implementation.
44 //
45 MDNode::MDNode(LLVMContext &C, Value *const *Vals, unsigned NumVals)
46   : MetadataBase(Type::getMetadataTy(C), Value::MDNodeVal) {
47   NodeSize = NumVals;
48   Node = new ElementVH[NodeSize];
49   ElementVH *Ptr = Node;
50   for (unsigned i = 0; i != NumVals; ++i) 
51     *Ptr++ = ElementVH(Vals[i], this);
52 }
53
54 void MDNode::Profile(FoldingSetNodeID &ID) const {
55   for (unsigned i = 0, e = getNumElements(); i != e; ++i)
56     ID.AddPointer(getElement(i));
57 }
58
59 MDNode *MDNode::get(LLVMContext &Context, Value*const* Vals, unsigned NumVals) {
60   LLVMContextImpl *pImpl = Context.pImpl;
61   FoldingSetNodeID ID;
62   for (unsigned i = 0; i != NumVals; ++i)
63     ID.AddPointer(Vals[i]);
64
65   void *InsertPoint;
66   MDNode *N;
67   {
68     N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint);
69   }  
70   if (N) return N;
71   
72   N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint);
73   if (!N) {
74     // InsertPoint will have been set by the FindNodeOrInsertPos call.
75     N = new MDNode(Context, Vals, NumVals);
76     pImpl->MDNodeSet.InsertNode(N, InsertPoint);
77   }
78
79   return N;
80 }
81
82 /// ~MDNode - Destroy MDNode.
83 MDNode::~MDNode() {
84   {
85     LLVMContextImpl *pImpl = getType()->getContext().pImpl;
86     pImpl->MDNodeSet.RemoveNode(this);
87   }
88   delete [] Node;
89   Node = NULL;
90 }
91
92 // Replace value from this node's element list.
93 void MDNode::replaceElement(Value *From, Value *To) {
94   if (From == To || !getType())
95     return;
96   LLVMContext &Context = getType()->getContext();
97   LLVMContextImpl *pImpl = Context.pImpl;
98
99   // Find value. This is a linear search, do something if it consumes 
100   // lot of time. It is possible that to have multiple instances of
101   // From in this MDNode's element list.
102   SmallVector<unsigned, 4> Indexes;
103   unsigned Index = 0;
104   for (unsigned i = 0, e = getNumElements(); i != e; ++i, ++Index) {
105     Value *V = getElement(i);
106     if (V && V == From) 
107       Indexes.push_back(Index);
108   }
109
110   if (Indexes.empty())
111     return;
112
113   // Remove "this" from the context map. 
114   pImpl->MDNodeSet.RemoveNode(this);
115
116   // Replace From element(s) in place.
117   for (SmallVector<unsigned, 4>::iterator I = Indexes.begin(), E = Indexes.end(); 
118        I != E; ++I) {
119     unsigned Index = *I;
120     Node[Index] = ElementVH(To, this);
121   }
122
123   // Insert updated "this" into the context's folding node set.
124   // If a node with same element list already exist then before inserting 
125   // updated "this" into the folding node set, replace all uses of existing 
126   // node with updated "this" node.
127   FoldingSetNodeID ID;
128   Profile(ID);
129   void *InsertPoint;
130   MDNode *N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint);
131
132   if (N) {
133     N->replaceAllUsesWith(this);
134     delete N;
135     N = 0;
136   }
137
138   N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint);
139   if (!N) {
140     // InsertPoint will have been set by the FindNodeOrInsertPos call.
141     N = this;
142     pImpl->MDNodeSet.InsertNode(N, InsertPoint);
143   }
144 }
145
146 //===----------------------------------------------------------------------===//
147 // NamedMDNode implementation.
148 //
149 NamedMDNode::NamedMDNode(LLVMContext &C, const Twine &N,
150                          MetadataBase *const *MDs, 
151                          unsigned NumMDs, Module *ParentModule)
152   : MetadataBase(Type::getMetadataTy(C), Value::NamedMDNodeVal), Parent(0) {
153   setName(N);
154
155   for (unsigned i = 0; i != NumMDs; ++i)
156     Node.push_back(TrackingVH<MetadataBase>(MDs[i]));
157
158   if (ParentModule)
159     ParentModule->getNamedMDList().push_back(this);
160 }
161
162 NamedMDNode *NamedMDNode::Create(const NamedMDNode *NMD, Module *M) {
163   assert(NMD && "Invalid source NamedMDNode!");
164   SmallVector<MetadataBase *, 4> Elems;
165   for (unsigned i = 0, e = NMD->getNumElements(); i != e; ++i)
166     Elems.push_back(NMD->getElement(i));
167   return new NamedMDNode(NMD->getContext(), NMD->getName().data(),
168                          Elems.data(), Elems.size(), M);
169 }
170
171 /// eraseFromParent - Drop all references and remove the node from parent
172 /// module.
173 void NamedMDNode::eraseFromParent() {
174   getParent()->getNamedMDList().erase(this);
175 }
176
177 /// dropAllReferences - Remove all uses and clear node vector.
178 void NamedMDNode::dropAllReferences() {
179   Node.clear();
180 }
181
182 NamedMDNode::~NamedMDNode() {
183   dropAllReferences();
184 }
185
186 //===----------------------------------------------------------------------===//
187 // MetadataContextImpl implementation.
188 //
189 namespace llvm {
190 class MetadataContextImpl {
191 public:
192   typedef std::pair<unsigned, TrackingVH<MDNode> > MDPairTy;
193   typedef SmallVector<MDPairTy, 2> MDMapTy;
194   typedef DenseMap<const Instruction *, MDMapTy> MDStoreTy;
195   friend class BitcodeReader;
196 private:
197
198   /// MetadataStore - Collection of metadata used in this context.
199   MDStoreTy MetadataStore;
200
201   /// MDHandlerNames - Map to hold metadata handler names.
202   StringMap<unsigned> MDHandlerNames;
203
204 public:
205   /// registerMDKind - Register a new metadata kind and return its ID.
206   /// A metadata kind can be registered only once. 
207   unsigned registerMDKind(StringRef Name);
208
209   /// getMDKind - Return metadata kind. If the requested metadata kind
210   /// is not registered then return 0.
211   unsigned getMDKind(StringRef Name) const;
212
213   /// getMD - Get the metadata of given kind attached to an Instruction.
214   /// If the metadata is not found then return 0.
215   MDNode *getMD(unsigned Kind, const Instruction *Inst);
216
217   /// getMDs - Get the metadata attached to an Instruction.
218   void getMDs(const Instruction *Inst, SmallVectorImpl<MDPairTy> &MDs) const;
219
220   /// addMD - Attach the metadata of given kind to an Instruction.
221   void addMD(unsigned Kind, MDNode *Node, Instruction *Inst);
222   
223   /// removeMD - Remove metadata of given kind attached with an instuction.
224   void removeMD(unsigned Kind, Instruction *Inst);
225   
226   /// removeAllMetadata - Remove all metadata attached with an instruction.
227   void removeAllMetadata(Instruction *Inst);
228
229   /// copyMD - If metadata is attached with Instruction In1 then attach
230   /// the same metadata to In2.
231   void copyMD(Instruction *In1, Instruction *In2);
232
233   /// getHandlerNames - Populate client supplied smallvector using custome
234   /// metadata name and ID.
235   void getHandlerNames(SmallVectorImpl<std::pair<unsigned, StringRef> >&) const;
236
237   /// ValueIsDeleted - This handler is used to update metadata store
238   /// when a value is deleted.
239   void ValueIsDeleted(const Value *) {}
240   void ValueIsDeleted(Instruction *Inst) {
241     removeAllMetadata(Inst);
242   }
243   void ValueIsRAUWd(Value *V1, Value *V2);
244
245   /// ValueIsCloned - This handler is used to update metadata store
246   /// when In1 is cloned to create In2.
247   void ValueIsCloned(const Instruction *In1, Instruction *In2);
248 };
249 }
250
251 /// registerMDKind - Register a new metadata kind and return its ID.
252 /// A metadata kind can be registered only once. 
253 unsigned MetadataContextImpl::registerMDKind(StringRef Name) {
254   unsigned Count = MDHandlerNames.size();
255   assert(MDHandlerNames.count(Name) == 0 && "Already registered MDKind!");
256   return MDHandlerNames[Name] = Count + 1;
257 }
258
259 /// getMDKind - Return metadata kind. If the requested metadata kind
260 /// is not registered then return 0.
261 unsigned MetadataContextImpl::getMDKind(StringRef Name) const {
262   StringMap<unsigned>::const_iterator I = MDHandlerNames.find(Name);
263   if (I == MDHandlerNames.end())
264     return 0;
265
266   return I->getValue();
267 }
268
269 /// addMD - Attach the metadata of given kind to an Instruction.
270 void MetadataContextImpl::addMD(unsigned MDKind, MDNode *Node, 
271                                 Instruction *Inst) {
272   assert(Node && "Invalid null MDNode");
273   Inst->HasMetadata = true;
274   MDMapTy &Info = MetadataStore[Inst];
275   if (Info.empty()) {
276     Info.push_back(std::make_pair(MDKind, Node));
277     MetadataStore.insert(std::make_pair(Inst, Info));
278     return;
279   }
280
281   // If there is an entry for this MDKind then replace it.
282   for (unsigned i = 0, e = Info.size(); i != e; ++i) {
283     MDPairTy &P = Info[i];
284     if (P.first == MDKind) {
285       Info[i] = std::make_pair(MDKind, Node);
286       return;
287     }
288   }
289
290   // Otherwise add a new entry.
291   Info.push_back(std::make_pair(MDKind, Node));
292 }
293
294 /// removeMD - Remove metadata of given kind attached with an instuction.
295 void MetadataContextImpl::removeMD(unsigned Kind, Instruction *Inst) {
296   MDStoreTy::iterator I = MetadataStore.find(Inst);
297   if (I == MetadataStore.end())
298     return;
299
300   MDMapTy &Info = I->second;
301   for (MDMapTy::iterator MI = Info.begin(), ME = Info.end(); MI != ME; ++MI) {
302     MDPairTy &P = *MI;
303     if (P.first == Kind) {
304       Info.erase(MI);
305       return;
306     }
307   }
308 }
309   
310 /// removeAllMetadata - Remove all metadata attached with an instruction.
311 void MetadataContextImpl::removeAllMetadata(Instruction *Inst) {
312   MetadataStore.erase(Inst);
313   Inst->HasMetadata = false;
314 }
315
316 /// copyMD - If metadata is attached with Instruction In1 then attach
317 /// the same metadata to In2.
318 void MetadataContextImpl::copyMD(Instruction *In1, Instruction *In2) {
319   assert(In1 && In2 && "Invalid instruction!");
320   MDMapTy &In1Info = MetadataStore[In1];
321   if (In1Info.empty())
322     return;
323
324   for (MDMapTy::iterator I = In1Info.begin(), E = In1Info.end(); I != E; ++I)
325     addMD(I->first, I->second, In2);
326 }
327
328 /// getMD - Get the metadata of given kind attached to an Instruction.
329 /// If the metadata is not found then return 0.
330 MDNode *MetadataContextImpl::getMD(unsigned MDKind, const Instruction *Inst) {
331   MDMapTy &Info = MetadataStore[Inst];
332   if (Info.empty())
333     return NULL;
334
335   for (MDMapTy::iterator I = Info.begin(), E = Info.end(); I != E; ++I)
336     if (I->first == MDKind)
337       return I->second;
338   return NULL;
339 }
340
341 /// getMDs - Get the metadata attached to an Instruction.
342 void MetadataContextImpl::
343 getMDs(const Instruction *Inst, SmallVectorImpl<MDPairTy> &MDs) const {
344   MDStoreTy::const_iterator I = MetadataStore.find(Inst);
345   if (I == MetadataStore.end())
346     return;
347   MDs.resize(I->second.size());
348   for (MDMapTy::const_iterator MI = I->second.begin(), ME = I->second.end();
349        MI != ME; ++MI)
350     // MD kinds are numbered from 1.
351     MDs[MI->first - 1] = std::make_pair(MI->first, MI->second);
352 }
353
354 /// getHandlerNames - Populate client supplied smallvector using custome
355 /// metadata name and ID.
356 void MetadataContextImpl::
357 getHandlerNames(SmallVectorImpl<std::pair<unsigned, StringRef> >&Names) const {
358   Names.resize(MDHandlerNames.size());
359   for (StringMap<unsigned>::const_iterator I = MDHandlerNames.begin(),
360          E = MDHandlerNames.end(); I != E; ++I) 
361     // MD Handlers are numbered from 1.
362     Names[I->second - 1] = std::make_pair(I->second, I->first());
363 }
364
365 /// ValueIsCloned - This handler is used to update metadata store
366 /// when In1 is cloned to create In2.
367 void MetadataContextImpl::ValueIsCloned(const Instruction *In1, 
368                                         Instruction *In2) {
369   // Find Metadata handles for In1.
370   MDStoreTy::iterator I = MetadataStore.find(In1);
371   assert(I != MetadataStore.end() && "Invalid custom metadata info!");
372
373   // FIXME : Give all metadata handlers a chance to adjust.
374
375   MDMapTy &In1Info = I->second;
376   MDMapTy In2Info;
377   for (MDMapTy::iterator I = In1Info.begin(), E = In1Info.end(); I != E; ++I)
378     addMD(I->first, I->second, In2);
379 }
380
381 /// ValueIsRAUWd - This handler is used when V1's all uses are replaced by
382 /// V2.
383 void MetadataContextImpl::ValueIsRAUWd(Value *V1, Value *V2) {
384   Instruction *I1 = dyn_cast<Instruction>(V1);
385   Instruction *I2 = dyn_cast<Instruction>(V2);
386   if (!I1 || !I2)
387     return;
388
389   // FIXME : Give custom handlers a chance to override this.
390   ValueIsCloned(I1, I2);
391 }
392
393 //===----------------------------------------------------------------------===//
394 // MetadataContext implementation.
395 //
396 MetadataContext::MetadataContext() 
397   : pImpl(new MetadataContextImpl()) { }
398 MetadataContext::~MetadataContext() { delete pImpl; }
399
400 /// isValidName - Return true if Name is a valid custom metadata handler name.
401 bool MetadataContext::isValidName(StringRef MDName) {
402   if (MDName.empty())
403     return false;
404
405   if (!isalpha(MDName[0]))
406     return false;
407
408   for (StringRef::iterator I = MDName.begin() + 1, E = MDName.end(); I != E;
409        ++I) {
410     if (!isalnum(*I) && *I != '_' && *I != '-' && *I != '.')
411         return false;
412   }
413   return true;
414 }
415
416 /// registerMDKind - Register a new metadata kind and return its ID.
417 /// A metadata kind can be registered only once. 
418 unsigned MetadataContext::registerMDKind(StringRef Name) {
419   assert(isValidName(Name) && "Invalid custome metadata name!");
420   return pImpl->registerMDKind(Name);
421 }
422
423 /// getMDKind - Return metadata kind. If the requested metadata kind
424 /// is not registered then return 0.
425 unsigned MetadataContext::getMDKind(StringRef Name) const {
426   return pImpl->getMDKind(Name);
427 }
428
429 /// getMD - Get the metadata of given kind attached to an Instruction.
430 /// If the metadata is not found then return 0.
431 MDNode *MetadataContext::getMD(unsigned Kind, const Instruction *Inst) {
432   return pImpl->getMD(Kind, Inst);
433 }
434
435 /// getMDs - Get the metadata attached to an Instruction.
436 void MetadataContext::
437 getMDs(const Instruction *Inst, 
438        SmallVectorImpl<std::pair<unsigned, TrackingVH<MDNode> > > &MDs) const {
439   return pImpl->getMDs(Inst, MDs);
440 }
441
442 /// addMD - Attach the metadata of given kind to an Instruction.
443 void MetadataContext::addMD(unsigned Kind, MDNode *Node, Instruction *Inst) {
444   pImpl->addMD(Kind, Node, Inst);
445 }
446   
447 /// removeMD - Remove metadata of given kind attached with an instuction.
448 void MetadataContext::removeMD(unsigned Kind, Instruction *Inst) {
449   pImpl->removeMD(Kind, Inst);
450 }
451   
452 /// removeAllMetadata - Remove all metadata attached with an instruction.
453 void MetadataContext::removeAllMetadata(Instruction *Inst) {
454   pImpl->removeAllMetadata(Inst);
455 }
456
457 /// copyMD - If metadata is attached with Instruction In1 then attach
458 /// the same metadata to In2.
459 void MetadataContext::copyMD(Instruction *In1, Instruction *In2) {
460   pImpl->copyMD(In1, In2);
461 }
462
463 /// getHandlerNames - Populate client supplied smallvector using custome
464 /// metadata name and ID.
465 void MetadataContext::
466 getHandlerNames(SmallVectorImpl<std::pair<unsigned, StringRef> >&N) const {
467   pImpl->getHandlerNames(N);
468 }
469
470 /// ValueIsDeleted - This handler is used to update metadata store
471 /// when a value is deleted.
472 void MetadataContext::ValueIsDeleted(Instruction *Inst) {
473   pImpl->ValueIsDeleted(Inst);
474 }
475 void MetadataContext::ValueIsRAUWd(Value *V1, Value *V2) {
476   pImpl->ValueIsRAUWd(V1, V2);
477 }
478
479 /// ValueIsCloned - This handler is used to update metadata store
480 /// when In1 is cloned to create In2.
481 void MetadataContext::ValueIsCloned(const Instruction *In1, Instruction *In2) {
482   pImpl->ValueIsCloned(In1, In2);
483 }