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