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