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