xref: /llvm-project-15.0.7/llvm/lib/IR/Value.cpp (revision 4c1a1d3c)
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"
17*4c1a1d3cSReid 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"
32*4c1a1d3cSReid 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   //
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 {
1334de31bbaSVedant Kumar   return hasNItems(use_begin(), use_end(), N);
134ef860a24SChandler Carruth }
135ef860a24SChandler Carruth 
136ef860a24SChandler Carruth bool Value::hasNUsesOrMore(unsigned N) const {
1374de31bbaSVedant Kumar   return hasNItemsOrMore(use_begin(), use_end(), N);
138ef860a24SChandler Carruth }
139ef860a24SChandler Carruth 
140ef860a24SChandler Carruth bool Value::isUsedInBasicBlock(const BasicBlock *BB) const {
1410925b24dSJakob Stoklund Olesen   // This can be computed either by scanning the instructions in BB, or by
1420925b24dSJakob Stoklund Olesen   // scanning the use list of this Value. Both lists can be very long, but
1430925b24dSJakob Stoklund Olesen   // usually one is quite short.
1440925b24dSJakob Stoklund Olesen   //
1450925b24dSJakob Stoklund Olesen   // Scan both lists simultaneously until one is exhausted. This limits the
1460925b24dSJakob Stoklund Olesen   // search to the shorter list.
1470925b24dSJakob Stoklund Olesen   BasicBlock::const_iterator BI = BB->begin(), BE = BB->end();
148cdf47884SChandler Carruth   const_user_iterator UI = user_begin(), UE = user_end();
1490925b24dSJakob Stoklund Olesen   for (; BI != BE && UI != UE; ++BI, ++UI) {
1500925b24dSJakob Stoklund Olesen     // Scan basic block: Check if this Value is used by the instruction at BI.
15142531260SDavid Majnemer     if (is_contained(BI->operands(), this))
152ef860a24SChandler Carruth       return true;
1530925b24dSJakob Stoklund Olesen     // Scan use list: Check if the use at UI is in BB.
15442531260SDavid Majnemer     const auto *User = dyn_cast<Instruction>(*UI);
155ef860a24SChandler Carruth     if (User && User->getParent() == BB)
156ef860a24SChandler Carruth       return true;
157ef860a24SChandler Carruth   }
158ef860a24SChandler Carruth   return false;
159ef860a24SChandler Carruth }
160ef860a24SChandler Carruth 
1615a0872c2SVedant Kumar unsigned Value::getNumUses() const {
1625a0872c2SVedant Kumar   return (unsigned)std::distance(use_begin(), use_end());
1635a0872c2SVedant Kumar }
164ef860a24SChandler Carruth 
165ef860a24SChandler Carruth static bool getSymTab(Value *V, ValueSymbolTable *&ST) {
166c620761cSCraig Topper   ST = nullptr;
167ef860a24SChandler Carruth   if (Instruction *I = dyn_cast<Instruction>(V)) {
168ef860a24SChandler Carruth     if (BasicBlock *P = I->getParent())
169ef860a24SChandler Carruth       if (Function *PP = P->getParent())
170a53d49e1SMehdi Amini         ST = PP->getValueSymbolTable();
171ef860a24SChandler Carruth   } else if (BasicBlock *BB = dyn_cast<BasicBlock>(V)) {
172ef860a24SChandler Carruth     if (Function *P = BB->getParent())
173a53d49e1SMehdi Amini       ST = P->getValueSymbolTable();
174ef860a24SChandler Carruth   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
175ef860a24SChandler Carruth     if (Module *P = GV->getParent())
176ef860a24SChandler Carruth       ST = &P->getValueSymbolTable();
177ef860a24SChandler Carruth   } else if (Argument *A = dyn_cast<Argument>(V)) {
178ef860a24SChandler Carruth     if (Function *P = A->getParent())
179a53d49e1SMehdi Amini       ST = P->getValueSymbolTable();
1805bf8fef5SDuncan P. N. Exon Smith   } else {
181ef860a24SChandler Carruth     assert(isa<Constant>(V) && "Unknown value type!");
182ef860a24SChandler Carruth     return true;  // no name is setable for this.
183ef860a24SChandler Carruth   }
184ef860a24SChandler Carruth   return false;
185ef860a24SChandler Carruth }
186ef860a24SChandler Carruth 
1877349ab93SOwen Anderson ValueName *Value::getValueName() const {
1887349ab93SOwen Anderson   if (!HasName) return nullptr;
1897349ab93SOwen Anderson 
1907349ab93SOwen Anderson   LLVMContext &Ctx = getContext();
1917349ab93SOwen Anderson   auto I = Ctx.pImpl->ValueNames.find(this);
1927349ab93SOwen Anderson   assert(I != Ctx.pImpl->ValueNames.end() &&
1937349ab93SOwen Anderson          "No name entry found!");
1947349ab93SOwen Anderson 
1957349ab93SOwen Anderson   return I->second;
1967349ab93SOwen Anderson }
1977349ab93SOwen Anderson 
1987349ab93SOwen Anderson void Value::setValueName(ValueName *VN) {
1997349ab93SOwen Anderson   LLVMContext &Ctx = getContext();
2007349ab93SOwen Anderson 
2017349ab93SOwen Anderson   assert(HasName == Ctx.pImpl->ValueNames.count(this) &&
2027349ab93SOwen Anderson          "HasName bit out of sync!");
2037349ab93SOwen Anderson 
2047349ab93SOwen Anderson   if (!VN) {
2057349ab93SOwen Anderson     if (HasName)
2067349ab93SOwen Anderson       Ctx.pImpl->ValueNames.erase(this);
2077349ab93SOwen Anderson     HasName = false;
2087349ab93SOwen Anderson     return;
2097349ab93SOwen Anderson   }
2107349ab93SOwen Anderson 
2117349ab93SOwen Anderson   HasName = true;
2127349ab93SOwen Anderson   Ctx.pImpl->ValueNames[this] = VN;
2137349ab93SOwen Anderson }
2147349ab93SOwen Anderson 
215ef860a24SChandler Carruth StringRef Value::getName() const {
216ef860a24SChandler Carruth   // Make sure the empty string is still a C string. For historical reasons,
217ef860a24SChandler Carruth   // some clients want to call .data() on the result and expect it to be null
218ef860a24SChandler Carruth   // terminated.
2197349ab93SOwen Anderson   if (!hasName())
2205bf8fef5SDuncan P. N. Exon Smith     return StringRef("", 0);
2215bf8fef5SDuncan P. N. Exon Smith   return getValueName()->getKey();
222ef860a24SChandler Carruth }
223ef860a24SChandler Carruth 
224a7c0c18cSPete Cooper void Value::setNameImpl(const Twine &NewName) {
22509b4a8daSMehdi Amini   // Fast-path: LLVMContext can be set to strip out non-GlobalValue names
22650af49fcSMehdi Amini   if (getContext().shouldDiscardValueNames() && !isa<GlobalValue>(this))
22709b4a8daSMehdi Amini     return;
22809b4a8daSMehdi Amini 
229ef860a24SChandler Carruth   // Fast path for common IRBuilder case of setName("") when there is no name.
230ef860a24SChandler Carruth   if (NewName.isTriviallyEmpty() && !hasName())
231ef860a24SChandler Carruth     return;
232ef860a24SChandler Carruth 
233ef860a24SChandler Carruth   SmallString<256> NameData;
234ef860a24SChandler Carruth   StringRef NameRef = NewName.toStringRef(NameData);
23509d689f9SRafael Espindola   assert(NameRef.find_first_of(0) == StringRef::npos &&
23609d689f9SRafael Espindola          "Null bytes are not allowed in names");
237ef860a24SChandler Carruth 
238ef860a24SChandler Carruth   // Name isn't changing?
239ef860a24SChandler Carruth   if (getName() == NameRef)
240ef860a24SChandler Carruth     return;
241ef860a24SChandler Carruth 
2424c975578SSerge Guelton   // Cap the size of non-GlobalValue names.
2434c975578SSerge Guelton   if (NameRef.size() > NonGlobalValueMaxNameSize && !isa<GlobalValue>(this))
2444c975578SSerge Guelton     NameRef =
2454c975578SSerge Guelton         NameRef.substr(0, std::max(1u, (unsigned)NonGlobalValueMaxNameSize));
2464c975578SSerge Guelton 
247ef860a24SChandler Carruth   assert(!getType()->isVoidTy() && "Cannot assign a name to void values!");
248ef860a24SChandler Carruth 
249ef860a24SChandler Carruth   // Get the symbol table to update for this object.
250ef860a24SChandler Carruth   ValueSymbolTable *ST;
251ef860a24SChandler Carruth   if (getSymTab(this, ST))
252ef860a24SChandler Carruth     return;  // Cannot set a name on this value (e.g. constant).
253ef860a24SChandler Carruth 
254ef860a24SChandler Carruth   if (!ST) { // No symbol table to update?  Just do the change.
255ef860a24SChandler Carruth     if (NameRef.empty()) {
256ef860a24SChandler Carruth       // Free the name for this value.
2575bf8fef5SDuncan P. N. Exon Smith       destroyValueName();
258ef860a24SChandler Carruth       return;
259ef860a24SChandler Carruth     }
260ef860a24SChandler Carruth 
261ef860a24SChandler Carruth     // NOTE: Could optimize for the case the name is shrinking to not deallocate
262ef860a24SChandler Carruth     // then reallocated.
2635bf8fef5SDuncan P. N. Exon Smith     destroyValueName();
264ef860a24SChandler Carruth 
265ef860a24SChandler Carruth     // Create the new name.
2665bf8fef5SDuncan P. N. Exon Smith     setValueName(ValueName::Create(NameRef));
2675bf8fef5SDuncan P. N. Exon Smith     getValueName()->setValue(this);
268ef860a24SChandler Carruth     return;
269ef860a24SChandler Carruth   }
270ef860a24SChandler Carruth 
271ef860a24SChandler Carruth   // NOTE: Could optimize for the case the name is shrinking to not deallocate
272ef860a24SChandler Carruth   // then reallocated.
273ef860a24SChandler Carruth   if (hasName()) {
274ef860a24SChandler Carruth     // Remove old name.
2755bf8fef5SDuncan P. N. Exon Smith     ST->removeValueName(getValueName());
2765bf8fef5SDuncan P. N. Exon Smith     destroyValueName();
277ef860a24SChandler Carruth 
278ef860a24SChandler Carruth     if (NameRef.empty())
279ef860a24SChandler Carruth       return;
280ef860a24SChandler Carruth   }
281ef860a24SChandler Carruth 
282ef860a24SChandler Carruth   // Name is changing to something new.
2835bf8fef5SDuncan P. N. Exon Smith   setValueName(ST->createValueName(NameRef, this));
284ef860a24SChandler Carruth }
285ef860a24SChandler Carruth 
286a7c0c18cSPete Cooper void Value::setName(const Twine &NewName) {
287a7c0c18cSPete Cooper   setNameImpl(NewName);
288a7c0c18cSPete Cooper   if (Function *F = dyn_cast<Function>(this))
289a7c0c18cSPete Cooper     F->recalculateIntrinsicID();
290a7c0c18cSPete Cooper }
291a7c0c18cSPete Cooper 
292ef860a24SChandler Carruth void Value::takeName(Value *V) {
293c620761cSCraig Topper   ValueSymbolTable *ST = nullptr;
294ef860a24SChandler Carruth   // If this value has a name, drop it.
295ef860a24SChandler Carruth   if (hasName()) {
296ef860a24SChandler Carruth     // Get the symtab this is in.
297ef860a24SChandler Carruth     if (getSymTab(this, ST)) {
298ef860a24SChandler Carruth       // We can't set a name on this value, but we need to clear V's name if
299ef860a24SChandler Carruth       // it has one.
300ef860a24SChandler Carruth       if (V->hasName()) V->setName("");
301ef860a24SChandler Carruth       return;  // Cannot set a name on this value (e.g. constant).
302ef860a24SChandler Carruth     }
303ef860a24SChandler Carruth 
304ef860a24SChandler Carruth     // Remove old name.
305ef860a24SChandler Carruth     if (ST)
3065bf8fef5SDuncan P. N. Exon Smith       ST->removeValueName(getValueName());
3075bf8fef5SDuncan P. N. Exon Smith     destroyValueName();
308ef860a24SChandler Carruth   }
309ef860a24SChandler Carruth 
310ef860a24SChandler Carruth   // Now we know that this has no name.
311ef860a24SChandler Carruth 
312ef860a24SChandler Carruth   // If V has no name either, we're done.
313ef860a24SChandler Carruth   if (!V->hasName()) return;
314ef860a24SChandler Carruth 
315ef860a24SChandler Carruth   // Get this's symtab if we didn't before.
316ef860a24SChandler Carruth   if (!ST) {
317ef860a24SChandler Carruth     if (getSymTab(this, ST)) {
318ef860a24SChandler Carruth       // Clear V's name.
319ef860a24SChandler Carruth       V->setName("");
320ef860a24SChandler Carruth       return;  // Cannot set a name on this value (e.g. constant).
321ef860a24SChandler Carruth     }
322ef860a24SChandler Carruth   }
323ef860a24SChandler Carruth 
324ef860a24SChandler Carruth   // Get V's ST, this should always succed, because V has a name.
325ef860a24SChandler Carruth   ValueSymbolTable *VST;
326ef860a24SChandler Carruth   bool Failure = getSymTab(V, VST);
327ef860a24SChandler Carruth   assert(!Failure && "V has a name, so it should have a ST!"); (void)Failure;
328ef860a24SChandler Carruth 
329ef860a24SChandler Carruth   // If these values are both in the same symtab, we can do this very fast.
330ef860a24SChandler Carruth   // This works even if both values have no symtab yet.
331ef860a24SChandler Carruth   if (ST == VST) {
332ef860a24SChandler Carruth     // Take the name!
3335bf8fef5SDuncan P. N. Exon Smith     setValueName(V->getValueName());
3345bf8fef5SDuncan P. N. Exon Smith     V->setValueName(nullptr);
3355bf8fef5SDuncan P. N. Exon Smith     getValueName()->setValue(this);
336ef860a24SChandler Carruth     return;
337ef860a24SChandler Carruth   }
338ef860a24SChandler Carruth 
339ef860a24SChandler Carruth   // Otherwise, things are slightly more complex.  Remove V's name from VST and
340ef860a24SChandler Carruth   // then reinsert it into ST.
341ef860a24SChandler Carruth 
342ef860a24SChandler Carruth   if (VST)
3435bf8fef5SDuncan P. N. Exon Smith     VST->removeValueName(V->getValueName());
3445bf8fef5SDuncan P. N. Exon Smith   setValueName(V->getValueName());
3455bf8fef5SDuncan P. N. Exon Smith   V->setValueName(nullptr);
3465bf8fef5SDuncan P. N. Exon Smith   getValueName()->setValue(this);
347ef860a24SChandler Carruth 
348ef860a24SChandler Carruth   if (ST)
349ef860a24SChandler Carruth     ST->reinsertValue(this);
350ef860a24SChandler Carruth }
351ef860a24SChandler Carruth 
352eec48903SCraig Topper void Value::assertModuleIsMaterializedImpl() const {
353675bdcedSTodd Fiala #ifndef NDEBUG
354257a3536SRafael Espindola   const GlobalValue *GV = dyn_cast<GlobalValue>(this);
355257a3536SRafael Espindola   if (!GV)
356257a3536SRafael Espindola     return;
357257a3536SRafael Espindola   const Module *M = GV->getParent();
358257a3536SRafael Espindola   if (!M)
359257a3536SRafael Espindola     return;
360257a3536SRafael Espindola   assert(M->isMaterialized());
361675bdcedSTodd Fiala #endif
362257a3536SRafael Espindola }
363257a3536SRafael Espindola 
364675bdcedSTodd Fiala #ifndef NDEBUG
36571b7b68bSCraig Topper static bool contains(SmallPtrSetImpl<ConstantExpr *> &Cache, ConstantExpr *Expr,
3667e2b7567SRafael Espindola                      Constant *C) {
36770573dcdSDavid Blaikie   if (!Cache.insert(Expr).second)
3687e2b7567SRafael Espindola     return false;
3697e2b7567SRafael Espindola 
3707e2b7567SRafael Espindola   for (auto &O : Expr->operands()) {
3717e2b7567SRafael Espindola     if (O == C)
3727e2b7567SRafael Espindola       return true;
3737e2b7567SRafael Espindola     auto *CE = dyn_cast<ConstantExpr>(O);
3747e2b7567SRafael Espindola     if (!CE)
3757e2b7567SRafael Espindola       continue;
3767e2b7567SRafael Espindola     if (contains(Cache, CE, C))
3777e2b7567SRafael Espindola       return true;
3787e2b7567SRafael Espindola   }
3797e2b7567SRafael Espindola   return false;
3807e2b7567SRafael Espindola }
3817e2b7567SRafael Espindola 
3827e2b7567SRafael Espindola static bool contains(Value *Expr, Value *V) {
3837e2b7567SRafael Espindola   if (Expr == V)
3847e2b7567SRafael Espindola     return true;
3857e2b7567SRafael Espindola 
3867e2b7567SRafael Espindola   auto *C = dyn_cast<Constant>(V);
3877e2b7567SRafael Espindola   if (!C)
3887e2b7567SRafael Espindola     return false;
3897e2b7567SRafael Espindola 
3907e2b7567SRafael Espindola   auto *CE = dyn_cast<ConstantExpr>(Expr);
3917e2b7567SRafael Espindola   if (!CE)
3927e2b7567SRafael Espindola     return false;
3937e2b7567SRafael Espindola 
3947e2b7567SRafael Espindola   SmallPtrSet<ConstantExpr *, 4> Cache;
3957e2b7567SRafael Espindola   return contains(Cache, CE, C);
3967e2b7567SRafael Espindola }
397ecefe5a8SEugene Zelenko #endif // NDEBUG
398ef860a24SChandler Carruth 
399e69ae76bSJF Bastien void Value::doRAUW(Value *New, ReplaceMetadataUses ReplaceMetaUses) {
400ef860a24SChandler Carruth   assert(New && "Value::replaceAllUsesWith(<null>) is invalid!");
4017e2b7567SRafael Espindola   assert(!contains(New, this) &&
4027e2b7567SRafael Espindola          "this->replaceAllUsesWith(expr(this)) is NOT valid!");
403ef860a24SChandler Carruth   assert(New->getType() == getType() &&
404ef860a24SChandler Carruth          "replaceAllUses of value with new value of different type!");
405ef860a24SChandler Carruth 
406ef860a24SChandler Carruth   // Notify all ValueHandles (if present) that this value is going away.
407ef860a24SChandler Carruth   if (HasValueHandle)
408ef860a24SChandler Carruth     ValueHandleBase::ValueIsRAUWd(this, New);
409e69ae76bSJF Bastien   if (ReplaceMetaUses == ReplaceMetadataUses::Yes && isUsedByMetadata())
4105bf8fef5SDuncan P. N. Exon Smith     ValueAsMetadata::handleRAUW(this, New);
411ef860a24SChandler Carruth 
41281bbf742STeresa Johnson   while (!materialized_use_empty()) {
413ef860a24SChandler Carruth     Use &U = *UseList;
414ef860a24SChandler Carruth     // Must handle Constants specially, we cannot call replaceUsesOfWith on a
415ef860a24SChandler Carruth     // constant because they are uniqued.
4166b238633SRafael Espindola     if (auto *C = dyn_cast<Constant>(U.getUser())) {
417ef860a24SChandler Carruth       if (!isa<GlobalValue>(C)) {
4188914d290SMehdi Amini         C->handleOperandChange(this, New);
419ef860a24SChandler Carruth         continue;
420ef860a24SChandler Carruth       }
421ef860a24SChandler Carruth     }
422ef860a24SChandler Carruth 
423ef860a24SChandler Carruth     U.set(New);
424ef860a24SChandler Carruth   }
425ef860a24SChandler Carruth 
426ef860a24SChandler Carruth   if (BasicBlock *BB = dyn_cast<BasicBlock>(this))
427ef860a24SChandler Carruth     BB->replaceSuccessorsPhiUsesWith(cast<BasicBlock>(New));
428ef860a24SChandler Carruth }
429ef860a24SChandler Carruth 
4301ed53963SDavide Italiano void Value::replaceAllUsesWith(Value *New) {
431e69ae76bSJF Bastien   doRAUW(New, ReplaceMetadataUses::Yes);
4321ed53963SDavide Italiano }
4331ed53963SDavide Italiano 
4341ed53963SDavide Italiano void Value::replaceNonMetadataUsesWith(Value *New) {
435e69ae76bSJF Bastien   doRAUW(New, ReplaceMetadataUses::No);
4361ed53963SDavide Italiano }
4371ed53963SDavide Italiano 
438ec6217c9SGerolf Hoflehner // Like replaceAllUsesWith except it does not handle constants or basic blocks.
439ec6217c9SGerolf Hoflehner // This routine leaves uses within BB.
440ec6217c9SGerolf Hoflehner void Value::replaceUsesOutsideBlock(Value *New, BasicBlock *BB) {
441ec6217c9SGerolf Hoflehner   assert(New && "Value::replaceUsesOutsideBlock(<null>, BB) is invalid!");
442ec6217c9SGerolf Hoflehner   assert(!contains(New, this) &&
443ec6217c9SGerolf Hoflehner          "this->replaceUsesOutsideBlock(expr(this), BB) is NOT valid!");
444ec6217c9SGerolf Hoflehner   assert(New->getType() == getType() &&
445ec6217c9SGerolf Hoflehner          "replaceUses of value with new value of different type!");
446ec6217c9SGerolf Hoflehner   assert(BB && "Basic block that may contain a use of 'New' must be defined\n");
447ec6217c9SGerolf Hoflehner 
448081e990dSRoman Lebedev   replaceUsesWithIf(New, [BB](Use &U) {
449081e990dSRoman Lebedev     auto *I = dyn_cast<Instruction>(U.getUser());
450081e990dSRoman Lebedev     // Don't replace if it's an instruction in the BB basic block.
451081e990dSRoman Lebedev     return !I || I->getParent() != BB;
452081e990dSRoman Lebedev   });
453ec6217c9SGerolf Hoflehner }
454ec6217c9SGerolf Hoflehner 
455ef860a24SChandler Carruth namespace {
456ef860a24SChandler Carruth // Various metrics for how much to strip off of pointers.
457ef860a24SChandler Carruth enum PointerStripKind {
458ef860a24SChandler Carruth   PSK_ZeroIndices,
4598a410bceSErich Keane   PSK_ZeroIndicesAndAliases,
4602452d703SPeter Collingbourne   PSK_ZeroIndicesSameRepresentation,
4612452d703SPeter Collingbourne   PSK_ZeroIndicesAndInvariantGroups,
462ef860a24SChandler Carruth   PSK_InBoundsConstantIndices,
463ef860a24SChandler Carruth   PSK_InBounds
464ef860a24SChandler Carruth };
465ef860a24SChandler Carruth 
466ef860a24SChandler Carruth template <PointerStripKind StripKind>
4671dd20e65SCraig Topper static const Value *stripPointerCastsAndOffsets(const Value *V) {
468ef860a24SChandler Carruth   if (!V->getType()->isPointerTy())
469ef860a24SChandler Carruth     return V;
470ef860a24SChandler Carruth 
471ef860a24SChandler Carruth   // Even though we don't look through PHI nodes, we could be called on an
472ef860a24SChandler Carruth   // instruction in an unreachable block, which may be on a cycle.
4731dd20e65SCraig Topper   SmallPtrSet<const Value *, 4> Visited;
474ef860a24SChandler Carruth 
475ef860a24SChandler Carruth   Visited.insert(V);
476ef860a24SChandler Carruth   do {
4771dd20e65SCraig Topper     if (auto *GEP = dyn_cast<GEPOperator>(V)) {
478ef860a24SChandler Carruth       switch (StripKind) {
479ef860a24SChandler Carruth       case PSK_ZeroIndices:
4808a410bceSErich Keane       case PSK_ZeroIndicesAndAliases:
4812452d703SPeter Collingbourne       case PSK_ZeroIndicesSameRepresentation:
4822452d703SPeter Collingbourne       case PSK_ZeroIndicesAndInvariantGroups:
483ef860a24SChandler Carruth         if (!GEP->hasAllZeroIndices())
484ef860a24SChandler Carruth           return V;
485ef860a24SChandler Carruth         break;
486ef860a24SChandler Carruth       case PSK_InBoundsConstantIndices:
487ef860a24SChandler Carruth         if (!GEP->hasAllConstantIndices())
488ef860a24SChandler Carruth           return V;
489b03fd12cSJustin Bogner         LLVM_FALLTHROUGH;
490ef860a24SChandler Carruth       case PSK_InBounds:
491ef860a24SChandler Carruth         if (!GEP->isInBounds())
492ef860a24SChandler Carruth           return V;
493ef860a24SChandler Carruth         break;
494ef860a24SChandler Carruth       }
495ef860a24SChandler Carruth       V = GEP->getPointerOperand();
49640107ce7SJohannes Doerfert     } else if (Operator::getOpcode(V) == Instruction::BitCast) {
49740107ce7SJohannes Doerfert       V = cast<Operator>(V)->getOperand(0);
4982452d703SPeter Collingbourne     } else if (StripKind != PSK_ZeroIndicesSameRepresentation &&
499b03bd4d9SMatt Arsenault                Operator::getOpcode(V) == Instruction::AddrSpaceCast) {
50040107ce7SJohannes Doerfert       // TODO: If we know an address space cast will not change the
50140107ce7SJohannes Doerfert       //       representation we could look through it here as well.
502ef860a24SChandler Carruth       V = cast<Operator>(V)->getOperand(0);
5038a410bceSErich Keane     } else if (StripKind == PSK_ZeroIndicesAndAliases && isa<GlobalAlias>(V)) {
5048a410bceSErich Keane       V = cast<GlobalAlias>(V)->getAliasee();
505ef860a24SChandler Carruth     } else {
50690c09232SChandler Carruth       if (const auto *Call = dyn_cast<CallBase>(V)) {
50790c09232SChandler Carruth         if (const Value *RV = Call->getReturnedArgOperand()) {
5085c12d8feSHal Finkel           V = RV;
5095c12d8feSHal Finkel           continue;
5105c12d8feSHal Finkel         }
5115dde8094SPiotr Padlewski         // The result of launder.invariant.group must alias it's argument,
512610c966aSPiotr Padlewski         // but it can't be marked with returned attribute, that's why it needs
513610c966aSPiotr Padlewski         // special case.
5142452d703SPeter Collingbourne         if (StripKind == PSK_ZeroIndicesAndInvariantGroups &&
51590c09232SChandler Carruth             (Call->getIntrinsicID() == Intrinsic::launder_invariant_group ||
51690c09232SChandler Carruth              Call->getIntrinsicID() == Intrinsic::strip_invariant_group)) {
51790c09232SChandler Carruth           V = Call->getArgOperand(0);
518610c966aSPiotr Padlewski           continue;
519610c966aSPiotr Padlewski         }
520610c966aSPiotr Padlewski       }
521ef860a24SChandler Carruth       return V;
522ef860a24SChandler Carruth     }
523ef860a24SChandler Carruth     assert(V->getType()->isPointerTy() && "Unexpected operand type!");
52470573dcdSDavid Blaikie   } while (Visited.insert(V).second);
525ef860a24SChandler Carruth 
526ef860a24SChandler Carruth   return V;
527ef860a24SChandler Carruth }
528ecefe5a8SEugene Zelenko } // end anonymous namespace
529ef860a24SChandler Carruth 
5301dd20e65SCraig Topper const Value *Value::stripPointerCasts() const {
5312452d703SPeter Collingbourne   return stripPointerCastsAndOffsets<PSK_ZeroIndices>(this);
532c229a4ffSRafael Espindola }
533c229a4ffSRafael Espindola 
5348a410bceSErich Keane const Value *Value::stripPointerCastsAndAliases() const {
5358a410bceSErich Keane   return stripPointerCastsAndOffsets<PSK_ZeroIndicesAndAliases>(this);
5368a410bceSErich Keane }
5378a410bceSErich Keane 
53840107ce7SJohannes Doerfert const Value *Value::stripPointerCastsSameRepresentation() const {
5392452d703SPeter Collingbourne   return stripPointerCastsAndOffsets<PSK_ZeroIndicesSameRepresentation>(this);
540ef860a24SChandler Carruth }
541ef860a24SChandler Carruth 
5421dd20e65SCraig Topper const Value *Value::stripInBoundsConstantOffsets() const {
543ef860a24SChandler Carruth   return stripPointerCastsAndOffsets<PSK_InBoundsConstantIndices>(this);
544ef860a24SChandler Carruth }
545ef860a24SChandler Carruth 
5465dde8094SPiotr Padlewski const Value *Value::stripPointerCastsAndInvariantGroups() const {
5472452d703SPeter Collingbourne   return stripPointerCastsAndOffsets<PSK_ZeroIndicesAndInvariantGroups>(this);
548610c966aSPiotr Padlewski }
549610c966aSPiotr Padlewski 
5501dd20e65SCraig Topper const Value *
5513ed286a3SJohannes Doerfert Value::stripAndAccumulateConstantOffsets(const DataLayout &DL, APInt &Offset,
5523ed286a3SJohannes Doerfert                                          bool AllowNonInbounds) const {
5533ed286a3SJohannes Doerfert   if (!getType()->isPtrOrPtrVectorTy())
554989e6308SChandler Carruth     return this;
555989e6308SChandler Carruth 
5563ed286a3SJohannes Doerfert   unsigned BitWidth = Offset.getBitWidth();
5573ed286a3SJohannes Doerfert   assert(BitWidth == DL.getIndexTypeSizeInBits(getType()) &&
558945b7e5aSElena Demikhovsky          "The offset bit width does not match the DL specification.");
559989e6308SChandler Carruth 
560989e6308SChandler Carruth   // Even though we don't look through PHI nodes, we could be called on an
561989e6308SChandler Carruth   // instruction in an unreachable block, which may be on a cycle.
5621dd20e65SCraig Topper   SmallPtrSet<const Value *, 4> Visited;
563989e6308SChandler Carruth   Visited.insert(this);
5641dd20e65SCraig Topper   const Value *V = this;
565989e6308SChandler Carruth   do {
5661dd20e65SCraig Topper     if (auto *GEP = dyn_cast<GEPOperator>(V)) {
5673ed286a3SJohannes Doerfert       // If in-bounds was requested, we do not strip non-in-bounds GEPs.
5683ed286a3SJohannes Doerfert       if (!AllowNonInbounds && !GEP->isInBounds())
569989e6308SChandler Carruth         return V;
5703ed286a3SJohannes Doerfert 
5713ed286a3SJohannes Doerfert       // If one of the values we have visited is an addrspacecast, then
5723ed286a3SJohannes Doerfert       // the pointer type of this GEP may be different from the type
5733ed286a3SJohannes Doerfert       // of the Ptr parameter which was passed to this function.  This
5743ed286a3SJohannes Doerfert       // means when we construct GEPOffset, we need to use the size
5753ed286a3SJohannes Doerfert       // of GEP's pointer type rather than the size of the original
5763ed286a3SJohannes Doerfert       // pointer type.
5773ed286a3SJohannes Doerfert       APInt GEPOffset(DL.getIndexTypeSizeInBits(V->getType()), 0);
578ba689b33SChandler Carruth       if (!GEP->accumulateConstantOffset(DL, GEPOffset))
579989e6308SChandler Carruth         return V;
5803ed286a3SJohannes Doerfert 
5813ed286a3SJohannes Doerfert       // Stop traversal if the pointer offset wouldn't fit in the bit-width
5823ed286a3SJohannes Doerfert       // provided by the Offset argument. This can happen due to AddrSpaceCast
5833ed286a3SJohannes Doerfert       // stripping.
5843ed286a3SJohannes Doerfert       if (GEPOffset.getMinSignedBits() > BitWidth)
5853ed286a3SJohannes Doerfert         return V;
5863ed286a3SJohannes Doerfert 
5873ed286a3SJohannes Doerfert       Offset += GEPOffset.sextOrTrunc(BitWidth);
588989e6308SChandler Carruth       V = GEP->getPointerOperand();
5893ed286a3SJohannes Doerfert     } else if (Operator::getOpcode(V) == Instruction::BitCast ||
5903ed286a3SJohannes Doerfert                Operator::getOpcode(V) == Instruction::AddrSpaceCast) {
591989e6308SChandler Carruth       V = cast<Operator>(V)->getOperand(0);
5921dd20e65SCraig Topper     } else if (auto *GA = dyn_cast<GlobalAlias>(V)) {
5933ed286a3SJohannes Doerfert       if (!GA->isInterposable())
594989e6308SChandler Carruth         V = GA->getAliasee();
5953ed286a3SJohannes Doerfert     } else if (const auto *Call = dyn_cast<CallBase>(V)) {
5963ed286a3SJohannes Doerfert         if (const Value *RV = Call->getReturnedArgOperand())
5975c12d8feSHal Finkel           V = RV;
5985c12d8feSHal Finkel     }
5993ed286a3SJohannes Doerfert     assert(V->getType()->isPtrOrPtrVectorTy() && "Unexpected operand type!");
60070573dcdSDavid Blaikie   } while (Visited.insert(V).second);
601989e6308SChandler Carruth 
602989e6308SChandler Carruth   return V;
603989e6308SChandler Carruth }
604989e6308SChandler Carruth 
6051dd20e65SCraig Topper const Value *Value::stripInBoundsOffsets() const {
606ef860a24SChandler Carruth   return stripPointerCastsAndOffsets<PSK_InBounds>(this);
607ef860a24SChandler Carruth }
608ef860a24SChandler Carruth 
6093603de2fSBjorn Steinbrink uint64_t Value::getPointerDereferenceableBytes(const DataLayout &DL,
61000953cbeSSanjoy Das                                                bool &CanBeNull) const {
611345f0148SArtur Pilipenko   assert(getType()->isPointerTy() && "must be pointer");
612345f0148SArtur Pilipenko 
6133603de2fSBjorn Steinbrink   uint64_t DerefBytes = 0;
614345f0148SArtur Pilipenko   CanBeNull = false;
615345f0148SArtur Pilipenko   if (const Argument *A = dyn_cast<Argument>(this)) {
616345f0148SArtur Pilipenko     DerefBytes = A->getDereferenceableBytes();
6172da4d9d8SBjorn Steinbrink     if (DerefBytes == 0 && (A->hasByValAttr() || A->hasStructRetAttr())) {
618c27f81b9SBjorn Steinbrink       Type *PT = cast<PointerType>(A->getType())->getElementType();
6192da4d9d8SBjorn Steinbrink       if (PT->isSized())
620c27f81b9SBjorn Steinbrink         DerefBytes = DL.getTypeStoreSize(PT);
62100953cbeSSanjoy Das     }
622345f0148SArtur Pilipenko     if (DerefBytes == 0) {
623345f0148SArtur Pilipenko       DerefBytes = A->getDereferenceableOrNullBytes();
624345f0148SArtur Pilipenko       CanBeNull = true;
625345f0148SArtur Pilipenko     }
62690c09232SChandler Carruth   } else if (const auto *Call = dyn_cast<CallBase>(this)) {
62790c09232SChandler Carruth     DerefBytes = Call->getDereferenceableBytes(AttributeList::ReturnIndex);
628345f0148SArtur Pilipenko     if (DerefBytes == 0) {
62990c09232SChandler Carruth       DerefBytes =
63090c09232SChandler Carruth           Call->getDereferenceableOrNullBytes(AttributeList::ReturnIndex);
631345f0148SArtur Pilipenko       CanBeNull = true;
632345f0148SArtur Pilipenko     }
633345f0148SArtur Pilipenko   } else if (const LoadInst *LI = dyn_cast<LoadInst>(this)) {
634345f0148SArtur Pilipenko     if (MDNode *MD = LI->getMetadata(LLVMContext::MD_dereferenceable)) {
635345f0148SArtur Pilipenko       ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(0));
636345f0148SArtur Pilipenko       DerefBytes = CI->getLimitedValue();
637345f0148SArtur Pilipenko     }
638345f0148SArtur Pilipenko     if (DerefBytes == 0) {
639345f0148SArtur Pilipenko       if (MDNode *MD =
640345f0148SArtur Pilipenko               LI->getMetadata(LLVMContext::MD_dereferenceable_or_null)) {
641345f0148SArtur Pilipenko         ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(0));
642345f0148SArtur Pilipenko         DerefBytes = CI->getLimitedValue();
643345f0148SArtur Pilipenko       }
644345f0148SArtur Pilipenko       CanBeNull = true;
645345f0148SArtur Pilipenko     }
6466f13637aSRyan Taylor   } else if (auto *IP = dyn_cast<IntToPtrInst>(this)) {
6476f13637aSRyan Taylor     if (MDNode *MD = IP->getMetadata(LLVMContext::MD_dereferenceable)) {
6486f13637aSRyan Taylor       ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(0));
6496f13637aSRyan Taylor       DerefBytes = CI->getLimitedValue();
6506f13637aSRyan Taylor     }
6516f13637aSRyan Taylor     if (DerefBytes == 0) {
6526f13637aSRyan Taylor       if (MDNode *MD =
6536f13637aSRyan Taylor               IP->getMetadata(LLVMContext::MD_dereferenceable_or_null)) {
6546f13637aSRyan Taylor         ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(0));
6556f13637aSRyan Taylor         DerefBytes = CI->getLimitedValue();
6566f13637aSRyan Taylor       }
6576f13637aSRyan Taylor       CanBeNull = true;
6586f13637aSRyan Taylor     }
65900953cbeSSanjoy Das   } else if (auto *AI = dyn_cast<AllocaInst>(this)) {
660030123e8SBjorn Steinbrink     if (!AI->isArrayAllocation()) {
661030123e8SBjorn Steinbrink       DerefBytes = DL.getTypeStoreSize(AI->getAllocatedType());
66200953cbeSSanjoy Das       CanBeNull = false;
66300953cbeSSanjoy Das     }
66400953cbeSSanjoy Das   } else if (auto *GV = dyn_cast<GlobalVariable>(this)) {
66500953cbeSSanjoy Das     if (GV->getValueType()->isSized() && !GV->hasExternalWeakLinkage()) {
66600953cbeSSanjoy Das       // TODO: Don't outright reject hasExternalWeakLinkage but set the
66700953cbeSSanjoy Das       // CanBeNull flag.
66800953cbeSSanjoy Das       DerefBytes = DL.getTypeStoreSize(GV->getValueType());
66900953cbeSSanjoy Das       CanBeNull = false;
67000953cbeSSanjoy Das     }
671345f0148SArtur Pilipenko   }
672345f0148SArtur Pilipenko   return DerefBytes;
673345f0148SArtur Pilipenko }
674345f0148SArtur Pilipenko 
675bae629b9SGuillaume Chatelet MaybeAlign Value::getPointerAlignment(const DataLayout &DL) const {
676ae51afc5SArtur Pilipenko   assert(getType()->isPointerTy() && "must be pointer");
677ae51afc5SArtur Pilipenko   if (auto *GO = dyn_cast<GlobalObject>(this)) {
678308e82ecSMichael Platings     if (isa<Function>(GO)) {
67918f805a7SGuillaume Chatelet       const MaybeAlign FunctionPtrAlign = DL.getFunctionPtrAlign();
680308e82ecSMichael Platings       switch (DL.getFunctionPtrAlignType()) {
681308e82ecSMichael Platings       case DataLayout::FunctionPtrAlignType::Independent:
682bae629b9SGuillaume Chatelet         return FunctionPtrAlign;
683308e82ecSMichael Platings       case DataLayout::FunctionPtrAlignType::MultipleOfFunctionAlign:
684bae629b9SGuillaume Chatelet         return std::max(FunctionPtrAlign, MaybeAlign(GO->getAlignment()));
685308e82ecSMichael Platings       }
6866200a568SGuillaume Chatelet       llvm_unreachable("Unhandled FunctionPtrAlignType");
687308e82ecSMichael Platings     }
688bae629b9SGuillaume Chatelet     const MaybeAlign Alignment(GO->getAlignment());
689bae629b9SGuillaume Chatelet     if (!Alignment) {
690ae51afc5SArtur Pilipenko       if (auto *GVar = dyn_cast<GlobalVariable>(GO)) {
691ae51afc5SArtur Pilipenko         Type *ObjectType = GVar->getValueType();
692ae51afc5SArtur Pilipenko         if (ObjectType->isSized()) {
693ae51afc5SArtur Pilipenko           // If the object is defined in the current Module, we'll be giving
694ae51afc5SArtur Pilipenko           // it the preferred alignment. Otherwise, we have to assume that it
695ae51afc5SArtur Pilipenko           // may only have the minimum ABI alignment.
696ae51afc5SArtur Pilipenko           if (GVar->isStrongDefinitionForLinker())
697bae629b9SGuillaume Chatelet             return MaybeAlign(DL.getPreferredAlignment(GVar));
698ae51afc5SArtur Pilipenko           else
699bae629b9SGuillaume Chatelet             return Align(DL.getABITypeAlignment(ObjectType));
700ae51afc5SArtur Pilipenko         }
701ae51afc5SArtur Pilipenko       }
702ae51afc5SArtur Pilipenko     }
703bae629b9SGuillaume Chatelet     return Alignment;
704ae51afc5SArtur Pilipenko   } else if (const Argument *A = dyn_cast<Argument>(this)) {
705bae629b9SGuillaume Chatelet     const MaybeAlign Alignment(A->getParamAlignment());
706bae629b9SGuillaume Chatelet     if (!Alignment && A->hasStructRetAttr()) {
707ae51afc5SArtur Pilipenko       // An sret parameter has at least the ABI alignment of the return type.
708ae51afc5SArtur Pilipenko       Type *EltTy = cast<PointerType>(A->getType())->getElementType();
709ae51afc5SArtur Pilipenko       if (EltTy->isSized())
710bae629b9SGuillaume Chatelet         return Align(DL.getABITypeAlignment(EltTy));
711ae51afc5SArtur Pilipenko     }
712bae629b9SGuillaume Chatelet     return Alignment;
713c97eac65SArtur Pilipenko   } else if (const AllocaInst *AI = dyn_cast<AllocaInst>(this)) {
714bae629b9SGuillaume Chatelet     const MaybeAlign Alignment(AI->getAlignment());
715bae629b9SGuillaume Chatelet     if (!Alignment) {
716c97eac65SArtur Pilipenko       Type *AllocatedType = AI->getAllocatedType();
717c97eac65SArtur Pilipenko       if (AllocatedType->isSized())
718bae629b9SGuillaume Chatelet         return MaybeAlign(DL.getPrefTypeAlignment(AllocatedType));
719c97eac65SArtur Pilipenko     }
720bae629b9SGuillaume Chatelet     return Alignment;
721afd4a37bSHideto Ueno   } else if (const auto *Call = dyn_cast<CallBase>(this)) {
722bae629b9SGuillaume Chatelet     const MaybeAlign Alignment(Call->getRetAlignment());
723bae629b9SGuillaume Chatelet     if (!Alignment && Call->getCalledFunction())
724bae629b9SGuillaume Chatelet       return MaybeAlign(
725bae629b9SGuillaume Chatelet           Call->getCalledFunction()->getAttributes().getRetAlignment());
726bae629b9SGuillaume Chatelet     return Alignment;
7276200a568SGuillaume Chatelet   } else if (const LoadInst *LI = dyn_cast<LoadInst>(this)) {
728ae51afc5SArtur Pilipenko     if (MDNode *MD = LI->getMetadata(LLVMContext::MD_align)) {
729ae51afc5SArtur Pilipenko       ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(0));
730bae629b9SGuillaume Chatelet       return MaybeAlign(CI->getLimitedValue());
731ae51afc5SArtur Pilipenko     }
7326200a568SGuillaume Chatelet   }
733bae629b9SGuillaume Chatelet   return llvm::None;
734ae51afc5SArtur Pilipenko }
735ae51afc5SArtur Pilipenko 
7361dd20e65SCraig Topper const Value *Value::DoPHITranslation(const BasicBlock *CurBB,
7371dd20e65SCraig Topper                                      const BasicBlock *PredBB) const {
7381dd20e65SCraig Topper   auto *PN = dyn_cast<PHINode>(this);
739ef860a24SChandler Carruth   if (PN && PN->getParent() == CurBB)
740ef860a24SChandler Carruth     return PN->getIncomingValueForBlock(PredBB);
741ef860a24SChandler Carruth   return this;
742ef860a24SChandler Carruth }
743ef860a24SChandler Carruth 
744ef860a24SChandler Carruth LLVMContext &Value::getContext() const { return VTy->getContext(); }
745ef860a24SChandler Carruth 
7463441ffe9SDuncan P. N. Exon Smith void Value::reverseUseList() {
7473441ffe9SDuncan P. N. Exon Smith   if (!UseList || !UseList->Next)
7483441ffe9SDuncan P. N. Exon Smith     // No need to reverse 0 or 1 uses.
7493441ffe9SDuncan P. N. Exon Smith     return;
7503441ffe9SDuncan P. N. Exon Smith 
7513441ffe9SDuncan P. N. Exon Smith   Use *Head = UseList;
7523441ffe9SDuncan P. N. Exon Smith   Use *Current = UseList->Next;
7533441ffe9SDuncan P. N. Exon Smith   Head->Next = nullptr;
7543441ffe9SDuncan P. N. Exon Smith   while (Current) {
7553441ffe9SDuncan P. N. Exon Smith     Use *Next = Current->Next;
7563441ffe9SDuncan P. N. Exon Smith     Current->Next = Head;
7573441ffe9SDuncan P. N. Exon Smith     Head->setPrev(&Current->Next);
7583441ffe9SDuncan P. N. Exon Smith     Head = Current;
7593441ffe9SDuncan P. N. Exon Smith     Current = Next;
7603441ffe9SDuncan P. N. Exon Smith   }
7613441ffe9SDuncan P. N. Exon Smith   UseList = Head;
7623441ffe9SDuncan P. N. Exon Smith   Head->setPrev(&UseList);
7633441ffe9SDuncan P. N. Exon Smith }
7643441ffe9SDuncan P. N. Exon Smith 
765ad830022SArnold Schwaighofer bool Value::isSwiftError() const {
766ad830022SArnold Schwaighofer   auto *Arg = dyn_cast<Argument>(this);
767ad830022SArnold Schwaighofer   if (Arg)
768ad830022SArnold Schwaighofer     return Arg->hasSwiftErrorAttr();
769ad830022SArnold Schwaighofer   auto *Alloca = dyn_cast<AllocaInst>(this);
770ad830022SArnold Schwaighofer   if (!Alloca)
771ad830022SArnold Schwaighofer     return false;
772ad830022SArnold Schwaighofer   return Alloca->isSwiftError();
773ad830022SArnold Schwaighofer }
774ad830022SArnold Schwaighofer 
775ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
776ef860a24SChandler Carruth //                             ValueHandleBase Class
777ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
778ef860a24SChandler Carruth 
779ef860a24SChandler Carruth void ValueHandleBase::AddToExistingUseList(ValueHandleBase **List) {
780ef860a24SChandler Carruth   assert(List && "Handle list is null?");
781ef860a24SChandler Carruth 
782ef860a24SChandler Carruth   // Splice ourselves into the list.
783ef860a24SChandler Carruth   Next = *List;
784ef860a24SChandler Carruth   *List = this;
785ef860a24SChandler Carruth   setPrevPtr(List);
786ef860a24SChandler Carruth   if (Next) {
787ef860a24SChandler Carruth     Next->setPrevPtr(&Next);
7886f08789dSSanjoy Das     assert(getValPtr() == Next->getValPtr() && "Added to wrong list?");
789ef860a24SChandler Carruth   }
790ef860a24SChandler Carruth }
791ef860a24SChandler Carruth 
792ef860a24SChandler Carruth void ValueHandleBase::AddToExistingUseListAfter(ValueHandleBase *List) {
793ef860a24SChandler Carruth   assert(List && "Must insert after existing node");
794ef860a24SChandler Carruth 
795ef860a24SChandler Carruth   Next = List->Next;
796ef860a24SChandler Carruth   setPrevPtr(&List->Next);
797ef860a24SChandler Carruth   List->Next = this;
798ef860a24SChandler Carruth   if (Next)
799ef860a24SChandler Carruth     Next->setPrevPtr(&Next);
800ef860a24SChandler Carruth }
801ef860a24SChandler Carruth 
802ef860a24SChandler Carruth void ValueHandleBase::AddToUseList() {
8036f08789dSSanjoy Das   assert(getValPtr() && "Null pointer doesn't have a use list!");
804ef860a24SChandler Carruth 
8056f08789dSSanjoy Das   LLVMContextImpl *pImpl = getValPtr()->getContext().pImpl;
806ef860a24SChandler Carruth 
8076f08789dSSanjoy Das   if (getValPtr()->HasValueHandle) {
808ef860a24SChandler Carruth     // If this value already has a ValueHandle, then it must be in the
809ef860a24SChandler Carruth     // ValueHandles map already.
8106f08789dSSanjoy Das     ValueHandleBase *&Entry = pImpl->ValueHandles[getValPtr()];
8112617dcceSCraig Topper     assert(Entry && "Value doesn't have any handles?");
812ef860a24SChandler Carruth     AddToExistingUseList(&Entry);
813ef860a24SChandler Carruth     return;
814ef860a24SChandler Carruth   }
815ef860a24SChandler Carruth 
816ef860a24SChandler Carruth   // Ok, it doesn't have any handles yet, so we must insert it into the
817ef860a24SChandler Carruth   // DenseMap.  However, doing this insertion could cause the DenseMap to
818ef860a24SChandler Carruth   // reallocate itself, which would invalidate all of the PrevP pointers that
819ef860a24SChandler Carruth   // point into the old table.  Handle this by checking for reallocation and
820ef860a24SChandler Carruth   // updating the stale pointers only if needed.
821ef860a24SChandler Carruth   DenseMap<Value*, ValueHandleBase*> &Handles = pImpl->ValueHandles;
822ef860a24SChandler Carruth   const void *OldBucketPtr = Handles.getPointerIntoBucketsArray();
823ef860a24SChandler Carruth 
8246f08789dSSanjoy Das   ValueHandleBase *&Entry = Handles[getValPtr()];
8252617dcceSCraig Topper   assert(!Entry && "Value really did already have handles?");
826ef860a24SChandler Carruth   AddToExistingUseList(&Entry);
8276f08789dSSanjoy Das   getValPtr()->HasValueHandle = true;
828ef860a24SChandler Carruth 
829ef860a24SChandler Carruth   // If reallocation didn't happen or if this was the first insertion, don't
830ef860a24SChandler Carruth   // walk the table.
831ef860a24SChandler Carruth   if (Handles.isPointerIntoBucketsArray(OldBucketPtr) ||
832ef860a24SChandler Carruth       Handles.size() == 1) {
833ef860a24SChandler Carruth     return;
834ef860a24SChandler Carruth   }
835ef860a24SChandler Carruth 
836ef860a24SChandler Carruth   // Okay, reallocation did happen.  Fix the Prev Pointers.
837ef860a24SChandler Carruth   for (DenseMap<Value*, ValueHandleBase*>::iterator I = Handles.begin(),
838ef860a24SChandler Carruth        E = Handles.end(); I != E; ++I) {
8396f08789dSSanjoy Das     assert(I->second && I->first == I->second->getValPtr() &&
840ef860a24SChandler Carruth            "List invariant broken!");
841ef860a24SChandler Carruth     I->second->setPrevPtr(&I->second);
842ef860a24SChandler Carruth   }
843ef860a24SChandler Carruth }
844ef860a24SChandler Carruth 
845ef860a24SChandler Carruth void ValueHandleBase::RemoveFromUseList() {
8466f08789dSSanjoy Das   assert(getValPtr() && getValPtr()->HasValueHandle &&
847ef860a24SChandler Carruth          "Pointer doesn't have a use list!");
848ef860a24SChandler Carruth 
849ef860a24SChandler Carruth   // Unlink this from its use list.
850ef860a24SChandler Carruth   ValueHandleBase **PrevPtr = getPrevPtr();
851ef860a24SChandler Carruth   assert(*PrevPtr == this && "List invariant broken");
852ef860a24SChandler Carruth 
853ef860a24SChandler Carruth   *PrevPtr = Next;
854ef860a24SChandler Carruth   if (Next) {
855ef860a24SChandler Carruth     assert(Next->getPrevPtr() == &Next && "List invariant broken");
856ef860a24SChandler Carruth     Next->setPrevPtr(PrevPtr);
857ef860a24SChandler Carruth     return;
858ef860a24SChandler Carruth   }
859ef860a24SChandler Carruth 
860ef860a24SChandler Carruth   // If the Next pointer was null, then it is possible that this was the last
861ef860a24SChandler Carruth   // ValueHandle watching VP.  If so, delete its entry from the ValueHandles
862ef860a24SChandler Carruth   // map.
8636f08789dSSanjoy Das   LLVMContextImpl *pImpl = getValPtr()->getContext().pImpl;
864ef860a24SChandler Carruth   DenseMap<Value*, ValueHandleBase*> &Handles = pImpl->ValueHandles;
865ef860a24SChandler Carruth   if (Handles.isPointerIntoBucketsArray(PrevPtr)) {
8666f08789dSSanjoy Das     Handles.erase(getValPtr());
8676f08789dSSanjoy Das     getValPtr()->HasValueHandle = false;
868ef860a24SChandler Carruth   }
869ef860a24SChandler Carruth }
870ef860a24SChandler Carruth 
871ef860a24SChandler Carruth void ValueHandleBase::ValueIsDeleted(Value *V) {
872ef860a24SChandler Carruth   assert(V->HasValueHandle && "Should only be called if ValueHandles present");
873ef860a24SChandler Carruth 
874ef860a24SChandler Carruth   // Get the linked list base, which is guaranteed to exist since the
875ef860a24SChandler Carruth   // HasValueHandle flag is set.
876ef860a24SChandler Carruth   LLVMContextImpl *pImpl = V->getContext().pImpl;
877ef860a24SChandler Carruth   ValueHandleBase *Entry = pImpl->ValueHandles[V];
878ef860a24SChandler Carruth   assert(Entry && "Value bit set but no entries exist");
879ef860a24SChandler Carruth 
880ef860a24SChandler Carruth   // We use a local ValueHandleBase as an iterator so that ValueHandles can add
881ef860a24SChandler Carruth   // and remove themselves from the list without breaking our iteration.  This
882ef860a24SChandler Carruth   // is not really an AssertingVH; we just have to give ValueHandleBase a kind.
883ef860a24SChandler Carruth   // Note that we deliberately do not the support the case when dropping a value
884ef860a24SChandler Carruth   // handle results in a new value handle being permanently added to the list
885ef860a24SChandler Carruth   // (as might occur in theory for CallbackVH's): the new value handle will not
886ef860a24SChandler Carruth   // be processed and the checking code will mete out righteous punishment if
887ef860a24SChandler Carruth   // the handle is still present once we have finished processing all the other
888ef860a24SChandler Carruth   // value handles (it is fine to momentarily add then remove a value handle).
889ef860a24SChandler Carruth   for (ValueHandleBase Iterator(Assert, *Entry); Entry; Entry = Iterator.Next) {
890ef860a24SChandler Carruth     Iterator.RemoveFromUseList();
891ef860a24SChandler Carruth     Iterator.AddToExistingUseListAfter(Entry);
892ef860a24SChandler Carruth     assert(Entry->Next == &Iterator && "Loop invariant broken.");
893ef860a24SChandler Carruth 
894ef860a24SChandler Carruth     switch (Entry->getKind()) {
895ef860a24SChandler Carruth     case Assert:
896ef860a24SChandler Carruth       break;
897f1c0eafdSSanjoy Das     case Weak:
898e6bca0eeSSanjoy Das     case WeakTracking:
899f1c0eafdSSanjoy Das       // WeakTracking and Weak just go to null, which unlinks them
900f1c0eafdSSanjoy Das       // from the list.
901c620761cSCraig Topper       Entry->operator=(nullptr);
902ef860a24SChandler Carruth       break;
903ef860a24SChandler Carruth     case Callback:
904ef860a24SChandler Carruth       // Forward to the subclass's implementation.
905ef860a24SChandler Carruth       static_cast<CallbackVH*>(Entry)->deleted();
906ef860a24SChandler Carruth       break;
907ef860a24SChandler Carruth     }
908ef860a24SChandler Carruth   }
909ef860a24SChandler Carruth 
910ef860a24SChandler Carruth   // All callbacks, weak references, and assertingVHs should be dropped by now.
911ef860a24SChandler Carruth   if (V->HasValueHandle) {
912ef860a24SChandler Carruth #ifndef NDEBUG      // Only in +Asserts mode...
913ef860a24SChandler Carruth     dbgs() << "While deleting: " << *V->getType() << " %" << V->getName()
914ef860a24SChandler Carruth            << "\n";
915ef860a24SChandler Carruth     if (pImpl->ValueHandles[V]->getKind() == Assert)
916ef860a24SChandler Carruth       llvm_unreachable("An asserting value handle still pointed to this"
917ef860a24SChandler Carruth                        " value!");
918ef860a24SChandler Carruth 
919ef860a24SChandler Carruth #endif
920ef860a24SChandler Carruth     llvm_unreachable("All references to V were not removed?");
921ef860a24SChandler Carruth   }
922ef860a24SChandler Carruth }
923ef860a24SChandler Carruth 
924ef860a24SChandler Carruth void ValueHandleBase::ValueIsRAUWd(Value *Old, Value *New) {
925ef860a24SChandler Carruth   assert(Old->HasValueHandle &&"Should only be called if ValueHandles present");
926ef860a24SChandler Carruth   assert(Old != New && "Changing value into itself!");
927c1892e2dSFrederic Riss   assert(Old->getType() == New->getType() &&
928c1892e2dSFrederic Riss          "replaceAllUses of value with new value of different type!");
929ef860a24SChandler Carruth 
930ef860a24SChandler Carruth   // Get the linked list base, which is guaranteed to exist since the
931ef860a24SChandler Carruth   // HasValueHandle flag is set.
932ef860a24SChandler Carruth   LLVMContextImpl *pImpl = Old->getContext().pImpl;
933ef860a24SChandler Carruth   ValueHandleBase *Entry = pImpl->ValueHandles[Old];
934ef860a24SChandler Carruth 
935ef860a24SChandler Carruth   assert(Entry && "Value bit set but no entries exist");
936ef860a24SChandler Carruth 
937ef860a24SChandler Carruth   // We use a local ValueHandleBase as an iterator so that
938ef860a24SChandler Carruth   // ValueHandles can add and remove themselves from the list without
939ef860a24SChandler Carruth   // breaking our iteration.  This is not really an AssertingVH; we
940ef860a24SChandler Carruth   // just have to give ValueHandleBase some kind.
941ef860a24SChandler Carruth   for (ValueHandleBase Iterator(Assert, *Entry); Entry; Entry = Iterator.Next) {
942ef860a24SChandler Carruth     Iterator.RemoveFromUseList();
943ef860a24SChandler Carruth     Iterator.AddToExistingUseListAfter(Entry);
944ef860a24SChandler Carruth     assert(Entry->Next == &Iterator && "Loop invariant broken.");
945ef860a24SChandler Carruth 
946ef860a24SChandler Carruth     switch (Entry->getKind()) {
947ef860a24SChandler Carruth     case Assert:
948f1c0eafdSSanjoy Das     case Weak:
949f1c0eafdSSanjoy Das       // Asserting and Weak handles do not follow RAUW implicitly.
950ef860a24SChandler Carruth       break;
951e6bca0eeSSanjoy Das     case WeakTracking:
9522cbeb00fSSanjoy Das       // Weak goes to the new value, which will unlink it from Old's list.
953ef860a24SChandler Carruth       Entry->operator=(New);
954ef860a24SChandler Carruth       break;
955ef860a24SChandler Carruth     case Callback:
956ef860a24SChandler Carruth       // Forward to the subclass's implementation.
957ef860a24SChandler Carruth       static_cast<CallbackVH*>(Entry)->allUsesReplacedWith(New);
958ef860a24SChandler Carruth       break;
959ef860a24SChandler Carruth     }
960ef860a24SChandler Carruth   }
961ef860a24SChandler Carruth 
962ef860a24SChandler Carruth #ifndef NDEBUG
9638a623820SSanjoy Das   // If any new weak value handles were added while processing the
964ef860a24SChandler Carruth   // list, then complain about it now.
965ef860a24SChandler Carruth   if (Old->HasValueHandle)
966ef860a24SChandler Carruth     for (Entry = pImpl->ValueHandles[Old]; Entry; Entry = Entry->Next)
967ef860a24SChandler Carruth       switch (Entry->getKind()) {
968e6bca0eeSSanjoy Das       case WeakTracking:
969ef860a24SChandler Carruth         dbgs() << "After RAUW from " << *Old->getType() << " %"
970ef860a24SChandler Carruth                << Old->getName() << " to " << *New->getType() << " %"
971ef860a24SChandler Carruth                << New->getName() << "\n";
9728a623820SSanjoy Das         llvm_unreachable(
973e6bca0eeSSanjoy Das             "A weak tracking value handle still pointed to the old value!\n");
974ef860a24SChandler Carruth       default:
975ef860a24SChandler Carruth         break;
976ef860a24SChandler Carruth       }
977ef860a24SChandler Carruth #endif
978ef860a24SChandler Carruth }
979ef860a24SChandler Carruth 
980d12ccbd3SJuergen Ributzka // Pin the vtable to this file.
981d12ccbd3SJuergen Ributzka void CallbackVH::anchor() {}
982