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