Add MDNode::getFunction(), which figures out the metadata's function, if it has funct...
[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   : MetadataBase(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 MDString *MDString::get(LLVMContext &Context, const char *Str) {
43   LLVMContextImpl *pImpl = Context.pImpl;
44   StringMapEntry<MDString *> &Entry =
45     pImpl->MDStringCache.GetOrCreateValue(Str ? StringRef(Str) : StringRef());
46   MDString *&S = Entry.getValue();
47   if (!S) S = new MDString(Context, Entry.getKey());
48   return S;
49 }
50
51 //===----------------------------------------------------------------------===//
52 // MDNodeOperand implementation.
53 //
54
55 // Use CallbackVH to hold MDNode operands.
56 namespace llvm {
57 class MDNodeOperand : public CallbackVH {
58   MDNode *Parent;
59 public:
60   MDNodeOperand(Value *V, MDNode *P) : CallbackVH(V), Parent(P) {}
61   ~MDNodeOperand() {}
62
63   void set(Value *V) {
64     setValPtr(V);
65   }
66
67   virtual void deleted();
68   virtual void allUsesReplacedWith(Value *NV);
69 };
70 } // end namespace llvm.
71
72
73 void MDNodeOperand::deleted() {
74   Parent->replaceOperand(this, 0);
75 }
76
77 void MDNodeOperand::allUsesReplacedWith(Value *NV) {
78   Parent->replaceOperand(this, NV);
79 }
80
81
82
83 //===----------------------------------------------------------------------===//
84 // MDNode implementation.
85 //
86
87 /// getOperandPtr - Helper function to get the MDNodeOperand's coallocated on
88 /// the end of the MDNode.
89 static MDNodeOperand *getOperandPtr(MDNode *N, unsigned Op) {
90   assert(Op < N->getNumOperands() && "Invalid operand number");
91   return reinterpret_cast<MDNodeOperand*>(N+1)+Op;
92 }
93
94 MDNode::MDNode(LLVMContext &C, Value *const *Vals, unsigned NumVals,
95                bool isFunctionLocal)
96 : MetadataBase(Type::getMetadataTy(C), Value::MDNodeVal) {
97   NumOperands = NumVals;
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   for (MDNodeOperand *Op = getOperandPtr(this, 0), *E = Op+NumOperands;
104        Op != E; ++Op, ++Vals)
105     new (Op) MDNodeOperand(*Vals, this);
106 }
107
108
109 /// ~MDNode - Destroy MDNode.
110 MDNode::~MDNode() {
111   assert((getSubclassDataFromValue() & DestroyFlag) != 0 &&
112          "Not being destroyed through destroy()?");
113   if (!isNotUniqued()) {
114     LLVMContextImpl *pImpl = getType()->getContext().pImpl;
115     pImpl->MDNodeSet.RemoveNode(this);
116   }
117
118   // Destroy the operands.
119   for (MDNodeOperand *Op = getOperandPtr(this, 0), *E = Op+NumOperands;
120        Op != E; ++Op)
121     Op->~MDNodeOperand();
122 }
123
124 static Function *getFunctionHelper(const MDNode *N,
125                                    SmallPtrSet<const MDNode *, 32> &Visited) {
126   assert(N->isFunctionLocal() && "Should only be called on function-local MD");
127   Function *F = NULL;
128   // Only visit each MDNode once.
129   if (!Visited.insert(N)) return F;
130   
131   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
132     Value *V = N->getOperand(i);
133     if (!V) continue;
134     if (Instruction *I = dyn_cast<Instruction>(V))
135       F = I->getParent()->getParent();
136     else if (BasicBlock *BB = dyn_cast<BasicBlock>(V))
137       F = BB->getParent();
138     else if (Argument *A = dyn_cast<Argument>(V))
139       F = A->getParent();
140     else if (MDNode *MD = dyn_cast<MDNode>(V))
141       if (MD->isFunctionLocal())
142         F = getFunctionHelper(MD, Visited);
143     if (F) break;
144   }
145   
146   return F;
147 }
148
149 // getFunction - If this metadata is function-local and recursively has a
150 // function-local operand, return the first such operand's parent function.
151 // Otherwise, return null. 
152 Function *MDNode::getFunction() const {
153   if (!isFunctionLocal()) return NULL;
154   SmallPtrSet<const MDNode *, 32> Visited;
155   return getFunctionHelper(this, Visited);
156 }
157
158 // destroy - Delete this node.  Only when there are no uses.
159 void MDNode::destroy() {
160   setValueSubclassData(getSubclassDataFromValue() | DestroyFlag);
161   // Placement delete, the free the memory.
162   this->~MDNode();
163   free(this);
164 }
165
166 MDNode *MDNode::getMDNode(LLVMContext &Context, Value *const *Vals,
167                           unsigned NumVals, FunctionLocalness FL) {
168   LLVMContextImpl *pImpl = Context.pImpl;
169   FoldingSetNodeID ID;
170   for (unsigned i = 0; i != NumVals; ++i)
171     ID.AddPointer(Vals[i]);
172
173   void *InsertPoint;
174   MDNode *N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint);
175   if (!N) {
176     bool isFunctionLocal = false;
177     switch (FL) {
178     case FL_Unknown:
179       for (unsigned i = 0; i != NumVals; ++i) {
180         Value *V = Vals[i];
181         if (!V) continue;
182         if (isa<Instruction>(V) || isa<Argument>(V) || isa<BasicBlock>(V) ||
183             (isa<MDNode>(V) && cast<MDNode>(V)->isFunctionLocal())) {
184           isFunctionLocal = true;
185           break;
186         }
187       }
188       break;
189     case FL_No:
190       isFunctionLocal = false;
191       break;
192     case FL_Yes:
193       isFunctionLocal = true;
194       break;
195     }
196
197     // Coallocate space for the node and Operands together, then placement new.
198     void *Ptr = malloc(sizeof(MDNode)+NumVals*sizeof(MDNodeOperand));
199     N = new (Ptr) MDNode(Context, Vals, NumVals, isFunctionLocal);
200
201     // InsertPoint will have been set by the FindNodeOrInsertPos call.
202     pImpl->MDNodeSet.InsertNode(N, InsertPoint);
203   }
204   return N;
205 }
206
207 MDNode *MDNode::get(LLVMContext &Context, Value*const* Vals, unsigned NumVals) {
208   return getMDNode(Context, Vals, NumVals, FL_Unknown);
209 }
210
211 MDNode *MDNode::getWhenValsUnresolved(LLVMContext &Context, Value*const* Vals,
212                                       unsigned NumVals, bool isFunctionLocal) {
213   return getMDNode(Context, Vals, NumVals, isFunctionLocal ? FL_Yes : FL_No);
214 }
215
216 /// getOperand - Return specified operand.
217 Value *MDNode::getOperand(unsigned i) const {
218   return *getOperandPtr(const_cast<MDNode*>(this), i);
219 }
220
221 void MDNode::Profile(FoldingSetNodeID &ID) const {
222   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
223     ID.AddPointer(getOperand(i));
224 }
225
226
227 // Replace value from this node's operand list.
228 void MDNode::replaceOperand(MDNodeOperand *Op, Value *To) {
229   Value *From = *Op;
230
231   if (From == To)
232     return;
233
234   // Update the operand.
235   Op->set(To);
236
237   // If this node is already not being uniqued (because one of the operands
238   // already went to null), then there is nothing else to do here.
239   if (isNotUniqued()) return;
240
241   LLVMContextImpl *pImpl = getType()->getContext().pImpl;
242
243   // Remove "this" from the context map.  FoldingSet doesn't have to reprofile
244   // this node to remove it, so we don't care what state the operands are in.
245   pImpl->MDNodeSet.RemoveNode(this);
246
247   // If we are dropping an argument to null, we choose to not unique the MDNode
248   // anymore.  This commonly occurs during destruction, and uniquing these
249   // brings little reuse.
250   if (To == 0) {
251     setIsNotUniqued();
252     return;
253   }
254
255   // Now that the node is out of the folding set, get ready to reinsert it.
256   // First, check to see if another node with the same operands already exists
257   // in the set.  If it doesn't exist, this returns the position to insert it.
258   FoldingSetNodeID ID;
259   Profile(ID);
260   void *InsertPoint;
261   MDNode *N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint);
262
263   if (N) {
264     N->replaceAllUsesWith(this);
265     N->destroy();
266     N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint);
267     assert(N == 0 && "shouldn't be in the map now!"); (void)N;
268   }
269
270   // InsertPoint will have been set by the FindNodeOrInsertPos call.
271   pImpl->MDNodeSet.InsertNode(this, InsertPoint);
272 }
273
274 //===----------------------------------------------------------------------===//
275 // NamedMDNode implementation.
276 //
277
278 namespace llvm {
279 // SymbolTableListTraits specialization for MDSymbolTable.
280 void ilist_traits<NamedMDNode>
281 ::addNodeToList(NamedMDNode *N) {
282   assert(N->getParent() == 0 && "Value already in a container!!");
283   Module *Owner = getListOwner();
284   N->setParent(Owner);
285   MDSymbolTable &ST = Owner->getMDSymbolTable();
286   ST.insert(N->getName(), N);
287 }
288
289 void ilist_traits<NamedMDNode>::removeNodeFromList(NamedMDNode *N) {
290   N->setParent(0);
291   Module *Owner = getListOwner();
292   MDSymbolTable &ST = Owner->getMDSymbolTable();
293   ST.remove(N->getName());
294 }
295 }
296
297 static SmallVector<WeakVH, 4> &getNMDOps(void *Operands) {
298   return *(SmallVector<WeakVH, 4>*)Operands;
299 }
300
301 NamedMDNode::NamedMDNode(LLVMContext &C, const Twine &N,
302                          MDNode *const *MDs,
303                          unsigned NumMDs, Module *ParentModule)
304   : Value(Type::getMetadataTy(C), Value::NamedMDNodeVal), Parent(0) {
305   setName(N);
306   Operands = new SmallVector<WeakVH, 4>();
307
308   SmallVector<WeakVH, 4> &Node = getNMDOps(Operands);
309   for (unsigned i = 0; i != NumMDs; ++i)
310     Node.push_back(WeakVH(MDs[i]));
311
312   if (ParentModule)
313     ParentModule->getNamedMDList().push_back(this);
314 }
315
316 NamedMDNode *NamedMDNode::Create(const NamedMDNode *NMD, Module *M) {
317   assert(NMD && "Invalid source NamedMDNode!");
318   SmallVector<MDNode *, 4> Elems;
319   Elems.reserve(NMD->getNumOperands());
320
321   for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i)
322     Elems.push_back(NMD->getOperand(i));
323   return new NamedMDNode(NMD->getContext(), NMD->getName().data(),
324                          Elems.data(), Elems.size(), M);
325 }
326
327 NamedMDNode::~NamedMDNode() {
328   dropAllReferences();
329   delete &getNMDOps(Operands);
330 }
331
332 /// getNumOperands - Return number of NamedMDNode operands.
333 unsigned NamedMDNode::getNumOperands() const {
334   return (unsigned)getNMDOps(Operands).size();
335 }
336
337 /// getOperand - Return specified operand.
338 MDNode *NamedMDNode::getOperand(unsigned i) const {
339   assert(i < getNumOperands() && "Invalid Operand number!");
340   return dyn_cast_or_null<MDNode>(getNMDOps(Operands)[i]);
341 }
342
343 /// addOperand - Add metadata Operand.
344 void NamedMDNode::addOperand(MDNode *M) {
345   getNMDOps(Operands).push_back(WeakVH(M));
346 }
347
348 /// eraseFromParent - Drop all references and remove the node from parent
349 /// module.
350 void NamedMDNode::eraseFromParent() {
351   getParent()->getNamedMDList().erase(this);
352 }
353
354 /// dropAllReferences - Remove all uses and clear node vector.
355 void NamedMDNode::dropAllReferences() {
356   getNMDOps(Operands).clear();
357 }
358
359 /// setName - Set the name of this named metadata.
360 void NamedMDNode::setName(const Twine &NewName) {
361   assert (!NewName.isTriviallyEmpty() && "Invalid named metadata name!");
362
363   SmallString<256> NameData;
364   StringRef NameRef = NewName.toStringRef(NameData);
365
366   // Name isn't changing?
367   if (getName() == NameRef)
368     return;
369
370   Name = NameRef.str();
371   if (Parent)
372     Parent->getMDSymbolTable().insert(NameRef, this);
373 }
374
375 /// getName - Return a constant reference to this named metadata's name.
376 StringRef NamedMDNode::getName() const {
377   return StringRef(Name);
378 }
379
380 //===----------------------------------------------------------------------===//
381 // LLVMContext MDKind naming implementation.
382 //
383
384 #ifndef NDEBUG
385 /// isValidName - Return true if Name is a valid custom metadata handler name.
386 static bool isValidName(StringRef MDName) {
387   if (MDName.empty())
388     return false;
389
390   if (!isalpha(MDName[0]))
391     return false;
392
393   for (StringRef::iterator I = MDName.begin() + 1, E = MDName.end(); I != E;
394        ++I) {
395     if (!isalnum(*I) && *I != '_' && *I != '-' && *I != '.')
396         return false;
397   }
398   return true;
399 }
400 #endif
401
402 /// getMDKindID - Return a unique non-zero ID for the specified metadata kind.
403 unsigned LLVMContext::getMDKindID(StringRef Name) const {
404   assert(isValidName(Name) && "Invalid MDNode name");
405
406   unsigned &Entry = pImpl->CustomMDKindNames[Name];
407
408   // If this is new, assign it its ID.
409   if (Entry == 0) Entry = pImpl->CustomMDKindNames.size();
410   return Entry;
411 }
412
413 /// getHandlerNames - Populate client supplied smallvector using custome
414 /// metadata name and ID.
415 void LLVMContext::getMDKindNames(SmallVectorImpl<StringRef> &Names) const {
416   Names.resize(pImpl->CustomMDKindNames.size()+1);
417   Names[0] = "";
418   for (StringMap<unsigned>::const_iterator I = pImpl->CustomMDKindNames.begin(),
419        E = pImpl->CustomMDKindNames.end(); I != E; ++I)
420     // MD Handlers are numbered from 1.
421     Names[I->second] = I->first();
422 }
423
424 //===----------------------------------------------------------------------===//
425 // Instruction Metadata method implementations.
426 //
427
428 void Instruction::setMetadata(const char *Kind, MDNode *Node) {
429   if (Node == 0 && !hasMetadata()) return;
430   setMetadata(getContext().getMDKindID(Kind), Node);
431 }
432
433 MDNode *Instruction::getMetadataImpl(const char *Kind) const {
434   return getMetadataImpl(getContext().getMDKindID(Kind));
435 }
436
437 /// setMetadata - Set the metadata of of the specified kind to the specified
438 /// node.  This updates/replaces metadata if already present, or removes it if
439 /// Node is null.
440 void Instruction::setMetadata(unsigned KindID, MDNode *Node) {
441   if (Node == 0 && !hasMetadata()) return;
442
443   // Handle the case when we're adding/updating metadata on an instruction.
444   if (Node) {
445     LLVMContextImpl::MDMapTy &Info = getContext().pImpl->MetadataStore[this];
446     assert(!Info.empty() == hasMetadata() && "HasMetadata bit is wonked");
447     if (Info.empty()) {
448       setHasMetadata(true);
449     } else {
450       // Handle replacement of an existing value.
451       for (unsigned i = 0, e = Info.size(); i != e; ++i)
452         if (Info[i].first == KindID) {
453           Info[i].second = Node;
454           return;
455         }
456     }
457
458     // No replacement, just add it to the list.
459     Info.push_back(std::make_pair(KindID, Node));
460     return;
461   }
462
463   // Otherwise, we're removing metadata from an instruction.
464   assert(hasMetadata() && getContext().pImpl->MetadataStore.count(this) &&
465          "HasMetadata bit out of date!");
466   LLVMContextImpl::MDMapTy &Info = getContext().pImpl->MetadataStore[this];
467
468   // Common case is removing the only entry.
469   if (Info.size() == 1 && Info[0].first == KindID) {
470     getContext().pImpl->MetadataStore.erase(this);
471     setHasMetadata(false);
472     return;
473   }
474
475   // Handle replacement of an existing value.
476   for (unsigned i = 0, e = Info.size(); i != e; ++i)
477     if (Info[i].first == KindID) {
478       Info[i] = Info.back();
479       Info.pop_back();
480       assert(!Info.empty() && "Removing last entry should be handled above");
481       return;
482     }
483   // Otherwise, removing an entry that doesn't exist on the instruction.
484 }
485
486 MDNode *Instruction::getMetadataImpl(unsigned KindID) const {
487   LLVMContextImpl::MDMapTy &Info = getContext().pImpl->MetadataStore[this];
488   assert(hasMetadata() && !Info.empty() && "Shouldn't have called this");
489
490   for (LLVMContextImpl::MDMapTy::iterator I = Info.begin(), E = Info.end();
491        I != E; ++I)
492     if (I->first == KindID)
493       return I->second;
494   return 0;
495 }
496
497 void Instruction::getAllMetadataImpl(SmallVectorImpl<std::pair<unsigned,
498                                        MDNode*> > &Result)const {
499   assert(hasMetadata() && getContext().pImpl->MetadataStore.count(this) &&
500          "Shouldn't have called this");
501   const LLVMContextImpl::MDMapTy &Info =
502     getContext().pImpl->MetadataStore.find(this)->second;
503   assert(!Info.empty() && "Shouldn't have called this");
504
505   Result.clear();
506   Result.append(Info.begin(), Info.end());
507
508   // Sort the resulting array so it is stable.
509   if (Result.size() > 1)
510     array_pod_sort(Result.begin(), Result.end());
511 }
512
513 /// removeAllMetadata - Remove all metadata from this instruction.
514 void Instruction::removeAllMetadata() {
515   assert(hasMetadata() && "Caller should check");
516   getContext().pImpl->MetadataStore.erase(this);
517   setHasMetadata(false);
518 }
519