LLVM API Documentation

Value.cpp
Go to the documentation of this file.
00001 //===-- Value.cpp - Implement the Value class -----------------------------===//
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 Value, ValueHandle, and User classes.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "llvm/IR/Value.h"
00015 #include "LLVMContextImpl.h"
00016 #include "llvm/ADT/DenseMap.h"
00017 #include "llvm/ADT/SmallString.h"
00018 #include "llvm/IR/Constant.h"
00019 #include "llvm/IR/Constants.h"
00020 #include "llvm/IR/DerivedTypes.h"
00021 #include "llvm/IR/GetElementPtrTypeIterator.h"
00022 #include "llvm/IR/InstrTypes.h"
00023 #include "llvm/IR/Instructions.h"
00024 #include "llvm/IR/LeakDetector.h"
00025 #include "llvm/IR/Module.h"
00026 #include "llvm/IR/Operator.h"
00027 #include "llvm/IR/ValueHandle.h"
00028 #include "llvm/IR/ValueSymbolTable.h"
00029 #include "llvm/Support/Debug.h"
00030 #include "llvm/Support/ErrorHandling.h"
00031 #include "llvm/Support/ManagedStatic.h"
00032 #include <algorithm>
00033 using namespace llvm;
00034 
00035 //===----------------------------------------------------------------------===//
00036 //                                Value Class
00037 //===----------------------------------------------------------------------===//
00038 
00039 static inline Type *checkType(Type *Ty) {
00040   assert(Ty && "Value defined with a null type: Error!");
00041   return const_cast<Type*>(Ty);
00042 }
00043 
00044 Value::Value(Type *ty, unsigned scid)
00045   : SubclassID(scid), HasValueHandle(0),
00046     SubclassOptionalData(0), SubclassData(0), VTy((Type*)checkType(ty)),
00047     UseList(nullptr), Name(nullptr) {
00048   // FIXME: Why isn't this in the subclass gunk??
00049   // Note, we cannot call isa<CallInst> before the CallInst has been
00050   // constructed.
00051   if (SubclassID == Instruction::Call || SubclassID == Instruction::Invoke)
00052     assert((VTy->isFirstClassType() || VTy->isVoidTy() || VTy->isStructTy()) &&
00053            "invalid CallInst type!");
00054   else if (SubclassID != BasicBlockVal &&
00055            (SubclassID < ConstantFirstVal || SubclassID > ConstantLastVal))
00056     assert((VTy->isFirstClassType() || VTy->isVoidTy()) &&
00057            "Cannot create non-first-class values except for constants!");
00058 }
00059 
00060 Value::~Value() {
00061   // Notify all ValueHandles (if present) that this value is going away.
00062   if (HasValueHandle)
00063     ValueHandleBase::ValueIsDeleted(this);
00064 
00065 #ifndef NDEBUG      // Only in -g mode...
00066   // Check to make sure that there are no uses of this value that are still
00067   // around when the value is destroyed.  If there are, then we have a dangling
00068   // reference and something is wrong.  This code is here to print out what is
00069   // still being referenced.  The value in question should be printed as
00070   // a <badref>
00071   //
00072   if (!use_empty()) {
00073     dbgs() << "While deleting: " << *VTy << " %" << getName() << "\n";
00074     for (use_iterator I = use_begin(), E = use_end(); I != E; ++I)
00075       dbgs() << "Use still stuck around after Def is destroyed:"
00076            << **I << "\n";
00077   }
00078 #endif
00079   assert(use_empty() && "Uses remain when a value is destroyed!");
00080 
00081   // If this value is named, destroy the name.  This should not be in a symtab
00082   // at this point.
00083   if (Name && SubclassID != MDStringVal)
00084     Name->Destroy();
00085 
00086   // There should be no uses of this object anymore, remove it.
00087   LeakDetector::removeGarbageObject(this);
00088 }
00089 
00090 /// hasNUses - Return true if this Value has exactly N users.
00091 ///
00092 bool Value::hasNUses(unsigned N) const {
00093   const_use_iterator UI = use_begin(), E = use_end();
00094 
00095   for (; N; --N, ++UI)
00096     if (UI == E) return false;  // Too few.
00097   return UI == E;
00098 }
00099 
00100 /// hasNUsesOrMore - Return true if this value has N users or more.  This is
00101 /// logically equivalent to getNumUses() >= N.
00102 ///
00103 bool Value::hasNUsesOrMore(unsigned N) const {
00104   const_use_iterator UI = use_begin(), E = use_end();
00105 
00106   for (; N; --N, ++UI)
00107     if (UI == E) return false;  // Too few.
00108 
00109   return true;
00110 }
00111 
00112 /// isUsedInBasicBlock - Return true if this value is used in the specified
00113 /// basic block.
00114 bool Value::isUsedInBasicBlock(const BasicBlock *BB) const {
00115   // This can be computed either by scanning the instructions in BB, or by
00116   // scanning the use list of this Value. Both lists can be very long, but
00117   // usually one is quite short.
00118   //
00119   // Scan both lists simultaneously until one is exhausted. This limits the
00120   // search to the shorter list.
00121   BasicBlock::const_iterator BI = BB->begin(), BE = BB->end();
00122   const_user_iterator UI = user_begin(), UE = user_end();
00123   for (; BI != BE && UI != UE; ++BI, ++UI) {
00124     // Scan basic block: Check if this Value is used by the instruction at BI.
00125     if (std::find(BI->op_begin(), BI->op_end(), this) != BI->op_end())
00126       return true;
00127     // Scan use list: Check if the use at UI is in BB.
00128     const Instruction *User = dyn_cast<Instruction>(*UI);
00129     if (User && User->getParent() == BB)
00130       return true;
00131   }
00132   return false;
00133 }
00134 
00135 
00136 /// getNumUses - This method computes the number of uses of this Value.  This
00137 /// is a linear time operation.  Use hasOneUse or hasNUses to check for specific
00138 /// values.
00139 unsigned Value::getNumUses() const {
00140   return (unsigned)std::distance(use_begin(), use_end());
00141 }
00142 
00143 static bool getSymTab(Value *V, ValueSymbolTable *&ST) {
00144   ST = nullptr;
00145   if (Instruction *I = dyn_cast<Instruction>(V)) {
00146     if (BasicBlock *P = I->getParent())
00147       if (Function *PP = P->getParent())
00148         ST = &PP->getValueSymbolTable();
00149   } else if (BasicBlock *BB = dyn_cast<BasicBlock>(V)) {
00150     if (Function *P = BB->getParent())
00151       ST = &P->getValueSymbolTable();
00152   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
00153     if (Module *P = GV->getParent())
00154       ST = &P->getValueSymbolTable();
00155   } else if (Argument *A = dyn_cast<Argument>(V)) {
00156     if (Function *P = A->getParent())
00157       ST = &P->getValueSymbolTable();
00158   } else if (isa<MDString>(V))
00159     return true;
00160   else {
00161     assert(isa<Constant>(V) && "Unknown value type!");
00162     return true;  // no name is setable for this.
00163   }
00164   return false;
00165 }
00166 
00167 StringRef Value::getName() const {
00168   // Make sure the empty string is still a C string. For historical reasons,
00169   // some clients want to call .data() on the result and expect it to be null
00170   // terminated.
00171   if (!Name) return StringRef("", 0);
00172   return Name->getKey();
00173 }
00174 
00175 void Value::setName(const Twine &NewName) {
00176   assert(SubclassID != MDStringVal &&
00177          "Cannot set the name of MDString with this method!");
00178 
00179   // Fast path for common IRBuilder case of setName("") when there is no name.
00180   if (NewName.isTriviallyEmpty() && !hasName())
00181     return;
00182 
00183   SmallString<256> NameData;
00184   StringRef NameRef = NewName.toStringRef(NameData);
00185   assert(NameRef.find_first_of(0) == StringRef::npos &&
00186          "Null bytes are not allowed in names");
00187 
00188   // Name isn't changing?
00189   if (getName() == NameRef)
00190     return;
00191 
00192   assert(!getType()->isVoidTy() && "Cannot assign a name to void values!");
00193 
00194   // Get the symbol table to update for this object.
00195   ValueSymbolTable *ST;
00196   if (getSymTab(this, ST))
00197     return;  // Cannot set a name on this value (e.g. constant).
00198 
00199   if (Function *F = dyn_cast<Function>(this))
00200     getContext().pImpl->IntrinsicIDCache.erase(F);
00201 
00202   if (!ST) { // No symbol table to update?  Just do the change.
00203     if (NameRef.empty()) {
00204       // Free the name for this value.
00205       Name->Destroy();
00206       Name = nullptr;
00207       return;
00208     }
00209 
00210     if (Name)
00211       Name->Destroy();
00212 
00213     // NOTE: Could optimize for the case the name is shrinking to not deallocate
00214     // then reallocated.
00215 
00216     // Create the new name.
00217     Name = ValueName::Create(NameRef.begin(), NameRef.end());
00218     Name->setValue(this);
00219     return;
00220   }
00221 
00222   // NOTE: Could optimize for the case the name is shrinking to not deallocate
00223   // then reallocated.
00224   if (hasName()) {
00225     // Remove old name.
00226     ST->removeValueName(Name);
00227     Name->Destroy();
00228     Name = nullptr;
00229 
00230     if (NameRef.empty())
00231       return;
00232   }
00233 
00234   // Name is changing to something new.
00235   Name = ST->createValueName(NameRef, this);
00236 }
00237 
00238 
00239 /// takeName - transfer the name from V to this value, setting V's name to
00240 /// empty.  It is an error to call V->takeName(V).
00241 void Value::takeName(Value *V) {
00242   assert(SubclassID != MDStringVal && "Cannot take the name of an MDString!");
00243 
00244   ValueSymbolTable *ST = nullptr;
00245   // If this value has a name, drop it.
00246   if (hasName()) {
00247     // Get the symtab this is in.
00248     if (getSymTab(this, ST)) {
00249       // We can't set a name on this value, but we need to clear V's name if
00250       // it has one.
00251       if (V->hasName()) V->setName("");
00252       return;  // Cannot set a name on this value (e.g. constant).
00253     }
00254 
00255     // Remove old name.
00256     if (ST)
00257       ST->removeValueName(Name);
00258     Name->Destroy();
00259     Name = nullptr;
00260   }
00261 
00262   // Now we know that this has no name.
00263 
00264   // If V has no name either, we're done.
00265   if (!V->hasName()) return;
00266 
00267   // Get this's symtab if we didn't before.
00268   if (!ST) {
00269     if (getSymTab(this, ST)) {
00270       // Clear V's name.
00271       V->setName("");
00272       return;  // Cannot set a name on this value (e.g. constant).
00273     }
00274   }
00275 
00276   // Get V's ST, this should always succed, because V has a name.
00277   ValueSymbolTable *VST;
00278   bool Failure = getSymTab(V, VST);
00279   assert(!Failure && "V has a name, so it should have a ST!"); (void)Failure;
00280 
00281   // If these values are both in the same symtab, we can do this very fast.
00282   // This works even if both values have no symtab yet.
00283   if (ST == VST) {
00284     // Take the name!
00285     Name = V->Name;
00286     V->Name = nullptr;
00287     Name->setValue(this);
00288     return;
00289   }
00290 
00291   // Otherwise, things are slightly more complex.  Remove V's name from VST and
00292   // then reinsert it into ST.
00293 
00294   if (VST)
00295     VST->removeValueName(V->Name);
00296   Name = V->Name;
00297   V->Name = nullptr;
00298   Name->setValue(this);
00299 
00300   if (ST)
00301     ST->reinsertValue(this);
00302 }
00303 
00304 
00305 void Value::replaceAllUsesWith(Value *New) {
00306   assert(New && "Value::replaceAllUsesWith(<null>) is invalid!");
00307   assert(New != this && "this->replaceAllUsesWith(this) is NOT valid!");
00308   assert(New->getType() == getType() &&
00309          "replaceAllUses of value with new value of different type!");
00310 
00311   // Notify all ValueHandles (if present) that this value is going away.
00312   if (HasValueHandle)
00313     ValueHandleBase::ValueIsRAUWd(this, New);
00314 
00315   while (!use_empty()) {
00316     Use &U = *UseList;
00317     // Must handle Constants specially, we cannot call replaceUsesOfWith on a
00318     // constant because they are uniqued.
00319     if (Constant *C = dyn_cast<Constant>(U.getUser())) {
00320       if (!isa<GlobalValue>(C)) {
00321         C->replaceUsesOfWithOnConstant(this, New, &U);
00322         continue;
00323       }
00324     }
00325 
00326     U.set(New);
00327   }
00328 
00329   if (BasicBlock *BB = dyn_cast<BasicBlock>(this))
00330     BB->replaceSuccessorsPhiUsesWith(cast<BasicBlock>(New));
00331 }
00332 
00333 namespace {
00334 // Various metrics for how much to strip off of pointers.
00335 enum PointerStripKind {
00336   PSK_ZeroIndices,
00337   PSK_ZeroIndicesAndAliases,
00338   PSK_InBoundsConstantIndices,
00339   PSK_InBounds
00340 };
00341 
00342 template <PointerStripKind StripKind>
00343 static Value *stripPointerCastsAndOffsets(Value *V) {
00344   if (!V->getType()->isPointerTy())
00345     return V;
00346 
00347   // Even though we don't look through PHI nodes, we could be called on an
00348   // instruction in an unreachable block, which may be on a cycle.
00349   SmallPtrSet<Value *, 4> Visited;
00350 
00351   Visited.insert(V);
00352   do {
00353     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
00354       switch (StripKind) {
00355       case PSK_ZeroIndicesAndAliases:
00356       case PSK_ZeroIndices:
00357         if (!GEP->hasAllZeroIndices())
00358           return V;
00359         break;
00360       case PSK_InBoundsConstantIndices:
00361         if (!GEP->hasAllConstantIndices())
00362           return V;
00363         // fallthrough
00364       case PSK_InBounds:
00365         if (!GEP->isInBounds())
00366           return V;
00367         break;
00368       }
00369       V = GEP->getPointerOperand();
00370     } else if (Operator::getOpcode(V) == Instruction::BitCast ||
00371                Operator::getOpcode(V) == Instruction::AddrSpaceCast) {
00372       V = cast<Operator>(V)->getOperand(0);
00373     } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
00374       if (StripKind == PSK_ZeroIndices || GA->mayBeOverridden())
00375         return V;
00376       V = GA->getAliasee();
00377     } else {
00378       return V;
00379     }
00380     assert(V->getType()->isPointerTy() && "Unexpected operand type!");
00381   } while (Visited.insert(V));
00382 
00383   return V;
00384 }
00385 } // namespace
00386 
00387 Value *Value::stripPointerCasts() {
00388   return stripPointerCastsAndOffsets<PSK_ZeroIndicesAndAliases>(this);
00389 }
00390 
00391 Value *Value::stripPointerCastsNoFollowAliases() {
00392   return stripPointerCastsAndOffsets<PSK_ZeroIndices>(this);
00393 }
00394 
00395 Value *Value::stripInBoundsConstantOffsets() {
00396   return stripPointerCastsAndOffsets<PSK_InBoundsConstantIndices>(this);
00397 }
00398 
00399 Value *Value::stripAndAccumulateInBoundsConstantOffsets(const DataLayout &DL,
00400                                                         APInt &Offset) {
00401   if (!getType()->isPointerTy())
00402     return this;
00403 
00404   assert(Offset.getBitWidth() == DL.getPointerSizeInBits(cast<PointerType>(
00405                                      getType())->getAddressSpace()) &&
00406          "The offset must have exactly as many bits as our pointer.");
00407 
00408   // Even though we don't look through PHI nodes, we could be called on an
00409   // instruction in an unreachable block, which may be on a cycle.
00410   SmallPtrSet<Value *, 4> Visited;
00411   Visited.insert(this);
00412   Value *V = this;
00413   do {
00414     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
00415       if (!GEP->isInBounds())
00416         return V;
00417       APInt GEPOffset(Offset);
00418       if (!GEP->accumulateConstantOffset(DL, GEPOffset))
00419         return V;
00420       Offset = GEPOffset;
00421       V = GEP->getPointerOperand();
00422     } else if (Operator::getOpcode(V) == Instruction::BitCast) {
00423       V = cast<Operator>(V)->getOperand(0);
00424     } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
00425       V = GA->getAliasee();
00426     } else {
00427       return V;
00428     }
00429     assert(V->getType()->isPointerTy() && "Unexpected operand type!");
00430   } while (Visited.insert(V));
00431 
00432   return V;
00433 }
00434 
00435 Value *Value::stripInBoundsOffsets() {
00436   return stripPointerCastsAndOffsets<PSK_InBounds>(this);
00437 }
00438 
00439 /// isDereferenceablePointer - Test if this value is always a pointer to
00440 /// allocated and suitably aligned memory for a simple load or store.
00441 static bool isDereferenceablePointer(const Value *V,
00442                                      SmallPtrSet<const Value *, 32> &Visited) {
00443   // Note that it is not safe to speculate into a malloc'd region because
00444   // malloc may return null.
00445   // It's also not always safe to follow a bitcast, for example:
00446   //   bitcast i8* (alloca i8) to i32*
00447   // would result in a 4-byte load from a 1-byte alloca. Some cases could
00448   // be handled using DataLayout to check sizes and alignments though.
00449 
00450   // These are obviously ok.
00451   if (isa<AllocaInst>(V)) return true;
00452 
00453   // Global variables which can't collapse to null are ok.
00454   if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
00455     return !GV->hasExternalWeakLinkage();
00456 
00457   // byval arguments are ok.
00458   if (const Argument *A = dyn_cast<Argument>(V))
00459     return A->hasByValAttr();
00460 
00461   // For GEPs, determine if the indexing lands within the allocated object.
00462   if (const GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
00463     // Conservatively require that the base pointer be fully dereferenceable.
00464     if (!Visited.insert(GEP->getOperand(0)))
00465       return false;
00466     if (!isDereferenceablePointer(GEP->getOperand(0), Visited))
00467       return false;
00468     // Check the indices.
00469     gep_type_iterator GTI = gep_type_begin(GEP);
00470     for (User::const_op_iterator I = GEP->op_begin()+1,
00471          E = GEP->op_end(); I != E; ++I) {
00472       Value *Index = *I;
00473       Type *Ty = *GTI++;
00474       // Struct indices can't be out of bounds.
00475       if (isa<StructType>(Ty))
00476         continue;
00477       ConstantInt *CI = dyn_cast<ConstantInt>(Index);
00478       if (!CI)
00479         return false;
00480       // Zero is always ok.
00481       if (CI->isZero())
00482         continue;
00483       // Check to see that it's within the bounds of an array.
00484       ArrayType *ATy = dyn_cast<ArrayType>(Ty);
00485       if (!ATy)
00486         return false;
00487       if (CI->getValue().getActiveBits() > 64)
00488         return false;
00489       if (CI->getZExtValue() >= ATy->getNumElements())
00490         return false;
00491     }
00492     // Indices check out; this is dereferenceable.
00493     return true;
00494   }
00495 
00496   // If we don't know, assume the worst.
00497   return false;
00498 }
00499 
00500 /// isDereferenceablePointer - Test if this value is always a pointer to
00501 /// allocated and suitably aligned memory for a simple load or store.
00502 bool Value::isDereferenceablePointer() const {
00503   SmallPtrSet<const Value *, 32> Visited;
00504   return ::isDereferenceablePointer(this, Visited);
00505 }
00506 
00507 /// DoPHITranslation - If this value is a PHI node with CurBB as its parent,
00508 /// return the value in the PHI node corresponding to PredBB.  If not, return
00509 /// ourself.  This is useful if you want to know the value something has in a
00510 /// predecessor block.
00511 Value *Value::DoPHITranslation(const BasicBlock *CurBB,
00512                                const BasicBlock *PredBB) {
00513   PHINode *PN = dyn_cast<PHINode>(this);
00514   if (PN && PN->getParent() == CurBB)
00515     return PN->getIncomingValueForBlock(PredBB);
00516   return this;
00517 }
00518 
00519 LLVMContext &Value::getContext() const { return VTy->getContext(); }
00520 
00521 //===----------------------------------------------------------------------===//
00522 //                             ValueHandleBase Class
00523 //===----------------------------------------------------------------------===//
00524 
00525 /// AddToExistingUseList - Add this ValueHandle to the use list for VP, where
00526 /// List is known to point into the existing use list.
00527 void ValueHandleBase::AddToExistingUseList(ValueHandleBase **List) {
00528   assert(List && "Handle list is null?");
00529 
00530   // Splice ourselves into the list.
00531   Next = *List;
00532   *List = this;
00533   setPrevPtr(List);
00534   if (Next) {
00535     Next->setPrevPtr(&Next);
00536     assert(VP.getPointer() == Next->VP.getPointer() && "Added to wrong list?");
00537   }
00538 }
00539 
00540 void ValueHandleBase::AddToExistingUseListAfter(ValueHandleBase *List) {
00541   assert(List && "Must insert after existing node");
00542 
00543   Next = List->Next;
00544   setPrevPtr(&List->Next);
00545   List->Next = this;
00546   if (Next)
00547     Next->setPrevPtr(&Next);
00548 }
00549 
00550 /// AddToUseList - Add this ValueHandle to the use list for VP.
00551 void ValueHandleBase::AddToUseList() {
00552   assert(VP.getPointer() && "Null pointer doesn't have a use list!");
00553 
00554   LLVMContextImpl *pImpl = VP.getPointer()->getContext().pImpl;
00555 
00556   if (VP.getPointer()->HasValueHandle) {
00557     // If this value already has a ValueHandle, then it must be in the
00558     // ValueHandles map already.
00559     ValueHandleBase *&Entry = pImpl->ValueHandles[VP.getPointer()];
00560     assert(Entry && "Value doesn't have any handles?");
00561     AddToExistingUseList(&Entry);
00562     return;
00563   }
00564 
00565   // Ok, it doesn't have any handles yet, so we must insert it into the
00566   // DenseMap.  However, doing this insertion could cause the DenseMap to
00567   // reallocate itself, which would invalidate all of the PrevP pointers that
00568   // point into the old table.  Handle this by checking for reallocation and
00569   // updating the stale pointers only if needed.
00570   DenseMap<Value*, ValueHandleBase*> &Handles = pImpl->ValueHandles;
00571   const void *OldBucketPtr = Handles.getPointerIntoBucketsArray();
00572 
00573   ValueHandleBase *&Entry = Handles[VP.getPointer()];
00574   assert(!Entry && "Value really did already have handles?");
00575   AddToExistingUseList(&Entry);
00576   VP.getPointer()->HasValueHandle = true;
00577 
00578   // If reallocation didn't happen or if this was the first insertion, don't
00579   // walk the table.
00580   if (Handles.isPointerIntoBucketsArray(OldBucketPtr) ||
00581       Handles.size() == 1) {
00582     return;
00583   }
00584 
00585   // Okay, reallocation did happen.  Fix the Prev Pointers.
00586   for (DenseMap<Value*, ValueHandleBase*>::iterator I = Handles.begin(),
00587        E = Handles.end(); I != E; ++I) {
00588     assert(I->second && I->first == I->second->VP.getPointer() &&
00589            "List invariant broken!");
00590     I->second->setPrevPtr(&I->second);
00591   }
00592 }
00593 
00594 /// RemoveFromUseList - Remove this ValueHandle from its current use list.
00595 void ValueHandleBase::RemoveFromUseList() {
00596   assert(VP.getPointer() && VP.getPointer()->HasValueHandle &&
00597          "Pointer doesn't have a use list!");
00598 
00599   // Unlink this from its use list.
00600   ValueHandleBase **PrevPtr = getPrevPtr();
00601   assert(*PrevPtr == this && "List invariant broken");
00602 
00603   *PrevPtr = Next;
00604   if (Next) {
00605     assert(Next->getPrevPtr() == &Next && "List invariant broken");
00606     Next->setPrevPtr(PrevPtr);
00607     return;
00608   }
00609 
00610   // If the Next pointer was null, then it is possible that this was the last
00611   // ValueHandle watching VP.  If so, delete its entry from the ValueHandles
00612   // map.
00613   LLVMContextImpl *pImpl = VP.getPointer()->getContext().pImpl;
00614   DenseMap<Value*, ValueHandleBase*> &Handles = pImpl->ValueHandles;
00615   if (Handles.isPointerIntoBucketsArray(PrevPtr)) {
00616     Handles.erase(VP.getPointer());
00617     VP.getPointer()->HasValueHandle = false;
00618   }
00619 }
00620 
00621 
00622 void ValueHandleBase::ValueIsDeleted(Value *V) {
00623   assert(V->HasValueHandle && "Should only be called if ValueHandles present");
00624 
00625   // Get the linked list base, which is guaranteed to exist since the
00626   // HasValueHandle flag is set.
00627   LLVMContextImpl *pImpl = V->getContext().pImpl;
00628   ValueHandleBase *Entry = pImpl->ValueHandles[V];
00629   assert(Entry && "Value bit set but no entries exist");
00630 
00631   // We use a local ValueHandleBase as an iterator so that ValueHandles can add
00632   // and remove themselves from the list without breaking our iteration.  This
00633   // is not really an AssertingVH; we just have to give ValueHandleBase a kind.
00634   // Note that we deliberately do not the support the case when dropping a value
00635   // handle results in a new value handle being permanently added to the list
00636   // (as might occur in theory for CallbackVH's): the new value handle will not
00637   // be processed and the checking code will mete out righteous punishment if
00638   // the handle is still present once we have finished processing all the other
00639   // value handles (it is fine to momentarily add then remove a value handle).
00640   for (ValueHandleBase Iterator(Assert, *Entry); Entry; Entry = Iterator.Next) {
00641     Iterator.RemoveFromUseList();
00642     Iterator.AddToExistingUseListAfter(Entry);
00643     assert(Entry->Next == &Iterator && "Loop invariant broken.");
00644 
00645     switch (Entry->getKind()) {
00646     case Assert:
00647       break;
00648     case Tracking:
00649       // Mark that this value has been deleted by setting it to an invalid Value
00650       // pointer.
00651       Entry->operator=(DenseMapInfo<Value *>::getTombstoneKey());
00652       break;
00653     case Weak:
00654       // Weak just goes to null, which will unlink it from the list.
00655       Entry->operator=(nullptr);
00656       break;
00657     case Callback:
00658       // Forward to the subclass's implementation.
00659       static_cast<CallbackVH*>(Entry)->deleted();
00660       break;
00661     }
00662   }
00663 
00664   // All callbacks, weak references, and assertingVHs should be dropped by now.
00665   if (V->HasValueHandle) {
00666 #ifndef NDEBUG      // Only in +Asserts mode...
00667     dbgs() << "While deleting: " << *V->getType() << " %" << V->getName()
00668            << "\n";
00669     if (pImpl->ValueHandles[V]->getKind() == Assert)
00670       llvm_unreachable("An asserting value handle still pointed to this"
00671                        " value!");
00672 
00673 #endif
00674     llvm_unreachable("All references to V were not removed?");
00675   }
00676 }
00677 
00678 
00679 void ValueHandleBase::ValueIsRAUWd(Value *Old, Value *New) {
00680   assert(Old->HasValueHandle &&"Should only be called if ValueHandles present");
00681   assert(Old != New && "Changing value into itself!");
00682 
00683   // Get the linked list base, which is guaranteed to exist since the
00684   // HasValueHandle flag is set.
00685   LLVMContextImpl *pImpl = Old->getContext().pImpl;
00686   ValueHandleBase *Entry = pImpl->ValueHandles[Old];
00687 
00688   assert(Entry && "Value bit set but no entries exist");
00689 
00690   // We use a local ValueHandleBase as an iterator so that
00691   // ValueHandles can add and remove themselves from the list without
00692   // breaking our iteration.  This is not really an AssertingVH; we
00693   // just have to give ValueHandleBase some kind.
00694   for (ValueHandleBase Iterator(Assert, *Entry); Entry; Entry = Iterator.Next) {
00695     Iterator.RemoveFromUseList();
00696     Iterator.AddToExistingUseListAfter(Entry);
00697     assert(Entry->Next == &Iterator && "Loop invariant broken.");
00698 
00699     switch (Entry->getKind()) {
00700     case Assert:
00701       // Asserting handle does not follow RAUW implicitly.
00702       break;
00703     case Tracking:
00704       // Tracking goes to new value like a WeakVH. Note that this may make it
00705       // something incompatible with its templated type. We don't want to have a
00706       // virtual (or inline) interface to handle this though, so instead we make
00707       // the TrackingVH accessors guarantee that a client never sees this value.
00708 
00709       // FALLTHROUGH
00710     case Weak:
00711       // Weak goes to the new value, which will unlink it from Old's list.
00712       Entry->operator=(New);
00713       break;
00714     case Callback:
00715       // Forward to the subclass's implementation.
00716       static_cast<CallbackVH*>(Entry)->allUsesReplacedWith(New);
00717       break;
00718     }
00719   }
00720 
00721 #ifndef NDEBUG
00722   // If any new tracking or weak value handles were added while processing the
00723   // list, then complain about it now.
00724   if (Old->HasValueHandle)
00725     for (Entry = pImpl->ValueHandles[Old]; Entry; Entry = Entry->Next)
00726       switch (Entry->getKind()) {
00727       case Tracking:
00728       case Weak:
00729         dbgs() << "After RAUW from " << *Old->getType() << " %"
00730                << Old->getName() << " to " << *New->getType() << " %"
00731                << New->getName() << "\n";
00732         llvm_unreachable("A tracking or weak value handle still pointed to the"
00733                          " old value!\n");
00734       default:
00735         break;
00736       }
00737 #endif
00738 }
00739 
00740 // Pin the vtable to this file.
00741 void CallbackVH::anchor() {}