blob: c74f604f682757558a6e7cfe5e9f0a19f2f3c682 [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"
Chris Lattner004e2502004-10-11 05:54:41 +000024#include "llvm/Target/TargetData.h"
25#include "llvm/Transforms/Utils/Local.h"
Chris Lattner25db5802004-10-07 04:16:33 +000026#include "llvm/ADT/Statistic.h"
Chris Lattnerabab0712004-10-08 17:32:09 +000027#include "llvm/ADT/StringExtras.h"
Chris Lattner25db5802004-10-07 04:16:33 +000028#include <set>
29#include <algorithm>
30using namespace llvm;
31
32namespace {
Chris Lattnerabab0712004-10-08 17:32:09 +000033 Statistic<> NumMarked ("globalopt", "Number of globals marked constant");
34 Statistic<> NumSRA ("globalopt", "Number of aggregate globals broken "
35 "into scalars");
Chris Lattner8e71c6a2004-10-16 18:09:00 +000036 Statistic<> NumSubstitute("globalopt",
37 "Number of globals with initializers stored into them");
Chris Lattnerabab0712004-10-08 17:32:09 +000038 Statistic<> NumDeleted ("globalopt", "Number of globals deleted");
Chris Lattner25db5802004-10-07 04:16:33 +000039 Statistic<> NumFnDeleted("globalopt", "Number of functions deleted");
Chris Lattnere42eb312004-10-10 23:14:11 +000040 Statistic<> NumGlobUses ("globalopt", "Number of global uses devirtualized");
Chris Lattner40e4cec2004-12-12 05:53:50 +000041 Statistic<> NumShrunkToBool("globalopt",
42 "Number of global vars shrunk to booleans");
Chris Lattner25db5802004-10-07 04:16:33 +000043
44 struct GlobalOpt : public ModulePass {
Chris Lattner004e2502004-10-11 05:54:41 +000045 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
46 AU.addRequired<TargetData>();
47 }
48
Chris Lattner25db5802004-10-07 04:16:33 +000049 bool runOnModule(Module &M);
Chris Lattner004e2502004-10-11 05:54:41 +000050
51 private:
52 bool ProcessInternalGlobal(GlobalVariable *GV, Module::giterator &GVI);
Chris Lattner25db5802004-10-07 04:16:33 +000053 };
54
55 RegisterOpt<GlobalOpt> X("globalopt", "Global Variable Optimizer");
56}
57
58ModulePass *llvm::createGlobalOptimizerPass() { return new GlobalOpt(); }
59
60/// GlobalStatus - As we analyze each global, keep track of some information
61/// about it. If we find out that the address of the global is taken, none of
Chris Lattner617f1a32004-10-07 21:30:30 +000062/// this info will be accurate.
Chris Lattner25db5802004-10-07 04:16:33 +000063struct GlobalStatus {
Chris Lattner617f1a32004-10-07 21:30:30 +000064 /// isLoaded - True if the global is ever loaded. If the global isn't ever
65 /// loaded it can be deleted.
Chris Lattner25db5802004-10-07 04:16:33 +000066 bool isLoaded;
Chris Lattner617f1a32004-10-07 21:30:30 +000067
68 /// StoredType - Keep track of what stores to the global look like.
69 ///
Chris Lattner25db5802004-10-07 04:16:33 +000070 enum StoredType {
Chris Lattner617f1a32004-10-07 21:30:30 +000071 /// NotStored - There is no store to this global. It can thus be marked
72 /// constant.
73 NotStored,
74
75 /// isInitializerStored - This global is stored to, but the only thing
76 /// stored is the constant it was initialized with. This is only tracked
77 /// for scalar globals.
78 isInitializerStored,
79
80 /// isStoredOnce - This global is stored to, but only its initializer and
81 /// one other value is ever stored to it. If this global isStoredOnce, we
82 /// track the value stored to it in StoredOnceValue below. This is only
83 /// tracked for scalar globals.
84 isStoredOnce,
85
86 /// isStored - This global is stored to by multiple values or something else
87 /// that we cannot track.
88 isStored
Chris Lattner25db5802004-10-07 04:16:33 +000089 } StoredType;
Chris Lattner617f1a32004-10-07 21:30:30 +000090
91 /// StoredOnceValue - If only one value (besides the initializer constant) is
92 /// ever stored to this global, keep track of what value it is.
93 Value *StoredOnceValue;
94
95 /// isNotSuitableForSRA - Keep track of whether any SRA preventing users of
96 /// the global exist. Such users include GEP instruction with variable
97 /// indexes, and non-gep/load/store users like constant expr casts.
Chris Lattner25db5802004-10-07 04:16:33 +000098 bool isNotSuitableForSRA;
99
Chris Lattner617f1a32004-10-07 21:30:30 +0000100 GlobalStatus() : isLoaded(false), StoredType(NotStored), StoredOnceValue(0),
Chris Lattner25db5802004-10-07 04:16:33 +0000101 isNotSuitableForSRA(false) {}
102};
103
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000104
105
106/// ConstantIsDead - Return true if the specified constant is (transitively)
107/// dead. The constant may be used by other constants (e.g. constant arrays and
108/// constant exprs) as long as they are dead, but it cannot be used by anything
109/// else.
110static bool ConstantIsDead(Constant *C) {
111 if (isa<GlobalValue>(C)) return false;
112
113 for (Value::use_iterator UI = C->use_begin(), E = C->use_end(); UI != E; ++UI)
114 if (Constant *CU = dyn_cast<Constant>(*UI)) {
115 if (!ConstantIsDead(CU)) return false;
116 } else
117 return false;
118 return true;
119}
120
121
Chris Lattner25db5802004-10-07 04:16:33 +0000122/// AnalyzeGlobal - Look at all uses of the global and fill in the GlobalStatus
123/// structure. If the global has its address taken, return true to indicate we
124/// can't do anything with it.
125///
126static bool AnalyzeGlobal(Value *V, GlobalStatus &GS,
127 std::set<PHINode*> &PHIUsers) {
128 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
129 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(*UI)) {
130 if (AnalyzeGlobal(CE, GS, PHIUsers)) return true;
131 if (CE->getOpcode() != Instruction::GetElementPtr)
132 GS.isNotSuitableForSRA = true;
Chris Lattnerabab0712004-10-08 17:32:09 +0000133 else if (!GS.isNotSuitableForSRA) {
134 // Check to see if this ConstantExpr GEP is SRA'able. In particular, we
135 // don't like < 3 operand CE's, and we don't like non-constant integer
136 // indices.
137 if (CE->getNumOperands() < 3 || !CE->getOperand(1)->isNullValue())
138 GS.isNotSuitableForSRA = true;
139 else {
140 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
141 if (!isa<ConstantInt>(CE->getOperand(i))) {
142 GS.isNotSuitableForSRA = true;
143 break;
144 }
145 }
146 }
147
Chris Lattner25db5802004-10-07 04:16:33 +0000148 } else if (Instruction *I = dyn_cast<Instruction>(*UI)) {
149 if (isa<LoadInst>(I)) {
150 GS.isLoaded = true;
151 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Chris Lattner02b6c912004-10-07 06:01:25 +0000152 // Don't allow a store OF the address, only stores TO the address.
153 if (SI->getOperand(0) == V) return true;
154
Chris Lattner617f1a32004-10-07 21:30:30 +0000155 // If this is a direct store to the global (i.e., the global is a scalar
156 // value, not an aggregate), keep more specific information about
157 // stores.
158 if (GS.StoredType != GlobalStatus::isStored)
159 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(SI->getOperand(1))){
Chris Lattner28eeb732004-11-14 20:50:30 +0000160 Value *StoredVal = SI->getOperand(0);
161 if (StoredVal == GV->getInitializer()) {
162 if (GS.StoredType < GlobalStatus::isInitializerStored)
163 GS.StoredType = GlobalStatus::isInitializerStored;
164 } else if (isa<LoadInst>(StoredVal) &&
165 cast<LoadInst>(StoredVal)->getOperand(0) == GV) {
166 // G = G
Chris Lattner617f1a32004-10-07 21:30:30 +0000167 if (GS.StoredType < GlobalStatus::isInitializerStored)
168 GS.StoredType = GlobalStatus::isInitializerStored;
169 } else if (GS.StoredType < GlobalStatus::isStoredOnce) {
170 GS.StoredType = GlobalStatus::isStoredOnce;
Chris Lattner28eeb732004-11-14 20:50:30 +0000171 GS.StoredOnceValue = StoredVal;
Chris Lattner617f1a32004-10-07 21:30:30 +0000172 } else if (GS.StoredType == GlobalStatus::isStoredOnce &&
Chris Lattner28eeb732004-11-14 20:50:30 +0000173 GS.StoredOnceValue == StoredVal) {
Chris Lattner617f1a32004-10-07 21:30:30 +0000174 // noop.
175 } else {
176 GS.StoredType = GlobalStatus::isStored;
177 }
178 } else {
Chris Lattner25db5802004-10-07 04:16:33 +0000179 GS.StoredType = GlobalStatus::isStored;
Chris Lattner617f1a32004-10-07 21:30:30 +0000180 }
Chris Lattner25db5802004-10-07 04:16:33 +0000181 } else if (I->getOpcode() == Instruction::GetElementPtr) {
182 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Chris Lattner004e2502004-10-11 05:54:41 +0000183
184 // If the first two indices are constants, this can be SRA'd.
185 if (isa<GlobalVariable>(I->getOperand(0))) {
186 if (I->getNumOperands() < 3 || !isa<Constant>(I->getOperand(1)) ||
187 !cast<Constant>(I->getOperand(1))->isNullValue() ||
188 !isa<ConstantInt>(I->getOperand(2)))
189 GS.isNotSuitableForSRA = true;
190 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(I->getOperand(0))){
191 if (CE->getOpcode() != Instruction::GetElementPtr ||
192 CE->getNumOperands() < 3 || I->getNumOperands() < 2 ||
193 !isa<Constant>(I->getOperand(0)) ||
194 !cast<Constant>(I->getOperand(0))->isNullValue())
195 GS.isNotSuitableForSRA = true;
196 } else {
197 GS.isNotSuitableForSRA = true;
198 }
Chris Lattner25db5802004-10-07 04:16:33 +0000199 } else if (I->getOpcode() == Instruction::Select) {
200 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
201 GS.isNotSuitableForSRA = true;
202 } else if (PHINode *PN = dyn_cast<PHINode>(I)) {
203 // PHI nodes we can check just like select or GEP instructions, but we
204 // have to be careful about infinite recursion.
205 if (PHIUsers.insert(PN).second) // Not already visited.
206 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
207 GS.isNotSuitableForSRA = true;
208 } else if (isa<SetCondInst>(I)) {
209 GS.isNotSuitableForSRA = true;
210 } else {
211 return true; // Any other non-load instruction might take address!
212 }
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000213 } else if (Constant *C = dyn_cast<Constant>(*UI)) {
214 // We might have a dead and dangling constant hanging off of here.
215 if (!ConstantIsDead(C))
216 return true;
Chris Lattner25db5802004-10-07 04:16:33 +0000217 } else {
218 // Otherwise must be a global or some other user.
219 return true;
220 }
221
222 return false;
223}
224
Chris Lattnerabab0712004-10-08 17:32:09 +0000225static Constant *getAggregateConstantElement(Constant *Agg, Constant *Idx) {
226 ConstantInt *CI = dyn_cast<ConstantInt>(Idx);
227 if (!CI) return 0;
228 uint64_t IdxV = CI->getRawValue();
Chris Lattner25db5802004-10-07 04:16:33 +0000229
Chris Lattnerabab0712004-10-08 17:32:09 +0000230 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Agg)) {
231 if (IdxV < CS->getNumOperands()) return CS->getOperand(IdxV);
232 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Agg)) {
233 if (IdxV < CA->getNumOperands()) return CA->getOperand(IdxV);
234 } else if (ConstantPacked *CP = dyn_cast<ConstantPacked>(Agg)) {
235 if (IdxV < CP->getNumOperands()) return CP->getOperand(IdxV);
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000236 } else if (isa<ConstantAggregateZero>(Agg)) {
Chris Lattnerabab0712004-10-08 17:32:09 +0000237 if (const StructType *STy = dyn_cast<StructType>(Agg->getType())) {
238 if (IdxV < STy->getNumElements())
239 return Constant::getNullValue(STy->getElementType(IdxV));
240 } else if (const SequentialType *STy =
241 dyn_cast<SequentialType>(Agg->getType())) {
242 return Constant::getNullValue(STy->getElementType());
243 }
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000244 } else if (isa<UndefValue>(Agg)) {
245 if (const StructType *STy = dyn_cast<StructType>(Agg->getType())) {
246 if (IdxV < STy->getNumElements())
247 return UndefValue::get(STy->getElementType(IdxV));
248 } else if (const SequentialType *STy =
249 dyn_cast<SequentialType>(Agg->getType())) {
250 return UndefValue::get(STy->getElementType());
251 }
Chris Lattnerabab0712004-10-08 17:32:09 +0000252 }
253 return 0;
254}
Chris Lattner25db5802004-10-07 04:16:33 +0000255
256static Constant *TraverseGEPInitializer(User *GEP, Constant *Init) {
257 if (GEP->getNumOperands() == 1 ||
258 !isa<Constant>(GEP->getOperand(1)) ||
259 !cast<Constant>(GEP->getOperand(1))->isNullValue())
260 return 0;
261
262 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i) {
263 ConstantInt *Idx = dyn_cast<ConstantInt>(GEP->getOperand(i));
264 if (!Idx) return 0;
Chris Lattnerabab0712004-10-08 17:32:09 +0000265 Init = getAggregateConstantElement(Init, Idx);
266 if (Init == 0) return 0;
Chris Lattner25db5802004-10-07 04:16:33 +0000267 }
268 return Init;
269}
270
271/// CleanupConstantGlobalUsers - We just marked GV constant. Loop over all
272/// users of the global, cleaning up the obvious ones. This is largely just a
Chris Lattnercb9f1522004-10-10 16:43:46 +0000273/// quick scan over the use list to clean up the easy and obvious cruft. This
274/// returns true if it made a change.
275static bool CleanupConstantGlobalUsers(Value *V, Constant *Init) {
276 bool Changed = false;
Chris Lattner25db5802004-10-07 04:16:33 +0000277 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;) {
278 User *U = *UI++;
279
280 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
281 // Replace the load with the initializer.
282 LI->replaceAllUsesWith(Init);
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000283 LI->eraseFromParent();
Chris Lattnercb9f1522004-10-10 16:43:46 +0000284 Changed = true;
Chris Lattner25db5802004-10-07 04:16:33 +0000285 } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
286 // Store must be unreachable or storing Init into the global.
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000287 SI->eraseFromParent();
Chris Lattnercb9f1522004-10-10 16:43:46 +0000288 Changed = true;
Chris Lattner25db5802004-10-07 04:16:33 +0000289 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
290 if (CE->getOpcode() == Instruction::GetElementPtr) {
291 if (Constant *SubInit = TraverseGEPInitializer(CE, Init))
Chris Lattnercb9f1522004-10-10 16:43:46 +0000292 Changed |= CleanupConstantGlobalUsers(CE, SubInit);
293 if (CE->use_empty()) {
294 CE->destroyConstant();
295 Changed = true;
296 }
Chris Lattner25db5802004-10-07 04:16:33 +0000297 }
298 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
299 if (Constant *SubInit = TraverseGEPInitializer(GEP, Init))
Chris Lattnercb9f1522004-10-10 16:43:46 +0000300 Changed |= CleanupConstantGlobalUsers(GEP, SubInit);
Chris Lattnera0e769c2004-10-10 16:47:33 +0000301 else {
302 // If this GEP has variable indexes, we should still be able to delete
303 // any stores through it.
304 for (Value::use_iterator GUI = GEP->use_begin(), E = GEP->use_end();
305 GUI != E;)
306 if (StoreInst *SI = dyn_cast<StoreInst>(*GUI++)) {
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000307 SI->eraseFromParent();
Chris Lattnera0e769c2004-10-10 16:47:33 +0000308 Changed = true;
309 }
310 }
311
Chris Lattnercb9f1522004-10-10 16:43:46 +0000312 if (GEP->use_empty()) {
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000313 GEP->eraseFromParent();
Chris Lattnercb9f1522004-10-10 16:43:46 +0000314 Changed = true;
315 }
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000316 } else if (Constant *C = dyn_cast<Constant>(U)) {
317 // If we have a chain of dead constantexprs or other things dangling from
318 // us, and if they are all dead, nuke them without remorse.
319 if (ConstantIsDead(C)) {
320 C->destroyConstant();
321 // This could have incalidated UI, start over from scratch.x
322 CleanupConstantGlobalUsers(V, Init);
Chris Lattnercb9f1522004-10-10 16:43:46 +0000323 return true;
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000324 }
Chris Lattner25db5802004-10-07 04:16:33 +0000325 }
326 }
Chris Lattnercb9f1522004-10-10 16:43:46 +0000327 return Changed;
Chris Lattner25db5802004-10-07 04:16:33 +0000328}
329
Chris Lattnerabab0712004-10-08 17:32:09 +0000330/// SRAGlobal - Perform scalar replacement of aggregates on the specified global
331/// variable. This opens the door for other optimizations by exposing the
332/// behavior of the program in a more fine-grained way. We have determined that
333/// this transformation is safe already. We return the first global variable we
334/// insert so that the caller can reprocess it.
335static GlobalVariable *SRAGlobal(GlobalVariable *GV) {
336 assert(GV->hasInternalLinkage() && !GV->isConstant());
337 Constant *Init = GV->getInitializer();
338 const Type *Ty = Init->getType();
339
340 std::vector<GlobalVariable*> NewGlobals;
341 Module::GlobalListType &Globals = GV->getParent()->getGlobalList();
342
343 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
344 NewGlobals.reserve(STy->getNumElements());
345 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
346 Constant *In = getAggregateConstantElement(Init,
347 ConstantUInt::get(Type::UIntTy, i));
348 assert(In && "Couldn't get element of initializer?");
349 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(i), false,
350 GlobalVariable::InternalLinkage,
351 In, GV->getName()+"."+utostr(i));
352 Globals.insert(GV, NGV);
353 NewGlobals.push_back(NGV);
354 }
355 } else if (const SequentialType *STy = dyn_cast<SequentialType>(Ty)) {
356 unsigned NumElements = 0;
357 if (const ArrayType *ATy = dyn_cast<ArrayType>(STy))
358 NumElements = ATy->getNumElements();
359 else if (const PackedType *PTy = dyn_cast<PackedType>(STy))
360 NumElements = PTy->getNumElements();
361 else
362 assert(0 && "Unknown aggregate sequential type!");
363
Chris Lattner004e2502004-10-11 05:54:41 +0000364 if (NumElements > 16 && GV->use_size() > 16) return 0; // It's not worth it.
Chris Lattnerabab0712004-10-08 17:32:09 +0000365 NewGlobals.reserve(NumElements);
366 for (unsigned i = 0, e = NumElements; i != e; ++i) {
367 Constant *In = getAggregateConstantElement(Init,
368 ConstantUInt::get(Type::UIntTy, i));
369 assert(In && "Couldn't get element of initializer?");
370
371 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(), false,
372 GlobalVariable::InternalLinkage,
373 In, GV->getName()+"."+utostr(i));
374 Globals.insert(GV, NGV);
375 NewGlobals.push_back(NGV);
376 }
377 }
378
379 if (NewGlobals.empty())
380 return 0;
381
Chris Lattner004e2502004-10-11 05:54:41 +0000382 DEBUG(std::cerr << "PERFORMING GLOBAL SRA ON: " << *GV);
383
Chris Lattnerabab0712004-10-08 17:32:09 +0000384 Constant *NullInt = Constant::getNullValue(Type::IntTy);
385
386 // Loop over all of the uses of the global, replacing the constantexpr geps,
387 // with smaller constantexpr geps or direct references.
388 while (!GV->use_empty()) {
Chris Lattner004e2502004-10-11 05:54:41 +0000389 User *GEP = GV->use_back();
390 assert(((isa<ConstantExpr>(GEP) &&
391 cast<ConstantExpr>(GEP)->getOpcode()==Instruction::GetElementPtr)||
392 isa<GetElementPtrInst>(GEP)) && "NonGEP CE's are not SRAable!");
393
Chris Lattnerabab0712004-10-08 17:32:09 +0000394 // Ignore the 1th operand, which has to be zero or else the program is quite
395 // broken (undefined). Get the 2nd operand, which is the structure or array
396 // index.
Chris Lattner004e2502004-10-11 05:54:41 +0000397 unsigned Val = cast<ConstantInt>(GEP->getOperand(2))->getRawValue();
Chris Lattnerabab0712004-10-08 17:32:09 +0000398 if (Val >= NewGlobals.size()) Val = 0; // Out of bound array access.
399
Chris Lattner004e2502004-10-11 05:54:41 +0000400 Value *NewPtr = NewGlobals[Val];
Chris Lattnerabab0712004-10-08 17:32:09 +0000401
402 // Form a shorter GEP if needed.
Chris Lattner004e2502004-10-11 05:54:41 +0000403 if (GEP->getNumOperands() > 3)
404 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEP)) {
405 std::vector<Constant*> Idxs;
406 Idxs.push_back(NullInt);
407 for (unsigned i = 3, e = CE->getNumOperands(); i != e; ++i)
408 Idxs.push_back(CE->getOperand(i));
409 NewPtr = ConstantExpr::getGetElementPtr(cast<Constant>(NewPtr), Idxs);
410 } else {
411 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(GEP);
412 std::vector<Value*> Idxs;
413 Idxs.push_back(NullInt);
414 for (unsigned i = 3, e = GEPI->getNumOperands(); i != e; ++i)
415 Idxs.push_back(GEPI->getOperand(i));
416 NewPtr = new GetElementPtrInst(NewPtr, Idxs,
417 GEPI->getName()+"."+utostr(Val), GEPI);
418 }
419 GEP->replaceAllUsesWith(NewPtr);
420
421 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(GEP))
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000422 GEPI->eraseFromParent();
Chris Lattner004e2502004-10-11 05:54:41 +0000423 else
424 cast<ConstantExpr>(GEP)->destroyConstant();
Chris Lattnerabab0712004-10-08 17:32:09 +0000425 }
426
Chris Lattner73ad73e2004-10-08 20:25:55 +0000427 // Delete the old global, now that it is dead.
428 Globals.erase(GV);
Chris Lattnerabab0712004-10-08 17:32:09 +0000429 ++NumSRA;
Chris Lattner004e2502004-10-11 05:54:41 +0000430
431 // Loop over the new globals array deleting any globals that are obviously
432 // dead. This can arise due to scalarization of a structure or an array that
433 // has elements that are dead.
434 unsigned FirstGlobal = 0;
435 for (unsigned i = 0, e = NewGlobals.size(); i != e; ++i)
436 if (NewGlobals[i]->use_empty()) {
437 Globals.erase(NewGlobals[i]);
438 if (FirstGlobal == i) ++FirstGlobal;
439 }
440
441 return FirstGlobal != NewGlobals.size() ? NewGlobals[FirstGlobal] : 0;
Chris Lattnerabab0712004-10-08 17:32:09 +0000442}
443
Chris Lattner09a52722004-10-09 21:48:45 +0000444/// AllUsesOfValueWillTrapIfNull - Return true if all users of the specified
445/// value will trap if the value is dynamically null.
446static bool AllUsesOfValueWillTrapIfNull(Value *V) {
447 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
448 if (isa<LoadInst>(*UI)) {
449 // Will trap.
450 } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
451 if (SI->getOperand(0) == V) {
452 //std::cerr << "NONTRAPPING USE: " << **UI;
453 return false; // Storing the value.
454 }
455 } else if (CallInst *CI = dyn_cast<CallInst>(*UI)) {
456 if (CI->getOperand(0) != V) {
457 //std::cerr << "NONTRAPPING USE: " << **UI;
458 return false; // Not calling the ptr
459 }
460 } else if (InvokeInst *II = dyn_cast<InvokeInst>(*UI)) {
461 if (II->getOperand(0) != V) {
462 //std::cerr << "NONTRAPPING USE: " << **UI;
463 return false; // Not calling the ptr
464 }
465 } else if (CastInst *CI = dyn_cast<CastInst>(*UI)) {
466 if (!AllUsesOfValueWillTrapIfNull(CI)) return false;
467 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(*UI)) {
468 if (!AllUsesOfValueWillTrapIfNull(GEPI)) return false;
Chris Lattnerfe9abf92004-10-22 06:43:28 +0000469 } else if (isa<SetCondInst>(*UI) &&
470 isa<ConstantPointerNull>(UI->getOperand(1))) {
471 // Ignore setcc X, null
Chris Lattner09a52722004-10-09 21:48:45 +0000472 } else {
473 //std::cerr << "NONTRAPPING USE: " << **UI;
474 return false;
475 }
476 return true;
477}
478
479/// AllUsesOfLoadedValueWillTrapIfNull - Return true if all uses of any loads
Chris Lattnerfe9abf92004-10-22 06:43:28 +0000480/// from GV will trap if the loaded value is null. Note that this also permits
481/// comparisons of the loaded value against null, as a special case.
Chris Lattner09a52722004-10-09 21:48:45 +0000482static bool AllUsesOfLoadedValueWillTrapIfNull(GlobalVariable *GV) {
483 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI!=E; ++UI)
484 if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
485 if (!AllUsesOfValueWillTrapIfNull(LI))
486 return false;
487 } else if (isa<StoreInst>(*UI)) {
488 // Ignore stores to the global.
489 } else {
490 // We don't know or understand this user, bail out.
491 //std::cerr << "UNKNOWN USER OF GLOBAL!: " << **UI;
492 return false;
493 }
494
495 return true;
496}
497
Chris Lattnere42eb312004-10-10 23:14:11 +0000498static bool OptimizeAwayTrappingUsesOfValue(Value *V, Constant *NewV) {
499 bool Changed = false;
500 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ) {
501 Instruction *I = cast<Instruction>(*UI++);
502 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
503 LI->setOperand(0, NewV);
504 Changed = true;
505 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
506 if (SI->getOperand(1) == V) {
507 SI->setOperand(1, NewV);
508 Changed = true;
509 }
510 } else if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
511 if (I->getOperand(0) == V) {
512 // Calling through the pointer! Turn into a direct call, but be careful
513 // that the pointer is not also being passed as an argument.
514 I->setOperand(0, NewV);
515 Changed = true;
516 bool PassedAsArg = false;
517 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i)
518 if (I->getOperand(i) == V) {
519 PassedAsArg = true;
520 I->setOperand(i, NewV);
521 }
522
523 if (PassedAsArg) {
524 // Being passed as an argument also. Be careful to not invalidate UI!
525 UI = V->use_begin();
526 }
527 }
528 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
529 Changed |= OptimizeAwayTrappingUsesOfValue(CI,
530 ConstantExpr::getCast(NewV, CI->getType()));
531 if (CI->use_empty()) {
532 Changed = true;
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000533 CI->eraseFromParent();
Chris Lattnere42eb312004-10-10 23:14:11 +0000534 }
535 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
536 // Should handle GEP here.
537 std::vector<Constant*> Indices;
538 Indices.reserve(GEPI->getNumOperands()-1);
539 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
540 if (Constant *C = dyn_cast<Constant>(GEPI->getOperand(i)))
541 Indices.push_back(C);
542 else
543 break;
544 if (Indices.size() == GEPI->getNumOperands()-1)
545 Changed |= OptimizeAwayTrappingUsesOfValue(GEPI,
546 ConstantExpr::getGetElementPtr(NewV, Indices));
547 if (GEPI->use_empty()) {
548 Changed = true;
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000549 GEPI->eraseFromParent();
Chris Lattnere42eb312004-10-10 23:14:11 +0000550 }
551 }
552 }
553
554 return Changed;
555}
556
557
558/// OptimizeAwayTrappingUsesOfLoads - The specified global has only one non-null
559/// value stored into it. If there are uses of the loaded value that would trap
560/// if the loaded value is dynamically null, then we know that they cannot be
561/// reachable with a null optimize away the load.
562static bool OptimizeAwayTrappingUsesOfLoads(GlobalVariable *GV, Constant *LV) {
563 std::vector<LoadInst*> Loads;
564 bool Changed = false;
565
566 // Replace all uses of loads with uses of uses of the stored value.
567 for (Value::use_iterator GUI = GV->use_begin(), E = GV->use_end();
568 GUI != E; ++GUI)
569 if (LoadInst *LI = dyn_cast<LoadInst>(*GUI)) {
570 Loads.push_back(LI);
571 Changed |= OptimizeAwayTrappingUsesOfValue(LI, LV);
572 } else {
573 assert(isa<StoreInst>(*GUI) && "Only expect load and stores!");
574 }
575
576 if (Changed) {
577 DEBUG(std::cerr << "OPTIMIZED LOADS FROM STORED ONCE POINTER: " << *GV);
578 ++NumGlobUses;
579 }
580
581 // Delete all of the loads we can, keeping track of whether we nuked them all!
582 bool AllLoadsGone = true;
583 while (!Loads.empty()) {
584 LoadInst *L = Loads.back();
585 if (L->use_empty()) {
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000586 L->eraseFromParent();
Chris Lattnere42eb312004-10-10 23:14:11 +0000587 Changed = true;
588 } else {
589 AllLoadsGone = false;
590 }
591 Loads.pop_back();
592 }
593
594 // If we nuked all of the loads, then none of the stores are needed either,
595 // nor is the global.
596 if (AllLoadsGone) {
597 DEBUG(std::cerr << " *** GLOBAL NOW DEAD!\n");
598 CleanupConstantGlobalUsers(GV, 0);
599 if (GV->use_empty()) {
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000600 GV->eraseFromParent();
Chris Lattnere42eb312004-10-10 23:14:11 +0000601 ++NumDeleted;
602 }
603 Changed = true;
604 }
605 return Changed;
606}
607
Chris Lattner004e2502004-10-11 05:54:41 +0000608/// ConstantPropUsersOf - Walk the use list of V, constant folding all of the
609/// instructions that are foldable.
610static void ConstantPropUsersOf(Value *V) {
611 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; )
612 if (Instruction *I = dyn_cast<Instruction>(*UI++))
613 if (Constant *NewC = ConstantFoldInstruction(I)) {
614 I->replaceAllUsesWith(NewC);
615
616 // Back up UI to avoid invalidating it!
617 bool AtBegin = false;
618 if (UI == V->use_begin())
619 AtBegin = true;
620 else
621 --UI;
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000622 I->eraseFromParent();
Chris Lattner004e2502004-10-11 05:54:41 +0000623 if (AtBegin)
624 UI = V->use_begin();
625 else
626 ++UI;
627 }
628}
629
630/// OptimizeGlobalAddressOfMalloc - This function takes the specified global
631/// variable, and transforms the program as if it always contained the result of
632/// the specified malloc. Because it is always the result of the specified
633/// malloc, there is no reason to actually DO the malloc. Instead, turn the
634/// malloc into a global, and any laods of GV as uses of the new global.
635static GlobalVariable *OptimizeGlobalAddressOfMalloc(GlobalVariable *GV,
636 MallocInst *MI) {
637 DEBUG(std::cerr << "PROMOTING MALLOC GLOBAL: " << *GV << " MALLOC = " <<*MI);
638 ConstantInt *NElements = cast<ConstantInt>(MI->getArraySize());
639
640 if (NElements->getRawValue() != 1) {
641 // If we have an array allocation, transform it to a single element
642 // allocation to make the code below simpler.
643 Type *NewTy = ArrayType::get(MI->getAllocatedType(),
644 NElements->getRawValue());
645 MallocInst *NewMI =
646 new MallocInst(NewTy, Constant::getNullValue(Type::UIntTy),
647 MI->getName(), MI);
648 std::vector<Value*> Indices;
649 Indices.push_back(Constant::getNullValue(Type::IntTy));
650 Indices.push_back(Indices[0]);
651 Value *NewGEP = new GetElementPtrInst(NewMI, Indices,
652 NewMI->getName()+".el0", MI);
653 MI->replaceAllUsesWith(NewGEP);
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000654 MI->eraseFromParent();
Chris Lattner004e2502004-10-11 05:54:41 +0000655 MI = NewMI;
656 }
657
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000658 // Create the new global variable. The contents of the malloc'd memory is
659 // undefined, so initialize with an undef value.
660 Constant *Init = UndefValue::get(MI->getAllocatedType());
Chris Lattner004e2502004-10-11 05:54:41 +0000661 GlobalVariable *NewGV = new GlobalVariable(MI->getAllocatedType(), false,
662 GlobalValue::InternalLinkage, Init,
663 GV->getName()+".body");
664 GV->getParent()->getGlobalList().insert(GV, NewGV);
665
666 // Anything that used the malloc now uses the global directly.
667 MI->replaceAllUsesWith(NewGV);
Chris Lattner004e2502004-10-11 05:54:41 +0000668
669 Constant *RepValue = NewGV;
670 if (NewGV->getType() != GV->getType()->getElementType())
671 RepValue = ConstantExpr::getCast(RepValue, GV->getType()->getElementType());
672
Chris Lattnerfe9abf92004-10-22 06:43:28 +0000673 // If there is a comparison against null, we will insert a global bool to
674 // keep track of whether the global was initialized yet or not.
Chris Lattner3b181392004-12-02 06:25:58 +0000675 GlobalVariable *InitBool =
676 new GlobalVariable(Type::BoolTy, false, GlobalValue::InternalLinkage,
677 ConstantBool::False, GV->getName()+".init");
678 bool InitBoolUsed = false;
Chris Lattnerfe9abf92004-10-22 06:43:28 +0000679
Chris Lattner004e2502004-10-11 05:54:41 +0000680 // Loop over all uses of GV, processing them in turn.
Chris Lattner3b181392004-12-02 06:25:58 +0000681 std::vector<StoreInst*> Stores;
Chris Lattner004e2502004-10-11 05:54:41 +0000682 while (!GV->use_empty())
683 if (LoadInst *LI = dyn_cast<LoadInst>(GV->use_back())) {
Chris Lattnerfe9abf92004-10-22 06:43:28 +0000684 while (!LI->use_empty()) {
685 // FIXME: the iterator should expose a getUse() method.
686 Use &LoadUse = *(const iplist<Use>::iterator&)LI->use_begin();
687 if (!isa<SetCondInst>(LoadUse.getUser()))
688 LoadUse = RepValue;
689 else {
Chris Lattnerfe9abf92004-10-22 06:43:28 +0000690 // Replace the setcc X, 0 with a use of the bool value.
691 SetCondInst *SCI = cast<SetCondInst>(LoadUse.getUser());
692 Value *LV = new LoadInst(InitBool, InitBool->getName()+".val", SCI);
Chris Lattner3b181392004-12-02 06:25:58 +0000693 InitBoolUsed = true;
Chris Lattnerfe9abf92004-10-22 06:43:28 +0000694 switch (SCI->getOpcode()) {
695 default: assert(0 && "Unknown opcode!");
696 case Instruction::SetLT:
697 LV = ConstantBool::False; // X < null -> always false
698 break;
699 case Instruction::SetEQ:
700 case Instruction::SetLE:
701 LV = BinaryOperator::createNot(LV, "notinit", SCI);
702 break;
703 case Instruction::SetNE:
704 case Instruction::SetGE:
705 case Instruction::SetGT:
706 break; // no change.
707 }
708 SCI->replaceAllUsesWith(LV);
709 SCI->eraseFromParent();
710 }
711 }
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000712 LI->eraseFromParent();
Chris Lattner004e2502004-10-11 05:54:41 +0000713 } else {
714 StoreInst *SI = cast<StoreInst>(GV->use_back());
Chris Lattner3b181392004-12-02 06:25:58 +0000715 // The global is initialized when the store to it occurs.
716 new StoreInst(ConstantBool::True, InitBool, SI);
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000717 SI->eraseFromParent();
Chris Lattner004e2502004-10-11 05:54:41 +0000718 }
719
Chris Lattner3b181392004-12-02 06:25:58 +0000720 // If the initialization boolean was used, insert it, otherwise delete it.
721 if (!InitBoolUsed) {
722 while (!InitBool->use_empty()) // Delete initializations
723 cast<Instruction>(InitBool->use_back())->eraseFromParent();
724 delete InitBool;
725 } else
726 GV->getParent()->getGlobalList().insert(GV, InitBool);
727
728
Chris Lattnerfe9abf92004-10-22 06:43:28 +0000729 // Now the GV is dead, nuke it and the malloc.
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000730 GV->eraseFromParent();
Chris Lattnerfe9abf92004-10-22 06:43:28 +0000731 MI->eraseFromParent();
Chris Lattner004e2502004-10-11 05:54:41 +0000732
733 // To further other optimizations, loop over all users of NewGV and try to
734 // constant prop them. This will promote GEP instructions with constant
735 // indices into GEP constant-exprs, which will allow global-opt to hack on it.
736 ConstantPropUsersOf(NewGV);
737 if (RepValue != NewGV)
738 ConstantPropUsersOf(RepValue);
739
740 return NewGV;
741}
Chris Lattnere42eb312004-10-10 23:14:11 +0000742
Chris Lattnerc0677c02004-12-02 07:11:07 +0000743/// ValueIsOnlyUsedLocallyOrStoredToOneGlobal - Scan the use-list of V checking
744/// to make sure that there are no complex uses of V. We permit simple things
745/// like dereferencing the pointer, but not storing through the address, unless
746/// it is to the specified global.
747static bool ValueIsOnlyUsedLocallyOrStoredToOneGlobal(Instruction *V,
748 GlobalVariable *GV) {
749 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;++UI)
750 if (isa<LoadInst>(*UI) || isa<SetCondInst>(*UI)) {
751 // Fine, ignore.
752 } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
753 if (SI->getOperand(0) == V && SI->getOperand(1) != GV)
754 return false; // Storing the pointer itself... bad.
755 // Otherwise, storing through it, or storing into GV... fine.
756 } else if (isa<GetElementPtrInst>(*UI) || isa<SelectInst>(*UI)) {
757 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(cast<Instruction>(*UI),GV))
758 return false;
759 } else {
760 return false;
761 }
762 return true;
763
764}
765
Chris Lattner09a52722004-10-09 21:48:45 +0000766// OptimizeOnceStoredGlobal - Try to optimize globals based on the knowledge
767// that only one value (besides its initializer) is ever stored to the global.
Chris Lattner004e2502004-10-11 05:54:41 +0000768static bool OptimizeOnceStoredGlobal(GlobalVariable *GV, Value *StoredOnceVal,
769 Module::giterator &GVI, TargetData &TD) {
Chris Lattner09a52722004-10-09 21:48:45 +0000770 if (CastInst *CI = dyn_cast<CastInst>(StoredOnceVal))
771 StoredOnceVal = CI->getOperand(0);
772 else if (GetElementPtrInst *GEPI =dyn_cast<GetElementPtrInst>(StoredOnceVal)){
Chris Lattnere42eb312004-10-10 23:14:11 +0000773 // "getelementptr Ptr, 0, 0, 0" is really just a cast.
Chris Lattner09a52722004-10-09 21:48:45 +0000774 bool IsJustACast = true;
775 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
776 if (!isa<Constant>(GEPI->getOperand(i)) ||
777 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
778 IsJustACast = false;
779 break;
780 }
781 if (IsJustACast)
782 StoredOnceVal = GEPI->getOperand(0);
783 }
784
Chris Lattnere42eb312004-10-10 23:14:11 +0000785 // If we are dealing with a pointer global that is initialized to null and
786 // only has one (non-null) value stored into it, then we can optimize any
787 // users of the loaded value (often calls and loads) that would trap if the
788 // value was null.
Chris Lattner09a52722004-10-09 21:48:45 +0000789 if (isa<PointerType>(GV->getInitializer()->getType()) &&
790 GV->getInitializer()->isNullValue()) {
Chris Lattnere42eb312004-10-10 23:14:11 +0000791 if (Constant *SOVC = dyn_cast<Constant>(StoredOnceVal)) {
792 if (GV->getInitializer()->getType() != SOVC->getType())
793 SOVC = ConstantExpr::getCast(SOVC, GV->getInitializer()->getType());
794
795 // Optimize away any trapping uses of the loaded value.
796 if (OptimizeAwayTrappingUsesOfLoads(GV, SOVC))
Chris Lattner604ed7a2004-10-10 17:07:12 +0000797 return true;
Chris Lattner004e2502004-10-11 05:54:41 +0000798 } else if (MallocInst *MI = dyn_cast<MallocInst>(StoredOnceVal)) {
799 // If we have a global that is only initialized with a fixed size malloc,
800 // and if all users of the malloc trap, and if the malloc'd address is not
801 // put anywhere else, transform the program to use global memory instead
802 // of malloc'd memory. This eliminates dynamic allocation (good) and
803 // exposes the resultant global to further GlobalOpt (even better). Note
804 // that we restrict this transformation to only working on small
805 // allocations (2048 bytes currently), as we don't want to introduce a 16M
806 // global or something.
807 if (ConstantInt *NElements = dyn_cast<ConstantInt>(MI->getArraySize()))
808 if (MI->getAllocatedType()->isSized() &&
809 NElements->getRawValue()*
810 TD.getTypeSize(MI->getAllocatedType()) < 2048 &&
Chris Lattnerc0677c02004-12-02 07:11:07 +0000811 AllUsesOfLoadedValueWillTrapIfNull(GV) &&
812 ValueIsOnlyUsedLocallyOrStoredToOneGlobal(MI, GV)) {
Chris Lattner004e2502004-10-11 05:54:41 +0000813 GVI = OptimizeGlobalAddressOfMalloc(GV, MI);
814 return true;
815 }
Chris Lattnere42eb312004-10-10 23:14:11 +0000816 }
Chris Lattner09a52722004-10-09 21:48:45 +0000817 }
Chris Lattner004e2502004-10-11 05:54:41 +0000818
Chris Lattner09a52722004-10-09 21:48:45 +0000819 return false;
820}
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000821
Chris Lattner40e4cec2004-12-12 05:53:50 +0000822/// ShrinkGlobalToBoolean - At this point, we have learned that the only two
823/// values ever stored into GV are its initializer and OtherVal.
824static void ShrinkGlobalToBoolean(GlobalVariable *GV, Constant *OtherVal) {
825 // Create the new global, initializing it to false.
826 GlobalVariable *NewGV = new GlobalVariable(Type::BoolTy, false,
827 GlobalValue::InternalLinkage, ConstantBool::False, GV->getName()+".b");
828 GV->getParent()->getGlobalList().insert(GV, NewGV);
829
830 Constant *InitVal = GV->getInitializer();
831 assert(InitVal->getType() != Type::BoolTy && "No reason to shrink to bool!");
832
833 // If initialized to zero and storing one into the global, we can use a cast
834 // instead of a select to synthesize the desired value.
835 bool IsOneZero = false;
836 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal))
837 IsOneZero = InitVal->isNullValue() && CI->equalsInt(1);
838
839 while (!GV->use_empty()) {
840 Instruction *UI = cast<Instruction>(GV->use_back());
841 if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
842 // Change the store into a boolean store.
843 bool StoringOther = SI->getOperand(0) == OtherVal;
844 // Only do this if we weren't storing a loaded value.
Chris Lattner745196a2004-12-12 19:34:41 +0000845 Value *StoreVal;
Chris Lattner40e4cec2004-12-12 05:53:50 +0000846 if (StoringOther || SI->getOperand(0) == InitVal)
Chris Lattner745196a2004-12-12 19:34:41 +0000847 StoreVal = ConstantBool::get(StoringOther);
848 else {
849 // Otherwise, we are storing a previously loaded copy. To do this,
850 // change the copy from copying the original value to just copying the
851 // bool.
852 Instruction *StoredVal = cast<Instruction>(SI->getOperand(0));
853
854 // If we're already replaced the input, StoredVal will be a cast or
855 // select instruction. If not, it will be a load of the original
856 // global.
857 if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
858 assert(LI->getOperand(0) == GV && "Not a copy!");
859 // Insert a new load, to preserve the saved value.
860 StoreVal = new LoadInst(NewGV, LI->getName()+".b", LI);
861 } else {
862 assert((isa<CastInst>(StoredVal) || isa<SelectInst>(StoredVal)) &&
863 "This is not a form that we understand!");
864 StoreVal = StoredVal->getOperand(0);
865 assert(isa<LoadInst>(StoreVal) && "Not a load of NewGV!");
866 }
867 }
868 new StoreInst(StoreVal, NewGV, SI);
869 } else if (!UI->use_empty()) {
Chris Lattner40e4cec2004-12-12 05:53:50 +0000870 // Change the load into a load of bool then a select.
871 LoadInst *LI = cast<LoadInst>(UI);
Chris Lattner745196a2004-12-12 19:34:41 +0000872
Chris Lattner40e4cec2004-12-12 05:53:50 +0000873 std::string Name = LI->getName(); LI->setName("");
874 LoadInst *NLI = new LoadInst(NewGV, Name+".b", LI);
875 Value *NSI;
876 if (IsOneZero)
877 NSI = new CastInst(NLI, LI->getType(), Name, LI);
878 else
879 NSI = new SelectInst(NLI, OtherVal, InitVal, Name, LI);
880 LI->replaceAllUsesWith(NSI);
881 }
882 UI->eraseFromParent();
883 }
884
885 GV->eraseFromParent();
886}
887
888
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000889/// ProcessInternalGlobal - Analyze the specified global variable and optimize
890/// it if possible. If we make a change, return true.
Chris Lattner004e2502004-10-11 05:54:41 +0000891bool GlobalOpt::ProcessInternalGlobal(GlobalVariable *GV,
892 Module::giterator &GVI) {
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000893 std::set<PHINode*> PHIUsers;
894 GlobalStatus GS;
895 PHIUsers.clear();
896 GV->removeDeadConstantUsers();
897
898 if (GV->use_empty()) {
899 DEBUG(std::cerr << "GLOBAL DEAD: " << *GV);
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000900 GV->eraseFromParent();
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000901 ++NumDeleted;
902 return true;
903 }
904
905 if (!AnalyzeGlobal(GV, GS, PHIUsers)) {
906 // If the global is never loaded (but may be stored to), it is dead.
907 // Delete it now.
908 if (!GS.isLoaded) {
909 DEBUG(std::cerr << "GLOBAL NEVER LOADED: " << *GV);
Chris Lattnerf369b382004-10-09 03:32:52 +0000910
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000911 // Delete any stores we can find to the global. We may not be able to
912 // make it completely dead though.
Chris Lattnercb9f1522004-10-10 16:43:46 +0000913 bool Changed = CleanupConstantGlobalUsers(GV, GV->getInitializer());
Chris Lattnerf369b382004-10-09 03:32:52 +0000914
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000915 // If the global is dead now, delete it.
916 if (GV->use_empty()) {
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000917 GV->eraseFromParent();
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000918 ++NumDeleted;
Chris Lattnerf369b382004-10-09 03:32:52 +0000919 Changed = true;
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000920 }
Chris Lattnerf369b382004-10-09 03:32:52 +0000921 return Changed;
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000922
923 } else if (GS.StoredType <= GlobalStatus::isInitializerStored) {
924 DEBUG(std::cerr << "MARKING CONSTANT: " << *GV);
925 GV->setConstant(true);
926
927 // Clean up any obviously simplifiable users now.
928 CleanupConstantGlobalUsers(GV, GV->getInitializer());
929
930 // If the global is dead now, just nuke it.
931 if (GV->use_empty()) {
932 DEBUG(std::cerr << " *** Marking constant allowed us to simplify "
933 "all users and delete global!\n");
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000934 GV->eraseFromParent();
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000935 ++NumDeleted;
936 }
937
938 ++NumMarked;
939 return true;
940 } else if (!GS.isNotSuitableForSRA &&
941 !GV->getInitializer()->getType()->isFirstClassType()) {
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000942 if (GlobalVariable *FirstNewGV = SRAGlobal(GV)) {
943 GVI = FirstNewGV; // Don't skip the newly produced globals!
944 return true;
945 }
Chris Lattner09a52722004-10-09 21:48:45 +0000946 } else if (GS.StoredType == GlobalStatus::isStoredOnce) {
Chris Lattner40e4cec2004-12-12 05:53:50 +0000947 // If the initial value for the global was an undef value, and if only
948 // one other value was stored into it, we can just change the
949 // initializer to be an undef value, then delete all stores to the
950 // global. This allows us to mark it constant.
951 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
952 if (isa<UndefValue>(GV->getInitializer())) {
953 // Change the initial value here.
954 GV->setInitializer(SOVConstant);
955
956 // Clean up any obviously simplifiable users now.
957 CleanupConstantGlobalUsers(GV, GV->getInitializer());
958
959 if (GV->use_empty()) {
960 DEBUG(std::cerr << " *** Substituting initializer allowed us to "
961 "simplify all users and delete global!\n");
962 GV->eraseFromParent();
963 ++NumDeleted;
964 } else {
965 GVI = GV;
966 }
967 ++NumSubstitute;
968 return true;
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000969 }
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000970
Chris Lattner09a52722004-10-09 21:48:45 +0000971 // Try to optimize globals based on the knowledge that only one value
972 // (besides its initializer) is ever stored to the global.
Chris Lattner004e2502004-10-11 05:54:41 +0000973 if (OptimizeOnceStoredGlobal(GV, GS.StoredOnceValue, GVI,
974 getAnalysis<TargetData>()))
Chris Lattner09a52722004-10-09 21:48:45 +0000975 return true;
Chris Lattner40e4cec2004-12-12 05:53:50 +0000976
977 // Otherwise, if the global was not a boolean, we can shrink it to be a
978 // boolean.
979 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
Chris Lattner1cbd5be2004-12-12 06:03:06 +0000980 if (GV->getType()->getElementType() != Type::BoolTy &&
981 !GV->getType()->getElementType()->isFloatingPoint()) {
Chris Lattner40e4cec2004-12-12 05:53:50 +0000982 DEBUG(std::cerr << " *** SHRINKING TO BOOL: " << *GV);
983 ShrinkGlobalToBoolean(GV, SOVConstant);
984 ++NumShrunkToBool;
985 return true;
986 }
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000987 }
988 }
989 return false;
990}
991
992
Chris Lattner25db5802004-10-07 04:16:33 +0000993bool GlobalOpt::runOnModule(Module &M) {
994 bool Changed = false;
995
996 // As a prepass, delete functions that are trivially dead.
997 bool LocalChange = true;
998 while (LocalChange) {
999 LocalChange = false;
1000 for (Module::iterator FI = M.begin(), E = M.end(); FI != E; ) {
1001 Function *F = FI++;
1002 F->removeDeadConstantUsers();
Chris Lattner5d33e8e2004-10-14 19:53:50 +00001003 if (F->use_empty() && (F->hasInternalLinkage() ||
1004 F->hasLinkOnceLinkage())) {
Chris Lattner25db5802004-10-07 04:16:33 +00001005 M.getFunctionList().erase(F);
1006 LocalChange = true;
1007 ++NumFnDeleted;
1008 }
1009 }
1010 Changed |= LocalChange;
1011 }
1012
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001013 LocalChange = true;
1014 while (LocalChange) {
1015 LocalChange = false;
1016 for (Module::giterator GVI = M.gbegin(), E = M.gend(); GVI != E;) {
1017 GlobalVariable *GV = GVI++;
1018 if (!GV->isConstant() && GV->hasInternalLinkage() &&
1019 GV->hasInitializer())
1020 LocalChange |= ProcessInternalGlobal(GV, GVI);
Chris Lattner25db5802004-10-07 04:16:33 +00001021 }
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001022 Changed |= LocalChange;
Chris Lattner25db5802004-10-07 04:16:33 +00001023 }
1024 return Changed;
1025}