Start converting to new error handling API.
[oota-llvm.git] / lib / VMCore / Globals.cpp
1 //===-- Globals.cpp - Implement the GlobalValue & GlobalVariable 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 GlobalValue & GlobalVariable classes for the VMCore
11 // library.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "llvm/Constants.h"
16 #include "llvm/GlobalVariable.h"
17 #include "llvm/GlobalAlias.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/LLVMContext.h"
20 #include "llvm/Module.h"
21 #include "llvm/ADT/SmallPtrSet.h"
22 #include "llvm/Support/ErrorHandling.h"
23 #include "llvm/Support/LeakDetector.h"
24 using namespace llvm;
25
26 //===----------------------------------------------------------------------===//
27 //                            GlobalValue Class
28 //===----------------------------------------------------------------------===//
29
30 /// removeDeadUsersOfConstant - If the specified constantexpr is dead, remove
31 /// it.  This involves recursively eliminating any dead users of the
32 /// constantexpr.
33 static bool removeDeadUsersOfConstant(const Constant *C) {
34   if (isa<GlobalValue>(C)) return false; // Cannot remove this
35
36   while (!C->use_empty()) {
37     const Constant *User = dyn_cast<Constant>(C->use_back());
38     if (!User) return false; // Non-constant usage;
39     if (!removeDeadUsersOfConstant(User))
40       return false; // Constant wasn't dead
41   }
42
43   const_cast<Constant*>(C)->destroyConstant();
44   return true;
45 }
46
47 /// removeDeadConstantUsers - If there are any dead constant users dangling
48 /// off of this global value, remove them.  This method is useful for clients
49 /// that want to check to see if a global is unused, but don't want to deal
50 /// with potentially dead constants hanging off of the globals.
51 void GlobalValue::removeDeadConstantUsers() const {
52   Value::use_const_iterator I = use_begin(), E = use_end();
53   Value::use_const_iterator LastNonDeadUser = E;
54   while (I != E) {
55     if (const Constant *User = dyn_cast<Constant>(*I)) {
56       if (!removeDeadUsersOfConstant(User)) {
57         // If the constant wasn't dead, remember that this was the last live use
58         // and move on to the next constant.
59         LastNonDeadUser = I;
60         ++I;
61       } else {
62         // If the constant was dead, then the iterator is invalidated.
63         if (LastNonDeadUser == E) {
64           I = use_begin();
65           if (I == E) break;
66         } else {
67           I = LastNonDeadUser;
68           ++I;
69         }
70       }
71     } else {
72       LastNonDeadUser = I;
73       ++I;
74     }
75   }
76 }
77
78 /// Override destroyConstant to make sure it doesn't get called on
79 /// GlobalValue's because they shouldn't be treated like other constants.
80 void GlobalValue::destroyConstant() {
81   LLVM_UNREACHABLE("You can't GV->destroyConstant()!");
82 }
83
84 /// copyAttributesFrom - copy all additional attributes (those not needed to
85 /// create a GlobalValue) from the GlobalValue Src to this one.
86 void GlobalValue::copyAttributesFrom(const GlobalValue *Src) {
87   setAlignment(Src->getAlignment());
88   setSection(Src->getSection());
89   setVisibility(Src->getVisibility());
90 }
91
92
93 //===----------------------------------------------------------------------===//
94 // GlobalVariable Implementation
95 //===----------------------------------------------------------------------===//
96
97 GlobalVariable::GlobalVariable(LLVMContext &Context, const Type *Ty,
98                                bool constant, LinkageTypes Link,
99                                Constant *InitVal, const std::string &Name,
100                                Module *ParentModule, bool ThreadLocal, 
101                                unsigned AddressSpace)
102   : GlobalValue(Context.getPointerType(Ty, AddressSpace), 
103                 Value::GlobalVariableVal,
104                 OperandTraits<GlobalVariable>::op_begin(this),
105                 InitVal != 0, Link, Name),
106     isConstantGlobal(constant), isThreadLocalSymbol(ThreadLocal) {
107   if (InitVal) {
108     assert(InitVal->getType() == Ty &&
109            "Initializer should be the same type as the GlobalVariable!");
110     Op<0>() = InitVal;
111   }
112
113   LeakDetector::addGarbageObject(this);
114
115   if (ParentModule)
116     ParentModule->getGlobalList().push_back(this);
117 }
118
119 GlobalVariable::GlobalVariable(LLVMContext &Context, const Type *Ty,
120                                bool constant, LinkageTypes Link,
121                                Constant *InitVal, const std::string &Name,
122                                GlobalVariable *Before, bool ThreadLocal,
123                                unsigned AddressSpace)
124   : GlobalValue(Context.getPointerType(Ty, AddressSpace),
125                 Value::GlobalVariableVal,
126                 OperandTraits<GlobalVariable>::op_begin(this),
127                 InitVal != 0, Link, Name),
128     isConstantGlobal(constant), isThreadLocalSymbol(ThreadLocal) {
129   if (InitVal) {
130     assert(InitVal->getType() == Ty &&
131            "Initializer should be the same type as the GlobalVariable!");
132     Op<0>() = InitVal;
133   }
134   
135   LeakDetector::addGarbageObject(this);
136   
137   if (Before)
138     Before->getParent()->getGlobalList().insert(Before, this);
139 }
140
141 void GlobalVariable::setParent(Module *parent) {
142   if (getParent())
143     LeakDetector::addGarbageObject(this);
144   Parent = parent;
145   if (getParent())
146     LeakDetector::removeGarbageObject(this);
147 }
148
149 void GlobalVariable::removeFromParent() {
150   getParent()->getGlobalList().remove(this);
151 }
152
153 void GlobalVariable::eraseFromParent() {
154   getParent()->getGlobalList().erase(this);
155 }
156
157 void GlobalVariable::replaceUsesOfWithOnConstant(Value *From, Value *To,
158                                                  Use *U) {
159   // If you call this, then you better know this GVar has a constant
160   // initializer worth replacing. Enforce that here.
161   assert(getNumOperands() == 1 &&
162          "Attempt to replace uses of Constants on a GVar with no initializer");
163
164   // And, since you know it has an initializer, the From value better be
165   // the initializer :)
166   assert(getOperand(0) == From &&
167          "Attempt to replace wrong constant initializer in GVar");
168
169   // And, you better have a constant for the replacement value
170   assert(isa<Constant>(To) &&
171          "Attempt to replace GVar initializer with non-constant");
172
173   // Okay, preconditions out of the way, replace the constant initializer.
174   this->setOperand(0, cast<Constant>(To));
175 }
176
177 /// copyAttributesFrom - copy all additional attributes (those not needed to
178 /// create a GlobalVariable) from the GlobalVariable Src to this one.
179 void GlobalVariable::copyAttributesFrom(const GlobalValue *Src) {
180   assert(isa<GlobalVariable>(Src) && "Expected a GlobalVariable!");
181   GlobalValue::copyAttributesFrom(Src);
182   const GlobalVariable *SrcVar = cast<GlobalVariable>(Src);
183   setThreadLocal(SrcVar->isThreadLocal());
184 }
185
186
187 //===----------------------------------------------------------------------===//
188 // GlobalAlias Implementation
189 //===----------------------------------------------------------------------===//
190
191 GlobalAlias::GlobalAlias(const Type *Ty, LinkageTypes Link,
192                          const std::string &Name, Constant* aliasee,
193                          Module *ParentModule)
194   : GlobalValue(Ty, Value::GlobalAliasVal, &Op<0>(), 1, Link, Name) {
195   LeakDetector::addGarbageObject(this);
196
197   if (aliasee)
198     assert(aliasee->getType() == Ty && "Alias and aliasee types should match!");
199   Op<0>() = aliasee;
200
201   if (ParentModule)
202     ParentModule->getAliasList().push_back(this);
203 }
204
205 void GlobalAlias::setParent(Module *parent) {
206   if (getParent())
207     LeakDetector::addGarbageObject(this);
208   Parent = parent;
209   if (getParent())
210     LeakDetector::removeGarbageObject(this);
211 }
212
213 void GlobalAlias::removeFromParent() {
214   getParent()->getAliasList().remove(this);
215 }
216
217 void GlobalAlias::eraseFromParent() {
218   getParent()->getAliasList().erase(this);
219 }
220
221 bool GlobalAlias::isDeclaration() const {
222   const GlobalValue* AV = getAliasedGlobal();
223   if (AV)
224     return AV->isDeclaration();
225   else
226     return false;
227 }
228
229 void GlobalAlias::setAliasee(Constant *Aliasee) 
230 {
231   if (Aliasee)
232     assert(Aliasee->getType() == getType() &&
233            "Alias and aliasee types should match!");
234   
235   setOperand(0, Aliasee);
236 }
237
238 const GlobalValue *GlobalAlias::getAliasedGlobal() const {
239   const Constant *C = getAliasee();
240   if (C) {
241     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
242       return GV;
243     else {
244       const ConstantExpr *CE = 0;
245       if ((CE = dyn_cast<ConstantExpr>(C)) &&
246           (CE->getOpcode() == Instruction::BitCast || 
247            CE->getOpcode() == Instruction::GetElementPtr))
248         return dyn_cast<GlobalValue>(CE->getOperand(0));
249       else
250         LLVM_UNREACHABLE("Unsupported aliasee");
251     }
252   }
253   return 0;
254 }
255
256 const GlobalValue *GlobalAlias::resolveAliasedGlobal(bool stopOnWeak) const {
257   SmallPtrSet<const GlobalValue*, 3> Visited;
258
259   // Check if we need to stop early.
260   if (stopOnWeak && mayBeOverridden())
261     return this;
262
263   const GlobalValue *GV = getAliasedGlobal();
264   Visited.insert(GV);
265
266   // Iterate over aliasing chain, stopping on weak alias if necessary.
267   while (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV)) {
268     if (stopOnWeak && GA->mayBeOverridden())
269       break;
270
271     GV = GA->getAliasedGlobal();
272
273     if (!Visited.insert(GV))
274       return NULL;
275   }
276
277   return GV;
278 }