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