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