blob: b3edc9b8e4a48618c1f29eac1f696ad93ee48704 [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
90/// AnalyzeGlobal - Look at all uses of the global and fill in the GlobalStatus
91/// structure. If the global has its address taken, return true to indicate we
92/// can't do anything with it.
93///
94static bool AnalyzeGlobal(Value *V, GlobalStatus &GS,
95 std::set<PHINode*> &PHIUsers) {
96 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
97 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(*UI)) {
98 if (AnalyzeGlobal(CE, GS, PHIUsers)) return true;
99 if (CE->getOpcode() != Instruction::GetElementPtr)
100 GS.isNotSuitableForSRA = true;
Chris Lattnerabab0712004-10-08 17:32:09 +0000101 else if (!GS.isNotSuitableForSRA) {
102 // Check to see if this ConstantExpr GEP is SRA'able. In particular, we
103 // don't like < 3 operand CE's, and we don't like non-constant integer
104 // indices.
105 if (CE->getNumOperands() < 3 || !CE->getOperand(1)->isNullValue())
106 GS.isNotSuitableForSRA = true;
107 else {
108 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
109 if (!isa<ConstantInt>(CE->getOperand(i))) {
110 GS.isNotSuitableForSRA = true;
111 break;
112 }
113 }
114 }
115
Chris Lattner25db5802004-10-07 04:16:33 +0000116 } else if (Instruction *I = dyn_cast<Instruction>(*UI)) {
117 if (isa<LoadInst>(I)) {
118 GS.isLoaded = true;
119 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Chris Lattner02b6c912004-10-07 06:01:25 +0000120 // Don't allow a store OF the address, only stores TO the address.
121 if (SI->getOperand(0) == V) return true;
122
Chris Lattner617f1a32004-10-07 21:30:30 +0000123 // If this is a direct store to the global (i.e., the global is a scalar
124 // value, not an aggregate), keep more specific information about
125 // stores.
126 if (GS.StoredType != GlobalStatus::isStored)
127 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(SI->getOperand(1))){
128 if (SI->getOperand(0) == GV->getInitializer()) {
129 if (GS.StoredType < GlobalStatus::isInitializerStored)
130 GS.StoredType = GlobalStatus::isInitializerStored;
131 } else if (GS.StoredType < GlobalStatus::isStoredOnce) {
132 GS.StoredType = GlobalStatus::isStoredOnce;
133 GS.StoredOnceValue = SI->getOperand(0);
134 } else if (GS.StoredType == GlobalStatus::isStoredOnce &&
135 GS.StoredOnceValue == SI->getOperand(0)) {
136 // noop.
137 } else {
138 GS.StoredType = GlobalStatus::isStored;
139 }
140 } else {
Chris Lattner25db5802004-10-07 04:16:33 +0000141 GS.StoredType = GlobalStatus::isStored;
Chris Lattner617f1a32004-10-07 21:30:30 +0000142 }
Chris Lattner25db5802004-10-07 04:16:33 +0000143 } else if (I->getOpcode() == Instruction::GetElementPtr) {
144 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Chris Lattnerabab0712004-10-08 17:32:09 +0000145 // Theoretically we could SRA globals with GEP insts if all indexes are
146 // constants. In practice, these GEPs would already be constant exprs
147 // if that was the case though.
148 GS.isNotSuitableForSRA = true;
Chris Lattner25db5802004-10-07 04:16:33 +0000149 } else if (I->getOpcode() == Instruction::Select) {
150 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
151 GS.isNotSuitableForSRA = true;
152 } else if (PHINode *PN = dyn_cast<PHINode>(I)) {
153 // PHI nodes we can check just like select or GEP instructions, but we
154 // have to be careful about infinite recursion.
155 if (PHIUsers.insert(PN).second) // Not already visited.
156 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
157 GS.isNotSuitableForSRA = true;
158 } else if (isa<SetCondInst>(I)) {
159 GS.isNotSuitableForSRA = true;
160 } else {
161 return true; // Any other non-load instruction might take address!
162 }
163 } else {
164 // Otherwise must be a global or some other user.
165 return true;
166 }
167
168 return false;
169}
170
Chris Lattnerabab0712004-10-08 17:32:09 +0000171static Constant *getAggregateConstantElement(Constant *Agg, Constant *Idx) {
172 ConstantInt *CI = dyn_cast<ConstantInt>(Idx);
173 if (!CI) return 0;
174 uint64_t IdxV = CI->getRawValue();
Chris Lattner25db5802004-10-07 04:16:33 +0000175
Chris Lattnerabab0712004-10-08 17:32:09 +0000176 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Agg)) {
177 if (IdxV < CS->getNumOperands()) return CS->getOperand(IdxV);
178 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Agg)) {
179 if (IdxV < CA->getNumOperands()) return CA->getOperand(IdxV);
180 } else if (ConstantPacked *CP = dyn_cast<ConstantPacked>(Agg)) {
181 if (IdxV < CP->getNumOperands()) return CP->getOperand(IdxV);
182 } else if (ConstantAggregateZero *CAZ =
183 dyn_cast<ConstantAggregateZero>(Agg)) {
184 if (const StructType *STy = dyn_cast<StructType>(Agg->getType())) {
185 if (IdxV < STy->getNumElements())
186 return Constant::getNullValue(STy->getElementType(IdxV));
187 } else if (const SequentialType *STy =
188 dyn_cast<SequentialType>(Agg->getType())) {
189 return Constant::getNullValue(STy->getElementType());
190 }
191 }
192 return 0;
193}
Chris Lattner25db5802004-10-07 04:16:33 +0000194
195static Constant *TraverseGEPInitializer(User *GEP, Constant *Init) {
196 if (GEP->getNumOperands() == 1 ||
197 !isa<Constant>(GEP->getOperand(1)) ||
198 !cast<Constant>(GEP->getOperand(1))->isNullValue())
199 return 0;
200
201 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i) {
202 ConstantInt *Idx = dyn_cast<ConstantInt>(GEP->getOperand(i));
203 if (!Idx) return 0;
Chris Lattnerabab0712004-10-08 17:32:09 +0000204 Init = getAggregateConstantElement(Init, Idx);
205 if (Init == 0) return 0;
Chris Lattner25db5802004-10-07 04:16:33 +0000206 }
207 return Init;
208}
209
210/// CleanupConstantGlobalUsers - We just marked GV constant. Loop over all
211/// users of the global, cleaning up the obvious ones. This is largely just a
212/// quick scan over the use list to clean up the easy and obvious cruft.
213static void CleanupConstantGlobalUsers(Value *V, Constant *Init) {
214 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;) {
215 User *U = *UI++;
216
217 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
218 // Replace the load with the initializer.
219 LI->replaceAllUsesWith(Init);
220 LI->getParent()->getInstList().erase(LI);
221 } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
222 // Store must be unreachable or storing Init into the global.
223 SI->getParent()->getInstList().erase(SI);
224 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
225 if (CE->getOpcode() == Instruction::GetElementPtr) {
226 if (Constant *SubInit = TraverseGEPInitializer(CE, Init))
227 CleanupConstantGlobalUsers(CE, SubInit);
228 if (CE->use_empty()) CE->destroyConstant();
229 }
230 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
231 if (Constant *SubInit = TraverseGEPInitializer(GEP, Init))
232 CleanupConstantGlobalUsers(GEP, SubInit);
233 if (GEP->use_empty())
234 GEP->getParent()->getInstList().erase(GEP);
235 }
236 }
237}
238
Chris Lattnerabab0712004-10-08 17:32:09 +0000239/// SRAGlobal - Perform scalar replacement of aggregates on the specified global
240/// variable. This opens the door for other optimizations by exposing the
241/// behavior of the program in a more fine-grained way. We have determined that
242/// this transformation is safe already. We return the first global variable we
243/// insert so that the caller can reprocess it.
244static GlobalVariable *SRAGlobal(GlobalVariable *GV) {
245 assert(GV->hasInternalLinkage() && !GV->isConstant());
246 Constant *Init = GV->getInitializer();
247 const Type *Ty = Init->getType();
248
249 std::vector<GlobalVariable*> NewGlobals;
250 Module::GlobalListType &Globals = GV->getParent()->getGlobalList();
251
252 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
253 NewGlobals.reserve(STy->getNumElements());
254 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
255 Constant *In = getAggregateConstantElement(Init,
256 ConstantUInt::get(Type::UIntTy, i));
257 assert(In && "Couldn't get element of initializer?");
258 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(i), false,
259 GlobalVariable::InternalLinkage,
260 In, GV->getName()+"."+utostr(i));
261 Globals.insert(GV, NGV);
262 NewGlobals.push_back(NGV);
263 }
264 } else if (const SequentialType *STy = dyn_cast<SequentialType>(Ty)) {
265 unsigned NumElements = 0;
266 if (const ArrayType *ATy = dyn_cast<ArrayType>(STy))
267 NumElements = ATy->getNumElements();
268 else if (const PackedType *PTy = dyn_cast<PackedType>(STy))
269 NumElements = PTy->getNumElements();
270 else
271 assert(0 && "Unknown aggregate sequential type!");
272
273 if (NumElements > 16) return 0; // It's not worth it.
274 NewGlobals.reserve(NumElements);
275 for (unsigned i = 0, e = NumElements; i != e; ++i) {
276 Constant *In = getAggregateConstantElement(Init,
277 ConstantUInt::get(Type::UIntTy, i));
278 assert(In && "Couldn't get element of initializer?");
279
280 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(), false,
281 GlobalVariable::InternalLinkage,
282 In, GV->getName()+"."+utostr(i));
283 Globals.insert(GV, NGV);
284 NewGlobals.push_back(NGV);
285 }
286 }
287
288 if (NewGlobals.empty())
289 return 0;
290
291 Constant *NullInt = Constant::getNullValue(Type::IntTy);
292
293 // Loop over all of the uses of the global, replacing the constantexpr geps,
294 // with smaller constantexpr geps or direct references.
295 while (!GV->use_empty()) {
296 ConstantExpr *CE = cast<ConstantExpr>(GV->use_back());
297 assert(CE->getOpcode() == Instruction::GetElementPtr &&
298 "NonGEP CE's are not SRAable!");
299 // Ignore the 1th operand, which has to be zero or else the program is quite
300 // broken (undefined). Get the 2nd operand, which is the structure or array
301 // index.
302 unsigned Val = cast<ConstantInt>(CE->getOperand(2))->getRawValue();
303 if (Val >= NewGlobals.size()) Val = 0; // Out of bound array access.
304
305 Constant *NewPtr = NewGlobals[Val];
306
307 // Form a shorter GEP if needed.
308 if (CE->getNumOperands() > 3) {
309 std::vector<Constant*> Idxs;
310 Idxs.push_back(NullInt);
311 for (unsigned i = 3, e = CE->getNumOperands(); i != e; ++i)
312 Idxs.push_back(CE->getOperand(i));
313 NewPtr = ConstantExpr::getGetElementPtr(NewPtr, Idxs);
314 }
315 CE->replaceAllUsesWith(NewPtr);
316 CE->destroyConstant();
317 }
318
Chris Lattner73ad73e2004-10-08 20:25:55 +0000319 // Delete the old global, now that it is dead.
320 Globals.erase(GV);
Chris Lattnerabab0712004-10-08 17:32:09 +0000321 ++NumSRA;
322 return NewGlobals[0];
323}
324
Chris Lattner25db5802004-10-07 04:16:33 +0000325bool GlobalOpt::runOnModule(Module &M) {
326 bool Changed = false;
327
328 // As a prepass, delete functions that are trivially dead.
329 bool LocalChange = true;
330 while (LocalChange) {
331 LocalChange = false;
332 for (Module::iterator FI = M.begin(), E = M.end(); FI != E; ) {
333 Function *F = FI++;
334 F->removeDeadConstantUsers();
335 if (F->use_empty() && (F->hasInternalLinkage() || F->hasWeakLinkage())) {
336 M.getFunctionList().erase(F);
337 LocalChange = true;
338 ++NumFnDeleted;
339 }
340 }
341 Changed |= LocalChange;
342 }
343
344 std::set<PHINode*> PHIUsers;
345 for (Module::giterator GVI = M.gbegin(), E = M.gend(); GVI != E;) {
346 GlobalVariable *GV = GVI++;
347 if (!GV->isConstant() && GV->hasInternalLinkage() && GV->hasInitializer()) {
348 GlobalStatus GS;
349 PHIUsers.clear();
350 GV->removeDeadConstantUsers();
351 if (!AnalyzeGlobal(GV, GS, PHIUsers)) {
352 // If the global is never loaded (but may be stored to), it is dead.
353 // Delete it now.
354 if (!GS.isLoaded) {
355 DEBUG(std::cerr << "GLOBAL NEVER LOADED: " << *GV);
356 // Delete any stores we can find to the global. We may not be able to
357 // make it completely dead though.
358 CleanupConstantGlobalUsers(GV, GV->getInitializer());
359
360 // If the global is dead now, delete it.
361 if (GV->use_empty()) {
362 M.getGlobalList().erase(GV);
363 ++NumDeleted;
364 }
365 Changed = true;
366
367 } else if (GS.StoredType <= GlobalStatus::isInitializerStored) {
368 DEBUG(std::cerr << "MARKING CONSTANT: " << *GV);
369 GV->setConstant(true);
370
371 // Clean up any obviously simplifiable users now.
372 CleanupConstantGlobalUsers(GV, GV->getInitializer());
373
374 // If the global is dead now, just nuke it.
375 if (GV->use_empty()) {
376 M.getGlobalList().erase(GV);
377 ++NumDeleted;
378 }
379
380 ++NumMarked;
381 Changed = true;
Chris Lattnerabab0712004-10-08 17:32:09 +0000382 } else if (!GS.isNotSuitableForSRA &&
383 !GV->getInitializer()->getType()->isFirstClassType()) {
384 DEBUG(std::cerr << "PERFORMING GLOBAL SRA ON: " << *GV);
385 if (GlobalVariable *FirstNewGV = SRAGlobal(GV))
386 GVI = FirstNewGV; // Don't skip the newly produced globals!
Chris Lattner25db5802004-10-07 04:16:33 +0000387 }
388 }
389 }
390 }
391 return Changed;
392}