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