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