Home | History | Annotate | Download | only in IR
      1 //===-- Value.cpp - Implement the Value class -----------------------------===//
      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 Value, ValueHandle, and User classes.
     11 //
     12 //===----------------------------------------------------------------------===//
     13 
     14 #include "llvm/IR/Value.h"
     15 #include "LLVMContextImpl.h"
     16 #include "llvm/ADT/DenseMap.h"
     17 #include "llvm/ADT/SmallString.h"
     18 #include "llvm/IR/Constant.h"
     19 #include "llvm/IR/Constants.h"
     20 #include "llvm/IR/DerivedTypes.h"
     21 #include "llvm/IR/InstrTypes.h"
     22 #include "llvm/IR/Instructions.h"
     23 #include "llvm/IR/Module.h"
     24 #include "llvm/IR/Operator.h"
     25 #include "llvm/IR/ValueSymbolTable.h"
     26 #include "llvm/Support/Debug.h"
     27 #include "llvm/Support/ErrorHandling.h"
     28 #include "llvm/Support/GetElementPtrTypeIterator.h"
     29 #include "llvm/Support/LeakDetector.h"
     30 #include "llvm/Support/ManagedStatic.h"
     31 #include "llvm/Support/ValueHandle.h"
     32 #include <algorithm>
     33 using namespace llvm;
     34 
     35 //===----------------------------------------------------------------------===//
     36 //                                Value Class
     37 //===----------------------------------------------------------------------===//
     38 
     39 static inline Type *checkType(Type *Ty) {
     40   assert(Ty && "Value defined with a null type: Error!");
     41   return const_cast<Type*>(Ty);
     42 }
     43 
     44 Value::Value(Type *ty, unsigned scid)
     45   : SubclassID(scid), HasValueHandle(0),
     46     SubclassOptionalData(0), SubclassData(0), VTy((Type*)checkType(ty)),
     47     UseList(0), Name(0) {
     48   // FIXME: Why isn't this in the subclass gunk??
     49   // Note, we cannot call isa<CallInst> before the CallInst has been
     50   // constructed.
     51   if (SubclassID == Instruction::Call || SubclassID == Instruction::Invoke)
     52     assert((VTy->isFirstClassType() || VTy->isVoidTy() || VTy->isStructTy()) &&
     53            "invalid CallInst type!");
     54   else if (SubclassID != BasicBlockVal &&
     55            (SubclassID < ConstantFirstVal || SubclassID > ConstantLastVal))
     56     assert((VTy->isFirstClassType() || VTy->isVoidTy()) &&
     57            "Cannot create non-first-class values except for constants!");
     58 }
     59 
     60 Value::~Value() {
     61   // Notify all ValueHandles (if present) that this value is going away.
     62   if (HasValueHandle)
     63     ValueHandleBase::ValueIsDeleted(this);
     64 
     65 #ifndef NDEBUG      // Only in -g mode...
     66   // Check to make sure that there are no uses of this value that are still
     67   // around when the value is destroyed.  If there are, then we have a dangling
     68   // reference and something is wrong.  This code is here to print out what is
     69   // still being referenced.  The value in question should be printed as
     70   // a <badref>
     71   //
     72   if (!use_empty()) {
     73     dbgs() << "While deleting: " << *VTy << " %" << getName() << "\n";
     74     for (use_iterator I = use_begin(), E = use_end(); I != E; ++I)
     75       dbgs() << "Use still stuck around after Def is destroyed:"
     76            << **I << "\n";
     77   }
     78 #endif
     79   assert(use_empty() && "Uses remain when a value is destroyed!");
     80 
     81   // If this value is named, destroy the name.  This should not be in a symtab
     82   // at this point.
     83   if (Name && SubclassID != MDStringVal)
     84     Name->Destroy();
     85 
     86   // There should be no uses of this object anymore, remove it.
     87   LeakDetector::removeGarbageObject(this);
     88 }
     89 
     90 /// hasNUses - Return true if this Value has exactly N users.
     91 ///
     92 bool Value::hasNUses(unsigned N) const {
     93   const_use_iterator UI = use_begin(), E = use_end();
     94 
     95   for (; N; --N, ++UI)
     96     if (UI == E) return false;  // Too few.
     97   return UI == E;
     98 }
     99 
    100 /// hasNUsesOrMore - Return true if this value has N users or more.  This is
    101 /// logically equivalent to getNumUses() >= N.
    102 ///
    103 bool Value::hasNUsesOrMore(unsigned N) const {
    104   const_use_iterator UI = use_begin(), E = use_end();
    105 
    106   for (; N; --N, ++UI)
    107     if (UI == E) return false;  // Too few.
    108 
    109   return true;
    110 }
    111 
    112 /// isUsedInBasicBlock - Return true if this value is used in the specified
    113 /// basic block.
    114 bool Value::isUsedInBasicBlock(const BasicBlock *BB) const {
    115   // This can be computed either by scanning the instructions in BB, or by
    116   // scanning the use list of this Value. Both lists can be very long, but
    117   // usually one is quite short.
    118   //
    119   // Scan both lists simultaneously until one is exhausted. This limits the
    120   // search to the shorter list.
    121   BasicBlock::const_iterator BI = BB->begin(), BE = BB->end();
    122   const_use_iterator UI = use_begin(), UE = use_end();
    123   for (; BI != BE && UI != UE; ++BI, ++UI) {
    124     // Scan basic block: Check if this Value is used by the instruction at BI.
    125     if (std::find(BI->op_begin(), BI->op_end(), this) != BI->op_end())
    126       return true;
    127     // Scan use list: Check if the use at UI is in BB.
    128     const Instruction *User = dyn_cast<Instruction>(*UI);
    129     if (User && User->getParent() == BB)
    130       return true;
    131   }
    132   return false;
    133 }
    134 
    135 
    136 /// getNumUses - This method computes the number of uses of this Value.  This
    137 /// is a linear time operation.  Use hasOneUse or hasNUses to check for specific
    138 /// values.
    139 unsigned Value::getNumUses() const {
    140   return (unsigned)std::distance(use_begin(), use_end());
    141 }
    142 
    143 static bool getSymTab(Value *V, ValueSymbolTable *&ST) {
    144   ST = 0;
    145   if (Instruction *I = dyn_cast<Instruction>(V)) {
    146     if (BasicBlock *P = I->getParent())
    147       if (Function *PP = P->getParent())
    148         ST = &PP->getValueSymbolTable();
    149   } else if (BasicBlock *BB = dyn_cast<BasicBlock>(V)) {
    150     if (Function *P = BB->getParent())
    151       ST = &P->getValueSymbolTable();
    152   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
    153     if (Module *P = GV->getParent())
    154       ST = &P->getValueSymbolTable();
    155   } else if (Argument *A = dyn_cast<Argument>(V)) {
    156     if (Function *P = A->getParent())
    157       ST = &P->getValueSymbolTable();
    158   } else if (isa<MDString>(V))
    159     return true;
    160   else {
    161     assert(isa<Constant>(V) && "Unknown value type!");
    162     return true;  // no name is setable for this.
    163   }
    164   return false;
    165 }
    166 
    167 StringRef Value::getName() const {
    168   // Make sure the empty string is still a C string. For historical reasons,
    169   // some clients want to call .data() on the result and expect it to be null
    170   // terminated.
    171   if (!Name) return StringRef("", 0);
    172   return Name->getKey();
    173 }
    174 
    175 void Value::setName(const Twine &NewName) {
    176   assert(SubclassID != MDStringVal &&
    177          "Cannot set the name of MDString with this method!");
    178 
    179   // Fast path for common IRBuilder case of setName("") when there is no name.
    180   if (NewName.isTriviallyEmpty() && !hasName())
    181     return;
    182 
    183   SmallString<256> NameData;
    184   StringRef NameRef = NewName.toStringRef(NameData);
    185 
    186   // Name isn't changing?
    187   if (getName() == NameRef)
    188     return;
    189 
    190   assert(!getType()->isVoidTy() && "Cannot assign a name to void values!");
    191 
    192   // Get the symbol table to update for this object.
    193   ValueSymbolTable *ST;
    194   if (getSymTab(this, ST))
    195     return;  // Cannot set a name on this value (e.g. constant).
    196 
    197   if (Function *F = dyn_cast<Function>(this))
    198     getContext().pImpl->IntrinsicIDCache.erase(F);
    199 
    200   if (!ST) { // No symbol table to update?  Just do the change.
    201     if (NameRef.empty()) {
    202       // Free the name for this value.
    203       Name->Destroy();
    204       Name = 0;
    205       return;
    206     }
    207 
    208     if (Name)
    209       Name->Destroy();
    210 
    211     // NOTE: Could optimize for the case the name is shrinking to not deallocate
    212     // then reallocated.
    213 
    214     // Create the new name.
    215     Name = ValueName::Create(NameRef.begin(), NameRef.end());
    216     Name->setValue(this);
    217     return;
    218   }
    219 
    220   // NOTE: Could optimize for the case the name is shrinking to not deallocate
    221   // then reallocated.
    222   if (hasName()) {
    223     // Remove old name.
    224     ST->removeValueName(Name);
    225     Name->Destroy();
    226     Name = 0;
    227 
    228     if (NameRef.empty())
    229       return;
    230   }
    231 
    232   // Name is changing to something new.
    233   Name = ST->createValueName(NameRef, this);
    234 }
    235 
    236 
    237 /// takeName - transfer the name from V to this value, setting V's name to
    238 /// empty.  It is an error to call V->takeName(V).
    239 void Value::takeName(Value *V) {
    240   assert(SubclassID != MDStringVal && "Cannot take the name of an MDString!");
    241 
    242   ValueSymbolTable *ST = 0;
    243   // If this value has a name, drop it.
    244   if (hasName()) {
    245     // Get the symtab this is in.
    246     if (getSymTab(this, ST)) {
    247       // We can't set a name on this value, but we need to clear V's name if
    248       // it has one.
    249       if (V->hasName()) V->setName("");
    250       return;  // Cannot set a name on this value (e.g. constant).
    251     }
    252 
    253     // Remove old name.
    254     if (ST)
    255       ST->removeValueName(Name);
    256     Name->Destroy();
    257     Name = 0;
    258   }
    259 
    260   // Now we know that this has no name.
    261 
    262   // If V has no name either, we're done.
    263   if (!V->hasName()) return;
    264 
    265   // Get this's symtab if we didn't before.
    266   if (!ST) {
    267     if (getSymTab(this, ST)) {
    268       // Clear V's name.
    269       V->setName("");
    270       return;  // Cannot set a name on this value (e.g. constant).
    271     }
    272   }
    273 
    274   // Get V's ST, this should always succed, because V has a name.
    275   ValueSymbolTable *VST;
    276   bool Failure = getSymTab(V, VST);
    277   assert(!Failure && "V has a name, so it should have a ST!"); (void)Failure;
    278 
    279   // If these values are both in the same symtab, we can do this very fast.
    280   // This works even if both values have no symtab yet.
    281   if (ST == VST) {
    282     // Take the name!
    283     Name = V->Name;
    284     V->Name = 0;
    285     Name->setValue(this);
    286     return;
    287   }
    288 
    289   // Otherwise, things are slightly more complex.  Remove V's name from VST and
    290   // then reinsert it into ST.
    291 
    292   if (VST)
    293     VST->removeValueName(V->Name);
    294   Name = V->Name;
    295   V->Name = 0;
    296   Name->setValue(this);
    297 
    298   if (ST)
    299     ST->reinsertValue(this);
    300 }
    301 
    302 
    303 void Value::replaceAllUsesWith(Value *New) {
    304   assert(New && "Value::replaceAllUsesWith(<null>) is invalid!");
    305   assert(New != this && "this->replaceAllUsesWith(this) is NOT valid!");
    306   assert(New->getType() == getType() &&
    307          "replaceAllUses of value with new value of different type!");
    308 
    309   // Notify all ValueHandles (if present) that this value is going away.
    310   if (HasValueHandle)
    311     ValueHandleBase::ValueIsRAUWd(this, New);
    312 
    313   while (!use_empty()) {
    314     Use &U = *UseList;
    315     // Must handle Constants specially, we cannot call replaceUsesOfWith on a
    316     // constant because they are uniqued.
    317     if (Constant *C = dyn_cast<Constant>(U.getUser())) {
    318       if (!isa<GlobalValue>(C)) {
    319         C->replaceUsesOfWithOnConstant(this, New, &U);
    320         continue;
    321       }
    322     }
    323 
    324     U.set(New);
    325   }
    326 
    327   if (BasicBlock *BB = dyn_cast<BasicBlock>(this))
    328     BB->replaceSuccessorsPhiUsesWith(cast<BasicBlock>(New));
    329 }
    330 
    331 namespace {
    332 // Various metrics for how much to strip off of pointers.
    333 enum PointerStripKind {
    334   PSK_ZeroIndices,
    335   PSK_ZeroIndicesAndAliases,
    336   PSK_InBoundsConstantIndices,
    337   PSK_InBounds
    338 };
    339 
    340 template <PointerStripKind StripKind>
    341 static Value *stripPointerCastsAndOffsets(Value *V) {
    342   if (!V->getType()->isPointerTy())
    343     return V;
    344 
    345   // Even though we don't look through PHI nodes, we could be called on an
    346   // instruction in an unreachable block, which may be on a cycle.
    347   SmallPtrSet<Value *, 4> Visited;
    348 
    349   Visited.insert(V);
    350   do {
    351     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
    352       switch (StripKind) {
    353       case PSK_ZeroIndicesAndAliases:
    354       case PSK_ZeroIndices:
    355         if (!GEP->hasAllZeroIndices())
    356           return V;
    357         break;
    358       case PSK_InBoundsConstantIndices:
    359         if (!GEP->hasAllConstantIndices())
    360           return V;
    361         // fallthrough
    362       case PSK_InBounds:
    363         if (!GEP->isInBounds())
    364           return V;
    365         break;
    366       }
    367       V = GEP->getPointerOperand();
    368     } else if (Operator::getOpcode(V) == Instruction::BitCast) {
    369       V = cast<Operator>(V)->getOperand(0);
    370     } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
    371       if (StripKind == PSK_ZeroIndices || GA->mayBeOverridden())
    372         return V;
    373       V = GA->getAliasee();
    374     } else {
    375       return V;
    376     }
    377     assert(V->getType()->isPointerTy() && "Unexpected operand type!");
    378   } while (Visited.insert(V));
    379 
    380   return V;
    381 }
    382 } // namespace
    383 
    384 Value *Value::stripPointerCasts() {
    385   return stripPointerCastsAndOffsets<PSK_ZeroIndicesAndAliases>(this);
    386 }
    387 
    388 Value *Value::stripPointerCastsNoFollowAliases() {
    389   return stripPointerCastsAndOffsets<PSK_ZeroIndices>(this);
    390 }
    391 
    392 Value *Value::stripInBoundsConstantOffsets() {
    393   return stripPointerCastsAndOffsets<PSK_InBoundsConstantIndices>(this);
    394 }
    395 
    396 Value *Value::stripInBoundsOffsets() {
    397   return stripPointerCastsAndOffsets<PSK_InBounds>(this);
    398 }
    399 
    400 /// isDereferenceablePointer - Test if this value is always a pointer to
    401 /// allocated and suitably aligned memory for a simple load or store.
    402 static bool isDereferenceablePointer(const Value *V,
    403                                      SmallPtrSet<const Value *, 32> &Visited) {
    404   // Note that it is not safe to speculate into a malloc'd region because
    405   // malloc may return null.
    406   // It's also not always safe to follow a bitcast, for example:
    407   //   bitcast i8* (alloca i8) to i32*
    408   // would result in a 4-byte load from a 1-byte alloca. Some cases could
    409   // be handled using DataLayout to check sizes and alignments though.
    410 
    411   // These are obviously ok.
    412   if (isa<AllocaInst>(V)) return true;
    413 
    414   // Global variables which can't collapse to null are ok.
    415   if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
    416     return !GV->hasExternalWeakLinkage();
    417 
    418   // byval arguments are ok.
    419   if (const Argument *A = dyn_cast<Argument>(V))
    420     return A->hasByValAttr();
    421 
    422   // For GEPs, determine if the indexing lands within the allocated object.
    423   if (const GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
    424     // Conservatively require that the base pointer be fully dereferenceable.
    425     if (!Visited.insert(GEP->getOperand(0)))
    426       return false;
    427     if (!isDereferenceablePointer(GEP->getOperand(0), Visited))
    428       return false;
    429     // Check the indices.
    430     gep_type_iterator GTI = gep_type_begin(GEP);
    431     for (User::const_op_iterator I = GEP->op_begin()+1,
    432          E = GEP->op_end(); I != E; ++I) {
    433       Value *Index = *I;
    434       Type *Ty = *GTI++;
    435       // Struct indices can't be out of bounds.
    436       if (isa<StructType>(Ty))
    437         continue;
    438       ConstantInt *CI = dyn_cast<ConstantInt>(Index);
    439       if (!CI)
    440         return false;
    441       // Zero is always ok.
    442       if (CI->isZero())
    443         continue;
    444       // Check to see that it's within the bounds of an array.
    445       ArrayType *ATy = dyn_cast<ArrayType>(Ty);
    446       if (!ATy)
    447         return false;
    448       if (CI->getValue().getActiveBits() > 64)
    449         return false;
    450       if (CI->getZExtValue() >= ATy->getNumElements())
    451         return false;
    452     }
    453     // Indices check out; this is dereferenceable.
    454     return true;
    455   }
    456 
    457   // If we don't know, assume the worst.
    458   return false;
    459 }
    460 
    461 /// isDereferenceablePointer - Test if this value is always a pointer to
    462 /// allocated and suitably aligned memory for a simple load or store.
    463 bool Value::isDereferenceablePointer() const {
    464   SmallPtrSet<const Value *, 32> Visited;
    465   return ::isDereferenceablePointer(this, Visited);
    466 }
    467 
    468 /// DoPHITranslation - If this value is a PHI node with CurBB as its parent,
    469 /// return the value in the PHI node corresponding to PredBB.  If not, return
    470 /// ourself.  This is useful if you want to know the value something has in a
    471 /// predecessor block.
    472 Value *Value::DoPHITranslation(const BasicBlock *CurBB,
    473                                const BasicBlock *PredBB) {
    474   PHINode *PN = dyn_cast<PHINode>(this);
    475   if (PN && PN->getParent() == CurBB)
    476     return PN->getIncomingValueForBlock(PredBB);
    477   return this;
    478 }
    479 
    480 LLVMContext &Value::getContext() const { return VTy->getContext(); }
    481 
    482 //===----------------------------------------------------------------------===//
    483 //                             ValueHandleBase Class
    484 //===----------------------------------------------------------------------===//
    485 
    486 /// AddToExistingUseList - Add this ValueHandle to the use list for VP, where
    487 /// List is known to point into the existing use list.
    488 void ValueHandleBase::AddToExistingUseList(ValueHandleBase **List) {
    489   assert(List && "Handle list is null?");
    490 
    491   // Splice ourselves into the list.
    492   Next = *List;
    493   *List = this;
    494   setPrevPtr(List);
    495   if (Next) {
    496     Next->setPrevPtr(&Next);
    497     assert(VP.getPointer() == Next->VP.getPointer() && "Added to wrong list?");
    498   }
    499 }
    500 
    501 void ValueHandleBase::AddToExistingUseListAfter(ValueHandleBase *List) {
    502   assert(List && "Must insert after existing node");
    503 
    504   Next = List->Next;
    505   setPrevPtr(&List->Next);
    506   List->Next = this;
    507   if (Next)
    508     Next->setPrevPtr(&Next);
    509 }
    510 
    511 /// AddToUseList - Add this ValueHandle to the use list for VP.
    512 void ValueHandleBase::AddToUseList() {
    513   assert(VP.getPointer() && "Null pointer doesn't have a use list!");
    514 
    515   LLVMContextImpl *pImpl = VP.getPointer()->getContext().pImpl;
    516 
    517   if (VP.getPointer()->HasValueHandle) {
    518     // If this value already has a ValueHandle, then it must be in the
    519     // ValueHandles map already.
    520     ValueHandleBase *&Entry = pImpl->ValueHandles[VP.getPointer()];
    521     assert(Entry != 0 && "Value doesn't have any handles?");
    522     AddToExistingUseList(&Entry);
    523     return;
    524   }
    525 
    526   // Ok, it doesn't have any handles yet, so we must insert it into the
    527   // DenseMap.  However, doing this insertion could cause the DenseMap to
    528   // reallocate itself, which would invalidate all of the PrevP pointers that
    529   // point into the old table.  Handle this by checking for reallocation and
    530   // updating the stale pointers only if needed.
    531   DenseMap<Value*, ValueHandleBase*> &Handles = pImpl->ValueHandles;
    532   const void *OldBucketPtr = Handles.getPointerIntoBucketsArray();
    533 
    534   ValueHandleBase *&Entry = Handles[VP.getPointer()];
    535   assert(Entry == 0 && "Value really did already have handles?");
    536   AddToExistingUseList(&Entry);
    537   VP.getPointer()->HasValueHandle = true;
    538 
    539   // If reallocation didn't happen or if this was the first insertion, don't
    540   // walk the table.
    541   if (Handles.isPointerIntoBucketsArray(OldBucketPtr) ||
    542       Handles.size() == 1) {
    543     return;
    544   }
    545 
    546   // Okay, reallocation did happen.  Fix the Prev Pointers.
    547   for (DenseMap<Value*, ValueHandleBase*>::iterator I = Handles.begin(),
    548        E = Handles.end(); I != E; ++I) {
    549     assert(I->second && I->first == I->second->VP.getPointer() &&
    550            "List invariant broken!");
    551     I->second->setPrevPtr(&I->second);
    552   }
    553 }
    554 
    555 /// RemoveFromUseList - Remove this ValueHandle from its current use list.
    556 void ValueHandleBase::RemoveFromUseList() {
    557   assert(VP.getPointer() && VP.getPointer()->HasValueHandle &&
    558          "Pointer doesn't have a use list!");
    559 
    560   // Unlink this from its use list.
    561   ValueHandleBase **PrevPtr = getPrevPtr();
    562   assert(*PrevPtr == this && "List invariant broken");
    563 
    564   *PrevPtr = Next;
    565   if (Next) {
    566     assert(Next->getPrevPtr() == &Next && "List invariant broken");
    567     Next->setPrevPtr(PrevPtr);
    568     return;
    569   }
    570 
    571   // If the Next pointer was null, then it is possible that this was the last
    572   // ValueHandle watching VP.  If so, delete its entry from the ValueHandles
    573   // map.
    574   LLVMContextImpl *pImpl = VP.getPointer()->getContext().pImpl;
    575   DenseMap<Value*, ValueHandleBase*> &Handles = pImpl->ValueHandles;
    576   if (Handles.isPointerIntoBucketsArray(PrevPtr)) {
    577     Handles.erase(VP.getPointer());
    578     VP.getPointer()->HasValueHandle = false;
    579   }
    580 }
    581 
    582 
    583 void ValueHandleBase::ValueIsDeleted(Value *V) {
    584   assert(V->HasValueHandle && "Should only be called if ValueHandles present");
    585 
    586   // Get the linked list base, which is guaranteed to exist since the
    587   // HasValueHandle flag is set.
    588   LLVMContextImpl *pImpl = V->getContext().pImpl;
    589   ValueHandleBase *Entry = pImpl->ValueHandles[V];
    590   assert(Entry && "Value bit set but no entries exist");
    591 
    592   // We use a local ValueHandleBase as an iterator so that ValueHandles can add
    593   // and remove themselves from the list without breaking our iteration.  This
    594   // is not really an AssertingVH; we just have to give ValueHandleBase a kind.
    595   // Note that we deliberately do not the support the case when dropping a value
    596   // handle results in a new value handle being permanently added to the list
    597   // (as might occur in theory for CallbackVH's): the new value handle will not
    598   // be processed and the checking code will mete out righteous punishment if
    599   // the handle is still present once we have finished processing all the other
    600   // value handles (it is fine to momentarily add then remove a value handle).
    601   for (ValueHandleBase Iterator(Assert, *Entry); Entry; Entry = Iterator.Next) {
    602     Iterator.RemoveFromUseList();
    603     Iterator.AddToExistingUseListAfter(Entry);
    604     assert(Entry->Next == &Iterator && "Loop invariant broken.");
    605 
    606     switch (Entry->getKind()) {
    607     case Assert:
    608       break;
    609     case Tracking:
    610       // Mark that this value has been deleted by setting it to an invalid Value
    611       // pointer.
    612       Entry->operator=(DenseMapInfo<Value *>::getTombstoneKey());
    613       break;
    614     case Weak:
    615       // Weak just goes to null, which will unlink it from the list.
    616       Entry->operator=(0);
    617       break;
    618     case Callback:
    619       // Forward to the subclass's implementation.
    620       static_cast<CallbackVH*>(Entry)->deleted();
    621       break;
    622     }
    623   }
    624 
    625   // All callbacks, weak references, and assertingVHs should be dropped by now.
    626   if (V->HasValueHandle) {
    627 #ifndef NDEBUG      // Only in +Asserts mode...
    628     dbgs() << "While deleting: " << *V->getType() << " %" << V->getName()
    629            << "\n";
    630     if (pImpl->ValueHandles[V]->getKind() == Assert)
    631       llvm_unreachable("An asserting value handle still pointed to this"
    632                        " value!");
    633 
    634 #endif
    635     llvm_unreachable("All references to V were not removed?");
    636   }
    637 }
    638 
    639 
    640 void ValueHandleBase::ValueIsRAUWd(Value *Old, Value *New) {
    641   assert(Old->HasValueHandle &&"Should only be called if ValueHandles present");
    642   assert(Old != New && "Changing value into itself!");
    643 
    644   // Get the linked list base, which is guaranteed to exist since the
    645   // HasValueHandle flag is set.
    646   LLVMContextImpl *pImpl = Old->getContext().pImpl;
    647   ValueHandleBase *Entry = pImpl->ValueHandles[Old];
    648 
    649   assert(Entry && "Value bit set but no entries exist");
    650 
    651   // We use a local ValueHandleBase as an iterator so that
    652   // ValueHandles can add and remove themselves from the list without
    653   // breaking our iteration.  This is not really an AssertingVH; we
    654   // just have to give ValueHandleBase some kind.
    655   for (ValueHandleBase Iterator(Assert, *Entry); Entry; Entry = Iterator.Next) {
    656     Iterator.RemoveFromUseList();
    657     Iterator.AddToExistingUseListAfter(Entry);
    658     assert(Entry->Next == &Iterator && "Loop invariant broken.");
    659 
    660     switch (Entry->getKind()) {
    661     case Assert:
    662       // Asserting handle does not follow RAUW implicitly.
    663       break;
    664     case Tracking:
    665       // Tracking goes to new value like a WeakVH. Note that this may make it
    666       // something incompatible with its templated type. We don't want to have a
    667       // virtual (or inline) interface to handle this though, so instead we make
    668       // the TrackingVH accessors guarantee that a client never sees this value.
    669 
    670       // FALLTHROUGH
    671     case Weak:
    672       // Weak goes to the new value, which will unlink it from Old's list.
    673       Entry->operator=(New);
    674       break;
    675     case Callback:
    676       // Forward to the subclass's implementation.
    677       static_cast<CallbackVH*>(Entry)->allUsesReplacedWith(New);
    678       break;
    679     }
    680   }
    681 
    682 #ifndef NDEBUG
    683   // If any new tracking or weak value handles were added while processing the
    684   // list, then complain about it now.
    685   if (Old->HasValueHandle)
    686     for (Entry = pImpl->ValueHandles[Old]; Entry; Entry = Entry->Next)
    687       switch (Entry->getKind()) {
    688       case Tracking:
    689       case Weak:
    690         dbgs() << "After RAUW from " << *Old->getType() << " %"
    691                << Old->getName() << " to " << *New->getType() << " %"
    692                << New->getName() << "\n";
    693         llvm_unreachable("A tracking or weak value handle still pointed to the"
    694                          " old value!\n");
    695       default:
    696         break;
    697       }
    698 #endif
    699 }
    700 
    701 // Default implementation for CallbackVH.
    702 void CallbackVH::allUsesReplacedWith(Value *) {}
    703 
    704 void CallbackVH::deleted() {
    705   setValPtr(NULL);
    706 }
    707