blob: 2de2dae1db46c748f368b2aded315922b7e4fc3a [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 Lattner25db5802004-10-07 04:16:33 +000041
42 struct GlobalOpt : public ModulePass {
Chris Lattner004e2502004-10-11 05:54:41 +000043 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
44 AU.addRequired<TargetData>();
45 }
46
Chris Lattner25db5802004-10-07 04:16:33 +000047 bool runOnModule(Module &M);
Chris Lattner004e2502004-10-11 05:54:41 +000048
49 private:
50 bool ProcessInternalGlobal(GlobalVariable *GV, Module::giterator &GVI);
Chris Lattner25db5802004-10-07 04:16:33 +000051 };
52
53 RegisterOpt<GlobalOpt> X("globalopt", "Global Variable Optimizer");
54}
55
56ModulePass *llvm::createGlobalOptimizerPass() { return new GlobalOpt(); }
57
58/// GlobalStatus - As we analyze each global, keep track of some information
59/// about it. If we find out that the address of the global is taken, none of
Chris Lattner617f1a32004-10-07 21:30:30 +000060/// this info will be accurate.
Chris Lattner25db5802004-10-07 04:16:33 +000061struct GlobalStatus {
Chris Lattner617f1a32004-10-07 21:30:30 +000062 /// isLoaded - True if the global is ever loaded. If the global isn't ever
63 /// loaded it can be deleted.
Chris Lattner25db5802004-10-07 04:16:33 +000064 bool isLoaded;
Chris Lattner617f1a32004-10-07 21:30:30 +000065
66 /// StoredType - Keep track of what stores to the global look like.
67 ///
Chris Lattner25db5802004-10-07 04:16:33 +000068 enum StoredType {
Chris Lattner617f1a32004-10-07 21:30:30 +000069 /// NotStored - There is no store to this global. It can thus be marked
70 /// constant.
71 NotStored,
72
73 /// isInitializerStored - This global is stored to, but the only thing
74 /// stored is the constant it was initialized with. This is only tracked
75 /// for scalar globals.
76 isInitializerStored,
77
78 /// isStoredOnce - This global is stored to, but only its initializer and
79 /// one other value is ever stored to it. If this global isStoredOnce, we
80 /// track the value stored to it in StoredOnceValue below. This is only
81 /// tracked for scalar globals.
82 isStoredOnce,
83
84 /// isStored - This global is stored to by multiple values or something else
85 /// that we cannot track.
86 isStored
Chris Lattner25db5802004-10-07 04:16:33 +000087 } StoredType;
Chris Lattner617f1a32004-10-07 21:30:30 +000088
89 /// StoredOnceValue - If only one value (besides the initializer constant) is
90 /// ever stored to this global, keep track of what value it is.
91 Value *StoredOnceValue;
92
93 /// isNotSuitableForSRA - Keep track of whether any SRA preventing users of
94 /// the global exist. Such users include GEP instruction with variable
95 /// indexes, and non-gep/load/store users like constant expr casts.
Chris Lattner25db5802004-10-07 04:16:33 +000096 bool isNotSuitableForSRA;
97
Chris Lattner617f1a32004-10-07 21:30:30 +000098 GlobalStatus() : isLoaded(false), StoredType(NotStored), StoredOnceValue(0),
Chris Lattner25db5802004-10-07 04:16:33 +000099 isNotSuitableForSRA(false) {}
100};
101
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000102
103
104/// ConstantIsDead - Return true if the specified constant is (transitively)
105/// dead. The constant may be used by other constants (e.g. constant arrays and
106/// constant exprs) as long as they are dead, but it cannot be used by anything
107/// else.
108static bool ConstantIsDead(Constant *C) {
109 if (isa<GlobalValue>(C)) return false;
110
111 for (Value::use_iterator UI = C->use_begin(), E = C->use_end(); UI != E; ++UI)
112 if (Constant *CU = dyn_cast<Constant>(*UI)) {
113 if (!ConstantIsDead(CU)) return false;
114 } else
115 return false;
116 return true;
117}
118
119
Chris Lattner25db5802004-10-07 04:16:33 +0000120/// AnalyzeGlobal - Look at all uses of the global and fill in the GlobalStatus
121/// structure. If the global has its address taken, return true to indicate we
122/// can't do anything with it.
123///
124static bool AnalyzeGlobal(Value *V, GlobalStatus &GS,
125 std::set<PHINode*> &PHIUsers) {
126 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
127 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(*UI)) {
128 if (AnalyzeGlobal(CE, GS, PHIUsers)) return true;
129 if (CE->getOpcode() != Instruction::GetElementPtr)
130 GS.isNotSuitableForSRA = true;
Chris Lattnerabab0712004-10-08 17:32:09 +0000131 else if (!GS.isNotSuitableForSRA) {
132 // Check to see if this ConstantExpr GEP is SRA'able. In particular, we
133 // don't like < 3 operand CE's, and we don't like non-constant integer
134 // indices.
135 if (CE->getNumOperands() < 3 || !CE->getOperand(1)->isNullValue())
136 GS.isNotSuitableForSRA = true;
137 else {
138 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
139 if (!isa<ConstantInt>(CE->getOperand(i))) {
140 GS.isNotSuitableForSRA = true;
141 break;
142 }
143 }
144 }
145
Chris Lattner25db5802004-10-07 04:16:33 +0000146 } else if (Instruction *I = dyn_cast<Instruction>(*UI)) {
147 if (isa<LoadInst>(I)) {
148 GS.isLoaded = true;
149 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Chris Lattner02b6c912004-10-07 06:01:25 +0000150 // Don't allow a store OF the address, only stores TO the address.
151 if (SI->getOperand(0) == V) return true;
152
Chris Lattner617f1a32004-10-07 21:30:30 +0000153 // If this is a direct store to the global (i.e., the global is a scalar
154 // value, not an aggregate), keep more specific information about
155 // stores.
156 if (GS.StoredType != GlobalStatus::isStored)
157 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(SI->getOperand(1))){
158 if (SI->getOperand(0) == GV->getInitializer()) {
159 if (GS.StoredType < GlobalStatus::isInitializerStored)
160 GS.StoredType = GlobalStatus::isInitializerStored;
161 } else if (GS.StoredType < GlobalStatus::isStoredOnce) {
162 GS.StoredType = GlobalStatus::isStoredOnce;
163 GS.StoredOnceValue = SI->getOperand(0);
164 } else if (GS.StoredType == GlobalStatus::isStoredOnce &&
165 GS.StoredOnceValue == SI->getOperand(0)) {
166 // noop.
167 } else {
168 GS.StoredType = GlobalStatus::isStored;
169 }
170 } else {
Chris Lattner25db5802004-10-07 04:16:33 +0000171 GS.StoredType = GlobalStatus::isStored;
Chris Lattner617f1a32004-10-07 21:30:30 +0000172 }
Chris Lattner25db5802004-10-07 04:16:33 +0000173 } else if (I->getOpcode() == Instruction::GetElementPtr) {
174 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Chris Lattner004e2502004-10-11 05:54:41 +0000175
176 // If the first two indices are constants, this can be SRA'd.
177 if (isa<GlobalVariable>(I->getOperand(0))) {
178 if (I->getNumOperands() < 3 || !isa<Constant>(I->getOperand(1)) ||
179 !cast<Constant>(I->getOperand(1))->isNullValue() ||
180 !isa<ConstantInt>(I->getOperand(2)))
181 GS.isNotSuitableForSRA = true;
182 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(I->getOperand(0))){
183 if (CE->getOpcode() != Instruction::GetElementPtr ||
184 CE->getNumOperands() < 3 || I->getNumOperands() < 2 ||
185 !isa<Constant>(I->getOperand(0)) ||
186 !cast<Constant>(I->getOperand(0))->isNullValue())
187 GS.isNotSuitableForSRA = true;
188 } else {
189 GS.isNotSuitableForSRA = true;
190 }
Chris Lattner25db5802004-10-07 04:16:33 +0000191 } else if (I->getOpcode() == Instruction::Select) {
192 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
193 GS.isNotSuitableForSRA = true;
194 } else if (PHINode *PN = dyn_cast<PHINode>(I)) {
195 // PHI nodes we can check just like select or GEP instructions, but we
196 // have to be careful about infinite recursion.
197 if (PHIUsers.insert(PN).second) // Not already visited.
198 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
199 GS.isNotSuitableForSRA = true;
200 } else if (isa<SetCondInst>(I)) {
201 GS.isNotSuitableForSRA = true;
202 } else {
203 return true; // Any other non-load instruction might take address!
204 }
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000205 } else if (Constant *C = dyn_cast<Constant>(*UI)) {
206 // We might have a dead and dangling constant hanging off of here.
207 if (!ConstantIsDead(C))
208 return true;
Chris Lattner25db5802004-10-07 04:16:33 +0000209 } else {
210 // Otherwise must be a global or some other user.
211 return true;
212 }
213
214 return false;
215}
216
Chris Lattnerabab0712004-10-08 17:32:09 +0000217static Constant *getAggregateConstantElement(Constant *Agg, Constant *Idx) {
218 ConstantInt *CI = dyn_cast<ConstantInt>(Idx);
219 if (!CI) return 0;
220 uint64_t IdxV = CI->getRawValue();
Chris Lattner25db5802004-10-07 04:16:33 +0000221
Chris Lattnerabab0712004-10-08 17:32:09 +0000222 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Agg)) {
223 if (IdxV < CS->getNumOperands()) return CS->getOperand(IdxV);
224 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Agg)) {
225 if (IdxV < CA->getNumOperands()) return CA->getOperand(IdxV);
226 } else if (ConstantPacked *CP = dyn_cast<ConstantPacked>(Agg)) {
227 if (IdxV < CP->getNumOperands()) return CP->getOperand(IdxV);
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000228 } else if (isa<ConstantAggregateZero>(Agg)) {
Chris Lattnerabab0712004-10-08 17:32:09 +0000229 if (const StructType *STy = dyn_cast<StructType>(Agg->getType())) {
230 if (IdxV < STy->getNumElements())
231 return Constant::getNullValue(STy->getElementType(IdxV));
232 } else if (const SequentialType *STy =
233 dyn_cast<SequentialType>(Agg->getType())) {
234 return Constant::getNullValue(STy->getElementType());
235 }
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000236 } else if (isa<UndefValue>(Agg)) {
237 if (const StructType *STy = dyn_cast<StructType>(Agg->getType())) {
238 if (IdxV < STy->getNumElements())
239 return UndefValue::get(STy->getElementType(IdxV));
240 } else if (const SequentialType *STy =
241 dyn_cast<SequentialType>(Agg->getType())) {
242 return UndefValue::get(STy->getElementType());
243 }
Chris Lattnerabab0712004-10-08 17:32:09 +0000244 }
245 return 0;
246}
Chris Lattner25db5802004-10-07 04:16:33 +0000247
248static Constant *TraverseGEPInitializer(User *GEP, Constant *Init) {
249 if (GEP->getNumOperands() == 1 ||
250 !isa<Constant>(GEP->getOperand(1)) ||
251 !cast<Constant>(GEP->getOperand(1))->isNullValue())
252 return 0;
253
254 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i) {
255 ConstantInt *Idx = dyn_cast<ConstantInt>(GEP->getOperand(i));
256 if (!Idx) return 0;
Chris Lattnerabab0712004-10-08 17:32:09 +0000257 Init = getAggregateConstantElement(Init, Idx);
258 if (Init == 0) return 0;
Chris Lattner25db5802004-10-07 04:16:33 +0000259 }
260 return Init;
261}
262
263/// CleanupConstantGlobalUsers - We just marked GV constant. Loop over all
264/// users of the global, cleaning up the obvious ones. This is largely just a
Chris Lattnercb9f1522004-10-10 16:43:46 +0000265/// quick scan over the use list to clean up the easy and obvious cruft. This
266/// returns true if it made a change.
267static bool CleanupConstantGlobalUsers(Value *V, Constant *Init) {
268 bool Changed = false;
Chris Lattner25db5802004-10-07 04:16:33 +0000269 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;) {
270 User *U = *UI++;
271
272 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
273 // Replace the load with the initializer.
274 LI->replaceAllUsesWith(Init);
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000275 LI->eraseFromParent();
Chris Lattnercb9f1522004-10-10 16:43:46 +0000276 Changed = true;
Chris Lattner25db5802004-10-07 04:16:33 +0000277 } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
278 // Store must be unreachable or storing Init into the global.
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000279 SI->eraseFromParent();
Chris Lattnercb9f1522004-10-10 16:43:46 +0000280 Changed = true;
Chris Lattner25db5802004-10-07 04:16:33 +0000281 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
282 if (CE->getOpcode() == Instruction::GetElementPtr) {
283 if (Constant *SubInit = TraverseGEPInitializer(CE, Init))
Chris Lattnercb9f1522004-10-10 16:43:46 +0000284 Changed |= CleanupConstantGlobalUsers(CE, SubInit);
285 if (CE->use_empty()) {
286 CE->destroyConstant();
287 Changed = true;
288 }
Chris Lattner25db5802004-10-07 04:16:33 +0000289 }
290 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
291 if (Constant *SubInit = TraverseGEPInitializer(GEP, Init))
Chris Lattnercb9f1522004-10-10 16:43:46 +0000292 Changed |= CleanupConstantGlobalUsers(GEP, SubInit);
Chris Lattnera0e769c2004-10-10 16:47:33 +0000293 else {
294 // If this GEP has variable indexes, we should still be able to delete
295 // any stores through it.
296 for (Value::use_iterator GUI = GEP->use_begin(), E = GEP->use_end();
297 GUI != E;)
298 if (StoreInst *SI = dyn_cast<StoreInst>(*GUI++)) {
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000299 SI->eraseFromParent();
Chris Lattnera0e769c2004-10-10 16:47:33 +0000300 Changed = true;
301 }
302 }
303
Chris Lattnercb9f1522004-10-10 16:43:46 +0000304 if (GEP->use_empty()) {
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000305 GEP->eraseFromParent();
Chris Lattnercb9f1522004-10-10 16:43:46 +0000306 Changed = true;
307 }
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000308 } else if (Constant *C = dyn_cast<Constant>(U)) {
309 // If we have a chain of dead constantexprs or other things dangling from
310 // us, and if they are all dead, nuke them without remorse.
311 if (ConstantIsDead(C)) {
312 C->destroyConstant();
313 // This could have incalidated UI, start over from scratch.x
314 CleanupConstantGlobalUsers(V, Init);
Chris Lattnercb9f1522004-10-10 16:43:46 +0000315 return true;
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000316 }
Chris Lattner25db5802004-10-07 04:16:33 +0000317 }
318 }
Chris Lattnercb9f1522004-10-10 16:43:46 +0000319 return Changed;
Chris Lattner25db5802004-10-07 04:16:33 +0000320}
321
Chris Lattnerabab0712004-10-08 17:32:09 +0000322/// SRAGlobal - Perform scalar replacement of aggregates on the specified global
323/// variable. This opens the door for other optimizations by exposing the
324/// behavior of the program in a more fine-grained way. We have determined that
325/// this transformation is safe already. We return the first global variable we
326/// insert so that the caller can reprocess it.
327static GlobalVariable *SRAGlobal(GlobalVariable *GV) {
328 assert(GV->hasInternalLinkage() && !GV->isConstant());
329 Constant *Init = GV->getInitializer();
330 const Type *Ty = Init->getType();
331
332 std::vector<GlobalVariable*> NewGlobals;
333 Module::GlobalListType &Globals = GV->getParent()->getGlobalList();
334
335 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
336 NewGlobals.reserve(STy->getNumElements());
337 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
338 Constant *In = getAggregateConstantElement(Init,
339 ConstantUInt::get(Type::UIntTy, i));
340 assert(In && "Couldn't get element of initializer?");
341 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(i), false,
342 GlobalVariable::InternalLinkage,
343 In, GV->getName()+"."+utostr(i));
344 Globals.insert(GV, NGV);
345 NewGlobals.push_back(NGV);
346 }
347 } else if (const SequentialType *STy = dyn_cast<SequentialType>(Ty)) {
348 unsigned NumElements = 0;
349 if (const ArrayType *ATy = dyn_cast<ArrayType>(STy))
350 NumElements = ATy->getNumElements();
351 else if (const PackedType *PTy = dyn_cast<PackedType>(STy))
352 NumElements = PTy->getNumElements();
353 else
354 assert(0 && "Unknown aggregate sequential type!");
355
Chris Lattner004e2502004-10-11 05:54:41 +0000356 if (NumElements > 16 && GV->use_size() > 16) return 0; // It's not worth it.
Chris Lattnerabab0712004-10-08 17:32:09 +0000357 NewGlobals.reserve(NumElements);
358 for (unsigned i = 0, e = NumElements; i != e; ++i) {
359 Constant *In = getAggregateConstantElement(Init,
360 ConstantUInt::get(Type::UIntTy, i));
361 assert(In && "Couldn't get element of initializer?");
362
363 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(), false,
364 GlobalVariable::InternalLinkage,
365 In, GV->getName()+"."+utostr(i));
366 Globals.insert(GV, NGV);
367 NewGlobals.push_back(NGV);
368 }
369 }
370
371 if (NewGlobals.empty())
372 return 0;
373
Chris Lattner004e2502004-10-11 05:54:41 +0000374 DEBUG(std::cerr << "PERFORMING GLOBAL SRA ON: " << *GV);
375
Chris Lattnerabab0712004-10-08 17:32:09 +0000376 Constant *NullInt = Constant::getNullValue(Type::IntTy);
377
378 // Loop over all of the uses of the global, replacing the constantexpr geps,
379 // with smaller constantexpr geps or direct references.
380 while (!GV->use_empty()) {
Chris Lattner004e2502004-10-11 05:54:41 +0000381 User *GEP = GV->use_back();
382 assert(((isa<ConstantExpr>(GEP) &&
383 cast<ConstantExpr>(GEP)->getOpcode()==Instruction::GetElementPtr)||
384 isa<GetElementPtrInst>(GEP)) && "NonGEP CE's are not SRAable!");
385
Chris Lattnerabab0712004-10-08 17:32:09 +0000386 // Ignore the 1th operand, which has to be zero or else the program is quite
387 // broken (undefined). Get the 2nd operand, which is the structure or array
388 // index.
Chris Lattner004e2502004-10-11 05:54:41 +0000389 unsigned Val = cast<ConstantInt>(GEP->getOperand(2))->getRawValue();
Chris Lattnerabab0712004-10-08 17:32:09 +0000390 if (Val >= NewGlobals.size()) Val = 0; // Out of bound array access.
391
Chris Lattner004e2502004-10-11 05:54:41 +0000392 Value *NewPtr = NewGlobals[Val];
Chris Lattnerabab0712004-10-08 17:32:09 +0000393
394 // Form a shorter GEP if needed.
Chris Lattner004e2502004-10-11 05:54:41 +0000395 if (GEP->getNumOperands() > 3)
396 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEP)) {
397 std::vector<Constant*> Idxs;
398 Idxs.push_back(NullInt);
399 for (unsigned i = 3, e = CE->getNumOperands(); i != e; ++i)
400 Idxs.push_back(CE->getOperand(i));
401 NewPtr = ConstantExpr::getGetElementPtr(cast<Constant>(NewPtr), Idxs);
402 } else {
403 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(GEP);
404 std::vector<Value*> Idxs;
405 Idxs.push_back(NullInt);
406 for (unsigned i = 3, e = GEPI->getNumOperands(); i != e; ++i)
407 Idxs.push_back(GEPI->getOperand(i));
408 NewPtr = new GetElementPtrInst(NewPtr, Idxs,
409 GEPI->getName()+"."+utostr(Val), GEPI);
410 }
411 GEP->replaceAllUsesWith(NewPtr);
412
413 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(GEP))
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000414 GEPI->eraseFromParent();
Chris Lattner004e2502004-10-11 05:54:41 +0000415 else
416 cast<ConstantExpr>(GEP)->destroyConstant();
Chris Lattnerabab0712004-10-08 17:32:09 +0000417 }
418
Chris Lattner73ad73e2004-10-08 20:25:55 +0000419 // Delete the old global, now that it is dead.
420 Globals.erase(GV);
Chris Lattnerabab0712004-10-08 17:32:09 +0000421 ++NumSRA;
Chris Lattner004e2502004-10-11 05:54:41 +0000422
423 // Loop over the new globals array deleting any globals that are obviously
424 // dead. This can arise due to scalarization of a structure or an array that
425 // has elements that are dead.
426 unsigned FirstGlobal = 0;
427 for (unsigned i = 0, e = NewGlobals.size(); i != e; ++i)
428 if (NewGlobals[i]->use_empty()) {
429 Globals.erase(NewGlobals[i]);
430 if (FirstGlobal == i) ++FirstGlobal;
431 }
432
433 return FirstGlobal != NewGlobals.size() ? NewGlobals[FirstGlobal] : 0;
Chris Lattnerabab0712004-10-08 17:32:09 +0000434}
435
Chris Lattner09a52722004-10-09 21:48:45 +0000436/// AllUsesOfValueWillTrapIfNull - Return true if all users of the specified
437/// value will trap if the value is dynamically null.
438static bool AllUsesOfValueWillTrapIfNull(Value *V) {
439 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
440 if (isa<LoadInst>(*UI)) {
441 // Will trap.
442 } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
443 if (SI->getOperand(0) == V) {
444 //std::cerr << "NONTRAPPING USE: " << **UI;
445 return false; // Storing the value.
446 }
447 } else if (CallInst *CI = dyn_cast<CallInst>(*UI)) {
448 if (CI->getOperand(0) != V) {
449 //std::cerr << "NONTRAPPING USE: " << **UI;
450 return false; // Not calling the ptr
451 }
452 } else if (InvokeInst *II = dyn_cast<InvokeInst>(*UI)) {
453 if (II->getOperand(0) != V) {
454 //std::cerr << "NONTRAPPING USE: " << **UI;
455 return false; // Not calling the ptr
456 }
457 } else if (CastInst *CI = dyn_cast<CastInst>(*UI)) {
458 if (!AllUsesOfValueWillTrapIfNull(CI)) return false;
459 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(*UI)) {
460 if (!AllUsesOfValueWillTrapIfNull(GEPI)) return false;
461 } else {
462 //std::cerr << "NONTRAPPING USE: " << **UI;
463 return false;
464 }
465 return true;
466}
467
468/// AllUsesOfLoadedValueWillTrapIfNull - Return true if all uses of any loads
469/// from GV will trap if the loaded value is null.
470static bool AllUsesOfLoadedValueWillTrapIfNull(GlobalVariable *GV) {
471 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI!=E; ++UI)
472 if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
473 if (!AllUsesOfValueWillTrapIfNull(LI))
474 return false;
475 } else if (isa<StoreInst>(*UI)) {
476 // Ignore stores to the global.
477 } else {
478 // We don't know or understand this user, bail out.
479 //std::cerr << "UNKNOWN USER OF GLOBAL!: " << **UI;
480 return false;
481 }
482
483 return true;
484}
485
Chris Lattnere42eb312004-10-10 23:14:11 +0000486static bool OptimizeAwayTrappingUsesOfValue(Value *V, Constant *NewV) {
487 bool Changed = false;
488 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ) {
489 Instruction *I = cast<Instruction>(*UI++);
490 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
491 LI->setOperand(0, NewV);
492 Changed = true;
493 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
494 if (SI->getOperand(1) == V) {
495 SI->setOperand(1, NewV);
496 Changed = true;
497 }
498 } else if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
499 if (I->getOperand(0) == V) {
500 // Calling through the pointer! Turn into a direct call, but be careful
501 // that the pointer is not also being passed as an argument.
502 I->setOperand(0, NewV);
503 Changed = true;
504 bool PassedAsArg = false;
505 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i)
506 if (I->getOperand(i) == V) {
507 PassedAsArg = true;
508 I->setOperand(i, NewV);
509 }
510
511 if (PassedAsArg) {
512 // Being passed as an argument also. Be careful to not invalidate UI!
513 UI = V->use_begin();
514 }
515 }
516 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
517 Changed |= OptimizeAwayTrappingUsesOfValue(CI,
518 ConstantExpr::getCast(NewV, CI->getType()));
519 if (CI->use_empty()) {
520 Changed = true;
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000521 CI->eraseFromParent();
Chris Lattnere42eb312004-10-10 23:14:11 +0000522 }
523 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
524 // Should handle GEP here.
525 std::vector<Constant*> Indices;
526 Indices.reserve(GEPI->getNumOperands()-1);
527 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
528 if (Constant *C = dyn_cast<Constant>(GEPI->getOperand(i)))
529 Indices.push_back(C);
530 else
531 break;
532 if (Indices.size() == GEPI->getNumOperands()-1)
533 Changed |= OptimizeAwayTrappingUsesOfValue(GEPI,
534 ConstantExpr::getGetElementPtr(NewV, Indices));
535 if (GEPI->use_empty()) {
536 Changed = true;
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000537 GEPI->eraseFromParent();
Chris Lattnere42eb312004-10-10 23:14:11 +0000538 }
539 }
540 }
541
542 return Changed;
543}
544
545
546/// OptimizeAwayTrappingUsesOfLoads - The specified global has only one non-null
547/// value stored into it. If there are uses of the loaded value that would trap
548/// if the loaded value is dynamically null, then we know that they cannot be
549/// reachable with a null optimize away the load.
550static bool OptimizeAwayTrappingUsesOfLoads(GlobalVariable *GV, Constant *LV) {
551 std::vector<LoadInst*> Loads;
552 bool Changed = false;
553
554 // Replace all uses of loads with uses of uses of the stored value.
555 for (Value::use_iterator GUI = GV->use_begin(), E = GV->use_end();
556 GUI != E; ++GUI)
557 if (LoadInst *LI = dyn_cast<LoadInst>(*GUI)) {
558 Loads.push_back(LI);
559 Changed |= OptimizeAwayTrappingUsesOfValue(LI, LV);
560 } else {
561 assert(isa<StoreInst>(*GUI) && "Only expect load and stores!");
562 }
563
564 if (Changed) {
565 DEBUG(std::cerr << "OPTIMIZED LOADS FROM STORED ONCE POINTER: " << *GV);
566 ++NumGlobUses;
567 }
568
569 // Delete all of the loads we can, keeping track of whether we nuked them all!
570 bool AllLoadsGone = true;
571 while (!Loads.empty()) {
572 LoadInst *L = Loads.back();
573 if (L->use_empty()) {
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000574 L->eraseFromParent();
Chris Lattnere42eb312004-10-10 23:14:11 +0000575 Changed = true;
576 } else {
577 AllLoadsGone = false;
578 }
579 Loads.pop_back();
580 }
581
582 // If we nuked all of the loads, then none of the stores are needed either,
583 // nor is the global.
584 if (AllLoadsGone) {
585 DEBUG(std::cerr << " *** GLOBAL NOW DEAD!\n");
586 CleanupConstantGlobalUsers(GV, 0);
587 if (GV->use_empty()) {
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000588 GV->eraseFromParent();
Chris Lattnere42eb312004-10-10 23:14:11 +0000589 ++NumDeleted;
590 }
591 Changed = true;
592 }
593 return Changed;
594}
595
Chris Lattner004e2502004-10-11 05:54:41 +0000596/// ConstantPropUsersOf - Walk the use list of V, constant folding all of the
597/// instructions that are foldable.
598static void ConstantPropUsersOf(Value *V) {
599 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; )
600 if (Instruction *I = dyn_cast<Instruction>(*UI++))
601 if (Constant *NewC = ConstantFoldInstruction(I)) {
602 I->replaceAllUsesWith(NewC);
603
604 // Back up UI to avoid invalidating it!
605 bool AtBegin = false;
606 if (UI == V->use_begin())
607 AtBegin = true;
608 else
609 --UI;
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000610 I->eraseFromParent();
Chris Lattner004e2502004-10-11 05:54:41 +0000611 if (AtBegin)
612 UI = V->use_begin();
613 else
614 ++UI;
615 }
616}
617
618/// OptimizeGlobalAddressOfMalloc - This function takes the specified global
619/// variable, and transforms the program as if it always contained the result of
620/// the specified malloc. Because it is always the result of the specified
621/// malloc, there is no reason to actually DO the malloc. Instead, turn the
622/// malloc into a global, and any laods of GV as uses of the new global.
623static GlobalVariable *OptimizeGlobalAddressOfMalloc(GlobalVariable *GV,
624 MallocInst *MI) {
625 DEBUG(std::cerr << "PROMOTING MALLOC GLOBAL: " << *GV << " MALLOC = " <<*MI);
626 ConstantInt *NElements = cast<ConstantInt>(MI->getArraySize());
627
628 if (NElements->getRawValue() != 1) {
629 // If we have an array allocation, transform it to a single element
630 // allocation to make the code below simpler.
631 Type *NewTy = ArrayType::get(MI->getAllocatedType(),
632 NElements->getRawValue());
633 MallocInst *NewMI =
634 new MallocInst(NewTy, Constant::getNullValue(Type::UIntTy),
635 MI->getName(), MI);
636 std::vector<Value*> Indices;
637 Indices.push_back(Constant::getNullValue(Type::IntTy));
638 Indices.push_back(Indices[0]);
639 Value *NewGEP = new GetElementPtrInst(NewMI, Indices,
640 NewMI->getName()+".el0", MI);
641 MI->replaceAllUsesWith(NewGEP);
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000642 MI->eraseFromParent();
Chris Lattner004e2502004-10-11 05:54:41 +0000643 MI = NewMI;
644 }
645
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000646 // Create the new global variable. The contents of the malloc'd memory is
647 // undefined, so initialize with an undef value.
648 Constant *Init = UndefValue::get(MI->getAllocatedType());
Chris Lattner004e2502004-10-11 05:54:41 +0000649 GlobalVariable *NewGV = new GlobalVariable(MI->getAllocatedType(), false,
650 GlobalValue::InternalLinkage, Init,
651 GV->getName()+".body");
652 GV->getParent()->getGlobalList().insert(GV, NewGV);
653
654 // Anything that used the malloc now uses the global directly.
655 MI->replaceAllUsesWith(NewGV);
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000656 MI->eraseFromParent();
Chris Lattner004e2502004-10-11 05:54:41 +0000657
658 Constant *RepValue = NewGV;
659 if (NewGV->getType() != GV->getType()->getElementType())
660 RepValue = ConstantExpr::getCast(RepValue, GV->getType()->getElementType());
661
662 // Loop over all uses of GV, processing them in turn.
663 while (!GV->use_empty())
664 if (LoadInst *LI = dyn_cast<LoadInst>(GV->use_back())) {
665 LI->replaceAllUsesWith(RepValue);
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000666 LI->eraseFromParent();
Chris Lattner004e2502004-10-11 05:54:41 +0000667 } else {
668 StoreInst *SI = cast<StoreInst>(GV->use_back());
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000669 SI->eraseFromParent();
Chris Lattner004e2502004-10-11 05:54:41 +0000670 }
671
672 // Now the GV is dead, nuke it.
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000673 GV->eraseFromParent();
Chris Lattner004e2502004-10-11 05:54:41 +0000674
675 // To further other optimizations, loop over all users of NewGV and try to
676 // constant prop them. This will promote GEP instructions with constant
677 // indices into GEP constant-exprs, which will allow global-opt to hack on it.
678 ConstantPropUsersOf(NewGV);
679 if (RepValue != NewGV)
680 ConstantPropUsersOf(RepValue);
681
682 return NewGV;
683}
Chris Lattnere42eb312004-10-10 23:14:11 +0000684
Chris Lattner09a52722004-10-09 21:48:45 +0000685// OptimizeOnceStoredGlobal - Try to optimize globals based on the knowledge
686// that only one value (besides its initializer) is ever stored to the global.
Chris Lattner004e2502004-10-11 05:54:41 +0000687static bool OptimizeOnceStoredGlobal(GlobalVariable *GV, Value *StoredOnceVal,
688 Module::giterator &GVI, TargetData &TD) {
Chris Lattner09a52722004-10-09 21:48:45 +0000689 if (CastInst *CI = dyn_cast<CastInst>(StoredOnceVal))
690 StoredOnceVal = CI->getOperand(0);
691 else if (GetElementPtrInst *GEPI =dyn_cast<GetElementPtrInst>(StoredOnceVal)){
Chris Lattnere42eb312004-10-10 23:14:11 +0000692 // "getelementptr Ptr, 0, 0, 0" is really just a cast.
Chris Lattner09a52722004-10-09 21:48:45 +0000693 bool IsJustACast = true;
694 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
695 if (!isa<Constant>(GEPI->getOperand(i)) ||
696 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
697 IsJustACast = false;
698 break;
699 }
700 if (IsJustACast)
701 StoredOnceVal = GEPI->getOperand(0);
702 }
703
Chris Lattnere42eb312004-10-10 23:14:11 +0000704 // If we are dealing with a pointer global that is initialized to null and
705 // only has one (non-null) value stored into it, then we can optimize any
706 // users of the loaded value (often calls and loads) that would trap if the
707 // value was null.
Chris Lattner09a52722004-10-09 21:48:45 +0000708 if (isa<PointerType>(GV->getInitializer()->getType()) &&
709 GV->getInitializer()->isNullValue()) {
Chris Lattnere42eb312004-10-10 23:14:11 +0000710 if (Constant *SOVC = dyn_cast<Constant>(StoredOnceVal)) {
711 if (GV->getInitializer()->getType() != SOVC->getType())
712 SOVC = ConstantExpr::getCast(SOVC, GV->getInitializer()->getType());
713
714 // Optimize away any trapping uses of the loaded value.
715 if (OptimizeAwayTrappingUsesOfLoads(GV, SOVC))
Chris Lattner604ed7a2004-10-10 17:07:12 +0000716 return true;
Chris Lattner004e2502004-10-11 05:54:41 +0000717 } else if (MallocInst *MI = dyn_cast<MallocInst>(StoredOnceVal)) {
718 // If we have a global that is only initialized with a fixed size malloc,
719 // and if all users of the malloc trap, and if the malloc'd address is not
720 // put anywhere else, transform the program to use global memory instead
721 // of malloc'd memory. This eliminates dynamic allocation (good) and
722 // exposes the resultant global to further GlobalOpt (even better). Note
723 // that we restrict this transformation to only working on small
724 // allocations (2048 bytes currently), as we don't want to introduce a 16M
725 // global or something.
726 if (ConstantInt *NElements = dyn_cast<ConstantInt>(MI->getArraySize()))
727 if (MI->getAllocatedType()->isSized() &&
728 NElements->getRawValue()*
729 TD.getTypeSize(MI->getAllocatedType()) < 2048 &&
730 AllUsesOfLoadedValueWillTrapIfNull(GV)) {
731 // FIXME: do more correctness checking to make sure the result of the
732 // malloc isn't squirrelled away somewhere.
733 GVI = OptimizeGlobalAddressOfMalloc(GV, MI);
734 return true;
735 }
Chris Lattnere42eb312004-10-10 23:14:11 +0000736 }
Chris Lattner09a52722004-10-09 21:48:45 +0000737 }
Chris Lattner004e2502004-10-11 05:54:41 +0000738
Chris Lattner09a52722004-10-09 21:48:45 +0000739 return false;
740}
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000741
742/// ProcessInternalGlobal - Analyze the specified global variable and optimize
743/// it if possible. If we make a change, return true.
Chris Lattner004e2502004-10-11 05:54:41 +0000744bool GlobalOpt::ProcessInternalGlobal(GlobalVariable *GV,
745 Module::giterator &GVI) {
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000746 std::set<PHINode*> PHIUsers;
747 GlobalStatus GS;
748 PHIUsers.clear();
749 GV->removeDeadConstantUsers();
750
751 if (GV->use_empty()) {
752 DEBUG(std::cerr << "GLOBAL DEAD: " << *GV);
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000753 GV->eraseFromParent();
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000754 ++NumDeleted;
755 return true;
756 }
757
758 if (!AnalyzeGlobal(GV, GS, PHIUsers)) {
759 // If the global is never loaded (but may be stored to), it is dead.
760 // Delete it now.
761 if (!GS.isLoaded) {
762 DEBUG(std::cerr << "GLOBAL NEVER LOADED: " << *GV);
Chris Lattnerf369b382004-10-09 03:32:52 +0000763
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000764 // Delete any stores we can find to the global. We may not be able to
765 // make it completely dead though.
Chris Lattnercb9f1522004-10-10 16:43:46 +0000766 bool Changed = CleanupConstantGlobalUsers(GV, GV->getInitializer());
Chris Lattnerf369b382004-10-09 03:32:52 +0000767
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000768 // If the global is dead now, delete it.
769 if (GV->use_empty()) {
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000770 GV->eraseFromParent();
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000771 ++NumDeleted;
Chris Lattnerf369b382004-10-09 03:32:52 +0000772 Changed = true;
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000773 }
Chris Lattnerf369b382004-10-09 03:32:52 +0000774 return Changed;
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000775
776 } else if (GS.StoredType <= GlobalStatus::isInitializerStored) {
777 DEBUG(std::cerr << "MARKING CONSTANT: " << *GV);
778 GV->setConstant(true);
779
780 // Clean up any obviously simplifiable users now.
781 CleanupConstantGlobalUsers(GV, GV->getInitializer());
782
783 // If the global is dead now, just nuke it.
784 if (GV->use_empty()) {
785 DEBUG(std::cerr << " *** Marking constant allowed us to simplify "
786 "all users and delete global!\n");
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000787 GV->eraseFromParent();
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000788 ++NumDeleted;
789 }
790
791 ++NumMarked;
792 return true;
793 } else if (!GS.isNotSuitableForSRA &&
794 !GV->getInitializer()->getType()->isFirstClassType()) {
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000795 if (GlobalVariable *FirstNewGV = SRAGlobal(GV)) {
796 GVI = FirstNewGV; // Don't skip the newly produced globals!
797 return true;
798 }
Chris Lattner09a52722004-10-09 21:48:45 +0000799 } else if (GS.StoredType == GlobalStatus::isStoredOnce) {
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000800 // If the initial value for the global was an undef value, and if only one
801 // other value was stored into it, we can just change the initializer to
802 // be an undef value, then delete all stores to the global. This allows
803 // us to mark it constant.
804 if (isa<UndefValue>(GV->getInitializer()) &&
805 isa<Constant>(GS.StoredOnceValue)) {
806 // Change the initial value here.
807 GV->setInitializer(cast<Constant>(GS.StoredOnceValue));
808
809 // Clean up any obviously simplifiable users now.
810 CleanupConstantGlobalUsers(GV, GV->getInitializer());
811
812 if (GV->use_empty()) {
813 DEBUG(std::cerr << " *** Substituting initializer allowed us to "
814 "simplify all users and delete global!\n");
815 GV->eraseFromParent();
816 ++NumDeleted;
817 } else {
818 GVI = GV;
819 }
820 ++NumSubstitute;
821 return true;
822 }
823
Chris Lattner09a52722004-10-09 21:48:45 +0000824 // Try to optimize globals based on the knowledge that only one value
825 // (besides its initializer) is ever stored to the global.
Chris Lattner004e2502004-10-11 05:54:41 +0000826 if (OptimizeOnceStoredGlobal(GV, GS.StoredOnceValue, GVI,
827 getAnalysis<TargetData>()))
Chris Lattner09a52722004-10-09 21:48:45 +0000828 return true;
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000829 }
830 }
831 return false;
832}
833
834
Chris Lattner25db5802004-10-07 04:16:33 +0000835bool GlobalOpt::runOnModule(Module &M) {
836 bool Changed = false;
837
838 // As a prepass, delete functions that are trivially dead.
839 bool LocalChange = true;
840 while (LocalChange) {
841 LocalChange = false;
842 for (Module::iterator FI = M.begin(), E = M.end(); FI != E; ) {
843 Function *F = FI++;
844 F->removeDeadConstantUsers();
Chris Lattner5d33e8e2004-10-14 19:53:50 +0000845 if (F->use_empty() && (F->hasInternalLinkage() ||
846 F->hasLinkOnceLinkage())) {
Chris Lattner25db5802004-10-07 04:16:33 +0000847 M.getFunctionList().erase(F);
848 LocalChange = true;
849 ++NumFnDeleted;
850 }
851 }
852 Changed |= LocalChange;
853 }
854
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000855 LocalChange = true;
856 while (LocalChange) {
857 LocalChange = false;
858 for (Module::giterator GVI = M.gbegin(), E = M.gend(); GVI != E;) {
859 GlobalVariable *GV = GVI++;
860 if (!GV->isConstant() && GV->hasInternalLinkage() &&
861 GV->hasInitializer())
862 LocalChange |= ProcessInternalGlobal(GV, GVI);
Chris Lattner25db5802004-10-07 04:16:33 +0000863 }
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000864 Changed |= LocalChange;
Chris Lattner25db5802004-10-07 04:16:33 +0000865 }
866 return Changed;
867}