LLVM API Documentation

Value.cpp
Go to the documentation of this file.
00001 //===-- Value.cpp - Implement the Value class -----------------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements the Value, ValueHandle, and User classes.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "llvm/IR/Value.h"
00015 #include "LLVMContextImpl.h"
00016 #include "llvm/ADT/DenseMap.h"
00017 #include "llvm/ADT/SmallString.h"
00018 #include "llvm/IR/CallSite.h"
00019 #include "llvm/IR/Constant.h"
00020 #include "llvm/IR/Constants.h"
00021 #include "llvm/IR/DataLayout.h"
00022 #include "llvm/IR/DerivedTypes.h"
00023 #include "llvm/IR/GetElementPtrTypeIterator.h"
00024 #include "llvm/IR/InstrTypes.h"
00025 #include "llvm/IR/Instructions.h"
00026 #include "llvm/IR/LeakDetector.h"
00027 #include "llvm/IR/Module.h"
00028 #include "llvm/IR/Operator.h"
00029 #include "llvm/IR/ValueHandle.h"
00030 #include "llvm/IR/ValueSymbolTable.h"
00031 #include "llvm/Support/Debug.h"
00032 #include "llvm/Support/ErrorHandling.h"
00033 #include "llvm/Support/ManagedStatic.h"
00034 #include <algorithm>
00035 using namespace llvm;
00036 
00037 //===----------------------------------------------------------------------===//
00038 //                                Value Class
00039 //===----------------------------------------------------------------------===//
00040 
00041 static inline Type *checkType(Type *Ty) {
00042   assert(Ty && "Value defined with a null type: Error!");
00043   return Ty;
00044 }
00045 
00046 Value::Value(Type *ty, unsigned scid)
00047     : VTy(checkType(ty)), UseList(nullptr), SubclassID(scid), HasValueHandle(0),
00048       SubclassOptionalData(0), SubclassData(0), NumOperands(0) {
00049   // FIXME: Why isn't this in the subclass gunk??
00050   // Note, we cannot call isa<CallInst> before the CallInst has been
00051   // constructed.
00052   if (SubclassID == Instruction::Call || SubclassID == Instruction::Invoke)
00053     assert((VTy->isFirstClassType() || VTy->isVoidTy() || VTy->isStructTy()) &&
00054            "invalid CallInst type!");
00055   else if (SubclassID != BasicBlockVal &&
00056            (SubclassID < ConstantFirstVal || SubclassID > ConstantLastVal))
00057     assert((VTy->isFirstClassType() || VTy->isVoidTy()) &&
00058            "Cannot create non-first-class values except for constants!");
00059 }
00060 
00061 Value::~Value() {
00062   // Notify all ValueHandles (if present) that this value is going away.
00063   if (HasValueHandle)
00064     ValueHandleBase::ValueIsDeleted(this);
00065   if (isUsedByMetadata())
00066     ValueAsMetadata::handleDeletion(this);
00067 
00068 #ifndef NDEBUG      // Only in -g mode...
00069   // Check to make sure that there are no uses of this value that are still
00070   // around when the value is destroyed.  If there are, then we have a dangling
00071   // reference and something is wrong.  This code is here to print out what is
00072   // still being referenced.  The value in question should be printed as
00073   // a <badref>
00074   //
00075   if (!use_empty()) {
00076     dbgs() << "While deleting: " << *VTy << " %" << getName() << "\n";
00077     for (use_iterator I = use_begin(), E = use_end(); I != E; ++I)
00078       dbgs() << "Use still stuck around after Def is destroyed:"
00079            << **I << "\n";
00080   }
00081 #endif
00082   assert(use_empty() && "Uses remain when a value is destroyed!");
00083 
00084   // If this value is named, destroy the name.  This should not be in a symtab
00085   // at this point.
00086   destroyValueName();
00087 
00088   // There should be no uses of this object anymore, remove it.
00089   LeakDetector::removeGarbageObject(this);
00090 }
00091 
00092 void Value::destroyValueName() {
00093   ValueName *Name = getValueName();
00094   if (Name)
00095     Name->Destroy();
00096   setValueName(nullptr);
00097 }
00098 
00099 bool Value::hasNUses(unsigned N) const {
00100   const_use_iterator UI = use_begin(), E = use_end();
00101 
00102   for (; N; --N, ++UI)
00103     if (UI == E) return false;  // Too few.
00104   return UI == E;
00105 }
00106 
00107 bool Value::hasNUsesOrMore(unsigned N) const {
00108   const_use_iterator UI = use_begin(), E = use_end();
00109 
00110   for (; N; --N, ++UI)
00111     if (UI == E) return false;  // Too few.
00112 
00113   return true;
00114 }
00115 
00116 bool Value::isUsedInBasicBlock(const BasicBlock *BB) const {
00117   // This can be computed either by scanning the instructions in BB, or by
00118   // scanning the use list of this Value. Both lists can be very long, but
00119   // usually one is quite short.
00120   //
00121   // Scan both lists simultaneously until one is exhausted. This limits the
00122   // search to the shorter list.
00123   BasicBlock::const_iterator BI = BB->begin(), BE = BB->end();
00124   const_user_iterator UI = user_begin(), UE = user_end();
00125   for (; BI != BE && UI != UE; ++BI, ++UI) {
00126     // Scan basic block: Check if this Value is used by the instruction at BI.
00127     if (std::find(BI->op_begin(), BI->op_end(), this) != BI->op_end())
00128       return true;
00129     // Scan use list: Check if the use at UI is in BB.
00130     const Instruction *User = dyn_cast<Instruction>(*UI);
00131     if (User && User->getParent() == BB)
00132       return true;
00133   }
00134   return false;
00135 }
00136 
00137 unsigned Value::getNumUses() const {
00138   return (unsigned)std::distance(use_begin(), use_end());
00139 }
00140 
00141 static bool getSymTab(Value *V, ValueSymbolTable *&ST) {
00142   ST = nullptr;
00143   if (Instruction *I = dyn_cast<Instruction>(V)) {
00144     if (BasicBlock *P = I->getParent())
00145       if (Function *PP = P->getParent())
00146         ST = &PP->getValueSymbolTable();
00147   } else if (BasicBlock *BB = dyn_cast<BasicBlock>(V)) {
00148     if (Function *P = BB->getParent())
00149       ST = &P->getValueSymbolTable();
00150   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
00151     if (Module *P = GV->getParent())
00152       ST = &P->getValueSymbolTable();
00153   } else if (Argument *A = dyn_cast<Argument>(V)) {
00154     if (Function *P = A->getParent())
00155       ST = &P->getValueSymbolTable();
00156   } else {
00157     assert(isa<Constant>(V) && "Unknown value type!");
00158     return true;  // no name is setable for this.
00159   }
00160   return false;
00161 }
00162 
00163 StringRef Value::getName() const {
00164   // Make sure the empty string is still a C string. For historical reasons,
00165   // some clients want to call .data() on the result and expect it to be null
00166   // terminated.
00167   if (!getValueName())
00168     return StringRef("", 0);
00169   return getValueName()->getKey();
00170 }
00171 
00172 void Value::setName(const Twine &NewName) {
00173   // Fast path for common IRBuilder case of setName("") when there is no name.
00174   if (NewName.isTriviallyEmpty() && !hasName())
00175     return;
00176 
00177   SmallString<256> NameData;
00178   StringRef NameRef = NewName.toStringRef(NameData);
00179   assert(NameRef.find_first_of(0) == StringRef::npos &&
00180          "Null bytes are not allowed in names");
00181 
00182   // Name isn't changing?
00183   if (getName() == NameRef)
00184     return;
00185 
00186   assert(!getType()->isVoidTy() && "Cannot assign a name to void values!");
00187 
00188   // Get the symbol table to update for this object.
00189   ValueSymbolTable *ST;
00190   if (getSymTab(this, ST))
00191     return;  // Cannot set a name on this value (e.g. constant).
00192 
00193   if (Function *F = dyn_cast<Function>(this))
00194     getContext().pImpl->IntrinsicIDCache.erase(F);
00195 
00196   if (!ST) { // No symbol table to update?  Just do the change.
00197     if (NameRef.empty()) {
00198       // Free the name for this value.
00199       destroyValueName();
00200       return;
00201     }
00202 
00203     // NOTE: Could optimize for the case the name is shrinking to not deallocate
00204     // then reallocated.
00205     destroyValueName();
00206 
00207     // Create the new name.
00208     setValueName(ValueName::Create(NameRef));
00209     getValueName()->setValue(this);
00210     return;
00211   }
00212 
00213   // NOTE: Could optimize for the case the name is shrinking to not deallocate
00214   // then reallocated.
00215   if (hasName()) {
00216     // Remove old name.
00217     ST->removeValueName(getValueName());
00218     destroyValueName();
00219 
00220     if (NameRef.empty())
00221       return;
00222   }
00223 
00224   // Name is changing to something new.
00225   setValueName(ST->createValueName(NameRef, this));
00226 }
00227 
00228 void Value::takeName(Value *V) {
00229   ValueSymbolTable *ST = nullptr;
00230   // If this value has a name, drop it.
00231   if (hasName()) {
00232     // Get the symtab this is in.
00233     if (getSymTab(this, ST)) {
00234       // We can't set a name on this value, but we need to clear V's name if
00235       // it has one.
00236       if (V->hasName()) V->setName("");
00237       return;  // Cannot set a name on this value (e.g. constant).
00238     }
00239 
00240     // Remove old name.
00241     if (ST)
00242       ST->removeValueName(getValueName());
00243     destroyValueName();
00244   }
00245 
00246   // Now we know that this has no name.
00247 
00248   // If V has no name either, we're done.
00249   if (!V->hasName()) return;
00250 
00251   // Get this's symtab if we didn't before.
00252   if (!ST) {
00253     if (getSymTab(this, ST)) {
00254       // Clear V's name.
00255       V->setName("");
00256       return;  // Cannot set a name on this value (e.g. constant).
00257     }
00258   }
00259 
00260   // Get V's ST, this should always succed, because V has a name.
00261   ValueSymbolTable *VST;
00262   bool Failure = getSymTab(V, VST);
00263   assert(!Failure && "V has a name, so it should have a ST!"); (void)Failure;
00264 
00265   // If these values are both in the same symtab, we can do this very fast.
00266   // This works even if both values have no symtab yet.
00267   if (ST == VST) {
00268     // Take the name!
00269     setValueName(V->getValueName());
00270     V->setValueName(nullptr);
00271     getValueName()->setValue(this);
00272     return;
00273   }
00274 
00275   // Otherwise, things are slightly more complex.  Remove V's name from VST and
00276   // then reinsert it into ST.
00277 
00278   if (VST)
00279     VST->removeValueName(V->getValueName());
00280   setValueName(V->getValueName());
00281   V->setValueName(nullptr);
00282   getValueName()->setValue(this);
00283 
00284   if (ST)
00285     ST->reinsertValue(this);
00286 }
00287 
00288 #ifndef NDEBUG
00289 static bool contains(SmallPtrSetImpl<ConstantExpr *> &Cache, ConstantExpr *Expr,
00290                      Constant *C) {
00291   if (!Cache.insert(Expr).second)
00292     return false;
00293 
00294   for (auto &O : Expr->operands()) {
00295     if (O == C)
00296       return true;
00297     auto *CE = dyn_cast<ConstantExpr>(O);
00298     if (!CE)
00299       continue;
00300     if (contains(Cache, CE, C))
00301       return true;
00302   }
00303   return false;
00304 }
00305 
00306 static bool contains(Value *Expr, Value *V) {
00307   if (Expr == V)
00308     return true;
00309 
00310   auto *C = dyn_cast<Constant>(V);
00311   if (!C)
00312     return false;
00313 
00314   auto *CE = dyn_cast<ConstantExpr>(Expr);
00315   if (!CE)
00316     return false;
00317 
00318   SmallPtrSet<ConstantExpr *, 4> Cache;
00319   return contains(Cache, CE, C);
00320 }
00321 #endif
00322 
00323 void Value::replaceAllUsesWith(Value *New) {
00324   assert(New && "Value::replaceAllUsesWith(<null>) is invalid!");
00325   assert(!contains(New, this) &&
00326          "this->replaceAllUsesWith(expr(this)) is NOT valid!");
00327   assert(New->getType() == getType() &&
00328          "replaceAllUses of value with new value of different type!");
00329 
00330   // Notify all ValueHandles (if present) that this value is going away.
00331   if (HasValueHandle)
00332     ValueHandleBase::ValueIsRAUWd(this, New);
00333   if (isUsedByMetadata())
00334     ValueAsMetadata::handleRAUW(this, New);
00335 
00336   while (!use_empty()) {
00337     Use &U = *UseList;
00338     // Must handle Constants specially, we cannot call replaceUsesOfWith on a
00339     // constant because they are uniqued.
00340     if (auto *C = dyn_cast<Constant>(U.getUser())) {
00341       if (!isa<GlobalValue>(C)) {
00342         C->replaceUsesOfWithOnConstant(this, New, &U);
00343         continue;
00344       }
00345     }
00346 
00347     U.set(New);
00348   }
00349 
00350   if (BasicBlock *BB = dyn_cast<BasicBlock>(this))
00351     BB->replaceSuccessorsPhiUsesWith(cast<BasicBlock>(New));
00352 }
00353 
00354 // Like replaceAllUsesWith except it does not handle constants or basic blocks.
00355 // This routine leaves uses within BB.
00356 void Value::replaceUsesOutsideBlock(Value *New, BasicBlock *BB) {
00357   assert(New && "Value::replaceUsesOutsideBlock(<null>, BB) is invalid!");
00358   assert(!contains(New, this) &&
00359          "this->replaceUsesOutsideBlock(expr(this), BB) is NOT valid!");
00360   assert(New->getType() == getType() &&
00361          "replaceUses of value with new value of different type!");
00362   assert(BB && "Basic block that may contain a use of 'New' must be defined\n");
00363 
00364   use_iterator UI = use_begin(), E = use_end();
00365   for (; UI != E;) {
00366     Use &U = *UI;
00367     ++UI;
00368     auto *Usr = dyn_cast<Instruction>(U.getUser());
00369     if (Usr && Usr->getParent() == BB)
00370       continue;
00371     U.set(New);
00372   }
00373   return;
00374 }
00375 
00376 namespace {
00377 // Various metrics for how much to strip off of pointers.
00378 enum PointerStripKind {
00379   PSK_ZeroIndices,
00380   PSK_ZeroIndicesAndAliases,
00381   PSK_InBoundsConstantIndices,
00382   PSK_InBounds
00383 };
00384 
00385 template <PointerStripKind StripKind>
00386 static Value *stripPointerCastsAndOffsets(Value *V) {
00387   if (!V->getType()->isPointerTy())
00388     return V;
00389 
00390   // Even though we don't look through PHI nodes, we could be called on an
00391   // instruction in an unreachable block, which may be on a cycle.
00392   SmallPtrSet<Value *, 4> Visited;
00393 
00394   Visited.insert(V);
00395   do {
00396     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
00397       switch (StripKind) {
00398       case PSK_ZeroIndicesAndAliases:
00399       case PSK_ZeroIndices:
00400         if (!GEP->hasAllZeroIndices())
00401           return V;
00402         break;
00403       case PSK_InBoundsConstantIndices:
00404         if (!GEP->hasAllConstantIndices())
00405           return V;
00406         // fallthrough
00407       case PSK_InBounds:
00408         if (!GEP->isInBounds())
00409           return V;
00410         break;
00411       }
00412       V = GEP->getPointerOperand();
00413     } else if (Operator::getOpcode(V) == Instruction::BitCast ||
00414                Operator::getOpcode(V) == Instruction::AddrSpaceCast) {
00415       V = cast<Operator>(V)->getOperand(0);
00416     } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
00417       if (StripKind == PSK_ZeroIndices || GA->mayBeOverridden())
00418         return V;
00419       V = GA->getAliasee();
00420     } else {
00421       return V;
00422     }
00423     assert(V->getType()->isPointerTy() && "Unexpected operand type!");
00424   } while (Visited.insert(V).second);
00425 
00426   return V;
00427 }
00428 } // namespace
00429 
00430 Value *Value::stripPointerCasts() {
00431   return stripPointerCastsAndOffsets<PSK_ZeroIndicesAndAliases>(this);
00432 }
00433 
00434 Value *Value::stripPointerCastsNoFollowAliases() {
00435   return stripPointerCastsAndOffsets<PSK_ZeroIndices>(this);
00436 }
00437 
00438 Value *Value::stripInBoundsConstantOffsets() {
00439   return stripPointerCastsAndOffsets<PSK_InBoundsConstantIndices>(this);
00440 }
00441 
00442 Value *Value::stripAndAccumulateInBoundsConstantOffsets(const DataLayout &DL,
00443                                                         APInt &Offset) {
00444   if (!getType()->isPointerTy())
00445     return this;
00446 
00447   assert(Offset.getBitWidth() == DL.getPointerSizeInBits(cast<PointerType>(
00448                                      getType())->getAddressSpace()) &&
00449          "The offset must have exactly as many bits as our pointer.");
00450 
00451   // Even though we don't look through PHI nodes, we could be called on an
00452   // instruction in an unreachable block, which may be on a cycle.
00453   SmallPtrSet<Value *, 4> Visited;
00454   Visited.insert(this);
00455   Value *V = this;
00456   do {
00457     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
00458       if (!GEP->isInBounds())
00459         return V;
00460       APInt GEPOffset(Offset);
00461       if (!GEP->accumulateConstantOffset(DL, GEPOffset))
00462         return V;
00463       Offset = GEPOffset;
00464       V = GEP->getPointerOperand();
00465     } else if (Operator::getOpcode(V) == Instruction::BitCast ||
00466                Operator::getOpcode(V) == Instruction::AddrSpaceCast) {
00467       V = cast<Operator>(V)->getOperand(0);
00468     } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
00469       V = GA->getAliasee();
00470     } else {
00471       return V;
00472     }
00473     assert(V->getType()->isPointerTy() && "Unexpected operand type!");
00474   } while (Visited.insert(V).second);
00475 
00476   return V;
00477 }
00478 
00479 Value *Value::stripInBoundsOffsets() {
00480   return stripPointerCastsAndOffsets<PSK_InBounds>(this);
00481 }
00482 
00483 /// \brief Check if Value is always a dereferenceable pointer.
00484 ///
00485 /// Test if V is always a pointer to allocated and suitably aligned memory for
00486 /// a simple load or store.
00487 static bool isDereferenceablePointer(const Value *V, const DataLayout *DL,
00488                                      SmallPtrSetImpl<const Value *> &Visited) {
00489   // Note that it is not safe to speculate into a malloc'd region because
00490   // malloc may return null.
00491 
00492   // These are obviously ok.
00493   if (isa<AllocaInst>(V)) return true;
00494 
00495   // It's not always safe to follow a bitcast, for example:
00496   //   bitcast i8* (alloca i8) to i32*
00497   // would result in a 4-byte load from a 1-byte alloca. However,
00498   // if we're casting from a pointer from a type of larger size
00499   // to a type of smaller size (or the same size), and the alignment
00500   // is at least as large as for the resulting pointer type, then
00501   // we can look through the bitcast.
00502   if (DL)
00503     if (const BitCastInst* BC = dyn_cast<BitCastInst>(V)) {
00504       Type *STy = BC->getSrcTy()->getPointerElementType(),
00505            *DTy = BC->getDestTy()->getPointerElementType();
00506       if (STy->isSized() && DTy->isSized() &&
00507           (DL->getTypeStoreSize(STy) >=
00508            DL->getTypeStoreSize(DTy)) &&
00509           (DL->getABITypeAlignment(STy) >=
00510            DL->getABITypeAlignment(DTy)))
00511         return isDereferenceablePointer(BC->getOperand(0), DL, Visited);
00512     }
00513 
00514   // Global variables which can't collapse to null are ok.
00515   if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
00516     return !GV->hasExternalWeakLinkage();
00517 
00518   // byval arguments are okay. Arguments specifically marked as
00519   // dereferenceable are okay too.
00520   if (const Argument *A = dyn_cast<Argument>(V)) {
00521     if (A->hasByValAttr())
00522       return true;
00523     else if (uint64_t Bytes = A->getDereferenceableBytes()) {
00524       Type *Ty = V->getType()->getPointerElementType();
00525       if (Ty->isSized() && DL && DL->getTypeStoreSize(Ty) <= Bytes)
00526         return true;
00527     }
00528 
00529     return false;
00530   }
00531 
00532   // Return values from call sites specifically marked as dereferenceable are
00533   // also okay.
00534   if (ImmutableCallSite CS = V) {
00535     if (uint64_t Bytes = CS.getDereferenceableBytes(0)) {
00536       Type *Ty = V->getType()->getPointerElementType();
00537       if (Ty->isSized() && DL && DL->getTypeStoreSize(Ty) <= Bytes)
00538         return true;
00539     }
00540   }
00541 
00542   // For GEPs, determine if the indexing lands within the allocated object.
00543   if (const GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
00544     // Conservatively require that the base pointer be fully dereferenceable.
00545     if (!Visited.insert(GEP->getOperand(0)).second)
00546       return false;
00547     if (!isDereferenceablePointer(GEP->getOperand(0), DL, Visited))
00548       return false;
00549     // Check the indices.
00550     gep_type_iterator GTI = gep_type_begin(GEP);
00551     for (User::const_op_iterator I = GEP->op_begin()+1,
00552          E = GEP->op_end(); I != E; ++I) {
00553       Value *Index = *I;
00554       Type *Ty = *GTI++;
00555       // Struct indices can't be out of bounds.
00556       if (isa<StructType>(Ty))
00557         continue;
00558       ConstantInt *CI = dyn_cast<ConstantInt>(Index);
00559       if (!CI)
00560         return false;
00561       // Zero is always ok.
00562       if (CI->isZero())
00563         continue;
00564       // Check to see that it's within the bounds of an array.
00565       ArrayType *ATy = dyn_cast<ArrayType>(Ty);
00566       if (!ATy)
00567         return false;
00568       if (CI->getValue().getActiveBits() > 64)
00569         return false;
00570       if (CI->getZExtValue() >= ATy->getNumElements())
00571         return false;
00572     }
00573     // Indices check out; this is dereferenceable.
00574     return true;
00575   }
00576 
00577   if (const AddrSpaceCastInst *ASC = dyn_cast<AddrSpaceCastInst>(V))
00578     return isDereferenceablePointer(ASC->getOperand(0), DL, Visited);
00579 
00580   // If we don't know, assume the worst.
00581   return false;
00582 }
00583 
00584 bool Value::isDereferenceablePointer(const DataLayout *DL) const {
00585   // When dereferenceability information is provided by a dereferenceable
00586   // attribute, we know exactly how many bytes are dereferenceable. If we can
00587   // determine the exact offset to the attributed variable, we can use that
00588   // information here.
00589   Type *Ty = getType()->getPointerElementType();
00590   if (Ty->isSized() && DL) {
00591     APInt Offset(DL->getTypeStoreSizeInBits(getType()), 0);
00592     const Value *BV = stripAndAccumulateInBoundsConstantOffsets(*DL, Offset);
00593 
00594     APInt DerefBytes(Offset.getBitWidth(), 0);
00595     if (const Argument *A = dyn_cast<Argument>(BV))
00596       DerefBytes = A->getDereferenceableBytes();
00597     else if (ImmutableCallSite CS = BV)
00598       DerefBytes = CS.getDereferenceableBytes(0);
00599 
00600     if (DerefBytes.getBoolValue() && Offset.isNonNegative()) {
00601       if (DerefBytes.uge(Offset + DL->getTypeStoreSize(Ty)))
00602         return true;
00603     }
00604   }
00605 
00606   SmallPtrSet<const Value *, 32> Visited;
00607   return ::isDereferenceablePointer(this, DL, Visited);
00608 }
00609 
00610 Value *Value::DoPHITranslation(const BasicBlock *CurBB,
00611                                const BasicBlock *PredBB) {
00612   PHINode *PN = dyn_cast<PHINode>(this);
00613   if (PN && PN->getParent() == CurBB)
00614     return PN->getIncomingValueForBlock(PredBB);
00615   return this;
00616 }
00617 
00618 LLVMContext &Value::getContext() const { return VTy->getContext(); }
00619 
00620 void Value::reverseUseList() {
00621   if (!UseList || !UseList->Next)
00622     // No need to reverse 0 or 1 uses.
00623     return;
00624 
00625   Use *Head = UseList;
00626   Use *Current = UseList->Next;
00627   Head->Next = nullptr;
00628   while (Current) {
00629     Use *Next = Current->Next;
00630     Current->Next = Head;
00631     Head->setPrev(&Current->Next);
00632     Head = Current;
00633     Current = Next;
00634   }
00635   UseList = Head;
00636   Head->setPrev(&UseList);
00637 }
00638 
00639 //===----------------------------------------------------------------------===//
00640 //                             ValueHandleBase Class
00641 //===----------------------------------------------------------------------===//
00642 
00643 void ValueHandleBase::AddToExistingUseList(ValueHandleBase **List) {
00644   assert(List && "Handle list is null?");
00645 
00646   // Splice ourselves into the list.
00647   Next = *List;
00648   *List = this;
00649   setPrevPtr(List);
00650   if (Next) {
00651     Next->setPrevPtr(&Next);
00652     assert(VP.getPointer() == Next->VP.getPointer() && "Added to wrong list?");
00653   }
00654 }
00655 
00656 void ValueHandleBase::AddToExistingUseListAfter(ValueHandleBase *List) {
00657   assert(List && "Must insert after existing node");
00658 
00659   Next = List->Next;
00660   setPrevPtr(&List->Next);
00661   List->Next = this;
00662   if (Next)
00663     Next->setPrevPtr(&Next);
00664 }
00665 
00666 void ValueHandleBase::AddToUseList() {
00667   assert(VP.getPointer() && "Null pointer doesn't have a use list!");
00668 
00669   LLVMContextImpl *pImpl = VP.getPointer()->getContext().pImpl;
00670 
00671   if (VP.getPointer()->HasValueHandle) {
00672     // If this value already has a ValueHandle, then it must be in the
00673     // ValueHandles map already.
00674     ValueHandleBase *&Entry = pImpl->ValueHandles[VP.getPointer()];
00675     assert(Entry && "Value doesn't have any handles?");
00676     AddToExistingUseList(&Entry);
00677     return;
00678   }
00679 
00680   // Ok, it doesn't have any handles yet, so we must insert it into the
00681   // DenseMap.  However, doing this insertion could cause the DenseMap to
00682   // reallocate itself, which would invalidate all of the PrevP pointers that
00683   // point into the old table.  Handle this by checking for reallocation and
00684   // updating the stale pointers only if needed.
00685   DenseMap<Value*, ValueHandleBase*> &Handles = pImpl->ValueHandles;
00686   const void *OldBucketPtr = Handles.getPointerIntoBucketsArray();
00687 
00688   ValueHandleBase *&Entry = Handles[VP.getPointer()];
00689   assert(!Entry && "Value really did already have handles?");
00690   AddToExistingUseList(&Entry);
00691   VP.getPointer()->HasValueHandle = true;
00692 
00693   // If reallocation didn't happen or if this was the first insertion, don't
00694   // walk the table.
00695   if (Handles.isPointerIntoBucketsArray(OldBucketPtr) ||
00696       Handles.size() == 1) {
00697     return;
00698   }
00699 
00700   // Okay, reallocation did happen.  Fix the Prev Pointers.
00701   for (DenseMap<Value*, ValueHandleBase*>::iterator I = Handles.begin(),
00702        E = Handles.end(); I != E; ++I) {
00703     assert(I->second && I->first == I->second->VP.getPointer() &&
00704            "List invariant broken!");
00705     I->second->setPrevPtr(&I->second);
00706   }
00707 }
00708 
00709 void ValueHandleBase::RemoveFromUseList() {
00710   assert(VP.getPointer() && VP.getPointer()->HasValueHandle &&
00711          "Pointer doesn't have a use list!");
00712 
00713   // Unlink this from its use list.
00714   ValueHandleBase **PrevPtr = getPrevPtr();
00715   assert(*PrevPtr == this && "List invariant broken");
00716 
00717   *PrevPtr = Next;
00718   if (Next) {
00719     assert(Next->getPrevPtr() == &Next && "List invariant broken");
00720     Next->setPrevPtr(PrevPtr);
00721     return;
00722   }
00723 
00724   // If the Next pointer was null, then it is possible that this was the last
00725   // ValueHandle watching VP.  If so, delete its entry from the ValueHandles
00726   // map.
00727   LLVMContextImpl *pImpl = VP.getPointer()->getContext().pImpl;
00728   DenseMap<Value*, ValueHandleBase*> &Handles = pImpl->ValueHandles;
00729   if (Handles.isPointerIntoBucketsArray(PrevPtr)) {
00730     Handles.erase(VP.getPointer());
00731     VP.getPointer()->HasValueHandle = false;
00732   }
00733 }
00734 
00735 
00736 void ValueHandleBase::ValueIsDeleted(Value *V) {
00737   assert(V->HasValueHandle && "Should only be called if ValueHandles present");
00738 
00739   // Get the linked list base, which is guaranteed to exist since the
00740   // HasValueHandle flag is set.
00741   LLVMContextImpl *pImpl = V->getContext().pImpl;
00742   ValueHandleBase *Entry = pImpl->ValueHandles[V];
00743   assert(Entry && "Value bit set but no entries exist");
00744 
00745   // We use a local ValueHandleBase as an iterator so that ValueHandles can add
00746   // and remove themselves from the list without breaking our iteration.  This
00747   // is not really an AssertingVH; we just have to give ValueHandleBase a kind.
00748   // Note that we deliberately do not the support the case when dropping a value
00749   // handle results in a new value handle being permanently added to the list
00750   // (as might occur in theory for CallbackVH's): the new value handle will not
00751   // be processed and the checking code will mete out righteous punishment if
00752   // the handle is still present once we have finished processing all the other
00753   // value handles (it is fine to momentarily add then remove a value handle).
00754   for (ValueHandleBase Iterator(Assert, *Entry); Entry; Entry = Iterator.Next) {
00755     Iterator.RemoveFromUseList();
00756     Iterator.AddToExistingUseListAfter(Entry);
00757     assert(Entry->Next == &Iterator && "Loop invariant broken.");
00758 
00759     switch (Entry->getKind()) {
00760     case Assert:
00761       break;
00762     case Tracking:
00763       // Mark that this value has been deleted by setting it to an invalid Value
00764       // pointer.
00765       Entry->operator=(DenseMapInfo<Value *>::getTombstoneKey());
00766       break;
00767     case Weak:
00768       // Weak just goes to null, which will unlink it from the list.
00769       Entry->operator=(nullptr);
00770       break;
00771     case Callback:
00772       // Forward to the subclass's implementation.
00773       static_cast<CallbackVH*>(Entry)->deleted();
00774       break;
00775     }
00776   }
00777 
00778   // All callbacks, weak references, and assertingVHs should be dropped by now.
00779   if (V->HasValueHandle) {
00780 #ifndef NDEBUG      // Only in +Asserts mode...
00781     dbgs() << "While deleting: " << *V->getType() << " %" << V->getName()
00782            << "\n";
00783     if (pImpl->ValueHandles[V]->getKind() == Assert)
00784       llvm_unreachable("An asserting value handle still pointed to this"
00785                        " value!");
00786 
00787 #endif
00788     llvm_unreachable("All references to V were not removed?");
00789   }
00790 }
00791 
00792 
00793 void ValueHandleBase::ValueIsRAUWd(Value *Old, Value *New) {
00794   assert(Old->HasValueHandle &&"Should only be called if ValueHandles present");
00795   assert(Old != New && "Changing value into itself!");
00796   assert(Old->getType() == New->getType() &&
00797          "replaceAllUses of value with new value of different type!");
00798 
00799   // Get the linked list base, which is guaranteed to exist since the
00800   // HasValueHandle flag is set.
00801   LLVMContextImpl *pImpl = Old->getContext().pImpl;
00802   ValueHandleBase *Entry = pImpl->ValueHandles[Old];
00803 
00804   assert(Entry && "Value bit set but no entries exist");
00805 
00806   // We use a local ValueHandleBase as an iterator so that
00807   // ValueHandles can add and remove themselves from the list without
00808   // breaking our iteration.  This is not really an AssertingVH; we
00809   // just have to give ValueHandleBase some kind.
00810   for (ValueHandleBase Iterator(Assert, *Entry); Entry; Entry = Iterator.Next) {
00811     Iterator.RemoveFromUseList();
00812     Iterator.AddToExistingUseListAfter(Entry);
00813     assert(Entry->Next == &Iterator && "Loop invariant broken.");
00814 
00815     switch (Entry->getKind()) {
00816     case Assert:
00817       // Asserting handle does not follow RAUW implicitly.
00818       break;
00819     case Tracking:
00820       // Tracking goes to new value like a WeakVH. Note that this may make it
00821       // something incompatible with its templated type. We don't want to have a
00822       // virtual (or inline) interface to handle this though, so instead we make
00823       // the TrackingVH accessors guarantee that a client never sees this value.
00824 
00825       // FALLTHROUGH
00826     case Weak:
00827       // Weak goes to the new value, which will unlink it from Old's list.
00828       Entry->operator=(New);
00829       break;
00830     case Callback:
00831       // Forward to the subclass's implementation.
00832       static_cast<CallbackVH*>(Entry)->allUsesReplacedWith(New);
00833       break;
00834     }
00835   }
00836 
00837 #ifndef NDEBUG
00838   // If any new tracking or weak value handles were added while processing the
00839   // list, then complain about it now.
00840   if (Old->HasValueHandle)
00841     for (Entry = pImpl->ValueHandles[Old]; Entry; Entry = Entry->Next)
00842       switch (Entry->getKind()) {
00843       case Tracking:
00844       case Weak:
00845         dbgs() << "After RAUW from " << *Old->getType() << " %"
00846                << Old->getName() << " to " << *New->getType() << " %"
00847                << New->getName() << "\n";
00848         llvm_unreachable("A tracking or weak value handle still pointed to the"
00849                          " old value!\n");
00850       default:
00851         break;
00852       }
00853 #endif
00854 }
00855 
00856 // Pin the vtable to this file.
00857 void CallbackVH::anchor() {}