763fc721e09b63986778d4b1e40c00f0709df7eb
[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 /// removeDeadBlockAddress - If there is a blockaddress node for this basic
79 /// block, try to remove it and any dead constant users of it.
80 void BasicBlock::removeDeadBlockAddress() {
81   if (!hasAddressTaken()) return;
82   removeDeadUsersOfConstant(BlockAddress::get(this));
83 }
84
85
86 /// Override destroyConstant to make sure it doesn't get called on
87 /// GlobalValue's because they shouldn't be treated like other constants.
88 void GlobalValue::destroyConstant() {
89   llvm_unreachable("You can't GV->destroyConstant()!");
90 }
91
92 /// copyAttributesFrom - copy all additional attributes (those not needed to
93 /// create a GlobalValue) from the GlobalValue Src to this one.
94 void GlobalValue::copyAttributesFrom(const GlobalValue *Src) {
95   setAlignment(Src->getAlignment());
96   setSection(Src->getSection());
97   setVisibility(Src->getVisibility());
98 }
99
100
101 //===----------------------------------------------------------------------===//
102 // GlobalVariable Implementation
103 //===----------------------------------------------------------------------===//
104
105 GlobalVariable::GlobalVariable(LLVMContext &Context, const Type *Ty,
106                                bool constant, LinkageTypes Link,
107                                Constant *InitVal, const Twine &Name,
108                                bool ThreadLocal, unsigned AddressSpace)
109   : GlobalValue(PointerType::get(Ty, AddressSpace), 
110                 Value::GlobalVariableVal,
111                 OperandTraits<GlobalVariable>::op_begin(this),
112                 InitVal != 0, Link, Name),
113     isConstantGlobal(constant), isThreadLocalSymbol(ThreadLocal) {
114   if (InitVal) {
115     assert(InitVal->getType() == Ty &&
116            "Initializer should be the same type as the GlobalVariable!");
117     Op<0>() = InitVal;
118   }
119
120   LeakDetector::addGarbageObject(this);
121 }
122
123 GlobalVariable::GlobalVariable(Module &M, const Type *Ty, bool constant,
124                                LinkageTypes Link, Constant *InitVal,
125                                const Twine &Name,
126                                GlobalVariable *Before, bool ThreadLocal,
127                                unsigned AddressSpace)
128   : GlobalValue(PointerType::get(Ty, AddressSpace), 
129                 Value::GlobalVariableVal,
130                 OperandTraits<GlobalVariable>::op_begin(this),
131                 InitVal != 0, Link, Name),
132     isConstantGlobal(constant), isThreadLocalSymbol(ThreadLocal) {
133   if (InitVal) {
134     assert(InitVal->getType() == Ty &&
135            "Initializer should be the same type as the GlobalVariable!");
136     Op<0>() = InitVal;
137   }
138   
139   LeakDetector::addGarbageObject(this);
140   
141   if (Before)
142     Before->getParent()->getGlobalList().insert(Before, this);
143   else
144     M.getGlobalList().push_back(this);
145 }
146
147 void GlobalVariable::setParent(Module *parent) {
148   if (getParent())
149     LeakDetector::addGarbageObject(this);
150   Parent = parent;
151   if (getParent())
152     LeakDetector::removeGarbageObject(this);
153 }
154
155 void GlobalVariable::removeFromParent() {
156   getParent()->getGlobalList().remove(this);
157 }
158
159 void GlobalVariable::eraseFromParent() {
160   getParent()->getGlobalList().erase(this);
161 }
162
163 void GlobalVariable::replaceUsesOfWithOnConstant(Value *From, Value *To,
164                                                  Use *U) {
165   // If you call this, then you better know this GVar has a constant
166   // initializer worth replacing. Enforce that here.
167   assert(getNumOperands() == 1 &&
168          "Attempt to replace uses of Constants on a GVar with no initializer");
169
170   // And, since you know it has an initializer, the From value better be
171   // the initializer :)
172   assert(getOperand(0) == From &&
173          "Attempt to replace wrong constant initializer in GVar");
174
175   // And, you better have a constant for the replacement value
176   assert(isa<Constant>(To) &&
177          "Attempt to replace GVar initializer with non-constant");
178
179   // Okay, preconditions out of the way, replace the constant initializer.
180   this->setOperand(0, cast<Constant>(To));
181 }
182
183 /// copyAttributesFrom - copy all additional attributes (those not needed to
184 /// create a GlobalVariable) from the GlobalVariable Src to this one.
185 void GlobalVariable::copyAttributesFrom(const GlobalValue *Src) {
186   assert(isa<GlobalVariable>(Src) && "Expected a GlobalVariable!");
187   GlobalValue::copyAttributesFrom(Src);
188   const GlobalVariable *SrcVar = cast<GlobalVariable>(Src);
189   setThreadLocal(SrcVar->isThreadLocal());
190 }
191
192
193 //===----------------------------------------------------------------------===//
194 // GlobalAlias Implementation
195 //===----------------------------------------------------------------------===//
196
197 GlobalAlias::GlobalAlias(const Type *Ty, LinkageTypes Link,
198                          const Twine &Name, Constant* aliasee,
199                          Module *ParentModule)
200   : GlobalValue(Ty, Value::GlobalAliasVal, &Op<0>(), 1, Link, Name) {
201   LeakDetector::addGarbageObject(this);
202
203   if (aliasee)
204     assert(aliasee->getType() == Ty && "Alias and aliasee types should match!");
205   Op<0>() = aliasee;
206
207   if (ParentModule)
208     ParentModule->getAliasList().push_back(this);
209 }
210
211 void GlobalAlias::setParent(Module *parent) {
212   if (getParent())
213     LeakDetector::addGarbageObject(this);
214   Parent = parent;
215   if (getParent())
216     LeakDetector::removeGarbageObject(this);
217 }
218
219 void GlobalAlias::removeFromParent() {
220   getParent()->getAliasList().remove(this);
221 }
222
223 void GlobalAlias::eraseFromParent() {
224   getParent()->getAliasList().erase(this);
225 }
226
227 bool GlobalAlias::isDeclaration() const {
228   const GlobalValue* AV = getAliasedGlobal();
229   if (AV)
230     return AV->isDeclaration();
231   else
232     return false;
233 }
234
235 void GlobalAlias::setAliasee(Constant *Aliasee) 
236 {
237   if (Aliasee)
238     assert(Aliasee->getType() == getType() &&
239            "Alias and aliasee types should match!");
240   
241   setOperand(0, Aliasee);
242 }
243
244 const GlobalValue *GlobalAlias::getAliasedGlobal() const {
245   const Constant *C = getAliasee();
246   if (C) {
247     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
248       return GV;
249     else {
250       const ConstantExpr *CE = 0;
251       if ((CE = dyn_cast<ConstantExpr>(C)) &&
252           (CE->getOpcode() == Instruction::BitCast || 
253            CE->getOpcode() == Instruction::GetElementPtr))
254         return dyn_cast<GlobalValue>(CE->getOperand(0));
255       else
256         llvm_unreachable("Unsupported aliasee");
257     }
258   }
259   return 0;
260 }
261
262 const GlobalValue *GlobalAlias::resolveAliasedGlobal(bool stopOnWeak) const {
263   SmallPtrSet<const GlobalValue*, 3> Visited;
264
265   // Check if we need to stop early.
266   if (stopOnWeak && mayBeOverridden())
267     return this;
268
269   const GlobalValue *GV = getAliasedGlobal();
270   Visited.insert(GV);
271
272   // Iterate over aliasing chain, stopping on weak alias if necessary.
273   while (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV)) {
274     if (stopOnWeak && GA->mayBeOverridden())
275       break;
276
277     GV = GA->getAliasedGlobal();
278
279     if (!Visited.insert(GV))
280       return NULL;
281   }
282
283   return GV;
284 }