blob: 7b06e41374b5f5883a1010013a62d154554e68ac [file] [log] [blame]
Chris Lattner25db5802004-10-07 04:16:33 +00001//===- GlobalOpt.cpp - Optimize Global Variables --------------------------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
Chris Lattner25db5802004-10-07 04:16:33 +00003// 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.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007//
Chris Lattner25db5802004-10-07 04:16:33 +00008//===----------------------------------------------------------------------===//
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"
Chris Lattnera4c80222005-05-08 22:18:06 +000018#include "llvm/CallingConv.h"
Chris Lattner25db5802004-10-07 04:16:33 +000019#include "llvm/Constants.h"
20#include "llvm/DerivedTypes.h"
21#include "llvm/Instructions.h"
Chris Lattner7561ca12005-02-27 18:58:52 +000022#include "llvm/IntrinsicInst.h"
Chris Lattner25db5802004-10-07 04:16:33 +000023#include "llvm/Module.h"
24#include "llvm/Pass.h"
25#include "llvm/Support/Debug.h"
Chris Lattner004e2502004-10-11 05:54:41 +000026#include "llvm/Target/TargetData.h"
27#include "llvm/Transforms/Utils/Local.h"
Chris Lattner25db5802004-10-07 04:16:33 +000028#include "llvm/ADT/Statistic.h"
Chris Lattnerabab0712004-10-08 17:32:09 +000029#include "llvm/ADT/StringExtras.h"
Chris Lattner25db5802004-10-07 04:16:33 +000030#include <set>
31#include <algorithm>
32using namespace llvm;
33
34namespace {
Chris Lattnerabab0712004-10-08 17:32:09 +000035 Statistic<> NumMarked ("globalopt", "Number of globals marked constant");
36 Statistic<> NumSRA ("globalopt", "Number of aggregate globals broken "
37 "into scalars");
Chris Lattner8e71c6a2004-10-16 18:09:00 +000038 Statistic<> NumSubstitute("globalopt",
39 "Number of globals with initializers stored into them");
Chris Lattnerabab0712004-10-08 17:32:09 +000040 Statistic<> NumDeleted ("globalopt", "Number of globals deleted");
Chris Lattner25db5802004-10-07 04:16:33 +000041 Statistic<> NumFnDeleted("globalopt", "Number of functions deleted");
Chris Lattnere42eb312004-10-10 23:14:11 +000042 Statistic<> NumGlobUses ("globalopt", "Number of global uses devirtualized");
Alkis Evlogimenosc4a44c62005-02-10 18:36:30 +000043 Statistic<> NumLocalized("globalopt", "Number of globals localized");
Chris Lattner40e4cec2004-12-12 05:53:50 +000044 Statistic<> NumShrunkToBool("globalopt",
45 "Number of global vars shrunk to booleans");
Chris Lattnera4c80222005-05-08 22:18:06 +000046 Statistic<> NumFastCallFns("globalopt",
47 "Number of functions converted to fastcc");
Chris Lattner41b6a5a2005-09-26 01:43:45 +000048 Statistic<> NumEmptyCtor ("globalopt", "Number of empty ctors removed");
Chris Lattner99e23fa2005-09-26 04:44:35 +000049 Statistic<> NumCtorsEvaluated("globalopt","Number of static ctors evaluated");
Chris Lattner25db5802004-10-07 04:16:33 +000050
51 struct GlobalOpt : public ModulePass {
Chris Lattner004e2502004-10-11 05:54:41 +000052 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
53 AU.addRequired<TargetData>();
54 }
Misha Brukmanb1c93172005-04-21 23:48:37 +000055
Chris Lattner25db5802004-10-07 04:16:33 +000056 bool runOnModule(Module &M);
Chris Lattner004e2502004-10-11 05:54:41 +000057
58 private:
Chris Lattner41b6a5a2005-09-26 01:43:45 +000059 GlobalVariable *FindGlobalCtors(Module &M);
60 bool OptimizeFunctions(Module &M);
61 bool OptimizeGlobalVars(Module &M);
62 bool OptimizeGlobalCtorsList(GlobalVariable *&GCL);
Chris Lattner531f9e92005-03-15 04:54:21 +000063 bool ProcessInternalGlobal(GlobalVariable *GV, Module::global_iterator &GVI);
Chris Lattner25db5802004-10-07 04:16:33 +000064 };
65
66 RegisterOpt<GlobalOpt> X("globalopt", "Global Variable Optimizer");
67}
68
69ModulePass *llvm::createGlobalOptimizerPass() { return new GlobalOpt(); }
70
71/// GlobalStatus - As we analyze each global, keep track of some information
72/// about it. If we find out that the address of the global is taken, none of
Chris Lattner617f1a32004-10-07 21:30:30 +000073/// this info will be accurate.
Chris Lattner25db5802004-10-07 04:16:33 +000074struct GlobalStatus {
Chris Lattner617f1a32004-10-07 21:30:30 +000075 /// isLoaded - True if the global is ever loaded. If the global isn't ever
76 /// loaded it can be deleted.
Chris Lattner25db5802004-10-07 04:16:33 +000077 bool isLoaded;
Chris Lattner617f1a32004-10-07 21:30:30 +000078
79 /// StoredType - Keep track of what stores to the global look like.
80 ///
Chris Lattner25db5802004-10-07 04:16:33 +000081 enum StoredType {
Chris Lattner617f1a32004-10-07 21:30:30 +000082 /// NotStored - There is no store to this global. It can thus be marked
83 /// constant.
84 NotStored,
85
86 /// isInitializerStored - This global is stored to, but the only thing
87 /// stored is the constant it was initialized with. This is only tracked
88 /// for scalar globals.
89 isInitializerStored,
90
91 /// isStoredOnce - This global is stored to, but only its initializer and
92 /// one other value is ever stored to it. If this global isStoredOnce, we
93 /// track the value stored to it in StoredOnceValue below. This is only
94 /// tracked for scalar globals.
95 isStoredOnce,
96
97 /// isStored - This global is stored to by multiple values or something else
98 /// that we cannot track.
99 isStored
Chris Lattner25db5802004-10-07 04:16:33 +0000100 } StoredType;
Chris Lattner617f1a32004-10-07 21:30:30 +0000101
102 /// StoredOnceValue - If only one value (besides the initializer constant) is
103 /// ever stored to this global, keep track of what value it is.
104 Value *StoredOnceValue;
105
Alkis Evlogimenosc4a44c62005-02-10 18:36:30 +0000106 // AccessingFunction/HasMultipleAccessingFunctions - These start out
107 // null/false. When the first accessing function is noticed, it is recorded.
108 // When a second different accessing function is noticed,
109 // HasMultipleAccessingFunctions is set to true.
110 Function *AccessingFunction;
111 bool HasMultipleAccessingFunctions;
112
Chris Lattner50bdfcb2005-06-15 21:11:48 +0000113 // HasNonInstructionUser - Set to true if this global has a user that is not
114 // an instruction (e.g. a constant expr or GV initializer).
115 bool HasNonInstructionUser;
116
Chris Lattner617f1a32004-10-07 21:30:30 +0000117 /// isNotSuitableForSRA - Keep track of whether any SRA preventing users of
118 /// the global exist. Such users include GEP instruction with variable
119 /// indexes, and non-gep/load/store users like constant expr casts.
Chris Lattner25db5802004-10-07 04:16:33 +0000120 bool isNotSuitableForSRA;
121
Chris Lattner617f1a32004-10-07 21:30:30 +0000122 GlobalStatus() : isLoaded(false), StoredType(NotStored), StoredOnceValue(0),
Alkis Evlogimenosc4a44c62005-02-10 18:36:30 +0000123 AccessingFunction(0), HasMultipleAccessingFunctions(false),
Chris Lattner50bdfcb2005-06-15 21:11:48 +0000124 HasNonInstructionUser(false), isNotSuitableForSRA(false) {}
Chris Lattner25db5802004-10-07 04:16:33 +0000125};
126
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000127
128
129/// ConstantIsDead - Return true if the specified constant is (transitively)
130/// dead. The constant may be used by other constants (e.g. constant arrays and
131/// constant exprs) as long as they are dead, but it cannot be used by anything
132/// else.
133static bool ConstantIsDead(Constant *C) {
134 if (isa<GlobalValue>(C)) return false;
135
136 for (Value::use_iterator UI = C->use_begin(), E = C->use_end(); UI != E; ++UI)
137 if (Constant *CU = dyn_cast<Constant>(*UI)) {
138 if (!ConstantIsDead(CU)) return false;
139 } else
140 return false;
141 return true;
142}
143
144
Chris Lattner25db5802004-10-07 04:16:33 +0000145/// AnalyzeGlobal - Look at all uses of the global and fill in the GlobalStatus
146/// structure. If the global has its address taken, return true to indicate we
147/// can't do anything with it.
148///
149static bool AnalyzeGlobal(Value *V, GlobalStatus &GS,
150 std::set<PHINode*> &PHIUsers) {
151 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
152 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(*UI)) {
Chris Lattner50bdfcb2005-06-15 21:11:48 +0000153 GS.HasNonInstructionUser = true;
154
Chris Lattner25db5802004-10-07 04:16:33 +0000155 if (AnalyzeGlobal(CE, GS, PHIUsers)) return true;
156 if (CE->getOpcode() != Instruction::GetElementPtr)
157 GS.isNotSuitableForSRA = true;
Chris Lattnerabab0712004-10-08 17:32:09 +0000158 else if (!GS.isNotSuitableForSRA) {
159 // Check to see if this ConstantExpr GEP is SRA'able. In particular, we
160 // don't like < 3 operand CE's, and we don't like non-constant integer
161 // indices.
162 if (CE->getNumOperands() < 3 || !CE->getOperand(1)->isNullValue())
163 GS.isNotSuitableForSRA = true;
164 else {
165 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
166 if (!isa<ConstantInt>(CE->getOperand(i))) {
167 GS.isNotSuitableForSRA = true;
168 break;
169 }
170 }
171 }
172
Chris Lattner25db5802004-10-07 04:16:33 +0000173 } else if (Instruction *I = dyn_cast<Instruction>(*UI)) {
Alkis Evlogimenosc4a44c62005-02-10 18:36:30 +0000174 if (!GS.HasMultipleAccessingFunctions) {
175 Function *F = I->getParent()->getParent();
176 if (GS.AccessingFunction == 0)
177 GS.AccessingFunction = F;
178 else if (GS.AccessingFunction != F)
179 GS.HasMultipleAccessingFunctions = true;
180 }
Chris Lattner25db5802004-10-07 04:16:33 +0000181 if (isa<LoadInst>(I)) {
182 GS.isLoaded = true;
183 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Chris Lattner02b6c912004-10-07 06:01:25 +0000184 // Don't allow a store OF the address, only stores TO the address.
185 if (SI->getOperand(0) == V) return true;
186
Chris Lattner617f1a32004-10-07 21:30:30 +0000187 // If this is a direct store to the global (i.e., the global is a scalar
188 // value, not an aggregate), keep more specific information about
189 // stores.
190 if (GS.StoredType != GlobalStatus::isStored)
191 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(SI->getOperand(1))){
Chris Lattner28eeb732004-11-14 20:50:30 +0000192 Value *StoredVal = SI->getOperand(0);
193 if (StoredVal == GV->getInitializer()) {
194 if (GS.StoredType < GlobalStatus::isInitializerStored)
195 GS.StoredType = GlobalStatus::isInitializerStored;
196 } else if (isa<LoadInst>(StoredVal) &&
197 cast<LoadInst>(StoredVal)->getOperand(0) == GV) {
198 // G = G
Chris Lattner617f1a32004-10-07 21:30:30 +0000199 if (GS.StoredType < GlobalStatus::isInitializerStored)
200 GS.StoredType = GlobalStatus::isInitializerStored;
201 } else if (GS.StoredType < GlobalStatus::isStoredOnce) {
202 GS.StoredType = GlobalStatus::isStoredOnce;
Chris Lattner28eeb732004-11-14 20:50:30 +0000203 GS.StoredOnceValue = StoredVal;
Chris Lattner617f1a32004-10-07 21:30:30 +0000204 } else if (GS.StoredType == GlobalStatus::isStoredOnce &&
Chris Lattner28eeb732004-11-14 20:50:30 +0000205 GS.StoredOnceValue == StoredVal) {
Chris Lattner617f1a32004-10-07 21:30:30 +0000206 // noop.
207 } else {
208 GS.StoredType = GlobalStatus::isStored;
209 }
210 } else {
Chris Lattner25db5802004-10-07 04:16:33 +0000211 GS.StoredType = GlobalStatus::isStored;
Chris Lattner617f1a32004-10-07 21:30:30 +0000212 }
Chris Lattner7561ca12005-02-27 18:58:52 +0000213 } else if (isa<GetElementPtrInst>(I)) {
Chris Lattner25db5802004-10-07 04:16:33 +0000214 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Chris Lattner004e2502004-10-11 05:54:41 +0000215
216 // If the first two indices are constants, this can be SRA'd.
217 if (isa<GlobalVariable>(I->getOperand(0))) {
218 if (I->getNumOperands() < 3 || !isa<Constant>(I->getOperand(1)) ||
Misha Brukmanb1c93172005-04-21 23:48:37 +0000219 !cast<Constant>(I->getOperand(1))->isNullValue() ||
Chris Lattner004e2502004-10-11 05:54:41 +0000220 !isa<ConstantInt>(I->getOperand(2)))
221 GS.isNotSuitableForSRA = true;
222 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(I->getOperand(0))){
223 if (CE->getOpcode() != Instruction::GetElementPtr ||
224 CE->getNumOperands() < 3 || I->getNumOperands() < 2 ||
225 !isa<Constant>(I->getOperand(0)) ||
226 !cast<Constant>(I->getOperand(0))->isNullValue())
227 GS.isNotSuitableForSRA = true;
228 } else {
229 GS.isNotSuitableForSRA = true;
230 }
Chris Lattner7561ca12005-02-27 18:58:52 +0000231 } else if (isa<SelectInst>(I)) {
Chris Lattner25db5802004-10-07 04:16:33 +0000232 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
233 GS.isNotSuitableForSRA = true;
234 } else if (PHINode *PN = dyn_cast<PHINode>(I)) {
235 // PHI nodes we can check just like select or GEP instructions, but we
236 // have to be careful about infinite recursion.
237 if (PHIUsers.insert(PN).second) // Not already visited.
238 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
239 GS.isNotSuitableForSRA = true;
240 } else if (isa<SetCondInst>(I)) {
241 GS.isNotSuitableForSRA = true;
Chris Lattner7561ca12005-02-27 18:58:52 +0000242 } else if (isa<MemCpyInst>(I) || isa<MemMoveInst>(I)) {
243 if (I->getOperand(1) == V)
244 GS.StoredType = GlobalStatus::isStored;
245 if (I->getOperand(2) == V)
246 GS.isLoaded = true;
247 GS.isNotSuitableForSRA = true;
248 } else if (isa<MemSetInst>(I)) {
249 assert(I->getOperand(1) == V && "Memset only takes one pointer!");
250 GS.StoredType = GlobalStatus::isStored;
251 GS.isNotSuitableForSRA = true;
Chris Lattner25db5802004-10-07 04:16:33 +0000252 } else {
253 return true; // Any other non-load instruction might take address!
254 }
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000255 } else if (Constant *C = dyn_cast<Constant>(*UI)) {
Chris Lattner50bdfcb2005-06-15 21:11:48 +0000256 GS.HasNonInstructionUser = true;
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000257 // We might have a dead and dangling constant hanging off of here.
258 if (!ConstantIsDead(C))
259 return true;
Chris Lattner25db5802004-10-07 04:16:33 +0000260 } else {
Chris Lattner50bdfcb2005-06-15 21:11:48 +0000261 GS.HasNonInstructionUser = true;
262 // Otherwise must be some other user.
Chris Lattner25db5802004-10-07 04:16:33 +0000263 return true;
264 }
265
266 return false;
267}
268
Chris Lattnerabab0712004-10-08 17:32:09 +0000269static Constant *getAggregateConstantElement(Constant *Agg, Constant *Idx) {
270 ConstantInt *CI = dyn_cast<ConstantInt>(Idx);
271 if (!CI) return 0;
Chris Lattner46fa04b2005-01-08 19:45:31 +0000272 unsigned IdxV = (unsigned)CI->getRawValue();
Chris Lattner25db5802004-10-07 04:16:33 +0000273
Chris Lattnerabab0712004-10-08 17:32:09 +0000274 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Agg)) {
275 if (IdxV < CS->getNumOperands()) return CS->getOperand(IdxV);
276 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Agg)) {
277 if (IdxV < CA->getNumOperands()) return CA->getOperand(IdxV);
278 } else if (ConstantPacked *CP = dyn_cast<ConstantPacked>(Agg)) {
279 if (IdxV < CP->getNumOperands()) return CP->getOperand(IdxV);
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000280 } else if (isa<ConstantAggregateZero>(Agg)) {
Chris Lattnerabab0712004-10-08 17:32:09 +0000281 if (const StructType *STy = dyn_cast<StructType>(Agg->getType())) {
282 if (IdxV < STy->getNumElements())
283 return Constant::getNullValue(STy->getElementType(IdxV));
284 } else if (const SequentialType *STy =
285 dyn_cast<SequentialType>(Agg->getType())) {
286 return Constant::getNullValue(STy->getElementType());
287 }
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000288 } else if (isa<UndefValue>(Agg)) {
289 if (const StructType *STy = dyn_cast<StructType>(Agg->getType())) {
290 if (IdxV < STy->getNumElements())
291 return UndefValue::get(STy->getElementType(IdxV));
292 } else if (const SequentialType *STy =
293 dyn_cast<SequentialType>(Agg->getType())) {
294 return UndefValue::get(STy->getElementType());
295 }
Chris Lattnerabab0712004-10-08 17:32:09 +0000296 }
297 return 0;
298}
Chris Lattner25db5802004-10-07 04:16:33 +0000299
Chris Lattner25db5802004-10-07 04:16:33 +0000300
301/// CleanupConstantGlobalUsers - We just marked GV constant. Loop over all
302/// users of the global, cleaning up the obvious ones. This is largely just a
Chris Lattnercb9f1522004-10-10 16:43:46 +0000303/// quick scan over the use list to clean up the easy and obvious cruft. This
304/// returns true if it made a change.
305static bool CleanupConstantGlobalUsers(Value *V, Constant *Init) {
306 bool Changed = false;
Chris Lattner25db5802004-10-07 04:16:33 +0000307 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;) {
308 User *U = *UI++;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000309
Chris Lattner25db5802004-10-07 04:16:33 +0000310 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
Chris Lattner7561ca12005-02-27 18:58:52 +0000311 if (Init) {
312 // Replace the load with the initializer.
313 LI->replaceAllUsesWith(Init);
314 LI->eraseFromParent();
315 Changed = true;
316 }
Chris Lattner25db5802004-10-07 04:16:33 +0000317 } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
318 // Store must be unreachable or storing Init into the global.
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000319 SI->eraseFromParent();
Chris Lattnercb9f1522004-10-10 16:43:46 +0000320 Changed = true;
Chris Lattner25db5802004-10-07 04:16:33 +0000321 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
322 if (CE->getOpcode() == Instruction::GetElementPtr) {
Chris Lattner61ff32c2005-09-26 05:34:07 +0000323 Constant *SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
Chris Lattner7561ca12005-02-27 18:58:52 +0000324 Changed |= CleanupConstantGlobalUsers(CE, SubInit);
325 } else if (CE->getOpcode() == Instruction::Cast &&
326 isa<PointerType>(CE->getType())) {
327 // Pointer cast, delete any stores and memsets to the global.
328 Changed |= CleanupConstantGlobalUsers(CE, 0);
329 }
330
331 if (CE->use_empty()) {
332 CE->destroyConstant();
333 Changed = true;
Chris Lattner25db5802004-10-07 04:16:33 +0000334 }
335 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
Chris Lattner61ff32c2005-09-26 05:34:07 +0000336 Constant *SubInit = 0;
Chris Lattner46af55e2005-09-26 06:52:44 +0000337 ConstantExpr *CE =
338 dyn_cast_or_null<ConstantExpr>(ConstantFoldInstruction(GEP));
Chris Lattner61ff32c2005-09-26 05:34:07 +0000339 if (CE && CE->getOpcode() == Instruction::GetElementPtr)
340 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
Chris Lattner7561ca12005-02-27 18:58:52 +0000341 Changed |= CleanupConstantGlobalUsers(GEP, SubInit);
Chris Lattnera0e769c2004-10-10 16:47:33 +0000342
Chris Lattnercb9f1522004-10-10 16:43:46 +0000343 if (GEP->use_empty()) {
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000344 GEP->eraseFromParent();
Chris Lattnercb9f1522004-10-10 16:43:46 +0000345 Changed = true;
346 }
Chris Lattner7561ca12005-02-27 18:58:52 +0000347 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U)) { // memset/cpy/mv
348 if (MI->getRawDest() == V) {
349 MI->eraseFromParent();
350 Changed = true;
351 }
352
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000353 } else if (Constant *C = dyn_cast<Constant>(U)) {
354 // If we have a chain of dead constantexprs or other things dangling from
355 // us, and if they are all dead, nuke them without remorse.
356 if (ConstantIsDead(C)) {
357 C->destroyConstant();
Chris Lattner7561ca12005-02-27 18:58:52 +0000358 // This could have invalidated UI, start over from scratch.
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000359 CleanupConstantGlobalUsers(V, Init);
Chris Lattnercb9f1522004-10-10 16:43:46 +0000360 return true;
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000361 }
Chris Lattner25db5802004-10-07 04:16:33 +0000362 }
363 }
Chris Lattnercb9f1522004-10-10 16:43:46 +0000364 return Changed;
Chris Lattner25db5802004-10-07 04:16:33 +0000365}
366
Chris Lattnerabab0712004-10-08 17:32:09 +0000367/// SRAGlobal - Perform scalar replacement of aggregates on the specified global
368/// variable. This opens the door for other optimizations by exposing the
369/// behavior of the program in a more fine-grained way. We have determined that
370/// this transformation is safe already. We return the first global variable we
371/// insert so that the caller can reprocess it.
372static GlobalVariable *SRAGlobal(GlobalVariable *GV) {
373 assert(GV->hasInternalLinkage() && !GV->isConstant());
374 Constant *Init = GV->getInitializer();
375 const Type *Ty = Init->getType();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000376
Chris Lattnerabab0712004-10-08 17:32:09 +0000377 std::vector<GlobalVariable*> NewGlobals;
378 Module::GlobalListType &Globals = GV->getParent()->getGlobalList();
379
380 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
381 NewGlobals.reserve(STy->getNumElements());
382 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
383 Constant *In = getAggregateConstantElement(Init,
384 ConstantUInt::get(Type::UIntTy, i));
385 assert(In && "Couldn't get element of initializer?");
386 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(i), false,
387 GlobalVariable::InternalLinkage,
388 In, GV->getName()+"."+utostr(i));
389 Globals.insert(GV, NGV);
390 NewGlobals.push_back(NGV);
391 }
392 } else if (const SequentialType *STy = dyn_cast<SequentialType>(Ty)) {
393 unsigned NumElements = 0;
394 if (const ArrayType *ATy = dyn_cast<ArrayType>(STy))
395 NumElements = ATy->getNumElements();
396 else if (const PackedType *PTy = dyn_cast<PackedType>(STy))
397 NumElements = PTy->getNumElements();
398 else
399 assert(0 && "Unknown aggregate sequential type!");
400
Chris Lattner25169ca2005-02-23 16:53:04 +0000401 if (NumElements > 16 && GV->hasNUsesOrMore(16))
Chris Lattnerd6a44922005-02-01 01:23:31 +0000402 return 0; // It's not worth it.
Chris Lattnerabab0712004-10-08 17:32:09 +0000403 NewGlobals.reserve(NumElements);
404 for (unsigned i = 0, e = NumElements; i != e; ++i) {
405 Constant *In = getAggregateConstantElement(Init,
406 ConstantUInt::get(Type::UIntTy, i));
407 assert(In && "Couldn't get element of initializer?");
408
409 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(), false,
410 GlobalVariable::InternalLinkage,
411 In, GV->getName()+"."+utostr(i));
412 Globals.insert(GV, NGV);
413 NewGlobals.push_back(NGV);
414 }
415 }
416
417 if (NewGlobals.empty())
418 return 0;
419
Chris Lattner004e2502004-10-11 05:54:41 +0000420 DEBUG(std::cerr << "PERFORMING GLOBAL SRA ON: " << *GV);
421
Chris Lattnerabab0712004-10-08 17:32:09 +0000422 Constant *NullInt = Constant::getNullValue(Type::IntTy);
423
424 // Loop over all of the uses of the global, replacing the constantexpr geps,
425 // with smaller constantexpr geps or direct references.
426 while (!GV->use_empty()) {
Chris Lattner004e2502004-10-11 05:54:41 +0000427 User *GEP = GV->use_back();
428 assert(((isa<ConstantExpr>(GEP) &&
429 cast<ConstantExpr>(GEP)->getOpcode()==Instruction::GetElementPtr)||
430 isa<GetElementPtrInst>(GEP)) && "NonGEP CE's are not SRAable!");
Misha Brukmanb1c93172005-04-21 23:48:37 +0000431
Chris Lattnerabab0712004-10-08 17:32:09 +0000432 // Ignore the 1th operand, which has to be zero or else the program is quite
433 // broken (undefined). Get the 2nd operand, which is the structure or array
434 // index.
Chris Lattner46fa04b2005-01-08 19:45:31 +0000435 unsigned Val =
436 (unsigned)cast<ConstantInt>(GEP->getOperand(2))->getRawValue();
Chris Lattnerabab0712004-10-08 17:32:09 +0000437 if (Val >= NewGlobals.size()) Val = 0; // Out of bound array access.
438
Chris Lattner004e2502004-10-11 05:54:41 +0000439 Value *NewPtr = NewGlobals[Val];
Chris Lattnerabab0712004-10-08 17:32:09 +0000440
441 // Form a shorter GEP if needed.
Chris Lattner004e2502004-10-11 05:54:41 +0000442 if (GEP->getNumOperands() > 3)
443 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEP)) {
444 std::vector<Constant*> Idxs;
445 Idxs.push_back(NullInt);
446 for (unsigned i = 3, e = CE->getNumOperands(); i != e; ++i)
447 Idxs.push_back(CE->getOperand(i));
448 NewPtr = ConstantExpr::getGetElementPtr(cast<Constant>(NewPtr), Idxs);
449 } else {
450 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(GEP);
451 std::vector<Value*> Idxs;
452 Idxs.push_back(NullInt);
453 for (unsigned i = 3, e = GEPI->getNumOperands(); i != e; ++i)
454 Idxs.push_back(GEPI->getOperand(i));
455 NewPtr = new GetElementPtrInst(NewPtr, Idxs,
456 GEPI->getName()+"."+utostr(Val), GEPI);
457 }
458 GEP->replaceAllUsesWith(NewPtr);
459
460 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(GEP))
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000461 GEPI->eraseFromParent();
Chris Lattner004e2502004-10-11 05:54:41 +0000462 else
463 cast<ConstantExpr>(GEP)->destroyConstant();
Chris Lattnerabab0712004-10-08 17:32:09 +0000464 }
465
Chris Lattner73ad73e2004-10-08 20:25:55 +0000466 // Delete the old global, now that it is dead.
467 Globals.erase(GV);
Chris Lattnerabab0712004-10-08 17:32:09 +0000468 ++NumSRA;
Chris Lattner004e2502004-10-11 05:54:41 +0000469
470 // Loop over the new globals array deleting any globals that are obviously
471 // dead. This can arise due to scalarization of a structure or an array that
472 // has elements that are dead.
473 unsigned FirstGlobal = 0;
474 for (unsigned i = 0, e = NewGlobals.size(); i != e; ++i)
475 if (NewGlobals[i]->use_empty()) {
476 Globals.erase(NewGlobals[i]);
477 if (FirstGlobal == i) ++FirstGlobal;
478 }
479
480 return FirstGlobal != NewGlobals.size() ? NewGlobals[FirstGlobal] : 0;
Chris Lattnerabab0712004-10-08 17:32:09 +0000481}
482
Chris Lattner09a52722004-10-09 21:48:45 +0000483/// AllUsesOfValueWillTrapIfNull - Return true if all users of the specified
484/// value will trap if the value is dynamically null.
485static bool AllUsesOfValueWillTrapIfNull(Value *V) {
486 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
487 if (isa<LoadInst>(*UI)) {
488 // Will trap.
489 } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
490 if (SI->getOperand(0) == V) {
491 //std::cerr << "NONTRAPPING USE: " << **UI;
492 return false; // Storing the value.
493 }
494 } else if (CallInst *CI = dyn_cast<CallInst>(*UI)) {
495 if (CI->getOperand(0) != V) {
496 //std::cerr << "NONTRAPPING USE: " << **UI;
497 return false; // Not calling the ptr
498 }
499 } else if (InvokeInst *II = dyn_cast<InvokeInst>(*UI)) {
500 if (II->getOperand(0) != V) {
501 //std::cerr << "NONTRAPPING USE: " << **UI;
502 return false; // Not calling the ptr
503 }
504 } else if (CastInst *CI = dyn_cast<CastInst>(*UI)) {
505 if (!AllUsesOfValueWillTrapIfNull(CI)) return false;
506 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(*UI)) {
507 if (!AllUsesOfValueWillTrapIfNull(GEPI)) return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000508 } else if (isa<SetCondInst>(*UI) &&
Chris Lattnerfe9abf92004-10-22 06:43:28 +0000509 isa<ConstantPointerNull>(UI->getOperand(1))) {
510 // Ignore setcc X, null
Chris Lattner09a52722004-10-09 21:48:45 +0000511 } else {
512 //std::cerr << "NONTRAPPING USE: " << **UI;
513 return false;
514 }
515 return true;
516}
517
518/// AllUsesOfLoadedValueWillTrapIfNull - Return true if all uses of any loads
Chris Lattnerfe9abf92004-10-22 06:43:28 +0000519/// from GV will trap if the loaded value is null. Note that this also permits
520/// comparisons of the loaded value against null, as a special case.
Chris Lattner09a52722004-10-09 21:48:45 +0000521static bool AllUsesOfLoadedValueWillTrapIfNull(GlobalVariable *GV) {
522 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI!=E; ++UI)
523 if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
524 if (!AllUsesOfValueWillTrapIfNull(LI))
525 return false;
526 } else if (isa<StoreInst>(*UI)) {
527 // Ignore stores to the global.
528 } else {
529 // We don't know or understand this user, bail out.
530 //std::cerr << "UNKNOWN USER OF GLOBAL!: " << **UI;
531 return false;
532 }
533
534 return true;
535}
536
Chris Lattnere42eb312004-10-10 23:14:11 +0000537static bool OptimizeAwayTrappingUsesOfValue(Value *V, Constant *NewV) {
538 bool Changed = false;
539 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ) {
540 Instruction *I = cast<Instruction>(*UI++);
541 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
542 LI->setOperand(0, NewV);
543 Changed = true;
544 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
545 if (SI->getOperand(1) == V) {
546 SI->setOperand(1, NewV);
547 Changed = true;
548 }
549 } else if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
550 if (I->getOperand(0) == V) {
551 // Calling through the pointer! Turn into a direct call, but be careful
552 // that the pointer is not also being passed as an argument.
553 I->setOperand(0, NewV);
554 Changed = true;
555 bool PassedAsArg = false;
556 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i)
557 if (I->getOperand(i) == V) {
558 PassedAsArg = true;
559 I->setOperand(i, NewV);
560 }
561
562 if (PassedAsArg) {
563 // Being passed as an argument also. Be careful to not invalidate UI!
564 UI = V->use_begin();
565 }
566 }
567 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
568 Changed |= OptimizeAwayTrappingUsesOfValue(CI,
569 ConstantExpr::getCast(NewV, CI->getType()));
570 if (CI->use_empty()) {
571 Changed = true;
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000572 CI->eraseFromParent();
Chris Lattnere42eb312004-10-10 23:14:11 +0000573 }
574 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
575 // Should handle GEP here.
576 std::vector<Constant*> Indices;
577 Indices.reserve(GEPI->getNumOperands()-1);
578 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
579 if (Constant *C = dyn_cast<Constant>(GEPI->getOperand(i)))
580 Indices.push_back(C);
581 else
582 break;
583 if (Indices.size() == GEPI->getNumOperands()-1)
584 Changed |= OptimizeAwayTrappingUsesOfValue(GEPI,
585 ConstantExpr::getGetElementPtr(NewV, Indices));
586 if (GEPI->use_empty()) {
587 Changed = true;
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000588 GEPI->eraseFromParent();
Chris Lattnere42eb312004-10-10 23:14:11 +0000589 }
590 }
591 }
592
593 return Changed;
594}
595
596
597/// OptimizeAwayTrappingUsesOfLoads - The specified global has only one non-null
598/// value stored into it. If there are uses of the loaded value that would trap
599/// if the loaded value is dynamically null, then we know that they cannot be
600/// reachable with a null optimize away the load.
601static bool OptimizeAwayTrappingUsesOfLoads(GlobalVariable *GV, Constant *LV) {
602 std::vector<LoadInst*> Loads;
603 bool Changed = false;
604
605 // Replace all uses of loads with uses of uses of the stored value.
606 for (Value::use_iterator GUI = GV->use_begin(), E = GV->use_end();
607 GUI != E; ++GUI)
608 if (LoadInst *LI = dyn_cast<LoadInst>(*GUI)) {
609 Loads.push_back(LI);
610 Changed |= OptimizeAwayTrappingUsesOfValue(LI, LV);
611 } else {
612 assert(isa<StoreInst>(*GUI) && "Only expect load and stores!");
613 }
614
615 if (Changed) {
616 DEBUG(std::cerr << "OPTIMIZED LOADS FROM STORED ONCE POINTER: " << *GV);
617 ++NumGlobUses;
618 }
619
620 // Delete all of the loads we can, keeping track of whether we nuked them all!
621 bool AllLoadsGone = true;
622 while (!Loads.empty()) {
623 LoadInst *L = Loads.back();
624 if (L->use_empty()) {
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000625 L->eraseFromParent();
Chris Lattnere42eb312004-10-10 23:14:11 +0000626 Changed = true;
627 } else {
628 AllLoadsGone = false;
629 }
630 Loads.pop_back();
631 }
632
633 // If we nuked all of the loads, then none of the stores are needed either,
634 // nor is the global.
635 if (AllLoadsGone) {
636 DEBUG(std::cerr << " *** GLOBAL NOW DEAD!\n");
637 CleanupConstantGlobalUsers(GV, 0);
638 if (GV->use_empty()) {
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000639 GV->eraseFromParent();
Chris Lattnere42eb312004-10-10 23:14:11 +0000640 ++NumDeleted;
641 }
642 Changed = true;
643 }
644 return Changed;
645}
646
Chris Lattner004e2502004-10-11 05:54:41 +0000647/// ConstantPropUsersOf - Walk the use list of V, constant folding all of the
648/// instructions that are foldable.
649static void ConstantPropUsersOf(Value *V) {
650 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; )
651 if (Instruction *I = dyn_cast<Instruction>(*UI++))
652 if (Constant *NewC = ConstantFoldInstruction(I)) {
653 I->replaceAllUsesWith(NewC);
654
Chris Lattnerd6a44922005-02-01 01:23:31 +0000655 // Advance UI to the next non-I use to avoid invalidating it!
656 // Instructions could multiply use V.
657 while (UI != E && *UI == I)
Chris Lattner004e2502004-10-11 05:54:41 +0000658 ++UI;
Chris Lattnerd6a44922005-02-01 01:23:31 +0000659 I->eraseFromParent();
Chris Lattner004e2502004-10-11 05:54:41 +0000660 }
661}
662
663/// OptimizeGlobalAddressOfMalloc - This function takes the specified global
664/// variable, and transforms the program as if it always contained the result of
665/// the specified malloc. Because it is always the result of the specified
666/// malloc, there is no reason to actually DO the malloc. Instead, turn the
667/// malloc into a global, and any laods of GV as uses of the new global.
668static GlobalVariable *OptimizeGlobalAddressOfMalloc(GlobalVariable *GV,
669 MallocInst *MI) {
670 DEBUG(std::cerr << "PROMOTING MALLOC GLOBAL: " << *GV << " MALLOC = " <<*MI);
671 ConstantInt *NElements = cast<ConstantInt>(MI->getArraySize());
672
673 if (NElements->getRawValue() != 1) {
674 // If we have an array allocation, transform it to a single element
675 // allocation to make the code below simpler.
676 Type *NewTy = ArrayType::get(MI->getAllocatedType(),
Chris Lattner46fa04b2005-01-08 19:45:31 +0000677 (unsigned)NElements->getRawValue());
Chris Lattner004e2502004-10-11 05:54:41 +0000678 MallocInst *NewMI =
679 new MallocInst(NewTy, Constant::getNullValue(Type::UIntTy),
680 MI->getName(), MI);
681 std::vector<Value*> Indices;
682 Indices.push_back(Constant::getNullValue(Type::IntTy));
683 Indices.push_back(Indices[0]);
684 Value *NewGEP = new GetElementPtrInst(NewMI, Indices,
685 NewMI->getName()+".el0", MI);
686 MI->replaceAllUsesWith(NewGEP);
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000687 MI->eraseFromParent();
Chris Lattner004e2502004-10-11 05:54:41 +0000688 MI = NewMI;
689 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000690
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000691 // Create the new global variable. The contents of the malloc'd memory is
692 // undefined, so initialize with an undef value.
693 Constant *Init = UndefValue::get(MI->getAllocatedType());
Chris Lattner004e2502004-10-11 05:54:41 +0000694 GlobalVariable *NewGV = new GlobalVariable(MI->getAllocatedType(), false,
695 GlobalValue::InternalLinkage, Init,
696 GV->getName()+".body");
697 GV->getParent()->getGlobalList().insert(GV, NewGV);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000698
Chris Lattner004e2502004-10-11 05:54:41 +0000699 // Anything that used the malloc now uses the global directly.
700 MI->replaceAllUsesWith(NewGV);
Chris Lattner004e2502004-10-11 05:54:41 +0000701
702 Constant *RepValue = NewGV;
703 if (NewGV->getType() != GV->getType()->getElementType())
704 RepValue = ConstantExpr::getCast(RepValue, GV->getType()->getElementType());
705
Chris Lattnerfe9abf92004-10-22 06:43:28 +0000706 // If there is a comparison against null, we will insert a global bool to
707 // keep track of whether the global was initialized yet or not.
Misha Brukmanb1c93172005-04-21 23:48:37 +0000708 GlobalVariable *InitBool =
709 new GlobalVariable(Type::BoolTy, false, GlobalValue::InternalLinkage,
Chris Lattner3b181392004-12-02 06:25:58 +0000710 ConstantBool::False, GV->getName()+".init");
711 bool InitBoolUsed = false;
Chris Lattnerfe9abf92004-10-22 06:43:28 +0000712
Chris Lattner004e2502004-10-11 05:54:41 +0000713 // Loop over all uses of GV, processing them in turn.
Chris Lattner3b181392004-12-02 06:25:58 +0000714 std::vector<StoreInst*> Stores;
Chris Lattner004e2502004-10-11 05:54:41 +0000715 while (!GV->use_empty())
716 if (LoadInst *LI = dyn_cast<LoadInst>(GV->use_back())) {
Chris Lattnerfe9abf92004-10-22 06:43:28 +0000717 while (!LI->use_empty()) {
Chris Lattnerd6a44922005-02-01 01:23:31 +0000718 Use &LoadUse = LI->use_begin().getUse();
Chris Lattnerfe9abf92004-10-22 06:43:28 +0000719 if (!isa<SetCondInst>(LoadUse.getUser()))
720 LoadUse = RepValue;
721 else {
Chris Lattnerfe9abf92004-10-22 06:43:28 +0000722 // Replace the setcc X, 0 with a use of the bool value.
723 SetCondInst *SCI = cast<SetCondInst>(LoadUse.getUser());
724 Value *LV = new LoadInst(InitBool, InitBool->getName()+".val", SCI);
Chris Lattner3b181392004-12-02 06:25:58 +0000725 InitBoolUsed = true;
Chris Lattnerfe9abf92004-10-22 06:43:28 +0000726 switch (SCI->getOpcode()) {
727 default: assert(0 && "Unknown opcode!");
728 case Instruction::SetLT:
729 LV = ConstantBool::False; // X < null -> always false
730 break;
731 case Instruction::SetEQ:
732 case Instruction::SetLE:
733 LV = BinaryOperator::createNot(LV, "notinit", SCI);
734 break;
735 case Instruction::SetNE:
736 case Instruction::SetGE:
737 case Instruction::SetGT:
738 break; // no change.
739 }
740 SCI->replaceAllUsesWith(LV);
741 SCI->eraseFromParent();
742 }
743 }
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000744 LI->eraseFromParent();
Chris Lattner004e2502004-10-11 05:54:41 +0000745 } else {
746 StoreInst *SI = cast<StoreInst>(GV->use_back());
Chris Lattner3b181392004-12-02 06:25:58 +0000747 // The global is initialized when the store to it occurs.
748 new StoreInst(ConstantBool::True, InitBool, SI);
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000749 SI->eraseFromParent();
Chris Lattner004e2502004-10-11 05:54:41 +0000750 }
751
Chris Lattner3b181392004-12-02 06:25:58 +0000752 // If the initialization boolean was used, insert it, otherwise delete it.
753 if (!InitBoolUsed) {
754 while (!InitBool->use_empty()) // Delete initializations
755 cast<Instruction>(InitBool->use_back())->eraseFromParent();
756 delete InitBool;
757 } else
758 GV->getParent()->getGlobalList().insert(GV, InitBool);
759
760
Chris Lattnerfe9abf92004-10-22 06:43:28 +0000761 // Now the GV is dead, nuke it and the malloc.
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000762 GV->eraseFromParent();
Chris Lattnerfe9abf92004-10-22 06:43:28 +0000763 MI->eraseFromParent();
Chris Lattner004e2502004-10-11 05:54:41 +0000764
765 // To further other optimizations, loop over all users of NewGV and try to
766 // constant prop them. This will promote GEP instructions with constant
767 // indices into GEP constant-exprs, which will allow global-opt to hack on it.
768 ConstantPropUsersOf(NewGV);
769 if (RepValue != NewGV)
770 ConstantPropUsersOf(RepValue);
771
772 return NewGV;
773}
Chris Lattnere42eb312004-10-10 23:14:11 +0000774
Chris Lattnerc0677c02004-12-02 07:11:07 +0000775/// ValueIsOnlyUsedLocallyOrStoredToOneGlobal - Scan the use-list of V checking
776/// to make sure that there are no complex uses of V. We permit simple things
777/// like dereferencing the pointer, but not storing through the address, unless
778/// it is to the specified global.
779static bool ValueIsOnlyUsedLocallyOrStoredToOneGlobal(Instruction *V,
780 GlobalVariable *GV) {
781 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;++UI)
782 if (isa<LoadInst>(*UI) || isa<SetCondInst>(*UI)) {
783 // Fine, ignore.
784 } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
785 if (SI->getOperand(0) == V && SI->getOperand(1) != GV)
786 return false; // Storing the pointer itself... bad.
787 // Otherwise, storing through it, or storing into GV... fine.
788 } else if (isa<GetElementPtrInst>(*UI) || isa<SelectInst>(*UI)) {
789 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(cast<Instruction>(*UI),GV))
790 return false;
791 } else {
792 return false;
793 }
794 return true;
795
796}
797
Chris Lattner09a52722004-10-09 21:48:45 +0000798// OptimizeOnceStoredGlobal - Try to optimize globals based on the knowledge
799// that only one value (besides its initializer) is ever stored to the global.
Chris Lattner004e2502004-10-11 05:54:41 +0000800static bool OptimizeOnceStoredGlobal(GlobalVariable *GV, Value *StoredOnceVal,
Chris Lattner531f9e92005-03-15 04:54:21 +0000801 Module::global_iterator &GVI, TargetData &TD) {
Chris Lattner09a52722004-10-09 21:48:45 +0000802 if (CastInst *CI = dyn_cast<CastInst>(StoredOnceVal))
803 StoredOnceVal = CI->getOperand(0);
804 else if (GetElementPtrInst *GEPI =dyn_cast<GetElementPtrInst>(StoredOnceVal)){
Chris Lattnere42eb312004-10-10 23:14:11 +0000805 // "getelementptr Ptr, 0, 0, 0" is really just a cast.
Chris Lattner09a52722004-10-09 21:48:45 +0000806 bool IsJustACast = true;
807 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
808 if (!isa<Constant>(GEPI->getOperand(i)) ||
809 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
810 IsJustACast = false;
811 break;
812 }
813 if (IsJustACast)
814 StoredOnceVal = GEPI->getOperand(0);
815 }
816
Chris Lattnere42eb312004-10-10 23:14:11 +0000817 // If we are dealing with a pointer global that is initialized to null and
818 // only has one (non-null) value stored into it, then we can optimize any
819 // users of the loaded value (often calls and loads) that would trap if the
820 // value was null.
Chris Lattner09a52722004-10-09 21:48:45 +0000821 if (isa<PointerType>(GV->getInitializer()->getType()) &&
822 GV->getInitializer()->isNullValue()) {
Chris Lattnere42eb312004-10-10 23:14:11 +0000823 if (Constant *SOVC = dyn_cast<Constant>(StoredOnceVal)) {
824 if (GV->getInitializer()->getType() != SOVC->getType())
825 SOVC = ConstantExpr::getCast(SOVC, GV->getInitializer()->getType());
Misha Brukmanb1c93172005-04-21 23:48:37 +0000826
Chris Lattnere42eb312004-10-10 23:14:11 +0000827 // Optimize away any trapping uses of the loaded value.
828 if (OptimizeAwayTrappingUsesOfLoads(GV, SOVC))
Chris Lattner604ed7a2004-10-10 17:07:12 +0000829 return true;
Chris Lattner004e2502004-10-11 05:54:41 +0000830 } else if (MallocInst *MI = dyn_cast<MallocInst>(StoredOnceVal)) {
831 // If we have a global that is only initialized with a fixed size malloc,
832 // and if all users of the malloc trap, and if the malloc'd address is not
833 // put anywhere else, transform the program to use global memory instead
834 // of malloc'd memory. This eliminates dynamic allocation (good) and
835 // exposes the resultant global to further GlobalOpt (even better). Note
836 // that we restrict this transformation to only working on small
837 // allocations (2048 bytes currently), as we don't want to introduce a 16M
838 // global or something.
839 if (ConstantInt *NElements = dyn_cast<ConstantInt>(MI->getArraySize()))
840 if (MI->getAllocatedType()->isSized() &&
841 NElements->getRawValue()*
842 TD.getTypeSize(MI->getAllocatedType()) < 2048 &&
Chris Lattnerc0677c02004-12-02 07:11:07 +0000843 AllUsesOfLoadedValueWillTrapIfNull(GV) &&
844 ValueIsOnlyUsedLocallyOrStoredToOneGlobal(MI, GV)) {
Chris Lattner004e2502004-10-11 05:54:41 +0000845 GVI = OptimizeGlobalAddressOfMalloc(GV, MI);
846 return true;
847 }
Chris Lattnere42eb312004-10-10 23:14:11 +0000848 }
Chris Lattner09a52722004-10-09 21:48:45 +0000849 }
Chris Lattner004e2502004-10-11 05:54:41 +0000850
Chris Lattner09a52722004-10-09 21:48:45 +0000851 return false;
852}
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000853
Chris Lattner40e4cec2004-12-12 05:53:50 +0000854/// ShrinkGlobalToBoolean - At this point, we have learned that the only two
Misha Brukmanb1c93172005-04-21 23:48:37 +0000855/// values ever stored into GV are its initializer and OtherVal.
Chris Lattner40e4cec2004-12-12 05:53:50 +0000856static void ShrinkGlobalToBoolean(GlobalVariable *GV, Constant *OtherVal) {
857 // Create the new global, initializing it to false.
858 GlobalVariable *NewGV = new GlobalVariable(Type::BoolTy, false,
859 GlobalValue::InternalLinkage, ConstantBool::False, GV->getName()+".b");
860 GV->getParent()->getGlobalList().insert(GV, NewGV);
861
862 Constant *InitVal = GV->getInitializer();
863 assert(InitVal->getType() != Type::BoolTy && "No reason to shrink to bool!");
864
865 // If initialized to zero and storing one into the global, we can use a cast
866 // instead of a select to synthesize the desired value.
867 bool IsOneZero = false;
868 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal))
869 IsOneZero = InitVal->isNullValue() && CI->equalsInt(1);
870
871 while (!GV->use_empty()) {
872 Instruction *UI = cast<Instruction>(GV->use_back());
873 if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
874 // Change the store into a boolean store.
875 bool StoringOther = SI->getOperand(0) == OtherVal;
876 // Only do this if we weren't storing a loaded value.
Chris Lattner745196a2004-12-12 19:34:41 +0000877 Value *StoreVal;
Chris Lattner40e4cec2004-12-12 05:53:50 +0000878 if (StoringOther || SI->getOperand(0) == InitVal)
Chris Lattner745196a2004-12-12 19:34:41 +0000879 StoreVal = ConstantBool::get(StoringOther);
880 else {
881 // Otherwise, we are storing a previously loaded copy. To do this,
882 // change the copy from copying the original value to just copying the
883 // bool.
884 Instruction *StoredVal = cast<Instruction>(SI->getOperand(0));
885
886 // If we're already replaced the input, StoredVal will be a cast or
887 // select instruction. If not, it will be a load of the original
888 // global.
889 if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
890 assert(LI->getOperand(0) == GV && "Not a copy!");
891 // Insert a new load, to preserve the saved value.
892 StoreVal = new LoadInst(NewGV, LI->getName()+".b", LI);
893 } else {
894 assert((isa<CastInst>(StoredVal) || isa<SelectInst>(StoredVal)) &&
895 "This is not a form that we understand!");
896 StoreVal = StoredVal->getOperand(0);
897 assert(isa<LoadInst>(StoreVal) && "Not a load of NewGV!");
898 }
899 }
900 new StoreInst(StoreVal, NewGV, SI);
901 } else if (!UI->use_empty()) {
Chris Lattner40e4cec2004-12-12 05:53:50 +0000902 // Change the load into a load of bool then a select.
903 LoadInst *LI = cast<LoadInst>(UI);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000904
Chris Lattner40e4cec2004-12-12 05:53:50 +0000905 std::string Name = LI->getName(); LI->setName("");
906 LoadInst *NLI = new LoadInst(NewGV, Name+".b", LI);
907 Value *NSI;
908 if (IsOneZero)
909 NSI = new CastInst(NLI, LI->getType(), Name, LI);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000910 else
Chris Lattner40e4cec2004-12-12 05:53:50 +0000911 NSI = new SelectInst(NLI, OtherVal, InitVal, Name, LI);
912 LI->replaceAllUsesWith(NSI);
913 }
914 UI->eraseFromParent();
915 }
916
917 GV->eraseFromParent();
918}
919
920
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000921/// ProcessInternalGlobal - Analyze the specified global variable and optimize
922/// it if possible. If we make a change, return true.
Chris Lattner004e2502004-10-11 05:54:41 +0000923bool GlobalOpt::ProcessInternalGlobal(GlobalVariable *GV,
Chris Lattner531f9e92005-03-15 04:54:21 +0000924 Module::global_iterator &GVI) {
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000925 std::set<PHINode*> PHIUsers;
926 GlobalStatus GS;
927 PHIUsers.clear();
928 GV->removeDeadConstantUsers();
929
930 if (GV->use_empty()) {
931 DEBUG(std::cerr << "GLOBAL DEAD: " << *GV);
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000932 GV->eraseFromParent();
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000933 ++NumDeleted;
934 return true;
935 }
936
937 if (!AnalyzeGlobal(GV, GS, PHIUsers)) {
Alkis Evlogimenosc4a44c62005-02-10 18:36:30 +0000938 // If this is a first class global and has only one accessing function
939 // and this function is main (which we know is not recursive we can make
940 // this global a local variable) we replace the global with a local alloca
941 // in this function.
942 //
943 // NOTE: It doesn't make sense to promote non first class types since we
944 // are just replacing static memory to stack memory.
945 if (!GS.HasMultipleAccessingFunctions &&
Chris Lattner50bdfcb2005-06-15 21:11:48 +0000946 GS.AccessingFunction && !GS.HasNonInstructionUser &&
Alkis Evlogimenosc4a44c62005-02-10 18:36:30 +0000947 GV->getType()->getElementType()->isFirstClassType() &&
948 GS.AccessingFunction->getName() == "main" &&
949 GS.AccessingFunction->hasExternalLinkage()) {
950 DEBUG(std::cerr << "LOCALIZING GLOBAL: " << *GV);
951 Instruction* FirstI = GS.AccessingFunction->getEntryBlock().begin();
952 const Type* ElemTy = GV->getType()->getElementType();
953 AllocaInst* Alloca = new AllocaInst(ElemTy, NULL, GV->getName(), FirstI);
954 if (!isa<UndefValue>(GV->getInitializer()))
955 new StoreInst(GV->getInitializer(), Alloca, FirstI);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000956
Alkis Evlogimenosc4a44c62005-02-10 18:36:30 +0000957 GV->replaceAllUsesWith(Alloca);
958 GV->eraseFromParent();
959 ++NumLocalized;
960 return true;
961 }
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000962 // If the global is never loaded (but may be stored to), it is dead.
963 // Delete it now.
964 if (!GS.isLoaded) {
965 DEBUG(std::cerr << "GLOBAL NEVER LOADED: " << *GV);
Chris Lattnerf369b382004-10-09 03:32:52 +0000966
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000967 // Delete any stores we can find to the global. We may not be able to
968 // make it completely dead though.
Chris Lattnercb9f1522004-10-10 16:43:46 +0000969 bool Changed = CleanupConstantGlobalUsers(GV, GV->getInitializer());
Chris Lattnerf369b382004-10-09 03:32:52 +0000970
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000971 // If the global is dead now, delete it.
972 if (GV->use_empty()) {
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000973 GV->eraseFromParent();
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000974 ++NumDeleted;
Chris Lattnerf369b382004-10-09 03:32:52 +0000975 Changed = true;
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000976 }
Chris Lattnerf369b382004-10-09 03:32:52 +0000977 return Changed;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000978
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000979 } else if (GS.StoredType <= GlobalStatus::isInitializerStored) {
980 DEBUG(std::cerr << "MARKING CONSTANT: " << *GV);
981 GV->setConstant(true);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000982
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000983 // Clean up any obviously simplifiable users now.
984 CleanupConstantGlobalUsers(GV, GV->getInitializer());
Misha Brukmanb1c93172005-04-21 23:48:37 +0000985
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000986 // If the global is dead now, just nuke it.
987 if (GV->use_empty()) {
988 DEBUG(std::cerr << " *** Marking constant allowed us to simplify "
989 "all users and delete global!\n");
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000990 GV->eraseFromParent();
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000991 ++NumDeleted;
992 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000993
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000994 ++NumMarked;
995 return true;
996 } else if (!GS.isNotSuitableForSRA &&
997 !GV->getInitializer()->getType()->isFirstClassType()) {
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000998 if (GlobalVariable *FirstNewGV = SRAGlobal(GV)) {
999 GVI = FirstNewGV; // Don't skip the newly produced globals!
1000 return true;
1001 }
Chris Lattner09a52722004-10-09 21:48:45 +00001002 } else if (GS.StoredType == GlobalStatus::isStoredOnce) {
Chris Lattner40e4cec2004-12-12 05:53:50 +00001003 // If the initial value for the global was an undef value, and if only
1004 // one other value was stored into it, we can just change the
1005 // initializer to be an undef value, then delete all stores to the
1006 // global. This allows us to mark it constant.
1007 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
1008 if (isa<UndefValue>(GV->getInitializer())) {
1009 // Change the initial value here.
1010 GV->setInitializer(SOVConstant);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001011
Chris Lattner40e4cec2004-12-12 05:53:50 +00001012 // Clean up any obviously simplifiable users now.
1013 CleanupConstantGlobalUsers(GV, GV->getInitializer());
Misha Brukmanb1c93172005-04-21 23:48:37 +00001014
Chris Lattner40e4cec2004-12-12 05:53:50 +00001015 if (GV->use_empty()) {
1016 DEBUG(std::cerr << " *** Substituting initializer allowed us to "
1017 "simplify all users and delete global!\n");
1018 GV->eraseFromParent();
1019 ++NumDeleted;
1020 } else {
1021 GVI = GV;
1022 }
1023 ++NumSubstitute;
1024 return true;
Chris Lattner8e71c6a2004-10-16 18:09:00 +00001025 }
Chris Lattner8e71c6a2004-10-16 18:09:00 +00001026
Chris Lattner09a52722004-10-09 21:48:45 +00001027 // Try to optimize globals based on the knowledge that only one value
1028 // (besides its initializer) is ever stored to the global.
Chris Lattner004e2502004-10-11 05:54:41 +00001029 if (OptimizeOnceStoredGlobal(GV, GS.StoredOnceValue, GVI,
1030 getAnalysis<TargetData>()))
Chris Lattner09a52722004-10-09 21:48:45 +00001031 return true;
Chris Lattner40e4cec2004-12-12 05:53:50 +00001032
1033 // Otherwise, if the global was not a boolean, we can shrink it to be a
1034 // boolean.
1035 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
Chris Lattner1cbd5be2004-12-12 06:03:06 +00001036 if (GV->getType()->getElementType() != Type::BoolTy &&
1037 !GV->getType()->getElementType()->isFloatingPoint()) {
Chris Lattner40e4cec2004-12-12 05:53:50 +00001038 DEBUG(std::cerr << " *** SHRINKING TO BOOL: " << *GV);
1039 ShrinkGlobalToBoolean(GV, SOVConstant);
1040 ++NumShrunkToBool;
1041 return true;
1042 }
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001043 }
1044 }
1045 return false;
1046}
1047
Chris Lattnera4c80222005-05-08 22:18:06 +00001048/// OnlyCalledDirectly - Return true if the specified function is only called
1049/// directly. In other words, its address is never taken.
1050static bool OnlyCalledDirectly(Function *F) {
1051 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
1052 Instruction *User = dyn_cast<Instruction>(*UI);
1053 if (!User) return false;
1054 if (!isa<CallInst>(User) && !isa<InvokeInst>(User)) return false;
1055
1056 // See if the function address is passed as an argument.
1057 for (unsigned i = 1, e = User->getNumOperands(); i != e; ++i)
1058 if (User->getOperand(i) == F) return false;
1059 }
1060 return true;
1061}
1062
1063/// ChangeCalleesToFastCall - Walk all of the direct calls of the specified
1064/// function, changing them to FastCC.
1065static void ChangeCalleesToFastCall(Function *F) {
1066 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
1067 Instruction *User = cast<Instruction>(*UI);
1068 if (CallInst *CI = dyn_cast<CallInst>(User))
1069 CI->setCallingConv(CallingConv::Fast);
1070 else
1071 cast<InvokeInst>(User)->setCallingConv(CallingConv::Fast);
1072 }
1073}
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001074
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001075bool GlobalOpt::OptimizeFunctions(Module &M) {
1076 bool Changed = false;
1077 // Optimize functions.
1078 for (Module::iterator FI = M.begin(), E = M.end(); FI != E; ) {
1079 Function *F = FI++;
1080 F->removeDeadConstantUsers();
1081 if (F->use_empty() && (F->hasInternalLinkage() ||
1082 F->hasLinkOnceLinkage())) {
1083 M.getFunctionList().erase(F);
1084 Changed = true;
1085 ++NumFnDeleted;
1086 } else if (F->hasInternalLinkage() &&
1087 F->getCallingConv() == CallingConv::C && !F->isVarArg() &&
1088 OnlyCalledDirectly(F)) {
1089 // If this function has C calling conventions, is not a varargs
1090 // function, and is only called directly, promote it to use the Fast
1091 // calling convention.
1092 F->setCallingConv(CallingConv::Fast);
1093 ChangeCalleesToFastCall(F);
1094 ++NumFastCallFns;
1095 Changed = true;
1096 }
1097 }
1098 return Changed;
1099}
1100
1101bool GlobalOpt::OptimizeGlobalVars(Module &M) {
1102 bool Changed = false;
1103 for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
1104 GVI != E; ) {
1105 GlobalVariable *GV = GVI++;
1106 if (!GV->isConstant() && GV->hasInternalLinkage() &&
1107 GV->hasInitializer())
1108 Changed |= ProcessInternalGlobal(GV, GVI);
1109 }
1110 return Changed;
1111}
1112
1113/// FindGlobalCtors - Find the llvm.globalctors list, verifying that all
1114/// initializers have an init priority of 65535.
1115GlobalVariable *GlobalOpt::FindGlobalCtors(Module &M) {
1116 for (Module::giterator I = M.global_begin(), E = M.global_end(); I != E; ++I)
1117 if (I->getName() == "llvm.global_ctors") {
1118 // Found it, verify it's an array of { int, void()* }.
1119 const ArrayType *ATy =dyn_cast<ArrayType>(I->getType()->getElementType());
1120 if (!ATy) return 0;
1121 const StructType *STy = dyn_cast<StructType>(ATy->getElementType());
1122 if (!STy || STy->getNumElements() != 2 ||
1123 STy->getElementType(0) != Type::IntTy) return 0;
1124 const PointerType *PFTy = dyn_cast<PointerType>(STy->getElementType(1));
1125 if (!PFTy) return 0;
1126 const FunctionType *FTy = dyn_cast<FunctionType>(PFTy->getElementType());
1127 if (!FTy || FTy->getReturnType() != Type::VoidTy || FTy->isVarArg() ||
1128 FTy->getNumParams() != 0)
1129 return 0;
1130
1131 // Verify that the initializer is simple enough for us to handle.
1132 if (!I->hasInitializer()) return 0;
1133 ConstantArray *CA = dyn_cast<ConstantArray>(I->getInitializer());
1134 if (!CA) return 0;
1135 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1136 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(CA->getOperand(i))) {
Chris Lattner838bdc12005-09-26 02:19:27 +00001137 if (isa<ConstantPointerNull>(CS->getOperand(1)))
1138 continue;
1139
1140 // Must have a function or null ptr.
1141 if (!isa<Function>(CS->getOperand(1)))
1142 return 0;
1143
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001144 // Init priority must be standard.
1145 ConstantInt *CI = dyn_cast<ConstantInt>(CS->getOperand(0));
1146 if (!CI || CI->getRawValue() != 65535)
1147 return 0;
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001148 } else {
1149 return 0;
1150 }
1151
1152 return I;
1153 }
1154 return 0;
1155}
1156
Chris Lattner696beef2005-09-26 02:31:18 +00001157/// ParseGlobalCtors - Given a llvm.global_ctors list that we can understand,
1158/// return a list of the functions and null terminator as a vector.
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001159static std::vector<Function*> ParseGlobalCtors(GlobalVariable *GV) {
1160 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
1161 std::vector<Function*> Result;
1162 Result.reserve(CA->getNumOperands());
1163 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i) {
1164 ConstantStruct *CS = cast<ConstantStruct>(CA->getOperand(i));
1165 Result.push_back(dyn_cast<Function>(CS->getOperand(1)));
1166 }
1167 return Result;
1168}
1169
Chris Lattner696beef2005-09-26 02:31:18 +00001170/// InstallGlobalCtors - Given a specified llvm.global_ctors list, install the
1171/// specified array, returning the new global to use.
1172static GlobalVariable *InstallGlobalCtors(GlobalVariable *GCL,
1173 const std::vector<Function*> &Ctors) {
1174 // If we made a change, reassemble the initializer list.
1175 std::vector<Constant*> CSVals;
1176 CSVals.push_back(ConstantSInt::get(Type::IntTy, 65535));
1177 CSVals.push_back(0);
1178
1179 // Create the new init list.
1180 std::vector<Constant*> CAList;
1181 for (unsigned i = 0, e = Ctors.size(); i != e; ++i) {
Chris Lattner99e23fa2005-09-26 04:44:35 +00001182 if (Ctors[i]) {
Chris Lattner696beef2005-09-26 02:31:18 +00001183 CSVals[1] = Ctors[i];
Chris Lattner99e23fa2005-09-26 04:44:35 +00001184 } else {
Chris Lattner696beef2005-09-26 02:31:18 +00001185 const Type *FTy = FunctionType::get(Type::VoidTy,
1186 std::vector<const Type*>(), false);
1187 const PointerType *PFTy = PointerType::get(FTy);
1188 CSVals[1] = Constant::getNullValue(PFTy);
1189 CSVals[0] = ConstantSInt::get(Type::IntTy, 2147483647);
1190 }
1191 CAList.push_back(ConstantStruct::get(CSVals));
1192 }
1193
1194 // Create the array initializer.
1195 const Type *StructTy =
1196 cast<ArrayType>(GCL->getType()->getElementType())->getElementType();
1197 Constant *CA = ConstantArray::get(ArrayType::get(StructTy, CAList.size()),
1198 CAList);
1199
1200 // If we didn't change the number of elements, don't create a new GV.
1201 if (CA->getType() == GCL->getInitializer()->getType()) {
1202 GCL->setInitializer(CA);
1203 return GCL;
1204 }
1205
1206 // Create the new global and insert it next to the existing list.
1207 GlobalVariable *NGV = new GlobalVariable(CA->getType(), GCL->isConstant(),
1208 GCL->getLinkage(), CA,
1209 GCL->getName());
1210 GCL->setName("");
1211 GCL->getParent()->getGlobalList().insert(GCL, NGV);
1212
1213 // Nuke the old list, replacing any uses with the new one.
1214 if (!GCL->use_empty()) {
1215 Constant *V = NGV;
1216 if (V->getType() != GCL->getType())
1217 V = ConstantExpr::getCast(V, GCL->getType());
1218 GCL->replaceAllUsesWith(V);
1219 }
1220 GCL->eraseFromParent();
1221
1222 if (Ctors.size())
1223 return NGV;
1224 else
1225 return 0;
1226}
Chris Lattner99e23fa2005-09-26 04:44:35 +00001227
1228
1229static Constant *getVal(std::map<Value*, Constant*> &ComputedValues,
1230 Value *V) {
1231 if (Constant *CV = dyn_cast<Constant>(V)) return CV;
1232 Constant *R = ComputedValues[V];
1233 assert(R && "Reference to an uncomputed value!");
1234 return R;
1235}
1236
1237/// isSimpleEnoughPointerToCommit - Return true if this constant is simple
1238/// enough for us to understand. In particular, if it is a cast of something,
1239/// we punt. We basically just support direct accesses to globals and GEP's of
1240/// globals. This should be kept up to date with CommitValueTo.
1241static bool isSimpleEnoughPointerToCommit(Constant *C) {
1242 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
1243 return !GV->isExternal(); // reject external globals.
Chris Lattner46af55e2005-09-26 06:52:44 +00001244 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
1245 // Handle a constantexpr gep.
1246 if (CE->getOpcode() == Instruction::GetElementPtr &&
1247 isa<GlobalVariable>(CE->getOperand(0))) {
1248 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
1249 return GV->hasInitializer() &&
1250 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
1251 }
Chris Lattner99e23fa2005-09-26 04:44:35 +00001252 return false;
1253}
1254
Chris Lattner46af55e2005-09-26 06:52:44 +00001255/// EvaluateStoreInto - Evaluate a piece of a constantexpr store into a global
1256/// initializer. This returns 'Init' modified to reflect 'Val' stored into it.
1257/// At this point, the GEP operands of Addr [0, OpNo) have been stepped into.
1258static Constant *EvaluateStoreInto(Constant *Init, Constant *Val,
1259 ConstantExpr *Addr, unsigned OpNo) {
1260 // Base case of the recursion.
1261 if (OpNo == Addr->getNumOperands()) {
1262 assert(Val->getType() == Init->getType() && "Type mismatch!");
1263 return Val;
1264 }
1265
1266 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
1267 std::vector<Constant*> Elts;
1268
1269 // Break up the constant into its elements.
1270 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
1271 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i)
1272 Elts.push_back(CS->getOperand(i));
1273 } else if (isa<ConstantAggregateZero>(Init)) {
1274 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
1275 Elts.push_back(Constant::getNullValue(STy->getElementType(i)));
1276 } else if (isa<UndefValue>(Init)) {
1277 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
1278 Elts.push_back(UndefValue::get(STy->getElementType(i)));
1279 } else {
1280 assert(0 && "This code is out of sync with "
1281 " ConstantFoldLoadThroughGEPConstantExpr");
1282 }
1283
1284 // Replace the element that we are supposed to.
1285 ConstantUInt *CU = cast<ConstantUInt>(Addr->getOperand(OpNo));
1286 assert(CU->getValue() < STy->getNumElements() &&
1287 "Struct index out of range!");
1288 unsigned Idx = (unsigned)CU->getValue();
1289 Elts[Idx] = EvaluateStoreInto(Elts[Idx], Val, Addr, OpNo+1);
1290
1291 // Return the modified struct.
1292 return ConstantStruct::get(Elts);
1293 } else {
1294 ConstantInt *CI = cast<ConstantInt>(Addr->getOperand(OpNo));
1295 const ArrayType *ATy = cast<ArrayType>(Init->getType());
1296
1297 // Break up the array into elements.
1298 std::vector<Constant*> Elts;
1299 if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
1300 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1301 Elts.push_back(CA->getOperand(i));
1302 } else if (isa<ConstantAggregateZero>(Init)) {
1303 Constant *Elt = Constant::getNullValue(ATy->getElementType());
1304 Elts.assign(ATy->getNumElements(), Elt);
1305 } else if (isa<UndefValue>(Init)) {
1306 Constant *Elt = UndefValue::get(ATy->getElementType());
1307 Elts.assign(ATy->getNumElements(), Elt);
1308 } else {
1309 assert(0 && "This code is out of sync with "
1310 " ConstantFoldLoadThroughGEPConstantExpr");
1311 }
1312
1313 assert((uint64_t)CI->getRawValue() < ATy->getNumElements());
1314 Elts[(uint64_t)CI->getRawValue()] =
1315 EvaluateStoreInto(Elts[(uint64_t)CI->getRawValue()], Val, Addr, OpNo+1);
1316 return ConstantArray::get(ATy, Elts);
1317 }
1318}
1319
Chris Lattner99e23fa2005-09-26 04:44:35 +00001320/// CommitValueTo - We have decided that Addr (which satisfies the predicate
1321/// isSimpleEnoughPointerToCommit) should get Val as its value. Make it happen.
1322static void CommitValueTo(Constant *Val, Constant *Addr) {
Chris Lattner46af55e2005-09-26 06:52:44 +00001323 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Addr)) {
1324 assert(GV->hasInitializer());
1325 GV->setInitializer(Val);
1326 return;
1327 }
1328
1329 ConstantExpr *CE = cast<ConstantExpr>(Addr);
1330 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
1331
1332 Constant *Init = GV->getInitializer();
1333 Init = EvaluateStoreInto(Init, Val, CE, 2);
1334 GV->setInitializer(Init);
Chris Lattner99e23fa2005-09-26 04:44:35 +00001335}
1336
Chris Lattnerb0096632005-09-26 05:16:34 +00001337/// ComputeLoadResult - Return the value that would be computed by a load from
1338/// P after the stores reflected by 'memory' have been performed. If we can't
1339/// decide, return null.
Chris Lattner4b05c322005-09-26 05:15:37 +00001340static Constant *ComputeLoadResult(Constant *P,
1341 const std::map<Constant*, Constant*> &Memory) {
1342 // If this memory location has been recently stored, use the stored value: it
1343 // is the most up-to-date.
1344 std::map<Constant*, Constant*>::const_iterator I = Memory.find(P);
1345 if (I != Memory.end()) return I->second;
1346
1347 // Access it.
1348 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(P)) {
1349 if (GV->hasInitializer())
1350 return GV->getInitializer();
1351 return 0;
Chris Lattner4b05c322005-09-26 05:15:37 +00001352 }
Chris Lattner46af55e2005-09-26 06:52:44 +00001353
1354 // Handle a constantexpr getelementptr.
1355 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(P))
1356 if (CE->getOpcode() == Instruction::GetElementPtr &&
1357 isa<GlobalVariable>(CE->getOperand(0))) {
1358 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
1359 if (GV->hasInitializer())
1360 return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
1361 }
1362
1363 return 0; // don't know how to evaluate.
Chris Lattner4b05c322005-09-26 05:15:37 +00001364}
1365
Chris Lattner99e23fa2005-09-26 04:44:35 +00001366/// EvaluateStaticConstructor - Evaluate static constructors in the function, if
1367/// we can. Return true if we can, false otherwise.
1368static bool EvaluateStaticConstructor(Function *F) {
1369 /// Values - As we compute SSA register values, we store their contents here.
1370 std::map<Value*, Constant*> Values;
1371
1372 /// MutatedMemory - For each store we execute, we update this map. Loads
1373 /// check this to get the most up-to-date value. If evaluation is successful,
1374 /// this state is committed to the process.
1375 std::map<Constant*, Constant*> MutatedMemory;
1376
Chris Lattner3e9ea5f2005-09-26 04:57:38 +00001377 /// ExecutedBlocks - We only handle non-looping, non-recursive code. As such,
1378 /// we can only evaluate any one basic block at most once. This set keeps
1379 /// track of what we have executed so we can detect recursive cases etc.
1380 std::set<BasicBlock*> ExecutedBlocks;
1381
Chris Lattner99e23fa2005-09-26 04:44:35 +00001382 // CurInst - The current instruction we're evaluating.
1383 BasicBlock::iterator CurInst = F->begin()->begin();
Chris Lattner3e9ea5f2005-09-26 04:57:38 +00001384 ExecutedBlocks.insert(F->begin());
Chris Lattner99e23fa2005-09-26 04:44:35 +00001385
1386 // This is the main evaluation loop.
1387 while (1) {
1388 Constant *InstResult = 0;
1389
1390 if (StoreInst *SI = dyn_cast<StoreInst>(CurInst)) {
Chris Lattner4b05c322005-09-26 05:15:37 +00001391 if (SI->isVolatile()) return false; // no volatile accesses.
Chris Lattner99e23fa2005-09-26 04:44:35 +00001392 Constant *Ptr = getVal(Values, SI->getOperand(1));
1393 if (!isSimpleEnoughPointerToCommit(Ptr))
1394 // If this is too complex for us to commit, reject it.
1395 return false;
1396 Constant *Val = getVal(Values, SI->getOperand(0));
1397 MutatedMemory[Ptr] = Val;
1398 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CurInst)) {
1399 InstResult = ConstantExpr::get(BO->getOpcode(),
1400 getVal(Values, BO->getOperand(0)),
1401 getVal(Values, BO->getOperand(1)));
1402 } else if (ShiftInst *SI = dyn_cast<ShiftInst>(CurInst)) {
1403 InstResult = ConstantExpr::get(SI->getOpcode(),
1404 getVal(Values, SI->getOperand(0)),
1405 getVal(Values, SI->getOperand(1)));
1406 } else if (CastInst *CI = dyn_cast<CastInst>(CurInst)) {
1407 InstResult = ConstantExpr::getCast(getVal(Values, CI->getOperand(0)),
1408 CI->getType());
1409 } else if (SelectInst *SI = dyn_cast<SelectInst>(CurInst)) {
1410 InstResult = ConstantExpr::getSelect(getVal(Values, SI->getOperand(0)),
1411 getVal(Values, SI->getOperand(1)),
1412 getVal(Values, SI->getOperand(2)));
Chris Lattner4b05c322005-09-26 05:15:37 +00001413 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurInst)) {
1414 Constant *P = getVal(Values, GEP->getOperand(0));
1415 std::vector<Constant*> GEPOps;
1416 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
1417 GEPOps.push_back(getVal(Values, GEP->getOperand(i)));
1418 InstResult = ConstantExpr::getGetElementPtr(P, GEPOps);
1419 } else if (LoadInst *LI = dyn_cast<LoadInst>(CurInst)) {
1420 if (LI->isVolatile()) return false; // no volatile accesses.
1421 InstResult = ComputeLoadResult(getVal(Values, LI->getOperand(0)),
1422 MutatedMemory);
1423 if (InstResult == 0) return false; // Could not evaluate load.
Chris Lattner3e9ea5f2005-09-26 04:57:38 +00001424 } else if (TerminatorInst *TI = dyn_cast<TerminatorInst>(CurInst)) {
1425 BasicBlock *NewBB = 0;
1426 if (BranchInst *BI = dyn_cast<BranchInst>(CurInst)) {
1427 if (BI->isUnconditional()) {
1428 NewBB = BI->getSuccessor(0);
1429 } else {
1430 ConstantBool *Cond =
1431 dyn_cast<ConstantBool>(getVal(Values, BI->getCondition()));
1432 if (!Cond) return false; // Cannot determine.
1433 NewBB = BI->getSuccessor(!Cond->getValue());
1434 }
1435 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(CurInst)) {
1436 ConstantInt *Val =
1437 dyn_cast<ConstantInt>(getVal(Values, SI->getCondition()));
1438 if (!Val) return false; // Cannot determine.
1439 NewBB = SI->getSuccessor(SI->findCaseValue(Val));
1440 } else if (ReturnInst *RI = dyn_cast<ReturnInst>(CurInst)) {
1441 assert(RI->getNumOperands() == 0);
1442 break; // We succeeded at evaluating this ctor!
1443 } else {
1444 // unwind, unreachable.
1445 return false; // Cannot handle this terminator.
1446 }
1447
1448 // Okay, we succeeded in evaluating this control flow. See if we have
1449 // executed the new block before. If so, we have a looping or recursive
1450 // function, which we cannot evaluate in reasonable time.
1451 if (!ExecutedBlocks.insert(NewBB).second)
1452 return false; // Recursed!
1453
1454 // Okay, we have never been in this block before. Check to see if there
1455 // are any PHI nodes. If so, evaluate them with information about where
1456 // we came from.
1457 BasicBlock *OldBB = CurInst->getParent();
1458 CurInst = NewBB->begin();
1459 PHINode *PN;
1460 for (; (PN = dyn_cast<PHINode>(CurInst)); ++CurInst)
1461 Values[PN] = getVal(Values, PN->getIncomingValueForBlock(OldBB));
1462
1463 // Do NOT increment CurInst. We know that the terminator had no value.
1464 continue;
Chris Lattner99e23fa2005-09-26 04:44:35 +00001465 } else {
1466 // TODO: use ConstantFoldCall for function calls.
1467
1468 // Did not know how to evaluate this!
1469 return false;
1470 }
1471
1472 if (!CurInst->use_empty())
1473 Values[CurInst] = InstResult;
1474
1475 // Advance program counter.
1476 ++CurInst;
1477 }
1478
1479 // If we get here, we know that we succeeded at evaluation: commit the result.
1480 //
1481 for (std::map<Constant*, Constant*>::iterator I = MutatedMemory.begin(),
1482 E = MutatedMemory.end(); I != E; ++I)
1483 CommitValueTo(I->second, I->first);
1484 return true;
1485}
1486
Chris Lattner696beef2005-09-26 02:31:18 +00001487
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001488/// OptimizeGlobalCtorsList - Simplify and evaluation global ctors if possible.
1489/// Return true if anything changed.
1490bool GlobalOpt::OptimizeGlobalCtorsList(GlobalVariable *&GCL) {
1491 std::vector<Function*> Ctors = ParseGlobalCtors(GCL);
1492 bool MadeChange = false;
1493 if (Ctors.empty()) return false;
1494
1495 // Loop over global ctors, optimizing them when we can.
1496 for (unsigned i = 0; i != Ctors.size(); ++i) {
1497 Function *F = Ctors[i];
1498 // Found a null terminator in the middle of the list, prune off the rest of
1499 // the list.
Chris Lattner838bdc12005-09-26 02:19:27 +00001500 if (F == 0) {
1501 if (i != Ctors.size()-1) {
1502 Ctors.resize(i+1);
1503 MadeChange = true;
1504 }
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001505 break;
1506 }
1507
Chris Lattner99e23fa2005-09-26 04:44:35 +00001508 // We cannot simplify external ctor functions.
1509 if (F->empty()) continue;
1510
1511 // If we can evaluate the ctor at compile time, do.
1512 if (EvaluateStaticConstructor(F)) {
1513 Ctors.erase(Ctors.begin()+i);
1514 MadeChange = true;
1515 --i;
1516 ++NumCtorsEvaluated;
1517 continue;
1518 }
1519
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001520 // If the function is empty, just remove it from the ctor list.
Chris Lattner99e23fa2005-09-26 04:44:35 +00001521 if (isa<ReturnInst>(F->begin()->getTerminator()) &&
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001522 &F->begin()->front() == F->begin()->getTerminator()) {
1523 Ctors.erase(Ctors.begin()+i);
1524 MadeChange = true;
1525 --i;
1526 ++NumEmptyCtor;
Chris Lattner99e23fa2005-09-26 04:44:35 +00001527 continue;
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001528 }
1529 }
1530
1531 if (!MadeChange) return false;
1532
Chris Lattner696beef2005-09-26 02:31:18 +00001533 GCL = InstallGlobalCtors(GCL, Ctors);
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001534 return true;
1535}
1536
1537
Chris Lattner25db5802004-10-07 04:16:33 +00001538bool GlobalOpt::runOnModule(Module &M) {
1539 bool Changed = false;
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001540
1541 // Try to find the llvm.globalctors list.
1542 GlobalVariable *GlobalCtors = FindGlobalCtors(M);
Chris Lattner25db5802004-10-07 04:16:33 +00001543
Chris Lattner25db5802004-10-07 04:16:33 +00001544 bool LocalChange = true;
1545 while (LocalChange) {
1546 LocalChange = false;
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001547
1548 // Delete functions that are trivially dead, ccc -> fastcc
1549 LocalChange |= OptimizeFunctions(M);
1550
1551 // Optimize global_ctors list.
1552 if (GlobalCtors)
1553 LocalChange |= OptimizeGlobalCtorsList(GlobalCtors);
1554
1555 // Optimize non-address-taken globals.
1556 LocalChange |= OptimizeGlobalVars(M);
Chris Lattner25db5802004-10-07 04:16:33 +00001557 Changed |= LocalChange;
1558 }
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001559
1560 // TODO: Move all global ctors functions to the end of the module for code
1561 // layout.
1562
Chris Lattner25db5802004-10-07 04:16:33 +00001563 return Changed;
1564}