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