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