add a setName variant that takes a null-terminated string. This can be
[oota-llvm.git] / lib / VMCore / Value.cpp
1 //===-- Value.cpp - Implement the Value class -----------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source 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/Module.h"
18 #include "llvm/ValueSymbolTable.h"
19 #include "llvm/Support/Debug.h"
20 #include "llvm/Support/LeakDetector.h"
21 #include <algorithm>
22 using namespace llvm;
23
24 //===----------------------------------------------------------------------===//
25 //                                Value Class
26 //===----------------------------------------------------------------------===//
27
28 static inline const Type *checkType(const Type *Ty) {
29   assert(Ty && "Value defined with a null type: Error!");
30   return Ty;
31 }
32
33 Value::Value(const Type *ty, unsigned scid)
34   : SubclassID(scid), SubclassData(0), Ty(checkType(ty)),
35     UseList(0), Name(0) {
36   if (!isa<Constant>(this) && !isa<BasicBlock>(this))
37     assert((Ty->isFirstClassType() || Ty == Type::VoidTy ||
38            isa<OpaqueType>(ty)) &&
39            "Cannot create non-first-class values except for constants!");
40 }
41
42 Value::~Value() {
43 #ifndef NDEBUG      // Only in -g mode...
44   // Check to make sure that there are no uses of this value that are still
45   // around when the value is destroyed.  If there are, then we have a dangling
46   // reference and something is wrong.  This code is here to print out what is
47   // still being referenced.  The value in question should be printed as
48   // a <badref>
49   //
50   if (use_begin() != use_end()) {
51     DOUT << "While deleting: " << *Ty << " %" << Name << "\n";
52     for (use_iterator I = use_begin(), E = use_end(); I != E; ++I)
53       DOUT << "Use still stuck around after Def is destroyed:"
54            << **I << "\n";
55   }
56 #endif
57   assert(use_begin() == use_end() && "Uses remain when a value is destroyed!");
58
59   // There should be no uses of this object anymore, remove it.
60   LeakDetector::removeGarbageObject(this);
61 }
62
63 /// hasNUses - Return true if this Value has exactly N users.
64 ///
65 bool Value::hasNUses(unsigned N) const {
66   use_const_iterator UI = use_begin(), E = use_end();
67
68   for (; N; --N, ++UI)
69     if (UI == E) return false;  // Too few.
70   return UI == E;
71 }
72
73 /// hasNUsesOrMore - Return true if this value has N users or more.  This is
74 /// logically equivalent to getNumUses() >= N.
75 ///
76 bool Value::hasNUsesOrMore(unsigned N) const {
77   use_const_iterator UI = use_begin(), E = use_end();
78
79   for (; N; --N, ++UI)
80     if (UI == E) return false;  // Too few.
81
82   return true;
83 }
84
85
86 /// getNumUses - This method computes the number of uses of this Value.  This
87 /// is a linear time operation.  Use hasOneUse or hasNUses to check for specific
88 /// values.
89 unsigned Value::getNumUses() const {
90   return (unsigned)std::distance(use_begin(), use_end());
91 }
92
93 static bool getSymTab(Value *V, ValueSymbolTable *&ST) {
94   ST = 0;
95   if (Instruction *I = dyn_cast<Instruction>(V)) {
96     if (BasicBlock *P = I->getParent())
97       if (Function *PP = P->getParent())
98         ST = &PP->getValueSymbolTable();
99   } else if (BasicBlock *BB = dyn_cast<BasicBlock>(V)) {
100     if (Function *P = BB->getParent()) 
101       ST = &P->getValueSymbolTable();
102   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
103     if (Module *P = GV->getParent()) 
104       ST = &P->getValueSymbolTable();
105   } else if (Argument *A = dyn_cast<Argument>(V)) {
106     if (Function *P = A->getParent()) 
107       ST = &P->getValueSymbolTable();
108   } else {
109     assert(isa<Constant>(V) && "Unknown value type!");
110     return true;  // no name is setable for this.
111   }
112   return false;
113 }
114
115 std::string Value::getName() const {
116   if (Name == 0) return "";
117   return std::string(Name->getKeyData(),
118                      Name->getKeyData()+Name->getKeyLength());
119 }
120
121 void Value::setName(const std::string &name) {
122   setName(&name[0], name.size());
123 }
124
125 void Value::setName(const char *Name) {
126   setName(Name, Name ? strlen(Name) : 0);
127 }
128
129 void Value::setName(const char *NameStr, unsigned NameLen) {
130   if (NameLen == 0 && !hasName()) return;
131   if (getType() != Type::VoidTy && "Cannot assign a name to void values!");
132   
133   // Get the symbol table to update for this object.
134   ValueSymbolTable *ST;
135   if (getSymTab(this, ST))
136     return;  // Cannot set a name on this value (e.g. constant).
137
138   if (!ST) { // No symbol table to update?  Just do the change.
139     if (NameLen == 0) {
140       // Free the name for this value.
141       Name->Destroy();
142       Name = 0;
143       return;
144     }
145     
146     if (Name) {
147       // Name isn't changing?
148       if (NameLen == Name->getKeyLength() &&
149           !memcmp(Name->getKeyData(), NameStr, NameLen))
150         return;
151       Name->Destroy();
152     }
153     
154     // NOTE: Could optimize for the case the name is shrinking to not deallocate
155     // then reallocated.
156       
157     // Create the new name.
158     Name = ValueName::Create(NameStr, NameStr+NameLen);
159     Name->setValue(this);
160     return;
161   }
162   
163   // NOTE: Could optimize for the case the name is shrinking to not deallocate
164   // then reallocated.
165   if (hasName()) {
166     // Name isn't changing?
167     if (NameLen == Name->getKeyLength() &&
168         !memcmp(Name->getKeyData(), NameStr, NameLen))
169       return;
170
171     // Remove old name.
172     ST->removeValueName(Name);
173     Name->Destroy();
174     Name = 0;
175
176     if (NameLen == 0)
177       return;
178   }
179
180   // Name is changing to something new.
181   Name = ST->createValueName(NameStr, NameLen, this);
182 }
183
184
185 /// takeName - transfer the name from V to this value, setting V's name to
186 /// empty.  It is an error to call V->takeName(V). 
187 void Value::takeName(Value *V) {
188   if (!V->hasName()) {
189     if (hasName())
190       setName("");
191     return;
192   }
193   
194   std::string Name = V->getName();
195   V->setName("");
196   setName(Name);
197 }
198
199
200 // uncheckedReplaceAllUsesWith - This is exactly the same as replaceAllUsesWith,
201 // except that it doesn't have all of the asserts.  The asserts fail because we
202 // are half-way done resolving types, which causes some types to exist as two
203 // different Type*'s at the same time.  This is a sledgehammer to work around
204 // this problem.
205 //
206 void Value::uncheckedReplaceAllUsesWith(Value *New) {
207   while (!use_empty()) {
208     Use &U = *UseList;
209     // Must handle Constants specially, we cannot call replaceUsesOfWith on a
210     // constant!
211     if (Constant *C = dyn_cast<Constant>(U.getUser())) {
212       if (!isa<GlobalValue>(C))
213         C->replaceUsesOfWithOnConstant(this, New, &U);
214       else
215         U.set(New);
216     } else {
217       U.set(New);
218     }
219   }
220 }
221
222 void Value::replaceAllUsesWith(Value *New) {
223   assert(New && "Value::replaceAllUsesWith(<null>) is invalid!");
224   assert(New != this && "this->replaceAllUsesWith(this) is NOT valid!");
225   assert(New->getType() == getType() &&
226          "replaceAllUses of value with new value of different type!");
227
228   uncheckedReplaceAllUsesWith(New);
229 }
230
231 //===----------------------------------------------------------------------===//
232 //                                 User Class
233 //===----------------------------------------------------------------------===//
234
235 // replaceUsesOfWith - Replaces all references to the "From" definition with
236 // references to the "To" definition.
237 //
238 void User::replaceUsesOfWith(Value *From, Value *To) {
239   if (From == To) return;   // Duh what?
240
241   assert(!isa<Constant>(this) || isa<GlobalValue>(this) &&
242          "Cannot call User::replaceUsesofWith on a constant!");
243
244   for (unsigned i = 0, E = getNumOperands(); i != E; ++i)
245     if (getOperand(i) == From) {  // Is This operand is pointing to oldval?
246       // The side effects of this setOperand call include linking to
247       // "To", adding "this" to the uses list of To, and
248       // most importantly, removing "this" from the use list of "From".
249       setOperand(i, To); // Fix it now...
250     }
251 }
252