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