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