1 //===-- Value.cpp - Implement the Value class -----------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements the Value, ValueHandle, and User classes. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "llvm/IR/Value.h" 14 #include "LLVMContextImpl.h" 15 #include "llvm/ADT/DenseMap.h" 16 #include "llvm/ADT/SmallString.h" 17 #include "llvm/ADT/SetVector.h" 18 #include "llvm/IR/Constant.h" 19 #include "llvm/IR/Constants.h" 20 #include "llvm/IR/DataLayout.h" 21 #include "llvm/IR/DerivedTypes.h" 22 #include "llvm/IR/DerivedUser.h" 23 #include "llvm/IR/GetElementPtrTypeIterator.h" 24 #include "llvm/IR/InstrTypes.h" 25 #include "llvm/IR/Instructions.h" 26 #include "llvm/IR/IntrinsicInst.h" 27 #include "llvm/IR/Module.h" 28 #include "llvm/IR/Operator.h" 29 #include "llvm/IR/Statepoint.h" 30 #include "llvm/IR/ValueHandle.h" 31 #include "llvm/IR/ValueSymbolTable.h" 32 #include "llvm/Support/Debug.h" 33 #include "llvm/Support/ErrorHandling.h" 34 #include "llvm/Support/ManagedStatic.h" 35 #include "llvm/Support/raw_ostream.h" 36 #include <algorithm> 37 38 using namespace llvm; 39 40 static cl::opt<unsigned> NonGlobalValueMaxNameSize( 41 "non-global-value-max-name-size", cl::Hidden, cl::init(1024), 42 cl::desc("Maximum size for the name of non-global values.")); 43 44 //===----------------------------------------------------------------------===// 45 // Value Class 46 //===----------------------------------------------------------------------===// 47 static inline Type *checkType(Type *Ty) { 48 assert(Ty && "Value defined with a null type: Error!"); 49 return Ty; 50 } 51 52 Value::Value(Type *ty, unsigned scid) 53 : VTy(checkType(ty)), UseList(nullptr), SubclassID(scid), 54 HasValueHandle(0), SubclassOptionalData(0), SubclassData(0), 55 NumUserOperands(0), IsUsedByMD(false), HasName(false) { 56 static_assert(ConstantFirstVal == 0, "!(SubclassID < ConstantFirstVal)"); 57 // FIXME: Why isn't this in the subclass gunk?? 58 // Note, we cannot call isa<CallInst> before the CallInst has been 59 // constructed. 60 if (SubclassID == Instruction::Call || SubclassID == Instruction::Invoke || 61 SubclassID == Instruction::CallBr) 62 assert((VTy->isFirstClassType() || VTy->isVoidTy() || VTy->isStructTy()) && 63 "invalid CallInst type!"); 64 else if (SubclassID != BasicBlockVal && 65 (/*SubclassID < ConstantFirstVal ||*/ SubclassID > ConstantLastVal)) 66 assert((VTy->isFirstClassType() || VTy->isVoidTy()) && 67 "Cannot create non-first-class values except for constants!"); 68 static_assert(sizeof(Value) == 2 * sizeof(void *) + 2 * sizeof(unsigned), 69 "Value too big"); 70 } 71 72 Value::~Value() { 73 // Notify all ValueHandles (if present) that this value is going away. 74 if (HasValueHandle) 75 ValueHandleBase::ValueIsDeleted(this); 76 if (isUsedByMetadata()) 77 ValueAsMetadata::handleDeletion(this); 78 79 #ifndef NDEBUG // Only in -g mode... 80 // Check to make sure that there are no uses of this value that are still 81 // around when the value is destroyed. If there are, then we have a dangling 82 // reference and something is wrong. This code is here to print out where 83 // the value is still being referenced. 84 // 85 if (!use_empty()) { 86 dbgs() << "While deleting: " << *VTy << " %" << getName() << "\n"; 87 for (auto *U : users()) 88 dbgs() << "Use still stuck around after Def is destroyed:" << *U << "\n"; 89 } 90 #endif 91 assert(use_empty() && "Uses remain when a value is destroyed!"); 92 93 // If this value is named, destroy the name. This should not be in a symtab 94 // at this point. 95 destroyValueName(); 96 } 97 98 void Value::deleteValue() { 99 switch (getValueID()) { 100 #define HANDLE_VALUE(Name) \ 101 case Value::Name##Val: \ 102 delete static_cast<Name *>(this); \ 103 break; 104 #define HANDLE_MEMORY_VALUE(Name) \ 105 case Value::Name##Val: \ 106 static_cast<DerivedUser *>(this)->DeleteValue( \ 107 static_cast<DerivedUser *>(this)); \ 108 break; 109 #define HANDLE_INSTRUCTION(Name) /* nothing */ 110 #include "llvm/IR/Value.def" 111 112 #define HANDLE_INST(N, OPC, CLASS) \ 113 case Value::InstructionVal + Instruction::OPC: \ 114 delete static_cast<CLASS *>(this); \ 115 break; 116 #define HANDLE_USER_INST(N, OPC, CLASS) 117 #include "llvm/IR/Instruction.def" 118 119 default: 120 llvm_unreachable("attempting to delete unknown value kind"); 121 } 122 } 123 124 void Value::destroyValueName() { 125 ValueName *Name = getValueName(); 126 if (Name) 127 Name->Destroy(); 128 setValueName(nullptr); 129 } 130 131 bool Value::hasNUses(unsigned N) const { 132 return hasNItems(use_begin(), use_end(), N); 133 } 134 135 bool Value::hasNUsesOrMore(unsigned N) const { 136 return hasNItemsOrMore(use_begin(), use_end(), N); 137 } 138 139 bool Value::isUsedInBasicBlock(const BasicBlock *BB) const { 140 // This can be computed either by scanning the instructions in BB, or by 141 // scanning the use list of this Value. Both lists can be very long, but 142 // usually one is quite short. 143 // 144 // Scan both lists simultaneously until one is exhausted. This limits the 145 // search to the shorter list. 146 BasicBlock::const_iterator BI = BB->begin(), BE = BB->end(); 147 const_user_iterator UI = user_begin(), UE = user_end(); 148 for (; BI != BE && UI != UE; ++BI, ++UI) { 149 // Scan basic block: Check if this Value is used by the instruction at BI. 150 if (is_contained(BI->operands(), this)) 151 return true; 152 // Scan use list: Check if the use at UI is in BB. 153 const auto *User = dyn_cast<Instruction>(*UI); 154 if (User && User->getParent() == BB) 155 return true; 156 } 157 return false; 158 } 159 160 unsigned Value::getNumUses() const { 161 return (unsigned)std::distance(use_begin(), use_end()); 162 } 163 164 static bool getSymTab(Value *V, ValueSymbolTable *&ST) { 165 ST = nullptr; 166 if (Instruction *I = dyn_cast<Instruction>(V)) { 167 if (BasicBlock *P = I->getParent()) 168 if (Function *PP = P->getParent()) 169 ST = PP->getValueSymbolTable(); 170 } else if (BasicBlock *BB = dyn_cast<BasicBlock>(V)) { 171 if (Function *P = BB->getParent()) 172 ST = P->getValueSymbolTable(); 173 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) { 174 if (Module *P = GV->getParent()) 175 ST = &P->getValueSymbolTable(); 176 } else if (Argument *A = dyn_cast<Argument>(V)) { 177 if (Function *P = A->getParent()) 178 ST = P->getValueSymbolTable(); 179 } else { 180 assert(isa<Constant>(V) && "Unknown value type!"); 181 return true; // no name is setable for this. 182 } 183 return false; 184 } 185 186 ValueName *Value::getValueName() const { 187 if (!HasName) return nullptr; 188 189 LLVMContext &Ctx = getContext(); 190 auto I = Ctx.pImpl->ValueNames.find(this); 191 assert(I != Ctx.pImpl->ValueNames.end() && 192 "No name entry found!"); 193 194 return I->second; 195 } 196 197 void Value::setValueName(ValueName *VN) { 198 LLVMContext &Ctx = getContext(); 199 200 assert(HasName == Ctx.pImpl->ValueNames.count(this) && 201 "HasName bit out of sync!"); 202 203 if (!VN) { 204 if (HasName) 205 Ctx.pImpl->ValueNames.erase(this); 206 HasName = false; 207 return; 208 } 209 210 HasName = true; 211 Ctx.pImpl->ValueNames[this] = VN; 212 } 213 214 StringRef Value::getName() const { 215 // Make sure the empty string is still a C string. For historical reasons, 216 // some clients want to call .data() on the result and expect it to be null 217 // terminated. 218 if (!hasName()) 219 return StringRef("", 0); 220 return getValueName()->getKey(); 221 } 222 223 void Value::setNameImpl(const Twine &NewName) { 224 // Fast-path: LLVMContext can be set to strip out non-GlobalValue names 225 if (getContext().shouldDiscardValueNames() && !isa<GlobalValue>(this)) 226 return; 227 228 // Fast path for common IRBuilder case of setName("") when there is no name. 229 if (NewName.isTriviallyEmpty() && !hasName()) 230 return; 231 232 SmallString<256> NameData; 233 StringRef NameRef = NewName.toStringRef(NameData); 234 assert(NameRef.find_first_of(0) == StringRef::npos && 235 "Null bytes are not allowed in names"); 236 237 // Name isn't changing? 238 if (getName() == NameRef) 239 return; 240 241 // Cap the size of non-GlobalValue names. 242 if (NameRef.size() > NonGlobalValueMaxNameSize && !isa<GlobalValue>(this)) 243 NameRef = 244 NameRef.substr(0, std::max(1u, (unsigned)NonGlobalValueMaxNameSize)); 245 246 assert(!getType()->isVoidTy() && "Cannot assign a name to void values!"); 247 248 // Get the symbol table to update for this object. 249 ValueSymbolTable *ST; 250 if (getSymTab(this, ST)) 251 return; // Cannot set a name on this value (e.g. constant). 252 253 if (!ST) { // No symbol table to update? Just do the change. 254 if (NameRef.empty()) { 255 // Free the name for this value. 256 destroyValueName(); 257 return; 258 } 259 260 // NOTE: Could optimize for the case the name is shrinking to not deallocate 261 // then reallocated. 262 destroyValueName(); 263 264 // Create the new name. 265 setValueName(ValueName::Create(NameRef)); 266 getValueName()->setValue(this); 267 return; 268 } 269 270 // NOTE: Could optimize for the case the name is shrinking to not deallocate 271 // then reallocated. 272 if (hasName()) { 273 // Remove old name. 274 ST->removeValueName(getValueName()); 275 destroyValueName(); 276 277 if (NameRef.empty()) 278 return; 279 } 280 281 // Name is changing to something new. 282 setValueName(ST->createValueName(NameRef, this)); 283 } 284 285 void Value::setName(const Twine &NewName) { 286 setNameImpl(NewName); 287 if (Function *F = dyn_cast<Function>(this)) 288 F->recalculateIntrinsicID(); 289 } 290 291 void Value::takeName(Value *V) { 292 ValueSymbolTable *ST = nullptr; 293 // If this value has a name, drop it. 294 if (hasName()) { 295 // Get the symtab this is in. 296 if (getSymTab(this, ST)) { 297 // We can't set a name on this value, but we need to clear V's name if 298 // it has one. 299 if (V->hasName()) V->setName(""); 300 return; // Cannot set a name on this value (e.g. constant). 301 } 302 303 // Remove old name. 304 if (ST) 305 ST->removeValueName(getValueName()); 306 destroyValueName(); 307 } 308 309 // Now we know that this has no name. 310 311 // If V has no name either, we're done. 312 if (!V->hasName()) return; 313 314 // Get this's symtab if we didn't before. 315 if (!ST) { 316 if (getSymTab(this, ST)) { 317 // Clear V's name. 318 V->setName(""); 319 return; // Cannot set a name on this value (e.g. constant). 320 } 321 } 322 323 // Get V's ST, this should always succed, because V has a name. 324 ValueSymbolTable *VST; 325 bool Failure = getSymTab(V, VST); 326 assert(!Failure && "V has a name, so it should have a ST!"); (void)Failure; 327 328 // If these values are both in the same symtab, we can do this very fast. 329 // This works even if both values have no symtab yet. 330 if (ST == VST) { 331 // Take the name! 332 setValueName(V->getValueName()); 333 V->setValueName(nullptr); 334 getValueName()->setValue(this); 335 return; 336 } 337 338 // Otherwise, things are slightly more complex. Remove V's name from VST and 339 // then reinsert it into ST. 340 341 if (VST) 342 VST->removeValueName(V->getValueName()); 343 setValueName(V->getValueName()); 344 V->setValueName(nullptr); 345 getValueName()->setValue(this); 346 347 if (ST) 348 ST->reinsertValue(this); 349 } 350 351 void Value::assertModuleIsMaterializedImpl() const { 352 #ifndef NDEBUG 353 const GlobalValue *GV = dyn_cast<GlobalValue>(this); 354 if (!GV) 355 return; 356 const Module *M = GV->getParent(); 357 if (!M) 358 return; 359 assert(M->isMaterialized()); 360 #endif 361 } 362 363 #ifndef NDEBUG 364 static bool contains(SmallPtrSetImpl<ConstantExpr *> &Cache, ConstantExpr *Expr, 365 Constant *C) { 366 if (!Cache.insert(Expr).second) 367 return false; 368 369 for (auto &O : Expr->operands()) { 370 if (O == C) 371 return true; 372 auto *CE = dyn_cast<ConstantExpr>(O); 373 if (!CE) 374 continue; 375 if (contains(Cache, CE, C)) 376 return true; 377 } 378 return false; 379 } 380 381 static bool contains(Value *Expr, Value *V) { 382 if (Expr == V) 383 return true; 384 385 auto *C = dyn_cast<Constant>(V); 386 if (!C) 387 return false; 388 389 auto *CE = dyn_cast<ConstantExpr>(Expr); 390 if (!CE) 391 return false; 392 393 SmallPtrSet<ConstantExpr *, 4> Cache; 394 return contains(Cache, CE, C); 395 } 396 #endif // NDEBUG 397 398 void Value::doRAUW(Value *New, ReplaceMetadataUses ReplaceMetaUses) { 399 assert(New && "Value::replaceAllUsesWith(<null>) is invalid!"); 400 assert(!contains(New, this) && 401 "this->replaceAllUsesWith(expr(this)) is NOT valid!"); 402 assert(New->getType() == getType() && 403 "replaceAllUses of value with new value of different type!"); 404 405 // Notify all ValueHandles (if present) that this value is going away. 406 if (HasValueHandle) 407 ValueHandleBase::ValueIsRAUWd(this, New); 408 if (ReplaceMetaUses == ReplaceMetadataUses::Yes && isUsedByMetadata()) 409 ValueAsMetadata::handleRAUW(this, New); 410 411 while (!materialized_use_empty()) { 412 Use &U = *UseList; 413 // Must handle Constants specially, we cannot call replaceUsesOfWith on a 414 // constant because they are uniqued. 415 if (auto *C = dyn_cast<Constant>(U.getUser())) { 416 if (!isa<GlobalValue>(C)) { 417 C->handleOperandChange(this, New); 418 continue; 419 } 420 } 421 422 U.set(New); 423 } 424 425 if (BasicBlock *BB = dyn_cast<BasicBlock>(this)) 426 BB->replaceSuccessorsPhiUsesWith(cast<BasicBlock>(New)); 427 } 428 429 void Value::replaceAllUsesWith(Value *New) { 430 doRAUW(New, ReplaceMetadataUses::Yes); 431 } 432 433 void Value::replaceNonMetadataUsesWith(Value *New) { 434 doRAUW(New, ReplaceMetadataUses::No); 435 } 436 437 // Like replaceAllUsesWith except it does not handle constants or basic blocks. 438 // This routine leaves uses within BB. 439 void Value::replaceUsesOutsideBlock(Value *New, BasicBlock *BB) { 440 assert(New && "Value::replaceUsesOutsideBlock(<null>, BB) is invalid!"); 441 assert(!contains(New, this) && 442 "this->replaceUsesOutsideBlock(expr(this), BB) is NOT valid!"); 443 assert(New->getType() == getType() && 444 "replaceUses of value with new value of different type!"); 445 assert(BB && "Basic block that may contain a use of 'New' must be defined\n"); 446 447 replaceUsesWithIf(New, [BB](Use &U) { 448 auto *I = dyn_cast<Instruction>(U.getUser()); 449 // Don't replace if it's an instruction in the BB basic block. 450 return !I || I->getParent() != BB; 451 }); 452 } 453 454 namespace { 455 // Various metrics for how much to strip off of pointers. 456 enum PointerStripKind { 457 PSK_ZeroIndices, 458 PSK_ZeroIndicesSameRepresentation, 459 PSK_ZeroIndicesAndInvariantGroups, 460 PSK_InBoundsConstantIndices, 461 PSK_InBounds 462 }; 463 464 template <PointerStripKind StripKind> 465 static const Value *stripPointerCastsAndOffsets(const Value *V) { 466 if (!V->getType()->isPointerTy()) 467 return V; 468 469 // Even though we don't look through PHI nodes, we could be called on an 470 // instruction in an unreachable block, which may be on a cycle. 471 SmallPtrSet<const Value *, 4> Visited; 472 473 Visited.insert(V); 474 do { 475 if (auto *GEP = dyn_cast<GEPOperator>(V)) { 476 switch (StripKind) { 477 case PSK_ZeroIndices: 478 case PSK_ZeroIndicesSameRepresentation: 479 case PSK_ZeroIndicesAndInvariantGroups: 480 if (!GEP->hasAllZeroIndices()) 481 return V; 482 break; 483 case PSK_InBoundsConstantIndices: 484 if (!GEP->hasAllConstantIndices()) 485 return V; 486 LLVM_FALLTHROUGH; 487 case PSK_InBounds: 488 if (!GEP->isInBounds()) 489 return V; 490 break; 491 } 492 V = GEP->getPointerOperand(); 493 } else if (Operator::getOpcode(V) == Instruction::BitCast) { 494 V = cast<Operator>(V)->getOperand(0); 495 } else if (StripKind != PSK_ZeroIndicesSameRepresentation && 496 Operator::getOpcode(V) == Instruction::AddrSpaceCast) { 497 // TODO: If we know an address space cast will not change the 498 // representation we could look through it here as well. 499 V = cast<Operator>(V)->getOperand(0); 500 } else { 501 if (const auto *Call = dyn_cast<CallBase>(V)) { 502 if (const Value *RV = Call->getReturnedArgOperand()) { 503 V = RV; 504 continue; 505 } 506 // The result of launder.invariant.group must alias it's argument, 507 // but it can't be marked with returned attribute, that's why it needs 508 // special case. 509 if (StripKind == PSK_ZeroIndicesAndInvariantGroups && 510 (Call->getIntrinsicID() == Intrinsic::launder_invariant_group || 511 Call->getIntrinsicID() == Intrinsic::strip_invariant_group)) { 512 V = Call->getArgOperand(0); 513 continue; 514 } 515 } 516 return V; 517 } 518 assert(V->getType()->isPointerTy() && "Unexpected operand type!"); 519 } while (Visited.insert(V).second); 520 521 return V; 522 } 523 } // end anonymous namespace 524 525 const Value *Value::stripPointerCasts() const { 526 return stripPointerCastsAndOffsets<PSK_ZeroIndices>(this); 527 } 528 529 const Value *Value::stripPointerCastsSameRepresentation() const { 530 return stripPointerCastsAndOffsets<PSK_ZeroIndicesSameRepresentation>(this); 531 } 532 533 const Value *Value::stripInBoundsConstantOffsets() const { 534 return stripPointerCastsAndOffsets<PSK_InBoundsConstantIndices>(this); 535 } 536 537 const Value *Value::stripPointerCastsAndInvariantGroups() const { 538 return stripPointerCastsAndOffsets<PSK_ZeroIndicesAndInvariantGroups>(this); 539 } 540 541 const Value * 542 Value::stripAndAccumulateConstantOffsets(const DataLayout &DL, APInt &Offset, 543 bool AllowNonInbounds) const { 544 if (!getType()->isPtrOrPtrVectorTy()) 545 return this; 546 547 unsigned BitWidth = Offset.getBitWidth(); 548 assert(BitWidth == DL.getIndexTypeSizeInBits(getType()) && 549 "The offset bit width does not match the DL specification."); 550 551 // Even though we don't look through PHI nodes, we could be called on an 552 // instruction in an unreachable block, which may be on a cycle. 553 SmallPtrSet<const Value *, 4> Visited; 554 Visited.insert(this); 555 const Value *V = this; 556 do { 557 if (auto *GEP = dyn_cast<GEPOperator>(V)) { 558 // If in-bounds was requested, we do not strip non-in-bounds GEPs. 559 if (!AllowNonInbounds && !GEP->isInBounds()) 560 return V; 561 562 // If one of the values we have visited is an addrspacecast, then 563 // the pointer type of this GEP may be different from the type 564 // of the Ptr parameter which was passed to this function. This 565 // means when we construct GEPOffset, we need to use the size 566 // of GEP's pointer type rather than the size of the original 567 // pointer type. 568 APInt GEPOffset(DL.getIndexTypeSizeInBits(V->getType()), 0); 569 if (!GEP->accumulateConstantOffset(DL, GEPOffset)) 570 return V; 571 572 // Stop traversal if the pointer offset wouldn't fit in the bit-width 573 // provided by the Offset argument. This can happen due to AddrSpaceCast 574 // stripping. 575 if (GEPOffset.getMinSignedBits() > BitWidth) 576 return V; 577 578 Offset += GEPOffset.sextOrTrunc(BitWidth); 579 V = GEP->getPointerOperand(); 580 } else if (Operator::getOpcode(V) == Instruction::BitCast || 581 Operator::getOpcode(V) == Instruction::AddrSpaceCast) { 582 V = cast<Operator>(V)->getOperand(0); 583 } else if (auto *GA = dyn_cast<GlobalAlias>(V)) { 584 if (!GA->isInterposable()) 585 V = GA->getAliasee(); 586 } else if (const auto *Call = dyn_cast<CallBase>(V)) { 587 if (const Value *RV = Call->getReturnedArgOperand()) 588 V = RV; 589 } 590 assert(V->getType()->isPtrOrPtrVectorTy() && "Unexpected operand type!"); 591 } while (Visited.insert(V).second); 592 593 return V; 594 } 595 596 const Value *Value::stripInBoundsOffsets() const { 597 return stripPointerCastsAndOffsets<PSK_InBounds>(this); 598 } 599 600 uint64_t Value::getPointerDereferenceableBytes(const DataLayout &DL, 601 bool &CanBeNull) const { 602 assert(getType()->isPointerTy() && "must be pointer"); 603 604 uint64_t DerefBytes = 0; 605 CanBeNull = false; 606 if (const Argument *A = dyn_cast<Argument>(this)) { 607 DerefBytes = A->getDereferenceableBytes(); 608 if (DerefBytes == 0 && (A->hasByValAttr() || A->hasStructRetAttr())) { 609 Type *PT = cast<PointerType>(A->getType())->getElementType(); 610 if (PT->isSized()) 611 DerefBytes = DL.getTypeStoreSize(PT); 612 } 613 if (DerefBytes == 0) { 614 DerefBytes = A->getDereferenceableOrNullBytes(); 615 CanBeNull = true; 616 } 617 } else if (const auto *Call = dyn_cast<CallBase>(this)) { 618 DerefBytes = Call->getDereferenceableBytes(AttributeList::ReturnIndex); 619 if (DerefBytes == 0) { 620 DerefBytes = 621 Call->getDereferenceableOrNullBytes(AttributeList::ReturnIndex); 622 CanBeNull = true; 623 } 624 } else if (const LoadInst *LI = dyn_cast<LoadInst>(this)) { 625 if (MDNode *MD = LI->getMetadata(LLVMContext::MD_dereferenceable)) { 626 ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(0)); 627 DerefBytes = CI->getLimitedValue(); 628 } 629 if (DerefBytes == 0) { 630 if (MDNode *MD = 631 LI->getMetadata(LLVMContext::MD_dereferenceable_or_null)) { 632 ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(0)); 633 DerefBytes = CI->getLimitedValue(); 634 } 635 CanBeNull = true; 636 } 637 } else if (auto *IP = dyn_cast<IntToPtrInst>(this)) { 638 if (MDNode *MD = IP->getMetadata(LLVMContext::MD_dereferenceable)) { 639 ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(0)); 640 DerefBytes = CI->getLimitedValue(); 641 } 642 if (DerefBytes == 0) { 643 if (MDNode *MD = 644 IP->getMetadata(LLVMContext::MD_dereferenceable_or_null)) { 645 ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(0)); 646 DerefBytes = CI->getLimitedValue(); 647 } 648 CanBeNull = true; 649 } 650 } else if (auto *AI = dyn_cast<AllocaInst>(this)) { 651 if (!AI->isArrayAllocation()) { 652 DerefBytes = DL.getTypeStoreSize(AI->getAllocatedType()); 653 CanBeNull = false; 654 } 655 } else if (auto *GV = dyn_cast<GlobalVariable>(this)) { 656 if (GV->getValueType()->isSized() && !GV->hasExternalWeakLinkage()) { 657 // TODO: Don't outright reject hasExternalWeakLinkage but set the 658 // CanBeNull flag. 659 DerefBytes = DL.getTypeStoreSize(GV->getValueType()); 660 CanBeNull = false; 661 } 662 } 663 return DerefBytes; 664 } 665 666 unsigned Value::getPointerAlignment(const DataLayout &DL) const { 667 assert(getType()->isPointerTy() && "must be pointer"); 668 669 unsigned Align = 0; 670 if (auto *GO = dyn_cast<GlobalObject>(this)) { 671 if (isa<Function>(GO)) { 672 MaybeAlign FunctionPtrAlign = DL.getFunctionPtrAlign(); 673 unsigned Align = FunctionPtrAlign ? FunctionPtrAlign->value() : 0; 674 switch (DL.getFunctionPtrAlignType()) { 675 case DataLayout::FunctionPtrAlignType::Independent: 676 return Align; 677 case DataLayout::FunctionPtrAlignType::MultipleOfFunctionAlign: 678 return std::max(Align, GO->getAlignment()); 679 } 680 } 681 Align = GO->getAlignment(); 682 if (Align == 0) { 683 if (auto *GVar = dyn_cast<GlobalVariable>(GO)) { 684 Type *ObjectType = GVar->getValueType(); 685 if (ObjectType->isSized()) { 686 // If the object is defined in the current Module, we'll be giving 687 // it the preferred alignment. Otherwise, we have to assume that it 688 // may only have the minimum ABI alignment. 689 if (GVar->isStrongDefinitionForLinker()) 690 Align = DL.getPreferredAlignment(GVar); 691 else 692 Align = DL.getABITypeAlignment(ObjectType); 693 } 694 } 695 } 696 } else if (const Argument *A = dyn_cast<Argument>(this)) { 697 Align = A->getParamAlignment(); 698 699 if (!Align && A->hasStructRetAttr()) { 700 // An sret parameter has at least the ABI alignment of the return type. 701 Type *EltTy = cast<PointerType>(A->getType())->getElementType(); 702 if (EltTy->isSized()) 703 Align = DL.getABITypeAlignment(EltTy); 704 } 705 } else if (const AllocaInst *AI = dyn_cast<AllocaInst>(this)) { 706 Align = AI->getAlignment(); 707 if (Align == 0) { 708 Type *AllocatedType = AI->getAllocatedType(); 709 if (AllocatedType->isSized()) 710 Align = DL.getPrefTypeAlignment(AllocatedType); 711 } 712 } else if (const auto *Call = dyn_cast<CallBase>(this)) { 713 Align = Call->getRetAlignment(); 714 if (Align == 0 && Call->getCalledFunction()) 715 Align = Call->getCalledFunction()->getAttributes().getRetAlignment(); 716 } else if (const LoadInst *LI = dyn_cast<LoadInst>(this)) 717 if (MDNode *MD = LI->getMetadata(LLVMContext::MD_align)) { 718 ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(0)); 719 Align = CI->getLimitedValue(); 720 } 721 722 return Align; 723 } 724 725 const Value *Value::DoPHITranslation(const BasicBlock *CurBB, 726 const BasicBlock *PredBB) const { 727 auto *PN = dyn_cast<PHINode>(this); 728 if (PN && PN->getParent() == CurBB) 729 return PN->getIncomingValueForBlock(PredBB); 730 return this; 731 } 732 733 LLVMContext &Value::getContext() const { return VTy->getContext(); } 734 735 void Value::reverseUseList() { 736 if (!UseList || !UseList->Next) 737 // No need to reverse 0 or 1 uses. 738 return; 739 740 Use *Head = UseList; 741 Use *Current = UseList->Next; 742 Head->Next = nullptr; 743 while (Current) { 744 Use *Next = Current->Next; 745 Current->Next = Head; 746 Head->setPrev(&Current->Next); 747 Head = Current; 748 Current = Next; 749 } 750 UseList = Head; 751 Head->setPrev(&UseList); 752 } 753 754 bool Value::isSwiftError() const { 755 auto *Arg = dyn_cast<Argument>(this); 756 if (Arg) 757 return Arg->hasSwiftErrorAttr(); 758 auto *Alloca = dyn_cast<AllocaInst>(this); 759 if (!Alloca) 760 return false; 761 return Alloca->isSwiftError(); 762 } 763 764 //===----------------------------------------------------------------------===// 765 // ValueHandleBase Class 766 //===----------------------------------------------------------------------===// 767 768 void ValueHandleBase::AddToExistingUseList(ValueHandleBase **List) { 769 assert(List && "Handle list is null?"); 770 771 // Splice ourselves into the list. 772 Next = *List; 773 *List = this; 774 setPrevPtr(List); 775 if (Next) { 776 Next->setPrevPtr(&Next); 777 assert(getValPtr() == Next->getValPtr() && "Added to wrong list?"); 778 } 779 } 780 781 void ValueHandleBase::AddToExistingUseListAfter(ValueHandleBase *List) { 782 assert(List && "Must insert after existing node"); 783 784 Next = List->Next; 785 setPrevPtr(&List->Next); 786 List->Next = this; 787 if (Next) 788 Next->setPrevPtr(&Next); 789 } 790 791 void ValueHandleBase::AddToUseList() { 792 assert(getValPtr() && "Null pointer doesn't have a use list!"); 793 794 LLVMContextImpl *pImpl = getValPtr()->getContext().pImpl; 795 796 if (getValPtr()->HasValueHandle) { 797 // If this value already has a ValueHandle, then it must be in the 798 // ValueHandles map already. 799 ValueHandleBase *&Entry = pImpl->ValueHandles[getValPtr()]; 800 assert(Entry && "Value doesn't have any handles?"); 801 AddToExistingUseList(&Entry); 802 return; 803 } 804 805 // Ok, it doesn't have any handles yet, so we must insert it into the 806 // DenseMap. However, doing this insertion could cause the DenseMap to 807 // reallocate itself, which would invalidate all of the PrevP pointers that 808 // point into the old table. Handle this by checking for reallocation and 809 // updating the stale pointers only if needed. 810 DenseMap<Value*, ValueHandleBase*> &Handles = pImpl->ValueHandles; 811 const void *OldBucketPtr = Handles.getPointerIntoBucketsArray(); 812 813 ValueHandleBase *&Entry = Handles[getValPtr()]; 814 assert(!Entry && "Value really did already have handles?"); 815 AddToExistingUseList(&Entry); 816 getValPtr()->HasValueHandle = true; 817 818 // If reallocation didn't happen or if this was the first insertion, don't 819 // walk the table. 820 if (Handles.isPointerIntoBucketsArray(OldBucketPtr) || 821 Handles.size() == 1) { 822 return; 823 } 824 825 // Okay, reallocation did happen. Fix the Prev Pointers. 826 for (DenseMap<Value*, ValueHandleBase*>::iterator I = Handles.begin(), 827 E = Handles.end(); I != E; ++I) { 828 assert(I->second && I->first == I->second->getValPtr() && 829 "List invariant broken!"); 830 I->second->setPrevPtr(&I->second); 831 } 832 } 833 834 void ValueHandleBase::RemoveFromUseList() { 835 assert(getValPtr() && getValPtr()->HasValueHandle && 836 "Pointer doesn't have a use list!"); 837 838 // Unlink this from its use list. 839 ValueHandleBase **PrevPtr = getPrevPtr(); 840 assert(*PrevPtr == this && "List invariant broken"); 841 842 *PrevPtr = Next; 843 if (Next) { 844 assert(Next->getPrevPtr() == &Next && "List invariant broken"); 845 Next->setPrevPtr(PrevPtr); 846 return; 847 } 848 849 // If the Next pointer was null, then it is possible that this was the last 850 // ValueHandle watching VP. If so, delete its entry from the ValueHandles 851 // map. 852 LLVMContextImpl *pImpl = getValPtr()->getContext().pImpl; 853 DenseMap<Value*, ValueHandleBase*> &Handles = pImpl->ValueHandles; 854 if (Handles.isPointerIntoBucketsArray(PrevPtr)) { 855 Handles.erase(getValPtr()); 856 getValPtr()->HasValueHandle = false; 857 } 858 } 859 860 void ValueHandleBase::ValueIsDeleted(Value *V) { 861 assert(V->HasValueHandle && "Should only be called if ValueHandles present"); 862 863 // Get the linked list base, which is guaranteed to exist since the 864 // HasValueHandle flag is set. 865 LLVMContextImpl *pImpl = V->getContext().pImpl; 866 ValueHandleBase *Entry = pImpl->ValueHandles[V]; 867 assert(Entry && "Value bit set but no entries exist"); 868 869 // We use a local ValueHandleBase as an iterator so that ValueHandles can add 870 // and remove themselves from the list without breaking our iteration. This 871 // is not really an AssertingVH; we just have to give ValueHandleBase a kind. 872 // Note that we deliberately do not the support the case when dropping a value 873 // handle results in a new value handle being permanently added to the list 874 // (as might occur in theory for CallbackVH's): the new value handle will not 875 // be processed and the checking code will mete out righteous punishment if 876 // the handle is still present once we have finished processing all the other 877 // value handles (it is fine to momentarily add then remove a value handle). 878 for (ValueHandleBase Iterator(Assert, *Entry); Entry; Entry = Iterator.Next) { 879 Iterator.RemoveFromUseList(); 880 Iterator.AddToExistingUseListAfter(Entry); 881 assert(Entry->Next == &Iterator && "Loop invariant broken."); 882 883 switch (Entry->getKind()) { 884 case Assert: 885 break; 886 case Weak: 887 case WeakTracking: 888 // WeakTracking and Weak just go to null, which unlinks them 889 // from the list. 890 Entry->operator=(nullptr); 891 break; 892 case Callback: 893 // Forward to the subclass's implementation. 894 static_cast<CallbackVH*>(Entry)->deleted(); 895 break; 896 } 897 } 898 899 // All callbacks, weak references, and assertingVHs should be dropped by now. 900 if (V->HasValueHandle) { 901 #ifndef NDEBUG // Only in +Asserts mode... 902 dbgs() << "While deleting: " << *V->getType() << " %" << V->getName() 903 << "\n"; 904 if (pImpl->ValueHandles[V]->getKind() == Assert) 905 llvm_unreachable("An asserting value handle still pointed to this" 906 " value!"); 907 908 #endif 909 llvm_unreachable("All references to V were not removed?"); 910 } 911 } 912 913 void ValueHandleBase::ValueIsRAUWd(Value *Old, Value *New) { 914 assert(Old->HasValueHandle &&"Should only be called if ValueHandles present"); 915 assert(Old != New && "Changing value into itself!"); 916 assert(Old->getType() == New->getType() && 917 "replaceAllUses of value with new value of different type!"); 918 919 // Get the linked list base, which is guaranteed to exist since the 920 // HasValueHandle flag is set. 921 LLVMContextImpl *pImpl = Old->getContext().pImpl; 922 ValueHandleBase *Entry = pImpl->ValueHandles[Old]; 923 924 assert(Entry && "Value bit set but no entries exist"); 925 926 // We use a local ValueHandleBase as an iterator so that 927 // ValueHandles can add and remove themselves from the list without 928 // breaking our iteration. This is not really an AssertingVH; we 929 // just have to give ValueHandleBase some kind. 930 for (ValueHandleBase Iterator(Assert, *Entry); Entry; Entry = Iterator.Next) { 931 Iterator.RemoveFromUseList(); 932 Iterator.AddToExistingUseListAfter(Entry); 933 assert(Entry->Next == &Iterator && "Loop invariant broken."); 934 935 switch (Entry->getKind()) { 936 case Assert: 937 case Weak: 938 // Asserting and Weak handles do not follow RAUW implicitly. 939 break; 940 case WeakTracking: 941 // Weak goes to the new value, which will unlink it from Old's list. 942 Entry->operator=(New); 943 break; 944 case Callback: 945 // Forward to the subclass's implementation. 946 static_cast<CallbackVH*>(Entry)->allUsesReplacedWith(New); 947 break; 948 } 949 } 950 951 #ifndef NDEBUG 952 // If any new weak value handles were added while processing the 953 // list, then complain about it now. 954 if (Old->HasValueHandle) 955 for (Entry = pImpl->ValueHandles[Old]; Entry; Entry = Entry->Next) 956 switch (Entry->getKind()) { 957 case WeakTracking: 958 dbgs() << "After RAUW from " << *Old->getType() << " %" 959 << Old->getName() << " to " << *New->getType() << " %" 960 << New->getName() << "\n"; 961 llvm_unreachable( 962 "A weak tracking value handle still pointed to the old value!\n"); 963 default: 964 break; 965 } 966 #endif 967 } 968 969 // Pin the vtable to this file. 970 void CallbackVH::anchor() {} 971