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