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