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