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