xref: /llvm-project-15.0.7/llvm/lib/IR/Value.cpp (revision 9fd33f24)
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"
18b0407ba0SHal Finkel #include "llvm/IR/CallSite.h"
199fb823bbSChandler Carruth #include "llvm/IR/Constant.h"
209fb823bbSChandler Carruth #include "llvm/IR/Constants.h"
212e42c34dSHal Finkel #include "llvm/IR/DataLayout.h"
229fb823bbSChandler Carruth #include "llvm/IR/DerivedTypes.h"
2396ab8726SReid Kleckner #include "llvm/IR/DerivedUser.h"
2403eb0de9SChandler Carruth #include "llvm/IR/GetElementPtrTypeIterator.h"
259fb823bbSChandler Carruth #include "llvm/IR/InstrTypes.h"
269fb823bbSChandler Carruth #include "llvm/IR/Instructions.h"
27a7343d65SRamkumar Ramachandra #include "llvm/IR/IntrinsicInst.h"
289fb823bbSChandler Carruth #include "llvm/IR/Module.h"
299fb823bbSChandler Carruth #include "llvm/IR/Operator.h"
30a7343d65SRamkumar Ramachandra #include "llvm/IR/Statepoint.h"
314220e9c1SChandler Carruth #include "llvm/IR/ValueHandle.h"
329fb823bbSChandler Carruth #include "llvm/IR/ValueSymbolTable.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 
41ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
42ef860a24SChandler Carruth //                                Value Class
43ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
44ef860a24SChandler Carruth static inline Type *checkType(Type *Ty) {
45ef860a24SChandler Carruth   assert(Ty && "Value defined with a null type: Error!");
4616bf89ecSReid Kleckner   return Ty;
47ef860a24SChandler Carruth }
48ef860a24SChandler Carruth 
49ef860a24SChandler Carruth Value::Value(Type *ty, unsigned scid)
507349ab93SOwen Anderson     : VTy(checkType(ty)), UseList(nullptr), SubclassID(scid),
517349ab93SOwen Anderson       HasValueHandle(0), SubclassOptionalData(0), SubclassData(0),
52b4eede2cSPete Cooper       NumUserOperands(0), IsUsedByMD(false), HasName(false) {
53*9fd33f24SSerge Guelton   static_assert(ConstantFirstVal == 0, "!(SubclassID < ConstantFirstVal)");
54ef860a24SChandler Carruth   // FIXME: Why isn't this in the subclass gunk??
55ef860a24SChandler Carruth   // Note, we cannot call isa<CallInst> before the CallInst has been
56ef860a24SChandler Carruth   // constructed.
57ef860a24SChandler Carruth   if (SubclassID == Instruction::Call || SubclassID == Instruction::Invoke)
58ef860a24SChandler Carruth     assert((VTy->isFirstClassType() || VTy->isVoidTy() || VTy->isStructTy()) &&
59ef860a24SChandler Carruth            "invalid CallInst type!");
60ef860a24SChandler Carruth   else if (SubclassID != BasicBlockVal &&
61*9fd33f24SSerge Guelton            (/*SubclassID < ConstantFirstVal ||*/ SubclassID > ConstantLastVal))
62ef860a24SChandler Carruth     assert((VTy->isFirstClassType() || VTy->isVoidTy()) &&
63ef860a24SChandler Carruth            "Cannot create non-first-class values except for constants!");
6496ab8726SReid Kleckner   static_assert(sizeof(Value) == 2 * sizeof(void *) + 2 * sizeof(unsigned),
651762ad3eSReid Kleckner                 "Value too big");
66ef860a24SChandler Carruth }
67ef860a24SChandler Carruth 
68ef860a24SChandler Carruth Value::~Value() {
69ef860a24SChandler Carruth   // Notify all ValueHandles (if present) that this value is going away.
70ef860a24SChandler Carruth   if (HasValueHandle)
71ef860a24SChandler Carruth     ValueHandleBase::ValueIsDeleted(this);
725bf8fef5SDuncan P. N. Exon Smith   if (isUsedByMetadata())
735bf8fef5SDuncan P. N. Exon Smith     ValueAsMetadata::handleDeletion(this);
74ef860a24SChandler Carruth 
75ef860a24SChandler Carruth #ifndef NDEBUG      // Only in -g mode...
76ef860a24SChandler Carruth   // Check to make sure that there are no uses of this value that are still
77ef860a24SChandler Carruth   // around when the value is destroyed.  If there are, then we have a dangling
78b93fb82bSAndrew Kaylor   // reference and something is wrong.  This code is here to print out where
79b93fb82bSAndrew Kaylor   // the value is still being referenced.
80ef860a24SChandler Carruth   //
81ef860a24SChandler Carruth   if (!use_empty()) {
82ef860a24SChandler Carruth     dbgs() << "While deleting: " << *VTy << " %" << getName() << "\n";
83b93fb82bSAndrew Kaylor     for (auto *U : users())
84b93fb82bSAndrew Kaylor       dbgs() << "Use still stuck around after Def is destroyed:" << *U << "\n";
85ef860a24SChandler Carruth   }
86ef860a24SChandler Carruth #endif
87ef860a24SChandler Carruth   assert(use_empty() && "Uses remain when a value is destroyed!");
88ef860a24SChandler Carruth 
89ef860a24SChandler Carruth   // If this value is named, destroy the name.  This should not be in a symtab
90ef860a24SChandler Carruth   // at this point.
915bf8fef5SDuncan P. N. Exon Smith   destroyValueName();
92ef860a24SChandler Carruth }
93ef860a24SChandler Carruth 
9496ab8726SReid Kleckner void Value::deleteValue() {
9596ab8726SReid Kleckner   switch (getValueID()) {
9696ab8726SReid Kleckner #define HANDLE_VALUE(Name)                                                     \
9796ab8726SReid Kleckner   case Value::Name##Val:                                                       \
9896ab8726SReid Kleckner     delete static_cast<Name *>(this);                                          \
9996ab8726SReid Kleckner     break;
10096ab8726SReid Kleckner #define HANDLE_MEMORY_VALUE(Name)                                              \
10196ab8726SReid Kleckner   case Value::Name##Val:                                                       \
10296ab8726SReid Kleckner     static_cast<DerivedUser *>(this)->DeleteValue(                             \
10396ab8726SReid Kleckner         static_cast<DerivedUser *>(this));                                     \
10496ab8726SReid Kleckner     break;
10596ab8726SReid Kleckner #define HANDLE_INSTRUCTION(Name)  /* nothing */
10696ab8726SReid Kleckner #include "llvm/IR/Value.def"
10796ab8726SReid Kleckner 
10896ab8726SReid Kleckner #define HANDLE_INST(N, OPC, CLASS)                                             \
10996ab8726SReid Kleckner   case Value::InstructionVal + Instruction::OPC:                               \
11096ab8726SReid Kleckner     delete static_cast<CLASS *>(this);                                         \
11196ab8726SReid Kleckner     break;
11296ab8726SReid Kleckner #define HANDLE_USER_INST(N, OPC, CLASS)
11396ab8726SReid Kleckner #include "llvm/IR/Instruction.def"
11496ab8726SReid Kleckner 
11596ab8726SReid Kleckner   default:
11696ab8726SReid Kleckner     llvm_unreachable("attempting to delete unknown value kind");
11796ab8726SReid Kleckner   }
11896ab8726SReid Kleckner }
11996ab8726SReid Kleckner 
1205bf8fef5SDuncan P. N. Exon Smith void Value::destroyValueName() {
1215bf8fef5SDuncan P. N. Exon Smith   ValueName *Name = getValueName();
1225bf8fef5SDuncan P. N. Exon Smith   if (Name)
1235bf8fef5SDuncan P. N. Exon Smith     Name->Destroy();
1245bf8fef5SDuncan P. N. Exon Smith   setValueName(nullptr);
1255bf8fef5SDuncan P. N. Exon Smith }
1265bf8fef5SDuncan P. N. Exon Smith 
127ef860a24SChandler Carruth bool Value::hasNUses(unsigned N) const {
128ef860a24SChandler Carruth   const_use_iterator UI = use_begin(), E = use_end();
129ef860a24SChandler Carruth 
130ef860a24SChandler Carruth   for (; N; --N, ++UI)
131ef860a24SChandler Carruth     if (UI == E) return false;  // Too few.
132ef860a24SChandler Carruth   return UI == E;
133ef860a24SChandler Carruth }
134ef860a24SChandler Carruth 
135ef860a24SChandler Carruth bool Value::hasNUsesOrMore(unsigned N) const {
136ef860a24SChandler Carruth   const_use_iterator UI = use_begin(), E = use_end();
137ef860a24SChandler Carruth 
138ef860a24SChandler Carruth   for (; N; --N, ++UI)
139ef860a24SChandler Carruth     if (UI == E) return false;  // Too few.
140ef860a24SChandler Carruth 
141ef860a24SChandler Carruth   return true;
142ef860a24SChandler Carruth }
143ef860a24SChandler Carruth 
144ef860a24SChandler Carruth bool Value::isUsedInBasicBlock(const BasicBlock *BB) const {
1450925b24dSJakob Stoklund Olesen   // This can be computed either by scanning the instructions in BB, or by
1460925b24dSJakob Stoklund Olesen   // scanning the use list of this Value. Both lists can be very long, but
1470925b24dSJakob Stoklund Olesen   // usually one is quite short.
1480925b24dSJakob Stoklund Olesen   //
1490925b24dSJakob Stoklund Olesen   // Scan both lists simultaneously until one is exhausted. This limits the
1500925b24dSJakob Stoklund Olesen   // search to the shorter list.
1510925b24dSJakob Stoklund Olesen   BasicBlock::const_iterator BI = BB->begin(), BE = BB->end();
152cdf47884SChandler Carruth   const_user_iterator UI = user_begin(), UE = user_end();
1530925b24dSJakob Stoklund Olesen   for (; BI != BE && UI != UE; ++BI, ++UI) {
1540925b24dSJakob Stoklund Olesen     // Scan basic block: Check if this Value is used by the instruction at BI.
15542531260SDavid Majnemer     if (is_contained(BI->operands(), this))
156ef860a24SChandler Carruth       return true;
1570925b24dSJakob Stoklund Olesen     // Scan use list: Check if the use at UI is in BB.
15842531260SDavid Majnemer     const auto *User = dyn_cast<Instruction>(*UI);
159ef860a24SChandler Carruth     if (User && User->getParent() == BB)
160ef860a24SChandler Carruth       return true;
161ef860a24SChandler Carruth   }
162ef860a24SChandler Carruth   return false;
163ef860a24SChandler Carruth }
164ef860a24SChandler Carruth 
165ef860a24SChandler Carruth unsigned Value::getNumUses() const {
166ef860a24SChandler Carruth   return (unsigned)std::distance(use_begin(), use_end());
167ef860a24SChandler Carruth }
168ef860a24SChandler Carruth 
169ef860a24SChandler Carruth static bool getSymTab(Value *V, ValueSymbolTable *&ST) {
170c620761cSCraig Topper   ST = nullptr;
171ef860a24SChandler Carruth   if (Instruction *I = dyn_cast<Instruction>(V)) {
172ef860a24SChandler Carruth     if (BasicBlock *P = I->getParent())
173ef860a24SChandler Carruth       if (Function *PP = P->getParent())
174a53d49e1SMehdi Amini         ST = PP->getValueSymbolTable();
175ef860a24SChandler Carruth   } else if (BasicBlock *BB = dyn_cast<BasicBlock>(V)) {
176ef860a24SChandler Carruth     if (Function *P = BB->getParent())
177a53d49e1SMehdi Amini       ST = P->getValueSymbolTable();
178ef860a24SChandler Carruth   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
179ef860a24SChandler Carruth     if (Module *P = GV->getParent())
180ef860a24SChandler Carruth       ST = &P->getValueSymbolTable();
181ef860a24SChandler Carruth   } else if (Argument *A = dyn_cast<Argument>(V)) {
182ef860a24SChandler Carruth     if (Function *P = A->getParent())
183a53d49e1SMehdi Amini       ST = P->getValueSymbolTable();
1845bf8fef5SDuncan P. N. Exon Smith   } else {
185ef860a24SChandler Carruth     assert(isa<Constant>(V) && "Unknown value type!");
186ef860a24SChandler Carruth     return true;  // no name is setable for this.
187ef860a24SChandler Carruth   }
188ef860a24SChandler Carruth   return false;
189ef860a24SChandler Carruth }
190ef860a24SChandler Carruth 
1917349ab93SOwen Anderson ValueName *Value::getValueName() const {
1927349ab93SOwen Anderson   if (!HasName) return nullptr;
1937349ab93SOwen Anderson 
1947349ab93SOwen Anderson   LLVMContext &Ctx = getContext();
1957349ab93SOwen Anderson   auto I = Ctx.pImpl->ValueNames.find(this);
1967349ab93SOwen Anderson   assert(I != Ctx.pImpl->ValueNames.end() &&
1977349ab93SOwen Anderson          "No name entry found!");
1987349ab93SOwen Anderson 
1997349ab93SOwen Anderson   return I->second;
2007349ab93SOwen Anderson }
2017349ab93SOwen Anderson 
2027349ab93SOwen Anderson void Value::setValueName(ValueName *VN) {
2037349ab93SOwen Anderson   LLVMContext &Ctx = getContext();
2047349ab93SOwen Anderson 
2057349ab93SOwen Anderson   assert(HasName == Ctx.pImpl->ValueNames.count(this) &&
2067349ab93SOwen Anderson          "HasName bit out of sync!");
2077349ab93SOwen Anderson 
2087349ab93SOwen Anderson   if (!VN) {
2097349ab93SOwen Anderson     if (HasName)
2107349ab93SOwen Anderson       Ctx.pImpl->ValueNames.erase(this);
2117349ab93SOwen Anderson     HasName = false;
2127349ab93SOwen Anderson     return;
2137349ab93SOwen Anderson   }
2147349ab93SOwen Anderson 
2157349ab93SOwen Anderson   HasName = true;
2167349ab93SOwen Anderson   Ctx.pImpl->ValueNames[this] = VN;
2177349ab93SOwen Anderson }
2187349ab93SOwen Anderson 
219ef860a24SChandler Carruth StringRef Value::getName() const {
220ef860a24SChandler Carruth   // Make sure the empty string is still a C string. For historical reasons,
221ef860a24SChandler Carruth   // some clients want to call .data() on the result and expect it to be null
222ef860a24SChandler Carruth   // terminated.
2237349ab93SOwen Anderson   if (!hasName())
2245bf8fef5SDuncan P. N. Exon Smith     return StringRef("", 0);
2255bf8fef5SDuncan P. N. Exon Smith   return getValueName()->getKey();
226ef860a24SChandler Carruth }
227ef860a24SChandler Carruth 
228a7c0c18cSPete Cooper void Value::setNameImpl(const Twine &NewName) {
22909b4a8daSMehdi Amini   // Fast-path: LLVMContext can be set to strip out non-GlobalValue names
23050af49fcSMehdi Amini   if (getContext().shouldDiscardValueNames() && !isa<GlobalValue>(this))
23109b4a8daSMehdi Amini     return;
23209b4a8daSMehdi Amini 
233ef860a24SChandler Carruth   // Fast path for common IRBuilder case of setName("") when there is no name.
234ef860a24SChandler Carruth   if (NewName.isTriviallyEmpty() && !hasName())
235ef860a24SChandler Carruth     return;
236ef860a24SChandler Carruth 
237ef860a24SChandler Carruth   SmallString<256> NameData;
238ef860a24SChandler Carruth   StringRef NameRef = NewName.toStringRef(NameData);
23909d689f9SRafael Espindola   assert(NameRef.find_first_of(0) == StringRef::npos &&
24009d689f9SRafael Espindola          "Null bytes are not allowed in names");
241ef860a24SChandler Carruth 
242ef860a24SChandler Carruth   // Name isn't changing?
243ef860a24SChandler Carruth   if (getName() == NameRef)
244ef860a24SChandler Carruth     return;
245ef860a24SChandler Carruth 
246ef860a24SChandler Carruth   assert(!getType()->isVoidTy() && "Cannot assign a name to void values!");
247ef860a24SChandler Carruth 
248ef860a24SChandler Carruth   // Get the symbol table to update for this object.
249ef860a24SChandler Carruth   ValueSymbolTable *ST;
250ef860a24SChandler Carruth   if (getSymTab(this, ST))
251ef860a24SChandler Carruth     return;  // Cannot set a name on this value (e.g. constant).
252ef860a24SChandler Carruth 
253ef860a24SChandler Carruth   if (!ST) { // No symbol table to update?  Just do the change.
254ef860a24SChandler Carruth     if (NameRef.empty()) {
255ef860a24SChandler Carruth       // Free the name for this value.
2565bf8fef5SDuncan P. N. Exon Smith       destroyValueName();
257ef860a24SChandler Carruth       return;
258ef860a24SChandler Carruth     }
259ef860a24SChandler Carruth 
260ef860a24SChandler Carruth     // NOTE: Could optimize for the case the name is shrinking to not deallocate
261ef860a24SChandler Carruth     // then reallocated.
2625bf8fef5SDuncan P. N. Exon Smith     destroyValueName();
263ef860a24SChandler Carruth 
264ef860a24SChandler Carruth     // Create the new name.
2655bf8fef5SDuncan P. N. Exon Smith     setValueName(ValueName::Create(NameRef));
2665bf8fef5SDuncan P. N. Exon Smith     getValueName()->setValue(this);
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.
272ef860a24SChandler Carruth   if (hasName()) {
273ef860a24SChandler Carruth     // Remove old name.
2745bf8fef5SDuncan P. N. Exon Smith     ST->removeValueName(getValueName());
2755bf8fef5SDuncan P. N. Exon Smith     destroyValueName();
276ef860a24SChandler Carruth 
277ef860a24SChandler Carruth     if (NameRef.empty())
278ef860a24SChandler Carruth       return;
279ef860a24SChandler Carruth   }
280ef860a24SChandler Carruth 
281ef860a24SChandler Carruth   // Name is changing to something new.
2825bf8fef5SDuncan P. N. Exon Smith   setValueName(ST->createValueName(NameRef, this));
283ef860a24SChandler Carruth }
284ef860a24SChandler Carruth 
285a7c0c18cSPete Cooper void Value::setName(const Twine &NewName) {
286a7c0c18cSPete Cooper   setNameImpl(NewName);
287a7c0c18cSPete Cooper   if (Function *F = dyn_cast<Function>(this))
288a7c0c18cSPete Cooper     F->recalculateIntrinsicID();
289a7c0c18cSPete Cooper }
290a7c0c18cSPete Cooper 
291ef860a24SChandler Carruth void Value::takeName(Value *V) {
292c620761cSCraig Topper   ValueSymbolTable *ST = nullptr;
293ef860a24SChandler Carruth   // If this value has a name, drop it.
294ef860a24SChandler Carruth   if (hasName()) {
295ef860a24SChandler Carruth     // Get the symtab this is in.
296ef860a24SChandler Carruth     if (getSymTab(this, ST)) {
297ef860a24SChandler Carruth       // We can't set a name on this value, but we need to clear V's name if
298ef860a24SChandler Carruth       // it has one.
299ef860a24SChandler Carruth       if (V->hasName()) V->setName("");
300ef860a24SChandler Carruth       return;  // Cannot set a name on this value (e.g. constant).
301ef860a24SChandler Carruth     }
302ef860a24SChandler Carruth 
303ef860a24SChandler Carruth     // Remove old name.
304ef860a24SChandler Carruth     if (ST)
3055bf8fef5SDuncan P. N. Exon Smith       ST->removeValueName(getValueName());
3065bf8fef5SDuncan P. N. Exon Smith     destroyValueName();
307ef860a24SChandler Carruth   }
308ef860a24SChandler Carruth 
309ef860a24SChandler Carruth   // Now we know that this has no name.
310ef860a24SChandler Carruth 
311ef860a24SChandler Carruth   // If V has no name either, we're done.
312ef860a24SChandler Carruth   if (!V->hasName()) return;
313ef860a24SChandler Carruth 
314ef860a24SChandler Carruth   // Get this's symtab if we didn't before.
315ef860a24SChandler Carruth   if (!ST) {
316ef860a24SChandler Carruth     if (getSymTab(this, ST)) {
317ef860a24SChandler Carruth       // Clear V's name.
318ef860a24SChandler Carruth       V->setName("");
319ef860a24SChandler Carruth       return;  // Cannot set a name on this value (e.g. constant).
320ef860a24SChandler Carruth     }
321ef860a24SChandler Carruth   }
322ef860a24SChandler Carruth 
323ef860a24SChandler Carruth   // Get V's ST, this should always succed, because V has a name.
324ef860a24SChandler Carruth   ValueSymbolTable *VST;
325ef860a24SChandler Carruth   bool Failure = getSymTab(V, VST);
326ef860a24SChandler Carruth   assert(!Failure && "V has a name, so it should have a ST!"); (void)Failure;
327ef860a24SChandler Carruth 
328ef860a24SChandler Carruth   // If these values are both in the same symtab, we can do this very fast.
329ef860a24SChandler Carruth   // This works even if both values have no symtab yet.
330ef860a24SChandler Carruth   if (ST == VST) {
331ef860a24SChandler Carruth     // Take the name!
3325bf8fef5SDuncan P. N. Exon Smith     setValueName(V->getValueName());
3335bf8fef5SDuncan P. N. Exon Smith     V->setValueName(nullptr);
3345bf8fef5SDuncan P. N. Exon Smith     getValueName()->setValue(this);
335ef860a24SChandler Carruth     return;
336ef860a24SChandler Carruth   }
337ef860a24SChandler Carruth 
338ef860a24SChandler Carruth   // Otherwise, things are slightly more complex.  Remove V's name from VST and
339ef860a24SChandler Carruth   // then reinsert it into ST.
340ef860a24SChandler Carruth 
341ef860a24SChandler Carruth   if (VST)
3425bf8fef5SDuncan P. N. Exon Smith     VST->removeValueName(V->getValueName());
3435bf8fef5SDuncan P. N. Exon Smith   setValueName(V->getValueName());
3445bf8fef5SDuncan P. N. Exon Smith   V->setValueName(nullptr);
3455bf8fef5SDuncan P. N. Exon Smith   getValueName()->setValue(this);
346ef860a24SChandler Carruth 
347ef860a24SChandler Carruth   if (ST)
348ef860a24SChandler Carruth     ST->reinsertValue(this);
349ef860a24SChandler Carruth }
350ef860a24SChandler Carruth 
351eec48903SCraig Topper void Value::assertModuleIsMaterializedImpl() const {
352675bdcedSTodd Fiala #ifndef NDEBUG
353257a3536SRafael Espindola   const GlobalValue *GV = dyn_cast<GlobalValue>(this);
354257a3536SRafael Espindola   if (!GV)
355257a3536SRafael Espindola     return;
356257a3536SRafael Espindola   const Module *M = GV->getParent();
357257a3536SRafael Espindola   if (!M)
358257a3536SRafael Espindola     return;
359257a3536SRafael Espindola   assert(M->isMaterialized());
360675bdcedSTodd Fiala #endif
361257a3536SRafael Espindola }
362257a3536SRafael Espindola 
363675bdcedSTodd Fiala #ifndef NDEBUG
36471b7b68bSCraig Topper static bool contains(SmallPtrSetImpl<ConstantExpr *> &Cache, ConstantExpr *Expr,
3657e2b7567SRafael Espindola                      Constant *C) {
36670573dcdSDavid Blaikie   if (!Cache.insert(Expr).second)
3677e2b7567SRafael Espindola     return false;
3687e2b7567SRafael Espindola 
3697e2b7567SRafael Espindola   for (auto &O : Expr->operands()) {
3707e2b7567SRafael Espindola     if (O == C)
3717e2b7567SRafael Espindola       return true;
3727e2b7567SRafael Espindola     auto *CE = dyn_cast<ConstantExpr>(O);
3737e2b7567SRafael Espindola     if (!CE)
3747e2b7567SRafael Espindola       continue;
3757e2b7567SRafael Espindola     if (contains(Cache, CE, C))
3767e2b7567SRafael Espindola       return true;
3777e2b7567SRafael Espindola   }
3787e2b7567SRafael Espindola   return false;
3797e2b7567SRafael Espindola }
3807e2b7567SRafael Espindola 
3817e2b7567SRafael Espindola static bool contains(Value *Expr, Value *V) {
3827e2b7567SRafael Espindola   if (Expr == V)
3837e2b7567SRafael Espindola     return true;
3847e2b7567SRafael Espindola 
3857e2b7567SRafael Espindola   auto *C = dyn_cast<Constant>(V);
3867e2b7567SRafael Espindola   if (!C)
3877e2b7567SRafael Espindola     return false;
3887e2b7567SRafael Espindola 
3897e2b7567SRafael Espindola   auto *CE = dyn_cast<ConstantExpr>(Expr);
3907e2b7567SRafael Espindola   if (!CE)
3917e2b7567SRafael Espindola     return false;
3927e2b7567SRafael Espindola 
3937e2b7567SRafael Espindola   SmallPtrSet<ConstantExpr *, 4> Cache;
3947e2b7567SRafael Espindola   return contains(Cache, CE, C);
3957e2b7567SRafael Espindola }
396ecefe5a8SEugene Zelenko #endif // NDEBUG
397ef860a24SChandler Carruth 
3981ed53963SDavide Italiano void Value::doRAUW(Value *New, bool NoMetadata) {
399ef860a24SChandler Carruth   assert(New && "Value::replaceAllUsesWith(<null>) is invalid!");
4007e2b7567SRafael Espindola   assert(!contains(New, this) &&
4017e2b7567SRafael Espindola          "this->replaceAllUsesWith(expr(this)) is NOT valid!");
402ef860a24SChandler Carruth   assert(New->getType() == getType() &&
403ef860a24SChandler Carruth          "replaceAllUses of value with new value of different type!");
404ef860a24SChandler Carruth 
405ef860a24SChandler Carruth   // Notify all ValueHandles (if present) that this value is going away.
406ef860a24SChandler Carruth   if (HasValueHandle)
407ef860a24SChandler Carruth     ValueHandleBase::ValueIsRAUWd(this, New);
4081ed53963SDavide Italiano   if (!NoMetadata && isUsedByMetadata())
4095bf8fef5SDuncan P. N. Exon Smith     ValueAsMetadata::handleRAUW(this, New);
410ef860a24SChandler Carruth 
411ef860a24SChandler Carruth   while (!use_empty()) {
412ef860a24SChandler Carruth     Use &U = *UseList;
413ef860a24SChandler Carruth     // Must handle Constants specially, we cannot call replaceUsesOfWith on a
414ef860a24SChandler Carruth     // constant because they are uniqued.
4156b238633SRafael Espindola     if (auto *C = dyn_cast<Constant>(U.getUser())) {
416ef860a24SChandler Carruth       if (!isa<GlobalValue>(C)) {
4178914d290SMehdi Amini         C->handleOperandChange(this, New);
418ef860a24SChandler Carruth         continue;
419ef860a24SChandler Carruth       }
420ef860a24SChandler Carruth     }
421ef860a24SChandler Carruth 
422ef860a24SChandler Carruth     U.set(New);
423ef860a24SChandler Carruth   }
424ef860a24SChandler Carruth 
425ef860a24SChandler Carruth   if (BasicBlock *BB = dyn_cast<BasicBlock>(this))
426ef860a24SChandler Carruth     BB->replaceSuccessorsPhiUsesWith(cast<BasicBlock>(New));
427ef860a24SChandler Carruth }
428ef860a24SChandler Carruth 
4291ed53963SDavide Italiano void Value::replaceAllUsesWith(Value *New) {
4301ed53963SDavide Italiano   doRAUW(New, false /* NoMetadata */);
4311ed53963SDavide Italiano }
4321ed53963SDavide Italiano 
4331ed53963SDavide Italiano void Value::replaceNonMetadataUsesWith(Value *New) {
4341ed53963SDavide Italiano   doRAUW(New, true /* NoMetadata */);
4351ed53963SDavide Italiano }
4361ed53963SDavide Italiano 
437ec6217c9SGerolf Hoflehner // Like replaceAllUsesWith except it does not handle constants or basic blocks.
438ec6217c9SGerolf Hoflehner // This routine leaves uses within BB.
439ec6217c9SGerolf Hoflehner void Value::replaceUsesOutsideBlock(Value *New, BasicBlock *BB) {
440ec6217c9SGerolf Hoflehner   assert(New && "Value::replaceUsesOutsideBlock(<null>, BB) is invalid!");
441ec6217c9SGerolf Hoflehner   assert(!contains(New, this) &&
442ec6217c9SGerolf Hoflehner          "this->replaceUsesOutsideBlock(expr(this), BB) is NOT valid!");
443ec6217c9SGerolf Hoflehner   assert(New->getType() == getType() &&
444ec6217c9SGerolf Hoflehner          "replaceUses of value with new value of different type!");
445ec6217c9SGerolf Hoflehner   assert(BB && "Basic block that may contain a use of 'New' must be defined\n");
446ec6217c9SGerolf Hoflehner 
447ec6217c9SGerolf Hoflehner   use_iterator UI = use_begin(), E = use_end();
448ec6217c9SGerolf Hoflehner   for (; UI != E;) {
449ec6217c9SGerolf Hoflehner     Use &U = *UI;
450ec6217c9SGerolf Hoflehner     ++UI;
451ec6217c9SGerolf Hoflehner     auto *Usr = dyn_cast<Instruction>(U.getUser());
452ec6217c9SGerolf Hoflehner     if (Usr && Usr->getParent() == BB)
453ec6217c9SGerolf Hoflehner       continue;
454ec6217c9SGerolf Hoflehner     U.set(New);
455ec6217c9SGerolf Hoflehner   }
456ec6217c9SGerolf Hoflehner }
457ec6217c9SGerolf Hoflehner 
4581a46affbSDavide Italiano void Value::replaceUsesExceptBlockAddr(Value *New) {
4591a46affbSDavide Italiano   use_iterator UI = use_begin(), E = use_end();
4601a46affbSDavide Italiano   for (; UI != E;) {
4611a46affbSDavide Italiano     Use &U = *UI;
4621a46affbSDavide Italiano     ++UI;
4631a46affbSDavide Italiano 
4641a46affbSDavide Italiano     if (isa<BlockAddress>(U.getUser()))
4651a46affbSDavide Italiano       continue;
4661a46affbSDavide Italiano 
4671a46affbSDavide Italiano     // Must handle Constants specially, we cannot call replaceUsesOfWith on a
4681a46affbSDavide Italiano     // constant because they are uniqued.
4691a46affbSDavide Italiano     if (auto *C = dyn_cast<Constant>(U.getUser())) {
4701a46affbSDavide Italiano       if (!isa<GlobalValue>(C)) {
4711a46affbSDavide Italiano         C->handleOperandChange(this, New);
4721a46affbSDavide Italiano         continue;
4731a46affbSDavide Italiano       }
4741a46affbSDavide Italiano     }
4751a46affbSDavide Italiano 
4761a46affbSDavide Italiano     U.set(New);
4771a46affbSDavide Italiano   }
4781a46affbSDavide Italiano }
4791a46affbSDavide Italiano 
480ef860a24SChandler Carruth namespace {
481ef860a24SChandler Carruth // Various metrics for how much to strip off of pointers.
482ef860a24SChandler Carruth enum PointerStripKind {
483ef860a24SChandler Carruth   PSK_ZeroIndices,
484c229a4ffSRafael Espindola   PSK_ZeroIndicesAndAliases,
485610c966aSPiotr Padlewski   PSK_ZeroIndicesAndAliasesAndBarriers,
486ef860a24SChandler Carruth   PSK_InBoundsConstantIndices,
487ef860a24SChandler Carruth   PSK_InBounds
488ef860a24SChandler Carruth };
489ef860a24SChandler Carruth 
490ef860a24SChandler Carruth template <PointerStripKind StripKind>
4911dd20e65SCraig Topper static const Value *stripPointerCastsAndOffsets(const Value *V) {
492ef860a24SChandler Carruth   if (!V->getType()->isPointerTy())
493ef860a24SChandler Carruth     return V;
494ef860a24SChandler Carruth 
495ef860a24SChandler Carruth   // Even though we don't look through PHI nodes, we could be called on an
496ef860a24SChandler Carruth   // instruction in an unreachable block, which may be on a cycle.
4971dd20e65SCraig Topper   SmallPtrSet<const Value *, 4> Visited;
498ef860a24SChandler Carruth 
499ef860a24SChandler Carruth   Visited.insert(V);
500ef860a24SChandler Carruth   do {
5011dd20e65SCraig Topper     if (auto *GEP = dyn_cast<GEPOperator>(V)) {
502ef860a24SChandler Carruth       switch (StripKind) {
503c229a4ffSRafael Espindola       case PSK_ZeroIndicesAndAliases:
504610c966aSPiotr Padlewski       case PSK_ZeroIndicesAndAliasesAndBarriers:
505ef860a24SChandler Carruth       case PSK_ZeroIndices:
506ef860a24SChandler Carruth         if (!GEP->hasAllZeroIndices())
507ef860a24SChandler Carruth           return V;
508ef860a24SChandler Carruth         break;
509ef860a24SChandler Carruth       case PSK_InBoundsConstantIndices:
510ef860a24SChandler Carruth         if (!GEP->hasAllConstantIndices())
511ef860a24SChandler Carruth           return V;
512b03fd12cSJustin Bogner         LLVM_FALLTHROUGH;
513ef860a24SChandler Carruth       case PSK_InBounds:
514ef860a24SChandler Carruth         if (!GEP->isInBounds())
515ef860a24SChandler Carruth           return V;
516ef860a24SChandler Carruth         break;
517ef860a24SChandler Carruth       }
518ef860a24SChandler Carruth       V = GEP->getPointerOperand();
519b03bd4d9SMatt Arsenault     } else if (Operator::getOpcode(V) == Instruction::BitCast ||
520b03bd4d9SMatt Arsenault                Operator::getOpcode(V) == Instruction::AddrSpaceCast) {
521ef860a24SChandler Carruth       V = cast<Operator>(V)->getOperand(0);
5221dd20e65SCraig Topper     } else if (auto *GA = dyn_cast<GlobalAlias>(V)) {
5235ce32728SSanjoy Das       if (StripKind == PSK_ZeroIndices || GA->isInterposable())
524ef860a24SChandler Carruth         return V;
525ef860a24SChandler Carruth       V = GA->getAliasee();
526ef860a24SChandler Carruth     } else {
527610c966aSPiotr Padlewski       if (auto CS = ImmutableCallSite(V)) {
5281dd20e65SCraig Topper         if (const Value *RV = CS.getReturnedArgOperand()) {
5295c12d8feSHal Finkel           V = RV;
5305c12d8feSHal Finkel           continue;
5315c12d8feSHal Finkel         }
532610c966aSPiotr Padlewski         // The result of invariant.group.barrier must alias it's argument,
533610c966aSPiotr Padlewski         // but it can't be marked with returned attribute, that's why it needs
534610c966aSPiotr Padlewski         // special case.
535610c966aSPiotr Padlewski         if (StripKind == PSK_ZeroIndicesAndAliasesAndBarriers &&
536610c966aSPiotr Padlewski             CS.getIntrinsicID() == Intrinsic::invariant_group_barrier) {
537610c966aSPiotr Padlewski           V = CS.getArgOperand(0);
538610c966aSPiotr Padlewski           continue;
539610c966aSPiotr Padlewski         }
540610c966aSPiotr Padlewski       }
541ef860a24SChandler Carruth       return V;
542ef860a24SChandler Carruth     }
543ef860a24SChandler Carruth     assert(V->getType()->isPointerTy() && "Unexpected operand type!");
54470573dcdSDavid Blaikie   } while (Visited.insert(V).second);
545ef860a24SChandler Carruth 
546ef860a24SChandler Carruth   return V;
547ef860a24SChandler Carruth }
548ecefe5a8SEugene Zelenko } // end anonymous namespace
549ef860a24SChandler Carruth 
5501dd20e65SCraig Topper const Value *Value::stripPointerCasts() const {
551c229a4ffSRafael Espindola   return stripPointerCastsAndOffsets<PSK_ZeroIndicesAndAliases>(this);
552c229a4ffSRafael Espindola }
553c229a4ffSRafael Espindola 
5541dd20e65SCraig Topper const Value *Value::stripPointerCastsNoFollowAliases() const {
555ef860a24SChandler Carruth   return stripPointerCastsAndOffsets<PSK_ZeroIndices>(this);
556ef860a24SChandler Carruth }
557ef860a24SChandler Carruth 
5581dd20e65SCraig Topper const Value *Value::stripInBoundsConstantOffsets() const {
559ef860a24SChandler Carruth   return stripPointerCastsAndOffsets<PSK_InBoundsConstantIndices>(this);
560ef860a24SChandler Carruth }
561ef860a24SChandler Carruth 
562610c966aSPiotr Padlewski const Value *Value::stripPointerCastsAndBarriers() const {
563610c966aSPiotr Padlewski   return stripPointerCastsAndOffsets<PSK_ZeroIndicesAndAliasesAndBarriers>(
564610c966aSPiotr Padlewski       this);
565610c966aSPiotr Padlewski }
566610c966aSPiotr Padlewski 
5671dd20e65SCraig Topper const Value *
5681dd20e65SCraig Topper Value::stripAndAccumulateInBoundsConstantOffsets(const DataLayout &DL,
5691dd20e65SCraig Topper                                                  APInt &Offset) const {
570989e6308SChandler Carruth   if (!getType()->isPointerTy())
571989e6308SChandler Carruth     return this;
572989e6308SChandler Carruth 
573989e6308SChandler Carruth   assert(Offset.getBitWidth() == DL.getPointerSizeInBits(cast<PointerType>(
574989e6308SChandler Carruth                                      getType())->getAddressSpace()) &&
575989e6308SChandler Carruth          "The offset must have exactly as many bits as our pointer.");
576989e6308SChandler Carruth 
577989e6308SChandler Carruth   // Even though we don't look through PHI nodes, we could be called on an
578989e6308SChandler Carruth   // instruction in an unreachable block, which may be on a cycle.
5791dd20e65SCraig Topper   SmallPtrSet<const Value *, 4> Visited;
580989e6308SChandler Carruth   Visited.insert(this);
5811dd20e65SCraig Topper   const Value *V = this;
582989e6308SChandler Carruth   do {
5831dd20e65SCraig Topper     if (auto *GEP = dyn_cast<GEPOperator>(V)) {
584989e6308SChandler Carruth       if (!GEP->isInBounds())
585989e6308SChandler Carruth         return V;
586ba689b33SChandler Carruth       APInt GEPOffset(Offset);
587ba689b33SChandler Carruth       if (!GEP->accumulateConstantOffset(DL, GEPOffset))
588989e6308SChandler Carruth         return V;
589ba689b33SChandler Carruth       Offset = GEPOffset;
590989e6308SChandler Carruth       V = GEP->getPointerOperand();
591d63df510SPhilip Reames     } else if (Operator::getOpcode(V) == Instruction::BitCast) {
592989e6308SChandler Carruth       V = cast<Operator>(V)->getOperand(0);
5931dd20e65SCraig Topper     } else if (auto *GA = dyn_cast<GlobalAlias>(V)) {
594989e6308SChandler Carruth       V = GA->getAliasee();
595989e6308SChandler Carruth     } else {
5961dd20e65SCraig Topper       if (auto CS = ImmutableCallSite(V))
5971dd20e65SCraig Topper         if (const Value *RV = CS.getReturnedArgOperand()) {
5985c12d8feSHal Finkel           V = RV;
5995c12d8feSHal Finkel           continue;
6005c12d8feSHal Finkel         }
6015c12d8feSHal Finkel 
602989e6308SChandler Carruth       return V;
603989e6308SChandler Carruth     }
604989e6308SChandler Carruth     assert(V->getType()->isPointerTy() && "Unexpected operand type!");
60570573dcdSDavid Blaikie   } while (Visited.insert(V).second);
606989e6308SChandler Carruth 
607989e6308SChandler Carruth   return V;
608989e6308SChandler Carruth }
609989e6308SChandler Carruth 
6101dd20e65SCraig Topper const Value *Value::stripInBoundsOffsets() const {
611ef860a24SChandler Carruth   return stripPointerCastsAndOffsets<PSK_InBounds>(this);
612ef860a24SChandler Carruth }
613ef860a24SChandler Carruth 
61400953cbeSSanjoy Das unsigned Value::getPointerDereferenceableBytes(const DataLayout &DL,
61500953cbeSSanjoy Das                                                bool &CanBeNull) const {
616345f0148SArtur Pilipenko   assert(getType()->isPointerTy() && "must be pointer");
617345f0148SArtur Pilipenko 
618345f0148SArtur Pilipenko   unsigned DerefBytes = 0;
619345f0148SArtur Pilipenko   CanBeNull = false;
620345f0148SArtur Pilipenko   if (const Argument *A = dyn_cast<Argument>(this)) {
621345f0148SArtur Pilipenko     DerefBytes = A->getDereferenceableBytes();
62200953cbeSSanjoy Das     if (DerefBytes == 0 && A->hasByValAttr() && A->getType()->isSized()) {
62300953cbeSSanjoy Das       DerefBytes = DL.getTypeStoreSize(A->getType());
62400953cbeSSanjoy Das       CanBeNull = false;
62500953cbeSSanjoy Das     }
626345f0148SArtur Pilipenko     if (DerefBytes == 0) {
627345f0148SArtur Pilipenko       DerefBytes = A->getDereferenceableOrNullBytes();
628345f0148SArtur Pilipenko       CanBeNull = true;
629345f0148SArtur Pilipenko     }
630345f0148SArtur Pilipenko   } else if (auto CS = ImmutableCallSite(this)) {
6316652a52eSReid Kleckner     DerefBytes = CS.getDereferenceableBytes(AttributeList::ReturnIndex);
632345f0148SArtur Pilipenko     if (DerefBytes == 0) {
6336652a52eSReid Kleckner       DerefBytes = CS.getDereferenceableOrNullBytes(AttributeList::ReturnIndex);
634345f0148SArtur Pilipenko       CanBeNull = true;
635345f0148SArtur Pilipenko     }
636345f0148SArtur Pilipenko   } else if (const LoadInst *LI = dyn_cast<LoadInst>(this)) {
637345f0148SArtur Pilipenko     if (MDNode *MD = LI->getMetadata(LLVMContext::MD_dereferenceable)) {
638345f0148SArtur Pilipenko       ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(0));
639345f0148SArtur Pilipenko       DerefBytes = CI->getLimitedValue();
640345f0148SArtur Pilipenko     }
641345f0148SArtur Pilipenko     if (DerefBytes == 0) {
642345f0148SArtur Pilipenko       if (MDNode *MD =
643345f0148SArtur Pilipenko               LI->getMetadata(LLVMContext::MD_dereferenceable_or_null)) {
644345f0148SArtur Pilipenko         ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(0));
645345f0148SArtur Pilipenko         DerefBytes = CI->getLimitedValue();
646345f0148SArtur Pilipenko       }
647345f0148SArtur Pilipenko       CanBeNull = true;
648345f0148SArtur Pilipenko     }
64900953cbeSSanjoy Das   } else if (auto *AI = dyn_cast<AllocaInst>(this)) {
65000953cbeSSanjoy Das     if (AI->getAllocatedType()->isSized()) {
65100953cbeSSanjoy Das       DerefBytes = DL.getTypeStoreSize(AI->getAllocatedType());
65200953cbeSSanjoy Das       CanBeNull = false;
65300953cbeSSanjoy Das     }
65400953cbeSSanjoy Das   } else if (auto *GV = dyn_cast<GlobalVariable>(this)) {
65500953cbeSSanjoy Das     if (GV->getValueType()->isSized() && !GV->hasExternalWeakLinkage()) {
65600953cbeSSanjoy Das       // TODO: Don't outright reject hasExternalWeakLinkage but set the
65700953cbeSSanjoy Das       // CanBeNull flag.
65800953cbeSSanjoy Das       DerefBytes = DL.getTypeStoreSize(GV->getValueType());
65900953cbeSSanjoy Das       CanBeNull = false;
66000953cbeSSanjoy Das     }
661345f0148SArtur Pilipenko   }
662345f0148SArtur Pilipenko   return DerefBytes;
663345f0148SArtur Pilipenko }
664345f0148SArtur Pilipenko 
665ae51afc5SArtur Pilipenko unsigned Value::getPointerAlignment(const DataLayout &DL) const {
666ae51afc5SArtur Pilipenko   assert(getType()->isPointerTy() && "must be pointer");
667ae51afc5SArtur Pilipenko 
668ae51afc5SArtur Pilipenko   unsigned Align = 0;
669ae51afc5SArtur Pilipenko   if (auto *GO = dyn_cast<GlobalObject>(this)) {
670ae51afc5SArtur Pilipenko     Align = GO->getAlignment();
671ae51afc5SArtur Pilipenko     if (Align == 0) {
672ae51afc5SArtur Pilipenko       if (auto *GVar = dyn_cast<GlobalVariable>(GO)) {
673ae51afc5SArtur Pilipenko         Type *ObjectType = GVar->getValueType();
674ae51afc5SArtur Pilipenko         if (ObjectType->isSized()) {
675ae51afc5SArtur Pilipenko           // If the object is defined in the current Module, we'll be giving
676ae51afc5SArtur Pilipenko           // it the preferred alignment. Otherwise, we have to assume that it
677ae51afc5SArtur Pilipenko           // may only have the minimum ABI alignment.
678ae51afc5SArtur Pilipenko           if (GVar->isStrongDefinitionForLinker())
679ae51afc5SArtur Pilipenko             Align = DL.getPreferredAlignment(GVar);
680ae51afc5SArtur Pilipenko           else
681ae51afc5SArtur Pilipenko             Align = DL.getABITypeAlignment(ObjectType);
682ae51afc5SArtur Pilipenko         }
683ae51afc5SArtur Pilipenko       }
684ae51afc5SArtur Pilipenko     }
685ae51afc5SArtur Pilipenko   } else if (const Argument *A = dyn_cast<Argument>(this)) {
686ae51afc5SArtur Pilipenko     Align = A->getParamAlignment();
687ae51afc5SArtur Pilipenko 
688ae51afc5SArtur Pilipenko     if (!Align && A->hasStructRetAttr()) {
689ae51afc5SArtur Pilipenko       // An sret parameter has at least the ABI alignment of the return type.
690ae51afc5SArtur Pilipenko       Type *EltTy = cast<PointerType>(A->getType())->getElementType();
691ae51afc5SArtur Pilipenko       if (EltTy->isSized())
692ae51afc5SArtur Pilipenko         Align = DL.getABITypeAlignment(EltTy);
693ae51afc5SArtur Pilipenko     }
694c97eac65SArtur Pilipenko   } else if (const AllocaInst *AI = dyn_cast<AllocaInst>(this)) {
695ae51afc5SArtur Pilipenko     Align = AI->getAlignment();
696c97eac65SArtur Pilipenko     if (Align == 0) {
697c97eac65SArtur Pilipenko       Type *AllocatedType = AI->getAllocatedType();
698c97eac65SArtur Pilipenko       if (AllocatedType->isSized())
699c97eac65SArtur Pilipenko         Align = DL.getPrefTypeAlignment(AllocatedType);
700c97eac65SArtur Pilipenko     }
701c97eac65SArtur Pilipenko   } else if (auto CS = ImmutableCallSite(this))
702859f8b54SReid Kleckner     Align = CS.getAttributes().getRetAlignment();
703ae51afc5SArtur Pilipenko   else if (const LoadInst *LI = dyn_cast<LoadInst>(this))
704ae51afc5SArtur Pilipenko     if (MDNode *MD = LI->getMetadata(LLVMContext::MD_align)) {
705ae51afc5SArtur Pilipenko       ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(0));
706ae51afc5SArtur Pilipenko       Align = CI->getLimitedValue();
707ae51afc5SArtur Pilipenko     }
708ae51afc5SArtur Pilipenko 
709ae51afc5SArtur Pilipenko   return Align;
710ae51afc5SArtur Pilipenko }
711ae51afc5SArtur Pilipenko 
7121dd20e65SCraig Topper const Value *Value::DoPHITranslation(const BasicBlock *CurBB,
7131dd20e65SCraig Topper                                      const BasicBlock *PredBB) const {
7141dd20e65SCraig Topper   auto *PN = dyn_cast<PHINode>(this);
715ef860a24SChandler Carruth   if (PN && PN->getParent() == CurBB)
716ef860a24SChandler Carruth     return PN->getIncomingValueForBlock(PredBB);
717ef860a24SChandler Carruth   return this;
718ef860a24SChandler Carruth }
719ef860a24SChandler Carruth 
720ef860a24SChandler Carruth LLVMContext &Value::getContext() const { return VTy->getContext(); }
721ef860a24SChandler Carruth 
7223441ffe9SDuncan P. N. Exon Smith void Value::reverseUseList() {
7233441ffe9SDuncan P. N. Exon Smith   if (!UseList || !UseList->Next)
7243441ffe9SDuncan P. N. Exon Smith     // No need to reverse 0 or 1 uses.
7253441ffe9SDuncan P. N. Exon Smith     return;
7263441ffe9SDuncan P. N. Exon Smith 
7273441ffe9SDuncan P. N. Exon Smith   Use *Head = UseList;
7283441ffe9SDuncan P. N. Exon Smith   Use *Current = UseList->Next;
7293441ffe9SDuncan P. N. Exon Smith   Head->Next = nullptr;
7303441ffe9SDuncan P. N. Exon Smith   while (Current) {
7313441ffe9SDuncan P. N. Exon Smith     Use *Next = Current->Next;
7323441ffe9SDuncan P. N. Exon Smith     Current->Next = Head;
7333441ffe9SDuncan P. N. Exon Smith     Head->setPrev(&Current->Next);
7343441ffe9SDuncan P. N. Exon Smith     Head = Current;
7353441ffe9SDuncan P. N. Exon Smith     Current = Next;
7363441ffe9SDuncan P. N. Exon Smith   }
7373441ffe9SDuncan P. N. Exon Smith   UseList = Head;
7383441ffe9SDuncan P. N. Exon Smith   Head->setPrev(&UseList);
7393441ffe9SDuncan P. N. Exon Smith }
7403441ffe9SDuncan P. N. Exon Smith 
741ad830022SArnold Schwaighofer bool Value::isSwiftError() const {
742ad830022SArnold Schwaighofer   auto *Arg = dyn_cast<Argument>(this);
743ad830022SArnold Schwaighofer   if (Arg)
744ad830022SArnold Schwaighofer     return Arg->hasSwiftErrorAttr();
745ad830022SArnold Schwaighofer   auto *Alloca = dyn_cast<AllocaInst>(this);
746ad830022SArnold Schwaighofer   if (!Alloca)
747ad830022SArnold Schwaighofer     return false;
748ad830022SArnold Schwaighofer   return Alloca->isSwiftError();
749ad830022SArnold Schwaighofer }
750ad830022SArnold Schwaighofer 
751ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
752ef860a24SChandler Carruth //                             ValueHandleBase Class
753ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
754ef860a24SChandler Carruth 
755ef860a24SChandler Carruth void ValueHandleBase::AddToExistingUseList(ValueHandleBase **List) {
756ef860a24SChandler Carruth   assert(List && "Handle list is null?");
757ef860a24SChandler Carruth 
758ef860a24SChandler Carruth   // Splice ourselves into the list.
759ef860a24SChandler Carruth   Next = *List;
760ef860a24SChandler Carruth   *List = this;
761ef860a24SChandler Carruth   setPrevPtr(List);
762ef860a24SChandler Carruth   if (Next) {
763ef860a24SChandler Carruth     Next->setPrevPtr(&Next);
7646f08789dSSanjoy Das     assert(getValPtr() == Next->getValPtr() && "Added to wrong list?");
765ef860a24SChandler Carruth   }
766ef860a24SChandler Carruth }
767ef860a24SChandler Carruth 
768ef860a24SChandler Carruth void ValueHandleBase::AddToExistingUseListAfter(ValueHandleBase *List) {
769ef860a24SChandler Carruth   assert(List && "Must insert after existing node");
770ef860a24SChandler Carruth 
771ef860a24SChandler Carruth   Next = List->Next;
772ef860a24SChandler Carruth   setPrevPtr(&List->Next);
773ef860a24SChandler Carruth   List->Next = this;
774ef860a24SChandler Carruth   if (Next)
775ef860a24SChandler Carruth     Next->setPrevPtr(&Next);
776ef860a24SChandler Carruth }
777ef860a24SChandler Carruth 
778ef860a24SChandler Carruth void ValueHandleBase::AddToUseList() {
7796f08789dSSanjoy Das   assert(getValPtr() && "Null pointer doesn't have a use list!");
780ef860a24SChandler Carruth 
7816f08789dSSanjoy Das   LLVMContextImpl *pImpl = getValPtr()->getContext().pImpl;
782ef860a24SChandler Carruth 
7836f08789dSSanjoy Das   if (getValPtr()->HasValueHandle) {
784ef860a24SChandler Carruth     // If this value already has a ValueHandle, then it must be in the
785ef860a24SChandler Carruth     // ValueHandles map already.
7866f08789dSSanjoy Das     ValueHandleBase *&Entry = pImpl->ValueHandles[getValPtr()];
7872617dcceSCraig Topper     assert(Entry && "Value doesn't have any handles?");
788ef860a24SChandler Carruth     AddToExistingUseList(&Entry);
789ef860a24SChandler Carruth     return;
790ef860a24SChandler Carruth   }
791ef860a24SChandler Carruth 
792ef860a24SChandler Carruth   // Ok, it doesn't have any handles yet, so we must insert it into the
793ef860a24SChandler Carruth   // DenseMap.  However, doing this insertion could cause the DenseMap to
794ef860a24SChandler Carruth   // reallocate itself, which would invalidate all of the PrevP pointers that
795ef860a24SChandler Carruth   // point into the old table.  Handle this by checking for reallocation and
796ef860a24SChandler Carruth   // updating the stale pointers only if needed.
797ef860a24SChandler Carruth   DenseMap<Value*, ValueHandleBase*> &Handles = pImpl->ValueHandles;
798ef860a24SChandler Carruth   const void *OldBucketPtr = Handles.getPointerIntoBucketsArray();
799ef860a24SChandler Carruth 
8006f08789dSSanjoy Das   ValueHandleBase *&Entry = Handles[getValPtr()];
8012617dcceSCraig Topper   assert(!Entry && "Value really did already have handles?");
802ef860a24SChandler Carruth   AddToExistingUseList(&Entry);
8036f08789dSSanjoy Das   getValPtr()->HasValueHandle = true;
804ef860a24SChandler Carruth 
805ef860a24SChandler Carruth   // If reallocation didn't happen or if this was the first insertion, don't
806ef860a24SChandler Carruth   // walk the table.
807ef860a24SChandler Carruth   if (Handles.isPointerIntoBucketsArray(OldBucketPtr) ||
808ef860a24SChandler Carruth       Handles.size() == 1) {
809ef860a24SChandler Carruth     return;
810ef860a24SChandler Carruth   }
811ef860a24SChandler Carruth 
812ef860a24SChandler Carruth   // Okay, reallocation did happen.  Fix the Prev Pointers.
813ef860a24SChandler Carruth   for (DenseMap<Value*, ValueHandleBase*>::iterator I = Handles.begin(),
814ef860a24SChandler Carruth        E = Handles.end(); I != E; ++I) {
8156f08789dSSanjoy Das     assert(I->second && I->first == I->second->getValPtr() &&
816ef860a24SChandler Carruth            "List invariant broken!");
817ef860a24SChandler Carruth     I->second->setPrevPtr(&I->second);
818ef860a24SChandler Carruth   }
819ef860a24SChandler Carruth }
820ef860a24SChandler Carruth 
821ef860a24SChandler Carruth void ValueHandleBase::RemoveFromUseList() {
8226f08789dSSanjoy Das   assert(getValPtr() && getValPtr()->HasValueHandle &&
823ef860a24SChandler Carruth          "Pointer doesn't have a use list!");
824ef860a24SChandler Carruth 
825ef860a24SChandler Carruth   // Unlink this from its use list.
826ef860a24SChandler Carruth   ValueHandleBase **PrevPtr = getPrevPtr();
827ef860a24SChandler Carruth   assert(*PrevPtr == this && "List invariant broken");
828ef860a24SChandler Carruth 
829ef860a24SChandler Carruth   *PrevPtr = Next;
830ef860a24SChandler Carruth   if (Next) {
831ef860a24SChandler Carruth     assert(Next->getPrevPtr() == &Next && "List invariant broken");
832ef860a24SChandler Carruth     Next->setPrevPtr(PrevPtr);
833ef860a24SChandler Carruth     return;
834ef860a24SChandler Carruth   }
835ef860a24SChandler Carruth 
836ef860a24SChandler Carruth   // If the Next pointer was null, then it is possible that this was the last
837ef860a24SChandler Carruth   // ValueHandle watching VP.  If so, delete its entry from the ValueHandles
838ef860a24SChandler Carruth   // map.
8396f08789dSSanjoy Das   LLVMContextImpl *pImpl = getValPtr()->getContext().pImpl;
840ef860a24SChandler Carruth   DenseMap<Value*, ValueHandleBase*> &Handles = pImpl->ValueHandles;
841ef860a24SChandler Carruth   if (Handles.isPointerIntoBucketsArray(PrevPtr)) {
8426f08789dSSanjoy Das     Handles.erase(getValPtr());
8436f08789dSSanjoy Das     getValPtr()->HasValueHandle = false;
844ef860a24SChandler Carruth   }
845ef860a24SChandler Carruth }
846ef860a24SChandler Carruth 
847ef860a24SChandler Carruth void ValueHandleBase::ValueIsDeleted(Value *V) {
848ef860a24SChandler Carruth   assert(V->HasValueHandle && "Should only be called if ValueHandles present");
849ef860a24SChandler Carruth 
850ef860a24SChandler Carruth   // Get the linked list base, which is guaranteed to exist since the
851ef860a24SChandler Carruth   // HasValueHandle flag is set.
852ef860a24SChandler Carruth   LLVMContextImpl *pImpl = V->getContext().pImpl;
853ef860a24SChandler Carruth   ValueHandleBase *Entry = pImpl->ValueHandles[V];
854ef860a24SChandler Carruth   assert(Entry && "Value bit set but no entries exist");
855ef860a24SChandler Carruth 
856ef860a24SChandler Carruth   // We use a local ValueHandleBase as an iterator so that ValueHandles can add
857ef860a24SChandler Carruth   // and remove themselves from the list without breaking our iteration.  This
858ef860a24SChandler Carruth   // is not really an AssertingVH; we just have to give ValueHandleBase a kind.
859ef860a24SChandler Carruth   // Note that we deliberately do not the support the case when dropping a value
860ef860a24SChandler Carruth   // handle results in a new value handle being permanently added to the list
861ef860a24SChandler Carruth   // (as might occur in theory for CallbackVH's): the new value handle will not
862ef860a24SChandler Carruth   // be processed and the checking code will mete out righteous punishment if
863ef860a24SChandler Carruth   // the handle is still present once we have finished processing all the other
864ef860a24SChandler Carruth   // value handles (it is fine to momentarily add then remove a value handle).
865ef860a24SChandler Carruth   for (ValueHandleBase Iterator(Assert, *Entry); Entry; Entry = Iterator.Next) {
866ef860a24SChandler Carruth     Iterator.RemoveFromUseList();
867ef860a24SChandler Carruth     Iterator.AddToExistingUseListAfter(Entry);
868ef860a24SChandler Carruth     assert(Entry->Next == &Iterator && "Loop invariant broken.");
869ef860a24SChandler Carruth 
870ef860a24SChandler Carruth     switch (Entry->getKind()) {
871ef860a24SChandler Carruth     case Assert:
872ef860a24SChandler Carruth       break;
873f1c0eafdSSanjoy Das     case Weak:
874e6bca0eeSSanjoy Das     case WeakTracking:
875f1c0eafdSSanjoy Das       // WeakTracking and Weak just go to null, which unlinks them
876f1c0eafdSSanjoy Das       // from the list.
877c620761cSCraig Topper       Entry->operator=(nullptr);
878ef860a24SChandler Carruth       break;
879ef860a24SChandler Carruth     case Callback:
880ef860a24SChandler Carruth       // Forward to the subclass's implementation.
881ef860a24SChandler Carruth       static_cast<CallbackVH*>(Entry)->deleted();
882ef860a24SChandler Carruth       break;
883ef860a24SChandler Carruth     }
884ef860a24SChandler Carruth   }
885ef860a24SChandler Carruth 
886ef860a24SChandler Carruth   // All callbacks, weak references, and assertingVHs should be dropped by now.
887ef860a24SChandler Carruth   if (V->HasValueHandle) {
888ef860a24SChandler Carruth #ifndef NDEBUG      // Only in +Asserts mode...
889ef860a24SChandler Carruth     dbgs() << "While deleting: " << *V->getType() << " %" << V->getName()
890ef860a24SChandler Carruth            << "\n";
891ef860a24SChandler Carruth     if (pImpl->ValueHandles[V]->getKind() == Assert)
892ef860a24SChandler Carruth       llvm_unreachable("An asserting value handle still pointed to this"
893ef860a24SChandler Carruth                        " value!");
894ef860a24SChandler Carruth 
895ef860a24SChandler Carruth #endif
896ef860a24SChandler Carruth     llvm_unreachable("All references to V were not removed?");
897ef860a24SChandler Carruth   }
898ef860a24SChandler Carruth }
899ef860a24SChandler Carruth 
900ef860a24SChandler Carruth void ValueHandleBase::ValueIsRAUWd(Value *Old, Value *New) {
901ef860a24SChandler Carruth   assert(Old->HasValueHandle &&"Should only be called if ValueHandles present");
902ef860a24SChandler Carruth   assert(Old != New && "Changing value into itself!");
903c1892e2dSFrederic Riss   assert(Old->getType() == New->getType() &&
904c1892e2dSFrederic Riss          "replaceAllUses of value with new value of different type!");
905ef860a24SChandler Carruth 
906ef860a24SChandler Carruth   // Get the linked list base, which is guaranteed to exist since the
907ef860a24SChandler Carruth   // HasValueHandle flag is set.
908ef860a24SChandler Carruth   LLVMContextImpl *pImpl = Old->getContext().pImpl;
909ef860a24SChandler Carruth   ValueHandleBase *Entry = pImpl->ValueHandles[Old];
910ef860a24SChandler Carruth 
911ef860a24SChandler Carruth   assert(Entry && "Value bit set but no entries exist");
912ef860a24SChandler Carruth 
913ef860a24SChandler Carruth   // We use a local ValueHandleBase as an iterator so that
914ef860a24SChandler Carruth   // ValueHandles can add and remove themselves from the list without
915ef860a24SChandler Carruth   // breaking our iteration.  This is not really an AssertingVH; we
916ef860a24SChandler Carruth   // just have to give ValueHandleBase some kind.
917ef860a24SChandler Carruth   for (ValueHandleBase Iterator(Assert, *Entry); Entry; Entry = Iterator.Next) {
918ef860a24SChandler Carruth     Iterator.RemoveFromUseList();
919ef860a24SChandler Carruth     Iterator.AddToExistingUseListAfter(Entry);
920ef860a24SChandler Carruth     assert(Entry->Next == &Iterator && "Loop invariant broken.");
921ef860a24SChandler Carruth 
922ef860a24SChandler Carruth     switch (Entry->getKind()) {
923ef860a24SChandler Carruth     case Assert:
924f1c0eafdSSanjoy Das     case Weak:
925f1c0eafdSSanjoy Das       // Asserting and Weak handles do not follow RAUW implicitly.
926ef860a24SChandler Carruth       break;
927e6bca0eeSSanjoy Das     case WeakTracking:
9282cbeb00fSSanjoy Das       // Weak goes to the new value, which will unlink it from Old's list.
929ef860a24SChandler Carruth       Entry->operator=(New);
930ef860a24SChandler Carruth       break;
931ef860a24SChandler Carruth     case Callback:
932ef860a24SChandler Carruth       // Forward to the subclass's implementation.
933ef860a24SChandler Carruth       static_cast<CallbackVH*>(Entry)->allUsesReplacedWith(New);
934ef860a24SChandler Carruth       break;
935ef860a24SChandler Carruth     }
936ef860a24SChandler Carruth   }
937ef860a24SChandler Carruth 
938ef860a24SChandler Carruth #ifndef NDEBUG
9398a623820SSanjoy Das   // If any new weak value handles were added while processing the
940ef860a24SChandler Carruth   // list, then complain about it now.
941ef860a24SChandler Carruth   if (Old->HasValueHandle)
942ef860a24SChandler Carruth     for (Entry = pImpl->ValueHandles[Old]; Entry; Entry = Entry->Next)
943ef860a24SChandler Carruth       switch (Entry->getKind()) {
944e6bca0eeSSanjoy Das       case WeakTracking:
945ef860a24SChandler Carruth         dbgs() << "After RAUW from " << *Old->getType() << " %"
946ef860a24SChandler Carruth                << Old->getName() << " to " << *New->getType() << " %"
947ef860a24SChandler Carruth                << New->getName() << "\n";
9488a623820SSanjoy Das         llvm_unreachable(
949e6bca0eeSSanjoy Das             "A weak tracking value handle still pointed to the  old value!\n");
950ef860a24SChandler Carruth       default:
951ef860a24SChandler Carruth         break;
952ef860a24SChandler Carruth       }
953ef860a24SChandler Carruth #endif
954ef860a24SChandler Carruth }
955ef860a24SChandler Carruth 
956d12ccbd3SJuergen Ributzka // Pin the vtable to this file.
957d12ccbd3SJuergen Ributzka void CallbackVH::anchor() {}
958