10b57cec5SDimitry Andric //===-- Value.cpp - Implement the Value class -----------------------------===// 20b57cec5SDimitry Andric // 30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information. 50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 60b57cec5SDimitry Andric // 70b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 80b57cec5SDimitry Andric // 90b57cec5SDimitry Andric // This file implements the Value, ValueHandle, and User classes. 100b57cec5SDimitry Andric // 110b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 120b57cec5SDimitry Andric 130b57cec5SDimitry Andric #include "llvm/IR/Value.h" 140b57cec5SDimitry Andric #include "LLVMContextImpl.h" 150b57cec5SDimitry Andric #include "llvm/ADT/DenseMap.h" 16480093f4SDimitry Andric #include "llvm/ADT/SmallString.h" 170b57cec5SDimitry Andric #include "llvm/IR/Constant.h" 180b57cec5SDimitry Andric #include "llvm/IR/Constants.h" 190b57cec5SDimitry Andric #include "llvm/IR/DataLayout.h" 20fe6060f1SDimitry Andric #include "llvm/IR/DebugInfo.h" 210b57cec5SDimitry Andric #include "llvm/IR/DerivedTypes.h" 220b57cec5SDimitry Andric #include "llvm/IR/DerivedUser.h" 230b57cec5SDimitry Andric #include "llvm/IR/InstrTypes.h" 240b57cec5SDimitry Andric #include "llvm/IR/Instructions.h" 250b57cec5SDimitry Andric #include "llvm/IR/IntrinsicInst.h" 260b57cec5SDimitry Andric #include "llvm/IR/Module.h" 270b57cec5SDimitry Andric #include "llvm/IR/Operator.h" 280b57cec5SDimitry Andric #include "llvm/IR/ValueHandle.h" 290b57cec5SDimitry Andric #include "llvm/IR/ValueSymbolTable.h" 30480093f4SDimitry Andric #include "llvm/Support/CommandLine.h" 310b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h" 320b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h" 330b57cec5SDimitry Andric #include <algorithm> 340b57cec5SDimitry Andric 350b57cec5SDimitry Andric using namespace llvm; 360b57cec5SDimitry Andric 37fe6060f1SDimitry Andric static cl::opt<unsigned> UseDerefAtPointSemantics( 38fe6060f1SDimitry Andric "use-dereferenceable-at-point-semantics", cl::Hidden, cl::init(false), 39fe6060f1SDimitry Andric cl::desc("Deref attributes and metadata infer facts at definition only")); 400b57cec5SDimitry Andric 410b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 420b57cec5SDimitry Andric // Value Class 430b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 440b57cec5SDimitry Andric static inline Type *checkType(Type *Ty) { 450b57cec5SDimitry Andric assert(Ty && "Value defined with a null type: Error!"); 460b57cec5SDimitry Andric return Ty; 470b57cec5SDimitry Andric } 480b57cec5SDimitry Andric 490b57cec5SDimitry Andric Value::Value(Type *ty, unsigned scid) 50e8d8bef9SDimitry Andric : VTy(checkType(ty)), UseList(nullptr), SubclassID(scid), HasValueHandle(0), 51e8d8bef9SDimitry Andric SubclassOptionalData(0), SubclassData(0), NumUserOperands(0), 52e8d8bef9SDimitry Andric IsUsedByMD(false), HasName(false), HasMetadata(false) { 530b57cec5SDimitry Andric static_assert(ConstantFirstVal == 0, "!(SubclassID < ConstantFirstVal)"); 540b57cec5SDimitry Andric // FIXME: Why isn't this in the subclass gunk?? 550b57cec5SDimitry Andric // Note, we cannot call isa<CallInst> before the CallInst has been 560b57cec5SDimitry Andric // constructed. 57fe6060f1SDimitry Andric unsigned OpCode = 0; 58fe6060f1SDimitry Andric if (SubclassID >= InstructionVal) 59fe6060f1SDimitry Andric OpCode = SubclassID - InstructionVal; 60fe6060f1SDimitry Andric if (OpCode == Instruction::Call || OpCode == Instruction::Invoke || 61fe6060f1SDimitry Andric OpCode == Instruction::CallBr) 620b57cec5SDimitry Andric assert((VTy->isFirstClassType() || VTy->isVoidTy() || VTy->isStructTy()) && 63fe6060f1SDimitry Andric "invalid CallBase type!"); 640b57cec5SDimitry Andric else if (SubclassID != BasicBlockVal && 650b57cec5SDimitry Andric (/*SubclassID < ConstantFirstVal ||*/ SubclassID > ConstantLastVal)) 660b57cec5SDimitry Andric assert((VTy->isFirstClassType() || VTy->isVoidTy()) && 670b57cec5SDimitry Andric "Cannot create non-first-class values except for constants!"); 680b57cec5SDimitry Andric static_assert(sizeof(Value) == 2 * sizeof(void *) + 2 * sizeof(unsigned), 690b57cec5SDimitry Andric "Value too big"); 700b57cec5SDimitry Andric } 710b57cec5SDimitry Andric 720b57cec5SDimitry Andric Value::~Value() { 730b57cec5SDimitry Andric // Notify all ValueHandles (if present) that this value is going away. 740b57cec5SDimitry Andric if (HasValueHandle) 750b57cec5SDimitry Andric ValueHandleBase::ValueIsDeleted(this); 760b57cec5SDimitry Andric if (isUsedByMetadata()) 770b57cec5SDimitry Andric ValueAsMetadata::handleDeletion(this); 780b57cec5SDimitry Andric 79e8d8bef9SDimitry Andric // Remove associated metadata from context. 80e8d8bef9SDimitry Andric if (HasMetadata) 81e8d8bef9SDimitry Andric clearMetadata(); 82e8d8bef9SDimitry Andric 830b57cec5SDimitry Andric #ifndef NDEBUG // Only in -g mode... 840b57cec5SDimitry Andric // Check to make sure that there are no uses of this value that are still 850b57cec5SDimitry Andric // around when the value is destroyed. If there are, then we have a dangling 860b57cec5SDimitry Andric // reference and something is wrong. This code is here to print out where 870b57cec5SDimitry Andric // the value is still being referenced. 880b57cec5SDimitry Andric // 895ffd83dbSDimitry Andric // Note that use_empty() cannot be called here, as it eventually downcasts 905ffd83dbSDimitry Andric // 'this' to GlobalValue (derived class of Value), but GlobalValue has already 915ffd83dbSDimitry Andric // been destructed, so accessing it is UB. 925ffd83dbSDimitry Andric // 935ffd83dbSDimitry Andric if (!materialized_use_empty()) { 940b57cec5SDimitry Andric dbgs() << "While deleting: " << *VTy << " %" << getName() << "\n"; 950b57cec5SDimitry Andric for (auto *U : users()) 960b57cec5SDimitry Andric dbgs() << "Use still stuck around after Def is destroyed:" << *U << "\n"; 970b57cec5SDimitry Andric } 980b57cec5SDimitry Andric #endif 995ffd83dbSDimitry Andric assert(materialized_use_empty() && "Uses remain when a value is destroyed!"); 1000b57cec5SDimitry Andric 1010b57cec5SDimitry Andric // If this value is named, destroy the name. This should not be in a symtab 1020b57cec5SDimitry Andric // at this point. 1030b57cec5SDimitry Andric destroyValueName(); 1040b57cec5SDimitry Andric } 1050b57cec5SDimitry Andric 1060b57cec5SDimitry Andric void Value::deleteValue() { 1070b57cec5SDimitry Andric switch (getValueID()) { 1080b57cec5SDimitry Andric #define HANDLE_VALUE(Name) \ 1090b57cec5SDimitry Andric case Value::Name##Val: \ 1100b57cec5SDimitry Andric delete static_cast<Name *>(this); \ 1110b57cec5SDimitry Andric break; 1120b57cec5SDimitry Andric #define HANDLE_MEMORY_VALUE(Name) \ 1130b57cec5SDimitry Andric case Value::Name##Val: \ 1140b57cec5SDimitry Andric static_cast<DerivedUser *>(this)->DeleteValue( \ 1150b57cec5SDimitry Andric static_cast<DerivedUser *>(this)); \ 1160b57cec5SDimitry Andric break; 1175ffd83dbSDimitry Andric #define HANDLE_CONSTANT(Name) \ 1185ffd83dbSDimitry Andric case Value::Name##Val: \ 1195ffd83dbSDimitry Andric llvm_unreachable("constants should be destroyed with destroyConstant"); \ 1205ffd83dbSDimitry Andric break; 1210b57cec5SDimitry Andric #define HANDLE_INSTRUCTION(Name) /* nothing */ 1220b57cec5SDimitry Andric #include "llvm/IR/Value.def" 1230b57cec5SDimitry Andric 1240b57cec5SDimitry Andric #define HANDLE_INST(N, OPC, CLASS) \ 1250b57cec5SDimitry Andric case Value::InstructionVal + Instruction::OPC: \ 1260b57cec5SDimitry Andric delete static_cast<CLASS *>(this); \ 1270b57cec5SDimitry Andric break; 1280b57cec5SDimitry Andric #define HANDLE_USER_INST(N, OPC, CLASS) 1290b57cec5SDimitry Andric #include "llvm/IR/Instruction.def" 1300b57cec5SDimitry Andric 1310b57cec5SDimitry Andric default: 1320b57cec5SDimitry Andric llvm_unreachable("attempting to delete unknown value kind"); 1330b57cec5SDimitry Andric } 1340b57cec5SDimitry Andric } 1350b57cec5SDimitry Andric 1360b57cec5SDimitry Andric void Value::destroyValueName() { 1370b57cec5SDimitry Andric ValueName *Name = getValueName(); 1385ffd83dbSDimitry Andric if (Name) { 1395ffd83dbSDimitry Andric MallocAllocator Allocator; 1405ffd83dbSDimitry Andric Name->Destroy(Allocator); 1415ffd83dbSDimitry Andric } 1420b57cec5SDimitry Andric setValueName(nullptr); 1430b57cec5SDimitry Andric } 1440b57cec5SDimitry Andric 1450b57cec5SDimitry Andric bool Value::hasNUses(unsigned N) const { 1460b57cec5SDimitry Andric return hasNItems(use_begin(), use_end(), N); 1470b57cec5SDimitry Andric } 1480b57cec5SDimitry Andric 1490b57cec5SDimitry Andric bool Value::hasNUsesOrMore(unsigned N) const { 1500b57cec5SDimitry Andric return hasNItemsOrMore(use_begin(), use_end(), N); 1510b57cec5SDimitry Andric } 1520b57cec5SDimitry Andric 153e8d8bef9SDimitry Andric bool Value::hasOneUser() const { 154e8d8bef9SDimitry Andric if (use_empty()) 155e8d8bef9SDimitry Andric return false; 156e8d8bef9SDimitry Andric if (hasOneUse()) 157e8d8bef9SDimitry Andric return true; 158e8d8bef9SDimitry Andric return std::equal(++user_begin(), user_end(), user_begin()); 159e8d8bef9SDimitry Andric } 160e8d8bef9SDimitry Andric 1615ffd83dbSDimitry Andric static bool isUnDroppableUser(const User *U) { return !U->isDroppable(); } 1625ffd83dbSDimitry Andric 1635ffd83dbSDimitry Andric Use *Value::getSingleUndroppableUse() { 1645ffd83dbSDimitry Andric Use *Result = nullptr; 1655ffd83dbSDimitry Andric for (Use &U : uses()) { 1665ffd83dbSDimitry Andric if (!U.getUser()->isDroppable()) { 1675ffd83dbSDimitry Andric if (Result) 1685ffd83dbSDimitry Andric return nullptr; 1695ffd83dbSDimitry Andric Result = &U; 1705ffd83dbSDimitry Andric } 1715ffd83dbSDimitry Andric } 1725ffd83dbSDimitry Andric return Result; 1735ffd83dbSDimitry Andric } 1745ffd83dbSDimitry Andric 175349cc55cSDimitry Andric User *Value::getUniqueUndroppableUser() { 176349cc55cSDimitry Andric User *Result = nullptr; 177349cc55cSDimitry Andric for (auto *U : users()) { 178349cc55cSDimitry Andric if (!U->isDroppable()) { 179349cc55cSDimitry Andric if (Result && Result != U) 180349cc55cSDimitry Andric return nullptr; 181349cc55cSDimitry Andric Result = U; 182349cc55cSDimitry Andric } 183349cc55cSDimitry Andric } 184349cc55cSDimitry Andric return Result; 185349cc55cSDimitry Andric } 186349cc55cSDimitry Andric 1875ffd83dbSDimitry Andric bool Value::hasNUndroppableUses(unsigned int N) const { 1885ffd83dbSDimitry Andric return hasNItems(user_begin(), user_end(), N, isUnDroppableUser); 1895ffd83dbSDimitry Andric } 1905ffd83dbSDimitry Andric 1915ffd83dbSDimitry Andric bool Value::hasNUndroppableUsesOrMore(unsigned int N) const { 1925ffd83dbSDimitry Andric return hasNItemsOrMore(user_begin(), user_end(), N, isUnDroppableUser); 1935ffd83dbSDimitry Andric } 1945ffd83dbSDimitry Andric 1955ffd83dbSDimitry Andric void Value::dropDroppableUses( 1965ffd83dbSDimitry Andric llvm::function_ref<bool(const Use *)> ShouldDrop) { 1975ffd83dbSDimitry Andric SmallVector<Use *, 8> ToBeEdited; 1985ffd83dbSDimitry Andric for (Use &U : uses()) 1995ffd83dbSDimitry Andric if (U.getUser()->isDroppable() && ShouldDrop(&U)) 2005ffd83dbSDimitry Andric ToBeEdited.push_back(&U); 201e8d8bef9SDimitry Andric for (Use *U : ToBeEdited) 202e8d8bef9SDimitry Andric dropDroppableUse(*U); 203e8d8bef9SDimitry Andric } 204e8d8bef9SDimitry Andric 205e8d8bef9SDimitry Andric void Value::dropDroppableUsesIn(User &Usr) { 206e8d8bef9SDimitry Andric assert(Usr.isDroppable() && "Expected a droppable user!"); 207e8d8bef9SDimitry Andric for (Use &UsrOp : Usr.operands()) { 208e8d8bef9SDimitry Andric if (UsrOp.get() == this) 209e8d8bef9SDimitry Andric dropDroppableUse(UsrOp); 210e8d8bef9SDimitry Andric } 211e8d8bef9SDimitry Andric } 212e8d8bef9SDimitry Andric 213e8d8bef9SDimitry Andric void Value::dropDroppableUse(Use &U) { 214e8d8bef9SDimitry Andric U.removeFromList(); 215fe6060f1SDimitry Andric if (auto *Assume = dyn_cast<AssumeInst>(U.getUser())) { 216e8d8bef9SDimitry Andric unsigned OpNo = U.getOperandNo(); 2175ffd83dbSDimitry Andric if (OpNo == 0) 218e8d8bef9SDimitry Andric U.set(ConstantInt::getTrue(Assume->getContext())); 2195ffd83dbSDimitry Andric else { 220e8d8bef9SDimitry Andric U.set(UndefValue::get(U.get()->getType())); 2215ffd83dbSDimitry Andric CallInst::BundleOpInfo &BOI = Assume->getBundleOpInfoForOperand(OpNo); 222e8d8bef9SDimitry Andric BOI.Tag = Assume->getContext().pImpl->getOrInsertBundleTag("ignore"); 2235ffd83dbSDimitry Andric } 224e8d8bef9SDimitry Andric return; 225e8d8bef9SDimitry Andric } 226e8d8bef9SDimitry Andric 2275ffd83dbSDimitry Andric llvm_unreachable("unkown droppable use"); 2285ffd83dbSDimitry Andric } 2295ffd83dbSDimitry Andric 2300b57cec5SDimitry Andric bool Value::isUsedInBasicBlock(const BasicBlock *BB) const { 2310b57cec5SDimitry Andric // This can be computed either by scanning the instructions in BB, or by 2320b57cec5SDimitry Andric // scanning the use list of this Value. Both lists can be very long, but 2330b57cec5SDimitry Andric // usually one is quite short. 2340b57cec5SDimitry Andric // 2350b57cec5SDimitry Andric // Scan both lists simultaneously until one is exhausted. This limits the 2360b57cec5SDimitry Andric // search to the shorter list. 2370b57cec5SDimitry Andric BasicBlock::const_iterator BI = BB->begin(), BE = BB->end(); 2380b57cec5SDimitry Andric const_user_iterator UI = user_begin(), UE = user_end(); 2390b57cec5SDimitry Andric for (; BI != BE && UI != UE; ++BI, ++UI) { 2400b57cec5SDimitry Andric // Scan basic block: Check if this Value is used by the instruction at BI. 2410b57cec5SDimitry Andric if (is_contained(BI->operands(), this)) 2420b57cec5SDimitry Andric return true; 2430b57cec5SDimitry Andric // Scan use list: Check if the use at UI is in BB. 2440b57cec5SDimitry Andric const auto *User = dyn_cast<Instruction>(*UI); 2450b57cec5SDimitry Andric if (User && User->getParent() == BB) 2460b57cec5SDimitry Andric return true; 2470b57cec5SDimitry Andric } 2480b57cec5SDimitry Andric return false; 2490b57cec5SDimitry Andric } 2500b57cec5SDimitry Andric 2510b57cec5SDimitry Andric unsigned Value::getNumUses() const { 2520b57cec5SDimitry Andric return (unsigned)std::distance(use_begin(), use_end()); 2530b57cec5SDimitry Andric } 2540b57cec5SDimitry Andric 2550b57cec5SDimitry Andric static bool getSymTab(Value *V, ValueSymbolTable *&ST) { 2560b57cec5SDimitry Andric ST = nullptr; 2570b57cec5SDimitry Andric if (Instruction *I = dyn_cast<Instruction>(V)) { 2580b57cec5SDimitry Andric if (BasicBlock *P = I->getParent()) 2590b57cec5SDimitry Andric if (Function *PP = P->getParent()) 2600b57cec5SDimitry Andric ST = PP->getValueSymbolTable(); 2610b57cec5SDimitry Andric } else if (BasicBlock *BB = dyn_cast<BasicBlock>(V)) { 2620b57cec5SDimitry Andric if (Function *P = BB->getParent()) 2630b57cec5SDimitry Andric ST = P->getValueSymbolTable(); 2640b57cec5SDimitry Andric } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) { 2650b57cec5SDimitry Andric if (Module *P = GV->getParent()) 2660b57cec5SDimitry Andric ST = &P->getValueSymbolTable(); 2670b57cec5SDimitry Andric } else if (Argument *A = dyn_cast<Argument>(V)) { 2680b57cec5SDimitry Andric if (Function *P = A->getParent()) 2690b57cec5SDimitry Andric ST = P->getValueSymbolTable(); 2700b57cec5SDimitry Andric } else { 2710b57cec5SDimitry Andric assert(isa<Constant>(V) && "Unknown value type!"); 2720b57cec5SDimitry Andric return true; // no name is setable for this. 2730b57cec5SDimitry Andric } 2740b57cec5SDimitry Andric return false; 2750b57cec5SDimitry Andric } 2760b57cec5SDimitry Andric 2770b57cec5SDimitry Andric ValueName *Value::getValueName() const { 2780b57cec5SDimitry Andric if (!HasName) return nullptr; 2790b57cec5SDimitry Andric 2800b57cec5SDimitry Andric LLVMContext &Ctx = getContext(); 2810b57cec5SDimitry Andric auto I = Ctx.pImpl->ValueNames.find(this); 2820b57cec5SDimitry Andric assert(I != Ctx.pImpl->ValueNames.end() && 2830b57cec5SDimitry Andric "No name entry found!"); 2840b57cec5SDimitry Andric 2850b57cec5SDimitry Andric return I->second; 2860b57cec5SDimitry Andric } 2870b57cec5SDimitry Andric 2880b57cec5SDimitry Andric void Value::setValueName(ValueName *VN) { 2890b57cec5SDimitry Andric LLVMContext &Ctx = getContext(); 2900b57cec5SDimitry Andric 2910b57cec5SDimitry Andric assert(HasName == Ctx.pImpl->ValueNames.count(this) && 2920b57cec5SDimitry Andric "HasName bit out of sync!"); 2930b57cec5SDimitry Andric 2940b57cec5SDimitry Andric if (!VN) { 2950b57cec5SDimitry Andric if (HasName) 2960b57cec5SDimitry Andric Ctx.pImpl->ValueNames.erase(this); 2970b57cec5SDimitry Andric HasName = false; 2980b57cec5SDimitry Andric return; 2990b57cec5SDimitry Andric } 3000b57cec5SDimitry Andric 3010b57cec5SDimitry Andric HasName = true; 3020b57cec5SDimitry Andric Ctx.pImpl->ValueNames[this] = VN; 3030b57cec5SDimitry Andric } 3040b57cec5SDimitry Andric 3050b57cec5SDimitry Andric StringRef Value::getName() const { 3060b57cec5SDimitry Andric // Make sure the empty string is still a C string. For historical reasons, 3070b57cec5SDimitry Andric // some clients want to call .data() on the result and expect it to be null 3080b57cec5SDimitry Andric // terminated. 3090b57cec5SDimitry Andric if (!hasName()) 3100b57cec5SDimitry Andric return StringRef("", 0); 3110b57cec5SDimitry Andric return getValueName()->getKey(); 3120b57cec5SDimitry Andric } 3130b57cec5SDimitry Andric 3140b57cec5SDimitry Andric void Value::setNameImpl(const Twine &NewName) { 3150b57cec5SDimitry Andric // Fast-path: LLVMContext can be set to strip out non-GlobalValue names 3160b57cec5SDimitry Andric if (getContext().shouldDiscardValueNames() && !isa<GlobalValue>(this)) 3170b57cec5SDimitry Andric return; 3180b57cec5SDimitry Andric 3190b57cec5SDimitry Andric // Fast path for common IRBuilder case of setName("") when there is no name. 3200b57cec5SDimitry Andric if (NewName.isTriviallyEmpty() && !hasName()) 3210b57cec5SDimitry Andric return; 3220b57cec5SDimitry Andric 3230b57cec5SDimitry Andric SmallString<256> NameData; 3240b57cec5SDimitry Andric StringRef NameRef = NewName.toStringRef(NameData); 3250b57cec5SDimitry Andric assert(NameRef.find_first_of(0) == StringRef::npos && 3260b57cec5SDimitry Andric "Null bytes are not allowed in names"); 3270b57cec5SDimitry Andric 3280b57cec5SDimitry Andric // Name isn't changing? 3290b57cec5SDimitry Andric if (getName() == NameRef) 3300b57cec5SDimitry Andric return; 3310b57cec5SDimitry Andric 3320b57cec5SDimitry Andric assert(!getType()->isVoidTy() && "Cannot assign a name to void values!"); 3330b57cec5SDimitry Andric 3340b57cec5SDimitry Andric // Get the symbol table to update for this object. 3350b57cec5SDimitry Andric ValueSymbolTable *ST; 3360b57cec5SDimitry Andric if (getSymTab(this, ST)) 3370b57cec5SDimitry Andric return; // Cannot set a name on this value (e.g. constant). 3380b57cec5SDimitry Andric 3390b57cec5SDimitry Andric if (!ST) { // No symbol table to update? Just do the change. 3400b57cec5SDimitry Andric if (NameRef.empty()) { 3410b57cec5SDimitry Andric // Free the name for this value. 3420b57cec5SDimitry Andric destroyValueName(); 3430b57cec5SDimitry Andric return; 3440b57cec5SDimitry Andric } 3450b57cec5SDimitry Andric 3460b57cec5SDimitry Andric // NOTE: Could optimize for the case the name is shrinking to not deallocate 3470b57cec5SDimitry Andric // then reallocated. 3480b57cec5SDimitry Andric destroyValueName(); 3490b57cec5SDimitry Andric 3500b57cec5SDimitry Andric // Create the new name. 3515ffd83dbSDimitry Andric MallocAllocator Allocator; 3525ffd83dbSDimitry Andric setValueName(ValueName::Create(NameRef, Allocator)); 3530b57cec5SDimitry Andric getValueName()->setValue(this); 3540b57cec5SDimitry Andric return; 3550b57cec5SDimitry Andric } 3560b57cec5SDimitry Andric 3570b57cec5SDimitry Andric // NOTE: Could optimize for the case the name is shrinking to not deallocate 3580b57cec5SDimitry Andric // then reallocated. 3590b57cec5SDimitry Andric if (hasName()) { 3600b57cec5SDimitry Andric // Remove old name. 3610b57cec5SDimitry Andric ST->removeValueName(getValueName()); 3620b57cec5SDimitry Andric destroyValueName(); 3630b57cec5SDimitry Andric 3640b57cec5SDimitry Andric if (NameRef.empty()) 3650b57cec5SDimitry Andric return; 3660b57cec5SDimitry Andric } 3670b57cec5SDimitry Andric 3680b57cec5SDimitry Andric // Name is changing to something new. 3690b57cec5SDimitry Andric setValueName(ST->createValueName(NameRef, this)); 3700b57cec5SDimitry Andric } 3710b57cec5SDimitry Andric 3720b57cec5SDimitry Andric void Value::setName(const Twine &NewName) { 3730b57cec5SDimitry Andric setNameImpl(NewName); 3740b57cec5SDimitry Andric if (Function *F = dyn_cast<Function>(this)) 3750b57cec5SDimitry Andric F->recalculateIntrinsicID(); 3760b57cec5SDimitry Andric } 3770b57cec5SDimitry Andric 3780b57cec5SDimitry Andric void Value::takeName(Value *V) { 379*81ad6265SDimitry Andric assert(V != this && "Illegal call to this->takeName(this)!"); 3800b57cec5SDimitry Andric ValueSymbolTable *ST = nullptr; 3810b57cec5SDimitry Andric // If this value has a name, drop it. 3820b57cec5SDimitry Andric if (hasName()) { 3830b57cec5SDimitry Andric // Get the symtab this is in. 3840b57cec5SDimitry Andric if (getSymTab(this, ST)) { 3850b57cec5SDimitry Andric // We can't set a name on this value, but we need to clear V's name if 3860b57cec5SDimitry Andric // it has one. 3870b57cec5SDimitry Andric if (V->hasName()) V->setName(""); 3880b57cec5SDimitry Andric return; // Cannot set a name on this value (e.g. constant). 3890b57cec5SDimitry Andric } 3900b57cec5SDimitry Andric 3910b57cec5SDimitry Andric // Remove old name. 3920b57cec5SDimitry Andric if (ST) 3930b57cec5SDimitry Andric ST->removeValueName(getValueName()); 3940b57cec5SDimitry Andric destroyValueName(); 3950b57cec5SDimitry Andric } 3960b57cec5SDimitry Andric 3970b57cec5SDimitry Andric // Now we know that this has no name. 3980b57cec5SDimitry Andric 3990b57cec5SDimitry Andric // If V has no name either, we're done. 4000b57cec5SDimitry Andric if (!V->hasName()) return; 4010b57cec5SDimitry Andric 4020b57cec5SDimitry Andric // Get this's symtab if we didn't before. 4030b57cec5SDimitry Andric if (!ST) { 4040b57cec5SDimitry Andric if (getSymTab(this, ST)) { 4050b57cec5SDimitry Andric // Clear V's name. 4060b57cec5SDimitry Andric V->setName(""); 4070b57cec5SDimitry Andric return; // Cannot set a name on this value (e.g. constant). 4080b57cec5SDimitry Andric } 4090b57cec5SDimitry Andric } 4100b57cec5SDimitry Andric 411*81ad6265SDimitry Andric // Get V's ST, this should always succeed, because V has a name. 4120b57cec5SDimitry Andric ValueSymbolTable *VST; 4130b57cec5SDimitry Andric bool Failure = getSymTab(V, VST); 4140b57cec5SDimitry Andric assert(!Failure && "V has a name, so it should have a ST!"); (void)Failure; 4150b57cec5SDimitry Andric 4160b57cec5SDimitry Andric // If these values are both in the same symtab, we can do this very fast. 4170b57cec5SDimitry Andric // This works even if both values have no symtab yet. 4180b57cec5SDimitry Andric if (ST == VST) { 4190b57cec5SDimitry Andric // Take the name! 4200b57cec5SDimitry Andric setValueName(V->getValueName()); 4210b57cec5SDimitry Andric V->setValueName(nullptr); 4220b57cec5SDimitry Andric getValueName()->setValue(this); 4230b57cec5SDimitry Andric return; 4240b57cec5SDimitry Andric } 4250b57cec5SDimitry Andric 4260b57cec5SDimitry Andric // Otherwise, things are slightly more complex. Remove V's name from VST and 4270b57cec5SDimitry Andric // then reinsert it into ST. 4280b57cec5SDimitry Andric 4290b57cec5SDimitry Andric if (VST) 4300b57cec5SDimitry Andric VST->removeValueName(V->getValueName()); 4310b57cec5SDimitry Andric setValueName(V->getValueName()); 4320b57cec5SDimitry Andric V->setValueName(nullptr); 4330b57cec5SDimitry Andric getValueName()->setValue(this); 4340b57cec5SDimitry Andric 4350b57cec5SDimitry Andric if (ST) 4360b57cec5SDimitry Andric ST->reinsertValue(this); 4370b57cec5SDimitry Andric } 4380b57cec5SDimitry Andric 439e8d8bef9SDimitry Andric #ifndef NDEBUG 440e8d8bef9SDimitry Andric std::string Value::getNameOrAsOperand() const { 441e8d8bef9SDimitry Andric if (!getName().empty()) 442e8d8bef9SDimitry Andric return std::string(getName()); 443e8d8bef9SDimitry Andric 444e8d8bef9SDimitry Andric std::string BBName; 445e8d8bef9SDimitry Andric raw_string_ostream OS(BBName); 446e8d8bef9SDimitry Andric printAsOperand(OS, false); 447e8d8bef9SDimitry Andric return OS.str(); 448e8d8bef9SDimitry Andric } 449e8d8bef9SDimitry Andric #endif 450e8d8bef9SDimitry Andric 4510b57cec5SDimitry Andric void Value::assertModuleIsMaterializedImpl() const { 4520b57cec5SDimitry Andric #ifndef NDEBUG 4530b57cec5SDimitry Andric const GlobalValue *GV = dyn_cast<GlobalValue>(this); 4540b57cec5SDimitry Andric if (!GV) 4550b57cec5SDimitry Andric return; 4560b57cec5SDimitry Andric const Module *M = GV->getParent(); 4570b57cec5SDimitry Andric if (!M) 4580b57cec5SDimitry Andric return; 4590b57cec5SDimitry Andric assert(M->isMaterialized()); 4600b57cec5SDimitry Andric #endif 4610b57cec5SDimitry Andric } 4620b57cec5SDimitry Andric 4630b57cec5SDimitry Andric #ifndef NDEBUG 4640b57cec5SDimitry Andric static bool contains(SmallPtrSetImpl<ConstantExpr *> &Cache, ConstantExpr *Expr, 4650b57cec5SDimitry Andric Constant *C) { 4660b57cec5SDimitry Andric if (!Cache.insert(Expr).second) 4670b57cec5SDimitry Andric return false; 4680b57cec5SDimitry Andric 4690b57cec5SDimitry Andric for (auto &O : Expr->operands()) { 4700b57cec5SDimitry Andric if (O == C) 4710b57cec5SDimitry Andric return true; 4720b57cec5SDimitry Andric auto *CE = dyn_cast<ConstantExpr>(O); 4730b57cec5SDimitry Andric if (!CE) 4740b57cec5SDimitry Andric continue; 4750b57cec5SDimitry Andric if (contains(Cache, CE, C)) 4760b57cec5SDimitry Andric return true; 4770b57cec5SDimitry Andric } 4780b57cec5SDimitry Andric return false; 4790b57cec5SDimitry Andric } 4800b57cec5SDimitry Andric 4810b57cec5SDimitry Andric static bool contains(Value *Expr, Value *V) { 4820b57cec5SDimitry Andric if (Expr == V) 4830b57cec5SDimitry Andric return true; 4840b57cec5SDimitry Andric 4850b57cec5SDimitry Andric auto *C = dyn_cast<Constant>(V); 4860b57cec5SDimitry Andric if (!C) 4870b57cec5SDimitry Andric return false; 4880b57cec5SDimitry Andric 4890b57cec5SDimitry Andric auto *CE = dyn_cast<ConstantExpr>(Expr); 4900b57cec5SDimitry Andric if (!CE) 4910b57cec5SDimitry Andric return false; 4920b57cec5SDimitry Andric 4930b57cec5SDimitry Andric SmallPtrSet<ConstantExpr *, 4> Cache; 4940b57cec5SDimitry Andric return contains(Cache, CE, C); 4950b57cec5SDimitry Andric } 4960b57cec5SDimitry Andric #endif // NDEBUG 4970b57cec5SDimitry Andric 4980b57cec5SDimitry Andric void Value::doRAUW(Value *New, ReplaceMetadataUses ReplaceMetaUses) { 4990b57cec5SDimitry Andric assert(New && "Value::replaceAllUsesWith(<null>) is invalid!"); 5000b57cec5SDimitry Andric assert(!contains(New, this) && 5010b57cec5SDimitry Andric "this->replaceAllUsesWith(expr(this)) is NOT valid!"); 5020b57cec5SDimitry Andric assert(New->getType() == getType() && 5030b57cec5SDimitry Andric "replaceAllUses of value with new value of different type!"); 5040b57cec5SDimitry Andric 5050b57cec5SDimitry Andric // Notify all ValueHandles (if present) that this value is going away. 5060b57cec5SDimitry Andric if (HasValueHandle) 5070b57cec5SDimitry Andric ValueHandleBase::ValueIsRAUWd(this, New); 5080b57cec5SDimitry Andric if (ReplaceMetaUses == ReplaceMetadataUses::Yes && isUsedByMetadata()) 5090b57cec5SDimitry Andric ValueAsMetadata::handleRAUW(this, New); 5100b57cec5SDimitry Andric 5110b57cec5SDimitry Andric while (!materialized_use_empty()) { 5120b57cec5SDimitry Andric Use &U = *UseList; 5130b57cec5SDimitry Andric // Must handle Constants specially, we cannot call replaceUsesOfWith on a 5140b57cec5SDimitry Andric // constant because they are uniqued. 5150b57cec5SDimitry Andric if (auto *C = dyn_cast<Constant>(U.getUser())) { 5160b57cec5SDimitry Andric if (!isa<GlobalValue>(C)) { 5170b57cec5SDimitry Andric C->handleOperandChange(this, New); 5180b57cec5SDimitry Andric continue; 5190b57cec5SDimitry Andric } 5200b57cec5SDimitry Andric } 5210b57cec5SDimitry Andric 5220b57cec5SDimitry Andric U.set(New); 5230b57cec5SDimitry Andric } 5240b57cec5SDimitry Andric 5250b57cec5SDimitry Andric if (BasicBlock *BB = dyn_cast<BasicBlock>(this)) 5260b57cec5SDimitry Andric BB->replaceSuccessorsPhiUsesWith(cast<BasicBlock>(New)); 5270b57cec5SDimitry Andric } 5280b57cec5SDimitry Andric 5290b57cec5SDimitry Andric void Value::replaceAllUsesWith(Value *New) { 5300b57cec5SDimitry Andric doRAUW(New, ReplaceMetadataUses::Yes); 5310b57cec5SDimitry Andric } 5320b57cec5SDimitry Andric 5330b57cec5SDimitry Andric void Value::replaceNonMetadataUsesWith(Value *New) { 5340b57cec5SDimitry Andric doRAUW(New, ReplaceMetadataUses::No); 5350b57cec5SDimitry Andric } 5360b57cec5SDimitry Andric 537fe6060f1SDimitry Andric void Value::replaceUsesWithIf(Value *New, 538fe6060f1SDimitry Andric llvm::function_ref<bool(Use &U)> ShouldReplace) { 539fe6060f1SDimitry Andric assert(New && "Value::replaceUsesWithIf(<null>) is invalid!"); 540fe6060f1SDimitry Andric assert(New->getType() == getType() && 541fe6060f1SDimitry Andric "replaceUses of value with new value of different type!"); 542fe6060f1SDimitry Andric 543fe6060f1SDimitry Andric SmallVector<TrackingVH<Constant>, 8> Consts; 544fe6060f1SDimitry Andric SmallPtrSet<Constant *, 8> Visited; 545fe6060f1SDimitry Andric 546349cc55cSDimitry Andric for (Use &U : llvm::make_early_inc_range(uses())) { 547fe6060f1SDimitry Andric if (!ShouldReplace(U)) 548fe6060f1SDimitry Andric continue; 549fe6060f1SDimitry Andric // Must handle Constants specially, we cannot call replaceUsesOfWith on a 550fe6060f1SDimitry Andric // constant because they are uniqued. 551fe6060f1SDimitry Andric if (auto *C = dyn_cast<Constant>(U.getUser())) { 552fe6060f1SDimitry Andric if (!isa<GlobalValue>(C)) { 553fe6060f1SDimitry Andric if (Visited.insert(C).second) 554fe6060f1SDimitry Andric Consts.push_back(TrackingVH<Constant>(C)); 555fe6060f1SDimitry Andric continue; 556fe6060f1SDimitry Andric } 557fe6060f1SDimitry Andric } 558fe6060f1SDimitry Andric U.set(New); 559fe6060f1SDimitry Andric } 560fe6060f1SDimitry Andric 561fe6060f1SDimitry Andric while (!Consts.empty()) { 562fe6060f1SDimitry Andric // FIXME: handleOperandChange() updates all the uses in a given Constant, 563fe6060f1SDimitry Andric // not just the one passed to ShouldReplace 564fe6060f1SDimitry Andric Consts.pop_back_val()->handleOperandChange(this, New); 565fe6060f1SDimitry Andric } 566fe6060f1SDimitry Andric } 567fe6060f1SDimitry Andric 568fe6060f1SDimitry Andric /// Replace llvm.dbg.* uses of MetadataAsValue(ValueAsMetadata(V)) outside BB 569fe6060f1SDimitry Andric /// with New. 570fe6060f1SDimitry Andric static void replaceDbgUsesOutsideBlock(Value *V, Value *New, BasicBlock *BB) { 571fe6060f1SDimitry Andric SmallVector<DbgVariableIntrinsic *> DbgUsers; 572fe6060f1SDimitry Andric findDbgUsers(DbgUsers, V); 573fe6060f1SDimitry Andric for (auto *DVI : DbgUsers) { 574fe6060f1SDimitry Andric if (DVI->getParent() != BB) 575fe6060f1SDimitry Andric DVI->replaceVariableLocationOp(V, New); 576fe6060f1SDimitry Andric } 577fe6060f1SDimitry Andric } 578fe6060f1SDimitry Andric 5790b57cec5SDimitry Andric // Like replaceAllUsesWith except it does not handle constants or basic blocks. 5800b57cec5SDimitry Andric // This routine leaves uses within BB. 5810b57cec5SDimitry Andric void Value::replaceUsesOutsideBlock(Value *New, BasicBlock *BB) { 5820b57cec5SDimitry Andric assert(New && "Value::replaceUsesOutsideBlock(<null>, BB) is invalid!"); 5830b57cec5SDimitry Andric assert(!contains(New, this) && 5840b57cec5SDimitry Andric "this->replaceUsesOutsideBlock(expr(this), BB) is NOT valid!"); 5850b57cec5SDimitry Andric assert(New->getType() == getType() && 5860b57cec5SDimitry Andric "replaceUses of value with new value of different type!"); 5870b57cec5SDimitry Andric assert(BB && "Basic block that may contain a use of 'New' must be defined\n"); 5880b57cec5SDimitry Andric 589fe6060f1SDimitry Andric replaceDbgUsesOutsideBlock(this, New, BB); 5908bcb0991SDimitry Andric replaceUsesWithIf(New, [BB](Use &U) { 5918bcb0991SDimitry Andric auto *I = dyn_cast<Instruction>(U.getUser()); 5928bcb0991SDimitry Andric // Don't replace if it's an instruction in the BB basic block. 5938bcb0991SDimitry Andric return !I || I->getParent() != BB; 5948bcb0991SDimitry Andric }); 5950b57cec5SDimitry Andric } 5960b57cec5SDimitry Andric 5970b57cec5SDimitry Andric namespace { 5980b57cec5SDimitry Andric // Various metrics for how much to strip off of pointers. 5990b57cec5SDimitry Andric enum PointerStripKind { 6000b57cec5SDimitry Andric PSK_ZeroIndices, 6010b57cec5SDimitry Andric PSK_ZeroIndicesAndAliases, 6028bcb0991SDimitry Andric PSK_ZeroIndicesSameRepresentation, 603fe6060f1SDimitry Andric PSK_ForAliasAnalysis, 6040b57cec5SDimitry Andric PSK_InBoundsConstantIndices, 6050b57cec5SDimitry Andric PSK_InBounds 6060b57cec5SDimitry Andric }; 6070b57cec5SDimitry Andric 6085ffd83dbSDimitry Andric template <PointerStripKind StripKind> static void NoopCallback(const Value *) {} 6095ffd83dbSDimitry Andric 6100b57cec5SDimitry Andric template <PointerStripKind StripKind> 6115ffd83dbSDimitry Andric static const Value *stripPointerCastsAndOffsets( 6125ffd83dbSDimitry Andric const Value *V, 6135ffd83dbSDimitry Andric function_ref<void(const Value *)> Func = NoopCallback<StripKind>) { 6140b57cec5SDimitry Andric if (!V->getType()->isPointerTy()) 6150b57cec5SDimitry Andric return V; 6160b57cec5SDimitry Andric 6170b57cec5SDimitry Andric // Even though we don't look through PHI nodes, we could be called on an 6180b57cec5SDimitry Andric // instruction in an unreachable block, which may be on a cycle. 6190b57cec5SDimitry Andric SmallPtrSet<const Value *, 4> Visited; 6200b57cec5SDimitry Andric 6210b57cec5SDimitry Andric Visited.insert(V); 6220b57cec5SDimitry Andric do { 6235ffd83dbSDimitry Andric Func(V); 6240b57cec5SDimitry Andric if (auto *GEP = dyn_cast<GEPOperator>(V)) { 6250b57cec5SDimitry Andric switch (StripKind) { 6260b57cec5SDimitry Andric case PSK_ZeroIndices: 6278bcb0991SDimitry Andric case PSK_ZeroIndicesAndAliases: 6288bcb0991SDimitry Andric case PSK_ZeroIndicesSameRepresentation: 629fe6060f1SDimitry Andric case PSK_ForAliasAnalysis: 6300b57cec5SDimitry Andric if (!GEP->hasAllZeroIndices()) 6310b57cec5SDimitry Andric return V; 6320b57cec5SDimitry Andric break; 6330b57cec5SDimitry Andric case PSK_InBoundsConstantIndices: 6340b57cec5SDimitry Andric if (!GEP->hasAllConstantIndices()) 6350b57cec5SDimitry Andric return V; 6360b57cec5SDimitry Andric LLVM_FALLTHROUGH; 6370b57cec5SDimitry Andric case PSK_InBounds: 6380b57cec5SDimitry Andric if (!GEP->isInBounds()) 6390b57cec5SDimitry Andric return V; 6400b57cec5SDimitry Andric break; 6410b57cec5SDimitry Andric } 6420b57cec5SDimitry Andric V = GEP->getPointerOperand(); 6430b57cec5SDimitry Andric } else if (Operator::getOpcode(V) == Instruction::BitCast) { 6440b57cec5SDimitry Andric V = cast<Operator>(V)->getOperand(0); 6455ffd83dbSDimitry Andric if (!V->getType()->isPointerTy()) 6465ffd83dbSDimitry Andric return V; 6478bcb0991SDimitry Andric } else if (StripKind != PSK_ZeroIndicesSameRepresentation && 6480b57cec5SDimitry Andric Operator::getOpcode(V) == Instruction::AddrSpaceCast) { 6490b57cec5SDimitry Andric // TODO: If we know an address space cast will not change the 6500b57cec5SDimitry Andric // representation we could look through it here as well. 6510b57cec5SDimitry Andric V = cast<Operator>(V)->getOperand(0); 6528bcb0991SDimitry Andric } else if (StripKind == PSK_ZeroIndicesAndAliases && isa<GlobalAlias>(V)) { 6538bcb0991SDimitry Andric V = cast<GlobalAlias>(V)->getAliasee(); 654fe6060f1SDimitry Andric } else if (StripKind == PSK_ForAliasAnalysis && isa<PHINode>(V) && 655fe6060f1SDimitry Andric cast<PHINode>(V)->getNumIncomingValues() == 1) { 656fe6060f1SDimitry Andric V = cast<PHINode>(V)->getIncomingValue(0); 6570b57cec5SDimitry Andric } else { 6580b57cec5SDimitry Andric if (const auto *Call = dyn_cast<CallBase>(V)) { 6590b57cec5SDimitry Andric if (const Value *RV = Call->getReturnedArgOperand()) { 6600b57cec5SDimitry Andric V = RV; 6610b57cec5SDimitry Andric continue; 6620b57cec5SDimitry Andric } 6630b57cec5SDimitry Andric // The result of launder.invariant.group must alias it's argument, 6640b57cec5SDimitry Andric // but it can't be marked with returned attribute, that's why it needs 6650b57cec5SDimitry Andric // special case. 666fe6060f1SDimitry Andric if (StripKind == PSK_ForAliasAnalysis && 6670b57cec5SDimitry Andric (Call->getIntrinsicID() == Intrinsic::launder_invariant_group || 6680b57cec5SDimitry Andric Call->getIntrinsicID() == Intrinsic::strip_invariant_group)) { 6690b57cec5SDimitry Andric V = Call->getArgOperand(0); 6700b57cec5SDimitry Andric continue; 6710b57cec5SDimitry Andric } 6720b57cec5SDimitry Andric } 6730b57cec5SDimitry Andric return V; 6740b57cec5SDimitry Andric } 6750b57cec5SDimitry Andric assert(V->getType()->isPointerTy() && "Unexpected operand type!"); 6760b57cec5SDimitry Andric } while (Visited.insert(V).second); 6770b57cec5SDimitry Andric 6780b57cec5SDimitry Andric return V; 6790b57cec5SDimitry Andric } 6800b57cec5SDimitry Andric } // end anonymous namespace 6810b57cec5SDimitry Andric 6820b57cec5SDimitry Andric const Value *Value::stripPointerCasts() const { 6838bcb0991SDimitry Andric return stripPointerCastsAndOffsets<PSK_ZeroIndices>(this); 6848bcb0991SDimitry Andric } 6858bcb0991SDimitry Andric 6868bcb0991SDimitry Andric const Value *Value::stripPointerCastsAndAliases() const { 6870b57cec5SDimitry Andric return stripPointerCastsAndOffsets<PSK_ZeroIndicesAndAliases>(this); 6880b57cec5SDimitry Andric } 6890b57cec5SDimitry Andric 6900b57cec5SDimitry Andric const Value *Value::stripPointerCastsSameRepresentation() const { 6918bcb0991SDimitry Andric return stripPointerCastsAndOffsets<PSK_ZeroIndicesSameRepresentation>(this); 6920b57cec5SDimitry Andric } 6930b57cec5SDimitry Andric 6940b57cec5SDimitry Andric const Value *Value::stripInBoundsConstantOffsets() const { 6950b57cec5SDimitry Andric return stripPointerCastsAndOffsets<PSK_InBoundsConstantIndices>(this); 6960b57cec5SDimitry Andric } 6970b57cec5SDimitry Andric 698fe6060f1SDimitry Andric const Value *Value::stripPointerCastsForAliasAnalysis() const { 699fe6060f1SDimitry Andric return stripPointerCastsAndOffsets<PSK_ForAliasAnalysis>(this); 7000b57cec5SDimitry Andric } 7010b57cec5SDimitry Andric 7025ffd83dbSDimitry Andric const Value *Value::stripAndAccumulateConstantOffsets( 7035ffd83dbSDimitry Andric const DataLayout &DL, APInt &Offset, bool AllowNonInbounds, 704349cc55cSDimitry Andric bool AllowInvariantGroup, 7055ffd83dbSDimitry Andric function_ref<bool(Value &, APInt &)> ExternalAnalysis) const { 7060b57cec5SDimitry Andric if (!getType()->isPtrOrPtrVectorTy()) 7070b57cec5SDimitry Andric return this; 7080b57cec5SDimitry Andric 7090b57cec5SDimitry Andric unsigned BitWidth = Offset.getBitWidth(); 7100b57cec5SDimitry Andric assert(BitWidth == DL.getIndexTypeSizeInBits(getType()) && 7110b57cec5SDimitry Andric "The offset bit width does not match the DL specification."); 7120b57cec5SDimitry Andric 7130b57cec5SDimitry Andric // Even though we don't look through PHI nodes, we could be called on an 7140b57cec5SDimitry Andric // instruction in an unreachable block, which may be on a cycle. 7150b57cec5SDimitry Andric SmallPtrSet<const Value *, 4> Visited; 7160b57cec5SDimitry Andric Visited.insert(this); 7170b57cec5SDimitry Andric const Value *V = this; 7180b57cec5SDimitry Andric do { 7190b57cec5SDimitry Andric if (auto *GEP = dyn_cast<GEPOperator>(V)) { 7200b57cec5SDimitry Andric // If in-bounds was requested, we do not strip non-in-bounds GEPs. 7210b57cec5SDimitry Andric if (!AllowNonInbounds && !GEP->isInBounds()) 7220b57cec5SDimitry Andric return V; 7230b57cec5SDimitry Andric 7240b57cec5SDimitry Andric // If one of the values we have visited is an addrspacecast, then 7250b57cec5SDimitry Andric // the pointer type of this GEP may be different from the type 7260b57cec5SDimitry Andric // of the Ptr parameter which was passed to this function. This 7270b57cec5SDimitry Andric // means when we construct GEPOffset, we need to use the size 7280b57cec5SDimitry Andric // of GEP's pointer type rather than the size of the original 7290b57cec5SDimitry Andric // pointer type. 7300b57cec5SDimitry Andric APInt GEPOffset(DL.getIndexTypeSizeInBits(V->getType()), 0); 7315ffd83dbSDimitry Andric if (!GEP->accumulateConstantOffset(DL, GEPOffset, ExternalAnalysis)) 7320b57cec5SDimitry Andric return V; 7330b57cec5SDimitry Andric 7340b57cec5SDimitry Andric // Stop traversal if the pointer offset wouldn't fit in the bit-width 7350b57cec5SDimitry Andric // provided by the Offset argument. This can happen due to AddrSpaceCast 7360b57cec5SDimitry Andric // stripping. 7370b57cec5SDimitry Andric if (GEPOffset.getMinSignedBits() > BitWidth) 7380b57cec5SDimitry Andric return V; 7390b57cec5SDimitry Andric 7405ffd83dbSDimitry Andric // External Analysis can return a result higher/lower than the value 7415ffd83dbSDimitry Andric // represents. We need to detect overflow/underflow. 7425ffd83dbSDimitry Andric APInt GEPOffsetST = GEPOffset.sextOrTrunc(BitWidth); 7435ffd83dbSDimitry Andric if (!ExternalAnalysis) { 7445ffd83dbSDimitry Andric Offset += GEPOffsetST; 7455ffd83dbSDimitry Andric } else { 7465ffd83dbSDimitry Andric bool Overflow = false; 7475ffd83dbSDimitry Andric APInt OldOffset = Offset; 7485ffd83dbSDimitry Andric Offset = Offset.sadd_ov(GEPOffsetST, Overflow); 7495ffd83dbSDimitry Andric if (Overflow) { 7505ffd83dbSDimitry Andric Offset = OldOffset; 7515ffd83dbSDimitry Andric return V; 7525ffd83dbSDimitry Andric } 7535ffd83dbSDimitry Andric } 7540b57cec5SDimitry Andric V = GEP->getPointerOperand(); 7550b57cec5SDimitry Andric } else if (Operator::getOpcode(V) == Instruction::BitCast || 7560b57cec5SDimitry Andric Operator::getOpcode(V) == Instruction::AddrSpaceCast) { 7570b57cec5SDimitry Andric V = cast<Operator>(V)->getOperand(0); 7580b57cec5SDimitry Andric } else if (auto *GA = dyn_cast<GlobalAlias>(V)) { 7590b57cec5SDimitry Andric if (!GA->isInterposable()) 7600b57cec5SDimitry Andric V = GA->getAliasee(); 7610b57cec5SDimitry Andric } else if (const auto *Call = dyn_cast<CallBase>(V)) { 7620b57cec5SDimitry Andric if (const Value *RV = Call->getReturnedArgOperand()) 7630b57cec5SDimitry Andric V = RV; 764349cc55cSDimitry Andric if (AllowInvariantGroup && Call->isLaunderOrStripInvariantGroup()) 765349cc55cSDimitry Andric V = Call->getArgOperand(0); 7660b57cec5SDimitry Andric } 7670b57cec5SDimitry Andric assert(V->getType()->isPtrOrPtrVectorTy() && "Unexpected operand type!"); 7680b57cec5SDimitry Andric } while (Visited.insert(V).second); 7690b57cec5SDimitry Andric 7700b57cec5SDimitry Andric return V; 7710b57cec5SDimitry Andric } 7720b57cec5SDimitry Andric 7735ffd83dbSDimitry Andric const Value * 7745ffd83dbSDimitry Andric Value::stripInBoundsOffsets(function_ref<void(const Value *)> Func) const { 7755ffd83dbSDimitry Andric return stripPointerCastsAndOffsets<PSK_InBounds>(this, Func); 7760b57cec5SDimitry Andric } 7770b57cec5SDimitry Andric 778fe6060f1SDimitry Andric bool Value::canBeFreed() const { 779fe6060f1SDimitry Andric assert(getType()->isPointerTy()); 780fe6060f1SDimitry Andric 781fe6060f1SDimitry Andric // Cases that can simply never be deallocated 782fe6060f1SDimitry Andric // *) Constants aren't allocated per se, thus not deallocated either. 783fe6060f1SDimitry Andric if (isa<Constant>(this)) 784fe6060f1SDimitry Andric return false; 785fe6060f1SDimitry Andric 786fe6060f1SDimitry Andric // Handle byval/byref/sret/inalloca/preallocated arguments. The storage 787fe6060f1SDimitry Andric // lifetime is guaranteed to be longer than the callee's lifetime. 788fe6060f1SDimitry Andric if (auto *A = dyn_cast<Argument>(this)) { 789fe6060f1SDimitry Andric if (A->hasPointeeInMemoryValueAttr()) 790fe6060f1SDimitry Andric return false; 791fe6060f1SDimitry Andric // A pointer to an object in a function which neither frees, nor can arrange 792fe6060f1SDimitry Andric // for another thread to free on its behalf, can not be freed in the scope 793fe6060f1SDimitry Andric // of the function. Note that this logic is restricted to memory 794fe6060f1SDimitry Andric // allocations in existance before the call; a nofree function *is* allowed 795fe6060f1SDimitry Andric // to free memory it allocated. 796fe6060f1SDimitry Andric const Function *F = A->getParent(); 797fe6060f1SDimitry Andric if (F->doesNotFreeMemory() && F->hasNoSync()) 798fe6060f1SDimitry Andric return false; 799fe6060f1SDimitry Andric } 800fe6060f1SDimitry Andric 801fe6060f1SDimitry Andric const Function *F = nullptr; 802fe6060f1SDimitry Andric if (auto *I = dyn_cast<Instruction>(this)) 803fe6060f1SDimitry Andric F = I->getFunction(); 804fe6060f1SDimitry Andric if (auto *A = dyn_cast<Argument>(this)) 805fe6060f1SDimitry Andric F = A->getParent(); 806fe6060f1SDimitry Andric 807fe6060f1SDimitry Andric if (!F) 808fe6060f1SDimitry Andric return true; 809fe6060f1SDimitry Andric 810fe6060f1SDimitry Andric // With garbage collection, deallocation typically occurs solely at or after 811fe6060f1SDimitry Andric // safepoints. If we're compiling for a collector which uses the 812fe6060f1SDimitry Andric // gc.statepoint infrastructure, safepoints aren't explicitly present 813fe6060f1SDimitry Andric // in the IR until after lowering from abstract to physical machine model. 814fe6060f1SDimitry Andric // The collector could chose to mix explicit deallocation and gc'd objects 815fe6060f1SDimitry Andric // which is why we need the explicit opt in on a per collector basis. 816fe6060f1SDimitry Andric if (!F->hasGC()) 817fe6060f1SDimitry Andric return true; 818fe6060f1SDimitry Andric 819fe6060f1SDimitry Andric const auto &GCName = F->getGC(); 820fe6060f1SDimitry Andric if (GCName == "statepoint-example") { 821fe6060f1SDimitry Andric auto *PT = cast<PointerType>(this->getType()); 822fe6060f1SDimitry Andric if (PT->getAddressSpace() != 1) 823fe6060f1SDimitry Andric // For the sake of this example GC, we arbitrarily pick addrspace(1) as 824fe6060f1SDimitry Andric // our GC managed heap. This must match the same check in 825fe6060f1SDimitry Andric // RewriteStatepointsForGC (and probably needs better factored.) 826fe6060f1SDimitry Andric return true; 827fe6060f1SDimitry Andric 828fe6060f1SDimitry Andric // It is cheaper to scan for a declaration than to scan for a use in this 829fe6060f1SDimitry Andric // function. Note that gc.statepoint is a type overloaded function so the 830fe6060f1SDimitry Andric // usual trick of requesting declaration of the intrinsic from the module 831fe6060f1SDimitry Andric // doesn't work. 832fe6060f1SDimitry Andric for (auto &Fn : *F->getParent()) 833fe6060f1SDimitry Andric if (Fn.getIntrinsicID() == Intrinsic::experimental_gc_statepoint) 834fe6060f1SDimitry Andric return true; 835fe6060f1SDimitry Andric return false; 836fe6060f1SDimitry Andric } 837fe6060f1SDimitry Andric return true; 838fe6060f1SDimitry Andric } 839fe6060f1SDimitry Andric 8400b57cec5SDimitry Andric uint64_t Value::getPointerDereferenceableBytes(const DataLayout &DL, 841fe6060f1SDimitry Andric bool &CanBeNull, 842fe6060f1SDimitry Andric bool &CanBeFreed) const { 8430b57cec5SDimitry Andric assert(getType()->isPointerTy() && "must be pointer"); 8440b57cec5SDimitry Andric 8450b57cec5SDimitry Andric uint64_t DerefBytes = 0; 8460b57cec5SDimitry Andric CanBeNull = false; 847fe6060f1SDimitry Andric CanBeFreed = UseDerefAtPointSemantics && canBeFreed(); 8480b57cec5SDimitry Andric if (const Argument *A = dyn_cast<Argument>(this)) { 8490b57cec5SDimitry Andric DerefBytes = A->getDereferenceableBytes(); 850e8d8bef9SDimitry Andric if (DerefBytes == 0) { 851e8d8bef9SDimitry Andric // Handle byval/byref/inalloca/preallocated arguments 852e8d8bef9SDimitry Andric if (Type *ArgMemTy = A->getPointeeInMemoryValueType()) { 853e8d8bef9SDimitry Andric if (ArgMemTy->isSized()) { 854e8d8bef9SDimitry Andric // FIXME: Why isn't this the type alloc size? 855e8d8bef9SDimitry Andric DerefBytes = DL.getTypeStoreSize(ArgMemTy).getKnownMinSize(); 8560b57cec5SDimitry Andric } 857e8d8bef9SDimitry Andric } 858e8d8bef9SDimitry Andric } 859e8d8bef9SDimitry Andric 8600b57cec5SDimitry Andric if (DerefBytes == 0) { 8610b57cec5SDimitry Andric DerefBytes = A->getDereferenceableOrNullBytes(); 8620b57cec5SDimitry Andric CanBeNull = true; 8630b57cec5SDimitry Andric } 8640b57cec5SDimitry Andric } else if (const auto *Call = dyn_cast<CallBase>(this)) { 865349cc55cSDimitry Andric DerefBytes = Call->getRetDereferenceableBytes(); 8660b57cec5SDimitry Andric if (DerefBytes == 0) { 867349cc55cSDimitry Andric DerefBytes = Call->getRetDereferenceableOrNullBytes(); 8680b57cec5SDimitry Andric CanBeNull = true; 8690b57cec5SDimitry Andric } 8700b57cec5SDimitry Andric } else if (const LoadInst *LI = dyn_cast<LoadInst>(this)) { 8710b57cec5SDimitry Andric if (MDNode *MD = LI->getMetadata(LLVMContext::MD_dereferenceable)) { 8720b57cec5SDimitry Andric ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(0)); 8730b57cec5SDimitry Andric DerefBytes = CI->getLimitedValue(); 8740b57cec5SDimitry Andric } 8750b57cec5SDimitry Andric if (DerefBytes == 0) { 8760b57cec5SDimitry Andric if (MDNode *MD = 8770b57cec5SDimitry Andric LI->getMetadata(LLVMContext::MD_dereferenceable_or_null)) { 8780b57cec5SDimitry Andric ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(0)); 8790b57cec5SDimitry Andric DerefBytes = CI->getLimitedValue(); 8800b57cec5SDimitry Andric } 8810b57cec5SDimitry Andric CanBeNull = true; 8820b57cec5SDimitry Andric } 8838bcb0991SDimitry Andric } else if (auto *IP = dyn_cast<IntToPtrInst>(this)) { 8848bcb0991SDimitry Andric if (MDNode *MD = IP->getMetadata(LLVMContext::MD_dereferenceable)) { 8858bcb0991SDimitry Andric ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(0)); 8868bcb0991SDimitry Andric DerefBytes = CI->getLimitedValue(); 8878bcb0991SDimitry Andric } 8888bcb0991SDimitry Andric if (DerefBytes == 0) { 8898bcb0991SDimitry Andric if (MDNode *MD = 8908bcb0991SDimitry Andric IP->getMetadata(LLVMContext::MD_dereferenceable_or_null)) { 8918bcb0991SDimitry Andric ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(0)); 8928bcb0991SDimitry Andric DerefBytes = CI->getLimitedValue(); 8938bcb0991SDimitry Andric } 8948bcb0991SDimitry Andric CanBeNull = true; 8958bcb0991SDimitry Andric } 8960b57cec5SDimitry Andric } else if (auto *AI = dyn_cast<AllocaInst>(this)) { 8970b57cec5SDimitry Andric if (!AI->isArrayAllocation()) { 8985ffd83dbSDimitry Andric DerefBytes = 8995ffd83dbSDimitry Andric DL.getTypeStoreSize(AI->getAllocatedType()).getKnownMinSize(); 9000b57cec5SDimitry Andric CanBeNull = false; 901fe6060f1SDimitry Andric CanBeFreed = false; 9020b57cec5SDimitry Andric } 9030b57cec5SDimitry Andric } else if (auto *GV = dyn_cast<GlobalVariable>(this)) { 9040b57cec5SDimitry Andric if (GV->getValueType()->isSized() && !GV->hasExternalWeakLinkage()) { 9050b57cec5SDimitry Andric // TODO: Don't outright reject hasExternalWeakLinkage but set the 9060b57cec5SDimitry Andric // CanBeNull flag. 9075ffd83dbSDimitry Andric DerefBytes = DL.getTypeStoreSize(GV->getValueType()).getFixedSize(); 9080b57cec5SDimitry Andric CanBeNull = false; 909fe6060f1SDimitry Andric CanBeFreed = false; 9100b57cec5SDimitry Andric } 9110b57cec5SDimitry Andric } 9120b57cec5SDimitry Andric return DerefBytes; 9130b57cec5SDimitry Andric } 9140b57cec5SDimitry Andric 9155ffd83dbSDimitry Andric Align Value::getPointerAlignment(const DataLayout &DL) const { 9160b57cec5SDimitry Andric assert(getType()->isPointerTy() && "must be pointer"); 9170b57cec5SDimitry Andric if (auto *GO = dyn_cast<GlobalObject>(this)) { 9180b57cec5SDimitry Andric if (isa<Function>(GO)) { 9195ffd83dbSDimitry Andric Align FunctionPtrAlign = DL.getFunctionPtrAlign().valueOrOne(); 9200b57cec5SDimitry Andric switch (DL.getFunctionPtrAlignType()) { 9210b57cec5SDimitry Andric case DataLayout::FunctionPtrAlignType::Independent: 9228bcb0991SDimitry Andric return FunctionPtrAlign; 9230b57cec5SDimitry Andric case DataLayout::FunctionPtrAlignType::MultipleOfFunctionAlign: 9245ffd83dbSDimitry Andric return std::max(FunctionPtrAlign, GO->getAlign().valueOrOne()); 9250b57cec5SDimitry Andric } 9268bcb0991SDimitry Andric llvm_unreachable("Unhandled FunctionPtrAlignType"); 9270b57cec5SDimitry Andric } 9280eae32dcSDimitry Andric const MaybeAlign Alignment(GO->getAlign()); 9298bcb0991SDimitry Andric if (!Alignment) { 9300b57cec5SDimitry Andric if (auto *GVar = dyn_cast<GlobalVariable>(GO)) { 9310b57cec5SDimitry Andric Type *ObjectType = GVar->getValueType(); 9320b57cec5SDimitry Andric if (ObjectType->isSized()) { 9330b57cec5SDimitry Andric // If the object is defined in the current Module, we'll be giving 9340b57cec5SDimitry Andric // it the preferred alignment. Otherwise, we have to assume that it 9350b57cec5SDimitry Andric // may only have the minimum ABI alignment. 9360b57cec5SDimitry Andric if (GVar->isStrongDefinitionForLinker()) 9375ffd83dbSDimitry Andric return DL.getPreferredAlign(GVar); 9380b57cec5SDimitry Andric else 9395ffd83dbSDimitry Andric return DL.getABITypeAlign(ObjectType); 9400b57cec5SDimitry Andric } 9410b57cec5SDimitry Andric } 9420b57cec5SDimitry Andric } 9435ffd83dbSDimitry Andric return Alignment.valueOrOne(); 9440b57cec5SDimitry Andric } else if (const Argument *A = dyn_cast<Argument>(this)) { 9455ffd83dbSDimitry Andric const MaybeAlign Alignment = A->getParamAlign(); 9468bcb0991SDimitry Andric if (!Alignment && A->hasStructRetAttr()) { 9470b57cec5SDimitry Andric // An sret parameter has at least the ABI alignment of the return type. 948e8d8bef9SDimitry Andric Type *EltTy = A->getParamStructRetType(); 9490b57cec5SDimitry Andric if (EltTy->isSized()) 9505ffd83dbSDimitry Andric return DL.getABITypeAlign(EltTy); 9510b57cec5SDimitry Andric } 9525ffd83dbSDimitry Andric return Alignment.valueOrOne(); 9530b57cec5SDimitry Andric } else if (const AllocaInst *AI = dyn_cast<AllocaInst>(this)) { 9545ffd83dbSDimitry Andric return AI->getAlign(); 9558bcb0991SDimitry Andric } else if (const auto *Call = dyn_cast<CallBase>(this)) { 9565ffd83dbSDimitry Andric MaybeAlign Alignment = Call->getRetAlign(); 9578bcb0991SDimitry Andric if (!Alignment && Call->getCalledFunction()) 9585ffd83dbSDimitry Andric Alignment = Call->getCalledFunction()->getAttributes().getRetAlignment(); 9595ffd83dbSDimitry Andric return Alignment.valueOrOne(); 9608bcb0991SDimitry Andric } else if (const LoadInst *LI = dyn_cast<LoadInst>(this)) { 9610b57cec5SDimitry Andric if (MDNode *MD = LI->getMetadata(LLVMContext::MD_align)) { 9620b57cec5SDimitry Andric ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(0)); 9635ffd83dbSDimitry Andric return Align(CI->getLimitedValue()); 9645ffd83dbSDimitry Andric } 9655ffd83dbSDimitry Andric } else if (auto *CstPtr = dyn_cast<Constant>(this)) { 966*81ad6265SDimitry Andric // Strip pointer casts to avoid creating unnecessary ptrtoint expression 967*81ad6265SDimitry Andric // if the only "reduction" is combining a bitcast + ptrtoint. 968*81ad6265SDimitry Andric CstPtr = CstPtr->stripPointerCasts(); 9695ffd83dbSDimitry Andric if (auto *CstInt = dyn_cast_or_null<ConstantInt>(ConstantExpr::getPtrToInt( 9705ffd83dbSDimitry Andric const_cast<Constant *>(CstPtr), DL.getIntPtrType(getType()), 9715ffd83dbSDimitry Andric /*OnlyIfReduced=*/true))) { 9725ffd83dbSDimitry Andric size_t TrailingZeros = CstInt->getValue().countTrailingZeros(); 9735ffd83dbSDimitry Andric // While the actual alignment may be large, elsewhere we have 9745ffd83dbSDimitry Andric // an arbitrary upper alignmet limit, so let's clamp to it. 9755ffd83dbSDimitry Andric return Align(TrailingZeros < Value::MaxAlignmentExponent 9765ffd83dbSDimitry Andric ? uint64_t(1) << TrailingZeros 9775ffd83dbSDimitry Andric : Value::MaximumAlignment); 9780b57cec5SDimitry Andric } 9798bcb0991SDimitry Andric } 9805ffd83dbSDimitry Andric return Align(1); 9810b57cec5SDimitry Andric } 9820b57cec5SDimitry Andric 9830b57cec5SDimitry Andric const Value *Value::DoPHITranslation(const BasicBlock *CurBB, 9840b57cec5SDimitry Andric const BasicBlock *PredBB) const { 9850b57cec5SDimitry Andric auto *PN = dyn_cast<PHINode>(this); 9860b57cec5SDimitry Andric if (PN && PN->getParent() == CurBB) 9870b57cec5SDimitry Andric return PN->getIncomingValueForBlock(PredBB); 9880b57cec5SDimitry Andric return this; 9890b57cec5SDimitry Andric } 9900b57cec5SDimitry Andric 9910b57cec5SDimitry Andric LLVMContext &Value::getContext() const { return VTy->getContext(); } 9920b57cec5SDimitry Andric 9930b57cec5SDimitry Andric void Value::reverseUseList() { 9940b57cec5SDimitry Andric if (!UseList || !UseList->Next) 9950b57cec5SDimitry Andric // No need to reverse 0 or 1 uses. 9960b57cec5SDimitry Andric return; 9970b57cec5SDimitry Andric 9980b57cec5SDimitry Andric Use *Head = UseList; 9990b57cec5SDimitry Andric Use *Current = UseList->Next; 10000b57cec5SDimitry Andric Head->Next = nullptr; 10010b57cec5SDimitry Andric while (Current) { 10020b57cec5SDimitry Andric Use *Next = Current->Next; 10030b57cec5SDimitry Andric Current->Next = Head; 10045ffd83dbSDimitry Andric Head->Prev = &Current->Next; 10050b57cec5SDimitry Andric Head = Current; 10060b57cec5SDimitry Andric Current = Next; 10070b57cec5SDimitry Andric } 10080b57cec5SDimitry Andric UseList = Head; 10095ffd83dbSDimitry Andric Head->Prev = &UseList; 10100b57cec5SDimitry Andric } 10110b57cec5SDimitry Andric 10120b57cec5SDimitry Andric bool Value::isSwiftError() const { 10130b57cec5SDimitry Andric auto *Arg = dyn_cast<Argument>(this); 10140b57cec5SDimitry Andric if (Arg) 10150b57cec5SDimitry Andric return Arg->hasSwiftErrorAttr(); 10160b57cec5SDimitry Andric auto *Alloca = dyn_cast<AllocaInst>(this); 10170b57cec5SDimitry Andric if (!Alloca) 10180b57cec5SDimitry Andric return false; 10190b57cec5SDimitry Andric return Alloca->isSwiftError(); 10200b57cec5SDimitry Andric } 10210b57cec5SDimitry Andric 1022fe6060f1SDimitry Andric bool Value::isTransitiveUsedByMetadataOnly() const { 1023*81ad6265SDimitry Andric SmallVector<const User *, 32> WorkList(user_begin(), user_end()); 1024*81ad6265SDimitry Andric SmallPtrSet<const User *, 32> Visited(user_begin(), user_end()); 1025fe6060f1SDimitry Andric while (!WorkList.empty()) { 1026349cc55cSDimitry Andric const User *U = WorkList.pop_back_val(); 1027fe6060f1SDimitry Andric // If it is transitively used by a global value or a non-constant value, 1028fe6060f1SDimitry Andric // it's obviously not only used by metadata. 1029fe6060f1SDimitry Andric if (!isa<Constant>(U) || isa<GlobalValue>(U)) 1030fe6060f1SDimitry Andric return false; 1031fe6060f1SDimitry Andric for (const User *UU : U->users()) 1032*81ad6265SDimitry Andric if (Visited.insert(UU).second) 1033fe6060f1SDimitry Andric WorkList.push_back(UU); 1034fe6060f1SDimitry Andric } 1035fe6060f1SDimitry Andric return true; 1036fe6060f1SDimitry Andric } 1037fe6060f1SDimitry Andric 10380b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 10390b57cec5SDimitry Andric // ValueHandleBase Class 10400b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 10410b57cec5SDimitry Andric 10420b57cec5SDimitry Andric void ValueHandleBase::AddToExistingUseList(ValueHandleBase **List) { 10430b57cec5SDimitry Andric assert(List && "Handle list is null?"); 10440b57cec5SDimitry Andric 10450b57cec5SDimitry Andric // Splice ourselves into the list. 10460b57cec5SDimitry Andric Next = *List; 10470b57cec5SDimitry Andric *List = this; 10480b57cec5SDimitry Andric setPrevPtr(List); 10490b57cec5SDimitry Andric if (Next) { 10500b57cec5SDimitry Andric Next->setPrevPtr(&Next); 10510b57cec5SDimitry Andric assert(getValPtr() == Next->getValPtr() && "Added to wrong list?"); 10520b57cec5SDimitry Andric } 10530b57cec5SDimitry Andric } 10540b57cec5SDimitry Andric 10550b57cec5SDimitry Andric void ValueHandleBase::AddToExistingUseListAfter(ValueHandleBase *List) { 10560b57cec5SDimitry Andric assert(List && "Must insert after existing node"); 10570b57cec5SDimitry Andric 10580b57cec5SDimitry Andric Next = List->Next; 10590b57cec5SDimitry Andric setPrevPtr(&List->Next); 10600b57cec5SDimitry Andric List->Next = this; 10610b57cec5SDimitry Andric if (Next) 10620b57cec5SDimitry Andric Next->setPrevPtr(&Next); 10630b57cec5SDimitry Andric } 10640b57cec5SDimitry Andric 10650b57cec5SDimitry Andric void ValueHandleBase::AddToUseList() { 10660b57cec5SDimitry Andric assert(getValPtr() && "Null pointer doesn't have a use list!"); 10670b57cec5SDimitry Andric 10680b57cec5SDimitry Andric LLVMContextImpl *pImpl = getValPtr()->getContext().pImpl; 10690b57cec5SDimitry Andric 10700b57cec5SDimitry Andric if (getValPtr()->HasValueHandle) { 10710b57cec5SDimitry Andric // If this value already has a ValueHandle, then it must be in the 10720b57cec5SDimitry Andric // ValueHandles map already. 10730b57cec5SDimitry Andric ValueHandleBase *&Entry = pImpl->ValueHandles[getValPtr()]; 10740b57cec5SDimitry Andric assert(Entry && "Value doesn't have any handles?"); 10750b57cec5SDimitry Andric AddToExistingUseList(&Entry); 10760b57cec5SDimitry Andric return; 10770b57cec5SDimitry Andric } 10780b57cec5SDimitry Andric 10790b57cec5SDimitry Andric // Ok, it doesn't have any handles yet, so we must insert it into the 10800b57cec5SDimitry Andric // DenseMap. However, doing this insertion could cause the DenseMap to 10810b57cec5SDimitry Andric // reallocate itself, which would invalidate all of the PrevP pointers that 10820b57cec5SDimitry Andric // point into the old table. Handle this by checking for reallocation and 10830b57cec5SDimitry Andric // updating the stale pointers only if needed. 10840b57cec5SDimitry Andric DenseMap<Value*, ValueHandleBase*> &Handles = pImpl->ValueHandles; 10850b57cec5SDimitry Andric const void *OldBucketPtr = Handles.getPointerIntoBucketsArray(); 10860b57cec5SDimitry Andric 10870b57cec5SDimitry Andric ValueHandleBase *&Entry = Handles[getValPtr()]; 10880b57cec5SDimitry Andric assert(!Entry && "Value really did already have handles?"); 10890b57cec5SDimitry Andric AddToExistingUseList(&Entry); 10900b57cec5SDimitry Andric getValPtr()->HasValueHandle = true; 10910b57cec5SDimitry Andric 10920b57cec5SDimitry Andric // If reallocation didn't happen or if this was the first insertion, don't 10930b57cec5SDimitry Andric // walk the table. 10940b57cec5SDimitry Andric if (Handles.isPointerIntoBucketsArray(OldBucketPtr) || 10950b57cec5SDimitry Andric Handles.size() == 1) { 10960b57cec5SDimitry Andric return; 10970b57cec5SDimitry Andric } 10980b57cec5SDimitry Andric 10990b57cec5SDimitry Andric // Okay, reallocation did happen. Fix the Prev Pointers. 11000b57cec5SDimitry Andric for (DenseMap<Value*, ValueHandleBase*>::iterator I = Handles.begin(), 11010b57cec5SDimitry Andric E = Handles.end(); I != E; ++I) { 11020b57cec5SDimitry Andric assert(I->second && I->first == I->second->getValPtr() && 11030b57cec5SDimitry Andric "List invariant broken!"); 11040b57cec5SDimitry Andric I->second->setPrevPtr(&I->second); 11050b57cec5SDimitry Andric } 11060b57cec5SDimitry Andric } 11070b57cec5SDimitry Andric 11080b57cec5SDimitry Andric void ValueHandleBase::RemoveFromUseList() { 11090b57cec5SDimitry Andric assert(getValPtr() && getValPtr()->HasValueHandle && 11100b57cec5SDimitry Andric "Pointer doesn't have a use list!"); 11110b57cec5SDimitry Andric 11120b57cec5SDimitry Andric // Unlink this from its use list. 11130b57cec5SDimitry Andric ValueHandleBase **PrevPtr = getPrevPtr(); 11140b57cec5SDimitry Andric assert(*PrevPtr == this && "List invariant broken"); 11150b57cec5SDimitry Andric 11160b57cec5SDimitry Andric *PrevPtr = Next; 11170b57cec5SDimitry Andric if (Next) { 11180b57cec5SDimitry Andric assert(Next->getPrevPtr() == &Next && "List invariant broken"); 11190b57cec5SDimitry Andric Next->setPrevPtr(PrevPtr); 11200b57cec5SDimitry Andric return; 11210b57cec5SDimitry Andric } 11220b57cec5SDimitry Andric 11230b57cec5SDimitry Andric // If the Next pointer was null, then it is possible that this was the last 11240b57cec5SDimitry Andric // ValueHandle watching VP. If so, delete its entry from the ValueHandles 11250b57cec5SDimitry Andric // map. 11260b57cec5SDimitry Andric LLVMContextImpl *pImpl = getValPtr()->getContext().pImpl; 11270b57cec5SDimitry Andric DenseMap<Value*, ValueHandleBase*> &Handles = pImpl->ValueHandles; 11280b57cec5SDimitry Andric if (Handles.isPointerIntoBucketsArray(PrevPtr)) { 11290b57cec5SDimitry Andric Handles.erase(getValPtr()); 11300b57cec5SDimitry Andric getValPtr()->HasValueHandle = false; 11310b57cec5SDimitry Andric } 11320b57cec5SDimitry Andric } 11330b57cec5SDimitry Andric 11340b57cec5SDimitry Andric void ValueHandleBase::ValueIsDeleted(Value *V) { 11350b57cec5SDimitry Andric assert(V->HasValueHandle && "Should only be called if ValueHandles present"); 11360b57cec5SDimitry Andric 11370b57cec5SDimitry Andric // Get the linked list base, which is guaranteed to exist since the 11380b57cec5SDimitry Andric // HasValueHandle flag is set. 11390b57cec5SDimitry Andric LLVMContextImpl *pImpl = V->getContext().pImpl; 11400b57cec5SDimitry Andric ValueHandleBase *Entry = pImpl->ValueHandles[V]; 11410b57cec5SDimitry Andric assert(Entry && "Value bit set but no entries exist"); 11420b57cec5SDimitry Andric 11430b57cec5SDimitry Andric // We use a local ValueHandleBase as an iterator so that ValueHandles can add 11440b57cec5SDimitry Andric // and remove themselves from the list without breaking our iteration. This 11450b57cec5SDimitry Andric // is not really an AssertingVH; we just have to give ValueHandleBase a kind. 11460b57cec5SDimitry Andric // Note that we deliberately do not the support the case when dropping a value 11470b57cec5SDimitry Andric // handle results in a new value handle being permanently added to the list 11480b57cec5SDimitry Andric // (as might occur in theory for CallbackVH's): the new value handle will not 11490b57cec5SDimitry Andric // be processed and the checking code will mete out righteous punishment if 11500b57cec5SDimitry Andric // the handle is still present once we have finished processing all the other 11510b57cec5SDimitry Andric // value handles (it is fine to momentarily add then remove a value handle). 11520b57cec5SDimitry Andric for (ValueHandleBase Iterator(Assert, *Entry); Entry; Entry = Iterator.Next) { 11530b57cec5SDimitry Andric Iterator.RemoveFromUseList(); 11540b57cec5SDimitry Andric Iterator.AddToExistingUseListAfter(Entry); 11550b57cec5SDimitry Andric assert(Entry->Next == &Iterator && "Loop invariant broken."); 11560b57cec5SDimitry Andric 11570b57cec5SDimitry Andric switch (Entry->getKind()) { 11580b57cec5SDimitry Andric case Assert: 11590b57cec5SDimitry Andric break; 11600b57cec5SDimitry Andric case Weak: 11610b57cec5SDimitry Andric case WeakTracking: 11620b57cec5SDimitry Andric // WeakTracking and Weak just go to null, which unlinks them 11630b57cec5SDimitry Andric // from the list. 11640b57cec5SDimitry Andric Entry->operator=(nullptr); 11650b57cec5SDimitry Andric break; 11660b57cec5SDimitry Andric case Callback: 11670b57cec5SDimitry Andric // Forward to the subclass's implementation. 11680b57cec5SDimitry Andric static_cast<CallbackVH*>(Entry)->deleted(); 11690b57cec5SDimitry Andric break; 11700b57cec5SDimitry Andric } 11710b57cec5SDimitry Andric } 11720b57cec5SDimitry Andric 11730b57cec5SDimitry Andric // All callbacks, weak references, and assertingVHs should be dropped by now. 11740b57cec5SDimitry Andric if (V->HasValueHandle) { 11750b57cec5SDimitry Andric #ifndef NDEBUG // Only in +Asserts mode... 11760b57cec5SDimitry Andric dbgs() << "While deleting: " << *V->getType() << " %" << V->getName() 11770b57cec5SDimitry Andric << "\n"; 11780b57cec5SDimitry Andric if (pImpl->ValueHandles[V]->getKind() == Assert) 11790b57cec5SDimitry Andric llvm_unreachable("An asserting value handle still pointed to this" 11800b57cec5SDimitry Andric " value!"); 11810b57cec5SDimitry Andric 11820b57cec5SDimitry Andric #endif 11830b57cec5SDimitry Andric llvm_unreachable("All references to V were not removed?"); 11840b57cec5SDimitry Andric } 11850b57cec5SDimitry Andric } 11860b57cec5SDimitry Andric 11870b57cec5SDimitry Andric void ValueHandleBase::ValueIsRAUWd(Value *Old, Value *New) { 11880b57cec5SDimitry Andric assert(Old->HasValueHandle &&"Should only be called if ValueHandles present"); 11890b57cec5SDimitry Andric assert(Old != New && "Changing value into itself!"); 11900b57cec5SDimitry Andric assert(Old->getType() == New->getType() && 11910b57cec5SDimitry Andric "replaceAllUses of value with new value of different type!"); 11920b57cec5SDimitry Andric 11930b57cec5SDimitry Andric // Get the linked list base, which is guaranteed to exist since the 11940b57cec5SDimitry Andric // HasValueHandle flag is set. 11950b57cec5SDimitry Andric LLVMContextImpl *pImpl = Old->getContext().pImpl; 11960b57cec5SDimitry Andric ValueHandleBase *Entry = pImpl->ValueHandles[Old]; 11970b57cec5SDimitry Andric 11980b57cec5SDimitry Andric assert(Entry && "Value bit set but no entries exist"); 11990b57cec5SDimitry Andric 12000b57cec5SDimitry Andric // We use a local ValueHandleBase as an iterator so that 12010b57cec5SDimitry Andric // ValueHandles can add and remove themselves from the list without 12020b57cec5SDimitry Andric // breaking our iteration. This is not really an AssertingVH; we 12030b57cec5SDimitry Andric // just have to give ValueHandleBase some kind. 12040b57cec5SDimitry Andric for (ValueHandleBase Iterator(Assert, *Entry); Entry; Entry = Iterator.Next) { 12050b57cec5SDimitry Andric Iterator.RemoveFromUseList(); 12060b57cec5SDimitry Andric Iterator.AddToExistingUseListAfter(Entry); 12070b57cec5SDimitry Andric assert(Entry->Next == &Iterator && "Loop invariant broken."); 12080b57cec5SDimitry Andric 12090b57cec5SDimitry Andric switch (Entry->getKind()) { 12100b57cec5SDimitry Andric case Assert: 12110b57cec5SDimitry Andric case Weak: 12120b57cec5SDimitry Andric // Asserting and Weak handles do not follow RAUW implicitly. 12130b57cec5SDimitry Andric break; 12140b57cec5SDimitry Andric case WeakTracking: 12150b57cec5SDimitry Andric // Weak goes to the new value, which will unlink it from Old's list. 12160b57cec5SDimitry Andric Entry->operator=(New); 12170b57cec5SDimitry Andric break; 12180b57cec5SDimitry Andric case Callback: 12190b57cec5SDimitry Andric // Forward to the subclass's implementation. 12200b57cec5SDimitry Andric static_cast<CallbackVH*>(Entry)->allUsesReplacedWith(New); 12210b57cec5SDimitry Andric break; 12220b57cec5SDimitry Andric } 12230b57cec5SDimitry Andric } 12240b57cec5SDimitry Andric 12250b57cec5SDimitry Andric #ifndef NDEBUG 12260b57cec5SDimitry Andric // If any new weak value handles were added while processing the 12270b57cec5SDimitry Andric // list, then complain about it now. 12280b57cec5SDimitry Andric if (Old->HasValueHandle) 12290b57cec5SDimitry Andric for (Entry = pImpl->ValueHandles[Old]; Entry; Entry = Entry->Next) 12300b57cec5SDimitry Andric switch (Entry->getKind()) { 12310b57cec5SDimitry Andric case WeakTracking: 12320b57cec5SDimitry Andric dbgs() << "After RAUW from " << *Old->getType() << " %" 12330b57cec5SDimitry Andric << Old->getName() << " to " << *New->getType() << " %" 12340b57cec5SDimitry Andric << New->getName() << "\n"; 12350b57cec5SDimitry Andric llvm_unreachable( 12360b57cec5SDimitry Andric "A weak tracking value handle still pointed to the old value!\n"); 12370b57cec5SDimitry Andric default: 12380b57cec5SDimitry Andric break; 12390b57cec5SDimitry Andric } 12400b57cec5SDimitry Andric #endif 12410b57cec5SDimitry Andric } 12420b57cec5SDimitry Andric 12430b57cec5SDimitry Andric // Pin the vtable to this file. 12440b57cec5SDimitry Andric void CallbackVH::anchor() {} 1245