1 //===-- Value.cpp - Implement the Value class -----------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the Value, ValueHandle, and User classes.
12 //===----------------------------------------------------------------------===//
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/CallSite.h"
19 #include "llvm/IR/Constant.h"
20 #include "llvm/IR/Constants.h"
21 #include "llvm/IR/DataLayout.h"
22 #include "llvm/IR/DerivedTypes.h"
23 #include "llvm/IR/GetElementPtrTypeIterator.h"
24 #include "llvm/IR/InstrTypes.h"
25 #include "llvm/IR/Instructions.h"
26 #include "llvm/IR/IntrinsicInst.h"
27 #include "llvm/IR/Module.h"
28 #include "llvm/IR/Operator.h"
29 #include "llvm/IR/Statepoint.h"
30 #include "llvm/IR/ValueHandle.h"
31 #include "llvm/IR/ValueSymbolTable.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/ManagedStatic.h"
38 //===----------------------------------------------------------------------===//
40 //===----------------------------------------------------------------------===//
42 static inline Type *checkType(Type *Ty) {
43 assert(Ty && "Value defined with a null type: Error!");
47 Value::Value(Type *ty, unsigned scid)
48 : VTy(checkType(ty)), UseList(nullptr), SubclassID(scid), HasValueHandle(0),
49 SubclassOptionalData(0), SubclassData(0), NumOperands(0) {
50 // FIXME: Why isn't this in the subclass gunk??
51 // Note, we cannot call isa<CallInst> before the CallInst has been
53 if (SubclassID == Instruction::Call || SubclassID == Instruction::Invoke)
54 assert((VTy->isFirstClassType() || VTy->isVoidTy() || VTy->isStructTy()) &&
55 "invalid CallInst type!");
56 else if (SubclassID != BasicBlockVal &&
57 (SubclassID < ConstantFirstVal || SubclassID > ConstantLastVal))
58 assert((VTy->isFirstClassType() || VTy->isVoidTy()) &&
59 "Cannot create non-first-class values except for constants!");
63 // Notify all ValueHandles (if present) that this value is going away.
65 ValueHandleBase::ValueIsDeleted(this);
66 if (isUsedByMetadata())
67 ValueAsMetadata::handleDeletion(this);
69 #ifndef NDEBUG // Only in -g mode...
70 // Check to make sure that there are no uses of this value that are still
71 // around when the value is destroyed. If there are, then we have a dangling
72 // reference and something is wrong. This code is here to print out what is
73 // still being referenced. The value in question should be printed as
77 dbgs() << "While deleting: " << *VTy << " %" << getName() << "\n";
78 for (use_iterator I = use_begin(), E = use_end(); I != E; ++I)
79 dbgs() << "Use still stuck around after Def is destroyed:"
83 assert(use_empty() && "Uses remain when a value is destroyed!");
85 // If this value is named, destroy the name. This should not be in a symtab
90 void Value::destroyValueName() {
91 ValueName *Name = getValueName();
94 setValueName(nullptr);
97 bool Value::hasNUses(unsigned N) const {
98 const_use_iterator UI = use_begin(), E = use_end();
101 if (UI == E) return false; // Too few.
105 bool Value::hasNUsesOrMore(unsigned N) const {
106 const_use_iterator UI = use_begin(), E = use_end();
109 if (UI == E) return false; // Too few.
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.
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_user_iterator UI = user_begin(), UE = user_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())
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)
135 unsigned Value::getNumUses() const {
136 return (unsigned)std::distance(use_begin(), use_end());
139 static bool getSymTab(Value *V, ValueSymbolTable *&ST) {
141 if (Instruction *I = dyn_cast<Instruction>(V)) {
142 if (BasicBlock *P = I->getParent())
143 if (Function *PP = P->getParent())
144 ST = &PP->getValueSymbolTable();
145 } else if (BasicBlock *BB = dyn_cast<BasicBlock>(V)) {
146 if (Function *P = BB->getParent())
147 ST = &P->getValueSymbolTable();
148 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
149 if (Module *P = GV->getParent())
150 ST = &P->getValueSymbolTable();
151 } else if (Argument *A = dyn_cast<Argument>(V)) {
152 if (Function *P = A->getParent())
153 ST = &P->getValueSymbolTable();
155 assert(isa<Constant>(V) && "Unknown value type!");
156 return true; // no name is setable for this.
161 StringRef Value::getName() const {
162 // Make sure the empty string is still a C string. For historical reasons,
163 // some clients want to call .data() on the result and expect it to be null
166 return StringRef("", 0);
167 return getValueName()->getKey();
170 void Value::setName(const Twine &NewName) {
171 // Fast path for common IRBuilder case of setName("") when there is no name.
172 if (NewName.isTriviallyEmpty() && !hasName())
175 SmallString<256> NameData;
176 StringRef NameRef = NewName.toStringRef(NameData);
177 assert(NameRef.find_first_of(0) == StringRef::npos &&
178 "Null bytes are not allowed in names");
180 // Name isn't changing?
181 if (getName() == NameRef)
184 assert(!getType()->isVoidTy() && "Cannot assign a name to void values!");
186 // Get the symbol table to update for this object.
187 ValueSymbolTable *ST;
188 if (getSymTab(this, ST))
189 return; // Cannot set a name on this value (e.g. constant).
191 if (Function *F = dyn_cast<Function>(this))
192 getContext().pImpl->IntrinsicIDCache.erase(F);
194 if (!ST) { // No symbol table to update? Just do the change.
195 if (NameRef.empty()) {
196 // Free the name for this value.
201 // NOTE: Could optimize for the case the name is shrinking to not deallocate
205 // Create the new name.
206 setValueName(ValueName::Create(NameRef));
207 getValueName()->setValue(this);
211 // NOTE: Could optimize for the case the name is shrinking to not deallocate
215 ST->removeValueName(getValueName());
222 // Name is changing to something new.
223 setValueName(ST->createValueName(NameRef, this));
226 void Value::takeName(Value *V) {
227 ValueSymbolTable *ST = nullptr;
228 // If this value has a name, drop it.
230 // Get the symtab this is in.
231 if (getSymTab(this, ST)) {
232 // We can't set a name on this value, but we need to clear V's name if
234 if (V->hasName()) V->setName("");
235 return; // Cannot set a name on this value (e.g. constant).
240 ST->removeValueName(getValueName());
244 // Now we know that this has no name.
246 // If V has no name either, we're done.
247 if (!V->hasName()) return;
249 // Get this's symtab if we didn't before.
251 if (getSymTab(this, ST)) {
254 return; // Cannot set a name on this value (e.g. constant).
258 // Get V's ST, this should always succed, because V has a name.
259 ValueSymbolTable *VST;
260 bool Failure = getSymTab(V, VST);
261 assert(!Failure && "V has a name, so it should have a ST!"); (void)Failure;
263 // If these values are both in the same symtab, we can do this very fast.
264 // This works even if both values have no symtab yet.
267 setValueName(V->getValueName());
268 V->setValueName(nullptr);
269 getValueName()->setValue(this);
273 // Otherwise, things are slightly more complex. Remove V's name from VST and
274 // then reinsert it into ST.
277 VST->removeValueName(V->getValueName());
278 setValueName(V->getValueName());
279 V->setValueName(nullptr);
280 getValueName()->setValue(this);
283 ST->reinsertValue(this);
287 static bool contains(SmallPtrSetImpl<ConstantExpr *> &Cache, ConstantExpr *Expr,
289 if (!Cache.insert(Expr).second)
292 for (auto &O : Expr->operands()) {
295 auto *CE = dyn_cast<ConstantExpr>(O);
298 if (contains(Cache, CE, C))
304 static bool contains(Value *Expr, Value *V) {
308 auto *C = dyn_cast<Constant>(V);
312 auto *CE = dyn_cast<ConstantExpr>(Expr);
316 SmallPtrSet<ConstantExpr *, 4> Cache;
317 return contains(Cache, CE, C);
321 void Value::replaceAllUsesWith(Value *New) {
322 assert(New && "Value::replaceAllUsesWith(<null>) is invalid!");
323 assert(!contains(New, this) &&
324 "this->replaceAllUsesWith(expr(this)) is NOT valid!");
325 assert(New->getType() == getType() &&
326 "replaceAllUses of value with new value of different type!");
328 // Notify all ValueHandles (if present) that this value is going away.
330 ValueHandleBase::ValueIsRAUWd(this, New);
331 if (isUsedByMetadata())
332 ValueAsMetadata::handleRAUW(this, New);
334 while (!use_empty()) {
336 // Must handle Constants specially, we cannot call replaceUsesOfWith on a
337 // constant because they are uniqued.
338 if (auto *C = dyn_cast<Constant>(U.getUser())) {
339 if (!isa<GlobalValue>(C)) {
340 C->replaceUsesOfWithOnConstant(this, New, &U);
348 if (BasicBlock *BB = dyn_cast<BasicBlock>(this))
349 BB->replaceSuccessorsPhiUsesWith(cast<BasicBlock>(New));
352 // Like replaceAllUsesWith except it does not handle constants or basic blocks.
353 // This routine leaves uses within BB.
354 void Value::replaceUsesOutsideBlock(Value *New, BasicBlock *BB) {
355 assert(New && "Value::replaceUsesOutsideBlock(<null>, BB) is invalid!");
356 assert(!contains(New, this) &&
357 "this->replaceUsesOutsideBlock(expr(this), BB) is NOT valid!");
358 assert(New->getType() == getType() &&
359 "replaceUses of value with new value of different type!");
360 assert(BB && "Basic block that may contain a use of 'New' must be defined\n");
362 use_iterator UI = use_begin(), E = use_end();
366 auto *Usr = dyn_cast<Instruction>(U.getUser());
367 if (Usr && Usr->getParent() == BB)
375 // Various metrics for how much to strip off of pointers.
376 enum PointerStripKind {
378 PSK_ZeroIndicesAndAliases,
379 PSK_InBoundsConstantIndices,
383 template <PointerStripKind StripKind>
384 static Value *stripPointerCastsAndOffsets(Value *V) {
385 if (!V->getType()->isPointerTy())
388 // Even though we don't look through PHI nodes, we could be called on an
389 // instruction in an unreachable block, which may be on a cycle.
390 SmallPtrSet<Value *, 4> Visited;
394 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
396 case PSK_ZeroIndicesAndAliases:
397 case PSK_ZeroIndices:
398 if (!GEP->hasAllZeroIndices())
401 case PSK_InBoundsConstantIndices:
402 if (!GEP->hasAllConstantIndices())
406 if (!GEP->isInBounds())
410 V = GEP->getPointerOperand();
411 } else if (Operator::getOpcode(V) == Instruction::BitCast ||
412 Operator::getOpcode(V) == Instruction::AddrSpaceCast) {
413 V = cast<Operator>(V)->getOperand(0);
414 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
415 if (StripKind == PSK_ZeroIndices || GA->mayBeOverridden())
417 V = GA->getAliasee();
421 assert(V->getType()->isPointerTy() && "Unexpected operand type!");
422 } while (Visited.insert(V).second);
428 Value *Value::stripPointerCasts() {
429 return stripPointerCastsAndOffsets<PSK_ZeroIndicesAndAliases>(this);
432 Value *Value::stripPointerCastsNoFollowAliases() {
433 return stripPointerCastsAndOffsets<PSK_ZeroIndices>(this);
436 Value *Value::stripInBoundsConstantOffsets() {
437 return stripPointerCastsAndOffsets<PSK_InBoundsConstantIndices>(this);
440 Value *Value::stripAndAccumulateInBoundsConstantOffsets(const DataLayout &DL,
442 if (!getType()->isPointerTy())
445 assert(Offset.getBitWidth() == DL.getPointerSizeInBits(cast<PointerType>(
446 getType())->getAddressSpace()) &&
447 "The offset must have exactly as many bits as our pointer.");
449 // Even though we don't look through PHI nodes, we could be called on an
450 // instruction in an unreachable block, which may be on a cycle.
451 SmallPtrSet<Value *, 4> Visited;
452 Visited.insert(this);
455 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
456 if (!GEP->isInBounds())
458 APInt GEPOffset(Offset);
459 if (!GEP->accumulateConstantOffset(DL, GEPOffset))
462 V = GEP->getPointerOperand();
463 } else if (Operator::getOpcode(V) == Instruction::BitCast ||
464 Operator::getOpcode(V) == Instruction::AddrSpaceCast) {
465 V = cast<Operator>(V)->getOperand(0);
466 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
467 V = GA->getAliasee();
471 assert(V->getType()->isPointerTy() && "Unexpected operand type!");
472 } while (Visited.insert(V).second);
477 Value *Value::stripInBoundsOffsets() {
478 return stripPointerCastsAndOffsets<PSK_InBounds>(this);
481 /// \brief Check if Value is always a dereferenceable pointer.
483 /// Test if V is always a pointer to allocated and suitably aligned memory for
484 /// a simple load or store.
485 static bool isDereferenceablePointer(const Value *V, const DataLayout *DL,
486 SmallPtrSetImpl<const Value *> &Visited) {
487 // Note that it is not safe to speculate into a malloc'd region because
488 // malloc may return null.
490 // These are obviously ok.
491 if (isa<AllocaInst>(V)) return true;
493 // It's not always safe to follow a bitcast, for example:
494 // bitcast i8* (alloca i8) to i32*
495 // would result in a 4-byte load from a 1-byte alloca. However,
496 // if we're casting from a pointer from a type of larger size
497 // to a type of smaller size (or the same size), and the alignment
498 // is at least as large as for the resulting pointer type, then
499 // we can look through the bitcast.
501 if (const BitCastOperator *BC = dyn_cast<BitCastOperator>(V)) {
502 Type *STy = BC->getSrcTy()->getPointerElementType(),
503 *DTy = BC->getDestTy()->getPointerElementType();
504 if (STy->isSized() && DTy->isSized() &&
505 (DL->getTypeStoreSize(STy) >=
506 DL->getTypeStoreSize(DTy)) &&
507 (DL->getABITypeAlignment(STy) >=
508 DL->getABITypeAlignment(DTy)))
509 return isDereferenceablePointer(BC->getOperand(0), DL, Visited);
512 // Global variables which can't collapse to null are ok.
513 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
514 return !GV->hasExternalWeakLinkage();
516 // byval arguments are okay. Arguments specifically marked as
517 // dereferenceable are okay too.
518 if (const Argument *A = dyn_cast<Argument>(V)) {
519 if (A->hasByValAttr())
521 else if (uint64_t Bytes = A->getDereferenceableBytes()) {
522 Type *Ty = V->getType()->getPointerElementType();
523 if (Ty->isSized() && DL && DL->getTypeStoreSize(Ty) <= Bytes)
530 // Return values from call sites specifically marked as dereferenceable are
532 if (ImmutableCallSite CS = V) {
533 if (uint64_t Bytes = CS.getDereferenceableBytes(0)) {
534 Type *Ty = V->getType()->getPointerElementType();
535 if (Ty->isSized() && DL && DL->getTypeStoreSize(Ty) <= Bytes)
540 // For GEPs, determine if the indexing lands within the allocated object.
541 if (const GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
542 // Conservatively require that the base pointer be fully dereferenceable.
543 if (!Visited.insert(GEP->getOperand(0)).second)
545 if (!isDereferenceablePointer(GEP->getOperand(0), DL, Visited))
547 // Check the indices.
548 gep_type_iterator GTI = gep_type_begin(GEP);
549 for (User::const_op_iterator I = GEP->op_begin()+1,
550 E = GEP->op_end(); I != E; ++I) {
553 // Struct indices can't be out of bounds.
554 if (isa<StructType>(Ty))
556 ConstantInt *CI = dyn_cast<ConstantInt>(Index);
559 // Zero is always ok.
562 // Check to see that it's within the bounds of an array.
563 ArrayType *ATy = dyn_cast<ArrayType>(Ty);
566 if (CI->getValue().getActiveBits() > 64)
568 if (CI->getZExtValue() >= ATy->getNumElements())
571 // Indices check out; this is dereferenceable.
575 // For gc.relocate, look through relocations
576 if (const IntrinsicInst *I = dyn_cast<IntrinsicInst>(V))
577 if (I->getIntrinsicID() == Intrinsic::experimental_gc_relocate) {
578 GCRelocateOperands RelocateInst(I);
579 return isDereferenceablePointer(RelocateInst.derivedPtr(), DL, Visited);
582 if (const AddrSpaceCastInst *ASC = dyn_cast<AddrSpaceCastInst>(V))
583 return isDereferenceablePointer(ASC->getOperand(0), DL, Visited);
585 // If we don't know, assume the worst.
589 bool Value::isDereferenceablePointer(const DataLayout *DL) const {
590 // When dereferenceability information is provided by a dereferenceable
591 // attribute, we know exactly how many bytes are dereferenceable. If we can
592 // determine the exact offset to the attributed variable, we can use that
594 Type *Ty = getType()->getPointerElementType();
595 if (Ty->isSized() && DL) {
596 APInt Offset(DL->getTypeStoreSizeInBits(getType()), 0);
597 const Value *BV = stripAndAccumulateInBoundsConstantOffsets(*DL, Offset);
599 APInt DerefBytes(Offset.getBitWidth(), 0);
600 if (const Argument *A = dyn_cast<Argument>(BV))
601 DerefBytes = A->getDereferenceableBytes();
602 else if (ImmutableCallSite CS = BV)
603 DerefBytes = CS.getDereferenceableBytes(0);
605 if (DerefBytes.getBoolValue() && Offset.isNonNegative()) {
606 if (DerefBytes.uge(Offset + DL->getTypeStoreSize(Ty)))
611 SmallPtrSet<const Value *, 32> Visited;
612 return ::isDereferenceablePointer(this, DL, Visited);
615 Value *Value::DoPHITranslation(const BasicBlock *CurBB,
616 const BasicBlock *PredBB) {
617 PHINode *PN = dyn_cast<PHINode>(this);
618 if (PN && PN->getParent() == CurBB)
619 return PN->getIncomingValueForBlock(PredBB);
623 LLVMContext &Value::getContext() const { return VTy->getContext(); }
625 void Value::reverseUseList() {
626 if (!UseList || !UseList->Next)
627 // No need to reverse 0 or 1 uses.
631 Use *Current = UseList->Next;
632 Head->Next = nullptr;
634 Use *Next = Current->Next;
635 Current->Next = Head;
636 Head->setPrev(&Current->Next);
641 Head->setPrev(&UseList);
644 //===----------------------------------------------------------------------===//
645 // ValueHandleBase Class
646 //===----------------------------------------------------------------------===//
648 void ValueHandleBase::AddToExistingUseList(ValueHandleBase **List) {
649 assert(List && "Handle list is null?");
651 // Splice ourselves into the list.
656 Next->setPrevPtr(&Next);
657 assert(V == Next->V && "Added to wrong list?");
661 void ValueHandleBase::AddToExistingUseListAfter(ValueHandleBase *List) {
662 assert(List && "Must insert after existing node");
665 setPrevPtr(&List->Next);
668 Next->setPrevPtr(&Next);
671 void ValueHandleBase::AddToUseList() {
672 assert(V && "Null pointer doesn't have a use list!");
674 LLVMContextImpl *pImpl = V->getContext().pImpl;
676 if (V->HasValueHandle) {
677 // If this value already has a ValueHandle, then it must be in the
678 // ValueHandles map already.
679 ValueHandleBase *&Entry = pImpl->ValueHandles[V];
680 assert(Entry && "Value doesn't have any handles?");
681 AddToExistingUseList(&Entry);
685 // Ok, it doesn't have any handles yet, so we must insert it into the
686 // DenseMap. However, doing this insertion could cause the DenseMap to
687 // reallocate itself, which would invalidate all of the PrevP pointers that
688 // point into the old table. Handle this by checking for reallocation and
689 // updating the stale pointers only if needed.
690 DenseMap<Value*, ValueHandleBase*> &Handles = pImpl->ValueHandles;
691 const void *OldBucketPtr = Handles.getPointerIntoBucketsArray();
693 ValueHandleBase *&Entry = Handles[V];
694 assert(!Entry && "Value really did already have handles?");
695 AddToExistingUseList(&Entry);
696 V->HasValueHandle = true;
698 // If reallocation didn't happen or if this was the first insertion, don't
700 if (Handles.isPointerIntoBucketsArray(OldBucketPtr) ||
701 Handles.size() == 1) {
705 // Okay, reallocation did happen. Fix the Prev Pointers.
706 for (DenseMap<Value*, ValueHandleBase*>::iterator I = Handles.begin(),
707 E = Handles.end(); I != E; ++I) {
708 assert(I->second && I->first == I->second->V &&
709 "List invariant broken!");
710 I->second->setPrevPtr(&I->second);
714 void ValueHandleBase::RemoveFromUseList() {
715 assert(V && V->HasValueHandle &&
716 "Pointer doesn't have a use list!");
718 // Unlink this from its use list.
719 ValueHandleBase **PrevPtr = getPrevPtr();
720 assert(*PrevPtr == this && "List invariant broken");
724 assert(Next->getPrevPtr() == &Next && "List invariant broken");
725 Next->setPrevPtr(PrevPtr);
729 // If the Next pointer was null, then it is possible that this was the last
730 // ValueHandle watching VP. If so, delete its entry from the ValueHandles
732 LLVMContextImpl *pImpl = V->getContext().pImpl;
733 DenseMap<Value*, ValueHandleBase*> &Handles = pImpl->ValueHandles;
734 if (Handles.isPointerIntoBucketsArray(PrevPtr)) {
736 V->HasValueHandle = false;
741 void ValueHandleBase::ValueIsDeleted(Value *V) {
742 assert(V->HasValueHandle && "Should only be called if ValueHandles present");
744 // Get the linked list base, which is guaranteed to exist since the
745 // HasValueHandle flag is set.
746 LLVMContextImpl *pImpl = V->getContext().pImpl;
747 ValueHandleBase *Entry = pImpl->ValueHandles[V];
748 assert(Entry && "Value bit set but no entries exist");
750 // We use a local ValueHandleBase as an iterator so that ValueHandles can add
751 // and remove themselves from the list without breaking our iteration. This
752 // is not really an AssertingVH; we just have to give ValueHandleBase a kind.
753 // Note that we deliberately do not the support the case when dropping a value
754 // handle results in a new value handle being permanently added to the list
755 // (as might occur in theory for CallbackVH's): the new value handle will not
756 // be processed and the checking code will mete out righteous punishment if
757 // the handle is still present once we have finished processing all the other
758 // value handles (it is fine to momentarily add then remove a value handle).
759 for (ValueHandleBase Iterator(Assert, *Entry); Entry; Entry = Iterator.Next) {
760 Iterator.RemoveFromUseList();
761 Iterator.AddToExistingUseListAfter(Entry);
762 assert(Entry->Next == &Iterator && "Loop invariant broken.");
764 switch (Entry->getKind()) {
768 // Mark that this value has been deleted by setting it to an invalid Value
770 Entry->operator=(DenseMapInfo<Value *>::getTombstoneKey());
773 // Weak just goes to null, which will unlink it from the list.
774 Entry->operator=(nullptr);
777 // Forward to the subclass's implementation.
778 static_cast<CallbackVH*>(Entry)->deleted();
783 // All callbacks, weak references, and assertingVHs should be dropped by now.
784 if (V->HasValueHandle) {
785 #ifndef NDEBUG // Only in +Asserts mode...
786 dbgs() << "While deleting: " << *V->getType() << " %" << V->getName()
788 if (pImpl->ValueHandles[V]->getKind() == Assert)
789 llvm_unreachable("An asserting value handle still pointed to this"
793 llvm_unreachable("All references to V were not removed?");
798 void ValueHandleBase::ValueIsRAUWd(Value *Old, Value *New) {
799 assert(Old->HasValueHandle &&"Should only be called if ValueHandles present");
800 assert(Old != New && "Changing value into itself!");
801 assert(Old->getType() == New->getType() &&
802 "replaceAllUses of value with new value of different type!");
804 // Get the linked list base, which is guaranteed to exist since the
805 // HasValueHandle flag is set.
806 LLVMContextImpl *pImpl = Old->getContext().pImpl;
807 ValueHandleBase *Entry = pImpl->ValueHandles[Old];
809 assert(Entry && "Value bit set but no entries exist");
811 // We use a local ValueHandleBase as an iterator so that
812 // ValueHandles can add and remove themselves from the list without
813 // breaking our iteration. This is not really an AssertingVH; we
814 // just have to give ValueHandleBase some kind.
815 for (ValueHandleBase Iterator(Assert, *Entry); Entry; Entry = Iterator.Next) {
816 Iterator.RemoveFromUseList();
817 Iterator.AddToExistingUseListAfter(Entry);
818 assert(Entry->Next == &Iterator && "Loop invariant broken.");
820 switch (Entry->getKind()) {
822 // Asserting handle does not follow RAUW implicitly.
825 // Tracking goes to new value like a WeakVH. Note that this may make it
826 // something incompatible with its templated type. We don't want to have a
827 // virtual (or inline) interface to handle this though, so instead we make
828 // the TrackingVH accessors guarantee that a client never sees this value.
832 // Weak goes to the new value, which will unlink it from Old's list.
833 Entry->operator=(New);
836 // Forward to the subclass's implementation.
837 static_cast<CallbackVH*>(Entry)->allUsesReplacedWith(New);
843 // If any new tracking or weak value handles were added while processing the
844 // list, then complain about it now.
845 if (Old->HasValueHandle)
846 for (Entry = pImpl->ValueHandles[Old]; Entry; Entry = Entry->Next)
847 switch (Entry->getKind()) {
850 dbgs() << "After RAUW from " << *Old->getType() << " %"
851 << Old->getName() << " to " << *New->getType() << " %"
852 << New->getName() << "\n";
853 llvm_unreachable("A tracking or weak value handle still pointed to the"
861 // Pin the vtable to this file.
862 void CallbackVH::anchor() {}