move ElementVH out of the MDNode class into the MDNode.cpp file. Among
[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) S = new MDString(Context, Entry.getKey());
37   return S;
38 }
39
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());
46   return S;
47 }
48
49 //===----------------------------------------------------------------------===//
50 // MDNodeElement implementation.
51 //
52
53 // Use CallbackVH to hold MDNode elements.
54 namespace llvm {
55 class MDNodeElement : public CallbackVH {
56   MDNode *Parent;
57 public:
58   MDNodeElement() {}
59   MDNodeElement(Value *V, MDNode *P) : CallbackVH(V), Parent(P) {}
60   ~MDNodeElement() {}
61   
62   virtual void deleted();
63   virtual void allUsesReplacedWith(Value *NV);
64 };
65 } // end namespace llvm.
66
67
68 void MDNodeElement::deleted() {
69   Parent->replaceElement(this->operator Value*(), 0);
70 }
71
72 void MDNodeElement::allUsesReplacedWith(Value *NV) {
73   Parent->replaceElement(this->operator Value*(), NV);
74 }
75
76
77
78 //===----------------------------------------------------------------------===//
79 // MDNode implementation.
80 //
81
82 MDNode::MDNode(LLVMContext &C, Value *const *Vals, unsigned NumVals,
83                bool isFunctionLocal)
84   : MetadataBase(Type::getMetadataTy(C), Value::MDNodeVal) {
85   NodeSize = NumVals;
86   Node = new MDNodeElement[NodeSize];
87   MDNodeElement *Ptr = Node;
88   for (unsigned i = 0; i != NumVals; ++i) 
89     *Ptr++ = MDNodeElement(Vals[i], this);
90   if (isFunctionLocal)
91     SubclassData |= FunctionLocalBit;
92 }
93
94 void MDNode::Profile(FoldingSetNodeID &ID) const {
95   for (unsigned i = 0, e = getNumElements(); i != e; ++i)
96     ID.AddPointer(getElement(i));
97 }
98
99 MDNode *MDNode::get(LLVMContext &Context, Value*const* Vals, unsigned NumVals,
100                     bool isFunctionLocal) {
101   LLVMContextImpl *pImpl = Context.pImpl;
102   FoldingSetNodeID ID;
103   for (unsigned i = 0; i != NumVals; ++i)
104     ID.AddPointer(Vals[i]);
105
106   void *InsertPoint;
107   MDNode *N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint);
108   if (!N) {
109     // InsertPoint will have been set by the FindNodeOrInsertPos call.
110     N = new MDNode(Context, Vals, NumVals, isFunctionLocal);
111     pImpl->MDNodeSet.InsertNode(N, InsertPoint);
112   }
113   return N;
114 }
115
116 /// ~MDNode - Destroy MDNode.
117 MDNode::~MDNode() {
118   LLVMContextImpl *pImpl = getType()->getContext().pImpl;
119   pImpl->MDNodeSet.RemoveNode(this);
120   delete [] Node;
121   Node = NULL;
122 }
123
124 /// getElement - Return specified element.
125 Value *MDNode::getElement(unsigned i) const {
126   assert(i < getNumElements() && "Invalid element number!");
127   return Node[i];
128 }
129
130
131
132 // Replace value from this node's element list.
133 void MDNode::replaceElement(Value *From, Value *To) {
134   if (From == To || !getType())
135     return;
136   LLVMContext &Context = getType()->getContext();
137   LLVMContextImpl *pImpl = Context.pImpl;
138
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;
143   unsigned Index = 0;
144   for (unsigned i = 0, e = getNumElements(); i != e; ++i, ++Index) {
145     Value *V = getElement(i);
146     if (V && V == From) 
147       Indexes.push_back(Index);
148   }
149
150   if (Indexes.empty())
151     return;
152
153   // Remove "this" from the context map. 
154   pImpl->MDNodeSet.RemoveNode(this);
155
156   // Replace From element(s) in place.
157   for (SmallVector<unsigned, 4>::iterator I = Indexes.begin(), E = Indexes.end(); 
158        I != E; ++I) {
159     unsigned Index = *I;
160     Node[Index] = MDNodeElement(To, this);
161   }
162
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.
167   FoldingSetNodeID ID;
168   Profile(ID);
169   void *InsertPoint;
170   MDNode *N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint);
171
172   if (N) {
173     N->replaceAllUsesWith(this);
174     delete N;
175     N = 0;
176   }
177
178   N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint);
179   if (!N) {
180     // InsertPoint will have been set by the FindNodeOrInsertPos call.
181     N = this;
182     pImpl->MDNodeSet.InsertNode(N, InsertPoint);
183   }
184 }
185
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())
192     return true;
193     
194   if (!VisitedMDNodes)
195     VisitedMDNodes = new SmallPtrSet<MDNode *, 32>();
196     
197   if (!VisitedMDNodes->insert(this))
198     // MDNode has already been visited, nothing to do.
199     return true;
200
201   for (unsigned i = 0, e = getNumElements(); i != e; ++i) {
202     Value *V = getElement(i);
203     if (!V) continue;
204
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.
212         return false;
213
214     if (LocalFunctionTemp) {
215       if (!LocalFunction)
216         LocalFunction = LocalFunctionTemp;
217       else if (LocalFunction != LocalFunctionTemp)
218         // This MDNode contains operands that are local to different functions.
219         return false;
220     }
221   }
222     
223   return true;
224 }
225
226 //===----------------------------------------------------------------------===//
227 // NamedMDNode implementation.
228 //
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) {
233   setName(N);
234
235   for (unsigned i = 0; i != NumMDs; ++i)
236     Node.push_back(TrackingVH<MetadataBase>(MDs[i]));
237
238   if (ParentModule)
239     ParentModule->getNamedMDList().push_back(this);
240 }
241
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);
249 }
250
251 /// eraseFromParent - Drop all references and remove the node from parent
252 /// module.
253 void NamedMDNode::eraseFromParent() {
254   getParent()->getNamedMDList().erase(this);
255 }
256
257 /// dropAllReferences - Remove all uses and clear node vector.
258 void NamedMDNode::dropAllReferences() {
259   Node.clear();
260 }
261
262 NamedMDNode::~NamedMDNode() {
263   dropAllReferences();
264 }
265
266 //===----------------------------------------------------------------------===//
267 // MetadataContextImpl implementation.
268 //
269 namespace llvm {
270 class MetadataContextImpl {
271 public:
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;
276 private:
277
278   /// MetadataStore - Collection of metadata used in this context.
279   MDStoreTy MetadataStore;
280
281   /// MDHandlerNames - Map to hold metadata handler names.
282   StringMap<unsigned> MDHandlerNames;
283
284 public:
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);
288
289   /// getMDKind - Return metadata kind. If the requested metadata kind
290   /// is not registered then return 0.
291   unsigned getMDKind(StringRef Name) const;
292
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);
296
297   /// getMDs - Get the metadata attached to an Instruction.
298   void getMDs(const Instruction *Inst, SmallVectorImpl<MDPairTy> &MDs) const;
299
300   /// addMD - Attach the metadata of given kind to an Instruction.
301   void addMD(unsigned Kind, MDNode *Node, Instruction *Inst);
302   
303   /// removeMD - Remove metadata of given kind attached with an instruction.
304   void removeMD(unsigned Kind, Instruction *Inst);
305   
306   /// removeAllMetadata - Remove all metadata attached with an instruction.
307   void removeAllMetadata(Instruction *Inst);
308
309   /// copyMD - If metadata is attached with Instruction In1 then attach
310   /// the same metadata to In2.
311   void copyMD(Instruction *In1, Instruction *In2);
312
313   /// getHandlerNames - Populate client-supplied smallvector using custom
314   /// metadata name and ID.
315   void getHandlerNames(SmallVectorImpl<std::pair<unsigned, StringRef> >&) const;
316
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);
322   }
323   void ValueIsRAUWd(Value *V1, Value *V2);
324
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);
328 };
329 }
330
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;
337 }
338
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())
344     return 0;
345
346   return I->getValue();
347 }
348
349 /// addMD - Attach the metadata of given kind to an Instruction.
350 void MetadataContextImpl::addMD(unsigned MDKind, MDNode *Node, 
351                                 Instruction *Inst) {
352   assert(Node && "Invalid null MDNode");
353   Inst->HasMetadata = true;
354   MDMapTy &Info = MetadataStore[Inst];
355   if (Info.empty()) {
356     Info.push_back(std::make_pair(MDKind, Node));
357     MetadataStore.insert(std::make_pair(Inst, Info));
358     return;
359   }
360
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);
366       return;
367     }
368   }
369
370   // Otherwise add a new entry.
371   Info.push_back(std::make_pair(MDKind, Node));
372 }
373
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())
378     return;
379
380   MDMapTy &Info = I->second;
381   for (MDMapTy::iterator MI = Info.begin(), ME = Info.end(); MI != ME; ++MI) {
382     MDPairTy &P = *MI;
383     if (P.first == Kind) {
384       Info.erase(MI);
385       return;
386     }
387   }
388 }
389
390 /// removeAllMetadata - Remove all metadata attached with an instruction.
391 void MetadataContextImpl::removeAllMetadata(Instruction *Inst) {
392   MetadataStore.erase(Inst);
393   Inst->HasMetadata = false;
394 }
395
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];
401   if (In1Info.empty())
402     return;
403
404   for (MDMapTy::iterator I = In1Info.begin(), E = In1Info.end(); I != E; ++I)
405     addMD(I->first, I->second, In2);
406 }
407
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];
412   if (Info.empty())
413     return NULL;
414
415   for (MDMapTy::iterator I = Info.begin(), E = Info.end(); I != E; ++I)
416     if (I->first == MDKind)
417       return I->second;
418   return NULL;
419 }
420
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())
426     return;
427   MDs.resize(I->second.size());
428   for (MDMapTy::const_iterator MI = I->second.begin(), ME = I->second.end();
429        MI != ME; ++MI)
430     // MD kinds are numbered from 1.
431     MDs[MI->first - 1] = std::make_pair(MI->first, MI->second);
432 }
433
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());
443 }
444
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, 
448                                         Instruction *In2) {
449   // Find Metadata handles for In1.
450   MDStoreTy::iterator I = MetadataStore.find(In1);
451   assert(I != MetadataStore.end() && "Invalid custom metadata info!");
452
453   // FIXME : Give all metadata handlers a chance to adjust.
454
455   MDMapTy &In1Info = I->second;
456   MDMapTy In2Info;
457   for (MDMapTy::iterator I = In1Info.begin(), E = In1Info.end(); I != E; ++I)
458     addMD(I->first, I->second, In2);
459 }
460
461 /// ValueIsRAUWd - This handler is used when V1's all uses are replaced by
462 /// V2.
463 void MetadataContextImpl::ValueIsRAUWd(Value *V1, Value *V2) {
464   Instruction *I1 = dyn_cast<Instruction>(V1);
465   Instruction *I2 = dyn_cast<Instruction>(V2);
466   if (!I1 || !I2)
467     return;
468
469   // FIXME : Give custom handlers a chance to override this.
470   ValueIsCloned(I1, I2);
471 }
472
473 //===----------------------------------------------------------------------===//
474 // MetadataContext implementation.
475 //
476 MetadataContext::MetadataContext() 
477   : pImpl(new MetadataContextImpl()) { }
478 MetadataContext::~MetadataContext() { delete pImpl; }
479
480 /// isValidName - Return true if Name is a valid custom metadata handler name.
481 bool MetadataContext::isValidName(StringRef MDName) {
482   if (MDName.empty())
483     return false;
484
485   if (!isalpha(MDName[0]))
486     return false;
487
488   for (StringRef::iterator I = MDName.begin() + 1, E = MDName.end(); I != E;
489        ++I) {
490     if (!isalnum(*I) && *I != '_' && *I != '-' && *I != '.')
491         return false;
492   }
493   return true;
494 }
495
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);
501 }
502
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);
507 }
508
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);
513 }
514
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);
520 }
521
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);
525 }
526
527 /// removeMD - Remove metadata of given kind attached with an instruction.
528 void MetadataContext::removeMD(unsigned Kind, Instruction *Inst) {
529   pImpl->removeMD(Kind, Inst);
530 }
531
532 /// removeAllMetadata - Remove all metadata attached with an instruction.
533 void MetadataContext::removeAllMetadata(Instruction *Inst) {
534   pImpl->removeAllMetadata(Inst);
535 }
536
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);
541 }
542
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);
548 }
549
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);
554 }
555 void MetadataContext::ValueIsRAUWd(Value *V1, Value *V2) {
556   pImpl->ValueIsRAUWd(V1, V2);
557 }
558
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);
563 }