xref: /llvm-project-15.0.7/llvm/lib/IR/Value.cpp (revision 4d75e8d6)
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/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"
35 #include "llvm/Support/raw_ostream.h"
36 #include <algorithm>
37 
38 using namespace llvm;
39 
40 //===----------------------------------------------------------------------===//
41 //                                Value Class
42 //===----------------------------------------------------------------------===//
43 static inline Type *checkType(Type *Ty) {
44   assert(Ty && "Value defined with a null type: Error!");
45   return Ty;
46 }
47 
48 Value::Value(Type *ty, unsigned scid)
49     : VTy(checkType(ty)), UseList(nullptr), SubclassID(scid),
50       HasValueHandle(0), SubclassOptionalData(0), SubclassData(0),
51       NumUserOperands(0), IsUsedByMD(false), HasName(false) {
52   // FIXME: Why isn't this in the subclass gunk??
53   // Note, we cannot call isa<CallInst> before the CallInst has been
54   // constructed.
55   if (SubclassID == Instruction::Call || SubclassID == Instruction::Invoke)
56     assert((VTy->isFirstClassType() || VTy->isVoidTy() || VTy->isStructTy()) &&
57            "invalid CallInst type!");
58   else if (SubclassID != BasicBlockVal &&
59            (SubclassID < ConstantFirstVal || SubclassID > ConstantLastVal))
60     assert((VTy->isFirstClassType() || VTy->isVoidTy()) &&
61            "Cannot create non-first-class values except for constants!");
62   static_assert(sizeof(Value) == 3 * sizeof(void *) + 2 * sizeof(unsigned),
63                 "Value too big");
64 }
65 
66 Value::~Value() {
67   // Notify all ValueHandles (if present) that this value is going away.
68   if (HasValueHandle)
69     ValueHandleBase::ValueIsDeleted(this);
70   if (isUsedByMetadata())
71     ValueAsMetadata::handleDeletion(this);
72 
73 #ifndef NDEBUG      // Only in -g mode...
74   // Check to make sure that there are no uses of this value that are still
75   // around when the value is destroyed.  If there are, then we have a dangling
76   // reference and something is wrong.  This code is here to print out where
77   // the value is still being referenced.
78   //
79   if (!use_empty()) {
80     dbgs() << "While deleting: " << *VTy << " %" << getName() << "\n";
81     for (auto *U : users())
82       dbgs() << "Use still stuck around after Def is destroyed:" << *U << "\n";
83   }
84 #endif
85   assert(use_empty() && "Uses remain when a value is destroyed!");
86 
87   // If this value is named, destroy the name.  This should not be in a symtab
88   // at this point.
89   destroyValueName();
90 }
91 
92 void Value::destroyValueName() {
93   ValueName *Name = getValueName();
94   if (Name)
95     Name->Destroy();
96   setValueName(nullptr);
97 }
98 
99 bool Value::hasNUses(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   return UI == E;
105 }
106 
107 bool Value::hasNUsesOrMore(unsigned N) const {
108   const_use_iterator UI = use_begin(), E = use_end();
109 
110   for (; N; --N, ++UI)
111     if (UI == E) return false;  // Too few.
112 
113   return true;
114 }
115 
116 bool Value::isUsedInBasicBlock(const BasicBlock *BB) const {
117   // This can be computed either by scanning the instructions in BB, or by
118   // scanning the use list of this Value. Both lists can be very long, but
119   // usually one is quite short.
120   //
121   // Scan both lists simultaneously until one is exhausted. This limits the
122   // search to the shorter list.
123   BasicBlock::const_iterator BI = BB->begin(), BE = BB->end();
124   const_user_iterator UI = user_begin(), UE = user_end();
125   for (; BI != BE && UI != UE; ++BI, ++UI) {
126     // Scan basic block: Check if this Value is used by the instruction at BI.
127     if (std::find(BI->op_begin(), BI->op_end(), this) != BI->op_end())
128       return true;
129     // Scan use list: Check if the use at UI is in BB.
130     const Instruction *User = dyn_cast<Instruction>(*UI);
131     if (User && User->getParent() == BB)
132       return true;
133   }
134   return false;
135 }
136 
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 = nullptr;
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 {
157     assert(isa<Constant>(V) && "Unknown value type!");
158     return true;  // no name is setable for this.
159   }
160   return false;
161 }
162 
163 ValueName *Value::getValueName() const {
164   if (!HasName) return nullptr;
165 
166   LLVMContext &Ctx = getContext();
167   auto I = Ctx.pImpl->ValueNames.find(this);
168   assert(I != Ctx.pImpl->ValueNames.end() &&
169          "No name entry found!");
170 
171   return I->second;
172 }
173 
174 void Value::setValueName(ValueName *VN) {
175   LLVMContext &Ctx = getContext();
176 
177   assert(HasName == Ctx.pImpl->ValueNames.count(this) &&
178          "HasName bit out of sync!");
179 
180   if (!VN) {
181     if (HasName)
182       Ctx.pImpl->ValueNames.erase(this);
183     HasName = false;
184     return;
185   }
186 
187   HasName = true;
188   Ctx.pImpl->ValueNames[this] = VN;
189 }
190 
191 StringRef Value::getName() const {
192   // Make sure the empty string is still a C string. For historical reasons,
193   // some clients want to call .data() on the result and expect it to be null
194   // terminated.
195   if (!hasName())
196     return StringRef("", 0);
197   return getValueName()->getKey();
198 }
199 
200 void Value::setNameImpl(const Twine &NewName) {
201   // Fast path for common IRBuilder case of setName("") when there is no name.
202   if (NewName.isTriviallyEmpty() && !hasName())
203     return;
204 
205   SmallString<256> NameData;
206   StringRef NameRef = NewName.toStringRef(NameData);
207   assert(NameRef.find_first_of(0) == StringRef::npos &&
208          "Null bytes are not allowed in names");
209 
210   // Name isn't changing?
211   if (getName() == NameRef)
212     return;
213 
214   assert(!getType()->isVoidTy() && "Cannot assign a name to void values!");
215 
216   // Get the symbol table to update for this object.
217   ValueSymbolTable *ST;
218   if (getSymTab(this, ST))
219     return;  // Cannot set a name on this value (e.g. constant).
220 
221   if (!ST) { // No symbol table to update?  Just do the change.
222     if (NameRef.empty()) {
223       // Free the name for this value.
224       destroyValueName();
225       return;
226     }
227 
228     // NOTE: Could optimize for the case the name is shrinking to not deallocate
229     // then reallocated.
230     destroyValueName();
231 
232     // Create the new name.
233     setValueName(ValueName::Create(NameRef));
234     getValueName()->setValue(this);
235     return;
236   }
237 
238   // NOTE: Could optimize for the case the name is shrinking to not deallocate
239   // then reallocated.
240   if (hasName()) {
241     // Remove old name.
242     ST->removeValueName(getValueName());
243     destroyValueName();
244 
245     if (NameRef.empty())
246       return;
247   }
248 
249   // Name is changing to something new.
250   setValueName(ST->createValueName(NameRef, this));
251 }
252 
253 void Value::setName(const Twine &NewName) {
254   setNameImpl(NewName);
255   if (Function *F = dyn_cast<Function>(this))
256     F->recalculateIntrinsicID();
257 }
258 
259 void Value::takeName(Value *V) {
260   ValueSymbolTable *ST = nullptr;
261   // If this value has a name, drop it.
262   if (hasName()) {
263     // Get the symtab this is in.
264     if (getSymTab(this, ST)) {
265       // We can't set a name on this value, but we need to clear V's name if
266       // it has one.
267       if (V->hasName()) V->setName("");
268       return;  // Cannot set a name on this value (e.g. constant).
269     }
270 
271     // Remove old name.
272     if (ST)
273       ST->removeValueName(getValueName());
274     destroyValueName();
275   }
276 
277   // Now we know that this has no name.
278 
279   // If V has no name either, we're done.
280   if (!V->hasName()) return;
281 
282   // Get this's symtab if we didn't before.
283   if (!ST) {
284     if (getSymTab(this, ST)) {
285       // Clear V's name.
286       V->setName("");
287       return;  // Cannot set a name on this value (e.g. constant).
288     }
289   }
290 
291   // Get V's ST, this should always succed, because V has a name.
292   ValueSymbolTable *VST;
293   bool Failure = getSymTab(V, VST);
294   assert(!Failure && "V has a name, so it should have a ST!"); (void)Failure;
295 
296   // If these values are both in the same symtab, we can do this very fast.
297   // This works even if both values have no symtab yet.
298   if (ST == VST) {
299     // Take the name!
300     setValueName(V->getValueName());
301     V->setValueName(nullptr);
302     getValueName()->setValue(this);
303     return;
304   }
305 
306   // Otherwise, things are slightly more complex.  Remove V's name from VST and
307   // then reinsert it into ST.
308 
309   if (VST)
310     VST->removeValueName(V->getValueName());
311   setValueName(V->getValueName());
312   V->setValueName(nullptr);
313   getValueName()->setValue(this);
314 
315   if (ST)
316     ST->reinsertValue(this);
317 }
318 
319 void Value::assertModuleIsMaterialized() const {
320 #ifndef NDEBUG
321   const GlobalValue *GV = dyn_cast<GlobalValue>(this);
322   if (!GV)
323     return;
324   const Module *M = GV->getParent();
325   if (!M)
326     return;
327   assert(M->isMaterialized());
328 #endif
329 }
330 
331 #ifndef NDEBUG
332 static bool contains(SmallPtrSetImpl<ConstantExpr *> &Cache, ConstantExpr *Expr,
333                      Constant *C) {
334   if (!Cache.insert(Expr).second)
335     return false;
336 
337   for (auto &O : Expr->operands()) {
338     if (O == C)
339       return true;
340     auto *CE = dyn_cast<ConstantExpr>(O);
341     if (!CE)
342       continue;
343     if (contains(Cache, CE, C))
344       return true;
345   }
346   return false;
347 }
348 
349 static bool contains(Value *Expr, Value *V) {
350   if (Expr == V)
351     return true;
352 
353   auto *C = dyn_cast<Constant>(V);
354   if (!C)
355     return false;
356 
357   auto *CE = dyn_cast<ConstantExpr>(Expr);
358   if (!CE)
359     return false;
360 
361   SmallPtrSet<ConstantExpr *, 4> Cache;
362   return contains(Cache, CE, C);
363 }
364 #endif // NDEBUG
365 
366 void Value::replaceAllUsesWith(Value *New) {
367   assert(New && "Value::replaceAllUsesWith(<null>) is invalid!");
368   assert(!contains(New, this) &&
369          "this->replaceAllUsesWith(expr(this)) is NOT valid!");
370   assert(New->getType() == getType() &&
371          "replaceAllUses of value with new value of different type!");
372 
373   // Notify all ValueHandles (if present) that this value is going away.
374   if (HasValueHandle)
375     ValueHandleBase::ValueIsRAUWd(this, New);
376   if (isUsedByMetadata())
377     ValueAsMetadata::handleRAUW(this, New);
378 
379   while (!use_empty()) {
380     Use &U = *UseList;
381     // Must handle Constants specially, we cannot call replaceUsesOfWith on a
382     // constant because they are uniqued.
383     if (auto *C = dyn_cast<Constant>(U.getUser())) {
384       if (!isa<GlobalValue>(C)) {
385         C->handleOperandChange(this, New);
386         continue;
387       }
388     }
389 
390     U.set(New);
391   }
392 
393   if (BasicBlock *BB = dyn_cast<BasicBlock>(this))
394     BB->replaceSuccessorsPhiUsesWith(cast<BasicBlock>(New));
395 }
396 
397 // Like replaceAllUsesWith except it does not handle constants or basic blocks.
398 // This routine leaves uses within BB.
399 void Value::replaceUsesOutsideBlock(Value *New, BasicBlock *BB) {
400   assert(New && "Value::replaceUsesOutsideBlock(<null>, BB) is invalid!");
401   assert(!contains(New, this) &&
402          "this->replaceUsesOutsideBlock(expr(this), BB) is NOT valid!");
403   assert(New->getType() == getType() &&
404          "replaceUses of value with new value of different type!");
405   assert(BB && "Basic block that may contain a use of 'New' must be defined\n");
406 
407   use_iterator UI = use_begin(), E = use_end();
408   for (; UI != E;) {
409     Use &U = *UI;
410     ++UI;
411     auto *Usr = dyn_cast<Instruction>(U.getUser());
412     if (Usr && Usr->getParent() == BB)
413       continue;
414     U.set(New);
415   }
416 }
417 
418 namespace {
419 // Various metrics for how much to strip off of pointers.
420 enum PointerStripKind {
421   PSK_ZeroIndices,
422   PSK_ZeroIndicesAndAliases,
423   PSK_InBoundsConstantIndices,
424   PSK_InBounds
425 };
426 
427 template <PointerStripKind StripKind>
428 static Value *stripPointerCastsAndOffsets(Value *V) {
429   if (!V->getType()->isPointerTy())
430     return V;
431 
432   // Even though we don't look through PHI nodes, we could be called on an
433   // instruction in an unreachable block, which may be on a cycle.
434   SmallPtrSet<Value *, 4> Visited;
435 
436   Visited.insert(V);
437   do {
438     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
439       switch (StripKind) {
440       case PSK_ZeroIndicesAndAliases:
441       case PSK_ZeroIndices:
442         if (!GEP->hasAllZeroIndices())
443           return V;
444         break;
445       case PSK_InBoundsConstantIndices:
446         if (!GEP->hasAllConstantIndices())
447           return V;
448         // fallthrough
449       case PSK_InBounds:
450         if (!GEP->isInBounds())
451           return V;
452         break;
453       }
454       V = GEP->getPointerOperand();
455     } else if (Operator::getOpcode(V) == Instruction::BitCast ||
456                Operator::getOpcode(V) == Instruction::AddrSpaceCast) {
457       V = cast<Operator>(V)->getOperand(0);
458     } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
459       if (StripKind == PSK_ZeroIndices || GA->mayBeOverridden())
460         return V;
461       V = GA->getAliasee();
462     } else {
463       return V;
464     }
465     assert(V->getType()->isPointerTy() && "Unexpected operand type!");
466   } while (Visited.insert(V).second);
467 
468   return V;
469 }
470 } // end anonymous namespace
471 
472 Value *Value::stripPointerCasts() {
473   return stripPointerCastsAndOffsets<PSK_ZeroIndicesAndAliases>(this);
474 }
475 
476 Value *Value::stripPointerCastsNoFollowAliases() {
477   return stripPointerCastsAndOffsets<PSK_ZeroIndices>(this);
478 }
479 
480 Value *Value::stripInBoundsConstantOffsets() {
481   return stripPointerCastsAndOffsets<PSK_InBoundsConstantIndices>(this);
482 }
483 
484 Value *Value::stripAndAccumulateInBoundsConstantOffsets(const DataLayout &DL,
485                                                         APInt &Offset) {
486   if (!getType()->isPointerTy())
487     return this;
488 
489   assert(Offset.getBitWidth() == DL.getPointerSizeInBits(cast<PointerType>(
490                                      getType())->getAddressSpace()) &&
491          "The offset must have exactly as many bits as our pointer.");
492 
493   // Even though we don't look through PHI nodes, we could be called on an
494   // instruction in an unreachable block, which may be on a cycle.
495   SmallPtrSet<Value *, 4> Visited;
496   Visited.insert(this);
497   Value *V = this;
498   do {
499     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
500       if (!GEP->isInBounds())
501         return V;
502       APInt GEPOffset(Offset);
503       if (!GEP->accumulateConstantOffset(DL, GEPOffset))
504         return V;
505       Offset = GEPOffset;
506       V = GEP->getPointerOperand();
507     } else if (Operator::getOpcode(V) == Instruction::BitCast) {
508       V = cast<Operator>(V)->getOperand(0);
509     } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
510       V = GA->getAliasee();
511     } else {
512       return V;
513     }
514     assert(V->getType()->isPointerTy() && "Unexpected operand type!");
515   } while (Visited.insert(V).second);
516 
517   return V;
518 }
519 
520 Value *Value::stripInBoundsOffsets() {
521   return stripPointerCastsAndOffsets<PSK_InBounds>(this);
522 }
523 
524 unsigned Value::getPointerAlignment(const DataLayout &DL) const {
525   assert(getType()->isPointerTy() && "must be pointer");
526 
527   unsigned Align = 0;
528   if (auto *GO = dyn_cast<GlobalObject>(this)) {
529     Align = GO->getAlignment();
530     if (Align == 0) {
531       if (auto *GVar = dyn_cast<GlobalVariable>(GO)) {
532         Type *ObjectType = GVar->getValueType();
533         if (ObjectType->isSized()) {
534           // If the object is defined in the current Module, we'll be giving
535           // it the preferred alignment. Otherwise, we have to assume that it
536           // may only have the minimum ABI alignment.
537           if (GVar->isStrongDefinitionForLinker())
538             Align = DL.getPreferredAlignment(GVar);
539           else
540             Align = DL.getABITypeAlignment(ObjectType);
541         }
542       }
543     }
544   } else if (const Argument *A = dyn_cast<Argument>(this)) {
545     Align = A->getParamAlignment();
546 
547     if (!Align && A->hasStructRetAttr()) {
548       // An sret parameter has at least the ABI alignment of the return type.
549       Type *EltTy = cast<PointerType>(A->getType())->getElementType();
550       if (EltTy->isSized())
551         Align = DL.getABITypeAlignment(EltTy);
552     }
553   } else if (const AllocaInst *AI = dyn_cast<AllocaInst>(this))
554     Align = AI->getAlignment();
555   else if (auto CS = ImmutableCallSite(this))
556     Align = CS.getAttributes().getParamAlignment(AttributeSet::ReturnIndex);
557   else if (const LoadInst *LI = dyn_cast<LoadInst>(this))
558     if (MDNode *MD = LI->getMetadata(LLVMContext::MD_align)) {
559       ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(0));
560       Align = CI->getLimitedValue();
561     }
562 
563   return Align;
564 }
565 
566 Value *Value::DoPHITranslation(const BasicBlock *CurBB,
567                                const BasicBlock *PredBB) {
568   PHINode *PN = dyn_cast<PHINode>(this);
569   if (PN && PN->getParent() == CurBB)
570     return PN->getIncomingValueForBlock(PredBB);
571   return this;
572 }
573 
574 LLVMContext &Value::getContext() const { return VTy->getContext(); }
575 
576 void Value::reverseUseList() {
577   if (!UseList || !UseList->Next)
578     // No need to reverse 0 or 1 uses.
579     return;
580 
581   Use *Head = UseList;
582   Use *Current = UseList->Next;
583   Head->Next = nullptr;
584   while (Current) {
585     Use *Next = Current->Next;
586     Current->Next = Head;
587     Head->setPrev(&Current->Next);
588     Head = Current;
589     Current = Next;
590   }
591   UseList = Head;
592   Head->setPrev(&UseList);
593 }
594 
595 //===----------------------------------------------------------------------===//
596 //                             ValueHandleBase Class
597 //===----------------------------------------------------------------------===//
598 
599 void ValueHandleBase::AddToExistingUseList(ValueHandleBase **List) {
600   assert(List && "Handle list is null?");
601 
602   // Splice ourselves into the list.
603   Next = *List;
604   *List = this;
605   setPrevPtr(List);
606   if (Next) {
607     Next->setPrevPtr(&Next);
608     assert(V == Next->V && "Added to wrong list?");
609   }
610 }
611 
612 void ValueHandleBase::AddToExistingUseListAfter(ValueHandleBase *List) {
613   assert(List && "Must insert after existing node");
614 
615   Next = List->Next;
616   setPrevPtr(&List->Next);
617   List->Next = this;
618   if (Next)
619     Next->setPrevPtr(&Next);
620 }
621 
622 void ValueHandleBase::AddToUseList() {
623   assert(V && "Null pointer doesn't have a use list!");
624 
625   LLVMContextImpl *pImpl = V->getContext().pImpl;
626 
627   if (V->HasValueHandle) {
628     // If this value already has a ValueHandle, then it must be in the
629     // ValueHandles map already.
630     ValueHandleBase *&Entry = pImpl->ValueHandles[V];
631     assert(Entry && "Value doesn't have any handles?");
632     AddToExistingUseList(&Entry);
633     return;
634   }
635 
636   // Ok, it doesn't have any handles yet, so we must insert it into the
637   // DenseMap.  However, doing this insertion could cause the DenseMap to
638   // reallocate itself, which would invalidate all of the PrevP pointers that
639   // point into the old table.  Handle this by checking for reallocation and
640   // updating the stale pointers only if needed.
641   DenseMap<Value*, ValueHandleBase*> &Handles = pImpl->ValueHandles;
642   const void *OldBucketPtr = Handles.getPointerIntoBucketsArray();
643 
644   ValueHandleBase *&Entry = Handles[V];
645   assert(!Entry && "Value really did already have handles?");
646   AddToExistingUseList(&Entry);
647   V->HasValueHandle = true;
648 
649   // If reallocation didn't happen or if this was the first insertion, don't
650   // walk the table.
651   if (Handles.isPointerIntoBucketsArray(OldBucketPtr) ||
652       Handles.size() == 1) {
653     return;
654   }
655 
656   // Okay, reallocation did happen.  Fix the Prev Pointers.
657   for (DenseMap<Value*, ValueHandleBase*>::iterator I = Handles.begin(),
658        E = Handles.end(); I != E; ++I) {
659     assert(I->second && I->first == I->second->V &&
660            "List invariant broken!");
661     I->second->setPrevPtr(&I->second);
662   }
663 }
664 
665 void ValueHandleBase::RemoveFromUseList() {
666   assert(V && V->HasValueHandle &&
667          "Pointer doesn't have a use list!");
668 
669   // Unlink this from its use list.
670   ValueHandleBase **PrevPtr = getPrevPtr();
671   assert(*PrevPtr == this && "List invariant broken");
672 
673   *PrevPtr = Next;
674   if (Next) {
675     assert(Next->getPrevPtr() == &Next && "List invariant broken");
676     Next->setPrevPtr(PrevPtr);
677     return;
678   }
679 
680   // If the Next pointer was null, then it is possible that this was the last
681   // ValueHandle watching VP.  If so, delete its entry from the ValueHandles
682   // map.
683   LLVMContextImpl *pImpl = V->getContext().pImpl;
684   DenseMap<Value*, ValueHandleBase*> &Handles = pImpl->ValueHandles;
685   if (Handles.isPointerIntoBucketsArray(PrevPtr)) {
686     Handles.erase(V);
687     V->HasValueHandle = false;
688   }
689 }
690 
691 void ValueHandleBase::ValueIsDeleted(Value *V) {
692   assert(V->HasValueHandle && "Should only be called if ValueHandles present");
693 
694   // Get the linked list base, which is guaranteed to exist since the
695   // HasValueHandle flag is set.
696   LLVMContextImpl *pImpl = V->getContext().pImpl;
697   ValueHandleBase *Entry = pImpl->ValueHandles[V];
698   assert(Entry && "Value bit set but no entries exist");
699 
700   // We use a local ValueHandleBase as an iterator so that ValueHandles can add
701   // and remove themselves from the list without breaking our iteration.  This
702   // is not really an AssertingVH; we just have to give ValueHandleBase a kind.
703   // Note that we deliberately do not the support the case when dropping a value
704   // handle results in a new value handle being permanently added to the list
705   // (as might occur in theory for CallbackVH's): the new value handle will not
706   // be processed and the checking code will mete out righteous punishment if
707   // the handle is still present once we have finished processing all the other
708   // value handles (it is fine to momentarily add then remove a value handle).
709   for (ValueHandleBase Iterator(Assert, *Entry); Entry; Entry = Iterator.Next) {
710     Iterator.RemoveFromUseList();
711     Iterator.AddToExistingUseListAfter(Entry);
712     assert(Entry->Next == &Iterator && "Loop invariant broken.");
713 
714     switch (Entry->getKind()) {
715     case Assert:
716       break;
717     case Tracking:
718       // Mark that this value has been deleted by setting it to an invalid Value
719       // pointer.
720       Entry->operator=(DenseMapInfo<Value *>::getTombstoneKey());
721       break;
722     case Weak:
723       // Weak just goes to null, which will unlink it from the list.
724       Entry->operator=(nullptr);
725       break;
726     case Callback:
727       // Forward to the subclass's implementation.
728       static_cast<CallbackVH*>(Entry)->deleted();
729       break;
730     }
731   }
732 
733   // All callbacks, weak references, and assertingVHs should be dropped by now.
734   if (V->HasValueHandle) {
735 #ifndef NDEBUG      // Only in +Asserts mode...
736     dbgs() << "While deleting: " << *V->getType() << " %" << V->getName()
737            << "\n";
738     if (pImpl->ValueHandles[V]->getKind() == Assert)
739       llvm_unreachable("An asserting value handle still pointed to this"
740                        " value!");
741 
742 #endif
743     llvm_unreachable("All references to V were not removed?");
744   }
745 }
746 
747 void ValueHandleBase::ValueIsRAUWd(Value *Old, Value *New) {
748   assert(Old->HasValueHandle &&"Should only be called if ValueHandles present");
749   assert(Old != New && "Changing value into itself!");
750   assert(Old->getType() == New->getType() &&
751          "replaceAllUses of value with new value of different type!");
752 
753   // Get the linked list base, which is guaranteed to exist since the
754   // HasValueHandle flag is set.
755   LLVMContextImpl *pImpl = Old->getContext().pImpl;
756   ValueHandleBase *Entry = pImpl->ValueHandles[Old];
757 
758   assert(Entry && "Value bit set but no entries exist");
759 
760   // We use a local ValueHandleBase as an iterator so that
761   // ValueHandles can add and remove themselves from the list without
762   // breaking our iteration.  This is not really an AssertingVH; we
763   // just have to give ValueHandleBase some kind.
764   for (ValueHandleBase Iterator(Assert, *Entry); Entry; Entry = Iterator.Next) {
765     Iterator.RemoveFromUseList();
766     Iterator.AddToExistingUseListAfter(Entry);
767     assert(Entry->Next == &Iterator && "Loop invariant broken.");
768 
769     switch (Entry->getKind()) {
770     case Assert:
771       // Asserting handle does not follow RAUW implicitly.
772       break;
773     case Tracking:
774       // Tracking goes to new value like a WeakVH. Note that this may make it
775       // something incompatible with its templated type. We don't want to have a
776       // virtual (or inline) interface to handle this though, so instead we make
777       // the TrackingVH accessors guarantee that a client never sees this value.
778 
779       // FALLTHROUGH
780     case Weak:
781       // Weak goes to the new value, which will unlink it from Old's list.
782       Entry->operator=(New);
783       break;
784     case Callback:
785       // Forward to the subclass's implementation.
786       static_cast<CallbackVH*>(Entry)->allUsesReplacedWith(New);
787       break;
788     }
789   }
790 
791 #ifndef NDEBUG
792   // If any new tracking or weak value handles were added while processing the
793   // list, then complain about it now.
794   if (Old->HasValueHandle)
795     for (Entry = pImpl->ValueHandles[Old]; Entry; Entry = Entry->Next)
796       switch (Entry->getKind()) {
797       case Tracking:
798       case Weak:
799         dbgs() << "After RAUW from " << *Old->getType() << " %"
800                << Old->getName() << " to " << *New->getType() << " %"
801                << New->getName() << "\n";
802         llvm_unreachable("A tracking or weak value handle still pointed to the"
803                          " old value!\n");
804       default:
805         break;
806       }
807 #endif
808 }
809 
810 // Pin the vtable to this file.
811 void CallbackVH::anchor() {}
812