Compute isFunctionLocal in MDNode ctor or via argument in new function getWhenValsUnr...
[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 static SmallVector<WeakVH, 4> &getNMDOps(void *Operands) {
243   return *(SmallVector<WeakVH, 4>*)Operands;
244 }
245
246 NamedMDNode::NamedMDNode(LLVMContext &C, StringRef N,
247                          MDNode *const *MDs, 
248                          unsigned NumMDs, Module *ParentModule)
249   : Value(Type::getMetadataTy(C), Value::NamedMDNodeVal), Parent(0) {
250   setName(N);
251   Operands = new SmallVector<WeakVH, 4>();
252     
253   SmallVector<WeakVH, 4> &Node = getNMDOps(Operands);
254   for (unsigned i = 0; i != NumMDs; ++i)
255     Node.push_back(WeakVH(MDs[i]));
256
257   if (ParentModule) {
258     ParentModule->getNamedMDList().push_back(this);
259     ParentModule->addMDNodeName(N, this);
260   }
261 }
262
263 NamedMDNode *NamedMDNode::Create(const NamedMDNode *NMD, Module *M) {
264   assert(NMD && "Invalid source NamedMDNode!");
265   SmallVector<MDNode *, 4> Elems;
266   Elems.reserve(NMD->getNumOperands());
267   
268   for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i)
269     Elems.push_back(NMD->getOperand(i));
270   return new NamedMDNode(NMD->getContext(), NMD->getName().data(),
271                          Elems.data(), Elems.size(), M);
272 }
273
274 NamedMDNode::~NamedMDNode() {
275   dropAllReferences();
276   delete &getNMDOps(Operands);
277 }
278
279 /// getNumOperands - Return number of NamedMDNode operands.
280 unsigned NamedMDNode::getNumOperands() const {
281   return (unsigned)getNMDOps(Operands).size();
282 }
283
284 /// getOperand - Return specified operand.
285 MDNode *NamedMDNode::getOperand(unsigned i) const {
286   assert(i < getNumOperands() && "Invalid Operand number!");
287   return dyn_cast_or_null<MDNode>(getNMDOps(Operands)[i]);
288 }
289
290 /// addOperand - Add metadata Operand.
291 void NamedMDNode::addOperand(MDNode *M) {
292   getNMDOps(Operands).push_back(WeakVH(M));
293 }
294
295 /// eraseFromParent - Drop all references and remove the node from parent
296 /// module.
297 void NamedMDNode::eraseFromParent() {
298   getParent()->getMDSymbolTable().remove(getName());
299   getParent()->getNamedMDList().erase(this);
300 }
301
302 /// dropAllReferences - Remove all uses and clear node vector.
303 void NamedMDNode::dropAllReferences() {
304   getNMDOps(Operands).clear();
305 }
306
307 /// setName - Set the name of this named metadata.
308 void NamedMDNode::setName(StringRef N) {
309   if (!N.empty())
310     Name = N.str();
311 }
312
313 /// getName - Return a constant reference to this named metadata's name.
314 StringRef NamedMDNode::getName() const {
315   return StringRef(Name);
316 }
317
318 //===----------------------------------------------------------------------===//
319 // LLVMContext MDKind naming implementation.
320 //
321
322 #ifndef NDEBUG
323 /// isValidName - Return true if Name is a valid custom metadata handler name.
324 static bool isValidName(StringRef MDName) {
325   if (MDName.empty())
326     return false;
327
328   if (!isalpha(MDName[0]))
329     return false;
330
331   for (StringRef::iterator I = MDName.begin() + 1, E = MDName.end(); I != E;
332        ++I) {
333     if (!isalnum(*I) && *I != '_' && *I != '-' && *I != '.')
334         return false;
335   }
336   return true;
337 }
338 #endif
339
340 /// getMDKindID - Return a unique non-zero ID for the specified metadata kind.
341 unsigned LLVMContext::getMDKindID(StringRef Name) const {
342   assert(isValidName(Name) && "Invalid MDNode name");
343   
344   unsigned &Entry = pImpl->CustomMDKindNames[Name];
345   
346   // If this is new, assign it its ID.
347   if (Entry == 0) Entry = pImpl->CustomMDKindNames.size();
348   return Entry;
349 }
350
351 /// getHandlerNames - Populate client supplied smallvector using custome
352 /// metadata name and ID.
353 void LLVMContext::getMDKindNames(SmallVectorImpl<StringRef> &Names) const {
354   Names.resize(pImpl->CustomMDKindNames.size()+1);
355   Names[0] = "";
356   for (StringMap<unsigned>::const_iterator I = pImpl->CustomMDKindNames.begin(),
357        E = pImpl->CustomMDKindNames.end(); I != E; ++I) 
358     // MD Handlers are numbered from 1.
359     Names[I->second] = I->first();
360 }
361
362 //===----------------------------------------------------------------------===//
363 // Instruction Metadata method implementations.
364 //
365
366 void Instruction::setMetadata(const char *Kind, MDNode *Node) {
367   if (Node == 0 && !hasMetadata()) return;
368   setMetadata(getContext().getMDKindID(Kind), Node);
369 }
370
371 MDNode *Instruction::getMetadataImpl(const char *Kind) const {
372   return getMetadataImpl(getContext().getMDKindID(Kind));
373 }
374
375 /// setMetadata - Set the metadata of of the specified kind to the specified
376 /// node.  This updates/replaces metadata if already present, or removes it if
377 /// Node is null.
378 void Instruction::setMetadata(unsigned KindID, MDNode *Node) {
379   if (Node == 0 && !hasMetadata()) return;
380   
381   // Handle the case when we're adding/updating metadata on an instruction.
382   if (Node) {
383     LLVMContextImpl::MDMapTy &Info = getContext().pImpl->MetadataStore[this];
384     assert(!Info.empty() == hasMetadata() && "HasMetadata bit is wonked");
385     if (Info.empty()) {
386       setHasMetadata(true);
387     } else {
388       // Handle replacement of an existing value.
389       for (unsigned i = 0, e = Info.size(); i != e; ++i)
390         if (Info[i].first == KindID) {
391           Info[i].second = Node;
392           return;
393         }
394     }
395     
396     // No replacement, just add it to the list.
397     Info.push_back(std::make_pair(KindID, Node));
398     return;
399   }
400   
401   // Otherwise, we're removing metadata from an instruction.
402   assert(hasMetadata() && getContext().pImpl->MetadataStore.count(this) &&
403          "HasMetadata bit out of date!");
404   LLVMContextImpl::MDMapTy &Info = getContext().pImpl->MetadataStore[this];
405   
406   // Common case is removing the only entry.
407   if (Info.size() == 1 && Info[0].first == KindID) {
408     getContext().pImpl->MetadataStore.erase(this);
409     setHasMetadata(false);
410     return;
411   }
412   
413   // Handle replacement of an existing value.
414   for (unsigned i = 0, e = Info.size(); i != e; ++i)
415     if (Info[i].first == KindID) {
416       Info[i] = Info.back();
417       Info.pop_back();
418       assert(!Info.empty() && "Removing last entry should be handled above");
419       return;
420     }
421   // Otherwise, removing an entry that doesn't exist on the instruction.
422 }
423
424 MDNode *Instruction::getMetadataImpl(unsigned KindID) const {
425   LLVMContextImpl::MDMapTy &Info = getContext().pImpl->MetadataStore[this];
426   assert(hasMetadata() && !Info.empty() && "Shouldn't have called this");
427   
428   for (LLVMContextImpl::MDMapTy::iterator I = Info.begin(), E = Info.end();
429        I != E; ++I)
430     if (I->first == KindID)
431       return I->second;
432   return 0;
433 }
434
435 void Instruction::getAllMetadataImpl(SmallVectorImpl<std::pair<unsigned,
436                                        MDNode*> > &Result)const {
437   assert(hasMetadata() && getContext().pImpl->MetadataStore.count(this) &&
438          "Shouldn't have called this");
439   const LLVMContextImpl::MDMapTy &Info =
440     getContext().pImpl->MetadataStore.find(this)->second;
441   assert(!Info.empty() && "Shouldn't have called this");
442   
443   Result.clear();
444   Result.append(Info.begin(), Info.end());
445   
446   // Sort the resulting array so it is stable.
447   if (Result.size() > 1)
448     array_pod_sort(Result.begin(), Result.end());
449 }
450
451 /// removeAllMetadata - Remove all metadata from this instruction.
452 void Instruction::removeAllMetadata() {
453   assert(hasMetadata() && "Caller should check");
454   getContext().pImpl->MetadataStore.erase(this);
455   setHasMetadata(false);
456 }
457