blob: 59ea4a6f6f0a3c35d5fac7eb1eaec005893c82d2 [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");
Alkis Evlogimenosc4a44c62005-02-10 18:36:30 +000041 Statistic<> NumLocalized("globalopt", "Number of globals localized");
Chris Lattner40e4cec2004-12-12 05:53:50 +000042 Statistic<> NumShrunkToBool("globalopt",
43 "Number of global vars shrunk to booleans");
Chris Lattner25db5802004-10-07 04:16:33 +000044
45 struct GlobalOpt : public ModulePass {
Chris Lattner004e2502004-10-11 05:54:41 +000046 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
47 AU.addRequired<TargetData>();
48 }
49
Chris Lattner25db5802004-10-07 04:16:33 +000050 bool runOnModule(Module &M);
Chris Lattner004e2502004-10-11 05:54:41 +000051
52 private:
53 bool ProcessInternalGlobal(GlobalVariable *GV, Module::giterator &GVI);
Chris Lattner25db5802004-10-07 04:16:33 +000054 };
55
56 RegisterOpt<GlobalOpt> X("globalopt", "Global Variable Optimizer");
57}
58
59ModulePass *llvm::createGlobalOptimizerPass() { return new GlobalOpt(); }
60
61/// GlobalStatus - As we analyze each global, keep track of some information
62/// about it. If we find out that the address of the global is taken, none of
Chris Lattner617f1a32004-10-07 21:30:30 +000063/// this info will be accurate.
Chris Lattner25db5802004-10-07 04:16:33 +000064struct GlobalStatus {
Chris Lattner617f1a32004-10-07 21:30:30 +000065 /// isLoaded - True if the global is ever loaded. If the global isn't ever
66 /// loaded it can be deleted.
Chris Lattner25db5802004-10-07 04:16:33 +000067 bool isLoaded;
Chris Lattner617f1a32004-10-07 21:30:30 +000068
69 /// StoredType - Keep track of what stores to the global look like.
70 ///
Chris Lattner25db5802004-10-07 04:16:33 +000071 enum StoredType {
Chris Lattner617f1a32004-10-07 21:30:30 +000072 /// NotStored - There is no store to this global. It can thus be marked
73 /// constant.
74 NotStored,
75
76 /// isInitializerStored - This global is stored to, but the only thing
77 /// stored is the constant it was initialized with. This is only tracked
78 /// for scalar globals.
79 isInitializerStored,
80
81 /// isStoredOnce - This global is stored to, but only its initializer and
82 /// one other value is ever stored to it. If this global isStoredOnce, we
83 /// track the value stored to it in StoredOnceValue below. This is only
84 /// tracked for scalar globals.
85 isStoredOnce,
86
87 /// isStored - This global is stored to by multiple values or something else
88 /// that we cannot track.
89 isStored
Chris Lattner25db5802004-10-07 04:16:33 +000090 } StoredType;
Chris Lattner617f1a32004-10-07 21:30:30 +000091
92 /// StoredOnceValue - If only one value (besides the initializer constant) is
93 /// ever stored to this global, keep track of what value it is.
94 Value *StoredOnceValue;
95
Alkis Evlogimenosc4a44c62005-02-10 18:36:30 +000096 // AccessingFunction/HasMultipleAccessingFunctions - These start out
97 // null/false. When the first accessing function is noticed, it is recorded.
98 // When a second different accessing function is noticed,
99 // HasMultipleAccessingFunctions is set to true.
100 Function *AccessingFunction;
101 bool HasMultipleAccessingFunctions;
102
Chris Lattner617f1a32004-10-07 21:30:30 +0000103 /// isNotSuitableForSRA - Keep track of whether any SRA preventing users of
104 /// the global exist. Such users include GEP instruction with variable
105 /// indexes, and non-gep/load/store users like constant expr casts.
Chris Lattner25db5802004-10-07 04:16:33 +0000106 bool isNotSuitableForSRA;
107
Chris Lattner617f1a32004-10-07 21:30:30 +0000108 GlobalStatus() : isLoaded(false), StoredType(NotStored), StoredOnceValue(0),
Alkis Evlogimenosc4a44c62005-02-10 18:36:30 +0000109 AccessingFunction(0), HasMultipleAccessingFunctions(false),
Chris Lattner25db5802004-10-07 04:16:33 +0000110 isNotSuitableForSRA(false) {}
111};
112
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000113
114
115/// ConstantIsDead - Return true if the specified constant is (transitively)
116/// dead. The constant may be used by other constants (e.g. constant arrays and
117/// constant exprs) as long as they are dead, but it cannot be used by anything
118/// else.
119static bool ConstantIsDead(Constant *C) {
120 if (isa<GlobalValue>(C)) return false;
121
122 for (Value::use_iterator UI = C->use_begin(), E = C->use_end(); UI != E; ++UI)
123 if (Constant *CU = dyn_cast<Constant>(*UI)) {
124 if (!ConstantIsDead(CU)) return false;
125 } else
126 return false;
127 return true;
128}
129
130
Chris Lattner25db5802004-10-07 04:16:33 +0000131/// AnalyzeGlobal - Look at all uses of the global and fill in the GlobalStatus
132/// structure. If the global has its address taken, return true to indicate we
133/// can't do anything with it.
134///
135static bool AnalyzeGlobal(Value *V, GlobalStatus &GS,
136 std::set<PHINode*> &PHIUsers) {
137 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
138 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(*UI)) {
139 if (AnalyzeGlobal(CE, GS, PHIUsers)) return true;
140 if (CE->getOpcode() != Instruction::GetElementPtr)
141 GS.isNotSuitableForSRA = true;
Chris Lattnerabab0712004-10-08 17:32:09 +0000142 else if (!GS.isNotSuitableForSRA) {
143 // Check to see if this ConstantExpr GEP is SRA'able. In particular, we
144 // don't like < 3 operand CE's, and we don't like non-constant integer
145 // indices.
146 if (CE->getNumOperands() < 3 || !CE->getOperand(1)->isNullValue())
147 GS.isNotSuitableForSRA = true;
148 else {
149 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
150 if (!isa<ConstantInt>(CE->getOperand(i))) {
151 GS.isNotSuitableForSRA = true;
152 break;
153 }
154 }
155 }
156
Chris Lattner25db5802004-10-07 04:16:33 +0000157 } else if (Instruction *I = dyn_cast<Instruction>(*UI)) {
Alkis Evlogimenosc4a44c62005-02-10 18:36:30 +0000158 if (!GS.HasMultipleAccessingFunctions) {
159 Function *F = I->getParent()->getParent();
160 if (GS.AccessingFunction == 0)
161 GS.AccessingFunction = F;
162 else if (GS.AccessingFunction != F)
163 GS.HasMultipleAccessingFunctions = true;
164 }
Chris Lattner25db5802004-10-07 04:16:33 +0000165 if (isa<LoadInst>(I)) {
166 GS.isLoaded = true;
167 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Chris Lattner02b6c912004-10-07 06:01:25 +0000168 // Don't allow a store OF the address, only stores TO the address.
169 if (SI->getOperand(0) == V) return true;
170
Chris Lattner617f1a32004-10-07 21:30:30 +0000171 // If this is a direct store to the global (i.e., the global is a scalar
172 // value, not an aggregate), keep more specific information about
173 // stores.
174 if (GS.StoredType != GlobalStatus::isStored)
175 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(SI->getOperand(1))){
Chris Lattner28eeb732004-11-14 20:50:30 +0000176 Value *StoredVal = SI->getOperand(0);
177 if (StoredVal == GV->getInitializer()) {
178 if (GS.StoredType < GlobalStatus::isInitializerStored)
179 GS.StoredType = GlobalStatus::isInitializerStored;
180 } else if (isa<LoadInst>(StoredVal) &&
181 cast<LoadInst>(StoredVal)->getOperand(0) == GV) {
182 // G = G
Chris Lattner617f1a32004-10-07 21:30:30 +0000183 if (GS.StoredType < GlobalStatus::isInitializerStored)
184 GS.StoredType = GlobalStatus::isInitializerStored;
185 } else if (GS.StoredType < GlobalStatus::isStoredOnce) {
186 GS.StoredType = GlobalStatus::isStoredOnce;
Chris Lattner28eeb732004-11-14 20:50:30 +0000187 GS.StoredOnceValue = StoredVal;
Chris Lattner617f1a32004-10-07 21:30:30 +0000188 } else if (GS.StoredType == GlobalStatus::isStoredOnce &&
Chris Lattner28eeb732004-11-14 20:50:30 +0000189 GS.StoredOnceValue == StoredVal) {
Chris Lattner617f1a32004-10-07 21:30:30 +0000190 // noop.
191 } else {
192 GS.StoredType = GlobalStatus::isStored;
193 }
194 } else {
Chris Lattner25db5802004-10-07 04:16:33 +0000195 GS.StoredType = GlobalStatus::isStored;
Chris Lattner617f1a32004-10-07 21:30:30 +0000196 }
Chris Lattner25db5802004-10-07 04:16:33 +0000197 } else if (I->getOpcode() == Instruction::GetElementPtr) {
198 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Chris Lattner004e2502004-10-11 05:54:41 +0000199
200 // If the first two indices are constants, this can be SRA'd.
201 if (isa<GlobalVariable>(I->getOperand(0))) {
202 if (I->getNumOperands() < 3 || !isa<Constant>(I->getOperand(1)) ||
203 !cast<Constant>(I->getOperand(1))->isNullValue() ||
204 !isa<ConstantInt>(I->getOperand(2)))
205 GS.isNotSuitableForSRA = true;
206 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(I->getOperand(0))){
207 if (CE->getOpcode() != Instruction::GetElementPtr ||
208 CE->getNumOperands() < 3 || I->getNumOperands() < 2 ||
209 !isa<Constant>(I->getOperand(0)) ||
210 !cast<Constant>(I->getOperand(0))->isNullValue())
211 GS.isNotSuitableForSRA = true;
212 } else {
213 GS.isNotSuitableForSRA = true;
214 }
Chris Lattner25db5802004-10-07 04:16:33 +0000215 } else if (I->getOpcode() == Instruction::Select) {
216 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
217 GS.isNotSuitableForSRA = true;
218 } else if (PHINode *PN = dyn_cast<PHINode>(I)) {
219 // PHI nodes we can check just like select or GEP instructions, but we
220 // have to be careful about infinite recursion.
221 if (PHIUsers.insert(PN).second) // Not already visited.
222 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
223 GS.isNotSuitableForSRA = true;
224 } else if (isa<SetCondInst>(I)) {
225 GS.isNotSuitableForSRA = true;
226 } else {
227 return true; // Any other non-load instruction might take address!
228 }
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000229 } else if (Constant *C = dyn_cast<Constant>(*UI)) {
230 // We might have a dead and dangling constant hanging off of here.
231 if (!ConstantIsDead(C))
232 return true;
Chris Lattner25db5802004-10-07 04:16:33 +0000233 } else {
234 // Otherwise must be a global or some other user.
235 return true;
236 }
237
238 return false;
239}
240
Chris Lattnerabab0712004-10-08 17:32:09 +0000241static Constant *getAggregateConstantElement(Constant *Agg, Constant *Idx) {
242 ConstantInt *CI = dyn_cast<ConstantInt>(Idx);
243 if (!CI) return 0;
Chris Lattner46fa04b2005-01-08 19:45:31 +0000244 unsigned IdxV = (unsigned)CI->getRawValue();
Chris Lattner25db5802004-10-07 04:16:33 +0000245
Chris Lattnerabab0712004-10-08 17:32:09 +0000246 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Agg)) {
247 if (IdxV < CS->getNumOperands()) return CS->getOperand(IdxV);
248 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Agg)) {
249 if (IdxV < CA->getNumOperands()) return CA->getOperand(IdxV);
250 } else if (ConstantPacked *CP = dyn_cast<ConstantPacked>(Agg)) {
251 if (IdxV < CP->getNumOperands()) return CP->getOperand(IdxV);
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000252 } else if (isa<ConstantAggregateZero>(Agg)) {
Chris Lattnerabab0712004-10-08 17:32:09 +0000253 if (const StructType *STy = dyn_cast<StructType>(Agg->getType())) {
254 if (IdxV < STy->getNumElements())
255 return Constant::getNullValue(STy->getElementType(IdxV));
256 } else if (const SequentialType *STy =
257 dyn_cast<SequentialType>(Agg->getType())) {
258 return Constant::getNullValue(STy->getElementType());
259 }
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000260 } else if (isa<UndefValue>(Agg)) {
261 if (const StructType *STy = dyn_cast<StructType>(Agg->getType())) {
262 if (IdxV < STy->getNumElements())
263 return UndefValue::get(STy->getElementType(IdxV));
264 } else if (const SequentialType *STy =
265 dyn_cast<SequentialType>(Agg->getType())) {
266 return UndefValue::get(STy->getElementType());
267 }
Chris Lattnerabab0712004-10-08 17:32:09 +0000268 }
269 return 0;
270}
Chris Lattner25db5802004-10-07 04:16:33 +0000271
272static Constant *TraverseGEPInitializer(User *GEP, Constant *Init) {
273 if (GEP->getNumOperands() == 1 ||
274 !isa<Constant>(GEP->getOperand(1)) ||
275 !cast<Constant>(GEP->getOperand(1))->isNullValue())
276 return 0;
277
278 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i) {
279 ConstantInt *Idx = dyn_cast<ConstantInt>(GEP->getOperand(i));
280 if (!Idx) return 0;
Chris Lattnerabab0712004-10-08 17:32:09 +0000281 Init = getAggregateConstantElement(Init, Idx);
282 if (Init == 0) return 0;
Chris Lattner25db5802004-10-07 04:16:33 +0000283 }
284 return Init;
285}
286
287/// CleanupConstantGlobalUsers - We just marked GV constant. Loop over all
288/// users of the global, cleaning up the obvious ones. This is largely just a
Chris Lattnercb9f1522004-10-10 16:43:46 +0000289/// quick scan over the use list to clean up the easy and obvious cruft. This
290/// returns true if it made a change.
291static bool CleanupConstantGlobalUsers(Value *V, Constant *Init) {
292 bool Changed = false;
Chris Lattner25db5802004-10-07 04:16:33 +0000293 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;) {
294 User *U = *UI++;
295
296 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
297 // Replace the load with the initializer.
298 LI->replaceAllUsesWith(Init);
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000299 LI->eraseFromParent();
Chris Lattnercb9f1522004-10-10 16:43:46 +0000300 Changed = true;
Chris Lattner25db5802004-10-07 04:16:33 +0000301 } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
302 // Store must be unreachable or storing Init into the global.
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000303 SI->eraseFromParent();
Chris Lattnercb9f1522004-10-10 16:43:46 +0000304 Changed = true;
Chris Lattner25db5802004-10-07 04:16:33 +0000305 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
306 if (CE->getOpcode() == Instruction::GetElementPtr) {
307 if (Constant *SubInit = TraverseGEPInitializer(CE, Init))
Chris Lattnercb9f1522004-10-10 16:43:46 +0000308 Changed |= CleanupConstantGlobalUsers(CE, SubInit);
309 if (CE->use_empty()) {
310 CE->destroyConstant();
311 Changed = true;
312 }
Chris Lattner25db5802004-10-07 04:16:33 +0000313 }
314 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
315 if (Constant *SubInit = TraverseGEPInitializer(GEP, Init))
Chris Lattnercb9f1522004-10-10 16:43:46 +0000316 Changed |= CleanupConstantGlobalUsers(GEP, SubInit);
Chris Lattnera0e769c2004-10-10 16:47:33 +0000317 else {
318 // If this GEP has variable indexes, we should still be able to delete
319 // any stores through it.
320 for (Value::use_iterator GUI = GEP->use_begin(), E = GEP->use_end();
321 GUI != E;)
322 if (StoreInst *SI = dyn_cast<StoreInst>(*GUI++)) {
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000323 SI->eraseFromParent();
Chris Lattnera0e769c2004-10-10 16:47:33 +0000324 Changed = true;
325 }
326 }
327
Chris Lattnercb9f1522004-10-10 16:43:46 +0000328 if (GEP->use_empty()) {
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000329 GEP->eraseFromParent();
Chris Lattnercb9f1522004-10-10 16:43:46 +0000330 Changed = true;
331 }
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000332 } else if (Constant *C = dyn_cast<Constant>(U)) {
333 // If we have a chain of dead constantexprs or other things dangling from
334 // us, and if they are all dead, nuke them without remorse.
335 if (ConstantIsDead(C)) {
336 C->destroyConstant();
337 // This could have incalidated UI, start over from scratch.x
338 CleanupConstantGlobalUsers(V, Init);
Chris Lattnercb9f1522004-10-10 16:43:46 +0000339 return true;
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000340 }
Chris Lattner25db5802004-10-07 04:16:33 +0000341 }
342 }
Chris Lattnercb9f1522004-10-10 16:43:46 +0000343 return Changed;
Chris Lattner25db5802004-10-07 04:16:33 +0000344}
345
Chris Lattnerabab0712004-10-08 17:32:09 +0000346/// SRAGlobal - Perform scalar replacement of aggregates on the specified global
347/// variable. This opens the door for other optimizations by exposing the
348/// behavior of the program in a more fine-grained way. We have determined that
349/// this transformation is safe already. We return the first global variable we
350/// insert so that the caller can reprocess it.
351static GlobalVariable *SRAGlobal(GlobalVariable *GV) {
352 assert(GV->hasInternalLinkage() && !GV->isConstant());
353 Constant *Init = GV->getInitializer();
354 const Type *Ty = Init->getType();
355
356 std::vector<GlobalVariable*> NewGlobals;
357 Module::GlobalListType &Globals = GV->getParent()->getGlobalList();
358
359 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
360 NewGlobals.reserve(STy->getNumElements());
361 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
362 Constant *In = getAggregateConstantElement(Init,
363 ConstantUInt::get(Type::UIntTy, i));
364 assert(In && "Couldn't get element of initializer?");
365 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(i), false,
366 GlobalVariable::InternalLinkage,
367 In, GV->getName()+"."+utostr(i));
368 Globals.insert(GV, NGV);
369 NewGlobals.push_back(NGV);
370 }
371 } else if (const SequentialType *STy = dyn_cast<SequentialType>(Ty)) {
372 unsigned NumElements = 0;
373 if (const ArrayType *ATy = dyn_cast<ArrayType>(STy))
374 NumElements = ATy->getNumElements();
375 else if (const PackedType *PTy = dyn_cast<PackedType>(STy))
376 NumElements = PTy->getNumElements();
377 else
378 assert(0 && "Unknown aggregate sequential type!");
379
Chris Lattnerd6a44922005-02-01 01:23:31 +0000380 if (NumElements > 16 && GV->getNumUses() > 16)
381 return 0; // It's not worth it.
Chris Lattnerabab0712004-10-08 17:32:09 +0000382 NewGlobals.reserve(NumElements);
383 for (unsigned i = 0, e = NumElements; i != e; ++i) {
384 Constant *In = getAggregateConstantElement(Init,
385 ConstantUInt::get(Type::UIntTy, i));
386 assert(In && "Couldn't get element of initializer?");
387
388 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(), false,
389 GlobalVariable::InternalLinkage,
390 In, GV->getName()+"."+utostr(i));
391 Globals.insert(GV, NGV);
392 NewGlobals.push_back(NGV);
393 }
394 }
395
396 if (NewGlobals.empty())
397 return 0;
398
Chris Lattner004e2502004-10-11 05:54:41 +0000399 DEBUG(std::cerr << "PERFORMING GLOBAL SRA ON: " << *GV);
400
Chris Lattnerabab0712004-10-08 17:32:09 +0000401 Constant *NullInt = Constant::getNullValue(Type::IntTy);
402
403 // Loop over all of the uses of the global, replacing the constantexpr geps,
404 // with smaller constantexpr geps or direct references.
405 while (!GV->use_empty()) {
Chris Lattner004e2502004-10-11 05:54:41 +0000406 User *GEP = GV->use_back();
407 assert(((isa<ConstantExpr>(GEP) &&
408 cast<ConstantExpr>(GEP)->getOpcode()==Instruction::GetElementPtr)||
409 isa<GetElementPtrInst>(GEP)) && "NonGEP CE's are not SRAable!");
410
Chris Lattnerabab0712004-10-08 17:32:09 +0000411 // Ignore the 1th operand, which has to be zero or else the program is quite
412 // broken (undefined). Get the 2nd operand, which is the structure or array
413 // index.
Chris Lattner46fa04b2005-01-08 19:45:31 +0000414 unsigned Val =
415 (unsigned)cast<ConstantInt>(GEP->getOperand(2))->getRawValue();
Chris Lattnerabab0712004-10-08 17:32:09 +0000416 if (Val >= NewGlobals.size()) Val = 0; // Out of bound array access.
417
Chris Lattner004e2502004-10-11 05:54:41 +0000418 Value *NewPtr = NewGlobals[Val];
Chris Lattnerabab0712004-10-08 17:32:09 +0000419
420 // Form a shorter GEP if needed.
Chris Lattner004e2502004-10-11 05:54:41 +0000421 if (GEP->getNumOperands() > 3)
422 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEP)) {
423 std::vector<Constant*> Idxs;
424 Idxs.push_back(NullInt);
425 for (unsigned i = 3, e = CE->getNumOperands(); i != e; ++i)
426 Idxs.push_back(CE->getOperand(i));
427 NewPtr = ConstantExpr::getGetElementPtr(cast<Constant>(NewPtr), Idxs);
428 } else {
429 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(GEP);
430 std::vector<Value*> Idxs;
431 Idxs.push_back(NullInt);
432 for (unsigned i = 3, e = GEPI->getNumOperands(); i != e; ++i)
433 Idxs.push_back(GEPI->getOperand(i));
434 NewPtr = new GetElementPtrInst(NewPtr, Idxs,
435 GEPI->getName()+"."+utostr(Val), GEPI);
436 }
437 GEP->replaceAllUsesWith(NewPtr);
438
439 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(GEP))
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000440 GEPI->eraseFromParent();
Chris Lattner004e2502004-10-11 05:54:41 +0000441 else
442 cast<ConstantExpr>(GEP)->destroyConstant();
Chris Lattnerabab0712004-10-08 17:32:09 +0000443 }
444
Chris Lattner73ad73e2004-10-08 20:25:55 +0000445 // Delete the old global, now that it is dead.
446 Globals.erase(GV);
Chris Lattnerabab0712004-10-08 17:32:09 +0000447 ++NumSRA;
Chris Lattner004e2502004-10-11 05:54:41 +0000448
449 // Loop over the new globals array deleting any globals that are obviously
450 // dead. This can arise due to scalarization of a structure or an array that
451 // has elements that are dead.
452 unsigned FirstGlobal = 0;
453 for (unsigned i = 0, e = NewGlobals.size(); i != e; ++i)
454 if (NewGlobals[i]->use_empty()) {
455 Globals.erase(NewGlobals[i]);
456 if (FirstGlobal == i) ++FirstGlobal;
457 }
458
459 return FirstGlobal != NewGlobals.size() ? NewGlobals[FirstGlobal] : 0;
Chris Lattnerabab0712004-10-08 17:32:09 +0000460}
461
Chris Lattner09a52722004-10-09 21:48:45 +0000462/// AllUsesOfValueWillTrapIfNull - Return true if all users of the specified
463/// value will trap if the value is dynamically null.
464static bool AllUsesOfValueWillTrapIfNull(Value *V) {
465 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
466 if (isa<LoadInst>(*UI)) {
467 // Will trap.
468 } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
469 if (SI->getOperand(0) == V) {
470 //std::cerr << "NONTRAPPING USE: " << **UI;
471 return false; // Storing the value.
472 }
473 } else if (CallInst *CI = dyn_cast<CallInst>(*UI)) {
474 if (CI->getOperand(0) != V) {
475 //std::cerr << "NONTRAPPING USE: " << **UI;
476 return false; // Not calling the ptr
477 }
478 } else if (InvokeInst *II = dyn_cast<InvokeInst>(*UI)) {
479 if (II->getOperand(0) != V) {
480 //std::cerr << "NONTRAPPING USE: " << **UI;
481 return false; // Not calling the ptr
482 }
483 } else if (CastInst *CI = dyn_cast<CastInst>(*UI)) {
484 if (!AllUsesOfValueWillTrapIfNull(CI)) return false;
485 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(*UI)) {
486 if (!AllUsesOfValueWillTrapIfNull(GEPI)) return false;
Chris Lattnerfe9abf92004-10-22 06:43:28 +0000487 } else if (isa<SetCondInst>(*UI) &&
488 isa<ConstantPointerNull>(UI->getOperand(1))) {
489 // Ignore setcc X, null
Chris Lattner09a52722004-10-09 21:48:45 +0000490 } else {
491 //std::cerr << "NONTRAPPING USE: " << **UI;
492 return false;
493 }
494 return true;
495}
496
497/// AllUsesOfLoadedValueWillTrapIfNull - Return true if all uses of any loads
Chris Lattnerfe9abf92004-10-22 06:43:28 +0000498/// from GV will trap if the loaded value is null. Note that this also permits
499/// comparisons of the loaded value against null, as a special case.
Chris Lattner09a52722004-10-09 21:48:45 +0000500static bool AllUsesOfLoadedValueWillTrapIfNull(GlobalVariable *GV) {
501 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI!=E; ++UI)
502 if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
503 if (!AllUsesOfValueWillTrapIfNull(LI))
504 return false;
505 } else if (isa<StoreInst>(*UI)) {
506 // Ignore stores to the global.
507 } else {
508 // We don't know or understand this user, bail out.
509 //std::cerr << "UNKNOWN USER OF GLOBAL!: " << **UI;
510 return false;
511 }
512
513 return true;
514}
515
Chris Lattnere42eb312004-10-10 23:14:11 +0000516static bool OptimizeAwayTrappingUsesOfValue(Value *V, Constant *NewV) {
517 bool Changed = false;
518 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ) {
519 Instruction *I = cast<Instruction>(*UI++);
520 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
521 LI->setOperand(0, NewV);
522 Changed = true;
523 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
524 if (SI->getOperand(1) == V) {
525 SI->setOperand(1, NewV);
526 Changed = true;
527 }
528 } else if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
529 if (I->getOperand(0) == V) {
530 // Calling through the pointer! Turn into a direct call, but be careful
531 // that the pointer is not also being passed as an argument.
532 I->setOperand(0, NewV);
533 Changed = true;
534 bool PassedAsArg = false;
535 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i)
536 if (I->getOperand(i) == V) {
537 PassedAsArg = true;
538 I->setOperand(i, NewV);
539 }
540
541 if (PassedAsArg) {
542 // Being passed as an argument also. Be careful to not invalidate UI!
543 UI = V->use_begin();
544 }
545 }
546 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
547 Changed |= OptimizeAwayTrappingUsesOfValue(CI,
548 ConstantExpr::getCast(NewV, CI->getType()));
549 if (CI->use_empty()) {
550 Changed = true;
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000551 CI->eraseFromParent();
Chris Lattnere42eb312004-10-10 23:14:11 +0000552 }
553 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
554 // Should handle GEP here.
555 std::vector<Constant*> Indices;
556 Indices.reserve(GEPI->getNumOperands()-1);
557 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
558 if (Constant *C = dyn_cast<Constant>(GEPI->getOperand(i)))
559 Indices.push_back(C);
560 else
561 break;
562 if (Indices.size() == GEPI->getNumOperands()-1)
563 Changed |= OptimizeAwayTrappingUsesOfValue(GEPI,
564 ConstantExpr::getGetElementPtr(NewV, Indices));
565 if (GEPI->use_empty()) {
566 Changed = true;
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000567 GEPI->eraseFromParent();
Chris Lattnere42eb312004-10-10 23:14:11 +0000568 }
569 }
570 }
571
572 return Changed;
573}
574
575
576/// OptimizeAwayTrappingUsesOfLoads - The specified global has only one non-null
577/// value stored into it. If there are uses of the loaded value that would trap
578/// if the loaded value is dynamically null, then we know that they cannot be
579/// reachable with a null optimize away the load.
580static bool OptimizeAwayTrappingUsesOfLoads(GlobalVariable *GV, Constant *LV) {
581 std::vector<LoadInst*> Loads;
582 bool Changed = false;
583
584 // Replace all uses of loads with uses of uses of the stored value.
585 for (Value::use_iterator GUI = GV->use_begin(), E = GV->use_end();
586 GUI != E; ++GUI)
587 if (LoadInst *LI = dyn_cast<LoadInst>(*GUI)) {
588 Loads.push_back(LI);
589 Changed |= OptimizeAwayTrappingUsesOfValue(LI, LV);
590 } else {
591 assert(isa<StoreInst>(*GUI) && "Only expect load and stores!");
592 }
593
594 if (Changed) {
595 DEBUG(std::cerr << "OPTIMIZED LOADS FROM STORED ONCE POINTER: " << *GV);
596 ++NumGlobUses;
597 }
598
599 // Delete all of the loads we can, keeping track of whether we nuked them all!
600 bool AllLoadsGone = true;
601 while (!Loads.empty()) {
602 LoadInst *L = Loads.back();
603 if (L->use_empty()) {
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000604 L->eraseFromParent();
Chris Lattnere42eb312004-10-10 23:14:11 +0000605 Changed = true;
606 } else {
607 AllLoadsGone = false;
608 }
609 Loads.pop_back();
610 }
611
612 // If we nuked all of the loads, then none of the stores are needed either,
613 // nor is the global.
614 if (AllLoadsGone) {
615 DEBUG(std::cerr << " *** GLOBAL NOW DEAD!\n");
616 CleanupConstantGlobalUsers(GV, 0);
617 if (GV->use_empty()) {
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000618 GV->eraseFromParent();
Chris Lattnere42eb312004-10-10 23:14:11 +0000619 ++NumDeleted;
620 }
621 Changed = true;
622 }
623 return Changed;
624}
625
Chris Lattner004e2502004-10-11 05:54:41 +0000626/// ConstantPropUsersOf - Walk the use list of V, constant folding all of the
627/// instructions that are foldable.
628static void ConstantPropUsersOf(Value *V) {
629 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; )
630 if (Instruction *I = dyn_cast<Instruction>(*UI++))
631 if (Constant *NewC = ConstantFoldInstruction(I)) {
632 I->replaceAllUsesWith(NewC);
633
Chris Lattnerd6a44922005-02-01 01:23:31 +0000634 // Advance UI to the next non-I use to avoid invalidating it!
635 // Instructions could multiply use V.
636 while (UI != E && *UI == I)
Chris Lattner004e2502004-10-11 05:54:41 +0000637 ++UI;
Chris Lattnerd6a44922005-02-01 01:23:31 +0000638 I->eraseFromParent();
Chris Lattner004e2502004-10-11 05:54:41 +0000639 }
640}
641
642/// OptimizeGlobalAddressOfMalloc - This function takes the specified global
643/// variable, and transforms the program as if it always contained the result of
644/// the specified malloc. Because it is always the result of the specified
645/// malloc, there is no reason to actually DO the malloc. Instead, turn the
646/// malloc into a global, and any laods of GV as uses of the new global.
647static GlobalVariable *OptimizeGlobalAddressOfMalloc(GlobalVariable *GV,
648 MallocInst *MI) {
649 DEBUG(std::cerr << "PROMOTING MALLOC GLOBAL: " << *GV << " MALLOC = " <<*MI);
650 ConstantInt *NElements = cast<ConstantInt>(MI->getArraySize());
651
652 if (NElements->getRawValue() != 1) {
653 // If we have an array allocation, transform it to a single element
654 // allocation to make the code below simpler.
655 Type *NewTy = ArrayType::get(MI->getAllocatedType(),
Chris Lattner46fa04b2005-01-08 19:45:31 +0000656 (unsigned)NElements->getRawValue());
Chris Lattner004e2502004-10-11 05:54:41 +0000657 MallocInst *NewMI =
658 new MallocInst(NewTy, Constant::getNullValue(Type::UIntTy),
659 MI->getName(), MI);
660 std::vector<Value*> Indices;
661 Indices.push_back(Constant::getNullValue(Type::IntTy));
662 Indices.push_back(Indices[0]);
663 Value *NewGEP = new GetElementPtrInst(NewMI, Indices,
664 NewMI->getName()+".el0", MI);
665 MI->replaceAllUsesWith(NewGEP);
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000666 MI->eraseFromParent();
Chris Lattner004e2502004-10-11 05:54:41 +0000667 MI = NewMI;
668 }
669
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000670 // Create the new global variable. The contents of the malloc'd memory is
671 // undefined, so initialize with an undef value.
672 Constant *Init = UndefValue::get(MI->getAllocatedType());
Chris Lattner004e2502004-10-11 05:54:41 +0000673 GlobalVariable *NewGV = new GlobalVariable(MI->getAllocatedType(), false,
674 GlobalValue::InternalLinkage, Init,
675 GV->getName()+".body");
676 GV->getParent()->getGlobalList().insert(GV, NewGV);
677
678 // Anything that used the malloc now uses the global directly.
679 MI->replaceAllUsesWith(NewGV);
Chris Lattner004e2502004-10-11 05:54:41 +0000680
681 Constant *RepValue = NewGV;
682 if (NewGV->getType() != GV->getType()->getElementType())
683 RepValue = ConstantExpr::getCast(RepValue, GV->getType()->getElementType());
684
Chris Lattnerfe9abf92004-10-22 06:43:28 +0000685 // If there is a comparison against null, we will insert a global bool to
686 // keep track of whether the global was initialized yet or not.
Chris Lattner3b181392004-12-02 06:25:58 +0000687 GlobalVariable *InitBool =
688 new GlobalVariable(Type::BoolTy, false, GlobalValue::InternalLinkage,
689 ConstantBool::False, GV->getName()+".init");
690 bool InitBoolUsed = false;
Chris Lattnerfe9abf92004-10-22 06:43:28 +0000691
Chris Lattner004e2502004-10-11 05:54:41 +0000692 // Loop over all uses of GV, processing them in turn.
Chris Lattner3b181392004-12-02 06:25:58 +0000693 std::vector<StoreInst*> Stores;
Chris Lattner004e2502004-10-11 05:54:41 +0000694 while (!GV->use_empty())
695 if (LoadInst *LI = dyn_cast<LoadInst>(GV->use_back())) {
Chris Lattnerfe9abf92004-10-22 06:43:28 +0000696 while (!LI->use_empty()) {
Chris Lattnerd6a44922005-02-01 01:23:31 +0000697 Use &LoadUse = LI->use_begin().getUse();
Chris Lattnerfe9abf92004-10-22 06:43:28 +0000698 if (!isa<SetCondInst>(LoadUse.getUser()))
699 LoadUse = RepValue;
700 else {
Chris Lattnerfe9abf92004-10-22 06:43:28 +0000701 // Replace the setcc X, 0 with a use of the bool value.
702 SetCondInst *SCI = cast<SetCondInst>(LoadUse.getUser());
703 Value *LV = new LoadInst(InitBool, InitBool->getName()+".val", SCI);
Chris Lattner3b181392004-12-02 06:25:58 +0000704 InitBoolUsed = true;
Chris Lattnerfe9abf92004-10-22 06:43:28 +0000705 switch (SCI->getOpcode()) {
706 default: assert(0 && "Unknown opcode!");
707 case Instruction::SetLT:
708 LV = ConstantBool::False; // X < null -> always false
709 break;
710 case Instruction::SetEQ:
711 case Instruction::SetLE:
712 LV = BinaryOperator::createNot(LV, "notinit", SCI);
713 break;
714 case Instruction::SetNE:
715 case Instruction::SetGE:
716 case Instruction::SetGT:
717 break; // no change.
718 }
719 SCI->replaceAllUsesWith(LV);
720 SCI->eraseFromParent();
721 }
722 }
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000723 LI->eraseFromParent();
Chris Lattner004e2502004-10-11 05:54:41 +0000724 } else {
725 StoreInst *SI = cast<StoreInst>(GV->use_back());
Chris Lattner3b181392004-12-02 06:25:58 +0000726 // The global is initialized when the store to it occurs.
727 new StoreInst(ConstantBool::True, InitBool, SI);
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000728 SI->eraseFromParent();
Chris Lattner004e2502004-10-11 05:54:41 +0000729 }
730
Chris Lattner3b181392004-12-02 06:25:58 +0000731 // If the initialization boolean was used, insert it, otherwise delete it.
732 if (!InitBoolUsed) {
733 while (!InitBool->use_empty()) // Delete initializations
734 cast<Instruction>(InitBool->use_back())->eraseFromParent();
735 delete InitBool;
736 } else
737 GV->getParent()->getGlobalList().insert(GV, InitBool);
738
739
Chris Lattnerfe9abf92004-10-22 06:43:28 +0000740 // Now the GV is dead, nuke it and the malloc.
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000741 GV->eraseFromParent();
Chris Lattnerfe9abf92004-10-22 06:43:28 +0000742 MI->eraseFromParent();
Chris Lattner004e2502004-10-11 05:54:41 +0000743
744 // To further other optimizations, loop over all users of NewGV and try to
745 // constant prop them. This will promote GEP instructions with constant
746 // indices into GEP constant-exprs, which will allow global-opt to hack on it.
747 ConstantPropUsersOf(NewGV);
748 if (RepValue != NewGV)
749 ConstantPropUsersOf(RepValue);
750
751 return NewGV;
752}
Chris Lattnere42eb312004-10-10 23:14:11 +0000753
Chris Lattnerc0677c02004-12-02 07:11:07 +0000754/// ValueIsOnlyUsedLocallyOrStoredToOneGlobal - Scan the use-list of V checking
755/// to make sure that there are no complex uses of V. We permit simple things
756/// like dereferencing the pointer, but not storing through the address, unless
757/// it is to the specified global.
758static bool ValueIsOnlyUsedLocallyOrStoredToOneGlobal(Instruction *V,
759 GlobalVariable *GV) {
760 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;++UI)
761 if (isa<LoadInst>(*UI) || isa<SetCondInst>(*UI)) {
762 // Fine, ignore.
763 } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
764 if (SI->getOperand(0) == V && SI->getOperand(1) != GV)
765 return false; // Storing the pointer itself... bad.
766 // Otherwise, storing through it, or storing into GV... fine.
767 } else if (isa<GetElementPtrInst>(*UI) || isa<SelectInst>(*UI)) {
768 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(cast<Instruction>(*UI),GV))
769 return false;
770 } else {
771 return false;
772 }
773 return true;
774
775}
776
Chris Lattner09a52722004-10-09 21:48:45 +0000777// OptimizeOnceStoredGlobal - Try to optimize globals based on the knowledge
778// that only one value (besides its initializer) is ever stored to the global.
Chris Lattner004e2502004-10-11 05:54:41 +0000779static bool OptimizeOnceStoredGlobal(GlobalVariable *GV, Value *StoredOnceVal,
780 Module::giterator &GVI, TargetData &TD) {
Chris Lattner09a52722004-10-09 21:48:45 +0000781 if (CastInst *CI = dyn_cast<CastInst>(StoredOnceVal))
782 StoredOnceVal = CI->getOperand(0);
783 else if (GetElementPtrInst *GEPI =dyn_cast<GetElementPtrInst>(StoredOnceVal)){
Chris Lattnere42eb312004-10-10 23:14:11 +0000784 // "getelementptr Ptr, 0, 0, 0" is really just a cast.
Chris Lattner09a52722004-10-09 21:48:45 +0000785 bool IsJustACast = true;
786 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
787 if (!isa<Constant>(GEPI->getOperand(i)) ||
788 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
789 IsJustACast = false;
790 break;
791 }
792 if (IsJustACast)
793 StoredOnceVal = GEPI->getOperand(0);
794 }
795
Chris Lattnere42eb312004-10-10 23:14:11 +0000796 // If we are dealing with a pointer global that is initialized to null and
797 // only has one (non-null) value stored into it, then we can optimize any
798 // users of the loaded value (often calls and loads) that would trap if the
799 // value was null.
Chris Lattner09a52722004-10-09 21:48:45 +0000800 if (isa<PointerType>(GV->getInitializer()->getType()) &&
801 GV->getInitializer()->isNullValue()) {
Chris Lattnere42eb312004-10-10 23:14:11 +0000802 if (Constant *SOVC = dyn_cast<Constant>(StoredOnceVal)) {
803 if (GV->getInitializer()->getType() != SOVC->getType())
804 SOVC = ConstantExpr::getCast(SOVC, GV->getInitializer()->getType());
805
806 // Optimize away any trapping uses of the loaded value.
807 if (OptimizeAwayTrappingUsesOfLoads(GV, SOVC))
Chris Lattner604ed7a2004-10-10 17:07:12 +0000808 return true;
Chris Lattner004e2502004-10-11 05:54:41 +0000809 } else if (MallocInst *MI = dyn_cast<MallocInst>(StoredOnceVal)) {
810 // If we have a global that is only initialized with a fixed size malloc,
811 // and if all users of the malloc trap, and if the malloc'd address is not
812 // put anywhere else, transform the program to use global memory instead
813 // of malloc'd memory. This eliminates dynamic allocation (good) and
814 // exposes the resultant global to further GlobalOpt (even better). Note
815 // that we restrict this transformation to only working on small
816 // allocations (2048 bytes currently), as we don't want to introduce a 16M
817 // global or something.
818 if (ConstantInt *NElements = dyn_cast<ConstantInt>(MI->getArraySize()))
819 if (MI->getAllocatedType()->isSized() &&
820 NElements->getRawValue()*
821 TD.getTypeSize(MI->getAllocatedType()) < 2048 &&
Chris Lattnerc0677c02004-12-02 07:11:07 +0000822 AllUsesOfLoadedValueWillTrapIfNull(GV) &&
823 ValueIsOnlyUsedLocallyOrStoredToOneGlobal(MI, GV)) {
Chris Lattner004e2502004-10-11 05:54:41 +0000824 GVI = OptimizeGlobalAddressOfMalloc(GV, MI);
825 return true;
826 }
Chris Lattnere42eb312004-10-10 23:14:11 +0000827 }
Chris Lattner09a52722004-10-09 21:48:45 +0000828 }
Chris Lattner004e2502004-10-11 05:54:41 +0000829
Chris Lattner09a52722004-10-09 21:48:45 +0000830 return false;
831}
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000832
Chris Lattner40e4cec2004-12-12 05:53:50 +0000833/// ShrinkGlobalToBoolean - At this point, we have learned that the only two
834/// values ever stored into GV are its initializer and OtherVal.
835static void ShrinkGlobalToBoolean(GlobalVariable *GV, Constant *OtherVal) {
836 // Create the new global, initializing it to false.
837 GlobalVariable *NewGV = new GlobalVariable(Type::BoolTy, false,
838 GlobalValue::InternalLinkage, ConstantBool::False, GV->getName()+".b");
839 GV->getParent()->getGlobalList().insert(GV, NewGV);
840
841 Constant *InitVal = GV->getInitializer();
842 assert(InitVal->getType() != Type::BoolTy && "No reason to shrink to bool!");
843
844 // If initialized to zero and storing one into the global, we can use a cast
845 // instead of a select to synthesize the desired value.
846 bool IsOneZero = false;
847 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal))
848 IsOneZero = InitVal->isNullValue() && CI->equalsInt(1);
849
850 while (!GV->use_empty()) {
851 Instruction *UI = cast<Instruction>(GV->use_back());
852 if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
853 // Change the store into a boolean store.
854 bool StoringOther = SI->getOperand(0) == OtherVal;
855 // Only do this if we weren't storing a loaded value.
Chris Lattner745196a2004-12-12 19:34:41 +0000856 Value *StoreVal;
Chris Lattner40e4cec2004-12-12 05:53:50 +0000857 if (StoringOther || SI->getOperand(0) == InitVal)
Chris Lattner745196a2004-12-12 19:34:41 +0000858 StoreVal = ConstantBool::get(StoringOther);
859 else {
860 // Otherwise, we are storing a previously loaded copy. To do this,
861 // change the copy from copying the original value to just copying the
862 // bool.
863 Instruction *StoredVal = cast<Instruction>(SI->getOperand(0));
864
865 // If we're already replaced the input, StoredVal will be a cast or
866 // select instruction. If not, it will be a load of the original
867 // global.
868 if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
869 assert(LI->getOperand(0) == GV && "Not a copy!");
870 // Insert a new load, to preserve the saved value.
871 StoreVal = new LoadInst(NewGV, LI->getName()+".b", LI);
872 } else {
873 assert((isa<CastInst>(StoredVal) || isa<SelectInst>(StoredVal)) &&
874 "This is not a form that we understand!");
875 StoreVal = StoredVal->getOperand(0);
876 assert(isa<LoadInst>(StoreVal) && "Not a load of NewGV!");
877 }
878 }
879 new StoreInst(StoreVal, NewGV, SI);
880 } else if (!UI->use_empty()) {
Chris Lattner40e4cec2004-12-12 05:53:50 +0000881 // Change the load into a load of bool then a select.
882 LoadInst *LI = cast<LoadInst>(UI);
Chris Lattner745196a2004-12-12 19:34:41 +0000883
Chris Lattner40e4cec2004-12-12 05:53:50 +0000884 std::string Name = LI->getName(); LI->setName("");
885 LoadInst *NLI = new LoadInst(NewGV, Name+".b", LI);
886 Value *NSI;
887 if (IsOneZero)
888 NSI = new CastInst(NLI, LI->getType(), Name, LI);
889 else
890 NSI = new SelectInst(NLI, OtherVal, InitVal, Name, LI);
891 LI->replaceAllUsesWith(NSI);
892 }
893 UI->eraseFromParent();
894 }
895
896 GV->eraseFromParent();
897}
898
899
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000900/// ProcessInternalGlobal - Analyze the specified global variable and optimize
901/// it if possible. If we make a change, return true.
Chris Lattner004e2502004-10-11 05:54:41 +0000902bool GlobalOpt::ProcessInternalGlobal(GlobalVariable *GV,
903 Module::giterator &GVI) {
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000904 std::set<PHINode*> PHIUsers;
905 GlobalStatus GS;
906 PHIUsers.clear();
907 GV->removeDeadConstantUsers();
908
909 if (GV->use_empty()) {
910 DEBUG(std::cerr << "GLOBAL DEAD: " << *GV);
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000911 GV->eraseFromParent();
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000912 ++NumDeleted;
913 return true;
914 }
915
916 if (!AnalyzeGlobal(GV, GS, PHIUsers)) {
Alkis Evlogimenosc4a44c62005-02-10 18:36:30 +0000917 // If this is a first class global and has only one accessing function
918 // and this function is main (which we know is not recursive we can make
919 // this global a local variable) we replace the global with a local alloca
920 // in this function.
921 //
922 // NOTE: It doesn't make sense to promote non first class types since we
923 // are just replacing static memory to stack memory.
924 if (!GS.HasMultipleAccessingFunctions &&
925 GS.AccessingFunction &&
926 GV->getType()->getElementType()->isFirstClassType() &&
927 GS.AccessingFunction->getName() == "main" &&
928 GS.AccessingFunction->hasExternalLinkage()) {
929 DEBUG(std::cerr << "LOCALIZING GLOBAL: " << *GV);
930 Instruction* FirstI = GS.AccessingFunction->getEntryBlock().begin();
931 const Type* ElemTy = GV->getType()->getElementType();
932 AllocaInst* Alloca = new AllocaInst(ElemTy, NULL, GV->getName(), FirstI);
933 if (!isa<UndefValue>(GV->getInitializer()))
934 new StoreInst(GV->getInitializer(), Alloca, FirstI);
935
936 GV->replaceAllUsesWith(Alloca);
937 GV->eraseFromParent();
938 ++NumLocalized;
939 return true;
940 }
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000941 // If the global is never loaded (but may be stored to), it is dead.
942 // Delete it now.
943 if (!GS.isLoaded) {
944 DEBUG(std::cerr << "GLOBAL NEVER LOADED: " << *GV);
Chris Lattnerf369b382004-10-09 03:32:52 +0000945
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000946 // Delete any stores we can find to the global. We may not be able to
947 // make it completely dead though.
Chris Lattnercb9f1522004-10-10 16:43:46 +0000948 bool Changed = CleanupConstantGlobalUsers(GV, GV->getInitializer());
Chris Lattnerf369b382004-10-09 03:32:52 +0000949
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000950 // If the global is dead now, delete it.
951 if (GV->use_empty()) {
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000952 GV->eraseFromParent();
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000953 ++NumDeleted;
Chris Lattnerf369b382004-10-09 03:32:52 +0000954 Changed = true;
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000955 }
Chris Lattnerf369b382004-10-09 03:32:52 +0000956 return Changed;
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000957
958 } else if (GS.StoredType <= GlobalStatus::isInitializerStored) {
959 DEBUG(std::cerr << "MARKING CONSTANT: " << *GV);
960 GV->setConstant(true);
961
962 // Clean up any obviously simplifiable users now.
963 CleanupConstantGlobalUsers(GV, GV->getInitializer());
964
965 // If the global is dead now, just nuke it.
966 if (GV->use_empty()) {
967 DEBUG(std::cerr << " *** Marking constant allowed us to simplify "
968 "all users and delete global!\n");
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000969 GV->eraseFromParent();
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000970 ++NumDeleted;
971 }
972
973 ++NumMarked;
974 return true;
975 } else if (!GS.isNotSuitableForSRA &&
976 !GV->getInitializer()->getType()->isFirstClassType()) {
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000977 if (GlobalVariable *FirstNewGV = SRAGlobal(GV)) {
978 GVI = FirstNewGV; // Don't skip the newly produced globals!
979 return true;
980 }
Chris Lattner09a52722004-10-09 21:48:45 +0000981 } else if (GS.StoredType == GlobalStatus::isStoredOnce) {
Chris Lattner40e4cec2004-12-12 05:53:50 +0000982 // If the initial value for the global was an undef value, and if only
983 // one other value was stored into it, we can just change the
984 // initializer to be an undef value, then delete all stores to the
985 // global. This allows us to mark it constant.
986 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
987 if (isa<UndefValue>(GV->getInitializer())) {
988 // Change the initial value here.
989 GV->setInitializer(SOVConstant);
990
991 // Clean up any obviously simplifiable users now.
992 CleanupConstantGlobalUsers(GV, GV->getInitializer());
993
994 if (GV->use_empty()) {
995 DEBUG(std::cerr << " *** Substituting initializer allowed us to "
996 "simplify all users and delete global!\n");
997 GV->eraseFromParent();
998 ++NumDeleted;
999 } else {
1000 GVI = GV;
1001 }
1002 ++NumSubstitute;
1003 return true;
Chris Lattner8e71c6a2004-10-16 18:09:00 +00001004 }
Chris Lattner8e71c6a2004-10-16 18:09:00 +00001005
Chris Lattner09a52722004-10-09 21:48:45 +00001006 // Try to optimize globals based on the knowledge that only one value
1007 // (besides its initializer) is ever stored to the global.
Chris Lattner004e2502004-10-11 05:54:41 +00001008 if (OptimizeOnceStoredGlobal(GV, GS.StoredOnceValue, GVI,
1009 getAnalysis<TargetData>()))
Chris Lattner09a52722004-10-09 21:48:45 +00001010 return true;
Chris Lattner40e4cec2004-12-12 05:53:50 +00001011
1012 // Otherwise, if the global was not a boolean, we can shrink it to be a
1013 // boolean.
1014 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
Chris Lattner1cbd5be2004-12-12 06:03:06 +00001015 if (GV->getType()->getElementType() != Type::BoolTy &&
1016 !GV->getType()->getElementType()->isFloatingPoint()) {
Chris Lattner40e4cec2004-12-12 05:53:50 +00001017 DEBUG(std::cerr << " *** SHRINKING TO BOOL: " << *GV);
1018 ShrinkGlobalToBoolean(GV, SOVConstant);
1019 ++NumShrunkToBool;
1020 return true;
1021 }
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001022 }
1023 }
1024 return false;
1025}
1026
1027
Chris Lattner25db5802004-10-07 04:16:33 +00001028bool GlobalOpt::runOnModule(Module &M) {
1029 bool Changed = false;
1030
1031 // As a prepass, delete functions that are trivially dead.
1032 bool LocalChange = true;
1033 while (LocalChange) {
1034 LocalChange = false;
1035 for (Module::iterator FI = M.begin(), E = M.end(); FI != E; ) {
1036 Function *F = FI++;
1037 F->removeDeadConstantUsers();
Chris Lattner5d33e8e2004-10-14 19:53:50 +00001038 if (F->use_empty() && (F->hasInternalLinkage() ||
1039 F->hasLinkOnceLinkage())) {
Chris Lattner25db5802004-10-07 04:16:33 +00001040 M.getFunctionList().erase(F);
1041 LocalChange = true;
1042 ++NumFnDeleted;
1043 }
1044 }
1045 Changed |= LocalChange;
1046 }
1047
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001048 LocalChange = true;
1049 while (LocalChange) {
1050 LocalChange = false;
1051 for (Module::giterator GVI = M.gbegin(), E = M.gend(); GVI != E;) {
1052 GlobalVariable *GV = GVI++;
1053 if (!GV->isConstant() && GV->hasInternalLinkage() &&
1054 GV->hasInitializer())
1055 LocalChange |= ProcessInternalGlobal(GV, GVI);
Chris Lattner25db5802004-10-07 04:16:33 +00001056 }
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001057 Changed |= LocalChange;
Chris Lattner25db5802004-10-07 04:16:33 +00001058 }
1059 return Changed;
1060}