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