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