blob: 7b6f649a0acc09912e0337bc1436a0b5008845e8 [file] [log] [blame]
Chris Lattner7a90b682004-10-07 04:16:33 +00001//===- GlobalOpt.cpp - Optimize Global Variables --------------------------===//
Chris Lattner079236d2004-02-25 21:34:36 +00002//
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//
Chris Lattner7a90b682004-10-07 04:16:33 +000010// 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.
Chris Lattner079236d2004-02-25 21:34:36 +000013//
14//===----------------------------------------------------------------------===//
15
Chris Lattner7a90b682004-10-07 04:16:33 +000016#define DEBUG_TYPE "globalopt"
Chris Lattner079236d2004-02-25 21:34:36 +000017#include "llvm/Transforms/IPO.h"
18#include "llvm/Constants.h"
Chris Lattner7a90b682004-10-07 04:16:33 +000019#include "llvm/DerivedTypes.h"
Chris Lattner7d90a272004-02-27 18:09:25 +000020#include "llvm/Instructions.h"
Chris Lattner35c81b02005-02-27 18:58:52 +000021#include "llvm/IntrinsicInst.h"
Chris Lattner079236d2004-02-25 21:34:36 +000022#include "llvm/Module.h"
23#include "llvm/Pass.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000024#include "llvm/Support/Debug.h"
Chris Lattner30ba5692004-10-11 05:54:41 +000025#include "llvm/Target/TargetData.h"
26#include "llvm/Transforms/Utils/Local.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000027#include "llvm/ADT/Statistic.h"
Chris Lattner670c8892004-10-08 17:32:09 +000028#include "llvm/ADT/StringExtras.h"
Chris Lattner77a2a9d2004-08-14 20:57:17 +000029#include <set>
Chris Lattnere47ba742004-10-06 20:57:02 +000030#include <algorithm>
Chris Lattner079236d2004-02-25 21:34:36 +000031using namespace llvm;
32
33namespace {
Chris Lattner670c8892004-10-08 17:32:09 +000034 Statistic<> NumMarked ("globalopt", "Number of globals marked constant");
35 Statistic<> NumSRA ("globalopt", "Number of aggregate globals broken "
36 "into scalars");
Chris Lattner7a7ed022004-10-16 18:09:00 +000037 Statistic<> NumSubstitute("globalopt",
38 "Number of globals with initializers stored into them");
Chris Lattner670c8892004-10-08 17:32:09 +000039 Statistic<> NumDeleted ("globalopt", "Number of globals deleted");
Chris Lattner7a90b682004-10-07 04:16:33 +000040 Statistic<> NumFnDeleted("globalopt", "Number of functions deleted");
Chris Lattner708148e2004-10-10 23:14:11 +000041 Statistic<> NumGlobUses ("globalopt", "Number of global uses devirtualized");
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +000042 Statistic<> NumLocalized("globalopt", "Number of globals localized");
Chris Lattner96a86b22004-12-12 05:53:50 +000043 Statistic<> NumShrunkToBool("globalopt",
44 "Number of global vars shrunk to booleans");
Chris Lattner079236d2004-02-25 21:34:36 +000045
Chris Lattner7a90b682004-10-07 04:16:33 +000046 struct GlobalOpt : public ModulePass {
Chris Lattner30ba5692004-10-11 05:54:41 +000047 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
48 AU.addRequired<TargetData>();
49 }
50
Chris Lattnerb12914b2004-09-20 04:48:05 +000051 bool runOnModule(Module &M);
Chris Lattner30ba5692004-10-11 05:54:41 +000052
53 private:
Chris Lattnere4d5c442005-03-15 04:54:21 +000054 bool ProcessInternalGlobal(GlobalVariable *GV, Module::global_iterator &GVI);
Chris Lattner079236d2004-02-25 21:34:36 +000055 };
56
Chris Lattner7a90b682004-10-07 04:16:33 +000057 RegisterOpt<GlobalOpt> X("globalopt", "Global Variable Optimizer");
Chris Lattner079236d2004-02-25 21:34:36 +000058}
59
Chris Lattner7a90b682004-10-07 04:16:33 +000060ModulePass *llvm::createGlobalOptimizerPass() { return new GlobalOpt(); }
Chris Lattner079236d2004-02-25 21:34:36 +000061
Chris Lattner7a90b682004-10-07 04:16:33 +000062/// GlobalStatus - As we analyze each global, keep track of some information
63/// about it. If we find out that the address of the global is taken, none of
Chris Lattnercf4d2a52004-10-07 21:30:30 +000064/// this info will be accurate.
Chris Lattner7a90b682004-10-07 04:16:33 +000065struct GlobalStatus {
Chris Lattnercf4d2a52004-10-07 21:30:30 +000066 /// isLoaded - True if the global is ever loaded. If the global isn't ever
67 /// loaded it can be deleted.
Chris Lattner7a90b682004-10-07 04:16:33 +000068 bool isLoaded;
Chris Lattnercf4d2a52004-10-07 21:30:30 +000069
70 /// StoredType - Keep track of what stores to the global look like.
71 ///
Chris Lattner7a90b682004-10-07 04:16:33 +000072 enum StoredType {
Chris Lattnercf4d2a52004-10-07 21:30:30 +000073 /// NotStored - There is no store to this global. It can thus be marked
74 /// constant.
75 NotStored,
76
77 /// isInitializerStored - This global is stored to, but the only thing
78 /// stored is the constant it was initialized with. This is only tracked
79 /// for scalar globals.
80 isInitializerStored,
81
82 /// isStoredOnce - This global is stored to, but only its initializer and
83 /// one other value is ever stored to it. If this global isStoredOnce, we
84 /// track the value stored to it in StoredOnceValue below. This is only
85 /// tracked for scalar globals.
86 isStoredOnce,
87
88 /// isStored - This global is stored to by multiple values or something else
89 /// that we cannot track.
90 isStored
Chris Lattner7a90b682004-10-07 04:16:33 +000091 } StoredType;
Chris Lattnercf4d2a52004-10-07 21:30:30 +000092
93 /// StoredOnceValue - If only one value (besides the initializer constant) is
94 /// ever stored to this global, keep track of what value it is.
95 Value *StoredOnceValue;
96
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +000097 // AccessingFunction/HasMultipleAccessingFunctions - These start out
98 // null/false. When the first accessing function is noticed, it is recorded.
99 // When a second different accessing function is noticed,
100 // HasMultipleAccessingFunctions is set to true.
101 Function *AccessingFunction;
102 bool HasMultipleAccessingFunctions;
103
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000104 /// isNotSuitableForSRA - Keep track of whether any SRA preventing users of
105 /// the global exist. Such users include GEP instruction with variable
106 /// indexes, and non-gep/load/store users like constant expr casts.
Chris Lattner7a90b682004-10-07 04:16:33 +0000107 bool isNotSuitableForSRA;
Chris Lattner9ce30002004-07-20 03:58:07 +0000108
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000109 GlobalStatus() : isLoaded(false), StoredType(NotStored), StoredOnceValue(0),
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +0000110 AccessingFunction(0), HasMultipleAccessingFunctions(false),
Chris Lattner7a90b682004-10-07 04:16:33 +0000111 isNotSuitableForSRA(false) {}
112};
Chris Lattnere47ba742004-10-06 20:57:02 +0000113
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000114
115
116/// ConstantIsDead - Return true if the specified constant is (transitively)
117/// dead. The constant may be used by other constants (e.g. constant arrays and
118/// constant exprs) as long as they are dead, but it cannot be used by anything
119/// else.
120static bool ConstantIsDead(Constant *C) {
121 if (isa<GlobalValue>(C)) return false;
122
123 for (Value::use_iterator UI = C->use_begin(), E = C->use_end(); UI != E; ++UI)
124 if (Constant *CU = dyn_cast<Constant>(*UI)) {
125 if (!ConstantIsDead(CU)) return false;
126 } else
127 return false;
128 return true;
129}
130
131
Chris Lattner7a90b682004-10-07 04:16:33 +0000132/// AnalyzeGlobal - Look at all uses of the global and fill in the GlobalStatus
133/// structure. If the global has its address taken, return true to indicate we
134/// can't do anything with it.
Chris Lattner079236d2004-02-25 21:34:36 +0000135///
Chris Lattner7a90b682004-10-07 04:16:33 +0000136static bool AnalyzeGlobal(Value *V, GlobalStatus &GS,
137 std::set<PHINode*> &PHIUsers) {
Chris Lattner079236d2004-02-25 21:34:36 +0000138 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
Chris Lattner96940cb2004-07-18 19:56:20 +0000139 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(*UI)) {
Chris Lattner7a90b682004-10-07 04:16:33 +0000140 if (AnalyzeGlobal(CE, GS, PHIUsers)) return true;
141 if (CE->getOpcode() != Instruction::GetElementPtr)
142 GS.isNotSuitableForSRA = true;
Chris Lattner670c8892004-10-08 17:32:09 +0000143 else if (!GS.isNotSuitableForSRA) {
144 // Check to see if this ConstantExpr GEP is SRA'able. In particular, we
145 // don't like < 3 operand CE's, and we don't like non-constant integer
146 // indices.
147 if (CE->getNumOperands() < 3 || !CE->getOperand(1)->isNullValue())
148 GS.isNotSuitableForSRA = true;
149 else {
150 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
151 if (!isa<ConstantInt>(CE->getOperand(i))) {
152 GS.isNotSuitableForSRA = true;
153 break;
154 }
155 }
156 }
157
Chris Lattner079236d2004-02-25 21:34:36 +0000158 } else if (Instruction *I = dyn_cast<Instruction>(*UI)) {
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +0000159 if (!GS.HasMultipleAccessingFunctions) {
160 Function *F = I->getParent()->getParent();
161 if (GS.AccessingFunction == 0)
162 GS.AccessingFunction = F;
163 else if (GS.AccessingFunction != F)
164 GS.HasMultipleAccessingFunctions = true;
165 }
Chris Lattner7a90b682004-10-07 04:16:33 +0000166 if (isa<LoadInst>(I)) {
167 GS.isLoaded = true;
168 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Chris Lattner36025492004-10-07 06:01:25 +0000169 // Don't allow a store OF the address, only stores TO the address.
170 if (SI->getOperand(0) == V) return true;
171
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000172 // If this is a direct store to the global (i.e., the global is a scalar
173 // value, not an aggregate), keep more specific information about
174 // stores.
175 if (GS.StoredType != GlobalStatus::isStored)
176 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(SI->getOperand(1))){
Chris Lattnerbd38edf2004-11-14 20:50:30 +0000177 Value *StoredVal = SI->getOperand(0);
178 if (StoredVal == GV->getInitializer()) {
179 if (GS.StoredType < GlobalStatus::isInitializerStored)
180 GS.StoredType = GlobalStatus::isInitializerStored;
181 } else if (isa<LoadInst>(StoredVal) &&
182 cast<LoadInst>(StoredVal)->getOperand(0) == GV) {
183 // G = G
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000184 if (GS.StoredType < GlobalStatus::isInitializerStored)
185 GS.StoredType = GlobalStatus::isInitializerStored;
186 } else if (GS.StoredType < GlobalStatus::isStoredOnce) {
187 GS.StoredType = GlobalStatus::isStoredOnce;
Chris Lattnerbd38edf2004-11-14 20:50:30 +0000188 GS.StoredOnceValue = StoredVal;
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000189 } else if (GS.StoredType == GlobalStatus::isStoredOnce &&
Chris Lattnerbd38edf2004-11-14 20:50:30 +0000190 GS.StoredOnceValue == StoredVal) {
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000191 // noop.
192 } else {
193 GS.StoredType = GlobalStatus::isStored;
194 }
195 } else {
Chris Lattner7a90b682004-10-07 04:16:33 +0000196 GS.StoredType = GlobalStatus::isStored;
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000197 }
Chris Lattner35c81b02005-02-27 18:58:52 +0000198 } else if (isa<GetElementPtrInst>(I)) {
Chris Lattner7a90b682004-10-07 04:16:33 +0000199 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Chris Lattner30ba5692004-10-11 05:54:41 +0000200
201 // If the first two indices are constants, this can be SRA'd.
202 if (isa<GlobalVariable>(I->getOperand(0))) {
203 if (I->getNumOperands() < 3 || !isa<Constant>(I->getOperand(1)) ||
204 !cast<Constant>(I->getOperand(1))->isNullValue() ||
205 !isa<ConstantInt>(I->getOperand(2)))
206 GS.isNotSuitableForSRA = true;
207 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(I->getOperand(0))){
208 if (CE->getOpcode() != Instruction::GetElementPtr ||
209 CE->getNumOperands() < 3 || I->getNumOperands() < 2 ||
210 !isa<Constant>(I->getOperand(0)) ||
211 !cast<Constant>(I->getOperand(0))->isNullValue())
212 GS.isNotSuitableForSRA = true;
213 } else {
214 GS.isNotSuitableForSRA = true;
215 }
Chris Lattner35c81b02005-02-27 18:58:52 +0000216 } else if (isa<SelectInst>(I)) {
Chris Lattner7a90b682004-10-07 04:16:33 +0000217 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
218 GS.isNotSuitableForSRA = true;
219 } else if (PHINode *PN = dyn_cast<PHINode>(I)) {
220 // PHI nodes we can check just like select or GEP instructions, but we
221 // have to be careful about infinite recursion.
222 if (PHIUsers.insert(PN).second) // Not already visited.
223 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
224 GS.isNotSuitableForSRA = true;
225 } else if (isa<SetCondInst>(I)) {
226 GS.isNotSuitableForSRA = true;
Chris Lattner35c81b02005-02-27 18:58:52 +0000227 } else if (isa<MemCpyInst>(I) || isa<MemMoveInst>(I)) {
228 if (I->getOperand(1) == V)
229 GS.StoredType = GlobalStatus::isStored;
230 if (I->getOperand(2) == V)
231 GS.isLoaded = true;
232 GS.isNotSuitableForSRA = true;
233 } else if (isa<MemSetInst>(I)) {
234 assert(I->getOperand(1) == V && "Memset only takes one pointer!");
235 GS.StoredType = GlobalStatus::isStored;
236 GS.isNotSuitableForSRA = true;
Chris Lattner7a90b682004-10-07 04:16:33 +0000237 } else {
238 return true; // Any other non-load instruction might take address!
Chris Lattner9ce30002004-07-20 03:58:07 +0000239 }
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000240 } else if (Constant *C = dyn_cast<Constant>(*UI)) {
241 // We might have a dead and dangling constant hanging off of here.
242 if (!ConstantIsDead(C))
243 return true;
Chris Lattner079236d2004-02-25 21:34:36 +0000244 } else {
245 // Otherwise must be a global or some other user.
246 return true;
247 }
248
249 return false;
250}
251
Chris Lattner670c8892004-10-08 17:32:09 +0000252static Constant *getAggregateConstantElement(Constant *Agg, Constant *Idx) {
253 ConstantInt *CI = dyn_cast<ConstantInt>(Idx);
254 if (!CI) return 0;
Chris Lattner4d0801b2005-01-08 19:45:31 +0000255 unsigned IdxV = (unsigned)CI->getRawValue();
Chris Lattner7a90b682004-10-07 04:16:33 +0000256
Chris Lattner670c8892004-10-08 17:32:09 +0000257 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Agg)) {
258 if (IdxV < CS->getNumOperands()) return CS->getOperand(IdxV);
259 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Agg)) {
260 if (IdxV < CA->getNumOperands()) return CA->getOperand(IdxV);
261 } else if (ConstantPacked *CP = dyn_cast<ConstantPacked>(Agg)) {
262 if (IdxV < CP->getNumOperands()) return CP->getOperand(IdxV);
Chris Lattner7a7ed022004-10-16 18:09:00 +0000263 } else if (isa<ConstantAggregateZero>(Agg)) {
Chris Lattner670c8892004-10-08 17:32:09 +0000264 if (const StructType *STy = dyn_cast<StructType>(Agg->getType())) {
265 if (IdxV < STy->getNumElements())
266 return Constant::getNullValue(STy->getElementType(IdxV));
267 } else if (const SequentialType *STy =
268 dyn_cast<SequentialType>(Agg->getType())) {
269 return Constant::getNullValue(STy->getElementType());
270 }
Chris Lattner7a7ed022004-10-16 18:09:00 +0000271 } else if (isa<UndefValue>(Agg)) {
272 if (const StructType *STy = dyn_cast<StructType>(Agg->getType())) {
273 if (IdxV < STy->getNumElements())
274 return UndefValue::get(STy->getElementType(IdxV));
275 } else if (const SequentialType *STy =
276 dyn_cast<SequentialType>(Agg->getType())) {
277 return UndefValue::get(STy->getElementType());
278 }
Chris Lattner670c8892004-10-08 17:32:09 +0000279 }
280 return 0;
281}
Chris Lattner7a90b682004-10-07 04:16:33 +0000282
283static Constant *TraverseGEPInitializer(User *GEP, Constant *Init) {
Chris Lattner35c81b02005-02-27 18:58:52 +0000284 if (Init == 0) return 0;
Chris Lattner7a90b682004-10-07 04:16:33 +0000285 if (GEP->getNumOperands() == 1 ||
286 !isa<Constant>(GEP->getOperand(1)) ||
287 !cast<Constant>(GEP->getOperand(1))->isNullValue())
288 return 0;
289
290 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i) {
291 ConstantInt *Idx = dyn_cast<ConstantInt>(GEP->getOperand(i));
292 if (!Idx) return 0;
Chris Lattner670c8892004-10-08 17:32:09 +0000293 Init = getAggregateConstantElement(Init, Idx);
294 if (Init == 0) return 0;
Chris Lattner7a90b682004-10-07 04:16:33 +0000295 }
296 return Init;
297}
298
Chris Lattnere47ba742004-10-06 20:57:02 +0000299/// CleanupConstantGlobalUsers - We just marked GV constant. Loop over all
300/// users of the global, cleaning up the obvious ones. This is largely just a
Chris Lattner031955d2004-10-10 16:43:46 +0000301/// quick scan over the use list to clean up the easy and obvious cruft. This
302/// returns true if it made a change.
303static bool CleanupConstantGlobalUsers(Value *V, Constant *Init) {
304 bool Changed = false;
Chris Lattner7a90b682004-10-07 04:16:33 +0000305 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;) {
306 User *U = *UI++;
307
308 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
Chris Lattner35c81b02005-02-27 18:58:52 +0000309 if (Init) {
310 // Replace the load with the initializer.
311 LI->replaceAllUsesWith(Init);
312 LI->eraseFromParent();
313 Changed = true;
314 }
Chris Lattner7a90b682004-10-07 04:16:33 +0000315 } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
Chris Lattnere47ba742004-10-06 20:57:02 +0000316 // Store must be unreachable or storing Init into the global.
Chris Lattner7a7ed022004-10-16 18:09:00 +0000317 SI->eraseFromParent();
Chris Lattner031955d2004-10-10 16:43:46 +0000318 Changed = true;
Chris Lattner7a90b682004-10-07 04:16:33 +0000319 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
320 if (CE->getOpcode() == Instruction::GetElementPtr) {
Chris Lattner35c81b02005-02-27 18:58:52 +0000321 Constant *SubInit = TraverseGEPInitializer(CE, Init);
322 Changed |= CleanupConstantGlobalUsers(CE, SubInit);
323 } else if (CE->getOpcode() == Instruction::Cast &&
324 isa<PointerType>(CE->getType())) {
325 // Pointer cast, delete any stores and memsets to the global.
326 Changed |= CleanupConstantGlobalUsers(CE, 0);
327 }
328
329 if (CE->use_empty()) {
330 CE->destroyConstant();
331 Changed = true;
Chris Lattner7a90b682004-10-07 04:16:33 +0000332 }
333 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
Chris Lattner35c81b02005-02-27 18:58:52 +0000334 Constant *SubInit = TraverseGEPInitializer(GEP, Init);
335 Changed |= CleanupConstantGlobalUsers(GEP, SubInit);
Chris Lattnerc4d81b02004-10-10 16:47:33 +0000336
Chris Lattner031955d2004-10-10 16:43:46 +0000337 if (GEP->use_empty()) {
Chris Lattner7a7ed022004-10-16 18:09:00 +0000338 GEP->eraseFromParent();
Chris Lattner031955d2004-10-10 16:43:46 +0000339 Changed = true;
340 }
Chris Lattner35c81b02005-02-27 18:58:52 +0000341 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U)) { // memset/cpy/mv
342 if (MI->getRawDest() == V) {
343 MI->eraseFromParent();
344 Changed = true;
345 }
346
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000347 } else if (Constant *C = dyn_cast<Constant>(U)) {
348 // If we have a chain of dead constantexprs or other things dangling from
349 // us, and if they are all dead, nuke them without remorse.
350 if (ConstantIsDead(C)) {
351 C->destroyConstant();
Chris Lattner35c81b02005-02-27 18:58:52 +0000352 // This could have invalidated UI, start over from scratch.
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000353 CleanupConstantGlobalUsers(V, Init);
Chris Lattner031955d2004-10-10 16:43:46 +0000354 return true;
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000355 }
Chris Lattnere47ba742004-10-06 20:57:02 +0000356 }
357 }
Chris Lattner031955d2004-10-10 16:43:46 +0000358 return Changed;
Chris Lattnere47ba742004-10-06 20:57:02 +0000359}
360
Chris Lattner670c8892004-10-08 17:32:09 +0000361/// SRAGlobal - Perform scalar replacement of aggregates on the specified global
362/// variable. This opens the door for other optimizations by exposing the
363/// behavior of the program in a more fine-grained way. We have determined that
364/// this transformation is safe already. We return the first global variable we
365/// insert so that the caller can reprocess it.
366static GlobalVariable *SRAGlobal(GlobalVariable *GV) {
367 assert(GV->hasInternalLinkage() && !GV->isConstant());
368 Constant *Init = GV->getInitializer();
369 const Type *Ty = Init->getType();
370
371 std::vector<GlobalVariable*> NewGlobals;
372 Module::GlobalListType &Globals = GV->getParent()->getGlobalList();
373
374 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
375 NewGlobals.reserve(STy->getNumElements());
376 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
377 Constant *In = getAggregateConstantElement(Init,
378 ConstantUInt::get(Type::UIntTy, i));
379 assert(In && "Couldn't get element of initializer?");
380 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(i), false,
381 GlobalVariable::InternalLinkage,
382 In, GV->getName()+"."+utostr(i));
383 Globals.insert(GV, NGV);
384 NewGlobals.push_back(NGV);
385 }
386 } else if (const SequentialType *STy = dyn_cast<SequentialType>(Ty)) {
387 unsigned NumElements = 0;
388 if (const ArrayType *ATy = dyn_cast<ArrayType>(STy))
389 NumElements = ATy->getNumElements();
390 else if (const PackedType *PTy = dyn_cast<PackedType>(STy))
391 NumElements = PTy->getNumElements();
392 else
393 assert(0 && "Unknown aggregate sequential type!");
394
Chris Lattner1f21ef12005-02-23 16:53:04 +0000395 if (NumElements > 16 && GV->hasNUsesOrMore(16))
Chris Lattnerd514d822005-02-01 01:23:31 +0000396 return 0; // It's not worth it.
Chris Lattner670c8892004-10-08 17:32:09 +0000397 NewGlobals.reserve(NumElements);
398 for (unsigned i = 0, e = NumElements; i != e; ++i) {
399 Constant *In = getAggregateConstantElement(Init,
400 ConstantUInt::get(Type::UIntTy, i));
401 assert(In && "Couldn't get element of initializer?");
402
403 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(), false,
404 GlobalVariable::InternalLinkage,
405 In, GV->getName()+"."+utostr(i));
406 Globals.insert(GV, NGV);
407 NewGlobals.push_back(NGV);
408 }
409 }
410
411 if (NewGlobals.empty())
412 return 0;
413
Chris Lattner30ba5692004-10-11 05:54:41 +0000414 DEBUG(std::cerr << "PERFORMING GLOBAL SRA ON: " << *GV);
415
Chris Lattner670c8892004-10-08 17:32:09 +0000416 Constant *NullInt = Constant::getNullValue(Type::IntTy);
417
418 // Loop over all of the uses of the global, replacing the constantexpr geps,
419 // with smaller constantexpr geps or direct references.
420 while (!GV->use_empty()) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000421 User *GEP = GV->use_back();
422 assert(((isa<ConstantExpr>(GEP) &&
423 cast<ConstantExpr>(GEP)->getOpcode()==Instruction::GetElementPtr)||
424 isa<GetElementPtrInst>(GEP)) && "NonGEP CE's are not SRAable!");
425
Chris Lattner670c8892004-10-08 17:32:09 +0000426 // Ignore the 1th operand, which has to be zero or else the program is quite
427 // broken (undefined). Get the 2nd operand, which is the structure or array
428 // index.
Chris Lattner4d0801b2005-01-08 19:45:31 +0000429 unsigned Val =
430 (unsigned)cast<ConstantInt>(GEP->getOperand(2))->getRawValue();
Chris Lattner670c8892004-10-08 17:32:09 +0000431 if (Val >= NewGlobals.size()) Val = 0; // Out of bound array access.
432
Chris Lattner30ba5692004-10-11 05:54:41 +0000433 Value *NewPtr = NewGlobals[Val];
Chris Lattner670c8892004-10-08 17:32:09 +0000434
435 // Form a shorter GEP if needed.
Chris Lattner30ba5692004-10-11 05:54:41 +0000436 if (GEP->getNumOperands() > 3)
437 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEP)) {
438 std::vector<Constant*> Idxs;
439 Idxs.push_back(NullInt);
440 for (unsigned i = 3, e = CE->getNumOperands(); i != e; ++i)
441 Idxs.push_back(CE->getOperand(i));
442 NewPtr = ConstantExpr::getGetElementPtr(cast<Constant>(NewPtr), Idxs);
443 } else {
444 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(GEP);
445 std::vector<Value*> Idxs;
446 Idxs.push_back(NullInt);
447 for (unsigned i = 3, e = GEPI->getNumOperands(); i != e; ++i)
448 Idxs.push_back(GEPI->getOperand(i));
449 NewPtr = new GetElementPtrInst(NewPtr, Idxs,
450 GEPI->getName()+"."+utostr(Val), GEPI);
451 }
452 GEP->replaceAllUsesWith(NewPtr);
453
454 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(GEP))
Chris Lattner7a7ed022004-10-16 18:09:00 +0000455 GEPI->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +0000456 else
457 cast<ConstantExpr>(GEP)->destroyConstant();
Chris Lattner670c8892004-10-08 17:32:09 +0000458 }
459
Chris Lattnere40e2d12004-10-08 20:25:55 +0000460 // Delete the old global, now that it is dead.
461 Globals.erase(GV);
Chris Lattner670c8892004-10-08 17:32:09 +0000462 ++NumSRA;
Chris Lattner30ba5692004-10-11 05:54:41 +0000463
464 // Loop over the new globals array deleting any globals that are obviously
465 // dead. This can arise due to scalarization of a structure or an array that
466 // has elements that are dead.
467 unsigned FirstGlobal = 0;
468 for (unsigned i = 0, e = NewGlobals.size(); i != e; ++i)
469 if (NewGlobals[i]->use_empty()) {
470 Globals.erase(NewGlobals[i]);
471 if (FirstGlobal == i) ++FirstGlobal;
472 }
473
474 return FirstGlobal != NewGlobals.size() ? NewGlobals[FirstGlobal] : 0;
Chris Lattner670c8892004-10-08 17:32:09 +0000475}
476
Chris Lattner9b34a612004-10-09 21:48:45 +0000477/// AllUsesOfValueWillTrapIfNull - Return true if all users of the specified
478/// value will trap if the value is dynamically null.
479static bool AllUsesOfValueWillTrapIfNull(Value *V) {
480 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
481 if (isa<LoadInst>(*UI)) {
482 // Will trap.
483 } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
484 if (SI->getOperand(0) == V) {
485 //std::cerr << "NONTRAPPING USE: " << **UI;
486 return false; // Storing the value.
487 }
488 } else if (CallInst *CI = dyn_cast<CallInst>(*UI)) {
489 if (CI->getOperand(0) != V) {
490 //std::cerr << "NONTRAPPING USE: " << **UI;
491 return false; // Not calling the ptr
492 }
493 } else if (InvokeInst *II = dyn_cast<InvokeInst>(*UI)) {
494 if (II->getOperand(0) != V) {
495 //std::cerr << "NONTRAPPING USE: " << **UI;
496 return false; // Not calling the ptr
497 }
498 } else if (CastInst *CI = dyn_cast<CastInst>(*UI)) {
499 if (!AllUsesOfValueWillTrapIfNull(CI)) return false;
500 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(*UI)) {
501 if (!AllUsesOfValueWillTrapIfNull(GEPI)) return false;
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000502 } else if (isa<SetCondInst>(*UI) &&
503 isa<ConstantPointerNull>(UI->getOperand(1))) {
504 // Ignore setcc X, null
Chris Lattner9b34a612004-10-09 21:48:45 +0000505 } else {
506 //std::cerr << "NONTRAPPING USE: " << **UI;
507 return false;
508 }
509 return true;
510}
511
512/// AllUsesOfLoadedValueWillTrapIfNull - Return true if all uses of any loads
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000513/// from GV will trap if the loaded value is null. Note that this also permits
514/// comparisons of the loaded value against null, as a special case.
Chris Lattner9b34a612004-10-09 21:48:45 +0000515static bool AllUsesOfLoadedValueWillTrapIfNull(GlobalVariable *GV) {
516 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI!=E; ++UI)
517 if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
518 if (!AllUsesOfValueWillTrapIfNull(LI))
519 return false;
520 } else if (isa<StoreInst>(*UI)) {
521 // Ignore stores to the global.
522 } else {
523 // We don't know or understand this user, bail out.
524 //std::cerr << "UNKNOWN USER OF GLOBAL!: " << **UI;
525 return false;
526 }
527
528 return true;
529}
530
Chris Lattner708148e2004-10-10 23:14:11 +0000531static bool OptimizeAwayTrappingUsesOfValue(Value *V, Constant *NewV) {
532 bool Changed = false;
533 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ) {
534 Instruction *I = cast<Instruction>(*UI++);
535 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
536 LI->setOperand(0, NewV);
537 Changed = true;
538 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
539 if (SI->getOperand(1) == V) {
540 SI->setOperand(1, NewV);
541 Changed = true;
542 }
543 } else if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
544 if (I->getOperand(0) == V) {
545 // Calling through the pointer! Turn into a direct call, but be careful
546 // that the pointer is not also being passed as an argument.
547 I->setOperand(0, NewV);
548 Changed = true;
549 bool PassedAsArg = false;
550 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i)
551 if (I->getOperand(i) == V) {
552 PassedAsArg = true;
553 I->setOperand(i, NewV);
554 }
555
556 if (PassedAsArg) {
557 // Being passed as an argument also. Be careful to not invalidate UI!
558 UI = V->use_begin();
559 }
560 }
561 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
562 Changed |= OptimizeAwayTrappingUsesOfValue(CI,
563 ConstantExpr::getCast(NewV, CI->getType()));
564 if (CI->use_empty()) {
565 Changed = true;
Chris Lattner7a7ed022004-10-16 18:09:00 +0000566 CI->eraseFromParent();
Chris Lattner708148e2004-10-10 23:14:11 +0000567 }
568 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
569 // Should handle GEP here.
570 std::vector<Constant*> Indices;
571 Indices.reserve(GEPI->getNumOperands()-1);
572 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
573 if (Constant *C = dyn_cast<Constant>(GEPI->getOperand(i)))
574 Indices.push_back(C);
575 else
576 break;
577 if (Indices.size() == GEPI->getNumOperands()-1)
578 Changed |= OptimizeAwayTrappingUsesOfValue(GEPI,
579 ConstantExpr::getGetElementPtr(NewV, Indices));
580 if (GEPI->use_empty()) {
581 Changed = true;
Chris Lattner7a7ed022004-10-16 18:09:00 +0000582 GEPI->eraseFromParent();
Chris Lattner708148e2004-10-10 23:14:11 +0000583 }
584 }
585 }
586
587 return Changed;
588}
589
590
591/// OptimizeAwayTrappingUsesOfLoads - The specified global has only one non-null
592/// value stored into it. If there are uses of the loaded value that would trap
593/// if the loaded value is dynamically null, then we know that they cannot be
594/// reachable with a null optimize away the load.
595static bool OptimizeAwayTrappingUsesOfLoads(GlobalVariable *GV, Constant *LV) {
596 std::vector<LoadInst*> Loads;
597 bool Changed = false;
598
599 // Replace all uses of loads with uses of uses of the stored value.
600 for (Value::use_iterator GUI = GV->use_begin(), E = GV->use_end();
601 GUI != E; ++GUI)
602 if (LoadInst *LI = dyn_cast<LoadInst>(*GUI)) {
603 Loads.push_back(LI);
604 Changed |= OptimizeAwayTrappingUsesOfValue(LI, LV);
605 } else {
606 assert(isa<StoreInst>(*GUI) && "Only expect load and stores!");
607 }
608
609 if (Changed) {
610 DEBUG(std::cerr << "OPTIMIZED LOADS FROM STORED ONCE POINTER: " << *GV);
611 ++NumGlobUses;
612 }
613
614 // Delete all of the loads we can, keeping track of whether we nuked them all!
615 bool AllLoadsGone = true;
616 while (!Loads.empty()) {
617 LoadInst *L = Loads.back();
618 if (L->use_empty()) {
Chris Lattner7a7ed022004-10-16 18:09:00 +0000619 L->eraseFromParent();
Chris Lattner708148e2004-10-10 23:14:11 +0000620 Changed = true;
621 } else {
622 AllLoadsGone = false;
623 }
624 Loads.pop_back();
625 }
626
627 // If we nuked all of the loads, then none of the stores are needed either,
628 // nor is the global.
629 if (AllLoadsGone) {
630 DEBUG(std::cerr << " *** GLOBAL NOW DEAD!\n");
631 CleanupConstantGlobalUsers(GV, 0);
632 if (GV->use_empty()) {
Chris Lattner7a7ed022004-10-16 18:09:00 +0000633 GV->eraseFromParent();
Chris Lattner708148e2004-10-10 23:14:11 +0000634 ++NumDeleted;
635 }
636 Changed = true;
637 }
638 return Changed;
639}
640
Chris Lattner30ba5692004-10-11 05:54:41 +0000641/// ConstantPropUsersOf - Walk the use list of V, constant folding all of the
642/// instructions that are foldable.
643static void ConstantPropUsersOf(Value *V) {
644 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; )
645 if (Instruction *I = dyn_cast<Instruction>(*UI++))
646 if (Constant *NewC = ConstantFoldInstruction(I)) {
647 I->replaceAllUsesWith(NewC);
648
Chris Lattnerd514d822005-02-01 01:23:31 +0000649 // Advance UI to the next non-I use to avoid invalidating it!
650 // Instructions could multiply use V.
651 while (UI != E && *UI == I)
Chris Lattner30ba5692004-10-11 05:54:41 +0000652 ++UI;
Chris Lattnerd514d822005-02-01 01:23:31 +0000653 I->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +0000654 }
655}
656
657/// OptimizeGlobalAddressOfMalloc - This function takes the specified global
658/// variable, and transforms the program as if it always contained the result of
659/// the specified malloc. Because it is always the result of the specified
660/// malloc, there is no reason to actually DO the malloc. Instead, turn the
661/// malloc into a global, and any laods of GV as uses of the new global.
662static GlobalVariable *OptimizeGlobalAddressOfMalloc(GlobalVariable *GV,
663 MallocInst *MI) {
664 DEBUG(std::cerr << "PROMOTING MALLOC GLOBAL: " << *GV << " MALLOC = " <<*MI);
665 ConstantInt *NElements = cast<ConstantInt>(MI->getArraySize());
666
667 if (NElements->getRawValue() != 1) {
668 // If we have an array allocation, transform it to a single element
669 // allocation to make the code below simpler.
670 Type *NewTy = ArrayType::get(MI->getAllocatedType(),
Chris Lattner4d0801b2005-01-08 19:45:31 +0000671 (unsigned)NElements->getRawValue());
Chris Lattner30ba5692004-10-11 05:54:41 +0000672 MallocInst *NewMI =
673 new MallocInst(NewTy, Constant::getNullValue(Type::UIntTy),
674 MI->getName(), MI);
675 std::vector<Value*> Indices;
676 Indices.push_back(Constant::getNullValue(Type::IntTy));
677 Indices.push_back(Indices[0]);
678 Value *NewGEP = new GetElementPtrInst(NewMI, Indices,
679 NewMI->getName()+".el0", MI);
680 MI->replaceAllUsesWith(NewGEP);
Chris Lattner7a7ed022004-10-16 18:09:00 +0000681 MI->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +0000682 MI = NewMI;
683 }
684
Chris Lattner7a7ed022004-10-16 18:09:00 +0000685 // Create the new global variable. The contents of the malloc'd memory is
686 // undefined, so initialize with an undef value.
687 Constant *Init = UndefValue::get(MI->getAllocatedType());
Chris Lattner30ba5692004-10-11 05:54:41 +0000688 GlobalVariable *NewGV = new GlobalVariable(MI->getAllocatedType(), false,
689 GlobalValue::InternalLinkage, Init,
690 GV->getName()+".body");
691 GV->getParent()->getGlobalList().insert(GV, NewGV);
692
693 // Anything that used the malloc now uses the global directly.
694 MI->replaceAllUsesWith(NewGV);
Chris Lattner30ba5692004-10-11 05:54:41 +0000695
696 Constant *RepValue = NewGV;
697 if (NewGV->getType() != GV->getType()->getElementType())
698 RepValue = ConstantExpr::getCast(RepValue, GV->getType()->getElementType());
699
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000700 // If there is a comparison against null, we will insert a global bool to
701 // keep track of whether the global was initialized yet or not.
Chris Lattnerbc965b92004-12-02 06:25:58 +0000702 GlobalVariable *InitBool =
703 new GlobalVariable(Type::BoolTy, false, GlobalValue::InternalLinkage,
704 ConstantBool::False, GV->getName()+".init");
705 bool InitBoolUsed = false;
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000706
Chris Lattner30ba5692004-10-11 05:54:41 +0000707 // Loop over all uses of GV, processing them in turn.
Chris Lattnerbc965b92004-12-02 06:25:58 +0000708 std::vector<StoreInst*> Stores;
Chris Lattner30ba5692004-10-11 05:54:41 +0000709 while (!GV->use_empty())
710 if (LoadInst *LI = dyn_cast<LoadInst>(GV->use_back())) {
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000711 while (!LI->use_empty()) {
Chris Lattnerd514d822005-02-01 01:23:31 +0000712 Use &LoadUse = LI->use_begin().getUse();
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000713 if (!isa<SetCondInst>(LoadUse.getUser()))
714 LoadUse = RepValue;
715 else {
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000716 // Replace the setcc X, 0 with a use of the bool value.
717 SetCondInst *SCI = cast<SetCondInst>(LoadUse.getUser());
718 Value *LV = new LoadInst(InitBool, InitBool->getName()+".val", SCI);
Chris Lattnerbc965b92004-12-02 06:25:58 +0000719 InitBoolUsed = true;
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000720 switch (SCI->getOpcode()) {
721 default: assert(0 && "Unknown opcode!");
722 case Instruction::SetLT:
723 LV = ConstantBool::False; // X < null -> always false
724 break;
725 case Instruction::SetEQ:
726 case Instruction::SetLE:
727 LV = BinaryOperator::createNot(LV, "notinit", SCI);
728 break;
729 case Instruction::SetNE:
730 case Instruction::SetGE:
731 case Instruction::SetGT:
732 break; // no change.
733 }
734 SCI->replaceAllUsesWith(LV);
735 SCI->eraseFromParent();
736 }
737 }
Chris Lattner7a7ed022004-10-16 18:09:00 +0000738 LI->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +0000739 } else {
740 StoreInst *SI = cast<StoreInst>(GV->use_back());
Chris Lattnerbc965b92004-12-02 06:25:58 +0000741 // The global is initialized when the store to it occurs.
742 new StoreInst(ConstantBool::True, InitBool, SI);
Chris Lattner7a7ed022004-10-16 18:09:00 +0000743 SI->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +0000744 }
745
Chris Lattnerbc965b92004-12-02 06:25:58 +0000746 // If the initialization boolean was used, insert it, otherwise delete it.
747 if (!InitBoolUsed) {
748 while (!InitBool->use_empty()) // Delete initializations
749 cast<Instruction>(InitBool->use_back())->eraseFromParent();
750 delete InitBool;
751 } else
752 GV->getParent()->getGlobalList().insert(GV, InitBool);
753
754
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000755 // Now the GV is dead, nuke it and the malloc.
Chris Lattner7a7ed022004-10-16 18:09:00 +0000756 GV->eraseFromParent();
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000757 MI->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +0000758
759 // To further other optimizations, loop over all users of NewGV and try to
760 // constant prop them. This will promote GEP instructions with constant
761 // indices into GEP constant-exprs, which will allow global-opt to hack on it.
762 ConstantPropUsersOf(NewGV);
763 if (RepValue != NewGV)
764 ConstantPropUsersOf(RepValue);
765
766 return NewGV;
767}
Chris Lattner708148e2004-10-10 23:14:11 +0000768
Chris Lattnerfa07e4f2004-12-02 07:11:07 +0000769/// ValueIsOnlyUsedLocallyOrStoredToOneGlobal - Scan the use-list of V checking
770/// to make sure that there are no complex uses of V. We permit simple things
771/// like dereferencing the pointer, but not storing through the address, unless
772/// it is to the specified global.
773static bool ValueIsOnlyUsedLocallyOrStoredToOneGlobal(Instruction *V,
774 GlobalVariable *GV) {
775 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;++UI)
776 if (isa<LoadInst>(*UI) || isa<SetCondInst>(*UI)) {
777 // Fine, ignore.
778 } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
779 if (SI->getOperand(0) == V && SI->getOperand(1) != GV)
780 return false; // Storing the pointer itself... bad.
781 // Otherwise, storing through it, or storing into GV... fine.
782 } else if (isa<GetElementPtrInst>(*UI) || isa<SelectInst>(*UI)) {
783 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(cast<Instruction>(*UI),GV))
784 return false;
785 } else {
786 return false;
787 }
788 return true;
789
790}
791
Chris Lattner9b34a612004-10-09 21:48:45 +0000792// OptimizeOnceStoredGlobal - Try to optimize globals based on the knowledge
793// that only one value (besides its initializer) is ever stored to the global.
Chris Lattner30ba5692004-10-11 05:54:41 +0000794static bool OptimizeOnceStoredGlobal(GlobalVariable *GV, Value *StoredOnceVal,
Chris Lattnere4d5c442005-03-15 04:54:21 +0000795 Module::global_iterator &GVI, TargetData &TD) {
Chris Lattner9b34a612004-10-09 21:48:45 +0000796 if (CastInst *CI = dyn_cast<CastInst>(StoredOnceVal))
797 StoredOnceVal = CI->getOperand(0);
798 else if (GetElementPtrInst *GEPI =dyn_cast<GetElementPtrInst>(StoredOnceVal)){
Chris Lattner708148e2004-10-10 23:14:11 +0000799 // "getelementptr Ptr, 0, 0, 0" is really just a cast.
Chris Lattner9b34a612004-10-09 21:48:45 +0000800 bool IsJustACast = true;
801 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
802 if (!isa<Constant>(GEPI->getOperand(i)) ||
803 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
804 IsJustACast = false;
805 break;
806 }
807 if (IsJustACast)
808 StoredOnceVal = GEPI->getOperand(0);
809 }
810
Chris Lattner708148e2004-10-10 23:14:11 +0000811 // If we are dealing with a pointer global that is initialized to null and
812 // only has one (non-null) value stored into it, then we can optimize any
813 // users of the loaded value (often calls and loads) that would trap if the
814 // value was null.
Chris Lattner9b34a612004-10-09 21:48:45 +0000815 if (isa<PointerType>(GV->getInitializer()->getType()) &&
816 GV->getInitializer()->isNullValue()) {
Chris Lattner708148e2004-10-10 23:14:11 +0000817 if (Constant *SOVC = dyn_cast<Constant>(StoredOnceVal)) {
818 if (GV->getInitializer()->getType() != SOVC->getType())
819 SOVC = ConstantExpr::getCast(SOVC, GV->getInitializer()->getType());
820
821 // Optimize away any trapping uses of the loaded value.
822 if (OptimizeAwayTrappingUsesOfLoads(GV, SOVC))
Chris Lattner8be80122004-10-10 17:07:12 +0000823 return true;
Chris Lattner30ba5692004-10-11 05:54:41 +0000824 } else if (MallocInst *MI = dyn_cast<MallocInst>(StoredOnceVal)) {
825 // If we have a global that is only initialized with a fixed size malloc,
826 // and if all users of the malloc trap, and if the malloc'd address is not
827 // put anywhere else, transform the program to use global memory instead
828 // of malloc'd memory. This eliminates dynamic allocation (good) and
829 // exposes the resultant global to further GlobalOpt (even better). Note
830 // that we restrict this transformation to only working on small
831 // allocations (2048 bytes currently), as we don't want to introduce a 16M
832 // global or something.
833 if (ConstantInt *NElements = dyn_cast<ConstantInt>(MI->getArraySize()))
834 if (MI->getAllocatedType()->isSized() &&
835 NElements->getRawValue()*
836 TD.getTypeSize(MI->getAllocatedType()) < 2048 &&
Chris Lattnerfa07e4f2004-12-02 07:11:07 +0000837 AllUsesOfLoadedValueWillTrapIfNull(GV) &&
838 ValueIsOnlyUsedLocallyOrStoredToOneGlobal(MI, GV)) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000839 GVI = OptimizeGlobalAddressOfMalloc(GV, MI);
840 return true;
841 }
Chris Lattner708148e2004-10-10 23:14:11 +0000842 }
Chris Lattner9b34a612004-10-09 21:48:45 +0000843 }
Chris Lattner30ba5692004-10-11 05:54:41 +0000844
Chris Lattner9b34a612004-10-09 21:48:45 +0000845 return false;
846}
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000847
Chris Lattner96a86b22004-12-12 05:53:50 +0000848/// ShrinkGlobalToBoolean - At this point, we have learned that the only two
849/// values ever stored into GV are its initializer and OtherVal.
850static void ShrinkGlobalToBoolean(GlobalVariable *GV, Constant *OtherVal) {
851 // Create the new global, initializing it to false.
852 GlobalVariable *NewGV = new GlobalVariable(Type::BoolTy, false,
853 GlobalValue::InternalLinkage, ConstantBool::False, GV->getName()+".b");
854 GV->getParent()->getGlobalList().insert(GV, NewGV);
855
856 Constant *InitVal = GV->getInitializer();
857 assert(InitVal->getType() != Type::BoolTy && "No reason to shrink to bool!");
858
859 // If initialized to zero and storing one into the global, we can use a cast
860 // instead of a select to synthesize the desired value.
861 bool IsOneZero = false;
862 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal))
863 IsOneZero = InitVal->isNullValue() && CI->equalsInt(1);
864
865 while (!GV->use_empty()) {
866 Instruction *UI = cast<Instruction>(GV->use_back());
867 if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
868 // Change the store into a boolean store.
869 bool StoringOther = SI->getOperand(0) == OtherVal;
870 // Only do this if we weren't storing a loaded value.
Chris Lattner38c25562004-12-12 19:34:41 +0000871 Value *StoreVal;
Chris Lattner96a86b22004-12-12 05:53:50 +0000872 if (StoringOther || SI->getOperand(0) == InitVal)
Chris Lattner38c25562004-12-12 19:34:41 +0000873 StoreVal = ConstantBool::get(StoringOther);
874 else {
875 // Otherwise, we are storing a previously loaded copy. To do this,
876 // change the copy from copying the original value to just copying the
877 // bool.
878 Instruction *StoredVal = cast<Instruction>(SI->getOperand(0));
879
880 // If we're already replaced the input, StoredVal will be a cast or
881 // select instruction. If not, it will be a load of the original
882 // global.
883 if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
884 assert(LI->getOperand(0) == GV && "Not a copy!");
885 // Insert a new load, to preserve the saved value.
886 StoreVal = new LoadInst(NewGV, LI->getName()+".b", LI);
887 } else {
888 assert((isa<CastInst>(StoredVal) || isa<SelectInst>(StoredVal)) &&
889 "This is not a form that we understand!");
890 StoreVal = StoredVal->getOperand(0);
891 assert(isa<LoadInst>(StoreVal) && "Not a load of NewGV!");
892 }
893 }
894 new StoreInst(StoreVal, NewGV, SI);
895 } else if (!UI->use_empty()) {
Chris Lattner96a86b22004-12-12 05:53:50 +0000896 // Change the load into a load of bool then a select.
897 LoadInst *LI = cast<LoadInst>(UI);
Chris Lattner38c25562004-12-12 19:34:41 +0000898
Chris Lattner96a86b22004-12-12 05:53:50 +0000899 std::string Name = LI->getName(); LI->setName("");
900 LoadInst *NLI = new LoadInst(NewGV, Name+".b", LI);
901 Value *NSI;
902 if (IsOneZero)
903 NSI = new CastInst(NLI, LI->getType(), Name, LI);
904 else
905 NSI = new SelectInst(NLI, OtherVal, InitVal, Name, LI);
906 LI->replaceAllUsesWith(NSI);
907 }
908 UI->eraseFromParent();
909 }
910
911 GV->eraseFromParent();
912}
913
914
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000915/// ProcessInternalGlobal - Analyze the specified global variable and optimize
916/// it if possible. If we make a change, return true.
Chris Lattner30ba5692004-10-11 05:54:41 +0000917bool GlobalOpt::ProcessInternalGlobal(GlobalVariable *GV,
Chris Lattnere4d5c442005-03-15 04:54:21 +0000918 Module::global_iterator &GVI) {
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000919 std::set<PHINode*> PHIUsers;
920 GlobalStatus GS;
921 PHIUsers.clear();
922 GV->removeDeadConstantUsers();
923
924 if (GV->use_empty()) {
925 DEBUG(std::cerr << "GLOBAL DEAD: " << *GV);
Chris Lattner7a7ed022004-10-16 18:09:00 +0000926 GV->eraseFromParent();
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000927 ++NumDeleted;
928 return true;
929 }
930
931 if (!AnalyzeGlobal(GV, GS, PHIUsers)) {
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +0000932 // If this is a first class global and has only one accessing function
933 // and this function is main (which we know is not recursive we can make
934 // this global a local variable) we replace the global with a local alloca
935 // in this function.
936 //
937 // NOTE: It doesn't make sense to promote non first class types since we
938 // are just replacing static memory to stack memory.
939 if (!GS.HasMultipleAccessingFunctions &&
940 GS.AccessingFunction &&
941 GV->getType()->getElementType()->isFirstClassType() &&
942 GS.AccessingFunction->getName() == "main" &&
943 GS.AccessingFunction->hasExternalLinkage()) {
944 DEBUG(std::cerr << "LOCALIZING GLOBAL: " << *GV);
945 Instruction* FirstI = GS.AccessingFunction->getEntryBlock().begin();
946 const Type* ElemTy = GV->getType()->getElementType();
947 AllocaInst* Alloca = new AllocaInst(ElemTy, NULL, GV->getName(), FirstI);
948 if (!isa<UndefValue>(GV->getInitializer()))
949 new StoreInst(GV->getInitializer(), Alloca, FirstI);
950
951 GV->replaceAllUsesWith(Alloca);
952 GV->eraseFromParent();
953 ++NumLocalized;
954 return true;
955 }
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000956 // If the global is never loaded (but may be stored to), it is dead.
957 // Delete it now.
958 if (!GS.isLoaded) {
959 DEBUG(std::cerr << "GLOBAL NEVER LOADED: " << *GV);
Chris Lattner930f4752004-10-09 03:32:52 +0000960
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000961 // Delete any stores we can find to the global. We may not be able to
962 // make it completely dead though.
Chris Lattner031955d2004-10-10 16:43:46 +0000963 bool Changed = CleanupConstantGlobalUsers(GV, GV->getInitializer());
Chris Lattner930f4752004-10-09 03:32:52 +0000964
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000965 // If the global is dead now, delete it.
966 if (GV->use_empty()) {
Chris Lattner7a7ed022004-10-16 18:09:00 +0000967 GV->eraseFromParent();
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000968 ++NumDeleted;
Chris Lattner930f4752004-10-09 03:32:52 +0000969 Changed = true;
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000970 }
Chris Lattner930f4752004-10-09 03:32:52 +0000971 return Changed;
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000972
973 } else if (GS.StoredType <= GlobalStatus::isInitializerStored) {
974 DEBUG(std::cerr << "MARKING CONSTANT: " << *GV);
975 GV->setConstant(true);
976
977 // Clean up any obviously simplifiable users now.
978 CleanupConstantGlobalUsers(GV, GV->getInitializer());
979
980 // If the global is dead now, just nuke it.
981 if (GV->use_empty()) {
982 DEBUG(std::cerr << " *** Marking constant allowed us to simplify "
983 "all users and delete global!\n");
Chris Lattner7a7ed022004-10-16 18:09:00 +0000984 GV->eraseFromParent();
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000985 ++NumDeleted;
986 }
987
988 ++NumMarked;
989 return true;
990 } else if (!GS.isNotSuitableForSRA &&
991 !GV->getInitializer()->getType()->isFirstClassType()) {
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000992 if (GlobalVariable *FirstNewGV = SRAGlobal(GV)) {
993 GVI = FirstNewGV; // Don't skip the newly produced globals!
994 return true;
995 }
Chris Lattner9b34a612004-10-09 21:48:45 +0000996 } else if (GS.StoredType == GlobalStatus::isStoredOnce) {
Chris Lattner96a86b22004-12-12 05:53:50 +0000997 // If the initial value for the global was an undef value, and if only
998 // one other value was stored into it, we can just change the
999 // initializer to be an undef value, then delete all stores to the
1000 // global. This allows us to mark it constant.
1001 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
1002 if (isa<UndefValue>(GV->getInitializer())) {
1003 // Change the initial value here.
1004 GV->setInitializer(SOVConstant);
1005
1006 // Clean up any obviously simplifiable users now.
1007 CleanupConstantGlobalUsers(GV, GV->getInitializer());
1008
1009 if (GV->use_empty()) {
1010 DEBUG(std::cerr << " *** Substituting initializer allowed us to "
1011 "simplify all users and delete global!\n");
1012 GV->eraseFromParent();
1013 ++NumDeleted;
1014 } else {
1015 GVI = GV;
1016 }
1017 ++NumSubstitute;
1018 return true;
Chris Lattner7a7ed022004-10-16 18:09:00 +00001019 }
Chris Lattner7a7ed022004-10-16 18:09:00 +00001020
Chris Lattner9b34a612004-10-09 21:48:45 +00001021 // Try to optimize globals based on the knowledge that only one value
1022 // (besides its initializer) is ever stored to the global.
Chris Lattner30ba5692004-10-11 05:54:41 +00001023 if (OptimizeOnceStoredGlobal(GV, GS.StoredOnceValue, GVI,
1024 getAnalysis<TargetData>()))
Chris Lattner9b34a612004-10-09 21:48:45 +00001025 return true;
Chris Lattner96a86b22004-12-12 05:53:50 +00001026
1027 // Otherwise, if the global was not a boolean, we can shrink it to be a
1028 // boolean.
1029 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
Chris Lattner077f1a82004-12-12 06:03:06 +00001030 if (GV->getType()->getElementType() != Type::BoolTy &&
1031 !GV->getType()->getElementType()->isFloatingPoint()) {
Chris Lattner96a86b22004-12-12 05:53:50 +00001032 DEBUG(std::cerr << " *** SHRINKING TO BOOL: " << *GV);
1033 ShrinkGlobalToBoolean(GV, SOVConstant);
1034 ++NumShrunkToBool;
1035 return true;
1036 }
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001037 }
1038 }
1039 return false;
1040}
1041
1042
Chris Lattner7a90b682004-10-07 04:16:33 +00001043bool GlobalOpt::runOnModule(Module &M) {
Chris Lattner079236d2004-02-25 21:34:36 +00001044 bool Changed = false;
Chris Lattner7a90b682004-10-07 04:16:33 +00001045
1046 // As a prepass, delete functions that are trivially dead.
1047 bool LocalChange = true;
1048 while (LocalChange) {
1049 LocalChange = false;
1050 for (Module::iterator FI = M.begin(), E = M.end(); FI != E; ) {
1051 Function *F = FI++;
1052 F->removeDeadConstantUsers();
Chris Lattnerb23cd2f2004-10-14 19:53:50 +00001053 if (F->use_empty() && (F->hasInternalLinkage() ||
1054 F->hasLinkOnceLinkage())) {
Chris Lattner7a90b682004-10-07 04:16:33 +00001055 M.getFunctionList().erase(F);
1056 LocalChange = true;
1057 ++NumFnDeleted;
1058 }
1059 }
1060 Changed |= LocalChange;
1061 }
1062
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001063 LocalChange = true;
1064 while (LocalChange) {
1065 LocalChange = false;
Chris Lattnere4d5c442005-03-15 04:54:21 +00001066 for (Module::global_iterator GVI = M.global_begin(), E = M.global_end(); GVI != E;) {
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001067 GlobalVariable *GV = GVI++;
1068 if (!GV->isConstant() && GV->hasInternalLinkage() &&
1069 GV->hasInitializer())
1070 LocalChange |= ProcessInternalGlobal(GV, GVI);
Chris Lattner079236d2004-02-25 21:34:36 +00001071 }
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001072 Changed |= LocalChange;
Chris Lattnere47ba742004-10-06 20:57:02 +00001073 }
Chris Lattner079236d2004-02-25 21:34:36 +00001074 return Changed;
1075}