API changes for class Use size reduction, wave 1.
[oota-llvm.git] / lib / VMCore / Value.cpp
1 //===-- Value.cpp - Implement the Value class -----------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the Value and User classes.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/Constant.h"
15 #include "llvm/DerivedTypes.h"
16 #include "llvm/InstrTypes.h"
17 #include "llvm/Instructions.h"
18 #include "llvm/Module.h"
19 #include "llvm/ValueSymbolTable.h"
20 #include "llvm/Support/Debug.h"
21 #include "llvm/Support/LeakDetector.h"
22 #include <algorithm>
23 using namespace llvm;
24
25 //===----------------------------------------------------------------------===//
26 //                                Value Class
27 //===----------------------------------------------------------------------===//
28
29 static inline const Type *checkType(const Type *Ty) {
30   assert(Ty && "Value defined with a null type: Error!");
31   return Ty;
32 }
33
34 Value::Value(const Type *ty, unsigned scid)
35   : SubclassID(scid), SubclassData(0), Ty(checkType(ty)),
36     UseList(0), Name(0) {
37   if (isa<CallInst>(this) || isa<InvokeInst>(this))
38     assert((Ty->isFirstClassType() || Ty == Type::VoidTy ||
39             isa<OpaqueType>(ty) || Ty->getTypeID() == Type::StructTyID) &&
40            "invalid CallInst  type!");
41   else if (!isa<Constant>(this) && !isa<BasicBlock>(this))
42     assert((Ty->isFirstClassType() || Ty == Type::VoidTy ||
43            isa<OpaqueType>(ty)) &&
44            "Cannot create non-first-class values except for constants!");
45 }
46
47 Value::~Value() {
48 #ifndef NDEBUG      // Only in -g mode...
49   // Check to make sure that there are no uses of this value that are still
50   // around when the value is destroyed.  If there are, then we have a dangling
51   // reference and something is wrong.  This code is here to print out what is
52   // still being referenced.  The value in question should be printed as
53   // a <badref>
54   //
55   if (!use_empty()) {
56     DOUT << "While deleting: " << *Ty << " %" << getNameStr() << "\n";
57     for (use_iterator I = use_begin(), E = use_end(); I != E; ++I)
58       DOUT << "Use still stuck around after Def is destroyed:"
59            << **I << "\n";
60   }
61 #endif
62   assert(use_empty() && "Uses remain when a value is destroyed!");
63
64   // If this value is named, destroy the name.  This should not be in a symtab
65   // at this point.
66   if (Name)
67     Name->Destroy();
68   
69   // There should be no uses of this object anymore, remove it.
70   LeakDetector::removeGarbageObject(this);
71 }
72
73 /// hasNUses - Return true if this Value has exactly N users.
74 ///
75 bool Value::hasNUses(unsigned N) const {
76   use_const_iterator UI = use_begin(), E = use_end();
77
78   for (; N; --N, ++UI)
79     if (UI == E) return false;  // Too few.
80   return UI == E;
81 }
82
83 /// hasNUsesOrMore - Return true if this value has N users or more.  This is
84 /// logically equivalent to getNumUses() >= N.
85 ///
86 bool Value::hasNUsesOrMore(unsigned N) const {
87   use_const_iterator UI = use_begin(), E = use_end();
88
89   for (; N; --N, ++UI)
90     if (UI == E) return false;  // Too few.
91
92   return true;
93 }
94
95
96 /// getNumUses - This method computes the number of uses of this Value.  This
97 /// is a linear time operation.  Use hasOneUse or hasNUses to check for specific
98 /// values.
99 unsigned Value::getNumUses() const {
100   return (unsigned)std::distance(use_begin(), use_end());
101 }
102
103 static bool getSymTab(Value *V, ValueSymbolTable *&ST) {
104   ST = 0;
105   if (Instruction *I = dyn_cast<Instruction>(V)) {
106     if (BasicBlock *P = I->getParent())
107       if (Function *PP = P->getParent())
108         ST = &PP->getValueSymbolTable();
109   } else if (BasicBlock *BB = dyn_cast<BasicBlock>(V)) {
110     if (Function *P = BB->getParent()) 
111       ST = &P->getValueSymbolTable();
112   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
113     if (Module *P = GV->getParent()) 
114       ST = &P->getValueSymbolTable();
115   } else if (Argument *A = dyn_cast<Argument>(V)) {
116     if (Function *P = A->getParent()) 
117       ST = &P->getValueSymbolTable();
118   } else {
119     assert(isa<Constant>(V) && "Unknown value type!");
120     return true;  // no name is setable for this.
121   }
122   return false;
123 }
124
125 /// getNameStart - Return a pointer to a null terminated string for this name.
126 /// Note that names can have null characters within the string as well as at
127 /// their end.  This always returns a non-null pointer.
128 const char *Value::getNameStart() const {
129   if (Name == 0) return "";
130   return Name->getKeyData();
131 }
132
133 /// getNameLen - Return the length of the string, correctly handling nul
134 /// characters embedded into them.
135 unsigned Value::getNameLen() const {
136   return Name ? Name->getKeyLength() : 0;
137 }
138
139
140 std::string Value::getNameStr() const {
141   if (Name == 0) return "";
142   return std::string(Name->getKeyData(),
143                      Name->getKeyData()+Name->getKeyLength());
144 }
145
146 void Value::setName(const std::string &name) {
147   setName(&name[0], name.size());
148 }
149
150 void Value::setName(const char *Name) {
151   setName(Name, Name ? strlen(Name) : 0);
152 }
153
154 void Value::setName(const char *NameStr, unsigned NameLen) {
155   if (NameLen == 0 && !hasName()) return;
156   assert(getType() != Type::VoidTy && "Cannot assign a name to void values!");
157   
158   // Get the symbol table to update for this object.
159   ValueSymbolTable *ST;
160   if (getSymTab(this, ST))
161     return;  // Cannot set a name on this value (e.g. constant).
162
163   if (!ST) { // No symbol table to update?  Just do the change.
164     if (NameLen == 0) {
165       // Free the name for this value.
166       Name->Destroy();
167       Name = 0;
168       return;
169     }
170     
171     if (Name) {
172       // Name isn't changing?
173       if (NameLen == Name->getKeyLength() &&
174           !memcmp(Name->getKeyData(), NameStr, NameLen))
175         return;
176       Name->Destroy();
177     }
178     
179     // NOTE: Could optimize for the case the name is shrinking to not deallocate
180     // then reallocated.
181       
182     // Create the new name.
183     Name = ValueName::Create(NameStr, NameStr+NameLen);
184     Name->setValue(this);
185     return;
186   }
187   
188   // NOTE: Could optimize for the case the name is shrinking to not deallocate
189   // then reallocated.
190   if (hasName()) {
191     // Name isn't changing?
192     if (NameLen == Name->getKeyLength() &&
193         !memcmp(Name->getKeyData(), NameStr, NameLen))
194       return;
195
196     // Remove old name.
197     ST->removeValueName(Name);
198     Name->Destroy();
199     Name = 0;
200
201     if (NameLen == 0)
202       return;
203   }
204
205   // Name is changing to something new.
206   Name = ST->createValueName(NameStr, NameLen, this);
207 }
208
209
210 /// takeName - transfer the name from V to this value, setting V's name to
211 /// empty.  It is an error to call V->takeName(V). 
212 void Value::takeName(Value *V) {
213   ValueSymbolTable *ST = 0;
214   // If this value has a name, drop it.
215   if (hasName()) {
216     // Get the symtab this is in.
217     if (getSymTab(this, ST)) {
218       // We can't set a name on this value, but we need to clear V's name if
219       // it has one.
220       if (V->hasName()) V->setName(0, 0);
221       return;  // Cannot set a name on this value (e.g. constant).
222     }
223     
224     // Remove old name.
225     if (ST)
226       ST->removeValueName(Name);
227     Name->Destroy();
228     Name = 0;
229   } 
230   
231   // Now we know that this has no name.
232   
233   // If V has no name either, we're done.
234   if (!V->hasName()) return;
235    
236   // Get this's symtab if we didn't before.
237   if (!ST) {
238     if (getSymTab(this, ST)) {
239       // Clear V's name.
240       V->setName(0, 0);
241       return;  // Cannot set a name on this value (e.g. constant).
242     }
243   }
244   
245   // Get V's ST, this should always succed, because V has a name.
246   ValueSymbolTable *VST;
247   bool Failure = getSymTab(V, VST);
248   assert(!Failure && "V has a name, so it should have a ST!");
249   
250   // If these values are both in the same symtab, we can do this very fast.
251   // This works even if both values have no symtab yet.
252   if (ST == VST) {
253     // Take the name!
254     Name = V->Name;
255     V->Name = 0;
256     Name->setValue(this);
257     return;
258   }
259   
260   // Otherwise, things are slightly more complex.  Remove V's name from VST and
261   // then reinsert it into ST.
262   
263   if (VST)
264     VST->removeValueName(V->Name);
265   Name = V->Name;
266   V->Name = 0;
267   Name->setValue(this);
268   
269   if (ST)
270     ST->reinsertValue(this);
271 }
272
273
274 // uncheckedReplaceAllUsesWith - This is exactly the same as replaceAllUsesWith,
275 // except that it doesn't have all of the asserts.  The asserts fail because we
276 // are half-way done resolving types, which causes some types to exist as two
277 // different Type*'s at the same time.  This is a sledgehammer to work around
278 // this problem.
279 //
280 void Value::uncheckedReplaceAllUsesWith(Value *New) {
281   while (!use_empty()) {
282     Use &U = *UseList;
283     // Must handle Constants specially, we cannot call replaceUsesOfWith on a
284     // constant because they are uniqued.
285     if (Constant *C = dyn_cast<Constant>(U.getUser())) {
286       if (!isa<GlobalValue>(C)) {
287         C->replaceUsesOfWithOnConstant(this, New, &U);
288         continue;
289       }
290     }
291     
292     U.set(New);
293   }
294 }
295
296 void Value::replaceAllUsesWith(Value *New) {
297   assert(New && "Value::replaceAllUsesWith(<null>) is invalid!");
298   assert(New != this && "this->replaceAllUsesWith(this) is NOT valid!");
299   assert(New->getType() == getType() &&
300          "replaceAllUses of value with new value of different type!");
301
302   uncheckedReplaceAllUsesWith(New);
303 }
304
305 //===----------------------------------------------------------------------===//
306 //                                 User Class
307 //===----------------------------------------------------------------------===//
308
309 // replaceUsesOfWith - Replaces all references to the "From" definition with
310 // references to the "To" definition.
311 //
312 void User::replaceUsesOfWith(Value *From, Value *To) {
313   if (From == To) return;   // Duh what?
314
315   assert((!isa<Constant>(this) || isa<GlobalValue>(this)) &&
316          "Cannot call User::replaceUsesofWith on a constant!");
317
318   for (unsigned i = 0, E = getNumOperands(); i != E; ++i)
319     if (getOperand(i) == From) {  // Is This operand is pointing to oldval?
320       // The side effects of this setOperand call include linking to
321       // "To", adding "this" to the uses list of To, and
322       // most importantly, removing "this" from the use list of "From".
323       setOperand(i, To); // Fix it now...
324     }
325 }
326