1 //===-- Value.cpp - Implement the Value class -----------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the Value and User classes.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Constant.h"
15 #include "llvm/Constants.h"
16 #include "llvm/DerivedTypes.h"
17 #include "llvm/InstrTypes.h"
18 #include "llvm/Instructions.h"
19 #include "llvm/Module.h"
20 #include "llvm/ValueSymbolTable.h"
21 #include "llvm/Support/Debug.h"
22 #include "llvm/Support/LeakDetector.h"
26 //===----------------------------------------------------------------------===//
28 //===----------------------------------------------------------------------===//
30 static inline const Type *checkType(const Type *Ty) {
31 assert(Ty && "Value defined with a null type: Error!");
35 Value::Value(const Type *ty, unsigned scid)
36 : SubclassID(scid), SubclassData(0), VTy(checkType(ty)),
38 if (isa<CallInst>(this) || isa<InvokeInst>(this))
39 assert((VTy->isFirstClassType() || VTy == Type::VoidTy ||
40 isa<OpaqueType>(ty) || VTy->getTypeID() == Type::StructTyID) &&
41 "invalid CallInst type!");
42 else if (!isa<Constant>(this) && !isa<BasicBlock>(this))
43 assert((VTy->isFirstClassType() || VTy == Type::VoidTy ||
44 isa<OpaqueType>(ty)) &&
45 "Cannot create non-first-class values except for constants!");
49 #ifndef NDEBUG // Only in -g mode...
50 // Check to make sure that there are no uses of this value that are still
51 // around when the value is destroyed. If there are, then we have a dangling
52 // reference and something is wrong. This code is here to print out what is
53 // still being referenced. The value in question should be printed as
57 cerr << "While deleting: " << *VTy << " %" << getNameStr() << "\n";
58 for (use_iterator I = use_begin(), E = use_end(); I != E; ++I)
59 cerr << "Use still stuck around after Def is destroyed:"
63 assert(use_empty() && "Uses remain when a value is destroyed!");
65 // If this value is named, destroy the name. This should not be in a symtab
70 // There should be no uses of this object anymore, remove it.
71 LeakDetector::removeGarbageObject(this);
74 /// hasNUses - Return true if this Value has exactly N users.
76 bool Value::hasNUses(unsigned N) const {
77 use_const_iterator UI = use_begin(), E = use_end();
80 if (UI == E) return false; // Too few.
84 /// hasNUsesOrMore - Return true if this value has N users or more. This is
85 /// logically equivalent to getNumUses() >= N.
87 bool Value::hasNUsesOrMore(unsigned N) const {
88 use_const_iterator UI = use_begin(), E = use_end();
91 if (UI == E) return false; // Too few.
96 /// isUsedInBasicBlock - Return true if this value is used in the specified
98 bool Value::isUsedInBasicBlock(const BasicBlock *BB) const {
99 for (use_const_iterator I = use_begin(), E = use_end(); I != E; ++I) {
100 const Instruction *User = dyn_cast<Instruction>(*I);
101 if (User && User->getParent() == BB)
108 /// getNumUses - This method computes the number of uses of this Value. This
109 /// is a linear time operation. Use hasOneUse or hasNUses to check for specific
111 unsigned Value::getNumUses() const {
112 return (unsigned)std::distance(use_begin(), use_end());
115 static bool getSymTab(Value *V, ValueSymbolTable *&ST) {
117 if (Instruction *I = dyn_cast<Instruction>(V)) {
118 if (BasicBlock *P = I->getParent())
119 if (Function *PP = P->getParent())
120 ST = &PP->getValueSymbolTable();
121 } else if (BasicBlock *BB = dyn_cast<BasicBlock>(V)) {
122 if (Function *P = BB->getParent())
123 ST = &P->getValueSymbolTable();
124 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
125 if (Module *P = GV->getParent())
126 ST = &P->getValueSymbolTable();
127 } else if (Argument *A = dyn_cast<Argument>(V)) {
128 if (Function *P = A->getParent())
129 ST = &P->getValueSymbolTable();
131 assert(isa<Constant>(V) && "Unknown value type!");
132 return true; // no name is setable for this.
137 /// getNameStart - Return a pointer to a null terminated string for this name.
138 /// Note that names can have null characters within the string as well as at
139 /// their end. This always returns a non-null pointer.
140 const char *Value::getNameStart() const {
141 if (Name == 0) return "";
142 return Name->getKeyData();
145 /// getNameLen - Return the length of the string, correctly handling nul
146 /// characters embedded into them.
147 unsigned Value::getNameLen() const {
148 return Name ? Name->getKeyLength() : 0;
151 /// isName - Return true if this value has the name specified by the provided
152 /// nul terminated string.
153 bool Value::isName(const char *N) const {
154 unsigned InLen = strlen(N);
155 return InLen == getNameLen() && memcmp(getNameStart(), N, InLen) == 0;
159 std::string Value::getNameStr() const {
160 if (Name == 0) return "";
161 return std::string(Name->getKeyData(),
162 Name->getKeyData()+Name->getKeyLength());
165 void Value::setName(const std::string &name) {
166 setName(&name[0], name.size());
169 void Value::setName(const char *Name) {
170 setName(Name, Name ? strlen(Name) : 0);
173 void Value::setName(const char *NameStr, unsigned NameLen) {
174 if (NameLen == 0 && !hasName()) return;
175 assert(getType() != Type::VoidTy && "Cannot assign a name to void values!");
177 // Get the symbol table to update for this object.
178 ValueSymbolTable *ST;
179 if (getSymTab(this, ST))
180 return; // Cannot set a name on this value (e.g. constant).
182 if (!ST) { // No symbol table to update? Just do the change.
184 // Free the name for this value.
191 // Name isn't changing?
192 if (NameLen == Name->getKeyLength() &&
193 !memcmp(Name->getKeyData(), NameStr, NameLen))
198 // NOTE: Could optimize for the case the name is shrinking to not deallocate
201 // Create the new name.
202 Name = ValueName::Create(NameStr, NameStr+NameLen);
203 Name->setValue(this);
207 // NOTE: Could optimize for the case the name is shrinking to not deallocate
210 // Name isn't changing?
211 if (NameLen == Name->getKeyLength() &&
212 !memcmp(Name->getKeyData(), NameStr, NameLen))
216 ST->removeValueName(Name);
224 // Name is changing to something new.
225 Name = ST->createValueName(NameStr, NameLen, this);
229 /// takeName - transfer the name from V to this value, setting V's name to
230 /// empty. It is an error to call V->takeName(V).
231 void Value::takeName(Value *V) {
232 ValueSymbolTable *ST = 0;
233 // If this value has a name, drop it.
235 // Get the symtab this is in.
236 if (getSymTab(this, ST)) {
237 // We can't set a name on this value, but we need to clear V's name if
239 if (V->hasName()) V->setName(0, 0);
240 return; // Cannot set a name on this value (e.g. constant).
245 ST->removeValueName(Name);
250 // Now we know that this has no name.
252 // If V has no name either, we're done.
253 if (!V->hasName()) return;
255 // Get this's symtab if we didn't before.
257 if (getSymTab(this, ST)) {
260 return; // Cannot set a name on this value (e.g. constant).
264 // Get V's ST, this should always succed, because V has a name.
265 ValueSymbolTable *VST;
266 bool Failure = getSymTab(V, VST);
267 assert(!Failure && "V has a name, so it should have a ST!"); Failure=Failure;
269 // If these values are both in the same symtab, we can do this very fast.
270 // This works even if both values have no symtab yet.
275 Name->setValue(this);
279 // Otherwise, things are slightly more complex. Remove V's name from VST and
280 // then reinsert it into ST.
283 VST->removeValueName(V->Name);
286 Name->setValue(this);
289 ST->reinsertValue(this);
293 // uncheckedReplaceAllUsesWith - This is exactly the same as replaceAllUsesWith,
294 // except that it doesn't have all of the asserts. The asserts fail because we
295 // are half-way done resolving types, which causes some types to exist as two
296 // different Type*'s at the same time. This is a sledgehammer to work around
299 void Value::uncheckedReplaceAllUsesWith(Value *New) {
300 while (!use_empty()) {
302 // Must handle Constants specially, we cannot call replaceUsesOfWith on a
303 // constant because they are uniqued.
304 if (Constant *C = dyn_cast<Constant>(U.getUser())) {
305 if (!isa<GlobalValue>(C)) {
306 C->replaceUsesOfWithOnConstant(this, New, &U);
315 void Value::replaceAllUsesWith(Value *New) {
316 assert(New && "Value::replaceAllUsesWith(<null>) is invalid!");
317 assert(New != this && "this->replaceAllUsesWith(this) is NOT valid!");
318 assert(New->getType() == getType() &&
319 "replaceAllUses of value with new value of different type!");
321 uncheckedReplaceAllUsesWith(New);
324 Value *Value::stripPointerCasts() {
325 if (!isa<PointerType>(getType()))
329 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
330 if (CE->getOpcode() == Instruction::GetElementPtr) {
331 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
332 if (!CE->getOperand(i)->isNullValue())
334 V = CE->getOperand(0);
335 } else if (CE->getOpcode() == Instruction::BitCast) {
336 V = CE->getOperand(0);
340 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(V)) {
341 if (!GEP->hasAllZeroIndices())
343 V = GEP->getOperand(0);
344 } else if (BitCastInst *CI = dyn_cast<BitCastInst>(V)) {
345 V = CI->getOperand(0);
349 assert(isa<PointerType>(V->getType()) && "Unexpected operand type!");
353 Value *Value::getUnderlyingObject() {
354 if (!isa<PointerType>(getType()))
358 if (Instruction *I = dyn_cast<Instruction>(V)) {
359 if (!isa<BitCastInst>(I) && !isa<GetElementPtrInst>(I))
361 V = I->getOperand(0);
362 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
363 if (CE->getOpcode() != Instruction::BitCast &&
364 CE->getOpcode() != Instruction::GetElementPtr)
366 V = CE->getOperand(0);
370 assert(isa<PointerType>(V->getType()) && "Unexpected operand type!");
374 /// DoPHITranslation - If this value is a PHI node with CurBB as its parent,
375 /// return the value in the PHI node corresponding to PredBB. If not, return
376 /// ourself. This is useful if you want to know the value something has in a
377 /// predecessor block.
378 Value *Value::DoPHITranslation(const BasicBlock *CurBB,
379 const BasicBlock *PredBB) {
380 PHINode *PN = dyn_cast<PHINode>(this);
381 if (PN && PN->getParent() == CurBB)
382 return PN->getIncomingValueForBlock(PredBB);
387 //===----------------------------------------------------------------------===//
389 //===----------------------------------------------------------------------===//
391 // replaceUsesOfWith - Replaces all references to the "From" definition with
392 // references to the "To" definition.
394 void User::replaceUsesOfWith(Value *From, Value *To) {
395 if (From == To) return; // Duh what?
397 assert((!isa<Constant>(this) || isa<GlobalValue>(this)) &&
398 "Cannot call User::replaceUsesofWith on a constant!");
400 for (unsigned i = 0, E = getNumOperands(); i != E; ++i)
401 if (getOperand(i) == From) { // Is This operand is pointing to oldval?
402 // The side effects of this setOperand call include linking to
403 // "To", adding "this" to the uses list of To, and
404 // most importantly, removing "this" from the use list of "From".
405 setOperand(i, To); // Fix it now...
409 void *User::operator new(size_t s, unsigned Us) {
410 void *Storage = ::operator new(s + sizeof(Use) * Us);
411 Use *Start = static_cast<Use*>(Storage);
412 Use *End = Start + Us;
413 User *Obj = reinterpret_cast<User*>(End);
414 Obj->OperandList = Start;
415 Obj->NumOperands = Us;
416 Use::initTags(Start, End);
420 void User::operator delete(void *Usr) {
421 User *Start = static_cast<User*>(Usr);
422 Use *Storage = static_cast<Use*>(Usr) - Start->NumOperands;
423 ::operator delete(Storage == Start->OperandList