blob: e4696e61031545d9a1ffb0b1aa140a5d2f51f20a [file] [log] [blame]
Chris Lattner25db5802004-10-07 04:16:33 +00001//===- GlobalOpt.cpp - Optimize Global Variables --------------------------===//
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 pass transforms simple global variables that never have their address
11// taken. If obviously true, it marks read/write globals as constant, deletes
12// variables only stored to, etc.
13//
14//===----------------------------------------------------------------------===//
15
16#define DEBUG_TYPE "globalopt"
17#include "llvm/Transforms/IPO.h"
18#include "llvm/Constants.h"
19#include "llvm/DerivedTypes.h"
20#include "llvm/Instructions.h"
21#include "llvm/Module.h"
22#include "llvm/Pass.h"
23#include "llvm/Support/Debug.h"
24#include "llvm/ADT/Statistic.h"
Chris Lattnerabab0712004-10-08 17:32:09 +000025#include "llvm/ADT/StringExtras.h"
Chris Lattner25db5802004-10-07 04:16:33 +000026#include <set>
27#include <algorithm>
28using namespace llvm;
29
30namespace {
Chris Lattnerabab0712004-10-08 17:32:09 +000031 Statistic<> NumMarked ("globalopt", "Number of globals marked constant");
32 Statistic<> NumSRA ("globalopt", "Number of aggregate globals broken "
33 "into scalars");
34 Statistic<> NumDeleted ("globalopt", "Number of globals deleted");
Chris Lattner25db5802004-10-07 04:16:33 +000035 Statistic<> NumFnDeleted("globalopt", "Number of functions deleted");
36
37 struct GlobalOpt : public ModulePass {
38 bool runOnModule(Module &M);
39 };
40
41 RegisterOpt<GlobalOpt> X("globalopt", "Global Variable Optimizer");
42}
43
44ModulePass *llvm::createGlobalOptimizerPass() { return new GlobalOpt(); }
45
46/// GlobalStatus - As we analyze each global, keep track of some information
47/// about it. If we find out that the address of the global is taken, none of
Chris Lattner617f1a32004-10-07 21:30:30 +000048/// this info will be accurate.
Chris Lattner25db5802004-10-07 04:16:33 +000049struct GlobalStatus {
Chris Lattner617f1a32004-10-07 21:30:30 +000050 /// isLoaded - True if the global is ever loaded. If the global isn't ever
51 /// loaded it can be deleted.
Chris Lattner25db5802004-10-07 04:16:33 +000052 bool isLoaded;
Chris Lattner617f1a32004-10-07 21:30:30 +000053
54 /// StoredType - Keep track of what stores to the global look like.
55 ///
Chris Lattner25db5802004-10-07 04:16:33 +000056 enum StoredType {
Chris Lattner617f1a32004-10-07 21:30:30 +000057 /// NotStored - There is no store to this global. It can thus be marked
58 /// constant.
59 NotStored,
60
61 /// isInitializerStored - This global is stored to, but the only thing
62 /// stored is the constant it was initialized with. This is only tracked
63 /// for scalar globals.
64 isInitializerStored,
65
66 /// isStoredOnce - This global is stored to, but only its initializer and
67 /// one other value is ever stored to it. If this global isStoredOnce, we
68 /// track the value stored to it in StoredOnceValue below. This is only
69 /// tracked for scalar globals.
70 isStoredOnce,
71
72 /// isStored - This global is stored to by multiple values or something else
73 /// that we cannot track.
74 isStored
Chris Lattner25db5802004-10-07 04:16:33 +000075 } StoredType;
Chris Lattner617f1a32004-10-07 21:30:30 +000076
77 /// StoredOnceValue - If only one value (besides the initializer constant) is
78 /// ever stored to this global, keep track of what value it is.
79 Value *StoredOnceValue;
80
81 /// isNotSuitableForSRA - Keep track of whether any SRA preventing users of
82 /// the global exist. Such users include GEP instruction with variable
83 /// indexes, and non-gep/load/store users like constant expr casts.
Chris Lattner25db5802004-10-07 04:16:33 +000084 bool isNotSuitableForSRA;
85
Chris Lattner617f1a32004-10-07 21:30:30 +000086 GlobalStatus() : isLoaded(false), StoredType(NotStored), StoredOnceValue(0),
Chris Lattner25db5802004-10-07 04:16:33 +000087 isNotSuitableForSRA(false) {}
88};
89
Chris Lattner1c4bddc2004-10-08 20:59:28 +000090
91
92/// ConstantIsDead - Return true if the specified constant is (transitively)
93/// dead. The constant may be used by other constants (e.g. constant arrays and
94/// constant exprs) as long as they are dead, but it cannot be used by anything
95/// else.
96static bool ConstantIsDead(Constant *C) {
97 if (isa<GlobalValue>(C)) return false;
98
99 for (Value::use_iterator UI = C->use_begin(), E = C->use_end(); UI != E; ++UI)
100 if (Constant *CU = dyn_cast<Constant>(*UI)) {
101 if (!ConstantIsDead(CU)) return false;
102 } else
103 return false;
104 return true;
105}
106
107
Chris Lattner25db5802004-10-07 04:16:33 +0000108/// AnalyzeGlobal - Look at all uses of the global and fill in the GlobalStatus
109/// structure. If the global has its address taken, return true to indicate we
110/// can't do anything with it.
111///
112static bool AnalyzeGlobal(Value *V, GlobalStatus &GS,
113 std::set<PHINode*> &PHIUsers) {
114 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
115 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(*UI)) {
116 if (AnalyzeGlobal(CE, GS, PHIUsers)) return true;
117 if (CE->getOpcode() != Instruction::GetElementPtr)
118 GS.isNotSuitableForSRA = true;
Chris Lattnerabab0712004-10-08 17:32:09 +0000119 else if (!GS.isNotSuitableForSRA) {
120 // Check to see if this ConstantExpr GEP is SRA'able. In particular, we
121 // don't like < 3 operand CE's, and we don't like non-constant integer
122 // indices.
123 if (CE->getNumOperands() < 3 || !CE->getOperand(1)->isNullValue())
124 GS.isNotSuitableForSRA = true;
125 else {
126 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
127 if (!isa<ConstantInt>(CE->getOperand(i))) {
128 GS.isNotSuitableForSRA = true;
129 break;
130 }
131 }
132 }
133
Chris Lattner25db5802004-10-07 04:16:33 +0000134 } else if (Instruction *I = dyn_cast<Instruction>(*UI)) {
135 if (isa<LoadInst>(I)) {
136 GS.isLoaded = true;
137 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Chris Lattner02b6c912004-10-07 06:01:25 +0000138 // Don't allow a store OF the address, only stores TO the address.
139 if (SI->getOperand(0) == V) return true;
140
Chris Lattner617f1a32004-10-07 21:30:30 +0000141 // If this is a direct store to the global (i.e., the global is a scalar
142 // value, not an aggregate), keep more specific information about
143 // stores.
144 if (GS.StoredType != GlobalStatus::isStored)
145 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(SI->getOperand(1))){
146 if (SI->getOperand(0) == GV->getInitializer()) {
147 if (GS.StoredType < GlobalStatus::isInitializerStored)
148 GS.StoredType = GlobalStatus::isInitializerStored;
149 } else if (GS.StoredType < GlobalStatus::isStoredOnce) {
150 GS.StoredType = GlobalStatus::isStoredOnce;
151 GS.StoredOnceValue = SI->getOperand(0);
152 } else if (GS.StoredType == GlobalStatus::isStoredOnce &&
153 GS.StoredOnceValue == SI->getOperand(0)) {
154 // noop.
155 } else {
156 GS.StoredType = GlobalStatus::isStored;
157 }
158 } else {
Chris Lattner25db5802004-10-07 04:16:33 +0000159 GS.StoredType = GlobalStatus::isStored;
Chris Lattner617f1a32004-10-07 21:30:30 +0000160 }
Chris Lattner25db5802004-10-07 04:16:33 +0000161 } else if (I->getOpcode() == Instruction::GetElementPtr) {
162 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Chris Lattnerabab0712004-10-08 17:32:09 +0000163 // Theoretically we could SRA globals with GEP insts if all indexes are
164 // constants. In practice, these GEPs would already be constant exprs
165 // if that was the case though.
166 GS.isNotSuitableForSRA = true;
Chris Lattner25db5802004-10-07 04:16:33 +0000167 } else if (I->getOpcode() == Instruction::Select) {
168 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
169 GS.isNotSuitableForSRA = true;
170 } else if (PHINode *PN = dyn_cast<PHINode>(I)) {
171 // PHI nodes we can check just like select or GEP instructions, but we
172 // have to be careful about infinite recursion.
173 if (PHIUsers.insert(PN).second) // Not already visited.
174 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
175 GS.isNotSuitableForSRA = true;
176 } else if (isa<SetCondInst>(I)) {
177 GS.isNotSuitableForSRA = true;
178 } else {
179 return true; // Any other non-load instruction might take address!
180 }
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000181 } else if (Constant *C = dyn_cast<Constant>(*UI)) {
182 // We might have a dead and dangling constant hanging off of here.
183 if (!ConstantIsDead(C))
184 return true;
Chris Lattner25db5802004-10-07 04:16:33 +0000185 } else {
186 // Otherwise must be a global or some other user.
187 return true;
188 }
189
190 return false;
191}
192
Chris Lattnerabab0712004-10-08 17:32:09 +0000193static Constant *getAggregateConstantElement(Constant *Agg, Constant *Idx) {
194 ConstantInt *CI = dyn_cast<ConstantInt>(Idx);
195 if (!CI) return 0;
196 uint64_t IdxV = CI->getRawValue();
Chris Lattner25db5802004-10-07 04:16:33 +0000197
Chris Lattnerabab0712004-10-08 17:32:09 +0000198 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Agg)) {
199 if (IdxV < CS->getNumOperands()) return CS->getOperand(IdxV);
200 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Agg)) {
201 if (IdxV < CA->getNumOperands()) return CA->getOperand(IdxV);
202 } else if (ConstantPacked *CP = dyn_cast<ConstantPacked>(Agg)) {
203 if (IdxV < CP->getNumOperands()) return CP->getOperand(IdxV);
204 } else if (ConstantAggregateZero *CAZ =
205 dyn_cast<ConstantAggregateZero>(Agg)) {
206 if (const StructType *STy = dyn_cast<StructType>(Agg->getType())) {
207 if (IdxV < STy->getNumElements())
208 return Constant::getNullValue(STy->getElementType(IdxV));
209 } else if (const SequentialType *STy =
210 dyn_cast<SequentialType>(Agg->getType())) {
211 return Constant::getNullValue(STy->getElementType());
212 }
213 }
214 return 0;
215}
Chris Lattner25db5802004-10-07 04:16:33 +0000216
217static Constant *TraverseGEPInitializer(User *GEP, Constant *Init) {
218 if (GEP->getNumOperands() == 1 ||
219 !isa<Constant>(GEP->getOperand(1)) ||
220 !cast<Constant>(GEP->getOperand(1))->isNullValue())
221 return 0;
222
223 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i) {
224 ConstantInt *Idx = dyn_cast<ConstantInt>(GEP->getOperand(i));
225 if (!Idx) return 0;
Chris Lattnerabab0712004-10-08 17:32:09 +0000226 Init = getAggregateConstantElement(Init, Idx);
227 if (Init == 0) return 0;
Chris Lattner25db5802004-10-07 04:16:33 +0000228 }
229 return Init;
230}
231
232/// CleanupConstantGlobalUsers - We just marked GV constant. Loop over all
233/// users of the global, cleaning up the obvious ones. This is largely just a
234/// quick scan over the use list to clean up the easy and obvious cruft.
235static void CleanupConstantGlobalUsers(Value *V, Constant *Init) {
236 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;) {
237 User *U = *UI++;
238
239 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
240 // Replace the load with the initializer.
241 LI->replaceAllUsesWith(Init);
242 LI->getParent()->getInstList().erase(LI);
243 } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
244 // Store must be unreachable or storing Init into the global.
245 SI->getParent()->getInstList().erase(SI);
246 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
247 if (CE->getOpcode() == Instruction::GetElementPtr) {
248 if (Constant *SubInit = TraverseGEPInitializer(CE, Init))
249 CleanupConstantGlobalUsers(CE, SubInit);
250 if (CE->use_empty()) CE->destroyConstant();
251 }
252 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
253 if (Constant *SubInit = TraverseGEPInitializer(GEP, Init))
254 CleanupConstantGlobalUsers(GEP, SubInit);
255 if (GEP->use_empty())
256 GEP->getParent()->getInstList().erase(GEP);
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000257 } else if (Constant *C = dyn_cast<Constant>(U)) {
258 // If we have a chain of dead constantexprs or other things dangling from
259 // us, and if they are all dead, nuke them without remorse.
260 if (ConstantIsDead(C)) {
261 C->destroyConstant();
262 // This could have incalidated UI, start over from scratch.x
263 CleanupConstantGlobalUsers(V, Init);
264 return;
265 }
Chris Lattner25db5802004-10-07 04:16:33 +0000266 }
267 }
268}
269
Chris Lattnerabab0712004-10-08 17:32:09 +0000270/// SRAGlobal - Perform scalar replacement of aggregates on the specified global
271/// variable. This opens the door for other optimizations by exposing the
272/// behavior of the program in a more fine-grained way. We have determined that
273/// this transformation is safe already. We return the first global variable we
274/// insert so that the caller can reprocess it.
275static GlobalVariable *SRAGlobal(GlobalVariable *GV) {
276 assert(GV->hasInternalLinkage() && !GV->isConstant());
277 Constant *Init = GV->getInitializer();
278 const Type *Ty = Init->getType();
279
280 std::vector<GlobalVariable*> NewGlobals;
281 Module::GlobalListType &Globals = GV->getParent()->getGlobalList();
282
283 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
284 NewGlobals.reserve(STy->getNumElements());
285 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
286 Constant *In = getAggregateConstantElement(Init,
287 ConstantUInt::get(Type::UIntTy, i));
288 assert(In && "Couldn't get element of initializer?");
289 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(i), false,
290 GlobalVariable::InternalLinkage,
291 In, GV->getName()+"."+utostr(i));
292 Globals.insert(GV, NGV);
293 NewGlobals.push_back(NGV);
294 }
295 } else if (const SequentialType *STy = dyn_cast<SequentialType>(Ty)) {
296 unsigned NumElements = 0;
297 if (const ArrayType *ATy = dyn_cast<ArrayType>(STy))
298 NumElements = ATy->getNumElements();
299 else if (const PackedType *PTy = dyn_cast<PackedType>(STy))
300 NumElements = PTy->getNumElements();
301 else
302 assert(0 && "Unknown aggregate sequential type!");
303
304 if (NumElements > 16) return 0; // It's not worth it.
305 NewGlobals.reserve(NumElements);
306 for (unsigned i = 0, e = NumElements; i != e; ++i) {
307 Constant *In = getAggregateConstantElement(Init,
308 ConstantUInt::get(Type::UIntTy, i));
309 assert(In && "Couldn't get element of initializer?");
310
311 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(), false,
312 GlobalVariable::InternalLinkage,
313 In, GV->getName()+"."+utostr(i));
314 Globals.insert(GV, NGV);
315 NewGlobals.push_back(NGV);
316 }
317 }
318
319 if (NewGlobals.empty())
320 return 0;
321
322 Constant *NullInt = Constant::getNullValue(Type::IntTy);
323
324 // Loop over all of the uses of the global, replacing the constantexpr geps,
325 // with smaller constantexpr geps or direct references.
326 while (!GV->use_empty()) {
327 ConstantExpr *CE = cast<ConstantExpr>(GV->use_back());
328 assert(CE->getOpcode() == Instruction::GetElementPtr &&
329 "NonGEP CE's are not SRAable!");
330 // Ignore the 1th operand, which has to be zero or else the program is quite
331 // broken (undefined). Get the 2nd operand, which is the structure or array
332 // index.
333 unsigned Val = cast<ConstantInt>(CE->getOperand(2))->getRawValue();
334 if (Val >= NewGlobals.size()) Val = 0; // Out of bound array access.
335
336 Constant *NewPtr = NewGlobals[Val];
337
338 // Form a shorter GEP if needed.
339 if (CE->getNumOperands() > 3) {
340 std::vector<Constant*> Idxs;
341 Idxs.push_back(NullInt);
342 for (unsigned i = 3, e = CE->getNumOperands(); i != e; ++i)
343 Idxs.push_back(CE->getOperand(i));
344 NewPtr = ConstantExpr::getGetElementPtr(NewPtr, Idxs);
345 }
346 CE->replaceAllUsesWith(NewPtr);
347 CE->destroyConstant();
348 }
349
Chris Lattner73ad73e2004-10-08 20:25:55 +0000350 // Delete the old global, now that it is dead.
351 Globals.erase(GV);
Chris Lattnerabab0712004-10-08 17:32:09 +0000352 ++NumSRA;
353 return NewGlobals[0];
354}
355
Chris Lattner09a52722004-10-09 21:48:45 +0000356/// AllUsesOfValueWillTrapIfNull - Return true if all users of the specified
357/// value will trap if the value is dynamically null.
358static bool AllUsesOfValueWillTrapIfNull(Value *V) {
359 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
360 if (isa<LoadInst>(*UI)) {
361 // Will trap.
362 } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
363 if (SI->getOperand(0) == V) {
364 //std::cerr << "NONTRAPPING USE: " << **UI;
365 return false; // Storing the value.
366 }
367 } else if (CallInst *CI = dyn_cast<CallInst>(*UI)) {
368 if (CI->getOperand(0) != V) {
369 //std::cerr << "NONTRAPPING USE: " << **UI;
370 return false; // Not calling the ptr
371 }
372 } else if (InvokeInst *II = dyn_cast<InvokeInst>(*UI)) {
373 if (II->getOperand(0) != V) {
374 //std::cerr << "NONTRAPPING USE: " << **UI;
375 return false; // Not calling the ptr
376 }
377 } else if (CastInst *CI = dyn_cast<CastInst>(*UI)) {
378 if (!AllUsesOfValueWillTrapIfNull(CI)) return false;
379 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(*UI)) {
380 if (!AllUsesOfValueWillTrapIfNull(GEPI)) return false;
381 } else {
382 //std::cerr << "NONTRAPPING USE: " << **UI;
383 return false;
384 }
385 return true;
386}
387
388/// AllUsesOfLoadedValueWillTrapIfNull - Return true if all uses of any loads
389/// from GV will trap if the loaded value is null.
390static bool AllUsesOfLoadedValueWillTrapIfNull(GlobalVariable *GV) {
391 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI!=E; ++UI)
392 if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
393 if (!AllUsesOfValueWillTrapIfNull(LI))
394 return false;
395 } else if (isa<StoreInst>(*UI)) {
396 // Ignore stores to the global.
397 } else {
398 // We don't know or understand this user, bail out.
399 //std::cerr << "UNKNOWN USER OF GLOBAL!: " << **UI;
400 return false;
401 }
402
403 return true;
404}
405
406// OptimizeOnceStoredGlobal - Try to optimize globals based on the knowledge
407// that only one value (besides its initializer) is ever stored to the global.
408static bool OptimizeOnceStoredGlobal(GlobalVariable *GV, Value *StoredOnceVal) {
409 if (CastInst *CI = dyn_cast<CastInst>(StoredOnceVal))
410 StoredOnceVal = CI->getOperand(0);
411 else if (GetElementPtrInst *GEPI =dyn_cast<GetElementPtrInst>(StoredOnceVal)){
412 bool IsJustACast = true;
413 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
414 if (!isa<Constant>(GEPI->getOperand(i)) ||
415 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
416 IsJustACast = false;
417 break;
418 }
419 if (IsJustACast)
420 StoredOnceVal = GEPI->getOperand(0);
421 }
422
423 // If we are dealing with a pointer global that is initialized to null, only
424 // has one (non-null) value stored into, and if we know that all users of the
425 // loaded value trap if null, then the load users must never get the
426 // initializer. Instead, replace all of the loads with the stored value.
427 if (isa<PointerType>(GV->getInitializer()->getType()) &&
428 GV->getInitializer()->isNullValue()) {
429 if (isa<Constant>(StoredOnceVal) &&
430 AllUsesOfLoadedValueWillTrapIfNull(GV)) {
431 DEBUG(std::cerr << "REPLACING STORED GLOBAL POINTER: " << *GV);
432
433 //std::cerr << " Stored Value: " << *StoredOnceVal << "\n";
434
435 // Replace all uses of loads with uses of uses of the stored value.
436 while (!GV->use_empty())
437 if (LoadInst *LI = dyn_cast<LoadInst>(GV->use_back())) {
438 LI->replaceAllUsesWith(StoredOnceVal);
439 LI->getParent()->getInstList().erase(LI); // Nuke the load.
440 } else if (StoreInst *SI = dyn_cast<StoreInst>(GV->use_back())) {
441 SI->getParent()->getInstList().erase(SI); // Nuke the store
442 } else {
443 assert(0 && "Unknown user of stored once global!");
444 }
445
446 // Nuke the now-dead global.
447 GV->getParent()->getGlobalList().erase(GV);
448 return true;
449 }
450 //if (isa<MallocInst>(StoredOnceValue))
451 }
452 return false;
453}
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000454
455/// ProcessInternalGlobal - Analyze the specified global variable and optimize
456/// it if possible. If we make a change, return true.
457static bool ProcessInternalGlobal(GlobalVariable *GV, Module::giterator &GVI) {
458 std::set<PHINode*> PHIUsers;
459 GlobalStatus GS;
460 PHIUsers.clear();
461 GV->removeDeadConstantUsers();
462
463 if (GV->use_empty()) {
464 DEBUG(std::cerr << "GLOBAL DEAD: " << *GV);
Chris Lattner1b8d2952004-10-08 22:05:31 +0000465 GV->getParent()->getGlobalList().erase(GV);
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000466 ++NumDeleted;
467 return true;
468 }
469
470 if (!AnalyzeGlobal(GV, GS, PHIUsers)) {
471 // If the global is never loaded (but may be stored to), it is dead.
472 // Delete it now.
473 if (!GS.isLoaded) {
474 DEBUG(std::cerr << "GLOBAL NEVER LOADED: " << *GV);
Chris Lattnerf369b382004-10-09 03:32:52 +0000475 unsigned NumUsers = GV->use_size();
476
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000477 // Delete any stores we can find to the global. We may not be able to
478 // make it completely dead though.
479 CleanupConstantGlobalUsers(GV, GV->getInitializer());
480
Chris Lattnerf369b382004-10-09 03:32:52 +0000481 // Did we delete any stores?
482 bool Changed = NumUsers != GV->use_size();
483
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000484 // If the global is dead now, delete it.
485 if (GV->use_empty()) {
486 GV->getParent()->getGlobalList().erase(GV);
487 ++NumDeleted;
Chris Lattnerf369b382004-10-09 03:32:52 +0000488 Changed = true;
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000489 }
Chris Lattnerf369b382004-10-09 03:32:52 +0000490 return Changed;
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000491
492 } else if (GS.StoredType <= GlobalStatus::isInitializerStored) {
493 DEBUG(std::cerr << "MARKING CONSTANT: " << *GV);
494 GV->setConstant(true);
495
496 // Clean up any obviously simplifiable users now.
497 CleanupConstantGlobalUsers(GV, GV->getInitializer());
498
499 // If the global is dead now, just nuke it.
500 if (GV->use_empty()) {
501 DEBUG(std::cerr << " *** Marking constant allowed us to simplify "
502 "all users and delete global!\n");
503 GV->getParent()->getGlobalList().erase(GV);
504 ++NumDeleted;
505 }
506
507 ++NumMarked;
508 return true;
509 } else if (!GS.isNotSuitableForSRA &&
510 !GV->getInitializer()->getType()->isFirstClassType()) {
511 DEBUG(std::cerr << "PERFORMING GLOBAL SRA ON: " << *GV);
512 if (GlobalVariable *FirstNewGV = SRAGlobal(GV)) {
513 GVI = FirstNewGV; // Don't skip the newly produced globals!
514 return true;
515 }
Chris Lattner09a52722004-10-09 21:48:45 +0000516 } else if (GS.StoredType == GlobalStatus::isStoredOnce) {
517 // Try to optimize globals based on the knowledge that only one value
518 // (besides its initializer) is ever stored to the global.
519 if (OptimizeOnceStoredGlobal(GV, GS.StoredOnceValue))
520 return true;
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000521 }
522 }
523 return false;
524}
525
526
Chris Lattner25db5802004-10-07 04:16:33 +0000527bool GlobalOpt::runOnModule(Module &M) {
528 bool Changed = false;
529
530 // As a prepass, delete functions that are trivially dead.
531 bool LocalChange = true;
532 while (LocalChange) {
533 LocalChange = false;
534 for (Module::iterator FI = M.begin(), E = M.end(); FI != E; ) {
535 Function *F = FI++;
536 F->removeDeadConstantUsers();
537 if (F->use_empty() && (F->hasInternalLinkage() || F->hasWeakLinkage())) {
538 M.getFunctionList().erase(F);
539 LocalChange = true;
540 ++NumFnDeleted;
541 }
542 }
543 Changed |= LocalChange;
544 }
545
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000546 LocalChange = true;
547 while (LocalChange) {
548 LocalChange = false;
549 for (Module::giterator GVI = M.gbegin(), E = M.gend(); GVI != E;) {
550 GlobalVariable *GV = GVI++;
551 if (!GV->isConstant() && GV->hasInternalLinkage() &&
552 GV->hasInitializer())
553 LocalChange |= ProcessInternalGlobal(GV, GVI);
Chris Lattner25db5802004-10-07 04:16:33 +0000554 }
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000555 Changed |= LocalChange;
Chris Lattner25db5802004-10-07 04:16:33 +0000556 }
557 return Changed;
558}