LLVM API Documentation

Metadata.cpp
Go to the documentation of this file.
00001 //===-- Metadata.cpp - Implement Metadata classes -------------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements the Metadata classes.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "llvm/IR/Metadata.h"
00015 #include "LLVMContextImpl.h"
00016 #include "SymbolTableListTraitsImpl.h"
00017 #include "llvm/ADT/DenseMap.h"
00018 #include "llvm/ADT/STLExtras.h"
00019 #include "llvm/ADT/SmallString.h"
00020 #include "llvm/ADT/StringMap.h"
00021 #include "llvm/IR/Instruction.h"
00022 #include "llvm/IR/LLVMContext.h"
00023 #include "llvm/IR/Module.h"
00024 #include "llvm/Support/ConstantRange.h"
00025 #include "llvm/Support/LeakDetector.h"
00026 #include "llvm/Support/ValueHandle.h"
00027 using namespace llvm;
00028 
00029 //===----------------------------------------------------------------------===//
00030 // MDString implementation.
00031 //
00032 
00033 void MDString::anchor() { }
00034 
00035 MDString::MDString(LLVMContext &C)
00036   : Value(Type::getMetadataTy(C), Value::MDStringVal) {}
00037 
00038 MDString *MDString::get(LLVMContext &Context, StringRef Str) {
00039   LLVMContextImpl *pImpl = Context.pImpl;
00040   StringMapEntry<Value*> &Entry =
00041     pImpl->MDStringCache.GetOrCreateValue(Str);
00042   Value *&S = Entry.getValue();
00043   if (!S) S = new MDString(Context);
00044   S->setValueName(&Entry);
00045   return cast<MDString>(S);
00046 }
00047 
00048 //===----------------------------------------------------------------------===//
00049 // MDNodeOperand implementation.
00050 //
00051 
00052 // Use CallbackVH to hold MDNode operands.
00053 namespace llvm {
00054 class MDNodeOperand : public CallbackVH {
00055   MDNode *getParent() {
00056     MDNodeOperand *Cur = this;
00057 
00058     while (Cur->getValPtrInt() != 1)
00059       --Cur;
00060 
00061     assert(Cur->getValPtrInt() == 1 &&
00062            "Couldn't find the beginning of the operand list!");
00063     return reinterpret_cast<MDNode*>(Cur) - 1;
00064   }
00065 
00066 public:
00067   MDNodeOperand(Value *V) : CallbackVH(V) {}
00068   ~MDNodeOperand() {}
00069 
00070   void set(Value *V) {
00071     unsigned IsFirst = this->getValPtrInt();
00072     this->setValPtr(V);
00073     this->setAsFirstOperand(IsFirst);
00074   }
00075 
00076   /// setAsFirstOperand - Accessor method to mark the operand as the first in
00077   /// the list.
00078   void setAsFirstOperand(unsigned V) { this->setValPtrInt(V); }
00079 
00080   virtual void deleted();
00081   virtual void allUsesReplacedWith(Value *NV);
00082 };
00083 } // end namespace llvm.
00084 
00085 
00086 void MDNodeOperand::deleted() {
00087   getParent()->replaceOperand(this, 0);
00088 }
00089 
00090 void MDNodeOperand::allUsesReplacedWith(Value *NV) {
00091   getParent()->replaceOperand(this, NV);
00092 }
00093 
00094 //===----------------------------------------------------------------------===//
00095 // MDNode implementation.
00096 //
00097 
00098 /// getOperandPtr - Helper function to get the MDNodeOperand's coallocated on
00099 /// the end of the MDNode.
00100 static MDNodeOperand *getOperandPtr(MDNode *N, unsigned Op) {
00101   // Use <= instead of < to permit a one-past-the-end address.
00102   assert(Op <= N->getNumOperands() && "Invalid operand number");
00103   return reinterpret_cast<MDNodeOperand*>(N + 1) + Op;
00104 }
00105 
00106 void MDNode::replaceOperandWith(unsigned i, Value *Val) {
00107   MDNodeOperand *Op = getOperandPtr(this, i);
00108   replaceOperand(Op, Val);
00109 }
00110 
00111 MDNode::MDNode(LLVMContext &C, ArrayRef<Value*> Vals, bool isFunctionLocal)
00112 : Value(Type::getMetadataTy(C), Value::MDNodeVal) {
00113   NumOperands = Vals.size();
00114 
00115   if (isFunctionLocal)
00116     setValueSubclassData(getSubclassDataFromValue() | FunctionLocalBit);
00117 
00118   // Initialize the operand list, which is co-allocated on the end of the node.
00119   unsigned i = 0;
00120   for (MDNodeOperand *Op = getOperandPtr(this, 0), *E = Op+NumOperands;
00121        Op != E; ++Op, ++i) {
00122     new (Op) MDNodeOperand(Vals[i]);
00123 
00124     // Mark the first MDNodeOperand as being the first in the list of operands.
00125     if (i == 0)
00126       Op->setAsFirstOperand(1);
00127   }
00128 }
00129 
00130 /// ~MDNode - Destroy MDNode.
00131 MDNode::~MDNode() {
00132   assert((getSubclassDataFromValue() & DestroyFlag) != 0 &&
00133          "Not being destroyed through destroy()?");
00134   LLVMContextImpl *pImpl = getType()->getContext().pImpl;
00135   if (isNotUniqued()) {
00136     pImpl->NonUniquedMDNodes.erase(this);
00137   } else {
00138     pImpl->MDNodeSet.RemoveNode(this);
00139   }
00140 
00141   // Destroy the operands.
00142   for (MDNodeOperand *Op = getOperandPtr(this, 0), *E = Op+NumOperands;
00143        Op != E; ++Op)
00144     Op->~MDNodeOperand();
00145 }
00146 
00147 static const Function *getFunctionForValue(Value *V) {
00148   if (!V) return NULL;
00149   if (Instruction *I = dyn_cast<Instruction>(V)) {
00150     BasicBlock *BB = I->getParent();
00151     return BB ? BB->getParent() : 0;
00152   }
00153   if (Argument *A = dyn_cast<Argument>(V))
00154     return A->getParent();
00155   if (BasicBlock *BB = dyn_cast<BasicBlock>(V))
00156     return BB->getParent();
00157   if (MDNode *MD = dyn_cast<MDNode>(V))
00158     return MD->getFunction();
00159   return NULL;
00160 }
00161 
00162 #ifndef NDEBUG
00163 static const Function *assertLocalFunction(const MDNode *N) {
00164   if (!N->isFunctionLocal()) return 0;
00165 
00166   // FIXME: This does not handle cyclic function local metadata.
00167   const Function *F = 0, *NewF = 0;
00168   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
00169     if (Value *V = N->getOperand(i)) {
00170       if (MDNode *MD = dyn_cast<MDNode>(V))
00171         NewF = assertLocalFunction(MD);
00172       else
00173         NewF = getFunctionForValue(V);
00174     }
00175     if (F == 0)
00176       F = NewF;
00177     else 
00178       assert((NewF == 0 || F == NewF) &&"inconsistent function-local metadata");
00179   }
00180   return F;
00181 }
00182 #endif
00183 
00184 // getFunction - If this metadata is function-local and recursively has a
00185 // function-local operand, return the first such operand's parent function.
00186 // Otherwise, return null. getFunction() should not be used for performance-
00187 // critical code because it recursively visits all the MDNode's operands.  
00188 const Function *MDNode::getFunction() const {
00189 #ifndef NDEBUG
00190   return assertLocalFunction(this);
00191 #else
00192   if (!isFunctionLocal()) return NULL;
00193   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
00194     if (const Function *F = getFunctionForValue(getOperand(i)))
00195       return F;
00196   return NULL;
00197 #endif
00198 }
00199 
00200 // destroy - Delete this node.  Only when there are no uses.
00201 void MDNode::destroy() {
00202   setValueSubclassData(getSubclassDataFromValue() | DestroyFlag);
00203   // Placement delete, then free the memory.
00204   this->~MDNode();
00205   free(this);
00206 }
00207 
00208 /// isFunctionLocalValue - Return true if this is a value that would require a
00209 /// function-local MDNode.
00210 static bool isFunctionLocalValue(Value *V) {
00211   return isa<Instruction>(V) || isa<Argument>(V) || isa<BasicBlock>(V) ||
00212          (isa<MDNode>(V) && cast<MDNode>(V)->isFunctionLocal());
00213 }
00214 
00215 MDNode *MDNode::getMDNode(LLVMContext &Context, ArrayRef<Value*> Vals,
00216                           FunctionLocalness FL, bool Insert) {
00217   LLVMContextImpl *pImpl = Context.pImpl;
00218 
00219   // Add all the operand pointers. Note that we don't have to add the
00220   // isFunctionLocal bit because that's implied by the operands.
00221   // Note that if the operands are later nulled out, the node will be
00222   // removed from the uniquing map.
00223   FoldingSetNodeID ID;
00224   for (unsigned i = 0; i != Vals.size(); ++i)
00225     ID.AddPointer(Vals[i]);
00226 
00227   void *InsertPoint;
00228   MDNode *N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint);
00229 
00230   if (N || !Insert)
00231     return N;
00232 
00233   bool isFunctionLocal = false;
00234   switch (FL) {
00235   case FL_Unknown:
00236     for (unsigned i = 0; i != Vals.size(); ++i) {
00237       Value *V = Vals[i];
00238       if (!V) continue;
00239       if (isFunctionLocalValue(V)) {
00240         isFunctionLocal = true;
00241         break;
00242       }
00243     }
00244     break;
00245   case FL_No:
00246     isFunctionLocal = false;
00247     break;
00248   case FL_Yes:
00249     isFunctionLocal = true;
00250     break;
00251   }
00252 
00253   // Coallocate space for the node and Operands together, then placement new.
00254   void *Ptr = malloc(sizeof(MDNode) + Vals.size() * sizeof(MDNodeOperand));
00255   N = new (Ptr) MDNode(Context, Vals, isFunctionLocal);
00256 
00257   // Cache the operand hash.
00258   N->Hash = ID.ComputeHash();
00259 
00260   // InsertPoint will have been set by the FindNodeOrInsertPos call.
00261   pImpl->MDNodeSet.InsertNode(N, InsertPoint);
00262 
00263   return N;
00264 }
00265 
00266 MDNode *MDNode::get(LLVMContext &Context, ArrayRef<Value*> Vals) {
00267   return getMDNode(Context, Vals, FL_Unknown);
00268 }
00269 
00270 MDNode *MDNode::getWhenValsUnresolved(LLVMContext &Context,
00271                                       ArrayRef<Value*> Vals,
00272                                       bool isFunctionLocal) {
00273   return getMDNode(Context, Vals, isFunctionLocal ? FL_Yes : FL_No);
00274 }
00275 
00276 MDNode *MDNode::getIfExists(LLVMContext &Context, ArrayRef<Value*> Vals) {
00277   return getMDNode(Context, Vals, FL_Unknown, false);
00278 }
00279 
00280 MDNode *MDNode::getTemporary(LLVMContext &Context, ArrayRef<Value*> Vals) {
00281   MDNode *N =
00282     (MDNode *)malloc(sizeof(MDNode) + Vals.size() * sizeof(MDNodeOperand));
00283   N = new (N) MDNode(Context, Vals, FL_No);
00284   N->setValueSubclassData(N->getSubclassDataFromValue() |
00285                           NotUniquedBit);
00286   LeakDetector::addGarbageObject(N);
00287   return N;
00288 }
00289 
00290 void MDNode::deleteTemporary(MDNode *N) {
00291   assert(N->use_empty() && "Temporary MDNode has uses!");
00292   assert(!N->getContext().pImpl->MDNodeSet.RemoveNode(N) &&
00293          "Deleting a non-temporary uniqued node!");
00294   assert(!N->getContext().pImpl->NonUniquedMDNodes.erase(N) &&
00295          "Deleting a non-temporary non-uniqued node!");
00296   assert((N->getSubclassDataFromValue() & NotUniquedBit) &&
00297          "Temporary MDNode does not have NotUniquedBit set!");
00298   assert((N->getSubclassDataFromValue() & DestroyFlag) == 0 &&
00299          "Temporary MDNode has DestroyFlag set!");
00300   LeakDetector::removeGarbageObject(N);
00301   N->destroy();
00302 }
00303 
00304 /// getOperand - Return specified operand.
00305 Value *MDNode::getOperand(unsigned i) const {
00306   assert(i < getNumOperands() && "Invalid operand number");
00307   return *getOperandPtr(const_cast<MDNode*>(this), i);
00308 }
00309 
00310 void MDNode::Profile(FoldingSetNodeID &ID) const {
00311   // Add all the operand pointers. Note that we don't have to add the
00312   // isFunctionLocal bit because that's implied by the operands.
00313   // Note that if the operands are later nulled out, the node will be
00314   // removed from the uniquing map.
00315   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
00316     ID.AddPointer(getOperand(i));
00317 }
00318 
00319 void MDNode::setIsNotUniqued() {
00320   setValueSubclassData(getSubclassDataFromValue() | NotUniquedBit);
00321   LLVMContextImpl *pImpl = getType()->getContext().pImpl;
00322   pImpl->NonUniquedMDNodes.insert(this);
00323 }
00324 
00325 // Replace value from this node's operand list.
00326 void MDNode::replaceOperand(MDNodeOperand *Op, Value *To) {
00327   Value *From = *Op;
00328 
00329   // If is possible that someone did GV->RAUW(inst), replacing a global variable
00330   // with an instruction or some other function-local object.  If this is a
00331   // non-function-local MDNode, it can't point to a function-local object.
00332   // Handle this case by implicitly dropping the MDNode reference to null.
00333   // Likewise if the MDNode is function-local but for a different function.
00334   if (To && isFunctionLocalValue(To)) {
00335     if (!isFunctionLocal())
00336       To = 0;
00337     else {
00338       const Function *F = getFunction();
00339       const Function *FV = getFunctionForValue(To);
00340       // Metadata can be function-local without having an associated function.
00341       // So only consider functions to have changed if non-null.
00342       if (F && FV && F != FV)
00343         To = 0;
00344     }
00345   }
00346   
00347   if (From == To)
00348     return;
00349 
00350   // Update the operand.
00351   Op->set(To);
00352 
00353   // If this node is already not being uniqued (because one of the operands
00354   // already went to null), then there is nothing else to do here.
00355   if (isNotUniqued()) return;
00356 
00357   LLVMContextImpl *pImpl = getType()->getContext().pImpl;
00358 
00359   // Remove "this" from the context map.  FoldingSet doesn't have to reprofile
00360   // this node to remove it, so we don't care what state the operands are in.
00361   pImpl->MDNodeSet.RemoveNode(this);
00362 
00363   // If we are dropping an argument to null, we choose to not unique the MDNode
00364   // anymore.  This commonly occurs during destruction, and uniquing these
00365   // brings little reuse.  Also, this means we don't need to include
00366   // isFunctionLocal bits in FoldingSetNodeIDs for MDNodes.
00367   if (To == 0) {
00368     setIsNotUniqued();
00369     return;
00370   }
00371 
00372   // Now that the node is out of the folding set, get ready to reinsert it.
00373   // First, check to see if another node with the same operands already exists
00374   // in the set.  If so, then this node is redundant.
00375   FoldingSetNodeID ID;
00376   Profile(ID);
00377   void *InsertPoint;
00378   if (MDNode *N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint)) {
00379     replaceAllUsesWith(N);
00380     destroy();
00381     return;
00382   }
00383 
00384   // Cache the operand hash.
00385   Hash = ID.ComputeHash();
00386   // InsertPoint will have been set by the FindNodeOrInsertPos call.
00387   pImpl->MDNodeSet.InsertNode(this, InsertPoint);
00388 
00389   // If this MDValue was previously function-local but no longer is, clear
00390   // its function-local flag.
00391   if (isFunctionLocal() && !isFunctionLocalValue(To)) {
00392     bool isStillFunctionLocal = false;
00393     for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
00394       Value *V = getOperand(i);
00395       if (!V) continue;
00396       if (isFunctionLocalValue(V)) {
00397         isStillFunctionLocal = true;
00398         break;
00399       }
00400     }
00401     if (!isStillFunctionLocal)
00402       setValueSubclassData(getSubclassDataFromValue() & ~FunctionLocalBit);
00403   }
00404 }
00405 
00406 MDNode *MDNode::getMostGenericFPMath(MDNode *A, MDNode *B) {
00407   if (!A || !B)
00408     return NULL;
00409 
00410   APFloat AVal = cast<ConstantFP>(A->getOperand(0))->getValueAPF();
00411   APFloat BVal = cast<ConstantFP>(B->getOperand(0))->getValueAPF();
00412   if (AVal.compare(BVal) == APFloat::cmpLessThan)
00413     return A;
00414   return B;
00415 }
00416 
00417 static bool isContiguous(const ConstantRange &A, const ConstantRange &B) {
00418   return A.getUpper() == B.getLower() || A.getLower() == B.getUpper();
00419 }
00420 
00421 static bool canBeMerged(const ConstantRange &A, const ConstantRange &B) {
00422   return !A.intersectWith(B).isEmptySet() || isContiguous(A, B);
00423 }
00424 
00425 static bool tryMergeRange(SmallVector<Value*, 4> &EndPoints, ConstantInt *Low,
00426                           ConstantInt *High) {
00427   ConstantRange NewRange(Low->getValue(), High->getValue());
00428   unsigned Size = EndPoints.size();
00429   APInt LB = cast<ConstantInt>(EndPoints[Size - 2])->getValue();
00430   APInt LE = cast<ConstantInt>(EndPoints[Size - 1])->getValue();
00431   ConstantRange LastRange(LB, LE);
00432   if (canBeMerged(NewRange, LastRange)) {
00433     ConstantRange Union = LastRange.unionWith(NewRange);
00434     Type *Ty = High->getType();
00435     EndPoints[Size - 2] = ConstantInt::get(Ty, Union.getLower());
00436     EndPoints[Size - 1] = ConstantInt::get(Ty, Union.getUpper());
00437     return true;
00438   }
00439   return false;
00440 }
00441 
00442 static void addRange(SmallVector<Value*, 4> &EndPoints, ConstantInt *Low,
00443                      ConstantInt *High) {
00444   if (!EndPoints.empty())
00445     if (tryMergeRange(EndPoints, Low, High))
00446       return;
00447 
00448   EndPoints.push_back(Low);
00449   EndPoints.push_back(High);
00450 }
00451 
00452 MDNode *MDNode::getMostGenericRange(MDNode *A, MDNode *B) {
00453   // Given two ranges, we want to compute the union of the ranges. This
00454   // is slightly complitade by having to combine the intervals and merge
00455   // the ones that overlap.
00456 
00457   if (!A || !B)
00458     return NULL;
00459 
00460   if (A == B)
00461     return A;
00462 
00463   // First, walk both lists in older of the lower boundary of each interval.
00464   // At each step, try to merge the new interval to the last one we adedd.
00465   SmallVector<Value*, 4> EndPoints;
00466   int AI = 0;
00467   int BI = 0;
00468   int AN = A->getNumOperands() / 2;
00469   int BN = B->getNumOperands() / 2;
00470   while (AI < AN && BI < BN) {
00471     ConstantInt *ALow = cast<ConstantInt>(A->getOperand(2 * AI));
00472     ConstantInt *BLow = cast<ConstantInt>(B->getOperand(2 * BI));
00473 
00474     if (ALow->getValue().slt(BLow->getValue())) {
00475       addRange(EndPoints, ALow, cast<ConstantInt>(A->getOperand(2 * AI + 1)));
00476       ++AI;
00477     } else {
00478       addRange(EndPoints, BLow, cast<ConstantInt>(B->getOperand(2 * BI + 1)));
00479       ++BI;
00480     }
00481   }
00482   while (AI < AN) {
00483     addRange(EndPoints, cast<ConstantInt>(A->getOperand(2 * AI)),
00484              cast<ConstantInt>(A->getOperand(2 * AI + 1)));
00485     ++AI;
00486   }
00487   while (BI < BN) {
00488     addRange(EndPoints, cast<ConstantInt>(B->getOperand(2 * BI)),
00489              cast<ConstantInt>(B->getOperand(2 * BI + 1)));
00490     ++BI;
00491   }
00492 
00493   // If we have more than 2 ranges (4 endpoints) we have to try to merge
00494   // the last and first ones.
00495   unsigned Size = EndPoints.size();
00496   if (Size > 4) {
00497     ConstantInt *FB = cast<ConstantInt>(EndPoints[0]);
00498     ConstantInt *FE = cast<ConstantInt>(EndPoints[1]);
00499     if (tryMergeRange(EndPoints, FB, FE)) {
00500       for (unsigned i = 0; i < Size - 2; ++i) {
00501         EndPoints[i] = EndPoints[i + 2];
00502       }
00503       EndPoints.resize(Size - 2);
00504     }
00505   }
00506 
00507   // If in the end we have a single range, it is possible that it is now the
00508   // full range. Just drop the metadata in that case.
00509   if (EndPoints.size() == 2) {
00510     ConstantRange Range(cast<ConstantInt>(EndPoints[0])->getValue(),
00511                         cast<ConstantInt>(EndPoints[1])->getValue());
00512     if (Range.isFullSet())
00513       return NULL;
00514   }
00515 
00516   return MDNode::get(A->getContext(), EndPoints);
00517 }
00518 
00519 //===----------------------------------------------------------------------===//
00520 // NamedMDNode implementation.
00521 //
00522 
00523 static SmallVector<TrackingVH<MDNode>, 4> &getNMDOps(void *Operands) {
00524   return *(SmallVector<TrackingVH<MDNode>, 4>*)Operands;
00525 }
00526 
00527 NamedMDNode::NamedMDNode(const Twine &N)
00528   : Name(N.str()), Parent(0),
00529     Operands(new SmallVector<TrackingVH<MDNode>, 4>()) {
00530 }
00531 
00532 NamedMDNode::~NamedMDNode() {
00533   dropAllReferences();
00534   delete &getNMDOps(Operands);
00535 }
00536 
00537 /// getNumOperands - Return number of NamedMDNode operands.
00538 unsigned NamedMDNode::getNumOperands() const {
00539   return (unsigned)getNMDOps(Operands).size();
00540 }
00541 
00542 /// getOperand - Return specified operand.
00543 MDNode *NamedMDNode::getOperand(unsigned i) const {
00544   assert(i < getNumOperands() && "Invalid Operand number!");
00545   return dyn_cast<MDNode>(&*getNMDOps(Operands)[i]);
00546 }
00547 
00548 /// addOperand - Add metadata Operand.
00549 void NamedMDNode::addOperand(MDNode *M) {
00550   assert(!M->isFunctionLocal() &&
00551          "NamedMDNode operands must not be function-local!");
00552   getNMDOps(Operands).push_back(TrackingVH<MDNode>(M));
00553 }
00554 
00555 /// eraseFromParent - Drop all references and remove the node from parent
00556 /// module.
00557 void NamedMDNode::eraseFromParent() {
00558   getParent()->eraseNamedMetadata(this);
00559 }
00560 
00561 /// dropAllReferences - Remove all uses and clear node vector.
00562 void NamedMDNode::dropAllReferences() {
00563   getNMDOps(Operands).clear();
00564 }
00565 
00566 /// getName - Return a constant reference to this named metadata's name.
00567 StringRef NamedMDNode::getName() const {
00568   return StringRef(Name);
00569 }
00570 
00571 //===----------------------------------------------------------------------===//
00572 // Instruction Metadata method implementations.
00573 //
00574 
00575 void Instruction::setMetadata(StringRef Kind, MDNode *Node) {
00576   if (Node == 0 && !hasMetadata()) return;
00577   setMetadata(getContext().getMDKindID(Kind), Node);
00578 }
00579 
00580 MDNode *Instruction::getMetadataImpl(StringRef Kind) const {
00581   return getMetadataImpl(getContext().getMDKindID(Kind));
00582 }
00583 
00584 /// setMetadata - Set the metadata of of the specified kind to the specified
00585 /// node.  This updates/replaces metadata if already present, or removes it if
00586 /// Node is null.
00587 void Instruction::setMetadata(unsigned KindID, MDNode *Node) {
00588   if (Node == 0 && !hasMetadata()) return;
00589 
00590   // Handle 'dbg' as a special case since it is not stored in the hash table.
00591   if (KindID == LLVMContext::MD_dbg) {
00592     DbgLoc = DebugLoc::getFromDILocation(Node);
00593     return;
00594   }
00595   
00596   // Handle the case when we're adding/updating metadata on an instruction.
00597   if (Node) {
00598     LLVMContextImpl::MDMapTy &Info = getContext().pImpl->MetadataStore[this];
00599     assert(!Info.empty() == hasMetadataHashEntry() &&
00600            "HasMetadata bit is wonked");
00601     if (Info.empty()) {
00602       setHasMetadataHashEntry(true);
00603     } else {
00604       // Handle replacement of an existing value.
00605       for (unsigned i = 0, e = Info.size(); i != e; ++i)
00606         if (Info[i].first == KindID) {
00607           Info[i].second = Node;
00608           return;
00609         }
00610     }
00611 
00612     // No replacement, just add it to the list.
00613     Info.push_back(std::make_pair(KindID, Node));
00614     return;
00615   }
00616 
00617   // Otherwise, we're removing metadata from an instruction.
00618   assert((hasMetadataHashEntry() ==
00619           getContext().pImpl->MetadataStore.count(this)) &&
00620          "HasMetadata bit out of date!");
00621   if (!hasMetadataHashEntry())
00622     return;  // Nothing to remove!
00623   LLVMContextImpl::MDMapTy &Info = getContext().pImpl->MetadataStore[this];
00624 
00625   // Common case is removing the only entry.
00626   if (Info.size() == 1 && Info[0].first == KindID) {
00627     getContext().pImpl->MetadataStore.erase(this);
00628     setHasMetadataHashEntry(false);
00629     return;
00630   }
00631 
00632   // Handle removal of an existing value.
00633   for (unsigned i = 0, e = Info.size(); i != e; ++i)
00634     if (Info[i].first == KindID) {
00635       Info[i] = Info.back();
00636       Info.pop_back();
00637       assert(!Info.empty() && "Removing last entry should be handled above");
00638       return;
00639     }
00640   // Otherwise, removing an entry that doesn't exist on the instruction.
00641 }
00642 
00643 MDNode *Instruction::getMetadataImpl(unsigned KindID) const {
00644   // Handle 'dbg' as a special case since it is not stored in the hash table.
00645   if (KindID == LLVMContext::MD_dbg)
00646     return DbgLoc.getAsMDNode(getContext());
00647   
00648   if (!hasMetadataHashEntry()) return 0;
00649   
00650   LLVMContextImpl::MDMapTy &Info = getContext().pImpl->MetadataStore[this];
00651   assert(!Info.empty() && "bit out of sync with hash table");
00652 
00653   for (LLVMContextImpl::MDMapTy::iterator I = Info.begin(), E = Info.end();
00654        I != E; ++I)
00655     if (I->first == KindID)
00656       return I->second;
00657   return 0;
00658 }
00659 
00660 void Instruction::getAllMetadataImpl(SmallVectorImpl<std::pair<unsigned,
00661                                        MDNode*> > &Result) const {
00662   Result.clear();
00663   
00664   // Handle 'dbg' as a special case since it is not stored in the hash table.
00665   if (!DbgLoc.isUnknown()) {
00666     Result.push_back(std::make_pair((unsigned)LLVMContext::MD_dbg,
00667                                     DbgLoc.getAsMDNode(getContext())));
00668     if (!hasMetadataHashEntry()) return;
00669   }
00670   
00671   assert(hasMetadataHashEntry() &&
00672          getContext().pImpl->MetadataStore.count(this) &&
00673          "Shouldn't have called this");
00674   const LLVMContextImpl::MDMapTy &Info =
00675     getContext().pImpl->MetadataStore.find(this)->second;
00676   assert(!Info.empty() && "Shouldn't have called this");
00677 
00678   Result.append(Info.begin(), Info.end());
00679 
00680   // Sort the resulting array so it is stable.
00681   if (Result.size() > 1)
00682     array_pod_sort(Result.begin(), Result.end());
00683 }
00684 
00685 void Instruction::
00686 getAllMetadataOtherThanDebugLocImpl(SmallVectorImpl<std::pair<unsigned,
00687                                     MDNode*> > &Result) const {
00688   Result.clear();
00689   assert(hasMetadataHashEntry() &&
00690          getContext().pImpl->MetadataStore.count(this) &&
00691          "Shouldn't have called this");
00692   const LLVMContextImpl::MDMapTy &Info =
00693     getContext().pImpl->MetadataStore.find(this)->second;
00694   assert(!Info.empty() && "Shouldn't have called this");
00695   Result.append(Info.begin(), Info.end());
00696 
00697   // Sort the resulting array so it is stable.
00698   if (Result.size() > 1)
00699     array_pod_sort(Result.begin(), Result.end());
00700 }
00701 
00702 /// clearMetadataHashEntries - Clear all hashtable-based metadata from
00703 /// this instruction.
00704 void Instruction::clearMetadataHashEntries() {
00705   assert(hasMetadataHashEntry() && "Caller should check");
00706   getContext().pImpl->MetadataStore.erase(this);
00707   setHasMetadataHashEntry(false);
00708 }
00709