Make NamedMDNode not be a subclass of Value, and simplify the interface
[oota-llvm.git] / lib / VMCore / Metadata.cpp
index 77926f9af3466d39ee00d937a2ac31f4298782e3..442b5c51b65510e0c1fe07c5bd683e9ddc5f8904 100644 (file)
@@ -78,7 +78,8 @@ void MDNodeOperand::allUsesReplacedWith(Value *NV) {
 /// getOperandPtr - Helper function to get the MDNodeOperand's coallocated on
 /// the end of the MDNode.
 static MDNodeOperand *getOperandPtr(MDNode *N, unsigned Op) {
-  assert(Op < N->getNumOperands() && "Invalid operand number");
+  // Use <= instead of < to permit a one-past-the-end address.
+  assert(Op <= N->getNumOperands() && "Invalid operand number");
   return reinterpret_cast<MDNodeOperand*>(N+1)+Op;
 }
 
@@ -115,14 +116,17 @@ MDNode::~MDNode() {
 }
 
 static const Function *getFunctionForValue(Value *V) {
-  assert(!isa<MDNode>(V) && "does not iterate over metadata operands");
   if (!V) return NULL;
-  if (Instruction *I = dyn_cast<Instruction>(V))
-    return I->getParent()->getParent();
-  if (BasicBlock *BB = dyn_cast<BasicBlock>(V))
-    return BB->getParent();
+  if (Instruction *I = dyn_cast<Instruction>(V)) {
+    BasicBlock *BB = I->getParent();
+    return BB ? BB->getParent() : 0;
+  }
   if (Argument *A = dyn_cast<Argument>(V))
     return A->getParent();
+  if (BasicBlock *BB = dyn_cast<BasicBlock>(V))
+    return BB->getParent();
+  if (MDNode *MD = dyn_cast<MDNode>(V))
+    return MD->getFunction();
   return NULL;
 }
 
@@ -130,6 +134,7 @@ static const Function *getFunctionForValue(Value *V) {
 static const Function *assertLocalFunction(const MDNode *N) {
   if (!N->isFunctionLocal()) return 0;
 
+  // FIXME: This does not handle cyclic function local metadata.
   const Function *F = 0, *NewF = 0;
   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
     if (Value *V = N->getOperand(i)) {
@@ -156,17 +161,9 @@ const Function *MDNode::getFunction() const {
   return assertLocalFunction(this);
 #endif
   if (!isFunctionLocal()) return NULL;
-
-  for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
-    if (Value *V = getOperand(i)) {
-      if (MDNode *MD = dyn_cast<MDNode>(V)) {
-        if (const Function *F = MD->getFunction())
-          return F;
-      } else {
-        return getFunctionForValue(V);
-      }
-    }
-  }
+  for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
+    if (const Function *F = getFunctionForValue(getOperand(i)))
+      return F;
   return NULL;
 }
 
@@ -178,6 +175,13 @@ void MDNode::destroy() {
   free(this);
 }
 
+/// isFunctionLocalValue - Return true if this is a value that would require a
+/// function-local MDNode.
+static bool isFunctionLocalValue(Value *V) {
+  return isa<Instruction>(V) || isa<Argument>(V) || isa<BasicBlock>(V) ||
+         (isa<MDNode>(V) && cast<MDNode>(V)->isFunctionLocal());
+}
+
 MDNode *MDNode::getMDNode(LLVMContext &Context, Value *const *Vals,
                           unsigned NumVals, FunctionLocalness FL,
                           bool Insert) {
@@ -188,8 +192,7 @@ MDNode *MDNode::getMDNode(LLVMContext &Context, Value *const *Vals,
     for (unsigned i = 0; i != NumVals; ++i) {
       Value *V = Vals[i];
       if (!V) continue;
-      if (isa<Instruction>(V) || isa<Argument>(V) || isa<BasicBlock>(V) ||
-          (isa<MDNode>(V) && cast<MDNode>(V)->isFunctionLocal())) {
+      if (isFunctionLocalValue(V)) {
         isFunctionLocal = true;
         break;
       }
@@ -262,6 +265,24 @@ void MDNode::setIsNotUniqued() {
 void MDNode::replaceOperand(MDNodeOperand *Op, Value *To) {
   Value *From = *Op;
 
+  // If is possible that someone did GV->RAUW(inst), replacing a global variable
+  // with an instruction or some other function-local object.  If this is a
+  // non-function-local MDNode, it can't point to a function-local object.
+  // Handle this case by implicitly dropping the MDNode reference to null.
+  // Likewise if the MDNode is function-local but for a different function.
+  if (To && isFunctionLocalValue(To)) {
+    if (!isFunctionLocal())
+      To = 0;
+    else {
+      const Function *F = getFunction();
+      const Function *FV = getFunctionForValue(To);
+      // Metadata can be function-local without having an associated function.
+      // So only consider functions to have changed if non-null.
+      if (F && FV && F != FV)
+        To = 0;
+    }
+  }
+  
   if (From == To)
     return;
 
@@ -309,53 +330,13 @@ void MDNode::replaceOperand(MDNodeOperand *Op, Value *To) {
 // NamedMDNode implementation.
 //
 
-namespace llvm {
-// SymbolTableListTraits specialization for MDSymbolTable.
-void ilist_traits<NamedMDNode>
-::addNodeToList(NamedMDNode *N) {
-  assert(N->getParent() == 0 && "Value already in a container!!");
-  Module *Owner = getListOwner();
-  N->setParent(Owner);
-  MDSymbolTable &ST = Owner->getMDSymbolTable();
-  ST.insert(N->getName(), N);
-}
-
-void ilist_traits<NamedMDNode>::removeNodeFromList(NamedMDNode *N) {
-  N->setParent(0);
-  Module *Owner = getListOwner();
-  MDSymbolTable &ST = Owner->getMDSymbolTable();
-  ST.remove(N->getName());
-}
-}
-
-static SmallVector<WeakVH, 4> &getNMDOps(void *Operands) {
-  return *(SmallVector<WeakVH, 4>*)Operands;
-}
-
-NamedMDNode::NamedMDNode(LLVMContext &C, const Twine &N,
-                         MDNode *const *MDs,
-                         unsigned NumMDs, Module *ParentModule)
-  : Value(Type::getMetadataTy(C), Value::NamedMDNodeVal), Parent(0) {
-  setName(N);
-  Operands = new SmallVector<WeakVH, 4>();
-
-  SmallVector<WeakVH, 4> &Node = getNMDOps(Operands);
-  for (unsigned i = 0; i != NumMDs; ++i)
-    Node.push_back(WeakVH(MDs[i]));
-
-  if (ParentModule)
-    ParentModule->getNamedMDList().push_back(this);
+static SmallVector<TrackingVH<MDNode>, 4> &getNMDOps(void *Operands) {
+  return *(SmallVector<TrackingVH<MDNode>, 4>*)Operands;
 }
 
-NamedMDNode *NamedMDNode::Create(const NamedMDNode *NMD, Module *M) {
-  assert(NMD && "Invalid source NamedMDNode!");
-  SmallVector<MDNode *, 4> Elems;
-  Elems.reserve(NMD->getNumOperands());
-
-  for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i)
-    Elems.push_back(NMD->getOperand(i));
-  return new NamedMDNode(NMD->getContext(), NMD->getName().data(),
-                         Elems.data(), Elems.size(), M);
+NamedMDNode::NamedMDNode(const Twine &N)
+  : Name(N.str()), Parent(0),
+    Operands(new SmallVector<TrackingVH<MDNode>, 4>()) {
 }
 
 NamedMDNode::~NamedMDNode() {
@@ -371,18 +352,18 @@ unsigned NamedMDNode::getNumOperands() const {
 /// getOperand - Return specified operand.
 MDNode *NamedMDNode::getOperand(unsigned i) const {
   assert(i < getNumOperands() && "Invalid Operand number!");
-  return dyn_cast_or_null<MDNode>(getNMDOps(Operands)[i]);
+  return dyn_cast<MDNode>(&*getNMDOps(Operands)[i]);
 }
 
 /// addOperand - Add metadata Operand.
 void NamedMDNode::addOperand(MDNode *M) {
-  getNMDOps(Operands).push_back(WeakVH(M));
+  getNMDOps(Operands).push_back(TrackingVH<MDNode>(M));
 }
 
 /// eraseFromParent - Drop all references and remove the node from parent
 /// module.
 void NamedMDNode::eraseFromParent() {
-  getParent()->getNamedMDList().erase(this);
+  getParent()->eraseNamedMetadata(this);
 }
 
 /// dropAllReferences - Remove all uses and clear node vector.
@@ -390,22 +371,6 @@ void NamedMDNode::dropAllReferences() {
   getNMDOps(Operands).clear();
 }
 
-/// setName - Set the name of this named metadata.
-void NamedMDNode::setName(const Twine &NewName) {
-  assert (!NewName.isTriviallyEmpty() && "Invalid named metadata name!");
-
-  SmallString<256> NameData;
-  StringRef NameRef = NewName.toStringRef(NameData);
-
-  // Name isn't changing?
-  if (getName() == NameRef)
-    return;
-
-  Name = NameRef.str();
-  if (Parent)
-    Parent->getMDSymbolTable().insert(NameRef, this);
-}
-
 /// getName - Return a constant reference to this named metadata's name.
 StringRef NamedMDNode::getName() const {
   return StringRef(Name);
@@ -432,7 +397,7 @@ void Instruction::setMetadata(unsigned KindID, MDNode *Node) {
 
   // Handle 'dbg' as a special case since it is not stored in the hash table.
   if (KindID == LLVMContext::MD_dbg) {
-    DbgInfo = Node;
+    DbgLoc = DebugLoc::getFromDILocation(Node);
     return;
   }
   
@@ -484,7 +449,7 @@ void Instruction::setMetadata(unsigned KindID, MDNode *Node) {
 MDNode *Instruction::getMetadataImpl(unsigned KindID) const {
   // Handle 'dbg' as a special case since it is not stored in the hash table.
   if (KindID == LLVMContext::MD_dbg)
-    return DbgInfo;
+    return DbgLoc.getAsMDNode(getContext());
   
   if (!hasMetadataHashEntry()) return 0;
   
@@ -503,8 +468,9 @@ void Instruction::getAllMetadataImpl(SmallVectorImpl<std::pair<unsigned,
   Result.clear();
   
   // Handle 'dbg' as a special case since it is not stored in the hash table.
-  if (DbgInfo) {
-    Result.push_back(std::make_pair((unsigned)LLVMContext::MD_dbg, DbgInfo));
+  if (!DbgLoc.isUnknown()) {
+    Result.push_back(std::make_pair((unsigned)LLVMContext::MD_dbg,
+                                    DbgLoc.getAsMDNode(getContext())));
     if (!hasMetadataHashEntry()) return;
   }
   
@@ -522,13 +488,30 @@ void Instruction::getAllMetadataImpl(SmallVectorImpl<std::pair<unsigned,
     array_pod_sort(Result.begin(), Result.end());
 }
 
-/// removeAllMetadata - Remove all metadata from this instruction.
-void Instruction::removeAllMetadata() {
-  assert(hasMetadata() && "Caller should check");
-  DbgInfo = 0;
-  if (hasMetadataHashEntry()) {
-    getContext().pImpl->MetadataStore.erase(this);
-    setHasMetadataHashEntry(false);
-  }
+void Instruction::
+getAllMetadataOtherThanDebugLocImpl(SmallVectorImpl<std::pair<unsigned,
+                                    MDNode*> > &Result) const {
+  Result.clear();
+  assert(hasMetadataHashEntry() &&
+         getContext().pImpl->MetadataStore.count(this) &&
+         "Shouldn't have called this");
+  const LLVMContextImpl::MDMapTy &Info =
+  getContext().pImpl->MetadataStore.find(this)->second;
+  assert(!Info.empty() && "Shouldn't have called this");
+  
+  Result.append(Info.begin(), Info.end());
+  
+  // Sort the resulting array so it is stable.
+  if (Result.size() > 1)
+    array_pod_sort(Result.begin(), Result.end());
+}
+
+
+/// clearMetadataHashEntries - Clear all hashtable-based metadata from
+/// this instruction.
+void Instruction::clearMetadataHashEntries() {
+  assert(hasMetadataHashEntry() && "Caller should check");
+  getContext().pImpl->MetadataStore.erase(this);
+  setHasMetadataHashEntry(false);
 }