xref: /llvm-project-15.0.7/llvm/lib/IR/Value.cpp (revision 9068bccb)
1ef860a24SChandler Carruth //===-- Value.cpp - Implement the Value class -----------------------------===//
2ef860a24SChandler Carruth //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6ef860a24SChandler Carruth //
7ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
8ef860a24SChandler Carruth //
9ef860a24SChandler Carruth // This file implements the Value, ValueHandle, and User classes.
10ef860a24SChandler Carruth //
11ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
12ef860a24SChandler Carruth 
139fb823bbSChandler Carruth #include "llvm/IR/Value.h"
14ef860a24SChandler Carruth #include "LLVMContextImpl.h"
15ef860a24SChandler Carruth #include "llvm/ADT/DenseMap.h"
162f2ace98SDmitry Mikulin #include "llvm/ADT/SetVector.h"
174c1a1d3cSReid Kleckner #include "llvm/ADT/SmallString.h"
189fb823bbSChandler Carruth #include "llvm/IR/Constant.h"
199fb823bbSChandler Carruth #include "llvm/IR/Constants.h"
202e42c34dSHal Finkel #include "llvm/IR/DataLayout.h"
219fb823bbSChandler Carruth #include "llvm/IR/DerivedTypes.h"
2296ab8726SReid Kleckner #include "llvm/IR/DerivedUser.h"
2303eb0de9SChandler Carruth #include "llvm/IR/GetElementPtrTypeIterator.h"
249fb823bbSChandler Carruth #include "llvm/IR/InstrTypes.h"
259fb823bbSChandler Carruth #include "llvm/IR/Instructions.h"
26a7343d65SRamkumar Ramachandra #include "llvm/IR/IntrinsicInst.h"
279fb823bbSChandler Carruth #include "llvm/IR/Module.h"
289fb823bbSChandler Carruth #include "llvm/IR/Operator.h"
29a7343d65SRamkumar Ramachandra #include "llvm/IR/Statepoint.h"
304220e9c1SChandler Carruth #include "llvm/IR/ValueHandle.h"
319fb823bbSChandler Carruth #include "llvm/IR/ValueSymbolTable.h"
324c1a1d3cSReid Kleckner #include "llvm/Support/CommandLine.h"
33ef860a24SChandler Carruth #include "llvm/Support/Debug.h"
34ef860a24SChandler Carruth #include "llvm/Support/ErrorHandling.h"
35ef860a24SChandler Carruth #include "llvm/Support/ManagedStatic.h"
36799003bfSBenjamin Kramer #include "llvm/Support/raw_ostream.h"
37ef860a24SChandler Carruth #include <algorithm>
38ecefe5a8SEugene Zelenko 
39ef860a24SChandler Carruth using namespace llvm;
40ef860a24SChandler Carruth 
414c975578SSerge Guelton static cl::opt<unsigned> NonGlobalValueMaxNameSize(
424c975578SSerge Guelton     "non-global-value-max-name-size", cl::Hidden, cl::init(1024),
434c975578SSerge Guelton     cl::desc("Maximum size for the name of non-global values."));
444c975578SSerge Guelton 
45ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
46ef860a24SChandler Carruth //                                Value Class
47ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
48ef860a24SChandler Carruth static inline Type *checkType(Type *Ty) {
49ef860a24SChandler Carruth   assert(Ty && "Value defined with a null type: Error!");
5016bf89ecSReid Kleckner   return Ty;
51ef860a24SChandler Carruth }
52ef860a24SChandler Carruth 
53ef860a24SChandler Carruth Value::Value(Type *ty, unsigned scid)
547349ab93SOwen Anderson     : VTy(checkType(ty)), UseList(nullptr), SubclassID(scid),
557349ab93SOwen Anderson       HasValueHandle(0), SubclassOptionalData(0), SubclassData(0),
56b4eede2cSPete Cooper       NumUserOperands(0), IsUsedByMD(false), HasName(false) {
579fd33f24SSerge Guelton   static_assert(ConstantFirstVal == 0, "!(SubclassID < ConstantFirstVal)");
58ef860a24SChandler Carruth   // FIXME: Why isn't this in the subclass gunk??
59ef860a24SChandler Carruth   // Note, we cannot call isa<CallInst> before the CallInst has been
60ef860a24SChandler Carruth   // constructed.
61784929d0SCraig Topper   if (SubclassID == Instruction::Call || SubclassID == Instruction::Invoke ||
62784929d0SCraig Topper       SubclassID == Instruction::CallBr)
63ef860a24SChandler Carruth     assert((VTy->isFirstClassType() || VTy->isVoidTy() || VTy->isStructTy()) &&
64ef860a24SChandler Carruth            "invalid CallInst type!");
65ef860a24SChandler Carruth   else if (SubclassID != BasicBlockVal &&
669fd33f24SSerge Guelton            (/*SubclassID < ConstantFirstVal ||*/ SubclassID > ConstantLastVal))
67ef860a24SChandler Carruth     assert((VTy->isFirstClassType() || VTy->isVoidTy()) &&
68ef860a24SChandler Carruth            "Cannot create non-first-class values except for constants!");
6996ab8726SReid Kleckner   static_assert(sizeof(Value) == 2 * sizeof(void *) + 2 * sizeof(unsigned),
701762ad3eSReid Kleckner                 "Value too big");
71ef860a24SChandler Carruth }
72ef860a24SChandler Carruth 
73ef860a24SChandler Carruth Value::~Value() {
74ef860a24SChandler Carruth   // Notify all ValueHandles (if present) that this value is going away.
75ef860a24SChandler Carruth   if (HasValueHandle)
76ef860a24SChandler Carruth     ValueHandleBase::ValueIsDeleted(this);
775bf8fef5SDuncan P. N. Exon Smith   if (isUsedByMetadata())
785bf8fef5SDuncan P. N. Exon Smith     ValueAsMetadata::handleDeletion(this);
79ef860a24SChandler Carruth 
80ef860a24SChandler Carruth #ifndef NDEBUG      // Only in -g mode...
81ef860a24SChandler Carruth   // Check to make sure that there are no uses of this value that are still
82ef860a24SChandler Carruth   // around when the value is destroyed.  If there are, then we have a dangling
83b93fb82bSAndrew Kaylor   // reference and something is wrong.  This code is here to print out where
84b93fb82bSAndrew Kaylor   // the value is still being referenced.
85ef860a24SChandler Carruth   //
867dd28109SEvgenii Stepanov   // Note that use_empty() cannot be called here, as it eventually downcasts
877dd28109SEvgenii Stepanov   // 'this' to GlobalValue (derived class of Value), but GlobalValue has already
887dd28109SEvgenii Stepanov   // been destructed, so accessing it is UB.
897dd28109SEvgenii Stepanov   //
907dd28109SEvgenii Stepanov   if (!materialized_use_empty()) {
91ef860a24SChandler Carruth     dbgs() << "While deleting: " << *VTy << " %" << getName() << "\n";
92b93fb82bSAndrew Kaylor     for (auto *U : users())
93b93fb82bSAndrew Kaylor       dbgs() << "Use still stuck around after Def is destroyed:" << *U << "\n";
94ef860a24SChandler Carruth   }
95ef860a24SChandler Carruth #endif
967dd28109SEvgenii Stepanov   assert(materialized_use_empty() && "Uses remain when a value is destroyed!");
97ef860a24SChandler Carruth 
98ef860a24SChandler Carruth   // If this value is named, destroy the name.  This should not be in a symtab
99ef860a24SChandler Carruth   // at this point.
1005bf8fef5SDuncan P. N. Exon Smith   destroyValueName();
101ef860a24SChandler Carruth }
102ef860a24SChandler Carruth 
10396ab8726SReid Kleckner void Value::deleteValue() {
10496ab8726SReid Kleckner   switch (getValueID()) {
10596ab8726SReid Kleckner #define HANDLE_VALUE(Name)                                                     \
10696ab8726SReid Kleckner   case Value::Name##Val:                                                       \
10796ab8726SReid Kleckner     delete static_cast<Name *>(this);                                          \
10896ab8726SReid Kleckner     break;
10996ab8726SReid Kleckner #define HANDLE_MEMORY_VALUE(Name)                                              \
11096ab8726SReid Kleckner   case Value::Name##Val:                                                       \
11196ab8726SReid Kleckner     static_cast<DerivedUser *>(this)->DeleteValue(                             \
11296ab8726SReid Kleckner         static_cast<DerivedUser *>(this));                                     \
11396ab8726SReid Kleckner     break;
11496ab8726SReid Kleckner #define HANDLE_INSTRUCTION(Name)  /* nothing */
11596ab8726SReid Kleckner #include "llvm/IR/Value.def"
11696ab8726SReid Kleckner 
11796ab8726SReid Kleckner #define HANDLE_INST(N, OPC, CLASS)                                             \
11896ab8726SReid Kleckner   case Value::InstructionVal + Instruction::OPC:                               \
11996ab8726SReid Kleckner     delete static_cast<CLASS *>(this);                                         \
12096ab8726SReid Kleckner     break;
12196ab8726SReid Kleckner #define HANDLE_USER_INST(N, OPC, CLASS)
12296ab8726SReid Kleckner #include "llvm/IR/Instruction.def"
12396ab8726SReid Kleckner 
12496ab8726SReid Kleckner   default:
12596ab8726SReid Kleckner     llvm_unreachable("attempting to delete unknown value kind");
12696ab8726SReid Kleckner   }
12796ab8726SReid Kleckner }
12896ab8726SReid Kleckner 
1295bf8fef5SDuncan P. N. Exon Smith void Value::destroyValueName() {
1305bf8fef5SDuncan P. N. Exon Smith   ValueName *Name = getValueName();
1315bf8fef5SDuncan P. N. Exon Smith   if (Name)
1325bf8fef5SDuncan P. N. Exon Smith     Name->Destroy();
1335bf8fef5SDuncan P. N. Exon Smith   setValueName(nullptr);
1345bf8fef5SDuncan P. N. Exon Smith }
1355bf8fef5SDuncan P. N. Exon Smith 
136ef860a24SChandler Carruth bool Value::hasNUses(unsigned N) const {
1374de31bbaSVedant Kumar   return hasNItems(use_begin(), use_end(), N);
138ef860a24SChandler Carruth }
139ef860a24SChandler Carruth 
140ef860a24SChandler Carruth bool Value::hasNUsesOrMore(unsigned N) const {
1414de31bbaSVedant Kumar   return hasNItemsOrMore(use_begin(), use_end(), N);
142ef860a24SChandler Carruth }
143ef860a24SChandler Carruth 
144f16f139dSTyker static bool isUnDroppableUser(const User *U) { return !U->isDroppable(); }
145f16f139dSTyker 
146f16f139dSTyker Use *Value::getSingleUndroppableUse() {
147f16f139dSTyker   Use *Result = nullptr;
148f16f139dSTyker   for (Use &U : uses()) {
149f16f139dSTyker     if (!U.getUser()->isDroppable()) {
150f16f139dSTyker       if (Result)
151f16f139dSTyker         return nullptr;
152f16f139dSTyker       Result = &U;
153f16f139dSTyker     }
154f16f139dSTyker   }
155f16f139dSTyker   return Result;
156f16f139dSTyker }
157f16f139dSTyker 
158f16f139dSTyker bool Value::hasNUndroppableUses(unsigned int N) const {
159f16f139dSTyker   return hasNItems(user_begin(), user_end(), N, isUnDroppableUser);
160f16f139dSTyker }
161f16f139dSTyker 
162f16f139dSTyker bool Value::hasNUndroppableUsesOrMore(unsigned int N) const {
163f16f139dSTyker   return hasNItemsOrMore(user_begin(), user_end(), N, isUnDroppableUser);
164f16f139dSTyker }
165f16f139dSTyker 
166f16f139dSTyker void Value::dropDroppableUses(
167f16f139dSTyker     llvm::function_ref<bool(const Use *)> ShouldDrop) {
168f16f139dSTyker   SmallVector<Use *, 8> ToBeEdited;
169f16f139dSTyker   for (Use &U : uses())
170f16f139dSTyker     if (U.getUser()->isDroppable() && ShouldDrop(&U))
171f16f139dSTyker       ToBeEdited.push_back(&U);
172f16f139dSTyker   for (Use *U : ToBeEdited) {
173f16f139dSTyker     U->removeFromList();
174f16f139dSTyker     if (auto *Assume = dyn_cast<IntrinsicInst>(U->getUser())) {
175f16f139dSTyker       assert(Assume->getIntrinsicID() == Intrinsic::assume);
176f16f139dSTyker       unsigned OpNo = U->getOperandNo();
177f16f139dSTyker       if (OpNo == 0)
178f16f139dSTyker         Assume->setOperand(0, ConstantInt::getTrue(Assume->getContext()));
179f16f139dSTyker       else {
180f16f139dSTyker         Assume->setOperand(OpNo, UndefValue::get(U->get()->getType()));
181f16f139dSTyker         CallInst::BundleOpInfo &BOI = Assume->getBundleOpInfoForOperand(OpNo);
182f16f139dSTyker         BOI.Tag = getContext().pImpl->getOrInsertBundleTag("ignore");
183f16f139dSTyker       }
184f16f139dSTyker     } else
185f16f139dSTyker       llvm_unreachable("unkown droppable use");
186f16f139dSTyker   }
187f16f139dSTyker }
188f16f139dSTyker 
189ef860a24SChandler Carruth bool Value::isUsedInBasicBlock(const BasicBlock *BB) const {
1900925b24dSJakob Stoklund Olesen   // This can be computed either by scanning the instructions in BB, or by
1910925b24dSJakob Stoklund Olesen   // scanning the use list of this Value. Both lists can be very long, but
1920925b24dSJakob Stoklund Olesen   // usually one is quite short.
1930925b24dSJakob Stoklund Olesen   //
1940925b24dSJakob Stoklund Olesen   // Scan both lists simultaneously until one is exhausted. This limits the
1950925b24dSJakob Stoklund Olesen   // search to the shorter list.
1960925b24dSJakob Stoklund Olesen   BasicBlock::const_iterator BI = BB->begin(), BE = BB->end();
197cdf47884SChandler Carruth   const_user_iterator UI = user_begin(), UE = user_end();
1980925b24dSJakob Stoklund Olesen   for (; BI != BE && UI != UE; ++BI, ++UI) {
1990925b24dSJakob Stoklund Olesen     // Scan basic block: Check if this Value is used by the instruction at BI.
20042531260SDavid Majnemer     if (is_contained(BI->operands(), this))
201ef860a24SChandler Carruth       return true;
2020925b24dSJakob Stoklund Olesen     // Scan use list: Check if the use at UI is in BB.
20342531260SDavid Majnemer     const auto *User = dyn_cast<Instruction>(*UI);
204ef860a24SChandler Carruth     if (User && User->getParent() == BB)
205ef860a24SChandler Carruth       return true;
206ef860a24SChandler Carruth   }
207ef860a24SChandler Carruth   return false;
208ef860a24SChandler Carruth }
209ef860a24SChandler Carruth 
2105a0872c2SVedant Kumar unsigned Value::getNumUses() const {
2115a0872c2SVedant Kumar   return (unsigned)std::distance(use_begin(), use_end());
2125a0872c2SVedant Kumar }
213ef860a24SChandler Carruth 
214ef860a24SChandler Carruth static bool getSymTab(Value *V, ValueSymbolTable *&ST) {
215c620761cSCraig Topper   ST = nullptr;
216ef860a24SChandler Carruth   if (Instruction *I = dyn_cast<Instruction>(V)) {
217ef860a24SChandler Carruth     if (BasicBlock *P = I->getParent())
218ef860a24SChandler Carruth       if (Function *PP = P->getParent())
219a53d49e1SMehdi Amini         ST = PP->getValueSymbolTable();
220ef860a24SChandler Carruth   } else if (BasicBlock *BB = dyn_cast<BasicBlock>(V)) {
221ef860a24SChandler Carruth     if (Function *P = BB->getParent())
222a53d49e1SMehdi Amini       ST = P->getValueSymbolTable();
223ef860a24SChandler Carruth   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
224ef860a24SChandler Carruth     if (Module *P = GV->getParent())
225ef860a24SChandler Carruth       ST = &P->getValueSymbolTable();
226ef860a24SChandler Carruth   } else if (Argument *A = dyn_cast<Argument>(V)) {
227ef860a24SChandler Carruth     if (Function *P = A->getParent())
228a53d49e1SMehdi Amini       ST = P->getValueSymbolTable();
2295bf8fef5SDuncan P. N. Exon Smith   } else {
230ef860a24SChandler Carruth     assert(isa<Constant>(V) && "Unknown value type!");
231ef860a24SChandler Carruth     return true;  // no name is setable for this.
232ef860a24SChandler Carruth   }
233ef860a24SChandler Carruth   return false;
234ef860a24SChandler Carruth }
235ef860a24SChandler Carruth 
2367349ab93SOwen Anderson ValueName *Value::getValueName() const {
2377349ab93SOwen Anderson   if (!HasName) return nullptr;
2387349ab93SOwen Anderson 
2397349ab93SOwen Anderson   LLVMContext &Ctx = getContext();
2407349ab93SOwen Anderson   auto I = Ctx.pImpl->ValueNames.find(this);
2417349ab93SOwen Anderson   assert(I != Ctx.pImpl->ValueNames.end() &&
2427349ab93SOwen Anderson          "No name entry found!");
2437349ab93SOwen Anderson 
2447349ab93SOwen Anderson   return I->second;
2457349ab93SOwen Anderson }
2467349ab93SOwen Anderson 
2477349ab93SOwen Anderson void Value::setValueName(ValueName *VN) {
2487349ab93SOwen Anderson   LLVMContext &Ctx = getContext();
2497349ab93SOwen Anderson 
2507349ab93SOwen Anderson   assert(HasName == Ctx.pImpl->ValueNames.count(this) &&
2517349ab93SOwen Anderson          "HasName bit out of sync!");
2527349ab93SOwen Anderson 
2537349ab93SOwen Anderson   if (!VN) {
2547349ab93SOwen Anderson     if (HasName)
2557349ab93SOwen Anderson       Ctx.pImpl->ValueNames.erase(this);
2567349ab93SOwen Anderson     HasName = false;
2577349ab93SOwen Anderson     return;
2587349ab93SOwen Anderson   }
2597349ab93SOwen Anderson 
2607349ab93SOwen Anderson   HasName = true;
2617349ab93SOwen Anderson   Ctx.pImpl->ValueNames[this] = VN;
2627349ab93SOwen Anderson }
2637349ab93SOwen Anderson 
264ef860a24SChandler Carruth StringRef Value::getName() const {
265ef860a24SChandler Carruth   // Make sure the empty string is still a C string. For historical reasons,
266ef860a24SChandler Carruth   // some clients want to call .data() on the result and expect it to be null
267ef860a24SChandler Carruth   // terminated.
2687349ab93SOwen Anderson   if (!hasName())
2695bf8fef5SDuncan P. N. Exon Smith     return StringRef("", 0);
2705bf8fef5SDuncan P. N. Exon Smith   return getValueName()->getKey();
271ef860a24SChandler Carruth }
272ef860a24SChandler Carruth 
273a7c0c18cSPete Cooper void Value::setNameImpl(const Twine &NewName) {
27409b4a8daSMehdi Amini   // Fast-path: LLVMContext can be set to strip out non-GlobalValue names
27550af49fcSMehdi Amini   if (getContext().shouldDiscardValueNames() && !isa<GlobalValue>(this))
27609b4a8daSMehdi Amini     return;
27709b4a8daSMehdi Amini 
278ef860a24SChandler Carruth   // Fast path for common IRBuilder case of setName("") when there is no name.
279ef860a24SChandler Carruth   if (NewName.isTriviallyEmpty() && !hasName())
280ef860a24SChandler Carruth     return;
281ef860a24SChandler Carruth 
282ef860a24SChandler Carruth   SmallString<256> NameData;
283ef860a24SChandler Carruth   StringRef NameRef = NewName.toStringRef(NameData);
28409d689f9SRafael Espindola   assert(NameRef.find_first_of(0) == StringRef::npos &&
28509d689f9SRafael Espindola          "Null bytes are not allowed in names");
286ef860a24SChandler Carruth 
287ef860a24SChandler Carruth   // Name isn't changing?
288ef860a24SChandler Carruth   if (getName() == NameRef)
289ef860a24SChandler Carruth     return;
290ef860a24SChandler Carruth 
2914c975578SSerge Guelton   // Cap the size of non-GlobalValue names.
2924c975578SSerge Guelton   if (NameRef.size() > NonGlobalValueMaxNameSize && !isa<GlobalValue>(this))
2934c975578SSerge Guelton     NameRef =
2944c975578SSerge Guelton         NameRef.substr(0, std::max(1u, (unsigned)NonGlobalValueMaxNameSize));
2954c975578SSerge Guelton 
296ef860a24SChandler Carruth   assert(!getType()->isVoidTy() && "Cannot assign a name to void values!");
297ef860a24SChandler Carruth 
298ef860a24SChandler Carruth   // Get the symbol table to update for this object.
299ef860a24SChandler Carruth   ValueSymbolTable *ST;
300ef860a24SChandler Carruth   if (getSymTab(this, ST))
301ef860a24SChandler Carruth     return;  // Cannot set a name on this value (e.g. constant).
302ef860a24SChandler Carruth 
303ef860a24SChandler Carruth   if (!ST) { // No symbol table to update?  Just do the change.
304ef860a24SChandler Carruth     if (NameRef.empty()) {
305ef860a24SChandler Carruth       // Free the name for this value.
3065bf8fef5SDuncan P. N. Exon Smith       destroyValueName();
307ef860a24SChandler Carruth       return;
308ef860a24SChandler Carruth     }
309ef860a24SChandler Carruth 
310ef860a24SChandler Carruth     // NOTE: Could optimize for the case the name is shrinking to not deallocate
311ef860a24SChandler Carruth     // then reallocated.
3125bf8fef5SDuncan P. N. Exon Smith     destroyValueName();
313ef860a24SChandler Carruth 
314ef860a24SChandler Carruth     // Create the new name.
3155bf8fef5SDuncan P. N. Exon Smith     setValueName(ValueName::Create(NameRef));
3165bf8fef5SDuncan P. N. Exon Smith     getValueName()->setValue(this);
317ef860a24SChandler Carruth     return;
318ef860a24SChandler Carruth   }
319ef860a24SChandler Carruth 
320ef860a24SChandler Carruth   // NOTE: Could optimize for the case the name is shrinking to not deallocate
321ef860a24SChandler Carruth   // then reallocated.
322ef860a24SChandler Carruth   if (hasName()) {
323ef860a24SChandler Carruth     // Remove old name.
3245bf8fef5SDuncan P. N. Exon Smith     ST->removeValueName(getValueName());
3255bf8fef5SDuncan P. N. Exon Smith     destroyValueName();
326ef860a24SChandler Carruth 
327ef860a24SChandler Carruth     if (NameRef.empty())
328ef860a24SChandler Carruth       return;
329ef860a24SChandler Carruth   }
330ef860a24SChandler Carruth 
331ef860a24SChandler Carruth   // Name is changing to something new.
3325bf8fef5SDuncan P. N. Exon Smith   setValueName(ST->createValueName(NameRef, this));
333ef860a24SChandler Carruth }
334ef860a24SChandler Carruth 
335a7c0c18cSPete Cooper void Value::setName(const Twine &NewName) {
336a7c0c18cSPete Cooper   setNameImpl(NewName);
337a7c0c18cSPete Cooper   if (Function *F = dyn_cast<Function>(this))
338a7c0c18cSPete Cooper     F->recalculateIntrinsicID();
339a7c0c18cSPete Cooper }
340a7c0c18cSPete Cooper 
341ef860a24SChandler Carruth void Value::takeName(Value *V) {
342c620761cSCraig Topper   ValueSymbolTable *ST = nullptr;
343ef860a24SChandler Carruth   // If this value has a name, drop it.
344ef860a24SChandler Carruth   if (hasName()) {
345ef860a24SChandler Carruth     // Get the symtab this is in.
346ef860a24SChandler Carruth     if (getSymTab(this, ST)) {
347ef860a24SChandler Carruth       // We can't set a name on this value, but we need to clear V's name if
348ef860a24SChandler Carruth       // it has one.
349ef860a24SChandler Carruth       if (V->hasName()) V->setName("");
350ef860a24SChandler Carruth       return;  // Cannot set a name on this value (e.g. constant).
351ef860a24SChandler Carruth     }
352ef860a24SChandler Carruth 
353ef860a24SChandler Carruth     // Remove old name.
354ef860a24SChandler Carruth     if (ST)
3555bf8fef5SDuncan P. N. Exon Smith       ST->removeValueName(getValueName());
3565bf8fef5SDuncan P. N. Exon Smith     destroyValueName();
357ef860a24SChandler Carruth   }
358ef860a24SChandler Carruth 
359ef860a24SChandler Carruth   // Now we know that this has no name.
360ef860a24SChandler Carruth 
361ef860a24SChandler Carruth   // If V has no name either, we're done.
362ef860a24SChandler Carruth   if (!V->hasName()) return;
363ef860a24SChandler Carruth 
364ef860a24SChandler Carruth   // Get this's symtab if we didn't before.
365ef860a24SChandler Carruth   if (!ST) {
366ef860a24SChandler Carruth     if (getSymTab(this, ST)) {
367ef860a24SChandler Carruth       // Clear V's name.
368ef860a24SChandler Carruth       V->setName("");
369ef860a24SChandler Carruth       return;  // Cannot set a name on this value (e.g. constant).
370ef860a24SChandler Carruth     }
371ef860a24SChandler Carruth   }
372ef860a24SChandler Carruth 
373ef860a24SChandler Carruth   // Get V's ST, this should always succed, because V has a name.
374ef860a24SChandler Carruth   ValueSymbolTable *VST;
375ef860a24SChandler Carruth   bool Failure = getSymTab(V, VST);
376ef860a24SChandler Carruth   assert(!Failure && "V has a name, so it should have a ST!"); (void)Failure;
377ef860a24SChandler Carruth 
378ef860a24SChandler Carruth   // If these values are both in the same symtab, we can do this very fast.
379ef860a24SChandler Carruth   // This works even if both values have no symtab yet.
380ef860a24SChandler Carruth   if (ST == VST) {
381ef860a24SChandler Carruth     // Take the name!
3825bf8fef5SDuncan P. N. Exon Smith     setValueName(V->getValueName());
3835bf8fef5SDuncan P. N. Exon Smith     V->setValueName(nullptr);
3845bf8fef5SDuncan P. N. Exon Smith     getValueName()->setValue(this);
385ef860a24SChandler Carruth     return;
386ef860a24SChandler Carruth   }
387ef860a24SChandler Carruth 
388ef860a24SChandler Carruth   // Otherwise, things are slightly more complex.  Remove V's name from VST and
389ef860a24SChandler Carruth   // then reinsert it into ST.
390ef860a24SChandler Carruth 
391ef860a24SChandler Carruth   if (VST)
3925bf8fef5SDuncan P. N. Exon Smith     VST->removeValueName(V->getValueName());
3935bf8fef5SDuncan P. N. Exon Smith   setValueName(V->getValueName());
3945bf8fef5SDuncan P. N. Exon Smith   V->setValueName(nullptr);
3955bf8fef5SDuncan P. N. Exon Smith   getValueName()->setValue(this);
396ef860a24SChandler Carruth 
397ef860a24SChandler Carruth   if (ST)
398ef860a24SChandler Carruth     ST->reinsertValue(this);
399ef860a24SChandler Carruth }
400ef860a24SChandler Carruth 
401eec48903SCraig Topper void Value::assertModuleIsMaterializedImpl() const {
402675bdcedSTodd Fiala #ifndef NDEBUG
403257a3536SRafael Espindola   const GlobalValue *GV = dyn_cast<GlobalValue>(this);
404257a3536SRafael Espindola   if (!GV)
405257a3536SRafael Espindola     return;
406257a3536SRafael Espindola   const Module *M = GV->getParent();
407257a3536SRafael Espindola   if (!M)
408257a3536SRafael Espindola     return;
409257a3536SRafael Espindola   assert(M->isMaterialized());
410675bdcedSTodd Fiala #endif
411257a3536SRafael Espindola }
412257a3536SRafael Espindola 
413675bdcedSTodd Fiala #ifndef NDEBUG
41471b7b68bSCraig Topper static bool contains(SmallPtrSetImpl<ConstantExpr *> &Cache, ConstantExpr *Expr,
4157e2b7567SRafael Espindola                      Constant *C) {
41670573dcdSDavid Blaikie   if (!Cache.insert(Expr).second)
4177e2b7567SRafael Espindola     return false;
4187e2b7567SRafael Espindola 
4197e2b7567SRafael Espindola   for (auto &O : Expr->operands()) {
4207e2b7567SRafael Espindola     if (O == C)
4217e2b7567SRafael Espindola       return true;
4227e2b7567SRafael Espindola     auto *CE = dyn_cast<ConstantExpr>(O);
4237e2b7567SRafael Espindola     if (!CE)
4247e2b7567SRafael Espindola       continue;
4257e2b7567SRafael Espindola     if (contains(Cache, CE, C))
4267e2b7567SRafael Espindola       return true;
4277e2b7567SRafael Espindola   }
4287e2b7567SRafael Espindola   return false;
4297e2b7567SRafael Espindola }
4307e2b7567SRafael Espindola 
4317e2b7567SRafael Espindola static bool contains(Value *Expr, Value *V) {
4327e2b7567SRafael Espindola   if (Expr == V)
4337e2b7567SRafael Espindola     return true;
4347e2b7567SRafael Espindola 
4357e2b7567SRafael Espindola   auto *C = dyn_cast<Constant>(V);
4367e2b7567SRafael Espindola   if (!C)
4377e2b7567SRafael Espindola     return false;
4387e2b7567SRafael Espindola 
4397e2b7567SRafael Espindola   auto *CE = dyn_cast<ConstantExpr>(Expr);
4407e2b7567SRafael Espindola   if (!CE)
4417e2b7567SRafael Espindola     return false;
4427e2b7567SRafael Espindola 
4437e2b7567SRafael Espindola   SmallPtrSet<ConstantExpr *, 4> Cache;
4447e2b7567SRafael Espindola   return contains(Cache, CE, C);
4457e2b7567SRafael Espindola }
446ecefe5a8SEugene Zelenko #endif // NDEBUG
447ef860a24SChandler Carruth 
448e69ae76bSJF Bastien void Value::doRAUW(Value *New, ReplaceMetadataUses ReplaceMetaUses) {
449ef860a24SChandler Carruth   assert(New && "Value::replaceAllUsesWith(<null>) is invalid!");
4507e2b7567SRafael Espindola   assert(!contains(New, this) &&
4517e2b7567SRafael Espindola          "this->replaceAllUsesWith(expr(this)) is NOT valid!");
452ef860a24SChandler Carruth   assert(New->getType() == getType() &&
453ef860a24SChandler Carruth          "replaceAllUses of value with new value of different type!");
454ef860a24SChandler Carruth 
455ef860a24SChandler Carruth   // Notify all ValueHandles (if present) that this value is going away.
456ef860a24SChandler Carruth   if (HasValueHandle)
457ef860a24SChandler Carruth     ValueHandleBase::ValueIsRAUWd(this, New);
458e69ae76bSJF Bastien   if (ReplaceMetaUses == ReplaceMetadataUses::Yes && isUsedByMetadata())
4595bf8fef5SDuncan P. N. Exon Smith     ValueAsMetadata::handleRAUW(this, New);
460ef860a24SChandler Carruth 
46181bbf742STeresa Johnson   while (!materialized_use_empty()) {
462ef860a24SChandler Carruth     Use &U = *UseList;
463ef860a24SChandler Carruth     // Must handle Constants specially, we cannot call replaceUsesOfWith on a
464ef860a24SChandler Carruth     // constant because they are uniqued.
4656b238633SRafael Espindola     if (auto *C = dyn_cast<Constant>(U.getUser())) {
466ef860a24SChandler Carruth       if (!isa<GlobalValue>(C)) {
4678914d290SMehdi Amini         C->handleOperandChange(this, New);
468ef860a24SChandler Carruth         continue;
469ef860a24SChandler Carruth       }
470ef860a24SChandler Carruth     }
471ef860a24SChandler Carruth 
472ef860a24SChandler Carruth     U.set(New);
473ef860a24SChandler Carruth   }
474ef860a24SChandler Carruth 
475ef860a24SChandler Carruth   if (BasicBlock *BB = dyn_cast<BasicBlock>(this))
476ef860a24SChandler Carruth     BB->replaceSuccessorsPhiUsesWith(cast<BasicBlock>(New));
477ef860a24SChandler Carruth }
478ef860a24SChandler Carruth 
4791ed53963SDavide Italiano void Value::replaceAllUsesWith(Value *New) {
480e69ae76bSJF Bastien   doRAUW(New, ReplaceMetadataUses::Yes);
4811ed53963SDavide Italiano }
4821ed53963SDavide Italiano 
4831ed53963SDavide Italiano void Value::replaceNonMetadataUsesWith(Value *New) {
484e69ae76bSJF Bastien   doRAUW(New, ReplaceMetadataUses::No);
4851ed53963SDavide Italiano }
4861ed53963SDavide Italiano 
487ec6217c9SGerolf Hoflehner // Like replaceAllUsesWith except it does not handle constants or basic blocks.
488ec6217c9SGerolf Hoflehner // This routine leaves uses within BB.
489ec6217c9SGerolf Hoflehner void Value::replaceUsesOutsideBlock(Value *New, BasicBlock *BB) {
490ec6217c9SGerolf Hoflehner   assert(New && "Value::replaceUsesOutsideBlock(<null>, BB) is invalid!");
491ec6217c9SGerolf Hoflehner   assert(!contains(New, this) &&
492ec6217c9SGerolf Hoflehner          "this->replaceUsesOutsideBlock(expr(this), BB) is NOT valid!");
493ec6217c9SGerolf Hoflehner   assert(New->getType() == getType() &&
494ec6217c9SGerolf Hoflehner          "replaceUses of value with new value of different type!");
495ec6217c9SGerolf Hoflehner   assert(BB && "Basic block that may contain a use of 'New' must be defined\n");
496ec6217c9SGerolf Hoflehner 
497081e990dSRoman Lebedev   replaceUsesWithIf(New, [BB](Use &U) {
498081e990dSRoman Lebedev     auto *I = dyn_cast<Instruction>(U.getUser());
499081e990dSRoman Lebedev     // Don't replace if it's an instruction in the BB basic block.
500081e990dSRoman Lebedev     return !I || I->getParent() != BB;
501081e990dSRoman Lebedev   });
502ec6217c9SGerolf Hoflehner }
503ec6217c9SGerolf Hoflehner 
504ef860a24SChandler Carruth namespace {
505ef860a24SChandler Carruth // Various metrics for how much to strip off of pointers.
506ef860a24SChandler Carruth enum PointerStripKind {
507ef860a24SChandler Carruth   PSK_ZeroIndices,
5088a410bceSErich Keane   PSK_ZeroIndicesAndAliases,
5092452d703SPeter Collingbourne   PSK_ZeroIndicesSameRepresentation,
5102452d703SPeter Collingbourne   PSK_ZeroIndicesAndInvariantGroups,
511ef860a24SChandler Carruth   PSK_InBoundsConstantIndices,
512ef860a24SChandler Carruth   PSK_InBounds
513ef860a24SChandler Carruth };
514ef860a24SChandler Carruth 
515ef860a24SChandler Carruth template <PointerStripKind StripKind>
5161dd20e65SCraig Topper static const Value *stripPointerCastsAndOffsets(const Value *V) {
517ef860a24SChandler Carruth   if (!V->getType()->isPointerTy())
518ef860a24SChandler Carruth     return V;
519ef860a24SChandler Carruth 
520ef860a24SChandler Carruth   // Even though we don't look through PHI nodes, we could be called on an
521ef860a24SChandler Carruth   // instruction in an unreachable block, which may be on a cycle.
5221dd20e65SCraig Topper   SmallPtrSet<const Value *, 4> Visited;
523ef860a24SChandler Carruth 
524ef860a24SChandler Carruth   Visited.insert(V);
525ef860a24SChandler Carruth   do {
5261dd20e65SCraig Topper     if (auto *GEP = dyn_cast<GEPOperator>(V)) {
527ef860a24SChandler Carruth       switch (StripKind) {
528ef860a24SChandler Carruth       case PSK_ZeroIndices:
5298a410bceSErich Keane       case PSK_ZeroIndicesAndAliases:
5302452d703SPeter Collingbourne       case PSK_ZeroIndicesSameRepresentation:
5312452d703SPeter Collingbourne       case PSK_ZeroIndicesAndInvariantGroups:
532ef860a24SChandler Carruth         if (!GEP->hasAllZeroIndices())
533ef860a24SChandler Carruth           return V;
534ef860a24SChandler Carruth         break;
535ef860a24SChandler Carruth       case PSK_InBoundsConstantIndices:
536ef860a24SChandler Carruth         if (!GEP->hasAllConstantIndices())
537ef860a24SChandler Carruth           return V;
538b03fd12cSJustin Bogner         LLVM_FALLTHROUGH;
539ef860a24SChandler Carruth       case PSK_InBounds:
540ef860a24SChandler Carruth         if (!GEP->isInBounds())
541ef860a24SChandler Carruth           return V;
542ef860a24SChandler Carruth         break;
543ef860a24SChandler Carruth       }
544ef860a24SChandler Carruth       V = GEP->getPointerOperand();
54540107ce7SJohannes Doerfert     } else if (Operator::getOpcode(V) == Instruction::BitCast) {
54640107ce7SJohannes Doerfert       V = cast<Operator>(V)->getOperand(0);
5472452d703SPeter Collingbourne     } else if (StripKind != PSK_ZeroIndicesSameRepresentation &&
548b03bd4d9SMatt Arsenault                Operator::getOpcode(V) == Instruction::AddrSpaceCast) {
54940107ce7SJohannes Doerfert       // TODO: If we know an address space cast will not change the
55040107ce7SJohannes Doerfert       //       representation we could look through it here as well.
551ef860a24SChandler Carruth       V = cast<Operator>(V)->getOperand(0);
5528a410bceSErich Keane     } else if (StripKind == PSK_ZeroIndicesAndAliases && isa<GlobalAlias>(V)) {
5538a410bceSErich Keane       V = cast<GlobalAlias>(V)->getAliasee();
554ef860a24SChandler Carruth     } else {
55590c09232SChandler Carruth       if (const auto *Call = dyn_cast<CallBase>(V)) {
55690c09232SChandler Carruth         if (const Value *RV = Call->getReturnedArgOperand()) {
5575c12d8feSHal Finkel           V = RV;
5585c12d8feSHal Finkel           continue;
5595c12d8feSHal Finkel         }
5605dde8094SPiotr Padlewski         // The result of launder.invariant.group must alias it's argument,
561610c966aSPiotr Padlewski         // but it can't be marked with returned attribute, that's why it needs
562610c966aSPiotr Padlewski         // special case.
5632452d703SPeter Collingbourne         if (StripKind == PSK_ZeroIndicesAndInvariantGroups &&
56490c09232SChandler Carruth             (Call->getIntrinsicID() == Intrinsic::launder_invariant_group ||
56590c09232SChandler Carruth              Call->getIntrinsicID() == Intrinsic::strip_invariant_group)) {
56690c09232SChandler Carruth           V = Call->getArgOperand(0);
567610c966aSPiotr Padlewski           continue;
568610c966aSPiotr Padlewski         }
569610c966aSPiotr Padlewski       }
570ef860a24SChandler Carruth       return V;
571ef860a24SChandler Carruth     }
572ef860a24SChandler Carruth     assert(V->getType()->isPointerTy() && "Unexpected operand type!");
57370573dcdSDavid Blaikie   } while (Visited.insert(V).second);
574ef860a24SChandler Carruth 
575ef860a24SChandler Carruth   return V;
576ef860a24SChandler Carruth }
577ecefe5a8SEugene Zelenko } // end anonymous namespace
578ef860a24SChandler Carruth 
5791dd20e65SCraig Topper const Value *Value::stripPointerCasts() const {
5802452d703SPeter Collingbourne   return stripPointerCastsAndOffsets<PSK_ZeroIndices>(this);
581c229a4ffSRafael Espindola }
582c229a4ffSRafael Espindola 
5838a410bceSErich Keane const Value *Value::stripPointerCastsAndAliases() const {
5848a410bceSErich Keane   return stripPointerCastsAndOffsets<PSK_ZeroIndicesAndAliases>(this);
5858a410bceSErich Keane }
5868a410bceSErich Keane 
58740107ce7SJohannes Doerfert const Value *Value::stripPointerCastsSameRepresentation() const {
5882452d703SPeter Collingbourne   return stripPointerCastsAndOffsets<PSK_ZeroIndicesSameRepresentation>(this);
589ef860a24SChandler Carruth }
590ef860a24SChandler Carruth 
5911dd20e65SCraig Topper const Value *Value::stripInBoundsConstantOffsets() const {
592ef860a24SChandler Carruth   return stripPointerCastsAndOffsets<PSK_InBoundsConstantIndices>(this);
593ef860a24SChandler Carruth }
594ef860a24SChandler Carruth 
5955dde8094SPiotr Padlewski const Value *Value::stripPointerCastsAndInvariantGroups() const {
5962452d703SPeter Collingbourne   return stripPointerCastsAndOffsets<PSK_ZeroIndicesAndInvariantGroups>(this);
597610c966aSPiotr Padlewski }
598610c966aSPiotr Padlewski 
5991dd20e65SCraig Topper const Value *
6003ed286a3SJohannes Doerfert Value::stripAndAccumulateConstantOffsets(const DataLayout &DL, APInt &Offset,
6013ed286a3SJohannes Doerfert                                          bool AllowNonInbounds) const {
6023ed286a3SJohannes Doerfert   if (!getType()->isPtrOrPtrVectorTy())
603989e6308SChandler Carruth     return this;
604989e6308SChandler Carruth 
6053ed286a3SJohannes Doerfert   unsigned BitWidth = Offset.getBitWidth();
6063ed286a3SJohannes Doerfert   assert(BitWidth == DL.getIndexTypeSizeInBits(getType()) &&
607945b7e5aSElena Demikhovsky          "The offset bit width does not match the DL specification.");
608989e6308SChandler Carruth 
609989e6308SChandler Carruth   // Even though we don't look through PHI nodes, we could be called on an
610989e6308SChandler Carruth   // instruction in an unreachable block, which may be on a cycle.
6111dd20e65SCraig Topper   SmallPtrSet<const Value *, 4> Visited;
612989e6308SChandler Carruth   Visited.insert(this);
6131dd20e65SCraig Topper   const Value *V = this;
614989e6308SChandler Carruth   do {
6151dd20e65SCraig Topper     if (auto *GEP = dyn_cast<GEPOperator>(V)) {
6163ed286a3SJohannes Doerfert       // If in-bounds was requested, we do not strip non-in-bounds GEPs.
6173ed286a3SJohannes Doerfert       if (!AllowNonInbounds && !GEP->isInBounds())
618989e6308SChandler Carruth         return V;
6193ed286a3SJohannes Doerfert 
6203ed286a3SJohannes Doerfert       // If one of the values we have visited is an addrspacecast, then
6213ed286a3SJohannes Doerfert       // the pointer type of this GEP may be different from the type
6223ed286a3SJohannes Doerfert       // of the Ptr parameter which was passed to this function.  This
6233ed286a3SJohannes Doerfert       // means when we construct GEPOffset, we need to use the size
6243ed286a3SJohannes Doerfert       // of GEP's pointer type rather than the size of the original
6253ed286a3SJohannes Doerfert       // pointer type.
6263ed286a3SJohannes Doerfert       APInt GEPOffset(DL.getIndexTypeSizeInBits(V->getType()), 0);
627ba689b33SChandler Carruth       if (!GEP->accumulateConstantOffset(DL, GEPOffset))
628989e6308SChandler Carruth         return V;
6293ed286a3SJohannes Doerfert 
6303ed286a3SJohannes Doerfert       // Stop traversal if the pointer offset wouldn't fit in the bit-width
6313ed286a3SJohannes Doerfert       // provided by the Offset argument. This can happen due to AddrSpaceCast
6323ed286a3SJohannes Doerfert       // stripping.
6333ed286a3SJohannes Doerfert       if (GEPOffset.getMinSignedBits() > BitWidth)
6343ed286a3SJohannes Doerfert         return V;
6353ed286a3SJohannes Doerfert 
6363ed286a3SJohannes Doerfert       Offset += GEPOffset.sextOrTrunc(BitWidth);
637989e6308SChandler Carruth       V = GEP->getPointerOperand();
6383ed286a3SJohannes Doerfert     } else if (Operator::getOpcode(V) == Instruction::BitCast ||
6393ed286a3SJohannes Doerfert                Operator::getOpcode(V) == Instruction::AddrSpaceCast) {
640989e6308SChandler Carruth       V = cast<Operator>(V)->getOperand(0);
6411dd20e65SCraig Topper     } else if (auto *GA = dyn_cast<GlobalAlias>(V)) {
6423ed286a3SJohannes Doerfert       if (!GA->isInterposable())
643989e6308SChandler Carruth         V = GA->getAliasee();
6443ed286a3SJohannes Doerfert     } else if (const auto *Call = dyn_cast<CallBase>(V)) {
6453ed286a3SJohannes Doerfert         if (const Value *RV = Call->getReturnedArgOperand())
6465c12d8feSHal Finkel           V = RV;
6475c12d8feSHal Finkel     }
6483ed286a3SJohannes Doerfert     assert(V->getType()->isPtrOrPtrVectorTy() && "Unexpected operand type!");
64970573dcdSDavid Blaikie   } while (Visited.insert(V).second);
650989e6308SChandler Carruth 
651989e6308SChandler Carruth   return V;
652989e6308SChandler Carruth }
653989e6308SChandler Carruth 
6541dd20e65SCraig Topper const Value *Value::stripInBoundsOffsets() const {
655ef860a24SChandler Carruth   return stripPointerCastsAndOffsets<PSK_InBounds>(this);
656ef860a24SChandler Carruth }
657ef860a24SChandler Carruth 
6583603de2fSBjorn Steinbrink uint64_t Value::getPointerDereferenceableBytes(const DataLayout &DL,
65900953cbeSSanjoy Das                                                bool &CanBeNull) const {
660345f0148SArtur Pilipenko   assert(getType()->isPointerTy() && "must be pointer");
661345f0148SArtur Pilipenko 
6623603de2fSBjorn Steinbrink   uint64_t DerefBytes = 0;
663345f0148SArtur Pilipenko   CanBeNull = false;
664345f0148SArtur Pilipenko   if (const Argument *A = dyn_cast<Argument>(this)) {
665345f0148SArtur Pilipenko     DerefBytes = A->getDereferenceableBytes();
6662da4d9d8SBjorn Steinbrink     if (DerefBytes == 0 && (A->hasByValAttr() || A->hasStructRetAttr())) {
667c27f81b9SBjorn Steinbrink       Type *PT = cast<PointerType>(A->getType())->getElementType();
6682da4d9d8SBjorn Steinbrink       if (PT->isSized())
669ebec984eSEli Friedman         DerefBytes = DL.getTypeStoreSize(PT).getKnownMinSize();
67000953cbeSSanjoy Das     }
671345f0148SArtur Pilipenko     if (DerefBytes == 0) {
672345f0148SArtur Pilipenko       DerefBytes = A->getDereferenceableOrNullBytes();
673345f0148SArtur Pilipenko       CanBeNull = true;
674345f0148SArtur Pilipenko     }
67590c09232SChandler Carruth   } else if (const auto *Call = dyn_cast<CallBase>(this)) {
67690c09232SChandler Carruth     DerefBytes = Call->getDereferenceableBytes(AttributeList::ReturnIndex);
677345f0148SArtur Pilipenko     if (DerefBytes == 0) {
67890c09232SChandler Carruth       DerefBytes =
67990c09232SChandler Carruth           Call->getDereferenceableOrNullBytes(AttributeList::ReturnIndex);
680345f0148SArtur Pilipenko       CanBeNull = true;
681345f0148SArtur Pilipenko     }
682345f0148SArtur Pilipenko   } else if (const LoadInst *LI = dyn_cast<LoadInst>(this)) {
683345f0148SArtur Pilipenko     if (MDNode *MD = LI->getMetadata(LLVMContext::MD_dereferenceable)) {
684345f0148SArtur Pilipenko       ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(0));
685345f0148SArtur Pilipenko       DerefBytes = CI->getLimitedValue();
686345f0148SArtur Pilipenko     }
687345f0148SArtur Pilipenko     if (DerefBytes == 0) {
688345f0148SArtur Pilipenko       if (MDNode *MD =
689345f0148SArtur Pilipenko               LI->getMetadata(LLVMContext::MD_dereferenceable_or_null)) {
690345f0148SArtur Pilipenko         ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(0));
691345f0148SArtur Pilipenko         DerefBytes = CI->getLimitedValue();
692345f0148SArtur Pilipenko       }
693345f0148SArtur Pilipenko       CanBeNull = true;
694345f0148SArtur Pilipenko     }
6956f13637aSRyan Taylor   } else if (auto *IP = dyn_cast<IntToPtrInst>(this)) {
6966f13637aSRyan Taylor     if (MDNode *MD = IP->getMetadata(LLVMContext::MD_dereferenceable)) {
6976f13637aSRyan Taylor       ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(0));
6986f13637aSRyan Taylor       DerefBytes = CI->getLimitedValue();
6996f13637aSRyan Taylor     }
7006f13637aSRyan Taylor     if (DerefBytes == 0) {
7016f13637aSRyan Taylor       if (MDNode *MD =
7026f13637aSRyan Taylor               IP->getMetadata(LLVMContext::MD_dereferenceable_or_null)) {
7036f13637aSRyan Taylor         ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(0));
7046f13637aSRyan Taylor         DerefBytes = CI->getLimitedValue();
7056f13637aSRyan Taylor       }
7066f13637aSRyan Taylor       CanBeNull = true;
7076f13637aSRyan Taylor     }
70800953cbeSSanjoy Das   } else if (auto *AI = dyn_cast<AllocaInst>(this)) {
709030123e8SBjorn Steinbrink     if (!AI->isArrayAllocation()) {
710ebec984eSEli Friedman       DerefBytes =
711ebec984eSEli Friedman           DL.getTypeStoreSize(AI->getAllocatedType()).getKnownMinSize();
71200953cbeSSanjoy Das       CanBeNull = false;
71300953cbeSSanjoy Das     }
71400953cbeSSanjoy Das   } else if (auto *GV = dyn_cast<GlobalVariable>(this)) {
71500953cbeSSanjoy Das     if (GV->getValueType()->isSized() && !GV->hasExternalWeakLinkage()) {
71600953cbeSSanjoy Das       // TODO: Don't outright reject hasExternalWeakLinkage but set the
71700953cbeSSanjoy Das       // CanBeNull flag.
718ebec984eSEli Friedman       DerefBytes = DL.getTypeStoreSize(GV->getValueType()).getFixedSize();
71900953cbeSSanjoy Das       CanBeNull = false;
72000953cbeSSanjoy Das     }
721345f0148SArtur Pilipenko   }
722345f0148SArtur Pilipenko   return DerefBytes;
723345f0148SArtur Pilipenko }
724345f0148SArtur Pilipenko 
725bae629b9SGuillaume Chatelet MaybeAlign Value::getPointerAlignment(const DataLayout &DL) const {
726ae51afc5SArtur Pilipenko   assert(getType()->isPointerTy() && "must be pointer");
727ae51afc5SArtur Pilipenko   if (auto *GO = dyn_cast<GlobalObject>(this)) {
728308e82ecSMichael Platings     if (isa<Function>(GO)) {
72918f805a7SGuillaume Chatelet       const MaybeAlign FunctionPtrAlign = DL.getFunctionPtrAlign();
730308e82ecSMichael Platings       switch (DL.getFunctionPtrAlignType()) {
731308e82ecSMichael Platings       case DataLayout::FunctionPtrAlignType::Independent:
732bae629b9SGuillaume Chatelet         return FunctionPtrAlign;
733308e82ecSMichael Platings       case DataLayout::FunctionPtrAlignType::MultipleOfFunctionAlign:
734bae629b9SGuillaume Chatelet         return std::max(FunctionPtrAlign, MaybeAlign(GO->getAlignment()));
735308e82ecSMichael Platings       }
7366200a568SGuillaume Chatelet       llvm_unreachable("Unhandled FunctionPtrAlignType");
737308e82ecSMichael Platings     }
738bae629b9SGuillaume Chatelet     const MaybeAlign Alignment(GO->getAlignment());
739bae629b9SGuillaume Chatelet     if (!Alignment) {
740ae51afc5SArtur Pilipenko       if (auto *GVar = dyn_cast<GlobalVariable>(GO)) {
741ae51afc5SArtur Pilipenko         Type *ObjectType = GVar->getValueType();
742ae51afc5SArtur Pilipenko         if (ObjectType->isSized()) {
743ae51afc5SArtur Pilipenko           // If the object is defined in the current Module, we'll be giving
744ae51afc5SArtur Pilipenko           // it the preferred alignment. Otherwise, we have to assume that it
745ae51afc5SArtur Pilipenko           // may only have the minimum ABI alignment.
746ae51afc5SArtur Pilipenko           if (GVar->isStrongDefinitionForLinker())
747bae629b9SGuillaume Chatelet             return MaybeAlign(DL.getPreferredAlignment(GVar));
748ae51afc5SArtur Pilipenko           else
749*9068bccbSGuillaume Chatelet             return DL.getABITypeAlign(ObjectType);
750ae51afc5SArtur Pilipenko         }
751ae51afc5SArtur Pilipenko       }
752ae51afc5SArtur Pilipenko     }
753bae629b9SGuillaume Chatelet     return Alignment;
754ae51afc5SArtur Pilipenko   } else if (const Argument *A = dyn_cast<Argument>(this)) {
755*9068bccbSGuillaume Chatelet     const MaybeAlign Alignment = A->getParamAlign();
756bae629b9SGuillaume Chatelet     if (!Alignment && A->hasStructRetAttr()) {
757ae51afc5SArtur Pilipenko       // An sret parameter has at least the ABI alignment of the return type.
758ae51afc5SArtur Pilipenko       Type *EltTy = cast<PointerType>(A->getType())->getElementType();
759ae51afc5SArtur Pilipenko       if (EltTy->isSized())
760*9068bccbSGuillaume Chatelet         return DL.getABITypeAlign(EltTy);
761ae51afc5SArtur Pilipenko     }
762bae629b9SGuillaume Chatelet     return Alignment;
763c97eac65SArtur Pilipenko   } else if (const AllocaInst *AI = dyn_cast<AllocaInst>(this)) {
764*9068bccbSGuillaume Chatelet     const MaybeAlign Alignment = AI->getAlign();
765bae629b9SGuillaume Chatelet     if (!Alignment) {
766c97eac65SArtur Pilipenko       Type *AllocatedType = AI->getAllocatedType();
767c97eac65SArtur Pilipenko       if (AllocatedType->isSized())
768bae629b9SGuillaume Chatelet         return MaybeAlign(DL.getPrefTypeAlignment(AllocatedType));
769c97eac65SArtur Pilipenko     }
770bae629b9SGuillaume Chatelet     return Alignment;
771afd4a37bSHideto Ueno   } else if (const auto *Call = dyn_cast<CallBase>(this)) {
772*9068bccbSGuillaume Chatelet     const MaybeAlign Alignment = Call->getRetAlign();
773bae629b9SGuillaume Chatelet     if (!Alignment && Call->getCalledFunction())
774bae629b9SGuillaume Chatelet       return MaybeAlign(
775bae629b9SGuillaume Chatelet           Call->getCalledFunction()->getAttributes().getRetAlignment());
776bae629b9SGuillaume Chatelet     return Alignment;
7776200a568SGuillaume Chatelet   } else if (const LoadInst *LI = dyn_cast<LoadInst>(this)) {
778ae51afc5SArtur Pilipenko     if (MDNode *MD = LI->getMetadata(LLVMContext::MD_align)) {
779ae51afc5SArtur Pilipenko       ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(0));
780bae629b9SGuillaume Chatelet       return MaybeAlign(CI->getLimitedValue());
781ae51afc5SArtur Pilipenko     }
782a6492e22SRoman Lebedev   } else if (auto *CstPtr = dyn_cast<Constant>(this)) {
783a6492e22SRoman Lebedev     if (auto *CstInt = dyn_cast_or_null<ConstantInt>(ConstantExpr::getPtrToInt(
784a6492e22SRoman Lebedev             const_cast<Constant *>(CstPtr), DL.getIntPtrType(getType()),
785a6492e22SRoman Lebedev             /*OnlyIfReduced=*/true))) {
786a6492e22SRoman Lebedev       size_t TrailingZeros = CstInt->getValue().countTrailingZeros();
787a6492e22SRoman Lebedev       // While the actual alignment may be large, elsewhere we have
788a6492e22SRoman Lebedev       // an arbitrary upper alignmet limit, so let's clamp to it.
789a6492e22SRoman Lebedev       return Align(TrailingZeros < Value::MaxAlignmentExponent
790a6492e22SRoman Lebedev                        ? uint64_t(1) << TrailingZeros
791a6492e22SRoman Lebedev                        : Value::MaximumAlignment);
792a6492e22SRoman Lebedev     }
7936200a568SGuillaume Chatelet   }
794bae629b9SGuillaume Chatelet   return llvm::None;
795ae51afc5SArtur Pilipenko }
796ae51afc5SArtur Pilipenko 
7971dd20e65SCraig Topper const Value *Value::DoPHITranslation(const BasicBlock *CurBB,
7981dd20e65SCraig Topper                                      const BasicBlock *PredBB) const {
7991dd20e65SCraig Topper   auto *PN = dyn_cast<PHINode>(this);
800ef860a24SChandler Carruth   if (PN && PN->getParent() == CurBB)
801ef860a24SChandler Carruth     return PN->getIncomingValueForBlock(PredBB);
802ef860a24SChandler Carruth   return this;
803ef860a24SChandler Carruth }
804ef860a24SChandler Carruth 
805ef860a24SChandler Carruth LLVMContext &Value::getContext() const { return VTy->getContext(); }
806ef860a24SChandler Carruth 
8073441ffe9SDuncan P. N. Exon Smith void Value::reverseUseList() {
8083441ffe9SDuncan P. N. Exon Smith   if (!UseList || !UseList->Next)
8093441ffe9SDuncan P. N. Exon Smith     // No need to reverse 0 or 1 uses.
8103441ffe9SDuncan P. N. Exon Smith     return;
8113441ffe9SDuncan P. N. Exon Smith 
8123441ffe9SDuncan P. N. Exon Smith   Use *Head = UseList;
8133441ffe9SDuncan P. N. Exon Smith   Use *Current = UseList->Next;
8143441ffe9SDuncan P. N. Exon Smith   Head->Next = nullptr;
8153441ffe9SDuncan P. N. Exon Smith   while (Current) {
8163441ffe9SDuncan P. N. Exon Smith     Use *Next = Current->Next;
8173441ffe9SDuncan P. N. Exon Smith     Current->Next = Head;
8183441ffe9SDuncan P. N. Exon Smith     Head->setPrev(&Current->Next);
8193441ffe9SDuncan P. N. Exon Smith     Head = Current;
8203441ffe9SDuncan P. N. Exon Smith     Current = Next;
8213441ffe9SDuncan P. N. Exon Smith   }
8223441ffe9SDuncan P. N. Exon Smith   UseList = Head;
8233441ffe9SDuncan P. N. Exon Smith   Head->setPrev(&UseList);
8243441ffe9SDuncan P. N. Exon Smith }
8253441ffe9SDuncan P. N. Exon Smith 
826ad830022SArnold Schwaighofer bool Value::isSwiftError() const {
827ad830022SArnold Schwaighofer   auto *Arg = dyn_cast<Argument>(this);
828ad830022SArnold Schwaighofer   if (Arg)
829ad830022SArnold Schwaighofer     return Arg->hasSwiftErrorAttr();
830ad830022SArnold Schwaighofer   auto *Alloca = dyn_cast<AllocaInst>(this);
831ad830022SArnold Schwaighofer   if (!Alloca)
832ad830022SArnold Schwaighofer     return false;
833ad830022SArnold Schwaighofer   return Alloca->isSwiftError();
834ad830022SArnold Schwaighofer }
835ad830022SArnold Schwaighofer 
836ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
837ef860a24SChandler Carruth //                             ValueHandleBase Class
838ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
839ef860a24SChandler Carruth 
840ef860a24SChandler Carruth void ValueHandleBase::AddToExistingUseList(ValueHandleBase **List) {
841ef860a24SChandler Carruth   assert(List && "Handle list is null?");
842ef860a24SChandler Carruth 
843ef860a24SChandler Carruth   // Splice ourselves into the list.
844ef860a24SChandler Carruth   Next = *List;
845ef860a24SChandler Carruth   *List = this;
846ef860a24SChandler Carruth   setPrevPtr(List);
847ef860a24SChandler Carruth   if (Next) {
848ef860a24SChandler Carruth     Next->setPrevPtr(&Next);
8496f08789dSSanjoy Das     assert(getValPtr() == Next->getValPtr() && "Added to wrong list?");
850ef860a24SChandler Carruth   }
851ef860a24SChandler Carruth }
852ef860a24SChandler Carruth 
853ef860a24SChandler Carruth void ValueHandleBase::AddToExistingUseListAfter(ValueHandleBase *List) {
854ef860a24SChandler Carruth   assert(List && "Must insert after existing node");
855ef860a24SChandler Carruth 
856ef860a24SChandler Carruth   Next = List->Next;
857ef860a24SChandler Carruth   setPrevPtr(&List->Next);
858ef860a24SChandler Carruth   List->Next = this;
859ef860a24SChandler Carruth   if (Next)
860ef860a24SChandler Carruth     Next->setPrevPtr(&Next);
861ef860a24SChandler Carruth }
862ef860a24SChandler Carruth 
863ef860a24SChandler Carruth void ValueHandleBase::AddToUseList() {
8646f08789dSSanjoy Das   assert(getValPtr() && "Null pointer doesn't have a use list!");
865ef860a24SChandler Carruth 
8666f08789dSSanjoy Das   LLVMContextImpl *pImpl = getValPtr()->getContext().pImpl;
867ef860a24SChandler Carruth 
8686f08789dSSanjoy Das   if (getValPtr()->HasValueHandle) {
869ef860a24SChandler Carruth     // If this value already has a ValueHandle, then it must be in the
870ef860a24SChandler Carruth     // ValueHandles map already.
8716f08789dSSanjoy Das     ValueHandleBase *&Entry = pImpl->ValueHandles[getValPtr()];
8722617dcceSCraig Topper     assert(Entry && "Value doesn't have any handles?");
873ef860a24SChandler Carruth     AddToExistingUseList(&Entry);
874ef860a24SChandler Carruth     return;
875ef860a24SChandler Carruth   }
876ef860a24SChandler Carruth 
877ef860a24SChandler Carruth   // Ok, it doesn't have any handles yet, so we must insert it into the
878ef860a24SChandler Carruth   // DenseMap.  However, doing this insertion could cause the DenseMap to
879ef860a24SChandler Carruth   // reallocate itself, which would invalidate all of the PrevP pointers that
880ef860a24SChandler Carruth   // point into the old table.  Handle this by checking for reallocation and
881ef860a24SChandler Carruth   // updating the stale pointers only if needed.
882ef860a24SChandler Carruth   DenseMap<Value*, ValueHandleBase*> &Handles = pImpl->ValueHandles;
883ef860a24SChandler Carruth   const void *OldBucketPtr = Handles.getPointerIntoBucketsArray();
884ef860a24SChandler Carruth 
8856f08789dSSanjoy Das   ValueHandleBase *&Entry = Handles[getValPtr()];
8862617dcceSCraig Topper   assert(!Entry && "Value really did already have handles?");
887ef860a24SChandler Carruth   AddToExistingUseList(&Entry);
8886f08789dSSanjoy Das   getValPtr()->HasValueHandle = true;
889ef860a24SChandler Carruth 
890ef860a24SChandler Carruth   // If reallocation didn't happen or if this was the first insertion, don't
891ef860a24SChandler Carruth   // walk the table.
892ef860a24SChandler Carruth   if (Handles.isPointerIntoBucketsArray(OldBucketPtr) ||
893ef860a24SChandler Carruth       Handles.size() == 1) {
894ef860a24SChandler Carruth     return;
895ef860a24SChandler Carruth   }
896ef860a24SChandler Carruth 
897ef860a24SChandler Carruth   // Okay, reallocation did happen.  Fix the Prev Pointers.
898ef860a24SChandler Carruth   for (DenseMap<Value*, ValueHandleBase*>::iterator I = Handles.begin(),
899ef860a24SChandler Carruth        E = Handles.end(); I != E; ++I) {
9006f08789dSSanjoy Das     assert(I->second && I->first == I->second->getValPtr() &&
901ef860a24SChandler Carruth            "List invariant broken!");
902ef860a24SChandler Carruth     I->second->setPrevPtr(&I->second);
903ef860a24SChandler Carruth   }
904ef860a24SChandler Carruth }
905ef860a24SChandler Carruth 
906ef860a24SChandler Carruth void ValueHandleBase::RemoveFromUseList() {
9076f08789dSSanjoy Das   assert(getValPtr() && getValPtr()->HasValueHandle &&
908ef860a24SChandler Carruth          "Pointer doesn't have a use list!");
909ef860a24SChandler Carruth 
910ef860a24SChandler Carruth   // Unlink this from its use list.
911ef860a24SChandler Carruth   ValueHandleBase **PrevPtr = getPrevPtr();
912ef860a24SChandler Carruth   assert(*PrevPtr == this && "List invariant broken");
913ef860a24SChandler Carruth 
914ef860a24SChandler Carruth   *PrevPtr = Next;
915ef860a24SChandler Carruth   if (Next) {
916ef860a24SChandler Carruth     assert(Next->getPrevPtr() == &Next && "List invariant broken");
917ef860a24SChandler Carruth     Next->setPrevPtr(PrevPtr);
918ef860a24SChandler Carruth     return;
919ef860a24SChandler Carruth   }
920ef860a24SChandler Carruth 
921ef860a24SChandler Carruth   // If the Next pointer was null, then it is possible that this was the last
922ef860a24SChandler Carruth   // ValueHandle watching VP.  If so, delete its entry from the ValueHandles
923ef860a24SChandler Carruth   // map.
9246f08789dSSanjoy Das   LLVMContextImpl *pImpl = getValPtr()->getContext().pImpl;
925ef860a24SChandler Carruth   DenseMap<Value*, ValueHandleBase*> &Handles = pImpl->ValueHandles;
926ef860a24SChandler Carruth   if (Handles.isPointerIntoBucketsArray(PrevPtr)) {
9276f08789dSSanjoy Das     Handles.erase(getValPtr());
9286f08789dSSanjoy Das     getValPtr()->HasValueHandle = false;
929ef860a24SChandler Carruth   }
930ef860a24SChandler Carruth }
931ef860a24SChandler Carruth 
932ef860a24SChandler Carruth void ValueHandleBase::ValueIsDeleted(Value *V) {
933ef860a24SChandler Carruth   assert(V->HasValueHandle && "Should only be called if ValueHandles present");
934ef860a24SChandler Carruth 
935ef860a24SChandler Carruth   // Get the linked list base, which is guaranteed to exist since the
936ef860a24SChandler Carruth   // HasValueHandle flag is set.
937ef860a24SChandler Carruth   LLVMContextImpl *pImpl = V->getContext().pImpl;
938ef860a24SChandler Carruth   ValueHandleBase *Entry = pImpl->ValueHandles[V];
939ef860a24SChandler Carruth   assert(Entry && "Value bit set but no entries exist");
940ef860a24SChandler Carruth 
941ef860a24SChandler Carruth   // We use a local ValueHandleBase as an iterator so that ValueHandles can add
942ef860a24SChandler Carruth   // and remove themselves from the list without breaking our iteration.  This
943ef860a24SChandler Carruth   // is not really an AssertingVH; we just have to give ValueHandleBase a kind.
944ef860a24SChandler Carruth   // Note that we deliberately do not the support the case when dropping a value
945ef860a24SChandler Carruth   // handle results in a new value handle being permanently added to the list
946ef860a24SChandler Carruth   // (as might occur in theory for CallbackVH's): the new value handle will not
947ef860a24SChandler Carruth   // be processed and the checking code will mete out righteous punishment if
948ef860a24SChandler Carruth   // the handle is still present once we have finished processing all the other
949ef860a24SChandler Carruth   // value handles (it is fine to momentarily add then remove a value handle).
950ef860a24SChandler Carruth   for (ValueHandleBase Iterator(Assert, *Entry); Entry; Entry = Iterator.Next) {
951ef860a24SChandler Carruth     Iterator.RemoveFromUseList();
952ef860a24SChandler Carruth     Iterator.AddToExistingUseListAfter(Entry);
953ef860a24SChandler Carruth     assert(Entry->Next == &Iterator && "Loop invariant broken.");
954ef860a24SChandler Carruth 
955ef860a24SChandler Carruth     switch (Entry->getKind()) {
956ef860a24SChandler Carruth     case Assert:
957ef860a24SChandler Carruth       break;
958f1c0eafdSSanjoy Das     case Weak:
959e6bca0eeSSanjoy Das     case WeakTracking:
960f1c0eafdSSanjoy Das       // WeakTracking and Weak just go to null, which unlinks them
961f1c0eafdSSanjoy Das       // from the list.
962c620761cSCraig Topper       Entry->operator=(nullptr);
963ef860a24SChandler Carruth       break;
964ef860a24SChandler Carruth     case Callback:
965ef860a24SChandler Carruth       // Forward to the subclass's implementation.
966ef860a24SChandler Carruth       static_cast<CallbackVH*>(Entry)->deleted();
967ef860a24SChandler Carruth       break;
968ef860a24SChandler Carruth     }
969ef860a24SChandler Carruth   }
970ef860a24SChandler Carruth 
971ef860a24SChandler Carruth   // All callbacks, weak references, and assertingVHs should be dropped by now.
972ef860a24SChandler Carruth   if (V->HasValueHandle) {
973ef860a24SChandler Carruth #ifndef NDEBUG      // Only in +Asserts mode...
974ef860a24SChandler Carruth     dbgs() << "While deleting: " << *V->getType() << " %" << V->getName()
975ef860a24SChandler Carruth            << "\n";
976ef860a24SChandler Carruth     if (pImpl->ValueHandles[V]->getKind() == Assert)
977ef860a24SChandler Carruth       llvm_unreachable("An asserting value handle still pointed to this"
978ef860a24SChandler Carruth                        " value!");
979ef860a24SChandler Carruth 
980ef860a24SChandler Carruth #endif
981ef860a24SChandler Carruth     llvm_unreachable("All references to V were not removed?");
982ef860a24SChandler Carruth   }
983ef860a24SChandler Carruth }
984ef860a24SChandler Carruth 
985ef860a24SChandler Carruth void ValueHandleBase::ValueIsRAUWd(Value *Old, Value *New) {
986ef860a24SChandler Carruth   assert(Old->HasValueHandle &&"Should only be called if ValueHandles present");
987ef860a24SChandler Carruth   assert(Old != New && "Changing value into itself!");
988c1892e2dSFrederic Riss   assert(Old->getType() == New->getType() &&
989c1892e2dSFrederic Riss          "replaceAllUses of value with new value of different type!");
990ef860a24SChandler Carruth 
991ef860a24SChandler Carruth   // Get the linked list base, which is guaranteed to exist since the
992ef860a24SChandler Carruth   // HasValueHandle flag is set.
993ef860a24SChandler Carruth   LLVMContextImpl *pImpl = Old->getContext().pImpl;
994ef860a24SChandler Carruth   ValueHandleBase *Entry = pImpl->ValueHandles[Old];
995ef860a24SChandler Carruth 
996ef860a24SChandler Carruth   assert(Entry && "Value bit set but no entries exist");
997ef860a24SChandler Carruth 
998ef860a24SChandler Carruth   // We use a local ValueHandleBase as an iterator so that
999ef860a24SChandler Carruth   // ValueHandles can add and remove themselves from the list without
1000ef860a24SChandler Carruth   // breaking our iteration.  This is not really an AssertingVH; we
1001ef860a24SChandler Carruth   // just have to give ValueHandleBase some kind.
1002ef860a24SChandler Carruth   for (ValueHandleBase Iterator(Assert, *Entry); Entry; Entry = Iterator.Next) {
1003ef860a24SChandler Carruth     Iterator.RemoveFromUseList();
1004ef860a24SChandler Carruth     Iterator.AddToExistingUseListAfter(Entry);
1005ef860a24SChandler Carruth     assert(Entry->Next == &Iterator && "Loop invariant broken.");
1006ef860a24SChandler Carruth 
1007ef860a24SChandler Carruth     switch (Entry->getKind()) {
1008ef860a24SChandler Carruth     case Assert:
1009f1c0eafdSSanjoy Das     case Weak:
1010f1c0eafdSSanjoy Das       // Asserting and Weak handles do not follow RAUW implicitly.
1011ef860a24SChandler Carruth       break;
1012e6bca0eeSSanjoy Das     case WeakTracking:
10132cbeb00fSSanjoy Das       // Weak goes to the new value, which will unlink it from Old's list.
1014ef860a24SChandler Carruth       Entry->operator=(New);
1015ef860a24SChandler Carruth       break;
1016ef860a24SChandler Carruth     case Callback:
1017ef860a24SChandler Carruth       // Forward to the subclass's implementation.
1018ef860a24SChandler Carruth       static_cast<CallbackVH*>(Entry)->allUsesReplacedWith(New);
1019ef860a24SChandler Carruth       break;
1020ef860a24SChandler Carruth     }
1021ef860a24SChandler Carruth   }
1022ef860a24SChandler Carruth 
1023ef860a24SChandler Carruth #ifndef NDEBUG
10248a623820SSanjoy Das   // If any new weak value handles were added while processing the
1025ef860a24SChandler Carruth   // list, then complain about it now.
1026ef860a24SChandler Carruth   if (Old->HasValueHandle)
1027ef860a24SChandler Carruth     for (Entry = pImpl->ValueHandles[Old]; Entry; Entry = Entry->Next)
1028ef860a24SChandler Carruth       switch (Entry->getKind()) {
1029e6bca0eeSSanjoy Das       case WeakTracking:
1030ef860a24SChandler Carruth         dbgs() << "After RAUW from " << *Old->getType() << " %"
1031ef860a24SChandler Carruth                << Old->getName() << " to " << *New->getType() << " %"
1032ef860a24SChandler Carruth                << New->getName() << "\n";
10338a623820SSanjoy Das         llvm_unreachable(
1034e6bca0eeSSanjoy Das             "A weak tracking value handle still pointed to the old value!\n");
1035ef860a24SChandler Carruth       default:
1036ef860a24SChandler Carruth         break;
1037ef860a24SChandler Carruth       }
1038ef860a24SChandler Carruth #endif
1039ef860a24SChandler Carruth }
1040ef860a24SChandler Carruth 
1041d12ccbd3SJuergen Ributzka // Pin the vtable to this file.
1042d12ccbd3SJuergen Ributzka void CallbackVH::anchor() {}
1043