add a helper method: Value::takeName
[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, const std::string &name)
34   : SubclassID(scid), SubclassData(0), Ty(checkType(ty)),
35     UseList(0), Name(name) {
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   if (ty == Type::VoidTy)
41     assert(name.empty() && "Cannot have named void values!");
42 }
43
44 Value::~Value() {
45 #ifndef NDEBUG      // Only in -g mode...
46   // Check to make sure that there are no uses of this value that are still
47   // around when the value is destroyed.  If there are, then we have a dangling
48   // reference and something is wrong.  This code is here to print out what is
49   // still being referenced.  The value in question should be printed as
50   // a <badref>
51   //
52   if (use_begin() != use_end()) {
53     DOUT << "While deleting: " << *Ty << " %" << Name << "\n";
54     for (use_iterator I = use_begin(), E = use_end(); I != E; ++I)
55       DOUT << "Use still stuck around after Def is destroyed:"
56            << **I << "\n";
57   }
58 #endif
59   assert(use_begin() == use_end() && "Uses remain when a value is destroyed!");
60
61   // There should be no uses of this object anymore, remove it.
62   LeakDetector::removeGarbageObject(this);
63 }
64
65 /// hasNUses - Return true if this Value has exactly N users.
66 ///
67 bool Value::hasNUses(unsigned N) const {
68   use_const_iterator UI = use_begin(), E = use_end();
69
70   for (; N; --N, ++UI)
71     if (UI == E) return false;  // Too few.
72   return UI == E;
73 }
74
75 /// hasNUsesOrMore - Return true if this value has N users or more.  This is
76 /// logically equivalent to getNumUses() >= N.
77 ///
78 bool Value::hasNUsesOrMore(unsigned N) const {
79   use_const_iterator UI = use_begin(), E = use_end();
80
81   for (; N; --N, ++UI)
82     if (UI == E) return false;  // Too few.
83
84   return true;
85 }
86
87
88 /// getNumUses - This method computes the number of uses of this Value.  This
89 /// is a linear time operation.  Use hasOneUse or hasNUses to check for specific
90 /// values.
91 unsigned Value::getNumUses() const {
92   return (unsigned)std::distance(use_begin(), use_end());
93 }
94
95 static bool getSymTab(Value *V, ValueSymbolTable *&ST) {
96   if (Instruction *I = dyn_cast<Instruction>(V)) {
97     if (BasicBlock *P = I->getParent())
98       if (Function *PP = P->getParent())
99         ST = &PP->getValueSymbolTable();
100   } else if (BasicBlock *BB = dyn_cast<BasicBlock>(V)) {
101     if (Function *P = BB->getParent()) 
102       ST = &P->getValueSymbolTable();
103   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
104     if (Module *P = GV->getParent()) 
105       ST = &P->getValueSymbolTable();
106   } else if (Argument *A = dyn_cast<Argument>(V)) {
107     if (Function *P = A->getParent()) 
108       ST = &P->getValueSymbolTable();
109   } else {
110     assert(isa<Constant>(V) && "Unknown value type!");
111     return true;  // no name is setable for this.
112   }
113   return false;
114 }
115
116 void Value::setName(const std::string &name) {
117   if (Name == name) return;   // Name is already set.
118
119   // Get the symbol table to update for this object.
120   ValueSymbolTable *ST;
121   if (getSymTab(this, ST))
122     return;  // Cannot set a name on this value (e.g. constant).
123
124   if (!ST)  // No symbol table to update?  Just do the change.
125     Name = name;
126   else if (hasName()) {
127     if (!name.empty()) {    // Replacing name.
128       ST->remove(this);
129       Name = name;
130       ST->insert(this);
131     } else {                // Transitioning from hasName -> noname.
132       ST->remove(this);
133       Name.clear();
134     }
135   } else {                  // Transitioning from noname -> hasName.
136     Name = name;
137     ST->insert(this);
138   }
139 }
140
141 /// takeName - transfer the name from V to this value, setting V's name to
142 /// empty.  It is an error to call V->takeName(V). 
143 void Value::takeName(Value *V) {
144   std::string Name = V->getName();
145   V->setName("");
146   setName(Name);
147 }
148
149
150 // uncheckedReplaceAllUsesWith - This is exactly the same as replaceAllUsesWith,
151 // except that it doesn't have all of the asserts.  The asserts fail because we
152 // are half-way done resolving types, which causes some types to exist as two
153 // different Type*'s at the same time.  This is a sledgehammer to work around
154 // this problem.
155 //
156 void Value::uncheckedReplaceAllUsesWith(Value *New) {
157   while (!use_empty()) {
158     Use &U = *UseList;
159     // Must handle Constants specially, we cannot call replaceUsesOfWith on a
160     // constant!
161     if (Constant *C = dyn_cast<Constant>(U.getUser())) {
162       if (!isa<GlobalValue>(C))
163         C->replaceUsesOfWithOnConstant(this, New, &U);
164       else
165         U.set(New);
166     } else {
167       U.set(New);
168     }
169   }
170 }
171
172 void Value::replaceAllUsesWith(Value *New) {
173   assert(New && "Value::replaceAllUsesWith(<null>) is invalid!");
174   assert(New != this && "this->replaceAllUsesWith(this) is NOT valid!");
175   assert(New->getType() == getType() &&
176          "replaceAllUses of value with new value of different type!");
177
178   uncheckedReplaceAllUsesWith(New);
179 }
180
181 //===----------------------------------------------------------------------===//
182 //                                 User Class
183 //===----------------------------------------------------------------------===//
184
185 // replaceUsesOfWith - Replaces all references to the "From" definition with
186 // references to the "To" definition.
187 //
188 void User::replaceUsesOfWith(Value *From, Value *To) {
189   if (From == To) return;   // Duh what?
190
191   assert(!isa<Constant>(this) || isa<GlobalValue>(this) &&
192          "Cannot call User::replaceUsesofWith on a constant!");
193
194   for (unsigned i = 0, E = getNumOperands(); i != E; ++i)
195     if (getOperand(i) == From) {  // Is This operand is pointing to oldval?
196       // The side effects of this setOperand call include linking to
197       // "To", adding "this" to the uses list of To, and
198       // most importantly, removing "this" from the use list of "From".
199       setOperand(i, To); // Fix it now...
200     }
201 }
202