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