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