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