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), Name(nullptr), SubclassID(scid),
00048       HasValueHandle(0), SubclassOptionalData(0), SubclassData(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 
00066 #ifndef NDEBUG      // Only in -g mode...
00067   // Check to make sure that there are no uses of this value that are still
00068   // around when the value is destroyed.  If there are, then we have a dangling
00069   // reference and something is wrong.  This code is here to print out what is
00070   // still being referenced.  The value in question should be printed as
00071   // a <badref>
00072   //
00073   if (!use_empty()) {
00074     dbgs() << "While deleting: " << *VTy << " %" << getName() << "\n";
00075     for (use_iterator I = use_begin(), E = use_end(); I != E; ++I)
00076       dbgs() << "Use still stuck around after Def is destroyed:"
00077            << **I << "\n";
00078   }
00079 #endif
00080   assert(use_empty() && "Uses remain when a value is destroyed!");
00081 
00082   // If this value is named, destroy the name.  This should not be in a symtab
00083   // at this point.
00084   if (Name && SubclassID != MDStringVal)
00085     Name->Destroy();
00086 
00087   // There should be no uses of this object anymore, remove it.
00088   LeakDetector::removeGarbageObject(this);
00089 }
00090 
00091 /// hasNUses - Return true if this Value has exactly N users.
00092 ///
00093 bool Value::hasNUses(unsigned N) const {
00094   const_use_iterator UI = use_begin(), E = use_end();
00095 
00096   for (; N; --N, ++UI)
00097     if (UI == E) return false;  // Too few.
00098   return UI == E;
00099 }
00100 
00101 /// hasNUsesOrMore - Return true if this value has N users or more.  This is
00102 /// logically equivalent to getNumUses() >= N.
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 /// isUsedInBasicBlock - Return true if this value is used in the specified
00114 /// basic block.
00115 bool Value::isUsedInBasicBlock(const BasicBlock *BB) const {
00116   // This can be computed either by scanning the instructions in BB, or by
00117   // scanning the use list of this Value. Both lists can be very long, but
00118   // usually one is quite short.
00119   //
00120   // Scan both lists simultaneously until one is exhausted. This limits the
00121   // search to the shorter list.
00122   BasicBlock::const_iterator BI = BB->begin(), BE = BB->end();
00123   const_user_iterator UI = user_begin(), UE = user_end();
00124   for (; BI != BE && UI != UE; ++BI, ++UI) {
00125     // Scan basic block: Check if this Value is used by the instruction at BI.
00126     if (std::find(BI->op_begin(), BI->op_end(), this) != BI->op_end())
00127       return true;
00128     // Scan use list: Check if the use at UI is in BB.
00129     const Instruction *User = dyn_cast<Instruction>(*UI);
00130     if (User && User->getParent() == BB)
00131       return true;
00132   }
00133   return false;
00134 }
00135 
00136 
00137 /// getNumUses - This method computes the number of uses of this Value.  This
00138 /// is a linear time operation.  Use hasOneUse or hasNUses to check for specific
00139 /// values.
00140 unsigned Value::getNumUses() const {
00141   return (unsigned)std::distance(use_begin(), use_end());
00142 }
00143 
00144 static bool getSymTab(Value *V, ValueSymbolTable *&ST) {
00145   ST = nullptr;
00146   if (Instruction *I = dyn_cast<Instruction>(V)) {
00147     if (BasicBlock *P = I->getParent())
00148       if (Function *PP = P->getParent())
00149         ST = &PP->getValueSymbolTable();
00150   } else if (BasicBlock *BB = dyn_cast<BasicBlock>(V)) {
00151     if (Function *P = BB->getParent())
00152       ST = &P->getValueSymbolTable();
00153   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
00154     if (Module *P = GV->getParent())
00155       ST = &P->getValueSymbolTable();
00156   } else if (Argument *A = dyn_cast<Argument>(V)) {
00157     if (Function *P = A->getParent())
00158       ST = &P->getValueSymbolTable();
00159   } else if (isa<MDString>(V))
00160     return true;
00161   else {
00162     assert(isa<Constant>(V) && "Unknown value type!");
00163     return true;  // no name is setable for this.
00164   }
00165   return false;
00166 }
00167 
00168 StringRef Value::getName() const {
00169   // Make sure the empty string is still a C string. For historical reasons,
00170   // some clients want to call .data() on the result and expect it to be null
00171   // terminated.
00172   if (!Name) return StringRef("", 0);
00173   return Name->getKey();
00174 }
00175 
00176 void Value::setName(const Twine &NewName) {
00177   assert(SubclassID != MDStringVal &&
00178          "Cannot set the name of MDString with this method!");
00179 
00180   // Fast path for common IRBuilder case of setName("") when there is no name.
00181   if (NewName.isTriviallyEmpty() && !hasName())
00182     return;
00183 
00184   SmallString<256> NameData;
00185   StringRef NameRef = NewName.toStringRef(NameData);
00186   assert(NameRef.find_first_of(0) == StringRef::npos &&
00187          "Null bytes are not allowed in names");
00188 
00189   // Name isn't changing?
00190   if (getName() == NameRef)
00191     return;
00192 
00193   assert(!getType()->isVoidTy() && "Cannot assign a name to void values!");
00194 
00195   // Get the symbol table to update for this object.
00196   ValueSymbolTable *ST;
00197   if (getSymTab(this, ST))
00198     return;  // Cannot set a name on this value (e.g. constant).
00199 
00200   if (Function *F = dyn_cast<Function>(this))
00201     getContext().pImpl->IntrinsicIDCache.erase(F);
00202 
00203   if (!ST) { // No symbol table to update?  Just do the change.
00204     if (NameRef.empty()) {
00205       // Free the name for this value.
00206       Name->Destroy();
00207       Name = nullptr;
00208       return;
00209     }
00210 
00211     if (Name)
00212       Name->Destroy();
00213 
00214     // NOTE: Could optimize for the case the name is shrinking to not deallocate
00215     // then reallocated.
00216 
00217     // Create the new name.
00218     Name = ValueName::Create(NameRef);
00219     Name->setValue(this);
00220     return;
00221   }
00222 
00223   // NOTE: Could optimize for the case the name is shrinking to not deallocate
00224   // then reallocated.
00225   if (hasName()) {
00226     // Remove old name.
00227     ST->removeValueName(Name);
00228     Name->Destroy();
00229     Name = nullptr;
00230 
00231     if (NameRef.empty())
00232       return;
00233   }
00234 
00235   // Name is changing to something new.
00236   Name = ST->createValueName(NameRef, this);
00237 }
00238 
00239 
00240 /// takeName - transfer the name from V to this value, setting V's name to
00241 /// empty.  It is an error to call V->takeName(V).
00242 void Value::takeName(Value *V) {
00243   assert(SubclassID != MDStringVal && "Cannot take the name of an MDString!");
00244 
00245   ValueSymbolTable *ST = nullptr;
00246   // If this value has a name, drop it.
00247   if (hasName()) {
00248     // Get the symtab this is in.
00249     if (getSymTab(this, ST)) {
00250       // We can't set a name on this value, but we need to clear V's name if
00251       // it has one.
00252       if (V->hasName()) V->setName("");
00253       return;  // Cannot set a name on this value (e.g. constant).
00254     }
00255 
00256     // Remove old name.
00257     if (ST)
00258       ST->removeValueName(Name);
00259     Name->Destroy();
00260     Name = nullptr;
00261   }
00262 
00263   // Now we know that this has no name.
00264 
00265   // If V has no name either, we're done.
00266   if (!V->hasName()) return;
00267 
00268   // Get this's symtab if we didn't before.
00269   if (!ST) {
00270     if (getSymTab(this, ST)) {
00271       // Clear V's name.
00272       V->setName("");
00273       return;  // Cannot set a name on this value (e.g. constant).
00274     }
00275   }
00276 
00277   // Get V's ST, this should always succed, because V has a name.
00278   ValueSymbolTable *VST;
00279   bool Failure = getSymTab(V, VST);
00280   assert(!Failure && "V has a name, so it should have a ST!"); (void)Failure;
00281 
00282   // If these values are both in the same symtab, we can do this very fast.
00283   // This works even if both values have no symtab yet.
00284   if (ST == VST) {
00285     // Take the name!
00286     Name = V->Name;
00287     V->Name = nullptr;
00288     Name->setValue(this);
00289     return;
00290   }
00291 
00292   // Otherwise, things are slightly more complex.  Remove V's name from VST and
00293   // then reinsert it into ST.
00294 
00295   if (VST)
00296     VST->removeValueName(V->Name);
00297   Name = V->Name;
00298   V->Name = nullptr;
00299   Name->setValue(this);
00300 
00301   if (ST)
00302     ST->reinsertValue(this);
00303 }
00304 
00305 #ifndef NDEBUG
00306 static bool contains(SmallPtrSetImpl<ConstantExpr *> &Cache, ConstantExpr *Expr,
00307                      Constant *C) {
00308   if (!Cache.insert(Expr))
00309     return false;
00310 
00311   for (auto &O : Expr->operands()) {
00312     if (O == C)
00313       return true;
00314     auto *CE = dyn_cast<ConstantExpr>(O);
00315     if (!CE)
00316       continue;
00317     if (contains(Cache, CE, C))
00318       return true;
00319   }
00320   return false;
00321 }
00322 
00323 static bool contains(Value *Expr, Value *V) {
00324   if (Expr == V)
00325     return true;
00326 
00327   auto *C = dyn_cast<Constant>(V);
00328   if (!C)
00329     return false;
00330 
00331   auto *CE = dyn_cast<ConstantExpr>(Expr);
00332   if (!CE)
00333     return false;
00334 
00335   SmallPtrSet<ConstantExpr *, 4> Cache;
00336   return contains(Cache, CE, C);
00337 }
00338 #endif
00339 
00340 void Value::replaceAllUsesWith(Value *New) {
00341   assert(New && "Value::replaceAllUsesWith(<null>) is invalid!");
00342   assert(!contains(New, this) &&
00343          "this->replaceAllUsesWith(expr(this)) is NOT valid!");
00344   assert(New->getType() == getType() &&
00345          "replaceAllUses of value with new value of different type!");
00346 
00347   // Notify all ValueHandles (if present) that this value is going away.
00348   if (HasValueHandle)
00349     ValueHandleBase::ValueIsRAUWd(this, New);
00350 
00351   while (!use_empty()) {
00352     Use &U = *UseList;
00353     // Must handle Constants specially, we cannot call replaceUsesOfWith on a
00354     // constant because they are uniqued.
00355     if (auto *C = dyn_cast<Constant>(U.getUser())) {
00356       if (!isa<GlobalValue>(C)) {
00357         C->replaceUsesOfWithOnConstant(this, New, &U);
00358         continue;
00359       }
00360     }
00361 
00362     U.set(New);
00363   }
00364 
00365   if (BasicBlock *BB = dyn_cast<BasicBlock>(this))
00366     BB->replaceSuccessorsPhiUsesWith(cast<BasicBlock>(New));
00367 }
00368 
00369 namespace {
00370 // Various metrics for how much to strip off of pointers.
00371 enum PointerStripKind {
00372   PSK_ZeroIndices,
00373   PSK_ZeroIndicesAndAliases,
00374   PSK_InBoundsConstantIndices,
00375   PSK_InBounds
00376 };
00377 
00378 template <PointerStripKind StripKind>
00379 static Value *stripPointerCastsAndOffsets(Value *V) {
00380   if (!V->getType()->isPointerTy())
00381     return V;
00382 
00383   // Even though we don't look through PHI nodes, we could be called on an
00384   // instruction in an unreachable block, which may be on a cycle.
00385   SmallPtrSet<Value *, 4> Visited;
00386 
00387   Visited.insert(V);
00388   do {
00389     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
00390       switch (StripKind) {
00391       case PSK_ZeroIndicesAndAliases:
00392       case PSK_ZeroIndices:
00393         if (!GEP->hasAllZeroIndices())
00394           return V;
00395         break;
00396       case PSK_InBoundsConstantIndices:
00397         if (!GEP->hasAllConstantIndices())
00398           return V;
00399         // fallthrough
00400       case PSK_InBounds:
00401         if (!GEP->isInBounds())
00402           return V;
00403         break;
00404       }
00405       V = GEP->getPointerOperand();
00406     } else if (Operator::getOpcode(V) == Instruction::BitCast ||
00407                Operator::getOpcode(V) == Instruction::AddrSpaceCast) {
00408       V = cast<Operator>(V)->getOperand(0);
00409     } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
00410       if (StripKind == PSK_ZeroIndices || GA->mayBeOverridden())
00411         return V;
00412       V = GA->getAliasee();
00413     } else {
00414       return V;
00415     }
00416     assert(V->getType()->isPointerTy() && "Unexpected operand type!");
00417   } while (Visited.insert(V));
00418 
00419   return V;
00420 }
00421 } // namespace
00422 
00423 Value *Value::stripPointerCasts() {
00424   return stripPointerCastsAndOffsets<PSK_ZeroIndicesAndAliases>(this);
00425 }
00426 
00427 Value *Value::stripPointerCastsNoFollowAliases() {
00428   return stripPointerCastsAndOffsets<PSK_ZeroIndices>(this);
00429 }
00430 
00431 Value *Value::stripInBoundsConstantOffsets() {
00432   return stripPointerCastsAndOffsets<PSK_InBoundsConstantIndices>(this);
00433 }
00434 
00435 Value *Value::stripAndAccumulateInBoundsConstantOffsets(const DataLayout &DL,
00436                                                         APInt &Offset) {
00437   if (!getType()->isPointerTy())
00438     return this;
00439 
00440   assert(Offset.getBitWidth() == DL.getPointerSizeInBits(cast<PointerType>(
00441                                      getType())->getAddressSpace()) &&
00442          "The offset must have exactly as many bits as our pointer.");
00443 
00444   // Even though we don't look through PHI nodes, we could be called on an
00445   // instruction in an unreachable block, which may be on a cycle.
00446   SmallPtrSet<Value *, 4> Visited;
00447   Visited.insert(this);
00448   Value *V = this;
00449   do {
00450     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
00451       if (!GEP->isInBounds())
00452         return V;
00453       APInt GEPOffset(Offset);
00454       if (!GEP->accumulateConstantOffset(DL, GEPOffset))
00455         return V;
00456       Offset = GEPOffset;
00457       V = GEP->getPointerOperand();
00458     } else if (Operator::getOpcode(V) == Instruction::BitCast ||
00459                Operator::getOpcode(V) == Instruction::AddrSpaceCast) {
00460       V = cast<Operator>(V)->getOperand(0);
00461     } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
00462       V = GA->getAliasee();
00463     } else {
00464       return V;
00465     }
00466     assert(V->getType()->isPointerTy() && "Unexpected operand type!");
00467   } while (Visited.insert(V));
00468 
00469   return V;
00470 }
00471 
00472 Value *Value::stripInBoundsOffsets() {
00473   return stripPointerCastsAndOffsets<PSK_InBounds>(this);
00474 }
00475 
00476 /// isDereferenceablePointer - Test if this value is always a pointer to
00477 /// allocated and suitably aligned memory for a simple load or store.
00478 static bool isDereferenceablePointer(const Value *V, const DataLayout *DL,
00479                                      SmallPtrSetImpl<const Value *> &Visited) {
00480   // Note that it is not safe to speculate into a malloc'd region because
00481   // malloc may return null.
00482 
00483   // These are obviously ok.
00484   if (isa<AllocaInst>(V)) return true;
00485 
00486   // It's not always safe to follow a bitcast, for example:
00487   //   bitcast i8* (alloca i8) to i32*
00488   // would result in a 4-byte load from a 1-byte alloca. However,
00489   // if we're casting from a pointer from a type of larger size
00490   // to a type of smaller size (or the same size), and the alignment
00491   // is at least as large as for the resulting pointer type, then
00492   // we can look through the bitcast.
00493   if (DL)
00494     if (const BitCastInst* BC = dyn_cast<BitCastInst>(V)) {
00495       Type *STy = BC->getSrcTy()->getPointerElementType(),
00496            *DTy = BC->getDestTy()->getPointerElementType();
00497       if (STy->isSized() && DTy->isSized() &&
00498           (DL->getTypeStoreSize(STy) >=
00499            DL->getTypeStoreSize(DTy)) &&
00500           (DL->getABITypeAlignment(STy) >=
00501            DL->getABITypeAlignment(DTy)))
00502         return isDereferenceablePointer(BC->getOperand(0), DL, Visited);
00503     }
00504 
00505   // Global variables which can't collapse to null are ok.
00506   if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
00507     return !GV->hasExternalWeakLinkage();
00508 
00509   // byval arguments are okay. Arguments specifically marked as
00510   // dereferenceable are okay too.
00511   if (const Argument *A = dyn_cast<Argument>(V)) {
00512     if (A->hasByValAttr())
00513       return true;
00514     else if (uint64_t Bytes = A->getDereferenceableBytes()) {
00515       Type *Ty = V->getType()->getPointerElementType();
00516       if (Ty->isSized() && DL && DL->getTypeStoreSize(Ty) <= Bytes)
00517         return true;
00518     }
00519 
00520     return false;
00521   }
00522 
00523   // Return values from call sites specifically marked as dereferenceable are
00524   // also okay.
00525   if (ImmutableCallSite CS = V) {
00526     if (uint64_t Bytes = CS.getDereferenceableBytes(0)) {
00527       Type *Ty = V->getType()->getPointerElementType();
00528       if (Ty->isSized() && DL && DL->getTypeStoreSize(Ty) <= Bytes)
00529         return true;
00530     }
00531   }
00532 
00533   // For GEPs, determine if the indexing lands within the allocated object.
00534   if (const GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
00535     // Conservatively require that the base pointer be fully dereferenceable.
00536     if (!Visited.insert(GEP->getOperand(0)))
00537       return false;
00538     if (!isDereferenceablePointer(GEP->getOperand(0), DL, Visited))
00539       return false;
00540     // Check the indices.
00541     gep_type_iterator GTI = gep_type_begin(GEP);
00542     for (User::const_op_iterator I = GEP->op_begin()+1,
00543          E = GEP->op_end(); I != E; ++I) {
00544       Value *Index = *I;
00545       Type *Ty = *GTI++;
00546       // Struct indices can't be out of bounds.
00547       if (isa<StructType>(Ty))
00548         continue;
00549       ConstantInt *CI = dyn_cast<ConstantInt>(Index);
00550       if (!CI)
00551         return false;
00552       // Zero is always ok.
00553       if (CI->isZero())
00554         continue;
00555       // Check to see that it's within the bounds of an array.
00556       ArrayType *ATy = dyn_cast<ArrayType>(Ty);
00557       if (!ATy)
00558         return false;
00559       if (CI->getValue().getActiveBits() > 64)
00560         return false;
00561       if (CI->getZExtValue() >= ATy->getNumElements())
00562         return false;
00563     }
00564     // Indices check out; this is dereferenceable.
00565     return true;
00566   }
00567 
00568   if (const AddrSpaceCastInst *ASC = dyn_cast<AddrSpaceCastInst>(V))
00569     return isDereferenceablePointer(ASC->getOperand(0), DL, Visited);
00570 
00571   // If we don't know, assume the worst.
00572   return false;
00573 }
00574 
00575 /// isDereferenceablePointer - Test if this value is always a pointer to
00576 /// allocated and suitably aligned memory for a simple load or store.
00577 bool Value::isDereferenceablePointer(const DataLayout *DL) const {
00578   // When dereferenceability information is provided by a dereferenceable
00579   // attribute, we know exactly how many bytes are dereferenceable. If we can
00580   // determine the exact offset to the attributed variable, we can use that
00581   // information here.
00582   Type *Ty = getType()->getPointerElementType();
00583   if (Ty->isSized() && DL) {
00584     APInt Offset(DL->getTypeStoreSizeInBits(getType()), 0);
00585     const Value *BV = stripAndAccumulateInBoundsConstantOffsets(*DL, Offset);
00586 
00587     APInt DerefBytes(Offset.getBitWidth(), 0);
00588     if (const Argument *A = dyn_cast<Argument>(BV))
00589       DerefBytes = A->getDereferenceableBytes();
00590     else if (ImmutableCallSite CS = BV)
00591       DerefBytes = CS.getDereferenceableBytes(0);
00592 
00593     if (DerefBytes.getBoolValue() && Offset.isNonNegative()) {
00594       if (DerefBytes.uge(Offset + DL->getTypeStoreSize(Ty)))
00595         return true;
00596     }
00597   }
00598 
00599   SmallPtrSet<const Value *, 32> Visited;
00600   return ::isDereferenceablePointer(this, DL, Visited);
00601 }
00602 
00603 /// DoPHITranslation - If this value is a PHI node with CurBB as its parent,
00604 /// return the value in the PHI node corresponding to PredBB.  If not, return
00605 /// ourself.  This is useful if you want to know the value something has in a
00606 /// predecessor block.
00607 Value *Value::DoPHITranslation(const BasicBlock *CurBB,
00608                                const BasicBlock *PredBB) {
00609   PHINode *PN = dyn_cast<PHINode>(this);
00610   if (PN && PN->getParent() == CurBB)
00611     return PN->getIncomingValueForBlock(PredBB);
00612   return this;
00613 }
00614 
00615 LLVMContext &Value::getContext() const { return VTy->getContext(); }
00616 
00617 void Value::reverseUseList() {
00618   if (!UseList || !UseList->Next)
00619     // No need to reverse 0 or 1 uses.
00620     return;
00621 
00622   Use *Head = UseList;
00623   Use *Current = UseList->Next;
00624   Head->Next = nullptr;
00625   while (Current) {
00626     Use *Next = Current->Next;
00627     Current->Next = Head;
00628     Head->setPrev(&Current->Next);
00629     Head = Current;
00630     Current = Next;
00631   }
00632   UseList = Head;
00633   Head->setPrev(&UseList);
00634 }
00635 
00636 //===----------------------------------------------------------------------===//
00637 //                             ValueHandleBase Class
00638 //===----------------------------------------------------------------------===//
00639 
00640 /// AddToExistingUseList - Add this ValueHandle to the use list for VP, where
00641 /// List is known to point into the existing use list.
00642 void ValueHandleBase::AddToExistingUseList(ValueHandleBase **List) {
00643   assert(List && "Handle list is null?");
00644 
00645   // Splice ourselves into the list.
00646   Next = *List;
00647   *List = this;
00648   setPrevPtr(List);
00649   if (Next) {
00650     Next->setPrevPtr(&Next);
00651     assert(VP.getPointer() == Next->VP.getPointer() && "Added to wrong list?");
00652   }
00653 }
00654 
00655 void ValueHandleBase::AddToExistingUseListAfter(ValueHandleBase *List) {
00656   assert(List && "Must insert after existing node");
00657 
00658   Next = List->Next;
00659   setPrevPtr(&List->Next);
00660   List->Next = this;
00661   if (Next)
00662     Next->setPrevPtr(&Next);
00663 }
00664 
00665 /// AddToUseList - Add this ValueHandle to the use list for VP.
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 /// RemoveFromUseList - Remove this ValueHandle from its current use list.
00710 void ValueHandleBase::RemoveFromUseList() {
00711   assert(VP.getPointer() && VP.getPointer()->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 = VP.getPointer()->getContext().pImpl;
00729   DenseMap<Value*, ValueHandleBase*> &Handles = pImpl->ValueHandles;
00730   if (Handles.isPointerIntoBucketsArray(PrevPtr)) {
00731     Handles.erase(VP.getPointer());
00732     VP.getPointer()->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 
00798   // Get the linked list base, which is guaranteed to exist since the
00799   // HasValueHandle flag is set.
00800   LLVMContextImpl *pImpl = Old->getContext().pImpl;
00801   ValueHandleBase *Entry = pImpl->ValueHandles[Old];
00802 
00803   assert(Entry && "Value bit set but no entries exist");
00804 
00805   // We use a local ValueHandleBase as an iterator so that
00806   // ValueHandles can add and remove themselves from the list without
00807   // breaking our iteration.  This is not really an AssertingVH; we
00808   // just have to give ValueHandleBase some kind.
00809   for (ValueHandleBase Iterator(Assert, *Entry); Entry; Entry = Iterator.Next) {
00810     Iterator.RemoveFromUseList();
00811     Iterator.AddToExistingUseListAfter(Entry);
00812     assert(Entry->Next == &Iterator && "Loop invariant broken.");
00813 
00814     switch (Entry->getKind()) {
00815     case Assert:
00816       // Asserting handle does not follow RAUW implicitly.
00817       break;
00818     case Tracking:
00819       // Tracking goes to new value like a WeakVH. Note that this may make it
00820       // something incompatible with its templated type. We don't want to have a
00821       // virtual (or inline) interface to handle this though, so instead we make
00822       // the TrackingVH accessors guarantee that a client never sees this value.
00823 
00824       // FALLTHROUGH
00825     case Weak:
00826       // Weak goes to the new value, which will unlink it from Old's list.
00827       Entry->operator=(New);
00828       break;
00829     case Callback:
00830       // Forward to the subclass's implementation.
00831       static_cast<CallbackVH*>(Entry)->allUsesReplacedWith(New);
00832       break;
00833     }
00834   }
00835 
00836 #ifndef NDEBUG
00837   // If any new tracking or weak value handles were added while processing the
00838   // list, then complain about it now.
00839   if (Old->HasValueHandle)
00840     for (Entry = pImpl->ValueHandles[Old]; Entry; Entry = Entry->Next)
00841       switch (Entry->getKind()) {
00842       case Tracking:
00843       case Weak:
00844         dbgs() << "After RAUW from " << *Old->getType() << " %"
00845                << Old->getName() << " to " << *New->getType() << " %"
00846                << New->getName() << "\n";
00847         llvm_unreachable("A tracking or weak value handle still pointed to the"
00848                          " old value!\n");
00849       default:
00850         break;
00851       }
00852 #endif
00853 }
00854 
00855 // Pin the vtable to this file.
00856 void CallbackVH::anchor() {}