Remove MetadataBase class because it is not adding significant value.
[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 "llvm/ADT/SmallString.h"
22 #include "SymbolTableListTraitsImpl.h"
23 #include "llvm/Support/ValueHandle.h"
24 using namespace llvm;
25
26 //===----------------------------------------------------------------------===//
27 // MDString implementation.
28 //
29
30 MDString::MDString(LLVMContext &C, StringRef S)
31   : Value(Type::getMetadataTy(C), Value::MDStringVal), Str(S) {}
32
33 MDString *MDString::get(LLVMContext &Context, StringRef Str) {
34   LLVMContextImpl *pImpl = Context.pImpl;
35   StringMapEntry<MDString *> &Entry =
36     pImpl->MDStringCache.GetOrCreateValue(Str);
37   MDString *&S = Entry.getValue();
38   if (!S) S = new MDString(Context, Entry.getKey());
39   return S;
40 }
41
42 MDString *MDString::get(LLVMContext &Context, const char *Str) {
43   LLVMContextImpl *pImpl = Context.pImpl;
44   StringMapEntry<MDString *> &Entry =
45     pImpl->MDStringCache.GetOrCreateValue(Str ? StringRef(Str) : StringRef());
46   MDString *&S = Entry.getValue();
47   if (!S) S = new MDString(Context, Entry.getKey());
48   return S;
49 }
50
51 //===----------------------------------------------------------------------===//
52 // MDNodeOperand implementation.
53 //
54
55 // Use CallbackVH to hold MDNode operands.
56 namespace llvm {
57 class MDNodeOperand : public CallbackVH {
58   MDNode *Parent;
59 public:
60   MDNodeOperand(Value *V, MDNode *P) : CallbackVH(V), Parent(P) {}
61   ~MDNodeOperand() {}
62
63   void set(Value *V) {
64     setValPtr(V);
65   }
66
67   virtual void deleted();
68   virtual void allUsesReplacedWith(Value *NV);
69 };
70 } // end namespace llvm.
71
72
73 void MDNodeOperand::deleted() {
74   Parent->replaceOperand(this, 0);
75 }
76
77 void MDNodeOperand::allUsesReplacedWith(Value *NV) {
78   Parent->replaceOperand(this, NV);
79 }
80
81
82
83 //===----------------------------------------------------------------------===//
84 // MDNode implementation.
85 //
86
87 /// getOperandPtr - Helper function to get the MDNodeOperand's coallocated on
88 /// the end of the MDNode.
89 static MDNodeOperand *getOperandPtr(MDNode *N, unsigned Op) {
90   assert(Op < N->getNumOperands() && "Invalid operand number");
91   return reinterpret_cast<MDNodeOperand*>(N+1)+Op;
92 }
93
94 MDNode::MDNode(LLVMContext &C, Value *const *Vals, unsigned NumVals,
95                bool isFunctionLocal)
96 : Value(Type::getMetadataTy(C), Value::MDNodeVal) {
97   NumOperands = NumVals;
98
99   if (isFunctionLocal)
100     setValueSubclassData(getSubclassDataFromValue() | FunctionLocalBit);
101
102   // Initialize the operand list, which is co-allocated on the end of the node.
103   for (MDNodeOperand *Op = getOperandPtr(this, 0), *E = Op+NumOperands;
104        Op != E; ++Op, ++Vals)
105     new (Op) MDNodeOperand(*Vals, this);
106 }
107
108
109 /// ~MDNode - Destroy MDNode.
110 MDNode::~MDNode() {
111   assert((getSubclassDataFromValue() & DestroyFlag) != 0 &&
112          "Not being destroyed through destroy()?");
113   if (!isNotUniqued()) {
114     LLVMContextImpl *pImpl = getType()->getContext().pImpl;
115     pImpl->MDNodeSet.RemoveNode(this);
116   }
117
118   // Destroy the operands.
119   for (MDNodeOperand *Op = getOperandPtr(this, 0), *E = Op+NumOperands;
120        Op != E; ++Op)
121     Op->~MDNodeOperand();
122 }
123
124 static const Function *getFunctionForValue(Value *V) {
125   assert(!isa<MDNode>(V) && "does not iterate over metadata operands");
126   if (!V) return NULL;
127   if (Instruction *I = dyn_cast<Instruction>(V))
128     return I->getParent()->getParent();
129   if (BasicBlock *BB = dyn_cast<BasicBlock>(V))
130     return BB->getParent();
131   if (Argument *A = dyn_cast<Argument>(V))
132     return A->getParent();
133   return NULL;
134 }
135
136 #ifndef NDEBUG
137 static const Function *assertLocalFunction(const MDNode *N) {
138   if (!N->isFunctionLocal()) return 0;
139
140   const Function *F = 0, *NewF = 0;
141   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
142     if (Value *V = N->getOperand(i)) {
143       if (MDNode *MD = dyn_cast<MDNode>(V))
144         NewF = assertLocalFunction(MD);
145       else
146         NewF = getFunctionForValue(V);
147     }
148     if (F == 0)
149       F = NewF;
150     else 
151       assert((NewF == 0 || F == NewF) &&"inconsistent function-local metadata");
152   }
153   return F;
154 }
155 #endif
156
157 // getFunction - If this metadata is function-local and recursively has a
158 // function-local operand, return the first such operand's parent function.
159 // Otherwise, return null. getFunction() should not be used for performance-
160 // critical code because it recursively visits all the MDNode's operands.  
161 const Function *MDNode::getFunction() const {
162 #ifndef NDEBUG
163   return assertLocalFunction(this);
164 #endif
165   if (!isFunctionLocal()) return NULL;
166
167   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
168     if (Value *V = getOperand(i)) {
169       if (MDNode *MD = dyn_cast<MDNode>(V)) {
170         if (const Function *F = MD->getFunction())
171           return F;
172       } else {
173         return getFunctionForValue(V);
174       }
175     }
176   }
177   return NULL;
178 }
179
180 // destroy - Delete this node.  Only when there are no uses.
181 void MDNode::destroy() {
182   setValueSubclassData(getSubclassDataFromValue() | DestroyFlag);
183   // Placement delete, the free the memory.
184   this->~MDNode();
185   free(this);
186 }
187
188 MDNode *MDNode::getMDNode(LLVMContext &Context, Value *const *Vals,
189                           unsigned NumVals, FunctionLocalness FL) {
190   LLVMContextImpl *pImpl = Context.pImpl;
191   FoldingSetNodeID ID;
192   for (unsigned i = 0; i != NumVals; ++i)
193     ID.AddPointer(Vals[i]);
194
195   void *InsertPoint;
196   MDNode *N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint);
197   if (!N) {
198     bool isFunctionLocal = false;
199     switch (FL) {
200     case FL_Unknown:
201       for (unsigned i = 0; i != NumVals; ++i) {
202         Value *V = Vals[i];
203         if (!V) continue;
204         if (isa<Instruction>(V) || isa<Argument>(V) || isa<BasicBlock>(V) ||
205             (isa<MDNode>(V) && cast<MDNode>(V)->isFunctionLocal())) {
206           isFunctionLocal = true;
207           break;
208         }
209       }
210       break;
211     case FL_No:
212       isFunctionLocal = false;
213       break;
214     case FL_Yes:
215       isFunctionLocal = true;
216       break;
217     }
218
219     // Coallocate space for the node and Operands together, then placement new.
220     void *Ptr = malloc(sizeof(MDNode)+NumVals*sizeof(MDNodeOperand));
221     N = new (Ptr) MDNode(Context, Vals, NumVals, isFunctionLocal);
222
223     // InsertPoint will have been set by the FindNodeOrInsertPos call.
224     pImpl->MDNodeSet.InsertNode(N, InsertPoint);
225   }
226   return N;
227 }
228
229 MDNode *MDNode::get(LLVMContext &Context, Value*const* Vals, unsigned NumVals) {
230   return getMDNode(Context, Vals, NumVals, FL_Unknown);
231 }
232
233 MDNode *MDNode::getWhenValsUnresolved(LLVMContext &Context, Value*const* Vals,
234                                       unsigned NumVals, bool isFunctionLocal) {
235   return getMDNode(Context, Vals, NumVals, isFunctionLocal ? FL_Yes : FL_No);
236 }
237
238 /// getOperand - Return specified operand.
239 Value *MDNode::getOperand(unsigned i) const {
240   return *getOperandPtr(const_cast<MDNode*>(this), i);
241 }
242
243 void MDNode::Profile(FoldingSetNodeID &ID) const {
244   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
245     ID.AddPointer(getOperand(i));
246 }
247
248
249 // Replace value from this node's operand list.
250 void MDNode::replaceOperand(MDNodeOperand *Op, Value *To) {
251   Value *From = *Op;
252
253   if (From == To)
254     return;
255
256   // Update the operand.
257   Op->set(To);
258
259   // If this node is already not being uniqued (because one of the operands
260   // already went to null), then there is nothing else to do here.
261   if (isNotUniqued()) return;
262
263   LLVMContextImpl *pImpl = getType()->getContext().pImpl;
264
265   // Remove "this" from the context map.  FoldingSet doesn't have to reprofile
266   // this node to remove it, so we don't care what state the operands are in.
267   pImpl->MDNodeSet.RemoveNode(this);
268
269   // If we are dropping an argument to null, we choose to not unique the MDNode
270   // anymore.  This commonly occurs during destruction, and uniquing these
271   // brings little reuse.
272   if (To == 0) {
273     setIsNotUniqued();
274     return;
275   }
276
277   // Now that the node is out of the folding set, get ready to reinsert it.
278   // First, check to see if another node with the same operands already exists
279   // in the set.  If it doesn't exist, this returns the position to insert it.
280   FoldingSetNodeID ID;
281   Profile(ID);
282   void *InsertPoint;
283   MDNode *N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint);
284
285   if (N) {
286     N->replaceAllUsesWith(this);
287     N->destroy();
288     N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint);
289     assert(N == 0 && "shouldn't be in the map now!"); (void)N;
290   }
291
292   // InsertPoint will have been set by the FindNodeOrInsertPos call.
293   pImpl->MDNodeSet.InsertNode(this, InsertPoint);
294 }
295
296 //===----------------------------------------------------------------------===//
297 // NamedMDNode implementation.
298 //
299
300 namespace llvm {
301 // SymbolTableListTraits specialization for MDSymbolTable.
302 void ilist_traits<NamedMDNode>
303 ::addNodeToList(NamedMDNode *N) {
304   assert(N->getParent() == 0 && "Value already in a container!!");
305   Module *Owner = getListOwner();
306   N->setParent(Owner);
307   MDSymbolTable &ST = Owner->getMDSymbolTable();
308   ST.insert(N->getName(), N);
309 }
310
311 void ilist_traits<NamedMDNode>::removeNodeFromList(NamedMDNode *N) {
312   N->setParent(0);
313   Module *Owner = getListOwner();
314   MDSymbolTable &ST = Owner->getMDSymbolTable();
315   ST.remove(N->getName());
316 }
317 }
318
319 static SmallVector<WeakVH, 4> &getNMDOps(void *Operands) {
320   return *(SmallVector<WeakVH, 4>*)Operands;
321 }
322
323 NamedMDNode::NamedMDNode(LLVMContext &C, const Twine &N,
324                          MDNode *const *MDs,
325                          unsigned NumMDs, Module *ParentModule)
326   : Value(Type::getMetadataTy(C), Value::NamedMDNodeVal), Parent(0) {
327   setName(N);
328   Operands = new SmallVector<WeakVH, 4>();
329
330   SmallVector<WeakVH, 4> &Node = getNMDOps(Operands);
331   for (unsigned i = 0; i != NumMDs; ++i)
332     Node.push_back(WeakVH(MDs[i]));
333
334   if (ParentModule)
335     ParentModule->getNamedMDList().push_back(this);
336 }
337
338 NamedMDNode *NamedMDNode::Create(const NamedMDNode *NMD, Module *M) {
339   assert(NMD && "Invalid source NamedMDNode!");
340   SmallVector<MDNode *, 4> Elems;
341   Elems.reserve(NMD->getNumOperands());
342
343   for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i)
344     Elems.push_back(NMD->getOperand(i));
345   return new NamedMDNode(NMD->getContext(), NMD->getName().data(),
346                          Elems.data(), Elems.size(), M);
347 }
348
349 NamedMDNode::~NamedMDNode() {
350   dropAllReferences();
351   delete &getNMDOps(Operands);
352 }
353
354 /// getNumOperands - Return number of NamedMDNode operands.
355 unsigned NamedMDNode::getNumOperands() const {
356   return (unsigned)getNMDOps(Operands).size();
357 }
358
359 /// getOperand - Return specified operand.
360 MDNode *NamedMDNode::getOperand(unsigned i) const {
361   assert(i < getNumOperands() && "Invalid Operand number!");
362   return dyn_cast_or_null<MDNode>(getNMDOps(Operands)[i]);
363 }
364
365 /// addOperand - Add metadata Operand.
366 void NamedMDNode::addOperand(MDNode *M) {
367   getNMDOps(Operands).push_back(WeakVH(M));
368 }
369
370 /// eraseFromParent - Drop all references and remove the node from parent
371 /// module.
372 void NamedMDNode::eraseFromParent() {
373   getParent()->getNamedMDList().erase(this);
374 }
375
376 /// dropAllReferences - Remove all uses and clear node vector.
377 void NamedMDNode::dropAllReferences() {
378   getNMDOps(Operands).clear();
379 }
380
381 /// setName - Set the name of this named metadata.
382 void NamedMDNode::setName(const Twine &NewName) {
383   assert (!NewName.isTriviallyEmpty() && "Invalid named metadata name!");
384
385   SmallString<256> NameData;
386   StringRef NameRef = NewName.toStringRef(NameData);
387
388   // Name isn't changing?
389   if (getName() == NameRef)
390     return;
391
392   Name = NameRef.str();
393   if (Parent)
394     Parent->getMDSymbolTable().insert(NameRef, this);
395 }
396
397 /// getName - Return a constant reference to this named metadata's name.
398 StringRef NamedMDNode::getName() const {
399   return StringRef(Name);
400 }
401
402 //===----------------------------------------------------------------------===//
403 // LLVMContext MDKind naming implementation.
404 //
405
406 #ifndef NDEBUG
407 /// isValidName - Return true if Name is a valid custom metadata handler name.
408 static bool isValidName(StringRef MDName) {
409   if (MDName.empty())
410     return false;
411
412   if (!isalpha(MDName[0]))
413     return false;
414
415   for (StringRef::iterator I = MDName.begin() + 1, E = MDName.end(); I != E;
416        ++I) {
417     if (!isalnum(*I) && *I != '_' && *I != '-' && *I != '.')
418         return false;
419   }
420   return true;
421 }
422 #endif
423
424 /// getMDKindID - Return a unique non-zero ID for the specified metadata kind.
425 unsigned LLVMContext::getMDKindID(StringRef Name) const {
426   assert(isValidName(Name) && "Invalid MDNode name");
427
428   unsigned &Entry = pImpl->CustomMDKindNames[Name];
429
430   // If this is new, assign it its ID.
431   if (Entry == 0) Entry = pImpl->CustomMDKindNames.size();
432   return Entry;
433 }
434
435 /// getHandlerNames - Populate client supplied smallvector using custome
436 /// metadata name and ID.
437 void LLVMContext::getMDKindNames(SmallVectorImpl<StringRef> &Names) const {
438   Names.resize(pImpl->CustomMDKindNames.size()+1);
439   Names[0] = "";
440   for (StringMap<unsigned>::const_iterator I = pImpl->CustomMDKindNames.begin(),
441        E = pImpl->CustomMDKindNames.end(); I != E; ++I)
442     // MD Handlers are numbered from 1.
443     Names[I->second] = I->first();
444 }
445
446 //===----------------------------------------------------------------------===//
447 // Instruction Metadata method implementations.
448 //
449
450 void Instruction::setMetadata(const char *Kind, MDNode *Node) {
451   if (Node == 0 && !hasMetadata()) return;
452   setMetadata(getContext().getMDKindID(Kind), Node);
453 }
454
455 MDNode *Instruction::getMetadataImpl(const char *Kind) const {
456   return getMetadataImpl(getContext().getMDKindID(Kind));
457 }
458
459 /// setMetadata - Set the metadata of of the specified kind to the specified
460 /// node.  This updates/replaces metadata if already present, or removes it if
461 /// Node is null.
462 void Instruction::setMetadata(unsigned KindID, MDNode *Node) {
463   if (Node == 0 && !hasMetadata()) return;
464
465   // Handle the case when we're adding/updating metadata on an instruction.
466   if (Node) {
467     LLVMContextImpl::MDMapTy &Info = getContext().pImpl->MetadataStore[this];
468     assert(!Info.empty() == hasMetadata() && "HasMetadata bit is wonked");
469     if (Info.empty()) {
470       setHasMetadata(true);
471     } else {
472       // Handle replacement of an existing value.
473       for (unsigned i = 0, e = Info.size(); i != e; ++i)
474         if (Info[i].first == KindID) {
475           Info[i].second = Node;
476           return;
477         }
478     }
479
480     // No replacement, just add it to the list.
481     Info.push_back(std::make_pair(KindID, Node));
482     return;
483   }
484
485   // Otherwise, we're removing metadata from an instruction.
486   assert(hasMetadata() && getContext().pImpl->MetadataStore.count(this) &&
487          "HasMetadata bit out of date!");
488   LLVMContextImpl::MDMapTy &Info = getContext().pImpl->MetadataStore[this];
489
490   // Common case is removing the only entry.
491   if (Info.size() == 1 && Info[0].first == KindID) {
492     getContext().pImpl->MetadataStore.erase(this);
493     setHasMetadata(false);
494     return;
495   }
496
497   // Handle replacement of an existing value.
498   for (unsigned i = 0, e = Info.size(); i != e; ++i)
499     if (Info[i].first == KindID) {
500       Info[i] = Info.back();
501       Info.pop_back();
502       assert(!Info.empty() && "Removing last entry should be handled above");
503       return;
504     }
505   // Otherwise, removing an entry that doesn't exist on the instruction.
506 }
507
508 MDNode *Instruction::getMetadataImpl(unsigned KindID) const {
509   LLVMContextImpl::MDMapTy &Info = getContext().pImpl->MetadataStore[this];
510   assert(hasMetadata() && !Info.empty() && "Shouldn't have called this");
511
512   for (LLVMContextImpl::MDMapTy::iterator I = Info.begin(), E = Info.end();
513        I != E; ++I)
514     if (I->first == KindID)
515       return I->second;
516   return 0;
517 }
518
519 void Instruction::getAllMetadataImpl(SmallVectorImpl<std::pair<unsigned,
520                                        MDNode*> > &Result)const {
521   assert(hasMetadata() && getContext().pImpl->MetadataStore.count(this) &&
522          "Shouldn't have called this");
523   const LLVMContextImpl::MDMapTy &Info =
524     getContext().pImpl->MetadataStore.find(this)->second;
525   assert(!Info.empty() && "Shouldn't have called this");
526
527   Result.clear();
528   Result.append(Info.begin(), Info.end());
529
530   // Sort the resulting array so it is stable.
531   if (Result.size() > 1)
532     array_pod_sort(Result.begin(), Result.end());
533 }
534
535 /// removeAllMetadata - Remove all metadata from this instruction.
536 void Instruction::removeAllMetadata() {
537   assert(hasMetadata() && "Caller should check");
538   getContext().pImpl->MetadataStore.erase(this);
539   setHasMetadata(false);
540 }
541