d790f9e10898bad1527304e8208ca62d15655af7
[oota-llvm.git] / lib / IR / Value.cpp
1 //===-- Value.cpp - Implement the Value class -----------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the Value, ValueHandle, and User classes.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/IR/Value.h"
15 #include "LLVMContextImpl.h"
16 #include "llvm/ADT/DenseMap.h"
17 #include "llvm/ADT/SmallString.h"
18 #include "llvm/IR/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/LeakDetector.h"
27 #include "llvm/IR/Module.h"
28 #include "llvm/IR/Operator.h"
29 #include "llvm/IR/ValueHandle.h"
30 #include "llvm/IR/ValueSymbolTable.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/ManagedStatic.h"
34 #include <algorithm>
35 using namespace llvm;
36
37 //===----------------------------------------------------------------------===//
38 //                                Value Class
39 //===----------------------------------------------------------------------===//
40
41 static inline Type *checkType(Type *Ty) {
42   assert(Ty && "Value defined with a null type: Error!");
43   return Ty;
44 }
45
46 Value::Value(Type *ty, unsigned scid)
47     : VTy(checkType(ty)), UseList(nullptr), SubclassID(scid), HasValueHandle(0),
48       SubclassOptionalData(0), SubclassData(0), NumOperands(0) {
49   // FIXME: Why isn't this in the subclass gunk??
50   // Note, we cannot call isa<CallInst> before the CallInst has been
51   // constructed.
52   if (SubclassID == Instruction::Call || SubclassID == Instruction::Invoke)
53     assert((VTy->isFirstClassType() || VTy->isVoidTy() || VTy->isStructTy()) &&
54            "invalid CallInst type!");
55   else if (SubclassID != BasicBlockVal &&
56            (SubclassID < ConstantFirstVal || SubclassID > ConstantLastVal))
57     assert((VTy->isFirstClassType() || VTy->isVoidTy()) &&
58            "Cannot create non-first-class values except for constants!");
59 }
60
61 Value::~Value() {
62   // Notify all ValueHandles (if present) that this value is going away.
63   if (HasValueHandle)
64     ValueHandleBase::ValueIsDeleted(this);
65   if (isUsedByMetadata())
66     ValueAsMetadata::handleDeletion(this);
67
68 #ifndef NDEBUG      // Only in -g mode...
69   // Check to make sure that there are no uses of this value that are still
70   // around when the value is destroyed.  If there are, then we have a dangling
71   // reference and something is wrong.  This code is here to print out what is
72   // still being referenced.  The value in question should be printed as
73   // a <badref>
74   //
75   if (!use_empty()) {
76     dbgs() << "While deleting: " << *VTy << " %" << getName() << "\n";
77     for (use_iterator I = use_begin(), E = use_end(); I != E; ++I)
78       dbgs() << "Use still stuck around after Def is destroyed:"
79            << **I << "\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   // There should be no uses of this object anymore, remove it.
89   LeakDetector::removeGarbageObject(this);
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 StringRef Value::getName() const {
164   // Make sure the empty string is still a C string. For historical reasons,
165   // some clients want to call .data() on the result and expect it to be null
166   // terminated.
167   if (!getValueName())
168     return StringRef("", 0);
169   return getValueName()->getKey();
170 }
171
172 void Value::setName(const Twine &NewName) {
173   // Fast path for common IRBuilder case of setName("") when there is no name.
174   if (NewName.isTriviallyEmpty() && !hasName())
175     return;
176
177   SmallString<256> NameData;
178   StringRef NameRef = NewName.toStringRef(NameData);
179   assert(NameRef.find_first_of(0) == StringRef::npos &&
180          "Null bytes are not allowed in names");
181
182   // Name isn't changing?
183   if (getName() == NameRef)
184     return;
185
186   assert(!getType()->isVoidTy() && "Cannot assign a name to void values!");
187
188   // Get the symbol table to update for this object.
189   ValueSymbolTable *ST;
190   if (getSymTab(this, ST))
191     return;  // Cannot set a name on this value (e.g. constant).
192
193   if (Function *F = dyn_cast<Function>(this))
194     getContext().pImpl->IntrinsicIDCache.erase(F);
195
196   if (!ST) { // No symbol table to update?  Just do the change.
197     if (NameRef.empty()) {
198       // Free the name for this value.
199       destroyValueName();
200       return;
201     }
202
203     // NOTE: Could optimize for the case the name is shrinking to not deallocate
204     // then reallocated.
205     destroyValueName();
206
207     // Create the new name.
208     setValueName(ValueName::Create(NameRef));
209     getValueName()->setValue(this);
210     return;
211   }
212
213   // NOTE: Could optimize for the case the name is shrinking to not deallocate
214   // then reallocated.
215   if (hasName()) {
216     // Remove old name.
217     ST->removeValueName(getValueName());
218     destroyValueName();
219
220     if (NameRef.empty())
221       return;
222   }
223
224   // Name is changing to something new.
225   setValueName(ST->createValueName(NameRef, this));
226 }
227
228 void Value::takeName(Value *V) {
229   ValueSymbolTable *ST = nullptr;
230   // If this value has a name, drop it.
231   if (hasName()) {
232     // Get the symtab this is in.
233     if (getSymTab(this, ST)) {
234       // We can't set a name on this value, but we need to clear V's name if
235       // it has one.
236       if (V->hasName()) V->setName("");
237       return;  // Cannot set a name on this value (e.g. constant).
238     }
239
240     // Remove old name.
241     if (ST)
242       ST->removeValueName(getValueName());
243     destroyValueName();
244   }
245
246   // Now we know that this has no name.
247
248   // If V has no name either, we're done.
249   if (!V->hasName()) return;
250
251   // Get this's symtab if we didn't before.
252   if (!ST) {
253     if (getSymTab(this, ST)) {
254       // Clear V's name.
255       V->setName("");
256       return;  // Cannot set a name on this value (e.g. constant).
257     }
258   }
259
260   // Get V's ST, this should always succed, because V has a name.
261   ValueSymbolTable *VST;
262   bool Failure = getSymTab(V, VST);
263   assert(!Failure && "V has a name, so it should have a ST!"); (void)Failure;
264
265   // If these values are both in the same symtab, we can do this very fast.
266   // This works even if both values have no symtab yet.
267   if (ST == VST) {
268     // Take the name!
269     setValueName(V->getValueName());
270     V->setValueName(nullptr);
271     getValueName()->setValue(this);
272     return;
273   }
274
275   // Otherwise, things are slightly more complex.  Remove V's name from VST and
276   // then reinsert it into ST.
277
278   if (VST)
279     VST->removeValueName(V->getValueName());
280   setValueName(V->getValueName());
281   V->setValueName(nullptr);
282   getValueName()->setValue(this);
283
284   if (ST)
285     ST->reinsertValue(this);
286 }
287
288 #ifndef NDEBUG
289 static bool contains(SmallPtrSetImpl<ConstantExpr *> &Cache, ConstantExpr *Expr,
290                      Constant *C) {
291   if (!Cache.insert(Expr).second)
292     return false;
293
294   for (auto &O : Expr->operands()) {
295     if (O == C)
296       return true;
297     auto *CE = dyn_cast<ConstantExpr>(O);
298     if (!CE)
299       continue;
300     if (contains(Cache, CE, C))
301       return true;
302   }
303   return false;
304 }
305
306 static bool contains(Value *Expr, Value *V) {
307   if (Expr == V)
308     return true;
309
310   auto *C = dyn_cast<Constant>(V);
311   if (!C)
312     return false;
313
314   auto *CE = dyn_cast<ConstantExpr>(Expr);
315   if (!CE)
316     return false;
317
318   SmallPtrSet<ConstantExpr *, 4> Cache;
319   return contains(Cache, CE, C);
320 }
321 #endif
322
323 void Value::replaceAllUsesWith(Value *New) {
324   assert(New && "Value::replaceAllUsesWith(<null>) is invalid!");
325   assert(!contains(New, this) &&
326          "this->replaceAllUsesWith(expr(this)) is NOT valid!");
327   assert(New->getType() == getType() &&
328          "replaceAllUses of value with new value of different type!");
329
330   // Notify all ValueHandles (if present) that this value is going away.
331   if (HasValueHandle)
332     ValueHandleBase::ValueIsRAUWd(this, New);
333   if (isUsedByMetadata())
334     ValueAsMetadata::handleRAUW(this, New);
335
336   while (!use_empty()) {
337     Use &U = *UseList;
338     // Must handle Constants specially, we cannot call replaceUsesOfWith on a
339     // constant because they are uniqued.
340     if (auto *C = dyn_cast<Constant>(U.getUser())) {
341       if (!isa<GlobalValue>(C)) {
342         C->replaceUsesOfWithOnConstant(this, New, &U);
343         continue;
344       }
345     }
346
347     U.set(New);
348   }
349
350   if (BasicBlock *BB = dyn_cast<BasicBlock>(this))
351     BB->replaceSuccessorsPhiUsesWith(cast<BasicBlock>(New));
352 }
353
354 // Like replaceAllUsesWith except it does not handle constants or basic blocks.
355 // This routine leaves uses within BB.
356 void Value::replaceUsesOutsideBlock(Value *New, BasicBlock *BB) {
357   assert(New && "Value::replaceUsesOutsideBlock(<null>, BB) is invalid!");
358   assert(!contains(New, this) &&
359          "this->replaceUsesOutsideBlock(expr(this), BB) is NOT valid!");
360   assert(New->getType() == getType() &&
361          "replaceUses of value with new value of different type!");
362   assert(BB && "Basic block that may contain a use of 'New' must be defined\n");
363
364   use_iterator UI = use_begin(), E = use_end();
365   for (; UI != E;) {
366     Use &U = *UI;
367     ++UI;
368     auto *Usr = dyn_cast<Instruction>(U.getUser());
369     if (Usr && Usr->getParent() == BB)
370       continue;
371     U.set(New);
372   }
373   return;
374 }
375
376 namespace {
377 // Various metrics for how much to strip off of pointers.
378 enum PointerStripKind {
379   PSK_ZeroIndices,
380   PSK_ZeroIndicesAndAliases,
381   PSK_InBoundsConstantIndices,
382   PSK_InBounds
383 };
384
385 template <PointerStripKind StripKind>
386 static Value *stripPointerCastsAndOffsets(Value *V) {
387   if (!V->getType()->isPointerTy())
388     return V;
389
390   // Even though we don't look through PHI nodes, we could be called on an
391   // instruction in an unreachable block, which may be on a cycle.
392   SmallPtrSet<Value *, 4> Visited;
393
394   Visited.insert(V);
395   do {
396     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
397       switch (StripKind) {
398       case PSK_ZeroIndicesAndAliases:
399       case PSK_ZeroIndices:
400         if (!GEP->hasAllZeroIndices())
401           return V;
402         break;
403       case PSK_InBoundsConstantIndices:
404         if (!GEP->hasAllConstantIndices())
405           return V;
406         // fallthrough
407       case PSK_InBounds:
408         if (!GEP->isInBounds())
409           return V;
410         break;
411       }
412       V = GEP->getPointerOperand();
413     } else if (Operator::getOpcode(V) == Instruction::BitCast ||
414                Operator::getOpcode(V) == Instruction::AddrSpaceCast) {
415       V = cast<Operator>(V)->getOperand(0);
416     } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
417       if (StripKind == PSK_ZeroIndices || GA->mayBeOverridden())
418         return V;
419       V = GA->getAliasee();
420     } else {
421       return V;
422     }
423     assert(V->getType()->isPointerTy() && "Unexpected operand type!");
424   } while (Visited.insert(V).second);
425
426   return V;
427 }
428 } // namespace
429
430 Value *Value::stripPointerCasts() {
431   return stripPointerCastsAndOffsets<PSK_ZeroIndicesAndAliases>(this);
432 }
433
434 Value *Value::stripPointerCastsNoFollowAliases() {
435   return stripPointerCastsAndOffsets<PSK_ZeroIndices>(this);
436 }
437
438 Value *Value::stripInBoundsConstantOffsets() {
439   return stripPointerCastsAndOffsets<PSK_InBoundsConstantIndices>(this);
440 }
441
442 Value *Value::stripAndAccumulateInBoundsConstantOffsets(const DataLayout &DL,
443                                                         APInt &Offset) {
444   if (!getType()->isPointerTy())
445     return this;
446
447   assert(Offset.getBitWidth() == DL.getPointerSizeInBits(cast<PointerType>(
448                                      getType())->getAddressSpace()) &&
449          "The offset must have exactly as many bits as our pointer.");
450
451   // Even though we don't look through PHI nodes, we could be called on an
452   // instruction in an unreachable block, which may be on a cycle.
453   SmallPtrSet<Value *, 4> Visited;
454   Visited.insert(this);
455   Value *V = this;
456   do {
457     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
458       if (!GEP->isInBounds())
459         return V;
460       APInt GEPOffset(Offset);
461       if (!GEP->accumulateConstantOffset(DL, GEPOffset))
462         return V;
463       Offset = GEPOffset;
464       V = GEP->getPointerOperand();
465     } else if (Operator::getOpcode(V) == Instruction::BitCast ||
466                Operator::getOpcode(V) == Instruction::AddrSpaceCast) {
467       V = cast<Operator>(V)->getOperand(0);
468     } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
469       V = GA->getAliasee();
470     } else {
471       return V;
472     }
473     assert(V->getType()->isPointerTy() && "Unexpected operand type!");
474   } while (Visited.insert(V).second);
475
476   return V;
477 }
478
479 Value *Value::stripInBoundsOffsets() {
480   return stripPointerCastsAndOffsets<PSK_InBounds>(this);
481 }
482
483 /// \brief Check if Value is always a dereferenceable pointer.
484 ///
485 /// Test if V is always a pointer to allocated and suitably aligned memory for
486 /// a simple load or store.
487 static bool isDereferenceablePointer(const Value *V, const DataLayout *DL,
488                                      SmallPtrSetImpl<const Value *> &Visited) {
489   // Note that it is not safe to speculate into a malloc'd region because
490   // malloc may return null.
491
492   // These are obviously ok.
493   if (isa<AllocaInst>(V)) return true;
494
495   // It's not always safe to follow a bitcast, for example:
496   //   bitcast i8* (alloca i8) to i32*
497   // would result in a 4-byte load from a 1-byte alloca. However,
498   // if we're casting from a pointer from a type of larger size
499   // to a type of smaller size (or the same size), and the alignment
500   // is at least as large as for the resulting pointer type, then
501   // we can look through the bitcast.
502   if (DL)
503     if (const BitCastInst* BC = dyn_cast<BitCastInst>(V)) {
504       Type *STy = BC->getSrcTy()->getPointerElementType(),
505            *DTy = BC->getDestTy()->getPointerElementType();
506       if (STy->isSized() && DTy->isSized() &&
507           (DL->getTypeStoreSize(STy) >=
508            DL->getTypeStoreSize(DTy)) &&
509           (DL->getABITypeAlignment(STy) >=
510            DL->getABITypeAlignment(DTy)))
511         return isDereferenceablePointer(BC->getOperand(0), DL, Visited);
512     }
513
514   // Global variables which can't collapse to null are ok.
515   if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
516     return !GV->hasExternalWeakLinkage();
517
518   // byval arguments are okay. Arguments specifically marked as
519   // dereferenceable are okay too.
520   if (const Argument *A = dyn_cast<Argument>(V)) {
521     if (A->hasByValAttr())
522       return true;
523     else if (uint64_t Bytes = A->getDereferenceableBytes()) {
524       Type *Ty = V->getType()->getPointerElementType();
525       if (Ty->isSized() && DL && DL->getTypeStoreSize(Ty) <= Bytes)
526         return true;
527     }
528
529     return false;
530   }
531
532   // Return values from call sites specifically marked as dereferenceable are
533   // also okay.
534   if (ImmutableCallSite CS = V) {
535     if (uint64_t Bytes = CS.getDereferenceableBytes(0)) {
536       Type *Ty = V->getType()->getPointerElementType();
537       if (Ty->isSized() && DL && DL->getTypeStoreSize(Ty) <= Bytes)
538         return true;
539     }
540   }
541
542   // For GEPs, determine if the indexing lands within the allocated object.
543   if (const GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
544     // Conservatively require that the base pointer be fully dereferenceable.
545     if (!Visited.insert(GEP->getOperand(0)).second)
546       return false;
547     if (!isDereferenceablePointer(GEP->getOperand(0), DL, Visited))
548       return false;
549     // Check the indices.
550     gep_type_iterator GTI = gep_type_begin(GEP);
551     for (User::const_op_iterator I = GEP->op_begin()+1,
552          E = GEP->op_end(); I != E; ++I) {
553       Value *Index = *I;
554       Type *Ty = *GTI++;
555       // Struct indices can't be out of bounds.
556       if (isa<StructType>(Ty))
557         continue;
558       ConstantInt *CI = dyn_cast<ConstantInt>(Index);
559       if (!CI)
560         return false;
561       // Zero is always ok.
562       if (CI->isZero())
563         continue;
564       // Check to see that it's within the bounds of an array.
565       ArrayType *ATy = dyn_cast<ArrayType>(Ty);
566       if (!ATy)
567         return false;
568       if (CI->getValue().getActiveBits() > 64)
569         return false;
570       if (CI->getZExtValue() >= ATy->getNumElements())
571         return false;
572     }
573     // Indices check out; this is dereferenceable.
574     return true;
575   }
576
577   if (const AddrSpaceCastInst *ASC = dyn_cast<AddrSpaceCastInst>(V))
578     return isDereferenceablePointer(ASC->getOperand(0), DL, Visited);
579
580   // If we don't know, assume the worst.
581   return false;
582 }
583
584 bool Value::isDereferenceablePointer(const DataLayout *DL) const {
585   // When dereferenceability information is provided by a dereferenceable
586   // attribute, we know exactly how many bytes are dereferenceable. If we can
587   // determine the exact offset to the attributed variable, we can use that
588   // information here.
589   Type *Ty = getType()->getPointerElementType();
590   if (Ty->isSized() && DL) {
591     APInt Offset(DL->getTypeStoreSizeInBits(getType()), 0);
592     const Value *BV = stripAndAccumulateInBoundsConstantOffsets(*DL, Offset);
593
594     APInt DerefBytes(Offset.getBitWidth(), 0);
595     if (const Argument *A = dyn_cast<Argument>(BV))
596       DerefBytes = A->getDereferenceableBytes();
597     else if (ImmutableCallSite CS = BV)
598       DerefBytes = CS.getDereferenceableBytes(0);
599
600     if (DerefBytes.getBoolValue() && Offset.isNonNegative()) {
601       if (DerefBytes.uge(Offset + DL->getTypeStoreSize(Ty)))
602         return true;
603     }
604   }
605
606   SmallPtrSet<const Value *, 32> Visited;
607   return ::isDereferenceablePointer(this, DL, Visited);
608 }
609
610 Value *Value::DoPHITranslation(const BasicBlock *CurBB,
611                                const BasicBlock *PredBB) {
612   PHINode *PN = dyn_cast<PHINode>(this);
613   if (PN && PN->getParent() == CurBB)
614     return PN->getIncomingValueForBlock(PredBB);
615   return this;
616 }
617
618 LLVMContext &Value::getContext() const { return VTy->getContext(); }
619
620 void Value::reverseUseList() {
621   if (!UseList || !UseList->Next)
622     // No need to reverse 0 or 1 uses.
623     return;
624
625   Use *Head = UseList;
626   Use *Current = UseList->Next;
627   Head->Next = nullptr;
628   while (Current) {
629     Use *Next = Current->Next;
630     Current->Next = Head;
631     Head->setPrev(&Current->Next);
632     Head = Current;
633     Current = Next;
634   }
635   UseList = Head;
636   Head->setPrev(&UseList);
637 }
638
639 //===----------------------------------------------------------------------===//
640 //                             ValueHandleBase Class
641 //===----------------------------------------------------------------------===//
642
643 void ValueHandleBase::AddToExistingUseList(ValueHandleBase **List) {
644   assert(List && "Handle list is null?");
645
646   // Splice ourselves into the list.
647   Next = *List;
648   *List = this;
649   setPrevPtr(List);
650   if (Next) {
651     Next->setPrevPtr(&Next);
652     assert(VP.getPointer() == Next->VP.getPointer() && "Added to wrong list?");
653   }
654 }
655
656 void ValueHandleBase::AddToExistingUseListAfter(ValueHandleBase *List) {
657   assert(List && "Must insert after existing node");
658
659   Next = List->Next;
660   setPrevPtr(&List->Next);
661   List->Next = this;
662   if (Next)
663     Next->setPrevPtr(&Next);
664 }
665
666 void ValueHandleBase::AddToUseList() {
667   assert(VP.getPointer() && "Null pointer doesn't have a use list!");
668
669   LLVMContextImpl *pImpl = VP.getPointer()->getContext().pImpl;
670
671   if (VP.getPointer()->HasValueHandle) {
672     // If this value already has a ValueHandle, then it must be in the
673     // ValueHandles map already.
674     ValueHandleBase *&Entry = pImpl->ValueHandles[VP.getPointer()];
675     assert(Entry && "Value doesn't have any handles?");
676     AddToExistingUseList(&Entry);
677     return;
678   }
679
680   // Ok, it doesn't have any handles yet, so we must insert it into the
681   // DenseMap.  However, doing this insertion could cause the DenseMap to
682   // reallocate itself, which would invalidate all of the PrevP pointers that
683   // point into the old table.  Handle this by checking for reallocation and
684   // updating the stale pointers only if needed.
685   DenseMap<Value*, ValueHandleBase*> &Handles = pImpl->ValueHandles;
686   const void *OldBucketPtr = Handles.getPointerIntoBucketsArray();
687
688   ValueHandleBase *&Entry = Handles[VP.getPointer()];
689   assert(!Entry && "Value really did already have handles?");
690   AddToExistingUseList(&Entry);
691   VP.getPointer()->HasValueHandle = true;
692
693   // If reallocation didn't happen or if this was the first insertion, don't
694   // walk the table.
695   if (Handles.isPointerIntoBucketsArray(OldBucketPtr) ||
696       Handles.size() == 1) {
697     return;
698   }
699
700   // Okay, reallocation did happen.  Fix the Prev Pointers.
701   for (DenseMap<Value*, ValueHandleBase*>::iterator I = Handles.begin(),
702        E = Handles.end(); I != E; ++I) {
703     assert(I->second && I->first == I->second->VP.getPointer() &&
704            "List invariant broken!");
705     I->second->setPrevPtr(&I->second);
706   }
707 }
708
709 void ValueHandleBase::RemoveFromUseList() {
710   assert(VP.getPointer() && VP.getPointer()->HasValueHandle &&
711          "Pointer doesn't have a use list!");
712
713   // Unlink this from its use list.
714   ValueHandleBase **PrevPtr = getPrevPtr();
715   assert(*PrevPtr == this && "List invariant broken");
716
717   *PrevPtr = Next;
718   if (Next) {
719     assert(Next->getPrevPtr() == &Next && "List invariant broken");
720     Next->setPrevPtr(PrevPtr);
721     return;
722   }
723
724   // If the Next pointer was null, then it is possible that this was the last
725   // ValueHandle watching VP.  If so, delete its entry from the ValueHandles
726   // map.
727   LLVMContextImpl *pImpl = VP.getPointer()->getContext().pImpl;
728   DenseMap<Value*, ValueHandleBase*> &Handles = pImpl->ValueHandles;
729   if (Handles.isPointerIntoBucketsArray(PrevPtr)) {
730     Handles.erase(VP.getPointer());
731     VP.getPointer()->HasValueHandle = false;
732   }
733 }
734
735
736 void ValueHandleBase::ValueIsDeleted(Value *V) {
737   assert(V->HasValueHandle && "Should only be called if ValueHandles present");
738
739   // Get the linked list base, which is guaranteed to exist since the
740   // HasValueHandle flag is set.
741   LLVMContextImpl *pImpl = V->getContext().pImpl;
742   ValueHandleBase *Entry = pImpl->ValueHandles[V];
743   assert(Entry && "Value bit set but no entries exist");
744
745   // We use a local ValueHandleBase as an iterator so that ValueHandles can add
746   // and remove themselves from the list without breaking our iteration.  This
747   // is not really an AssertingVH; we just have to give ValueHandleBase a kind.
748   // Note that we deliberately do not the support the case when dropping a value
749   // handle results in a new value handle being permanently added to the list
750   // (as might occur in theory for CallbackVH's): the new value handle will not
751   // be processed and the checking code will mete out righteous punishment if
752   // the handle is still present once we have finished processing all the other
753   // value handles (it is fine to momentarily add then remove a value handle).
754   for (ValueHandleBase Iterator(Assert, *Entry); Entry; Entry = Iterator.Next) {
755     Iterator.RemoveFromUseList();
756     Iterator.AddToExistingUseListAfter(Entry);
757     assert(Entry->Next == &Iterator && "Loop invariant broken.");
758
759     switch (Entry->getKind()) {
760     case Assert:
761       break;
762     case Tracking:
763       // Mark that this value has been deleted by setting it to an invalid Value
764       // pointer.
765       Entry->operator=(DenseMapInfo<Value *>::getTombstoneKey());
766       break;
767     case Weak:
768       // Weak just goes to null, which will unlink it from the list.
769       Entry->operator=(nullptr);
770       break;
771     case Callback:
772       // Forward to the subclass's implementation.
773       static_cast<CallbackVH*>(Entry)->deleted();
774       break;
775     }
776   }
777
778   // All callbacks, weak references, and assertingVHs should be dropped by now.
779   if (V->HasValueHandle) {
780 #ifndef NDEBUG      // Only in +Asserts mode...
781     dbgs() << "While deleting: " << *V->getType() << " %" << V->getName()
782            << "\n";
783     if (pImpl->ValueHandles[V]->getKind() == Assert)
784       llvm_unreachable("An asserting value handle still pointed to this"
785                        " value!");
786
787 #endif
788     llvm_unreachable("All references to V were not removed?");
789   }
790 }
791
792
793 void ValueHandleBase::ValueIsRAUWd(Value *Old, Value *New) {
794   assert(Old->HasValueHandle &&"Should only be called if ValueHandles present");
795   assert(Old != New && "Changing value into itself!");
796   assert(Old->getType() == New->getType() &&
797          "replaceAllUses of value with new value of different type!");
798
799   // Get the linked list base, which is guaranteed to exist since the
800   // HasValueHandle flag is set.
801   LLVMContextImpl *pImpl = Old->getContext().pImpl;
802   ValueHandleBase *Entry = pImpl->ValueHandles[Old];
803
804   assert(Entry && "Value bit set but no entries exist");
805
806   // We use a local ValueHandleBase as an iterator so that
807   // ValueHandles can add and remove themselves from the list without
808   // breaking our iteration.  This is not really an AssertingVH; we
809   // just have to give ValueHandleBase some kind.
810   for (ValueHandleBase Iterator(Assert, *Entry); Entry; Entry = Iterator.Next) {
811     Iterator.RemoveFromUseList();
812     Iterator.AddToExistingUseListAfter(Entry);
813     assert(Entry->Next == &Iterator && "Loop invariant broken.");
814
815     switch (Entry->getKind()) {
816     case Assert:
817       // Asserting handle does not follow RAUW implicitly.
818       break;
819     case Tracking:
820       // Tracking goes to new value like a WeakVH. Note that this may make it
821       // something incompatible with its templated type. We don't want to have a
822       // virtual (or inline) interface to handle this though, so instead we make
823       // the TrackingVH accessors guarantee that a client never sees this value.
824
825       // FALLTHROUGH
826     case Weak:
827       // Weak goes to the new value, which will unlink it from Old's list.
828       Entry->operator=(New);
829       break;
830     case Callback:
831       // Forward to the subclass's implementation.
832       static_cast<CallbackVH*>(Entry)->allUsesReplacedWith(New);
833       break;
834     }
835   }
836
837 #ifndef NDEBUG
838   // If any new tracking or weak value handles were added while processing the
839   // list, then complain about it now.
840   if (Old->HasValueHandle)
841     for (Entry = pImpl->ValueHandles[Old]; Entry; Entry = Entry->Next)
842       switch (Entry->getKind()) {
843       case Tracking:
844       case Weak:
845         dbgs() << "After RAUW from " << *Old->getType() << " %"
846                << Old->getName() << " to " << *New->getType() << " %"
847                << New->getName() << "\n";
848         llvm_unreachable("A tracking or weak value handle still pointed to the"
849                          " old value!\n");
850       default:
851         break;
852       }
853 #endif
854 }
855
856 // Pin the vtable to this file.
857 void CallbackVH::anchor() {}