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