xref: /llvm-project-15.0.7/llvm/lib/IR/Value.cpp (revision eee73f5f)
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"
189fb823bbSChandler Carruth #include "llvm/IR/Constant.h"
199fb823bbSChandler Carruth #include "llvm/IR/Constants.h"
209fb823bbSChandler Carruth #include "llvm/IR/DerivedTypes.h"
219fb823bbSChandler Carruth #include "llvm/IR/InstrTypes.h"
229fb823bbSChandler Carruth #include "llvm/IR/Instructions.h"
239fb823bbSChandler Carruth #include "llvm/IR/Module.h"
249fb823bbSChandler Carruth #include "llvm/IR/Operator.h"
259fb823bbSChandler Carruth #include "llvm/IR/ValueSymbolTable.h"
26ef860a24SChandler Carruth #include "llvm/Support/Debug.h"
27ef860a24SChandler Carruth #include "llvm/Support/ErrorHandling.h"
28ef860a24SChandler Carruth #include "llvm/Support/GetElementPtrTypeIterator.h"
29ef860a24SChandler Carruth #include "llvm/Support/LeakDetector.h"
30ef860a24SChandler Carruth #include "llvm/Support/ManagedStatic.h"
31ef860a24SChandler Carruth #include "llvm/Support/ValueHandle.h"
32ef860a24SChandler Carruth #include <algorithm>
33ef860a24SChandler Carruth using namespace llvm;
34ef860a24SChandler Carruth 
35ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
36ef860a24SChandler Carruth //                                Value Class
37ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
38ef860a24SChandler Carruth 
39ef860a24SChandler Carruth static inline Type *checkType(Type *Ty) {
40ef860a24SChandler Carruth   assert(Ty && "Value defined with a null type: Error!");
41ef860a24SChandler Carruth   return const_cast<Type*>(Ty);
42ef860a24SChandler Carruth }
43ef860a24SChandler Carruth 
44ef860a24SChandler Carruth Value::Value(Type *ty, unsigned scid)
45ef860a24SChandler Carruth   : SubclassID(scid), HasValueHandle(0),
46ef860a24SChandler Carruth     SubclassOptionalData(0), SubclassData(0), VTy((Type*)checkType(ty)),
47ef860a24SChandler Carruth     UseList(0), Name(0) {
48ef860a24SChandler Carruth   // FIXME: Why isn't this in the subclass gunk??
49ef860a24SChandler Carruth   // Note, we cannot call isa<CallInst> before the CallInst has been
50ef860a24SChandler Carruth   // constructed.
51ef860a24SChandler Carruth   if (SubclassID == Instruction::Call || SubclassID == Instruction::Invoke)
52ef860a24SChandler Carruth     assert((VTy->isFirstClassType() || VTy->isVoidTy() || VTy->isStructTy()) &&
53ef860a24SChandler Carruth            "invalid CallInst type!");
54ef860a24SChandler Carruth   else if (SubclassID != BasicBlockVal &&
55ef860a24SChandler Carruth            (SubclassID < ConstantFirstVal || SubclassID > ConstantLastVal))
56ef860a24SChandler Carruth     assert((VTy->isFirstClassType() || VTy->isVoidTy()) &&
57ef860a24SChandler Carruth            "Cannot create non-first-class values except for constants!");
58ef860a24SChandler Carruth }
59ef860a24SChandler Carruth 
60ef860a24SChandler Carruth Value::~Value() {
61ef860a24SChandler Carruth   // Notify all ValueHandles (if present) that this value is going away.
62ef860a24SChandler Carruth   if (HasValueHandle)
63ef860a24SChandler Carruth     ValueHandleBase::ValueIsDeleted(this);
64ef860a24SChandler Carruth 
65ef860a24SChandler Carruth #ifndef NDEBUG      // Only in -g mode...
66ef860a24SChandler Carruth   // Check to make sure that there are no uses of this value that are still
67ef860a24SChandler Carruth   // around when the value is destroyed.  If there are, then we have a dangling
68ef860a24SChandler Carruth   // reference and something is wrong.  This code is here to print out what is
69ef860a24SChandler Carruth   // still being referenced.  The value in question should be printed as
70ef860a24SChandler Carruth   // a <badref>
71ef860a24SChandler Carruth   //
72ef860a24SChandler Carruth   if (!use_empty()) {
73ef860a24SChandler Carruth     dbgs() << "While deleting: " << *VTy << " %" << getName() << "\n";
74ef860a24SChandler Carruth     for (use_iterator I = use_begin(), E = use_end(); I != E; ++I)
75ef860a24SChandler Carruth       dbgs() << "Use still stuck around after Def is destroyed:"
76ef860a24SChandler Carruth            << **I << "\n";
77ef860a24SChandler Carruth   }
78ef860a24SChandler Carruth #endif
79ef860a24SChandler Carruth   assert(use_empty() && "Uses remain when a value is destroyed!");
80ef860a24SChandler Carruth 
81ef860a24SChandler Carruth   // If this value is named, destroy the name.  This should not be in a symtab
82ef860a24SChandler Carruth   // at this point.
83ef860a24SChandler Carruth   if (Name && SubclassID != MDStringVal)
84ef860a24SChandler Carruth     Name->Destroy();
85ef860a24SChandler Carruth 
86ef860a24SChandler Carruth   // There should be no uses of this object anymore, remove it.
87ef860a24SChandler Carruth   LeakDetector::removeGarbageObject(this);
88ef860a24SChandler Carruth }
89ef860a24SChandler Carruth 
90ef860a24SChandler Carruth /// hasNUses - Return true if this Value has exactly N users.
91ef860a24SChandler Carruth ///
92ef860a24SChandler Carruth bool Value::hasNUses(unsigned N) const {
93ef860a24SChandler Carruth   const_use_iterator UI = use_begin(), E = use_end();
94ef860a24SChandler Carruth 
95ef860a24SChandler Carruth   for (; N; --N, ++UI)
96ef860a24SChandler Carruth     if (UI == E) return false;  // Too few.
97ef860a24SChandler Carruth   return UI == E;
98ef860a24SChandler Carruth }
99ef860a24SChandler Carruth 
100ef860a24SChandler Carruth /// hasNUsesOrMore - Return true if this value has N users or more.  This is
101ef860a24SChandler Carruth /// logically equivalent to getNumUses() >= N.
102ef860a24SChandler Carruth ///
103ef860a24SChandler Carruth bool Value::hasNUsesOrMore(unsigned N) const {
104ef860a24SChandler Carruth   const_use_iterator UI = use_begin(), E = use_end();
105ef860a24SChandler Carruth 
106ef860a24SChandler Carruth   for (; N; --N, ++UI)
107ef860a24SChandler Carruth     if (UI == E) return false;  // Too few.
108ef860a24SChandler Carruth 
109ef860a24SChandler Carruth   return true;
110ef860a24SChandler Carruth }
111ef860a24SChandler Carruth 
112ef860a24SChandler Carruth /// isUsedInBasicBlock - Return true if this value is used in the specified
113ef860a24SChandler Carruth /// basic block.
114ef860a24SChandler Carruth bool Value::isUsedInBasicBlock(const BasicBlock *BB) const {
115ef860a24SChandler Carruth   // Start by scanning over the instructions looking for a use before we start
116ef860a24SChandler Carruth   // the expensive use iteration.
117ef860a24SChandler Carruth   unsigned MaxBlockSize = 3;
118ef860a24SChandler Carruth   for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
119ef860a24SChandler Carruth     if (std::find(I->op_begin(), I->op_end(), this) != I->op_end())
120ef860a24SChandler Carruth       return true;
121*eee73f5fSBenjamin Kramer     if (--MaxBlockSize == 0) // If the block is larger fall back to use_iterator
122ef860a24SChandler Carruth       break;
123ef860a24SChandler Carruth   }
124ef860a24SChandler Carruth 
125ef860a24SChandler Carruth   if (MaxBlockSize != 0) // We scanned the entire block and found no use.
126ef860a24SChandler Carruth     return false;
127ef860a24SChandler Carruth 
128ef860a24SChandler Carruth   for (const_use_iterator I = use_begin(), E = use_end(); I != E; ++I) {
129ef860a24SChandler Carruth     const Instruction *User = dyn_cast<Instruction>(*I);
130ef860a24SChandler Carruth     if (User && User->getParent() == BB)
131ef860a24SChandler Carruth       return true;
132ef860a24SChandler Carruth   }
133ef860a24SChandler Carruth   return false;
134ef860a24SChandler Carruth }
135ef860a24SChandler Carruth 
136ef860a24SChandler Carruth 
137ef860a24SChandler Carruth /// getNumUses - This method computes the number of uses of this Value.  This
138ef860a24SChandler Carruth /// is a linear time operation.  Use hasOneUse or hasNUses to check for specific
139ef860a24SChandler Carruth /// values.
140ef860a24SChandler Carruth unsigned Value::getNumUses() const {
141ef860a24SChandler Carruth   return (unsigned)std::distance(use_begin(), use_end());
142ef860a24SChandler Carruth }
143ef860a24SChandler Carruth 
144ef860a24SChandler Carruth static bool getSymTab(Value *V, ValueSymbolTable *&ST) {
145ef860a24SChandler Carruth   ST = 0;
146ef860a24SChandler Carruth   if (Instruction *I = dyn_cast<Instruction>(V)) {
147ef860a24SChandler Carruth     if (BasicBlock *P = I->getParent())
148ef860a24SChandler Carruth       if (Function *PP = P->getParent())
149ef860a24SChandler Carruth         ST = &PP->getValueSymbolTable();
150ef860a24SChandler Carruth   } else if (BasicBlock *BB = dyn_cast<BasicBlock>(V)) {
151ef860a24SChandler Carruth     if (Function *P = BB->getParent())
152ef860a24SChandler Carruth       ST = &P->getValueSymbolTable();
153ef860a24SChandler Carruth   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
154ef860a24SChandler Carruth     if (Module *P = GV->getParent())
155ef860a24SChandler Carruth       ST = &P->getValueSymbolTable();
156ef860a24SChandler Carruth   } else if (Argument *A = dyn_cast<Argument>(V)) {
157ef860a24SChandler Carruth     if (Function *P = A->getParent())
158ef860a24SChandler Carruth       ST = &P->getValueSymbolTable();
159ef860a24SChandler Carruth   } else if (isa<MDString>(V))
160ef860a24SChandler Carruth     return true;
161ef860a24SChandler Carruth   else {
162ef860a24SChandler Carruth     assert(isa<Constant>(V) && "Unknown value type!");
163ef860a24SChandler Carruth     return true;  // no name is setable for this.
164ef860a24SChandler Carruth   }
165ef860a24SChandler Carruth   return false;
166ef860a24SChandler Carruth }
167ef860a24SChandler Carruth 
168ef860a24SChandler Carruth StringRef Value::getName() const {
169ef860a24SChandler Carruth   // Make sure the empty string is still a C string. For historical reasons,
170ef860a24SChandler Carruth   // some clients want to call .data() on the result and expect it to be null
171ef860a24SChandler Carruth   // terminated.
172ef860a24SChandler Carruth   if (!Name) return StringRef("", 0);
173ef860a24SChandler Carruth   return Name->getKey();
174ef860a24SChandler Carruth }
175ef860a24SChandler Carruth 
176ef860a24SChandler Carruth void Value::setName(const Twine &NewName) {
177ef860a24SChandler Carruth   assert(SubclassID != MDStringVal &&
178ef860a24SChandler Carruth          "Cannot set the name of MDString with this method!");
179ef860a24SChandler Carruth 
180ef860a24SChandler Carruth   // Fast path for common IRBuilder case of setName("") when there is no name.
181ef860a24SChandler Carruth   if (NewName.isTriviallyEmpty() && !hasName())
182ef860a24SChandler Carruth     return;
183ef860a24SChandler Carruth 
184ef860a24SChandler Carruth   SmallString<256> NameData;
185ef860a24SChandler Carruth   StringRef NameRef = NewName.toStringRef(NameData);
186ef860a24SChandler Carruth 
187ef860a24SChandler Carruth   // Name isn't changing?
188ef860a24SChandler Carruth   if (getName() == NameRef)
189ef860a24SChandler Carruth     return;
190ef860a24SChandler Carruth 
191ef860a24SChandler Carruth   assert(!getType()->isVoidTy() && "Cannot assign a name to void values!");
192ef860a24SChandler Carruth 
193ef860a24SChandler Carruth   // Get the symbol table to update for this object.
194ef860a24SChandler Carruth   ValueSymbolTable *ST;
195ef860a24SChandler Carruth   if (getSymTab(this, ST))
196ef860a24SChandler Carruth     return;  // Cannot set a name on this value (e.g. constant).
197ef860a24SChandler Carruth 
198516d7039SMichael Ilseman   if (Function *F = dyn_cast<Function>(this))
199516d7039SMichael Ilseman     getContext().pImpl->IntrinsicIDCache.erase(F);
200516d7039SMichael Ilseman 
201ef860a24SChandler Carruth   if (!ST) { // No symbol table to update?  Just do the change.
202ef860a24SChandler Carruth     if (NameRef.empty()) {
203ef860a24SChandler Carruth       // Free the name for this value.
204ef860a24SChandler Carruth       Name->Destroy();
205ef860a24SChandler Carruth       Name = 0;
206ef860a24SChandler Carruth       return;
207ef860a24SChandler Carruth     }
208ef860a24SChandler Carruth 
209ef860a24SChandler Carruth     if (Name)
210ef860a24SChandler Carruth       Name->Destroy();
211ef860a24SChandler Carruth 
212ef860a24SChandler Carruth     // NOTE: Could optimize for the case the name is shrinking to not deallocate
213ef860a24SChandler Carruth     // then reallocated.
214ef860a24SChandler Carruth 
215ef860a24SChandler Carruth     // Create the new name.
216ef860a24SChandler Carruth     Name = ValueName::Create(NameRef.begin(), NameRef.end());
217ef860a24SChandler Carruth     Name->setValue(this);
218ef860a24SChandler Carruth     return;
219ef860a24SChandler Carruth   }
220ef860a24SChandler Carruth 
221ef860a24SChandler Carruth   // NOTE: Could optimize for the case the name is shrinking to not deallocate
222ef860a24SChandler Carruth   // then reallocated.
223ef860a24SChandler Carruth   if (hasName()) {
224ef860a24SChandler Carruth     // Remove old name.
225ef860a24SChandler Carruth     ST->removeValueName(Name);
226ef860a24SChandler Carruth     Name->Destroy();
227ef860a24SChandler Carruth     Name = 0;
228ef860a24SChandler Carruth 
229ef860a24SChandler Carruth     if (NameRef.empty())
230ef860a24SChandler Carruth       return;
231ef860a24SChandler Carruth   }
232ef860a24SChandler Carruth 
233ef860a24SChandler Carruth   // Name is changing to something new.
234ef860a24SChandler Carruth   Name = ST->createValueName(NameRef, this);
235ef860a24SChandler Carruth }
236ef860a24SChandler Carruth 
237ef860a24SChandler Carruth 
238ef860a24SChandler Carruth /// takeName - transfer the name from V to this value, setting V's name to
239ef860a24SChandler Carruth /// empty.  It is an error to call V->takeName(V).
240ef860a24SChandler Carruth void Value::takeName(Value *V) {
241ef860a24SChandler Carruth   assert(SubclassID != MDStringVal && "Cannot take the name of an MDString!");
242ef860a24SChandler Carruth 
243ef860a24SChandler Carruth   ValueSymbolTable *ST = 0;
244ef860a24SChandler Carruth   // If this value has a name, drop it.
245ef860a24SChandler Carruth   if (hasName()) {
246ef860a24SChandler Carruth     // Get the symtab this is in.
247ef860a24SChandler Carruth     if (getSymTab(this, ST)) {
248ef860a24SChandler Carruth       // We can't set a name on this value, but we need to clear V's name if
249ef860a24SChandler Carruth       // it has one.
250ef860a24SChandler Carruth       if (V->hasName()) V->setName("");
251ef860a24SChandler Carruth       return;  // Cannot set a name on this value (e.g. constant).
252ef860a24SChandler Carruth     }
253ef860a24SChandler Carruth 
254ef860a24SChandler Carruth     // Remove old name.
255ef860a24SChandler Carruth     if (ST)
256ef860a24SChandler Carruth       ST->removeValueName(Name);
257ef860a24SChandler Carruth     Name->Destroy();
258ef860a24SChandler Carruth     Name = 0;
259ef860a24SChandler Carruth   }
260ef860a24SChandler Carruth 
261ef860a24SChandler Carruth   // Now we know that this has no name.
262ef860a24SChandler Carruth 
263ef860a24SChandler Carruth   // If V has no name either, we're done.
264ef860a24SChandler Carruth   if (!V->hasName()) return;
265ef860a24SChandler Carruth 
266ef860a24SChandler Carruth   // Get this's symtab if we didn't before.
267ef860a24SChandler Carruth   if (!ST) {
268ef860a24SChandler Carruth     if (getSymTab(this, ST)) {
269ef860a24SChandler Carruth       // Clear V's name.
270ef860a24SChandler Carruth       V->setName("");
271ef860a24SChandler Carruth       return;  // Cannot set a name on this value (e.g. constant).
272ef860a24SChandler Carruth     }
273ef860a24SChandler Carruth   }
274ef860a24SChandler Carruth 
275ef860a24SChandler Carruth   // Get V's ST, this should always succed, because V has a name.
276ef860a24SChandler Carruth   ValueSymbolTable *VST;
277ef860a24SChandler Carruth   bool Failure = getSymTab(V, VST);
278ef860a24SChandler Carruth   assert(!Failure && "V has a name, so it should have a ST!"); (void)Failure;
279ef860a24SChandler Carruth 
280ef860a24SChandler Carruth   // If these values are both in the same symtab, we can do this very fast.
281ef860a24SChandler Carruth   // This works even if both values have no symtab yet.
282ef860a24SChandler Carruth   if (ST == VST) {
283ef860a24SChandler Carruth     // Take the name!
284ef860a24SChandler Carruth     Name = V->Name;
285ef860a24SChandler Carruth     V->Name = 0;
286ef860a24SChandler Carruth     Name->setValue(this);
287ef860a24SChandler Carruth     return;
288ef860a24SChandler Carruth   }
289ef860a24SChandler Carruth 
290ef860a24SChandler Carruth   // Otherwise, things are slightly more complex.  Remove V's name from VST and
291ef860a24SChandler Carruth   // then reinsert it into ST.
292ef860a24SChandler Carruth 
293ef860a24SChandler Carruth   if (VST)
294ef860a24SChandler Carruth     VST->removeValueName(V->Name);
295ef860a24SChandler Carruth   Name = V->Name;
296ef860a24SChandler Carruth   V->Name = 0;
297ef860a24SChandler Carruth   Name->setValue(this);
298ef860a24SChandler Carruth 
299ef860a24SChandler Carruth   if (ST)
300ef860a24SChandler Carruth     ST->reinsertValue(this);
301ef860a24SChandler Carruth }
302ef860a24SChandler Carruth 
303ef860a24SChandler Carruth 
304ef860a24SChandler Carruth void Value::replaceAllUsesWith(Value *New) {
305ef860a24SChandler Carruth   assert(New && "Value::replaceAllUsesWith(<null>) is invalid!");
306ef860a24SChandler Carruth   assert(New != this && "this->replaceAllUsesWith(this) is NOT valid!");
307ef860a24SChandler Carruth   assert(New->getType() == getType() &&
308ef860a24SChandler Carruth          "replaceAllUses of value with new value of different type!");
309ef860a24SChandler Carruth 
310ef860a24SChandler Carruth   // Notify all ValueHandles (if present) that this value is going away.
311ef860a24SChandler Carruth   if (HasValueHandle)
312ef860a24SChandler Carruth     ValueHandleBase::ValueIsRAUWd(this, New);
313ef860a24SChandler Carruth 
314ef860a24SChandler Carruth   while (!use_empty()) {
315ef860a24SChandler Carruth     Use &U = *UseList;
316ef860a24SChandler Carruth     // Must handle Constants specially, we cannot call replaceUsesOfWith on a
317ef860a24SChandler Carruth     // constant because they are uniqued.
318ef860a24SChandler Carruth     if (Constant *C = dyn_cast<Constant>(U.getUser())) {
319ef860a24SChandler Carruth       if (!isa<GlobalValue>(C)) {
320ef860a24SChandler Carruth         C->replaceUsesOfWithOnConstant(this, New, &U);
321ef860a24SChandler Carruth         continue;
322ef860a24SChandler Carruth       }
323ef860a24SChandler Carruth     }
324ef860a24SChandler Carruth 
325ef860a24SChandler Carruth     U.set(New);
326ef860a24SChandler Carruth   }
327ef860a24SChandler Carruth 
328ef860a24SChandler Carruth   if (BasicBlock *BB = dyn_cast<BasicBlock>(this))
329ef860a24SChandler Carruth     BB->replaceSuccessorsPhiUsesWith(cast<BasicBlock>(New));
330ef860a24SChandler Carruth }
331ef860a24SChandler Carruth 
332ef860a24SChandler Carruth namespace {
333ef860a24SChandler Carruth // Various metrics for how much to strip off of pointers.
334ef860a24SChandler Carruth enum PointerStripKind {
335ef860a24SChandler Carruth   PSK_ZeroIndices,
336ef860a24SChandler Carruth   PSK_InBoundsConstantIndices,
337ef860a24SChandler Carruth   PSK_InBounds
338ef860a24SChandler Carruth };
339ef860a24SChandler Carruth 
340ef860a24SChandler Carruth template <PointerStripKind StripKind>
341ef860a24SChandler Carruth static Value *stripPointerCastsAndOffsets(Value *V) {
342ef860a24SChandler Carruth   if (!V->getType()->isPointerTy())
343ef860a24SChandler Carruth     return V;
344ef860a24SChandler Carruth 
345ef860a24SChandler Carruth   // Even though we don't look through PHI nodes, we could be called on an
346ef860a24SChandler Carruth   // instruction in an unreachable block, which may be on a cycle.
347ef860a24SChandler Carruth   SmallPtrSet<Value *, 4> Visited;
348ef860a24SChandler Carruth 
349ef860a24SChandler Carruth   Visited.insert(V);
350ef860a24SChandler Carruth   do {
351ef860a24SChandler Carruth     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
352ef860a24SChandler Carruth       switch (StripKind) {
353ef860a24SChandler Carruth       case PSK_ZeroIndices:
354ef860a24SChandler Carruth         if (!GEP->hasAllZeroIndices())
355ef860a24SChandler Carruth           return V;
356ef860a24SChandler Carruth         break;
357ef860a24SChandler Carruth       case PSK_InBoundsConstantIndices:
358ef860a24SChandler Carruth         if (!GEP->hasAllConstantIndices())
359ef860a24SChandler Carruth           return V;
360ef860a24SChandler Carruth         // fallthrough
361ef860a24SChandler Carruth       case PSK_InBounds:
362ef860a24SChandler Carruth         if (!GEP->isInBounds())
363ef860a24SChandler Carruth           return V;
364ef860a24SChandler Carruth         break;
365ef860a24SChandler Carruth       }
366ef860a24SChandler Carruth       V = GEP->getPointerOperand();
367ef860a24SChandler Carruth     } else if (Operator::getOpcode(V) == Instruction::BitCast) {
368ef860a24SChandler Carruth       V = cast<Operator>(V)->getOperand(0);
369ef860a24SChandler Carruth     } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
370ef860a24SChandler Carruth       if (GA->mayBeOverridden())
371ef860a24SChandler Carruth         return V;
372ef860a24SChandler Carruth       V = GA->getAliasee();
373ef860a24SChandler Carruth     } else {
374ef860a24SChandler Carruth       return V;
375ef860a24SChandler Carruth     }
376ef860a24SChandler Carruth     assert(V->getType()->isPointerTy() && "Unexpected operand type!");
377ef860a24SChandler Carruth   } while (Visited.insert(V));
378ef860a24SChandler Carruth 
379ef860a24SChandler Carruth   return V;
380ef860a24SChandler Carruth }
381ef860a24SChandler Carruth } // namespace
382ef860a24SChandler Carruth 
383ef860a24SChandler Carruth Value *Value::stripPointerCasts() {
384ef860a24SChandler Carruth   return stripPointerCastsAndOffsets<PSK_ZeroIndices>(this);
385ef860a24SChandler Carruth }
386ef860a24SChandler Carruth 
387ef860a24SChandler Carruth Value *Value::stripInBoundsConstantOffsets() {
388ef860a24SChandler Carruth   return stripPointerCastsAndOffsets<PSK_InBoundsConstantIndices>(this);
389ef860a24SChandler Carruth }
390ef860a24SChandler Carruth 
391ef860a24SChandler Carruth Value *Value::stripInBoundsOffsets() {
392ef860a24SChandler Carruth   return stripPointerCastsAndOffsets<PSK_InBounds>(this);
393ef860a24SChandler Carruth }
394ef860a24SChandler Carruth 
395ef860a24SChandler Carruth /// isDereferenceablePointer - Test if this value is always a pointer to
396ef860a24SChandler Carruth /// allocated and suitably aligned memory for a simple load or store.
397ef860a24SChandler Carruth static bool isDereferenceablePointer(const Value *V,
398ef860a24SChandler Carruth                                      SmallPtrSet<const Value *, 32> &Visited) {
399ef860a24SChandler Carruth   // Note that it is not safe to speculate into a malloc'd region because
400ef860a24SChandler Carruth   // malloc may return null.
401ef860a24SChandler Carruth   // It's also not always safe to follow a bitcast, for example:
402ef860a24SChandler Carruth   //   bitcast i8* (alloca i8) to i32*
403ef860a24SChandler Carruth   // would result in a 4-byte load from a 1-byte alloca. Some cases could
404ef860a24SChandler Carruth   // be handled using DataLayout to check sizes and alignments though.
405ef860a24SChandler Carruth 
406ef860a24SChandler Carruth   // These are obviously ok.
407ef860a24SChandler Carruth   if (isa<AllocaInst>(V)) return true;
408ef860a24SChandler Carruth 
409ef860a24SChandler Carruth   // Global variables which can't collapse to null are ok.
410ef860a24SChandler Carruth   if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
411ef860a24SChandler Carruth     return !GV->hasExternalWeakLinkage();
412ef860a24SChandler Carruth 
413ef860a24SChandler Carruth   // byval arguments are ok.
414ef860a24SChandler Carruth   if (const Argument *A = dyn_cast<Argument>(V))
415ef860a24SChandler Carruth     return A->hasByValAttr();
416ef860a24SChandler Carruth 
417ef860a24SChandler Carruth   // For GEPs, determine if the indexing lands within the allocated object.
418ef860a24SChandler Carruth   if (const GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
419ef860a24SChandler Carruth     // Conservatively require that the base pointer be fully dereferenceable.
420ef860a24SChandler Carruth     if (!Visited.insert(GEP->getOperand(0)))
421ef860a24SChandler Carruth       return false;
422ef860a24SChandler Carruth     if (!isDereferenceablePointer(GEP->getOperand(0), Visited))
423ef860a24SChandler Carruth       return false;
424ef860a24SChandler Carruth     // Check the indices.
425ef860a24SChandler Carruth     gep_type_iterator GTI = gep_type_begin(GEP);
426ef860a24SChandler Carruth     for (User::const_op_iterator I = GEP->op_begin()+1,
427ef860a24SChandler Carruth          E = GEP->op_end(); I != E; ++I) {
428ef860a24SChandler Carruth       Value *Index = *I;
429ef860a24SChandler Carruth       Type *Ty = *GTI++;
430ef860a24SChandler Carruth       // Struct indices can't be out of bounds.
431ef860a24SChandler Carruth       if (isa<StructType>(Ty))
432ef860a24SChandler Carruth         continue;
433ef860a24SChandler Carruth       ConstantInt *CI = dyn_cast<ConstantInt>(Index);
434ef860a24SChandler Carruth       if (!CI)
435ef860a24SChandler Carruth         return false;
436ef860a24SChandler Carruth       // Zero is always ok.
437ef860a24SChandler Carruth       if (CI->isZero())
438ef860a24SChandler Carruth         continue;
439ef860a24SChandler Carruth       // Check to see that it's within the bounds of an array.
440ef860a24SChandler Carruth       ArrayType *ATy = dyn_cast<ArrayType>(Ty);
441ef860a24SChandler Carruth       if (!ATy)
442ef860a24SChandler Carruth         return false;
443ef860a24SChandler Carruth       if (CI->getValue().getActiveBits() > 64)
444ef860a24SChandler Carruth         return false;
445ef860a24SChandler Carruth       if (CI->getZExtValue() >= ATy->getNumElements())
446ef860a24SChandler Carruth         return false;
447ef860a24SChandler Carruth     }
448ef860a24SChandler Carruth     // Indices check out; this is dereferenceable.
449ef860a24SChandler Carruth     return true;
450ef860a24SChandler Carruth   }
451ef860a24SChandler Carruth 
452ef860a24SChandler Carruth   // If we don't know, assume the worst.
453ef860a24SChandler Carruth   return false;
454ef860a24SChandler Carruth }
455ef860a24SChandler Carruth 
456ef860a24SChandler Carruth /// isDereferenceablePointer - Test if this value is always a pointer to
457ef860a24SChandler Carruth /// allocated and suitably aligned memory for a simple load or store.
458ef860a24SChandler Carruth bool Value::isDereferenceablePointer() const {
459ef860a24SChandler Carruth   SmallPtrSet<const Value *, 32> Visited;
460ef860a24SChandler Carruth   return ::isDereferenceablePointer(this, Visited);
461ef860a24SChandler Carruth }
462ef860a24SChandler Carruth 
463ef860a24SChandler Carruth /// DoPHITranslation - If this value is a PHI node with CurBB as its parent,
464ef860a24SChandler Carruth /// return the value in the PHI node corresponding to PredBB.  If not, return
465ef860a24SChandler Carruth /// ourself.  This is useful if you want to know the value something has in a
466ef860a24SChandler Carruth /// predecessor block.
467ef860a24SChandler Carruth Value *Value::DoPHITranslation(const BasicBlock *CurBB,
468ef860a24SChandler Carruth                                const BasicBlock *PredBB) {
469ef860a24SChandler Carruth   PHINode *PN = dyn_cast<PHINode>(this);
470ef860a24SChandler Carruth   if (PN && PN->getParent() == CurBB)
471ef860a24SChandler Carruth     return PN->getIncomingValueForBlock(PredBB);
472ef860a24SChandler Carruth   return this;
473ef860a24SChandler Carruth }
474ef860a24SChandler Carruth 
475ef860a24SChandler Carruth LLVMContext &Value::getContext() const { return VTy->getContext(); }
476ef860a24SChandler Carruth 
477ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
478ef860a24SChandler Carruth //                             ValueHandleBase Class
479ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
480ef860a24SChandler Carruth 
481ef860a24SChandler Carruth /// AddToExistingUseList - Add this ValueHandle to the use list for VP, where
482ef860a24SChandler Carruth /// List is known to point into the existing use list.
483ef860a24SChandler Carruth void ValueHandleBase::AddToExistingUseList(ValueHandleBase **List) {
484ef860a24SChandler Carruth   assert(List && "Handle list is null?");
485ef860a24SChandler Carruth 
486ef860a24SChandler Carruth   // Splice ourselves into the list.
487ef860a24SChandler Carruth   Next = *List;
488ef860a24SChandler Carruth   *List = this;
489ef860a24SChandler Carruth   setPrevPtr(List);
490ef860a24SChandler Carruth   if (Next) {
491ef860a24SChandler Carruth     Next->setPrevPtr(&Next);
492ef860a24SChandler Carruth     assert(VP.getPointer() == Next->VP.getPointer() && "Added to wrong list?");
493ef860a24SChandler Carruth   }
494ef860a24SChandler Carruth }
495ef860a24SChandler Carruth 
496ef860a24SChandler Carruth void ValueHandleBase::AddToExistingUseListAfter(ValueHandleBase *List) {
497ef860a24SChandler Carruth   assert(List && "Must insert after existing node");
498ef860a24SChandler Carruth 
499ef860a24SChandler Carruth   Next = List->Next;
500ef860a24SChandler Carruth   setPrevPtr(&List->Next);
501ef860a24SChandler Carruth   List->Next = this;
502ef860a24SChandler Carruth   if (Next)
503ef860a24SChandler Carruth     Next->setPrevPtr(&Next);
504ef860a24SChandler Carruth }
505ef860a24SChandler Carruth 
506ef860a24SChandler Carruth /// AddToUseList - Add this ValueHandle to the use list for VP.
507ef860a24SChandler Carruth void ValueHandleBase::AddToUseList() {
508ef860a24SChandler Carruth   assert(VP.getPointer() && "Null pointer doesn't have a use list!");
509ef860a24SChandler Carruth 
510ef860a24SChandler Carruth   LLVMContextImpl *pImpl = VP.getPointer()->getContext().pImpl;
511ef860a24SChandler Carruth 
512ef860a24SChandler Carruth   if (VP.getPointer()->HasValueHandle) {
513ef860a24SChandler Carruth     // If this value already has a ValueHandle, then it must be in the
514ef860a24SChandler Carruth     // ValueHandles map already.
515ef860a24SChandler Carruth     ValueHandleBase *&Entry = pImpl->ValueHandles[VP.getPointer()];
516ef860a24SChandler Carruth     assert(Entry != 0 && "Value doesn't have any handles?");
517ef860a24SChandler Carruth     AddToExistingUseList(&Entry);
518ef860a24SChandler Carruth     return;
519ef860a24SChandler Carruth   }
520ef860a24SChandler Carruth 
521ef860a24SChandler Carruth   // Ok, it doesn't have any handles yet, so we must insert it into the
522ef860a24SChandler Carruth   // DenseMap.  However, doing this insertion could cause the DenseMap to
523ef860a24SChandler Carruth   // reallocate itself, which would invalidate all of the PrevP pointers that
524ef860a24SChandler Carruth   // point into the old table.  Handle this by checking for reallocation and
525ef860a24SChandler Carruth   // updating the stale pointers only if needed.
526ef860a24SChandler Carruth   DenseMap<Value*, ValueHandleBase*> &Handles = pImpl->ValueHandles;
527ef860a24SChandler Carruth   const void *OldBucketPtr = Handles.getPointerIntoBucketsArray();
528ef860a24SChandler Carruth 
529ef860a24SChandler Carruth   ValueHandleBase *&Entry = Handles[VP.getPointer()];
530ef860a24SChandler Carruth   assert(Entry == 0 && "Value really did already have handles?");
531ef860a24SChandler Carruth   AddToExistingUseList(&Entry);
532ef860a24SChandler Carruth   VP.getPointer()->HasValueHandle = true;
533ef860a24SChandler Carruth 
534ef860a24SChandler Carruth   // If reallocation didn't happen or if this was the first insertion, don't
535ef860a24SChandler Carruth   // walk the table.
536ef860a24SChandler Carruth   if (Handles.isPointerIntoBucketsArray(OldBucketPtr) ||
537ef860a24SChandler Carruth       Handles.size() == 1) {
538ef860a24SChandler Carruth     return;
539ef860a24SChandler Carruth   }
540ef860a24SChandler Carruth 
541ef860a24SChandler Carruth   // Okay, reallocation did happen.  Fix the Prev Pointers.
542ef860a24SChandler Carruth   for (DenseMap<Value*, ValueHandleBase*>::iterator I = Handles.begin(),
543ef860a24SChandler Carruth        E = Handles.end(); I != E; ++I) {
544ef860a24SChandler Carruth     assert(I->second && I->first == I->second->VP.getPointer() &&
545ef860a24SChandler Carruth            "List invariant broken!");
546ef860a24SChandler Carruth     I->second->setPrevPtr(&I->second);
547ef860a24SChandler Carruth   }
548ef860a24SChandler Carruth }
549ef860a24SChandler Carruth 
550ef860a24SChandler Carruth /// RemoveFromUseList - Remove this ValueHandle from its current use list.
551ef860a24SChandler Carruth void ValueHandleBase::RemoveFromUseList() {
552ef860a24SChandler Carruth   assert(VP.getPointer() && VP.getPointer()->HasValueHandle &&
553ef860a24SChandler Carruth          "Pointer doesn't have a use list!");
554ef860a24SChandler Carruth 
555ef860a24SChandler Carruth   // Unlink this from its use list.
556ef860a24SChandler Carruth   ValueHandleBase **PrevPtr = getPrevPtr();
557ef860a24SChandler Carruth   assert(*PrevPtr == this && "List invariant broken");
558ef860a24SChandler Carruth 
559ef860a24SChandler Carruth   *PrevPtr = Next;
560ef860a24SChandler Carruth   if (Next) {
561ef860a24SChandler Carruth     assert(Next->getPrevPtr() == &Next && "List invariant broken");
562ef860a24SChandler Carruth     Next->setPrevPtr(PrevPtr);
563ef860a24SChandler Carruth     return;
564ef860a24SChandler Carruth   }
565ef860a24SChandler Carruth 
566ef860a24SChandler Carruth   // If the Next pointer was null, then it is possible that this was the last
567ef860a24SChandler Carruth   // ValueHandle watching VP.  If so, delete its entry from the ValueHandles
568ef860a24SChandler Carruth   // map.
569ef860a24SChandler Carruth   LLVMContextImpl *pImpl = VP.getPointer()->getContext().pImpl;
570ef860a24SChandler Carruth   DenseMap<Value*, ValueHandleBase*> &Handles = pImpl->ValueHandles;
571ef860a24SChandler Carruth   if (Handles.isPointerIntoBucketsArray(PrevPtr)) {
572ef860a24SChandler Carruth     Handles.erase(VP.getPointer());
573ef860a24SChandler Carruth     VP.getPointer()->HasValueHandle = false;
574ef860a24SChandler Carruth   }
575ef860a24SChandler Carruth }
576ef860a24SChandler Carruth 
577ef860a24SChandler Carruth 
578ef860a24SChandler Carruth void ValueHandleBase::ValueIsDeleted(Value *V) {
579ef860a24SChandler Carruth   assert(V->HasValueHandle && "Should only be called if ValueHandles present");
580ef860a24SChandler Carruth 
581ef860a24SChandler Carruth   // Get the linked list base, which is guaranteed to exist since the
582ef860a24SChandler Carruth   // HasValueHandle flag is set.
583ef860a24SChandler Carruth   LLVMContextImpl *pImpl = V->getContext().pImpl;
584ef860a24SChandler Carruth   ValueHandleBase *Entry = pImpl->ValueHandles[V];
585ef860a24SChandler Carruth   assert(Entry && "Value bit set but no entries exist");
586ef860a24SChandler Carruth 
587ef860a24SChandler Carruth   // We use a local ValueHandleBase as an iterator so that ValueHandles can add
588ef860a24SChandler Carruth   // and remove themselves from the list without breaking our iteration.  This
589ef860a24SChandler Carruth   // is not really an AssertingVH; we just have to give ValueHandleBase a kind.
590ef860a24SChandler Carruth   // Note that we deliberately do not the support the case when dropping a value
591ef860a24SChandler Carruth   // handle results in a new value handle being permanently added to the list
592ef860a24SChandler Carruth   // (as might occur in theory for CallbackVH's): the new value handle will not
593ef860a24SChandler Carruth   // be processed and the checking code will mete out righteous punishment if
594ef860a24SChandler Carruth   // the handle is still present once we have finished processing all the other
595ef860a24SChandler Carruth   // value handles (it is fine to momentarily add then remove a value handle).
596ef860a24SChandler Carruth   for (ValueHandleBase Iterator(Assert, *Entry); Entry; Entry = Iterator.Next) {
597ef860a24SChandler Carruth     Iterator.RemoveFromUseList();
598ef860a24SChandler Carruth     Iterator.AddToExistingUseListAfter(Entry);
599ef860a24SChandler Carruth     assert(Entry->Next == &Iterator && "Loop invariant broken.");
600ef860a24SChandler Carruth 
601ef860a24SChandler Carruth     switch (Entry->getKind()) {
602ef860a24SChandler Carruth     case Assert:
603ef860a24SChandler Carruth       break;
604ef860a24SChandler Carruth     case Tracking:
605ef860a24SChandler Carruth       // Mark that this value has been deleted by setting it to an invalid Value
606ef860a24SChandler Carruth       // pointer.
607ef860a24SChandler Carruth       Entry->operator=(DenseMapInfo<Value *>::getTombstoneKey());
608ef860a24SChandler Carruth       break;
609ef860a24SChandler Carruth     case Weak:
610ef860a24SChandler Carruth       // Weak just goes to null, which will unlink it from the list.
611ef860a24SChandler Carruth       Entry->operator=(0);
612ef860a24SChandler Carruth       break;
613ef860a24SChandler Carruth     case Callback:
614ef860a24SChandler Carruth       // Forward to the subclass's implementation.
615ef860a24SChandler Carruth       static_cast<CallbackVH*>(Entry)->deleted();
616ef860a24SChandler Carruth       break;
617ef860a24SChandler Carruth     }
618ef860a24SChandler Carruth   }
619ef860a24SChandler Carruth 
620ef860a24SChandler Carruth   // All callbacks, weak references, and assertingVHs should be dropped by now.
621ef860a24SChandler Carruth   if (V->HasValueHandle) {
622ef860a24SChandler Carruth #ifndef NDEBUG      // Only in +Asserts mode...
623ef860a24SChandler Carruth     dbgs() << "While deleting: " << *V->getType() << " %" << V->getName()
624ef860a24SChandler Carruth            << "\n";
625ef860a24SChandler Carruth     if (pImpl->ValueHandles[V]->getKind() == Assert)
626ef860a24SChandler Carruth       llvm_unreachable("An asserting value handle still pointed to this"
627ef860a24SChandler Carruth                        " value!");
628ef860a24SChandler Carruth 
629ef860a24SChandler Carruth #endif
630ef860a24SChandler Carruth     llvm_unreachable("All references to V were not removed?");
631ef860a24SChandler Carruth   }
632ef860a24SChandler Carruth }
633ef860a24SChandler Carruth 
634ef860a24SChandler Carruth 
635ef860a24SChandler Carruth void ValueHandleBase::ValueIsRAUWd(Value *Old, Value *New) {
636ef860a24SChandler Carruth   assert(Old->HasValueHandle &&"Should only be called if ValueHandles present");
637ef860a24SChandler Carruth   assert(Old != New && "Changing value into itself!");
638ef860a24SChandler Carruth 
639ef860a24SChandler Carruth   // Get the linked list base, which is guaranteed to exist since the
640ef860a24SChandler Carruth   // HasValueHandle flag is set.
641ef860a24SChandler Carruth   LLVMContextImpl *pImpl = Old->getContext().pImpl;
642ef860a24SChandler Carruth   ValueHandleBase *Entry = pImpl->ValueHandles[Old];
643ef860a24SChandler Carruth 
644ef860a24SChandler Carruth   assert(Entry && "Value bit set but no entries exist");
645ef860a24SChandler Carruth 
646ef860a24SChandler Carruth   // We use a local ValueHandleBase as an iterator so that
647ef860a24SChandler Carruth   // ValueHandles can add and remove themselves from the list without
648ef860a24SChandler Carruth   // breaking our iteration.  This is not really an AssertingVH; we
649ef860a24SChandler Carruth   // just have to give ValueHandleBase some kind.
650ef860a24SChandler Carruth   for (ValueHandleBase Iterator(Assert, *Entry); Entry; Entry = Iterator.Next) {
651ef860a24SChandler Carruth     Iterator.RemoveFromUseList();
652ef860a24SChandler Carruth     Iterator.AddToExistingUseListAfter(Entry);
653ef860a24SChandler Carruth     assert(Entry->Next == &Iterator && "Loop invariant broken.");
654ef860a24SChandler Carruth 
655ef860a24SChandler Carruth     switch (Entry->getKind()) {
656ef860a24SChandler Carruth     case Assert:
657ef860a24SChandler Carruth       // Asserting handle does not follow RAUW implicitly.
658ef860a24SChandler Carruth       break;
659ef860a24SChandler Carruth     case Tracking:
660ef860a24SChandler Carruth       // Tracking goes to new value like a WeakVH. Note that this may make it
661ef860a24SChandler Carruth       // something incompatible with its templated type. We don't want to have a
662ef860a24SChandler Carruth       // virtual (or inline) interface to handle this though, so instead we make
663ef860a24SChandler Carruth       // the TrackingVH accessors guarantee that a client never sees this value.
664ef860a24SChandler Carruth 
665ef860a24SChandler Carruth       // FALLTHROUGH
666ef860a24SChandler Carruth     case Weak:
667ef860a24SChandler Carruth       // Weak goes to the new value, which will unlink it from Old's list.
668ef860a24SChandler Carruth       Entry->operator=(New);
669ef860a24SChandler Carruth       break;
670ef860a24SChandler Carruth     case Callback:
671ef860a24SChandler Carruth       // Forward to the subclass's implementation.
672ef860a24SChandler Carruth       static_cast<CallbackVH*>(Entry)->allUsesReplacedWith(New);
673ef860a24SChandler Carruth       break;
674ef860a24SChandler Carruth     }
675ef860a24SChandler Carruth   }
676ef860a24SChandler Carruth 
677ef860a24SChandler Carruth #ifndef NDEBUG
678ef860a24SChandler Carruth   // If any new tracking or weak value handles were added while processing the
679ef860a24SChandler Carruth   // list, then complain about it now.
680ef860a24SChandler Carruth   if (Old->HasValueHandle)
681ef860a24SChandler Carruth     for (Entry = pImpl->ValueHandles[Old]; Entry; Entry = Entry->Next)
682ef860a24SChandler Carruth       switch (Entry->getKind()) {
683ef860a24SChandler Carruth       case Tracking:
684ef860a24SChandler Carruth       case Weak:
685ef860a24SChandler Carruth         dbgs() << "After RAUW from " << *Old->getType() << " %"
686ef860a24SChandler Carruth                << Old->getName() << " to " << *New->getType() << " %"
687ef860a24SChandler Carruth                << New->getName() << "\n";
688ef860a24SChandler Carruth         llvm_unreachable("A tracking or weak value handle still pointed to the"
689ef860a24SChandler Carruth                          " old value!\n");
690ef860a24SChandler Carruth       default:
691ef860a24SChandler Carruth         break;
692ef860a24SChandler Carruth       }
693ef860a24SChandler Carruth #endif
694ef860a24SChandler Carruth }
695ef860a24SChandler Carruth 
696ef860a24SChandler Carruth // Default implementation for CallbackVH.
697ef860a24SChandler Carruth void CallbackVH::allUsesReplacedWith(Value *) {}
698ef860a24SChandler Carruth 
699ef860a24SChandler Carruth void CallbackVH::deleted() {
700ef860a24SChandler Carruth   setValPtr(NULL);
701ef860a24SChandler Carruth }
702