xref: /llvm-project-15.0.7/llvm/lib/IR/Value.cpp (revision 5b3db45e)
1ef860a24SChandler Carruth //===-- Value.cpp - Implement the Value class -----------------------------===//
2ef860a24SChandler Carruth //
3ef860a24SChandler Carruth //                     The LLVM Compiler Infrastructure
4ef860a24SChandler Carruth //
5ef860a24SChandler Carruth // This file is distributed under the University of Illinois Open Source
6ef860a24SChandler Carruth // License. See LICENSE.TXT for details.
7ef860a24SChandler Carruth //
8ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
9ef860a24SChandler Carruth //
10ef860a24SChandler Carruth // This file implements the Value, ValueHandle, and User classes.
11ef860a24SChandler Carruth //
12ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
13ef860a24SChandler Carruth 
149fb823bbSChandler Carruth #include "llvm/IR/Value.h"
15ef860a24SChandler Carruth #include "LLVMContextImpl.h"
16ef860a24SChandler Carruth #include "llvm/ADT/DenseMap.h"
17ef860a24SChandler Carruth #include "llvm/ADT/SmallString.h"
182f2ace98SDmitry Mikulin #include "llvm/ADT/SetVector.h"
19b0407ba0SHal Finkel #include "llvm/IR/CallSite.h"
209fb823bbSChandler Carruth #include "llvm/IR/Constant.h"
219fb823bbSChandler Carruth #include "llvm/IR/Constants.h"
222e42c34dSHal Finkel #include "llvm/IR/DataLayout.h"
239fb823bbSChandler Carruth #include "llvm/IR/DerivedTypes.h"
2496ab8726SReid Kleckner #include "llvm/IR/DerivedUser.h"
2503eb0de9SChandler Carruth #include "llvm/IR/GetElementPtrTypeIterator.h"
269fb823bbSChandler Carruth #include "llvm/IR/InstrTypes.h"
279fb823bbSChandler Carruth #include "llvm/IR/Instructions.h"
28a7343d65SRamkumar Ramachandra #include "llvm/IR/IntrinsicInst.h"
299fb823bbSChandler Carruth #include "llvm/IR/Module.h"
309fb823bbSChandler Carruth #include "llvm/IR/Operator.h"
31a7343d65SRamkumar Ramachandra #include "llvm/IR/Statepoint.h"
324220e9c1SChandler Carruth #include "llvm/IR/ValueHandle.h"
339fb823bbSChandler Carruth #include "llvm/IR/ValueSymbolTable.h"
34ef860a24SChandler Carruth #include "llvm/Support/Debug.h"
35ef860a24SChandler Carruth #include "llvm/Support/ErrorHandling.h"
36ef860a24SChandler Carruth #include "llvm/Support/ManagedStatic.h"
37799003bfSBenjamin Kramer #include "llvm/Support/raw_ostream.h"
38ef860a24SChandler Carruth #include <algorithm>
39ecefe5a8SEugene Zelenko 
40ef860a24SChandler Carruth using namespace llvm;
41ef860a24SChandler Carruth 
424c975578SSerge Guelton static cl::opt<unsigned> NonGlobalValueMaxNameSize(
434c975578SSerge Guelton     "non-global-value-max-name-size", cl::Hidden, cl::init(1024),
444c975578SSerge Guelton     cl::desc("Maximum size for the name of non-global values."));
454c975578SSerge Guelton 
46ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
47ef860a24SChandler Carruth //                                Value Class
48ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
49ef860a24SChandler Carruth static inline Type *checkType(Type *Ty) {
50ef860a24SChandler Carruth   assert(Ty && "Value defined with a null type: Error!");
5116bf89ecSReid Kleckner   return Ty;
52ef860a24SChandler Carruth }
53ef860a24SChandler Carruth 
54ef860a24SChandler Carruth Value::Value(Type *ty, unsigned scid)
557349ab93SOwen Anderson     : VTy(checkType(ty)), UseList(nullptr), SubclassID(scid),
567349ab93SOwen Anderson       HasValueHandle(0), SubclassOptionalData(0), SubclassData(0),
57b4eede2cSPete Cooper       NumUserOperands(0), IsUsedByMD(false), HasName(false) {
589fd33f24SSerge Guelton   static_assert(ConstantFirstVal == 0, "!(SubclassID < ConstantFirstVal)");
59ef860a24SChandler Carruth   // FIXME: Why isn't this in the subclass gunk??
60ef860a24SChandler Carruth   // Note, we cannot call isa<CallInst> before the CallInst has been
61ef860a24SChandler Carruth   // constructed.
62ef860a24SChandler Carruth   if (SubclassID == Instruction::Call || SubclassID == Instruction::Invoke)
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   //
86ef860a24SChandler Carruth   if (!use_empty()) {
87ef860a24SChandler Carruth     dbgs() << "While deleting: " << *VTy << " %" << getName() << "\n";
88b93fb82bSAndrew Kaylor     for (auto *U : users())
89b93fb82bSAndrew Kaylor       dbgs() << "Use still stuck around after Def is destroyed:" << *U << "\n";
90ef860a24SChandler Carruth   }
91ef860a24SChandler Carruth #endif
92ef860a24SChandler Carruth   assert(use_empty() && "Uses remain when a value is destroyed!");
93ef860a24SChandler Carruth 
94ef860a24SChandler Carruth   // If this value is named, destroy the name.  This should not be in a symtab
95ef860a24SChandler Carruth   // at this point.
965bf8fef5SDuncan P. N. Exon Smith   destroyValueName();
97ef860a24SChandler Carruth }
98ef860a24SChandler Carruth 
9996ab8726SReid Kleckner void Value::deleteValue() {
10096ab8726SReid Kleckner   switch (getValueID()) {
10196ab8726SReid Kleckner #define HANDLE_VALUE(Name)                                                     \
10296ab8726SReid Kleckner   case Value::Name##Val:                                                       \
10396ab8726SReid Kleckner     delete static_cast<Name *>(this);                                          \
10496ab8726SReid Kleckner     break;
10596ab8726SReid Kleckner #define HANDLE_MEMORY_VALUE(Name)                                              \
10696ab8726SReid Kleckner   case Value::Name##Val:                                                       \
10796ab8726SReid Kleckner     static_cast<DerivedUser *>(this)->DeleteValue(                             \
10896ab8726SReid Kleckner         static_cast<DerivedUser *>(this));                                     \
10996ab8726SReid Kleckner     break;
11096ab8726SReid Kleckner #define HANDLE_INSTRUCTION(Name)  /* nothing */
11196ab8726SReid Kleckner #include "llvm/IR/Value.def"
11296ab8726SReid Kleckner 
11396ab8726SReid Kleckner #define HANDLE_INST(N, OPC, CLASS)                                             \
11496ab8726SReid Kleckner   case Value::InstructionVal + Instruction::OPC:                               \
11596ab8726SReid Kleckner     delete static_cast<CLASS *>(this);                                         \
11696ab8726SReid Kleckner     break;
11796ab8726SReid Kleckner #define HANDLE_USER_INST(N, OPC, CLASS)
11896ab8726SReid Kleckner #include "llvm/IR/Instruction.def"
11996ab8726SReid Kleckner 
12096ab8726SReid Kleckner   default:
12196ab8726SReid Kleckner     llvm_unreachable("attempting to delete unknown value kind");
12296ab8726SReid Kleckner   }
12396ab8726SReid Kleckner }
12496ab8726SReid Kleckner 
1255bf8fef5SDuncan P. N. Exon Smith void Value::destroyValueName() {
1265bf8fef5SDuncan P. N. Exon Smith   ValueName *Name = getValueName();
1275bf8fef5SDuncan P. N. Exon Smith   if (Name)
1285bf8fef5SDuncan P. N. Exon Smith     Name->Destroy();
1295bf8fef5SDuncan P. N. Exon Smith   setValueName(nullptr);
1305bf8fef5SDuncan P. N. Exon Smith }
1315bf8fef5SDuncan P. N. Exon Smith 
132ef860a24SChandler Carruth bool Value::hasNUses(unsigned N) const {
133ef860a24SChandler Carruth   const_use_iterator UI = use_begin(), E = use_end();
134ef860a24SChandler Carruth 
135ef860a24SChandler Carruth   for (; N; --N, ++UI)
136ef860a24SChandler Carruth     if (UI == E) return false;  // Too few.
137ef860a24SChandler Carruth   return UI == E;
138ef860a24SChandler Carruth }
139ef860a24SChandler Carruth 
140ef860a24SChandler Carruth bool Value::hasNUsesOrMore(unsigned N) const {
141ef860a24SChandler Carruth   const_use_iterator UI = use_begin(), E = use_end();
142ef860a24SChandler Carruth 
143ef860a24SChandler Carruth   for (; N; --N, ++UI)
144ef860a24SChandler Carruth     if (UI == E) return false;  // Too few.
145ef860a24SChandler Carruth 
146ef860a24SChandler Carruth   return true;
147ef860a24SChandler Carruth }
148ef860a24SChandler Carruth 
149ef860a24SChandler Carruth bool Value::isUsedInBasicBlock(const BasicBlock *BB) const {
1500925b24dSJakob Stoklund Olesen   // This can be computed either by scanning the instructions in BB, or by
1510925b24dSJakob Stoklund Olesen   // scanning the use list of this Value. Both lists can be very long, but
1520925b24dSJakob Stoklund Olesen   // usually one is quite short.
1530925b24dSJakob Stoklund Olesen   //
1540925b24dSJakob Stoklund Olesen   // Scan both lists simultaneously until one is exhausted. This limits the
1550925b24dSJakob Stoklund Olesen   // search to the shorter list.
1560925b24dSJakob Stoklund Olesen   BasicBlock::const_iterator BI = BB->begin(), BE = BB->end();
157cdf47884SChandler Carruth   const_user_iterator UI = user_begin(), UE = user_end();
1580925b24dSJakob Stoklund Olesen   for (; BI != BE && UI != UE; ++BI, ++UI) {
1590925b24dSJakob Stoklund Olesen     // Scan basic block: Check if this Value is used by the instruction at BI.
16042531260SDavid Majnemer     if (is_contained(BI->operands(), this))
161ef860a24SChandler Carruth       return true;
1620925b24dSJakob Stoklund Olesen     // Scan use list: Check if the use at UI is in BB.
16342531260SDavid Majnemer     const auto *User = dyn_cast<Instruction>(*UI);
164ef860a24SChandler Carruth     if (User && User->getParent() == BB)
165ef860a24SChandler Carruth       return true;
166ef860a24SChandler Carruth   }
167ef860a24SChandler Carruth   return false;
168ef860a24SChandler Carruth }
169ef860a24SChandler Carruth 
1705a0872c2SVedant Kumar unsigned Value::getNumUses() const {
1715a0872c2SVedant Kumar   return (unsigned)std::distance(use_begin(), use_end());
1725a0872c2SVedant Kumar }
173ef860a24SChandler Carruth 
174ef860a24SChandler Carruth static bool getSymTab(Value *V, ValueSymbolTable *&ST) {
175c620761cSCraig Topper   ST = nullptr;
176ef860a24SChandler Carruth   if (Instruction *I = dyn_cast<Instruction>(V)) {
177ef860a24SChandler Carruth     if (BasicBlock *P = I->getParent())
178ef860a24SChandler Carruth       if (Function *PP = P->getParent())
179a53d49e1SMehdi Amini         ST = PP->getValueSymbolTable();
180ef860a24SChandler Carruth   } else if (BasicBlock *BB = dyn_cast<BasicBlock>(V)) {
181ef860a24SChandler Carruth     if (Function *P = BB->getParent())
182a53d49e1SMehdi Amini       ST = P->getValueSymbolTable();
183ef860a24SChandler Carruth   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
184ef860a24SChandler Carruth     if (Module *P = GV->getParent())
185ef860a24SChandler Carruth       ST = &P->getValueSymbolTable();
186ef860a24SChandler Carruth   } else if (Argument *A = dyn_cast<Argument>(V)) {
187ef860a24SChandler Carruth     if (Function *P = A->getParent())
188a53d49e1SMehdi Amini       ST = P->getValueSymbolTable();
1895bf8fef5SDuncan P. N. Exon Smith   } else {
190ef860a24SChandler Carruth     assert(isa<Constant>(V) && "Unknown value type!");
191ef860a24SChandler Carruth     return true;  // no name is setable for this.
192ef860a24SChandler Carruth   }
193ef860a24SChandler Carruth   return false;
194ef860a24SChandler Carruth }
195ef860a24SChandler Carruth 
1967349ab93SOwen Anderson ValueName *Value::getValueName() const {
1977349ab93SOwen Anderson   if (!HasName) return nullptr;
1987349ab93SOwen Anderson 
1997349ab93SOwen Anderson   LLVMContext &Ctx = getContext();
2007349ab93SOwen Anderson   auto I = Ctx.pImpl->ValueNames.find(this);
2017349ab93SOwen Anderson   assert(I != Ctx.pImpl->ValueNames.end() &&
2027349ab93SOwen Anderson          "No name entry found!");
2037349ab93SOwen Anderson 
2047349ab93SOwen Anderson   return I->second;
2057349ab93SOwen Anderson }
2067349ab93SOwen Anderson 
2077349ab93SOwen Anderson void Value::setValueName(ValueName *VN) {
2087349ab93SOwen Anderson   LLVMContext &Ctx = getContext();
2097349ab93SOwen Anderson 
2107349ab93SOwen Anderson   assert(HasName == Ctx.pImpl->ValueNames.count(this) &&
2117349ab93SOwen Anderson          "HasName bit out of sync!");
2127349ab93SOwen Anderson 
2137349ab93SOwen Anderson   if (!VN) {
2147349ab93SOwen Anderson     if (HasName)
2157349ab93SOwen Anderson       Ctx.pImpl->ValueNames.erase(this);
2167349ab93SOwen Anderson     HasName = false;
2177349ab93SOwen Anderson     return;
2187349ab93SOwen Anderson   }
2197349ab93SOwen Anderson 
2207349ab93SOwen Anderson   HasName = true;
2217349ab93SOwen Anderson   Ctx.pImpl->ValueNames[this] = VN;
2227349ab93SOwen Anderson }
2237349ab93SOwen Anderson 
224ef860a24SChandler Carruth StringRef Value::getName() const {
225ef860a24SChandler Carruth   // Make sure the empty string is still a C string. For historical reasons,
226ef860a24SChandler Carruth   // some clients want to call .data() on the result and expect it to be null
227ef860a24SChandler Carruth   // terminated.
2287349ab93SOwen Anderson   if (!hasName())
2295bf8fef5SDuncan P. N. Exon Smith     return StringRef("", 0);
2305bf8fef5SDuncan P. N. Exon Smith   return getValueName()->getKey();
231ef860a24SChandler Carruth }
232ef860a24SChandler Carruth 
233a7c0c18cSPete Cooper void Value::setNameImpl(const Twine &NewName) {
23409b4a8daSMehdi Amini   // Fast-path: LLVMContext can be set to strip out non-GlobalValue names
23550af49fcSMehdi Amini   if (getContext().shouldDiscardValueNames() && !isa<GlobalValue>(this))
23609b4a8daSMehdi Amini     return;
23709b4a8daSMehdi Amini 
238ef860a24SChandler Carruth   // Fast path for common IRBuilder case of setName("") when there is no name.
239ef860a24SChandler Carruth   if (NewName.isTriviallyEmpty() && !hasName())
240ef860a24SChandler Carruth     return;
241ef860a24SChandler Carruth 
242ef860a24SChandler Carruth   SmallString<256> NameData;
243ef860a24SChandler Carruth   StringRef NameRef = NewName.toStringRef(NameData);
24409d689f9SRafael Espindola   assert(NameRef.find_first_of(0) == StringRef::npos &&
24509d689f9SRafael Espindola          "Null bytes are not allowed in names");
246ef860a24SChandler Carruth 
247ef860a24SChandler Carruth   // Name isn't changing?
248ef860a24SChandler Carruth   if (getName() == NameRef)
249ef860a24SChandler Carruth     return;
250ef860a24SChandler Carruth 
2514c975578SSerge Guelton   // Cap the size of non-GlobalValue names.
2524c975578SSerge Guelton   if (NameRef.size() > NonGlobalValueMaxNameSize && !isa<GlobalValue>(this))
2534c975578SSerge Guelton     NameRef =
2544c975578SSerge Guelton         NameRef.substr(0, std::max(1u, (unsigned)NonGlobalValueMaxNameSize));
2554c975578SSerge Guelton 
256ef860a24SChandler Carruth   assert(!getType()->isVoidTy() && "Cannot assign a name to void values!");
257ef860a24SChandler Carruth 
258ef860a24SChandler Carruth   // Get the symbol table to update for this object.
259ef860a24SChandler Carruth   ValueSymbolTable *ST;
260ef860a24SChandler Carruth   if (getSymTab(this, ST))
261ef860a24SChandler Carruth     return;  // Cannot set a name on this value (e.g. constant).
262ef860a24SChandler Carruth 
263ef860a24SChandler Carruth   if (!ST) { // No symbol table to update?  Just do the change.
264ef860a24SChandler Carruth     if (NameRef.empty()) {
265ef860a24SChandler Carruth       // Free the name for this value.
2665bf8fef5SDuncan P. N. Exon Smith       destroyValueName();
267ef860a24SChandler Carruth       return;
268ef860a24SChandler Carruth     }
269ef860a24SChandler Carruth 
270ef860a24SChandler Carruth     // NOTE: Could optimize for the case the name is shrinking to not deallocate
271ef860a24SChandler Carruth     // then reallocated.
2725bf8fef5SDuncan P. N. Exon Smith     destroyValueName();
273ef860a24SChandler Carruth 
274ef860a24SChandler Carruth     // Create the new name.
2755bf8fef5SDuncan P. N. Exon Smith     setValueName(ValueName::Create(NameRef));
2765bf8fef5SDuncan P. N. Exon Smith     getValueName()->setValue(this);
277ef860a24SChandler Carruth     return;
278ef860a24SChandler Carruth   }
279ef860a24SChandler Carruth 
280ef860a24SChandler Carruth   // NOTE: Could optimize for the case the name is shrinking to not deallocate
281ef860a24SChandler Carruth   // then reallocated.
282ef860a24SChandler Carruth   if (hasName()) {
283ef860a24SChandler Carruth     // Remove old name.
2845bf8fef5SDuncan P. N. Exon Smith     ST->removeValueName(getValueName());
2855bf8fef5SDuncan P. N. Exon Smith     destroyValueName();
286ef860a24SChandler Carruth 
287ef860a24SChandler Carruth     if (NameRef.empty())
288ef860a24SChandler Carruth       return;
289ef860a24SChandler Carruth   }
290ef860a24SChandler Carruth 
291ef860a24SChandler Carruth   // Name is changing to something new.
2925bf8fef5SDuncan P. N. Exon Smith   setValueName(ST->createValueName(NameRef, this));
293ef860a24SChandler Carruth }
294ef860a24SChandler Carruth 
295a7c0c18cSPete Cooper void Value::setName(const Twine &NewName) {
296a7c0c18cSPete Cooper   setNameImpl(NewName);
297a7c0c18cSPete Cooper   if (Function *F = dyn_cast<Function>(this))
298a7c0c18cSPete Cooper     F->recalculateIntrinsicID();
299a7c0c18cSPete Cooper }
300a7c0c18cSPete Cooper 
301ef860a24SChandler Carruth void Value::takeName(Value *V) {
302c620761cSCraig Topper   ValueSymbolTable *ST = nullptr;
303ef860a24SChandler Carruth   // If this value has a name, drop it.
304ef860a24SChandler Carruth   if (hasName()) {
305ef860a24SChandler Carruth     // Get the symtab this is in.
306ef860a24SChandler Carruth     if (getSymTab(this, ST)) {
307ef860a24SChandler Carruth       // We can't set a name on this value, but we need to clear V's name if
308ef860a24SChandler Carruth       // it has one.
309ef860a24SChandler Carruth       if (V->hasName()) V->setName("");
310ef860a24SChandler Carruth       return;  // Cannot set a name on this value (e.g. constant).
311ef860a24SChandler Carruth     }
312ef860a24SChandler Carruth 
313ef860a24SChandler Carruth     // Remove old name.
314ef860a24SChandler Carruth     if (ST)
3155bf8fef5SDuncan P. N. Exon Smith       ST->removeValueName(getValueName());
3165bf8fef5SDuncan P. N. Exon Smith     destroyValueName();
317ef860a24SChandler Carruth   }
318ef860a24SChandler Carruth 
319ef860a24SChandler Carruth   // Now we know that this has no name.
320ef860a24SChandler Carruth 
321ef860a24SChandler Carruth   // If V has no name either, we're done.
322ef860a24SChandler Carruth   if (!V->hasName()) return;
323ef860a24SChandler Carruth 
324ef860a24SChandler Carruth   // Get this's symtab if we didn't before.
325ef860a24SChandler Carruth   if (!ST) {
326ef860a24SChandler Carruth     if (getSymTab(this, ST)) {
327ef860a24SChandler Carruth       // Clear V's name.
328ef860a24SChandler Carruth       V->setName("");
329ef860a24SChandler Carruth       return;  // Cannot set a name on this value (e.g. constant).
330ef860a24SChandler Carruth     }
331ef860a24SChandler Carruth   }
332ef860a24SChandler Carruth 
333ef860a24SChandler Carruth   // Get V's ST, this should always succed, because V has a name.
334ef860a24SChandler Carruth   ValueSymbolTable *VST;
335ef860a24SChandler Carruth   bool Failure = getSymTab(V, VST);
336ef860a24SChandler Carruth   assert(!Failure && "V has a name, so it should have a ST!"); (void)Failure;
337ef860a24SChandler Carruth 
338ef860a24SChandler Carruth   // If these values are both in the same symtab, we can do this very fast.
339ef860a24SChandler Carruth   // This works even if both values have no symtab yet.
340ef860a24SChandler Carruth   if (ST == VST) {
341ef860a24SChandler Carruth     // Take the name!
3425bf8fef5SDuncan P. N. Exon Smith     setValueName(V->getValueName());
3435bf8fef5SDuncan P. N. Exon Smith     V->setValueName(nullptr);
3445bf8fef5SDuncan P. N. Exon Smith     getValueName()->setValue(this);
345ef860a24SChandler Carruth     return;
346ef860a24SChandler Carruth   }
347ef860a24SChandler Carruth 
348ef860a24SChandler Carruth   // Otherwise, things are slightly more complex.  Remove V's name from VST and
349ef860a24SChandler Carruth   // then reinsert it into ST.
350ef860a24SChandler Carruth 
351ef860a24SChandler Carruth   if (VST)
3525bf8fef5SDuncan P. N. Exon Smith     VST->removeValueName(V->getValueName());
3535bf8fef5SDuncan P. N. Exon Smith   setValueName(V->getValueName());
3545bf8fef5SDuncan P. N. Exon Smith   V->setValueName(nullptr);
3555bf8fef5SDuncan P. N. Exon Smith   getValueName()->setValue(this);
356ef860a24SChandler Carruth 
357ef860a24SChandler Carruth   if (ST)
358ef860a24SChandler Carruth     ST->reinsertValue(this);
359ef860a24SChandler Carruth }
360ef860a24SChandler Carruth 
361eec48903SCraig Topper void Value::assertModuleIsMaterializedImpl() const {
362675bdcedSTodd Fiala #ifndef NDEBUG
363257a3536SRafael Espindola   const GlobalValue *GV = dyn_cast<GlobalValue>(this);
364257a3536SRafael Espindola   if (!GV)
365257a3536SRafael Espindola     return;
366257a3536SRafael Espindola   const Module *M = GV->getParent();
367257a3536SRafael Espindola   if (!M)
368257a3536SRafael Espindola     return;
369257a3536SRafael Espindola   assert(M->isMaterialized());
370675bdcedSTodd Fiala #endif
371257a3536SRafael Espindola }
372257a3536SRafael Espindola 
373675bdcedSTodd Fiala #ifndef NDEBUG
37471b7b68bSCraig Topper static bool contains(SmallPtrSetImpl<ConstantExpr *> &Cache, ConstantExpr *Expr,
3757e2b7567SRafael Espindola                      Constant *C) {
37670573dcdSDavid Blaikie   if (!Cache.insert(Expr).second)
3777e2b7567SRafael Espindola     return false;
3787e2b7567SRafael Espindola 
3797e2b7567SRafael Espindola   for (auto &O : Expr->operands()) {
3807e2b7567SRafael Espindola     if (O == C)
3817e2b7567SRafael Espindola       return true;
3827e2b7567SRafael Espindola     auto *CE = dyn_cast<ConstantExpr>(O);
3837e2b7567SRafael Espindola     if (!CE)
3847e2b7567SRafael Espindola       continue;
3857e2b7567SRafael Espindola     if (contains(Cache, CE, C))
3867e2b7567SRafael Espindola       return true;
3877e2b7567SRafael Espindola   }
3887e2b7567SRafael Espindola   return false;
3897e2b7567SRafael Espindola }
3907e2b7567SRafael Espindola 
3917e2b7567SRafael Espindola static bool contains(Value *Expr, Value *V) {
3927e2b7567SRafael Espindola   if (Expr == V)
3937e2b7567SRafael Espindola     return true;
3947e2b7567SRafael Espindola 
3957e2b7567SRafael Espindola   auto *C = dyn_cast<Constant>(V);
3967e2b7567SRafael Espindola   if (!C)
3977e2b7567SRafael Espindola     return false;
3987e2b7567SRafael Espindola 
3997e2b7567SRafael Espindola   auto *CE = dyn_cast<ConstantExpr>(Expr);
4007e2b7567SRafael Espindola   if (!CE)
4017e2b7567SRafael Espindola     return false;
4027e2b7567SRafael Espindola 
4037e2b7567SRafael Espindola   SmallPtrSet<ConstantExpr *, 4> Cache;
4047e2b7567SRafael Espindola   return contains(Cache, CE, C);
4057e2b7567SRafael Espindola }
406ecefe5a8SEugene Zelenko #endif // NDEBUG
407ef860a24SChandler Carruth 
4081ed53963SDavide Italiano void Value::doRAUW(Value *New, bool NoMetadata) {
409ef860a24SChandler Carruth   assert(New && "Value::replaceAllUsesWith(<null>) is invalid!");
4107e2b7567SRafael Espindola   assert(!contains(New, this) &&
4117e2b7567SRafael Espindola          "this->replaceAllUsesWith(expr(this)) is NOT valid!");
412ef860a24SChandler Carruth   assert(New->getType() == getType() &&
413ef860a24SChandler Carruth          "replaceAllUses of value with new value of different type!");
414ef860a24SChandler Carruth 
415ef860a24SChandler Carruth   // Notify all ValueHandles (if present) that this value is going away.
416ef860a24SChandler Carruth   if (HasValueHandle)
417ef860a24SChandler Carruth     ValueHandleBase::ValueIsRAUWd(this, New);
4181ed53963SDavide Italiano   if (!NoMetadata && isUsedByMetadata())
4195bf8fef5SDuncan P. N. Exon Smith     ValueAsMetadata::handleRAUW(this, New);
420ef860a24SChandler Carruth 
42181bbf742STeresa Johnson   while (!materialized_use_empty()) {
422ef860a24SChandler Carruth     Use &U = *UseList;
423ef860a24SChandler Carruth     // Must handle Constants specially, we cannot call replaceUsesOfWith on a
424ef860a24SChandler Carruth     // constant because they are uniqued.
4256b238633SRafael Espindola     if (auto *C = dyn_cast<Constant>(U.getUser())) {
426ef860a24SChandler Carruth       if (!isa<GlobalValue>(C)) {
4278914d290SMehdi Amini         C->handleOperandChange(this, New);
428ef860a24SChandler Carruth         continue;
429ef860a24SChandler Carruth       }
430ef860a24SChandler Carruth     }
431ef860a24SChandler Carruth 
432ef860a24SChandler Carruth     U.set(New);
433ef860a24SChandler Carruth   }
434ef860a24SChandler Carruth 
435ef860a24SChandler Carruth   if (BasicBlock *BB = dyn_cast<BasicBlock>(this))
436ef860a24SChandler Carruth     BB->replaceSuccessorsPhiUsesWith(cast<BasicBlock>(New));
437ef860a24SChandler Carruth }
438ef860a24SChandler Carruth 
4391ed53963SDavide Italiano void Value::replaceAllUsesWith(Value *New) {
4401ed53963SDavide Italiano   doRAUW(New, false /* NoMetadata */);
4411ed53963SDavide Italiano }
4421ed53963SDavide Italiano 
4431ed53963SDavide Italiano void Value::replaceNonMetadataUsesWith(Value *New) {
4441ed53963SDavide Italiano   doRAUW(New, true /* NoMetadata */);
4451ed53963SDavide Italiano }
4461ed53963SDavide Italiano 
447ec6217c9SGerolf Hoflehner // Like replaceAllUsesWith except it does not handle constants or basic blocks.
448ec6217c9SGerolf Hoflehner // This routine leaves uses within BB.
449ec6217c9SGerolf Hoflehner void Value::replaceUsesOutsideBlock(Value *New, BasicBlock *BB) {
450ec6217c9SGerolf Hoflehner   assert(New && "Value::replaceUsesOutsideBlock(<null>, BB) is invalid!");
451ec6217c9SGerolf Hoflehner   assert(!contains(New, this) &&
452ec6217c9SGerolf Hoflehner          "this->replaceUsesOutsideBlock(expr(this), BB) is NOT valid!");
453ec6217c9SGerolf Hoflehner   assert(New->getType() == getType() &&
454ec6217c9SGerolf Hoflehner          "replaceUses of value with new value of different type!");
455ec6217c9SGerolf Hoflehner   assert(BB && "Basic block that may contain a use of 'New' must be defined\n");
456ec6217c9SGerolf Hoflehner 
457ec6217c9SGerolf Hoflehner   use_iterator UI = use_begin(), E = use_end();
458ec6217c9SGerolf Hoflehner   for (; UI != E;) {
459ec6217c9SGerolf Hoflehner     Use &U = *UI;
460ec6217c9SGerolf Hoflehner     ++UI;
461ec6217c9SGerolf Hoflehner     auto *Usr = dyn_cast<Instruction>(U.getUser());
462ec6217c9SGerolf Hoflehner     if (Usr && Usr->getParent() == BB)
463ec6217c9SGerolf Hoflehner       continue;
464ec6217c9SGerolf Hoflehner     U.set(New);
465ec6217c9SGerolf Hoflehner   }
466ec6217c9SGerolf Hoflehner }
467ec6217c9SGerolf Hoflehner 
468ef860a24SChandler Carruth namespace {
469ef860a24SChandler Carruth // Various metrics for how much to strip off of pointers.
470ef860a24SChandler Carruth enum PointerStripKind {
471ef860a24SChandler Carruth   PSK_ZeroIndices,
472c229a4ffSRafael Espindola   PSK_ZeroIndicesAndAliases,
4735dde8094SPiotr Padlewski   PSK_ZeroIndicesAndAliasesAndInvariantGroups,
474ef860a24SChandler Carruth   PSK_InBoundsConstantIndices,
475ef860a24SChandler Carruth   PSK_InBounds
476ef860a24SChandler Carruth };
477ef860a24SChandler Carruth 
478ef860a24SChandler Carruth template <PointerStripKind StripKind>
4791dd20e65SCraig Topper static const Value *stripPointerCastsAndOffsets(const Value *V) {
480ef860a24SChandler Carruth   if (!V->getType()->isPointerTy())
481ef860a24SChandler Carruth     return V;
482ef860a24SChandler Carruth 
483ef860a24SChandler Carruth   // Even though we don't look through PHI nodes, we could be called on an
484ef860a24SChandler Carruth   // instruction in an unreachable block, which may be on a cycle.
4851dd20e65SCraig Topper   SmallPtrSet<const Value *, 4> Visited;
486ef860a24SChandler Carruth 
487ef860a24SChandler Carruth   Visited.insert(V);
488ef860a24SChandler Carruth   do {
4891dd20e65SCraig Topper     if (auto *GEP = dyn_cast<GEPOperator>(V)) {
490ef860a24SChandler Carruth       switch (StripKind) {
491c229a4ffSRafael Espindola       case PSK_ZeroIndicesAndAliases:
4925dde8094SPiotr Padlewski       case PSK_ZeroIndicesAndAliasesAndInvariantGroups:
493ef860a24SChandler Carruth       case PSK_ZeroIndices:
494ef860a24SChandler Carruth         if (!GEP->hasAllZeroIndices())
495ef860a24SChandler Carruth           return V;
496ef860a24SChandler Carruth         break;
497ef860a24SChandler Carruth       case PSK_InBoundsConstantIndices:
498ef860a24SChandler Carruth         if (!GEP->hasAllConstantIndices())
499ef860a24SChandler Carruth           return V;
500b03fd12cSJustin Bogner         LLVM_FALLTHROUGH;
501ef860a24SChandler Carruth       case PSK_InBounds:
502ef860a24SChandler Carruth         if (!GEP->isInBounds())
503ef860a24SChandler Carruth           return V;
504ef860a24SChandler Carruth         break;
505ef860a24SChandler Carruth       }
506ef860a24SChandler Carruth       V = GEP->getPointerOperand();
507b03bd4d9SMatt Arsenault     } else if (Operator::getOpcode(V) == Instruction::BitCast ||
508b03bd4d9SMatt Arsenault                Operator::getOpcode(V) == Instruction::AddrSpaceCast) {
509ef860a24SChandler Carruth       V = cast<Operator>(V)->getOperand(0);
5101dd20e65SCraig Topper     } else if (auto *GA = dyn_cast<GlobalAlias>(V)) {
5115ce32728SSanjoy Das       if (StripKind == PSK_ZeroIndices || GA->isInterposable())
512ef860a24SChandler Carruth         return V;
513ef860a24SChandler Carruth       V = GA->getAliasee();
514ef860a24SChandler Carruth     } else {
515610c966aSPiotr Padlewski       if (auto CS = ImmutableCallSite(V)) {
5161dd20e65SCraig Topper         if (const Value *RV = CS.getReturnedArgOperand()) {
5175c12d8feSHal Finkel           V = RV;
5185c12d8feSHal Finkel           continue;
5195c12d8feSHal Finkel         }
5205dde8094SPiotr Padlewski         // The result of launder.invariant.group must alias it's argument,
521610c966aSPiotr Padlewski         // but it can't be marked with returned attribute, that's why it needs
522610c966aSPiotr Padlewski         // special case.
5235dde8094SPiotr Padlewski         if (StripKind == PSK_ZeroIndicesAndAliasesAndInvariantGroups &&
524*5b3db45eSPiotr Padlewski             (CS.getIntrinsicID() == Intrinsic::launder_invariant_group ||
525*5b3db45eSPiotr Padlewski              CS.getIntrinsicID() == Intrinsic::strip_invariant_group)) {
526610c966aSPiotr Padlewski           V = CS.getArgOperand(0);
527610c966aSPiotr Padlewski           continue;
528610c966aSPiotr Padlewski         }
529610c966aSPiotr Padlewski       }
530ef860a24SChandler Carruth       return V;
531ef860a24SChandler Carruth     }
532ef860a24SChandler Carruth     assert(V->getType()->isPointerTy() && "Unexpected operand type!");
53370573dcdSDavid Blaikie   } while (Visited.insert(V).second);
534ef860a24SChandler Carruth 
535ef860a24SChandler Carruth   return V;
536ef860a24SChandler Carruth }
537ecefe5a8SEugene Zelenko } // end anonymous namespace
538ef860a24SChandler Carruth 
5391dd20e65SCraig Topper const Value *Value::stripPointerCasts() const {
540c229a4ffSRafael Espindola   return stripPointerCastsAndOffsets<PSK_ZeroIndicesAndAliases>(this);
541c229a4ffSRafael Espindola }
542c229a4ffSRafael Espindola 
5431dd20e65SCraig Topper const Value *Value::stripPointerCastsNoFollowAliases() const {
544ef860a24SChandler Carruth   return stripPointerCastsAndOffsets<PSK_ZeroIndices>(this);
545ef860a24SChandler Carruth }
546ef860a24SChandler Carruth 
5471dd20e65SCraig Topper const Value *Value::stripInBoundsConstantOffsets() const {
548ef860a24SChandler Carruth   return stripPointerCastsAndOffsets<PSK_InBoundsConstantIndices>(this);
549ef860a24SChandler Carruth }
550ef860a24SChandler Carruth 
5515dde8094SPiotr Padlewski const Value *Value::stripPointerCastsAndInvariantGroups() const {
5525dde8094SPiotr Padlewski   return stripPointerCastsAndOffsets<PSK_ZeroIndicesAndAliasesAndInvariantGroups>(
553610c966aSPiotr Padlewski       this);
554610c966aSPiotr Padlewski }
555610c966aSPiotr Padlewski 
5561dd20e65SCraig Topper const Value *
5571dd20e65SCraig Topper Value::stripAndAccumulateInBoundsConstantOffsets(const DataLayout &DL,
5581dd20e65SCraig Topper                                                  APInt &Offset) const {
559989e6308SChandler Carruth   if (!getType()->isPointerTy())
560989e6308SChandler Carruth     return this;
561989e6308SChandler Carruth 
562945b7e5aSElena Demikhovsky   assert(Offset.getBitWidth() == DL.getIndexSizeInBits(cast<PointerType>(
563989e6308SChandler Carruth                                      getType())->getAddressSpace()) &&
564945b7e5aSElena Demikhovsky          "The offset bit width does not match the DL specification.");
565989e6308SChandler Carruth 
566989e6308SChandler Carruth   // Even though we don't look through PHI nodes, we could be called on an
567989e6308SChandler Carruth   // instruction in an unreachable block, which may be on a cycle.
5681dd20e65SCraig Topper   SmallPtrSet<const Value *, 4> Visited;
569989e6308SChandler Carruth   Visited.insert(this);
5701dd20e65SCraig Topper   const Value *V = this;
571989e6308SChandler Carruth   do {
5721dd20e65SCraig Topper     if (auto *GEP = dyn_cast<GEPOperator>(V)) {
573989e6308SChandler Carruth       if (!GEP->isInBounds())
574989e6308SChandler Carruth         return V;
575ba689b33SChandler Carruth       APInt GEPOffset(Offset);
576ba689b33SChandler Carruth       if (!GEP->accumulateConstantOffset(DL, GEPOffset))
577989e6308SChandler Carruth         return V;
578ba689b33SChandler Carruth       Offset = GEPOffset;
579989e6308SChandler Carruth       V = GEP->getPointerOperand();
580d63df510SPhilip Reames     } else if (Operator::getOpcode(V) == Instruction::BitCast) {
581989e6308SChandler Carruth       V = cast<Operator>(V)->getOperand(0);
5821dd20e65SCraig Topper     } else if (auto *GA = dyn_cast<GlobalAlias>(V)) {
583989e6308SChandler Carruth       V = GA->getAliasee();
584989e6308SChandler Carruth     } else {
5851dd20e65SCraig Topper       if (auto CS = ImmutableCallSite(V))
5861dd20e65SCraig Topper         if (const Value *RV = CS.getReturnedArgOperand()) {
5875c12d8feSHal Finkel           V = RV;
5885c12d8feSHal Finkel           continue;
5895c12d8feSHal Finkel         }
5905c12d8feSHal Finkel 
591989e6308SChandler Carruth       return V;
592989e6308SChandler Carruth     }
593989e6308SChandler Carruth     assert(V->getType()->isPointerTy() && "Unexpected operand type!");
59470573dcdSDavid Blaikie   } while (Visited.insert(V).second);
595989e6308SChandler Carruth 
596989e6308SChandler Carruth   return V;
597989e6308SChandler Carruth }
598989e6308SChandler Carruth 
5991dd20e65SCraig Topper const Value *Value::stripInBoundsOffsets() const {
600ef860a24SChandler Carruth   return stripPointerCastsAndOffsets<PSK_InBounds>(this);
601ef860a24SChandler Carruth }
602ef860a24SChandler Carruth 
6033603de2fSBjorn Steinbrink uint64_t Value::getPointerDereferenceableBytes(const DataLayout &DL,
60400953cbeSSanjoy Das                                                bool &CanBeNull) const {
605345f0148SArtur Pilipenko   assert(getType()->isPointerTy() && "must be pointer");
606345f0148SArtur Pilipenko 
6073603de2fSBjorn Steinbrink   uint64_t DerefBytes = 0;
608345f0148SArtur Pilipenko   CanBeNull = false;
609345f0148SArtur Pilipenko   if (const Argument *A = dyn_cast<Argument>(this)) {
610345f0148SArtur Pilipenko     DerefBytes = A->getDereferenceableBytes();
6112da4d9d8SBjorn Steinbrink     if (DerefBytes == 0 && (A->hasByValAttr() || A->hasStructRetAttr())) {
612c27f81b9SBjorn Steinbrink       Type *PT = cast<PointerType>(A->getType())->getElementType();
6132da4d9d8SBjorn Steinbrink       if (PT->isSized())
614c27f81b9SBjorn Steinbrink         DerefBytes = DL.getTypeStoreSize(PT);
61500953cbeSSanjoy Das     }
616345f0148SArtur Pilipenko     if (DerefBytes == 0) {
617345f0148SArtur Pilipenko       DerefBytes = A->getDereferenceableOrNullBytes();
618345f0148SArtur Pilipenko       CanBeNull = true;
619345f0148SArtur Pilipenko     }
620345f0148SArtur Pilipenko   } else if (auto CS = ImmutableCallSite(this)) {
6216652a52eSReid Kleckner     DerefBytes = CS.getDereferenceableBytes(AttributeList::ReturnIndex);
622345f0148SArtur Pilipenko     if (DerefBytes == 0) {
6236652a52eSReid Kleckner       DerefBytes = CS.getDereferenceableOrNullBytes(AttributeList::ReturnIndex);
624345f0148SArtur Pilipenko       CanBeNull = true;
625345f0148SArtur Pilipenko     }
626345f0148SArtur Pilipenko   } else if (const LoadInst *LI = dyn_cast<LoadInst>(this)) {
627345f0148SArtur Pilipenko     if (MDNode *MD = LI->getMetadata(LLVMContext::MD_dereferenceable)) {
628345f0148SArtur Pilipenko       ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(0));
629345f0148SArtur Pilipenko       DerefBytes = CI->getLimitedValue();
630345f0148SArtur Pilipenko     }
631345f0148SArtur Pilipenko     if (DerefBytes == 0) {
632345f0148SArtur Pilipenko       if (MDNode *MD =
633345f0148SArtur Pilipenko               LI->getMetadata(LLVMContext::MD_dereferenceable_or_null)) {
634345f0148SArtur Pilipenko         ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(0));
635345f0148SArtur Pilipenko         DerefBytes = CI->getLimitedValue();
636345f0148SArtur Pilipenko       }
637345f0148SArtur Pilipenko       CanBeNull = true;
638345f0148SArtur Pilipenko     }
63900953cbeSSanjoy Das   } else if (auto *AI = dyn_cast<AllocaInst>(this)) {
640030123e8SBjorn Steinbrink     if (!AI->isArrayAllocation()) {
641030123e8SBjorn Steinbrink       DerefBytes = DL.getTypeStoreSize(AI->getAllocatedType());
64200953cbeSSanjoy Das       CanBeNull = false;
64300953cbeSSanjoy Das     }
64400953cbeSSanjoy Das   } else if (auto *GV = dyn_cast<GlobalVariable>(this)) {
64500953cbeSSanjoy Das     if (GV->getValueType()->isSized() && !GV->hasExternalWeakLinkage()) {
64600953cbeSSanjoy Das       // TODO: Don't outright reject hasExternalWeakLinkage but set the
64700953cbeSSanjoy Das       // CanBeNull flag.
64800953cbeSSanjoy Das       DerefBytes = DL.getTypeStoreSize(GV->getValueType());
64900953cbeSSanjoy Das       CanBeNull = false;
65000953cbeSSanjoy Das     }
651345f0148SArtur Pilipenko   }
652345f0148SArtur Pilipenko   return DerefBytes;
653345f0148SArtur Pilipenko }
654345f0148SArtur Pilipenko 
655ae51afc5SArtur Pilipenko unsigned Value::getPointerAlignment(const DataLayout &DL) const {
656ae51afc5SArtur Pilipenko   assert(getType()->isPointerTy() && "must be pointer");
657ae51afc5SArtur Pilipenko 
658ae51afc5SArtur Pilipenko   unsigned Align = 0;
659ae51afc5SArtur Pilipenko   if (auto *GO = dyn_cast<GlobalObject>(this)) {
660ffaa8a87SMikhail Maltsev     // Don't make any assumptions about function pointer alignment. Some
661ffaa8a87SMikhail Maltsev     // targets use the LSBs to store additional information.
662ffaa8a87SMikhail Maltsev     if (isa<Function>(GO))
663ffaa8a87SMikhail Maltsev       return 0;
664ae51afc5SArtur Pilipenko     Align = GO->getAlignment();
665ae51afc5SArtur Pilipenko     if (Align == 0) {
666ae51afc5SArtur Pilipenko       if (auto *GVar = dyn_cast<GlobalVariable>(GO)) {
667ae51afc5SArtur Pilipenko         Type *ObjectType = GVar->getValueType();
668ae51afc5SArtur Pilipenko         if (ObjectType->isSized()) {
669ae51afc5SArtur Pilipenko           // If the object is defined in the current Module, we'll be giving
670ae51afc5SArtur Pilipenko           // it the preferred alignment. Otherwise, we have to assume that it
671ae51afc5SArtur Pilipenko           // may only have the minimum ABI alignment.
672ae51afc5SArtur Pilipenko           if (GVar->isStrongDefinitionForLinker())
673ae51afc5SArtur Pilipenko             Align = DL.getPreferredAlignment(GVar);
674ae51afc5SArtur Pilipenko           else
675ae51afc5SArtur Pilipenko             Align = DL.getABITypeAlignment(ObjectType);
676ae51afc5SArtur Pilipenko         }
677ae51afc5SArtur Pilipenko       }
678ae51afc5SArtur Pilipenko     }
679ae51afc5SArtur Pilipenko   } else if (const Argument *A = dyn_cast<Argument>(this)) {
680ae51afc5SArtur Pilipenko     Align = A->getParamAlignment();
681ae51afc5SArtur Pilipenko 
682ae51afc5SArtur Pilipenko     if (!Align && A->hasStructRetAttr()) {
683ae51afc5SArtur Pilipenko       // An sret parameter has at least the ABI alignment of the return type.
684ae51afc5SArtur Pilipenko       Type *EltTy = cast<PointerType>(A->getType())->getElementType();
685ae51afc5SArtur Pilipenko       if (EltTy->isSized())
686ae51afc5SArtur Pilipenko         Align = DL.getABITypeAlignment(EltTy);
687ae51afc5SArtur Pilipenko     }
688c97eac65SArtur Pilipenko   } else if (const AllocaInst *AI = dyn_cast<AllocaInst>(this)) {
689ae51afc5SArtur Pilipenko     Align = AI->getAlignment();
690c97eac65SArtur Pilipenko     if (Align == 0) {
691c97eac65SArtur Pilipenko       Type *AllocatedType = AI->getAllocatedType();
692c97eac65SArtur Pilipenko       if (AllocatedType->isSized())
693c97eac65SArtur Pilipenko         Align = DL.getPrefTypeAlignment(AllocatedType);
694c97eac65SArtur Pilipenko     }
695c97eac65SArtur Pilipenko   } else if (auto CS = ImmutableCallSite(this))
696859f8b54SReid Kleckner     Align = CS.getAttributes().getRetAlignment();
697ae51afc5SArtur Pilipenko   else if (const LoadInst *LI = dyn_cast<LoadInst>(this))
698ae51afc5SArtur Pilipenko     if (MDNode *MD = LI->getMetadata(LLVMContext::MD_align)) {
699ae51afc5SArtur Pilipenko       ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(0));
700ae51afc5SArtur Pilipenko       Align = CI->getLimitedValue();
701ae51afc5SArtur Pilipenko     }
702ae51afc5SArtur Pilipenko 
703ae51afc5SArtur Pilipenko   return Align;
704ae51afc5SArtur Pilipenko }
705ae51afc5SArtur Pilipenko 
7061dd20e65SCraig Topper const Value *Value::DoPHITranslation(const BasicBlock *CurBB,
7071dd20e65SCraig Topper                                      const BasicBlock *PredBB) const {
7081dd20e65SCraig Topper   auto *PN = dyn_cast<PHINode>(this);
709ef860a24SChandler Carruth   if (PN && PN->getParent() == CurBB)
710ef860a24SChandler Carruth     return PN->getIncomingValueForBlock(PredBB);
711ef860a24SChandler Carruth   return this;
712ef860a24SChandler Carruth }
713ef860a24SChandler Carruth 
714ef860a24SChandler Carruth LLVMContext &Value::getContext() const { return VTy->getContext(); }
715ef860a24SChandler Carruth 
7163441ffe9SDuncan P. N. Exon Smith void Value::reverseUseList() {
7173441ffe9SDuncan P. N. Exon Smith   if (!UseList || !UseList->Next)
7183441ffe9SDuncan P. N. Exon Smith     // No need to reverse 0 or 1 uses.
7193441ffe9SDuncan P. N. Exon Smith     return;
7203441ffe9SDuncan P. N. Exon Smith 
7213441ffe9SDuncan P. N. Exon Smith   Use *Head = UseList;
7223441ffe9SDuncan P. N. Exon Smith   Use *Current = UseList->Next;
7233441ffe9SDuncan P. N. Exon Smith   Head->Next = nullptr;
7243441ffe9SDuncan P. N. Exon Smith   while (Current) {
7253441ffe9SDuncan P. N. Exon Smith     Use *Next = Current->Next;
7263441ffe9SDuncan P. N. Exon Smith     Current->Next = Head;
7273441ffe9SDuncan P. N. Exon Smith     Head->setPrev(&Current->Next);
7283441ffe9SDuncan P. N. Exon Smith     Head = Current;
7293441ffe9SDuncan P. N. Exon Smith     Current = Next;
7303441ffe9SDuncan P. N. Exon Smith   }
7313441ffe9SDuncan P. N. Exon Smith   UseList = Head;
7323441ffe9SDuncan P. N. Exon Smith   Head->setPrev(&UseList);
7333441ffe9SDuncan P. N. Exon Smith }
7343441ffe9SDuncan P. N. Exon Smith 
735ad830022SArnold Schwaighofer bool Value::isSwiftError() const {
736ad830022SArnold Schwaighofer   auto *Arg = dyn_cast<Argument>(this);
737ad830022SArnold Schwaighofer   if (Arg)
738ad830022SArnold Schwaighofer     return Arg->hasSwiftErrorAttr();
739ad830022SArnold Schwaighofer   auto *Alloca = dyn_cast<AllocaInst>(this);
740ad830022SArnold Schwaighofer   if (!Alloca)
741ad830022SArnold Schwaighofer     return false;
742ad830022SArnold Schwaighofer   return Alloca->isSwiftError();
743ad830022SArnold Schwaighofer }
744ad830022SArnold Schwaighofer 
745ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
746ef860a24SChandler Carruth //                             ValueHandleBase Class
747ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
748ef860a24SChandler Carruth 
749ef860a24SChandler Carruth void ValueHandleBase::AddToExistingUseList(ValueHandleBase **List) {
750ef860a24SChandler Carruth   assert(List && "Handle list is null?");
751ef860a24SChandler Carruth 
752ef860a24SChandler Carruth   // Splice ourselves into the list.
753ef860a24SChandler Carruth   Next = *List;
754ef860a24SChandler Carruth   *List = this;
755ef860a24SChandler Carruth   setPrevPtr(List);
756ef860a24SChandler Carruth   if (Next) {
757ef860a24SChandler Carruth     Next->setPrevPtr(&Next);
7586f08789dSSanjoy Das     assert(getValPtr() == Next->getValPtr() && "Added to wrong list?");
759ef860a24SChandler Carruth   }
760ef860a24SChandler Carruth }
761ef860a24SChandler Carruth 
762ef860a24SChandler Carruth void ValueHandleBase::AddToExistingUseListAfter(ValueHandleBase *List) {
763ef860a24SChandler Carruth   assert(List && "Must insert after existing node");
764ef860a24SChandler Carruth 
765ef860a24SChandler Carruth   Next = List->Next;
766ef860a24SChandler Carruth   setPrevPtr(&List->Next);
767ef860a24SChandler Carruth   List->Next = this;
768ef860a24SChandler Carruth   if (Next)
769ef860a24SChandler Carruth     Next->setPrevPtr(&Next);
770ef860a24SChandler Carruth }
771ef860a24SChandler Carruth 
772ef860a24SChandler Carruth void ValueHandleBase::AddToUseList() {
7736f08789dSSanjoy Das   assert(getValPtr() && "Null pointer doesn't have a use list!");
774ef860a24SChandler Carruth 
7756f08789dSSanjoy Das   LLVMContextImpl *pImpl = getValPtr()->getContext().pImpl;
776ef860a24SChandler Carruth 
7776f08789dSSanjoy Das   if (getValPtr()->HasValueHandle) {
778ef860a24SChandler Carruth     // If this value already has a ValueHandle, then it must be in the
779ef860a24SChandler Carruth     // ValueHandles map already.
7806f08789dSSanjoy Das     ValueHandleBase *&Entry = pImpl->ValueHandles[getValPtr()];
7812617dcceSCraig Topper     assert(Entry && "Value doesn't have any handles?");
782ef860a24SChandler Carruth     AddToExistingUseList(&Entry);
783ef860a24SChandler Carruth     return;
784ef860a24SChandler Carruth   }
785ef860a24SChandler Carruth 
786ef860a24SChandler Carruth   // Ok, it doesn't have any handles yet, so we must insert it into the
787ef860a24SChandler Carruth   // DenseMap.  However, doing this insertion could cause the DenseMap to
788ef860a24SChandler Carruth   // reallocate itself, which would invalidate all of the PrevP pointers that
789ef860a24SChandler Carruth   // point into the old table.  Handle this by checking for reallocation and
790ef860a24SChandler Carruth   // updating the stale pointers only if needed.
791ef860a24SChandler Carruth   DenseMap<Value*, ValueHandleBase*> &Handles = pImpl->ValueHandles;
792ef860a24SChandler Carruth   const void *OldBucketPtr = Handles.getPointerIntoBucketsArray();
793ef860a24SChandler Carruth 
7946f08789dSSanjoy Das   ValueHandleBase *&Entry = Handles[getValPtr()];
7952617dcceSCraig Topper   assert(!Entry && "Value really did already have handles?");
796ef860a24SChandler Carruth   AddToExistingUseList(&Entry);
7976f08789dSSanjoy Das   getValPtr()->HasValueHandle = true;
798ef860a24SChandler Carruth 
799ef860a24SChandler Carruth   // If reallocation didn't happen or if this was the first insertion, don't
800ef860a24SChandler Carruth   // walk the table.
801ef860a24SChandler Carruth   if (Handles.isPointerIntoBucketsArray(OldBucketPtr) ||
802ef860a24SChandler Carruth       Handles.size() == 1) {
803ef860a24SChandler Carruth     return;
804ef860a24SChandler Carruth   }
805ef860a24SChandler Carruth 
806ef860a24SChandler Carruth   // Okay, reallocation did happen.  Fix the Prev Pointers.
807ef860a24SChandler Carruth   for (DenseMap<Value*, ValueHandleBase*>::iterator I = Handles.begin(),
808ef860a24SChandler Carruth        E = Handles.end(); I != E; ++I) {
8096f08789dSSanjoy Das     assert(I->second && I->first == I->second->getValPtr() &&
810ef860a24SChandler Carruth            "List invariant broken!");
811ef860a24SChandler Carruth     I->second->setPrevPtr(&I->second);
812ef860a24SChandler Carruth   }
813ef860a24SChandler Carruth }
814ef860a24SChandler Carruth 
815ef860a24SChandler Carruth void ValueHandleBase::RemoveFromUseList() {
8166f08789dSSanjoy Das   assert(getValPtr() && getValPtr()->HasValueHandle &&
817ef860a24SChandler Carruth          "Pointer doesn't have a use list!");
818ef860a24SChandler Carruth 
819ef860a24SChandler Carruth   // Unlink this from its use list.
820ef860a24SChandler Carruth   ValueHandleBase **PrevPtr = getPrevPtr();
821ef860a24SChandler Carruth   assert(*PrevPtr == this && "List invariant broken");
822ef860a24SChandler Carruth 
823ef860a24SChandler Carruth   *PrevPtr = Next;
824ef860a24SChandler Carruth   if (Next) {
825ef860a24SChandler Carruth     assert(Next->getPrevPtr() == &Next && "List invariant broken");
826ef860a24SChandler Carruth     Next->setPrevPtr(PrevPtr);
827ef860a24SChandler Carruth     return;
828ef860a24SChandler Carruth   }
829ef860a24SChandler Carruth 
830ef860a24SChandler Carruth   // If the Next pointer was null, then it is possible that this was the last
831ef860a24SChandler Carruth   // ValueHandle watching VP.  If so, delete its entry from the ValueHandles
832ef860a24SChandler Carruth   // map.
8336f08789dSSanjoy Das   LLVMContextImpl *pImpl = getValPtr()->getContext().pImpl;
834ef860a24SChandler Carruth   DenseMap<Value*, ValueHandleBase*> &Handles = pImpl->ValueHandles;
835ef860a24SChandler Carruth   if (Handles.isPointerIntoBucketsArray(PrevPtr)) {
8366f08789dSSanjoy Das     Handles.erase(getValPtr());
8376f08789dSSanjoy Das     getValPtr()->HasValueHandle = false;
838ef860a24SChandler Carruth   }
839ef860a24SChandler Carruth }
840ef860a24SChandler Carruth 
841ef860a24SChandler Carruth void ValueHandleBase::ValueIsDeleted(Value *V) {
842ef860a24SChandler Carruth   assert(V->HasValueHandle && "Should only be called if ValueHandles present");
843ef860a24SChandler Carruth 
844ef860a24SChandler Carruth   // Get the linked list base, which is guaranteed to exist since the
845ef860a24SChandler Carruth   // HasValueHandle flag is set.
846ef860a24SChandler Carruth   LLVMContextImpl *pImpl = V->getContext().pImpl;
847ef860a24SChandler Carruth   ValueHandleBase *Entry = pImpl->ValueHandles[V];
848ef860a24SChandler Carruth   assert(Entry && "Value bit set but no entries exist");
849ef860a24SChandler Carruth 
850ef860a24SChandler Carruth   // We use a local ValueHandleBase as an iterator so that ValueHandles can add
851ef860a24SChandler Carruth   // and remove themselves from the list without breaking our iteration.  This
852ef860a24SChandler Carruth   // is not really an AssertingVH; we just have to give ValueHandleBase a kind.
853ef860a24SChandler Carruth   // Note that we deliberately do not the support the case when dropping a value
854ef860a24SChandler Carruth   // handle results in a new value handle being permanently added to the list
855ef860a24SChandler Carruth   // (as might occur in theory for CallbackVH's): the new value handle will not
856ef860a24SChandler Carruth   // be processed and the checking code will mete out righteous punishment if
857ef860a24SChandler Carruth   // the handle is still present once we have finished processing all the other
858ef860a24SChandler Carruth   // value handles (it is fine to momentarily add then remove a value handle).
859ef860a24SChandler Carruth   for (ValueHandleBase Iterator(Assert, *Entry); Entry; Entry = Iterator.Next) {
860ef860a24SChandler Carruth     Iterator.RemoveFromUseList();
861ef860a24SChandler Carruth     Iterator.AddToExistingUseListAfter(Entry);
862ef860a24SChandler Carruth     assert(Entry->Next == &Iterator && "Loop invariant broken.");
863ef860a24SChandler Carruth 
864ef860a24SChandler Carruth     switch (Entry->getKind()) {
865ef860a24SChandler Carruth     case Assert:
866ef860a24SChandler Carruth       break;
867f1c0eafdSSanjoy Das     case Weak:
868e6bca0eeSSanjoy Das     case WeakTracking:
869f1c0eafdSSanjoy Das       // WeakTracking and Weak just go to null, which unlinks them
870f1c0eafdSSanjoy Das       // from the list.
871c620761cSCraig Topper       Entry->operator=(nullptr);
872ef860a24SChandler Carruth       break;
873ef860a24SChandler Carruth     case Callback:
874ef860a24SChandler Carruth       // Forward to the subclass's implementation.
875ef860a24SChandler Carruth       static_cast<CallbackVH*>(Entry)->deleted();
876ef860a24SChandler Carruth       break;
877ef860a24SChandler Carruth     }
878ef860a24SChandler Carruth   }
879ef860a24SChandler Carruth 
880ef860a24SChandler Carruth   // All callbacks, weak references, and assertingVHs should be dropped by now.
881ef860a24SChandler Carruth   if (V->HasValueHandle) {
882ef860a24SChandler Carruth #ifndef NDEBUG      // Only in +Asserts mode...
883ef860a24SChandler Carruth     dbgs() << "While deleting: " << *V->getType() << " %" << V->getName()
884ef860a24SChandler Carruth            << "\n";
885ef860a24SChandler Carruth     if (pImpl->ValueHandles[V]->getKind() == Assert)
886ef860a24SChandler Carruth       llvm_unreachable("An asserting value handle still pointed to this"
887ef860a24SChandler Carruth                        " value!");
888ef860a24SChandler Carruth 
889ef860a24SChandler Carruth #endif
890ef860a24SChandler Carruth     llvm_unreachable("All references to V were not removed?");
891ef860a24SChandler Carruth   }
892ef860a24SChandler Carruth }
893ef860a24SChandler Carruth 
894ef860a24SChandler Carruth void ValueHandleBase::ValueIsRAUWd(Value *Old, Value *New) {
895ef860a24SChandler Carruth   assert(Old->HasValueHandle &&"Should only be called if ValueHandles present");
896ef860a24SChandler Carruth   assert(Old != New && "Changing value into itself!");
897c1892e2dSFrederic Riss   assert(Old->getType() == New->getType() &&
898c1892e2dSFrederic Riss          "replaceAllUses of value with new value of different type!");
899ef860a24SChandler Carruth 
900ef860a24SChandler Carruth   // Get the linked list base, which is guaranteed to exist since the
901ef860a24SChandler Carruth   // HasValueHandle flag is set.
902ef860a24SChandler Carruth   LLVMContextImpl *pImpl = Old->getContext().pImpl;
903ef860a24SChandler Carruth   ValueHandleBase *Entry = pImpl->ValueHandles[Old];
904ef860a24SChandler Carruth 
905ef860a24SChandler Carruth   assert(Entry && "Value bit set but no entries exist");
906ef860a24SChandler Carruth 
907ef860a24SChandler Carruth   // We use a local ValueHandleBase as an iterator so that
908ef860a24SChandler Carruth   // ValueHandles can add and remove themselves from the list without
909ef860a24SChandler Carruth   // breaking our iteration.  This is not really an AssertingVH; we
910ef860a24SChandler Carruth   // just have to give ValueHandleBase some kind.
911ef860a24SChandler Carruth   for (ValueHandleBase Iterator(Assert, *Entry); Entry; Entry = Iterator.Next) {
912ef860a24SChandler Carruth     Iterator.RemoveFromUseList();
913ef860a24SChandler Carruth     Iterator.AddToExistingUseListAfter(Entry);
914ef860a24SChandler Carruth     assert(Entry->Next == &Iterator && "Loop invariant broken.");
915ef860a24SChandler Carruth 
916ef860a24SChandler Carruth     switch (Entry->getKind()) {
917ef860a24SChandler Carruth     case Assert:
918f1c0eafdSSanjoy Das     case Weak:
919f1c0eafdSSanjoy Das       // Asserting and Weak handles do not follow RAUW implicitly.
920ef860a24SChandler Carruth       break;
921e6bca0eeSSanjoy Das     case WeakTracking:
9222cbeb00fSSanjoy Das       // Weak goes to the new value, which will unlink it from Old's list.
923ef860a24SChandler Carruth       Entry->operator=(New);
924ef860a24SChandler Carruth       break;
925ef860a24SChandler Carruth     case Callback:
926ef860a24SChandler Carruth       // Forward to the subclass's implementation.
927ef860a24SChandler Carruth       static_cast<CallbackVH*>(Entry)->allUsesReplacedWith(New);
928ef860a24SChandler Carruth       break;
929ef860a24SChandler Carruth     }
930ef860a24SChandler Carruth   }
931ef860a24SChandler Carruth 
932ef860a24SChandler Carruth #ifndef NDEBUG
9338a623820SSanjoy Das   // If any new weak value handles were added while processing the
934ef860a24SChandler Carruth   // list, then complain about it now.
935ef860a24SChandler Carruth   if (Old->HasValueHandle)
936ef860a24SChandler Carruth     for (Entry = pImpl->ValueHandles[Old]; Entry; Entry = Entry->Next)
937ef860a24SChandler Carruth       switch (Entry->getKind()) {
938e6bca0eeSSanjoy Das       case WeakTracking:
939ef860a24SChandler Carruth         dbgs() << "After RAUW from " << *Old->getType() << " %"
940ef860a24SChandler Carruth                << Old->getName() << " to " << *New->getType() << " %"
941ef860a24SChandler Carruth                << New->getName() << "\n";
9428a623820SSanjoy Das         llvm_unreachable(
943e6bca0eeSSanjoy Das             "A weak tracking value handle still pointed to the  old value!\n");
944ef860a24SChandler Carruth       default:
945ef860a24SChandler Carruth         break;
946ef860a24SChandler Carruth       }
947ef860a24SChandler Carruth #endif
948ef860a24SChandler Carruth }
949ef860a24SChandler Carruth 
950d12ccbd3SJuergen Ributzka // Pin the vtable to this file.
951d12ccbd3SJuergen Ributzka void CallbackVH::anchor() {}
952