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