blob: 7c212e7b7a3bd109d487bf12b0d9ac0264c54c55 [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 <algorithm>
Chris Lattnerc597b8a2006-01-22 23:32:06 +000031#include <iostream>
32#include <set>
Chris Lattner25db5802004-10-07 04:16:33 +000033using namespace llvm;
34
35namespace {
Chris Lattnerabab0712004-10-08 17:32:09 +000036 Statistic<> NumMarked ("globalopt", "Number of globals marked constant");
37 Statistic<> NumSRA ("globalopt", "Number of aggregate globals broken "
38 "into scalars");
Chris Lattner8e71c6a2004-10-16 18:09:00 +000039 Statistic<> NumSubstitute("globalopt",
40 "Number of globals with initializers stored into them");
Chris Lattnerabab0712004-10-08 17:32:09 +000041 Statistic<> NumDeleted ("globalopt", "Number of globals deleted");
Chris Lattner25db5802004-10-07 04:16:33 +000042 Statistic<> NumFnDeleted("globalopt", "Number of functions deleted");
Chris Lattnere42eb312004-10-10 23:14:11 +000043 Statistic<> NumGlobUses ("globalopt", "Number of global uses devirtualized");
Alkis Evlogimenosc4a44c62005-02-10 18:36:30 +000044 Statistic<> NumLocalized("globalopt", "Number of globals localized");
Chris Lattner40e4cec2004-12-12 05:53:50 +000045 Statistic<> NumShrunkToBool("globalopt",
46 "Number of global vars shrunk to booleans");
Chris Lattnera4c80222005-05-08 22:18:06 +000047 Statistic<> NumFastCallFns("globalopt",
48 "Number of functions converted to fastcc");
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 Lattner46d9ff082005-09-26 07:34:35 +0000323 Constant *SubInit = 0;
324 if (Init)
325 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
Chris Lattner7561ca12005-02-27 18:58:52 +0000326 Changed |= CleanupConstantGlobalUsers(CE, SubInit);
327 } else if (CE->getOpcode() == Instruction::Cast &&
328 isa<PointerType>(CE->getType())) {
329 // Pointer cast, delete any stores and memsets to the global.
330 Changed |= CleanupConstantGlobalUsers(CE, 0);
331 }
332
333 if (CE->use_empty()) {
334 CE->destroyConstant();
335 Changed = true;
Chris Lattner25db5802004-10-07 04:16:33 +0000336 }
337 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
Chris Lattner61ff32c2005-09-26 05:34:07 +0000338 Constant *SubInit = 0;
Chris Lattner46af55e2005-09-26 06:52:44 +0000339 ConstantExpr *CE =
340 dyn_cast_or_null<ConstantExpr>(ConstantFoldInstruction(GEP));
Chris Lattnereb953f02005-09-27 22:28:11 +0000341 if (Init && CE && CE->getOpcode() == Instruction::GetElementPtr)
Chris Lattner61ff32c2005-09-26 05:34:07 +0000342 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
Chris Lattner7561ca12005-02-27 18:58:52 +0000343 Changed |= CleanupConstantGlobalUsers(GEP, SubInit);
Chris Lattnera0e769c2004-10-10 16:47:33 +0000344
Chris Lattnercb9f1522004-10-10 16:43:46 +0000345 if (GEP->use_empty()) {
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000346 GEP->eraseFromParent();
Chris Lattnercb9f1522004-10-10 16:43:46 +0000347 Changed = true;
348 }
Chris Lattner7561ca12005-02-27 18:58:52 +0000349 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U)) { // memset/cpy/mv
350 if (MI->getRawDest() == V) {
351 MI->eraseFromParent();
352 Changed = true;
353 }
354
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000355 } else if (Constant *C = dyn_cast<Constant>(U)) {
356 // If we have a chain of dead constantexprs or other things dangling from
357 // us, and if they are all dead, nuke them without remorse.
358 if (ConstantIsDead(C)) {
359 C->destroyConstant();
Chris Lattner7561ca12005-02-27 18:58:52 +0000360 // This could have invalidated UI, start over from scratch.
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000361 CleanupConstantGlobalUsers(V, Init);
Chris Lattnercb9f1522004-10-10 16:43:46 +0000362 return true;
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000363 }
Chris Lattner25db5802004-10-07 04:16:33 +0000364 }
365 }
Chris Lattnercb9f1522004-10-10 16:43:46 +0000366 return Changed;
Chris Lattner25db5802004-10-07 04:16:33 +0000367}
368
Chris Lattnerabab0712004-10-08 17:32:09 +0000369/// SRAGlobal - Perform scalar replacement of aggregates on the specified global
370/// variable. This opens the door for other optimizations by exposing the
371/// behavior of the program in a more fine-grained way. We have determined that
372/// this transformation is safe already. We return the first global variable we
373/// insert so that the caller can reprocess it.
374static GlobalVariable *SRAGlobal(GlobalVariable *GV) {
375 assert(GV->hasInternalLinkage() && !GV->isConstant());
376 Constant *Init = GV->getInitializer();
377 const Type *Ty = Init->getType();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000378
Chris Lattnerabab0712004-10-08 17:32:09 +0000379 std::vector<GlobalVariable*> NewGlobals;
380 Module::GlobalListType &Globals = GV->getParent()->getGlobalList();
381
382 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
383 NewGlobals.reserve(STy->getNumElements());
384 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
385 Constant *In = getAggregateConstantElement(Init,
386 ConstantUInt::get(Type::UIntTy, i));
387 assert(In && "Couldn't get element of initializer?");
388 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(i), false,
389 GlobalVariable::InternalLinkage,
390 In, GV->getName()+"."+utostr(i));
391 Globals.insert(GV, NGV);
392 NewGlobals.push_back(NGV);
393 }
394 } else if (const SequentialType *STy = dyn_cast<SequentialType>(Ty)) {
395 unsigned NumElements = 0;
396 if (const ArrayType *ATy = dyn_cast<ArrayType>(STy))
397 NumElements = ATy->getNumElements();
398 else if (const PackedType *PTy = dyn_cast<PackedType>(STy))
399 NumElements = PTy->getNumElements();
400 else
401 assert(0 && "Unknown aggregate sequential type!");
402
Chris Lattner25169ca2005-02-23 16:53:04 +0000403 if (NumElements > 16 && GV->hasNUsesOrMore(16))
Chris Lattnerd6a44922005-02-01 01:23:31 +0000404 return 0; // It's not worth it.
Chris Lattnerabab0712004-10-08 17:32:09 +0000405 NewGlobals.reserve(NumElements);
406 for (unsigned i = 0, e = NumElements; i != e; ++i) {
407 Constant *In = getAggregateConstantElement(Init,
408 ConstantUInt::get(Type::UIntTy, i));
409 assert(In && "Couldn't get element of initializer?");
410
411 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(), false,
412 GlobalVariable::InternalLinkage,
413 In, GV->getName()+"."+utostr(i));
414 Globals.insert(GV, NGV);
415 NewGlobals.push_back(NGV);
416 }
417 }
418
419 if (NewGlobals.empty())
420 return 0;
421
Chris Lattner004e2502004-10-11 05:54:41 +0000422 DEBUG(std::cerr << "PERFORMING GLOBAL SRA ON: " << *GV);
423
Chris Lattnerabab0712004-10-08 17:32:09 +0000424 Constant *NullInt = Constant::getNullValue(Type::IntTy);
425
426 // Loop over all of the uses of the global, replacing the constantexpr geps,
427 // with smaller constantexpr geps or direct references.
428 while (!GV->use_empty()) {
Chris Lattner004e2502004-10-11 05:54:41 +0000429 User *GEP = GV->use_back();
430 assert(((isa<ConstantExpr>(GEP) &&
431 cast<ConstantExpr>(GEP)->getOpcode()==Instruction::GetElementPtr)||
432 isa<GetElementPtrInst>(GEP)) && "NonGEP CE's are not SRAable!");
Misha Brukmanb1c93172005-04-21 23:48:37 +0000433
Chris Lattnerabab0712004-10-08 17:32:09 +0000434 // Ignore the 1th operand, which has to be zero or else the program is quite
435 // broken (undefined). Get the 2nd operand, which is the structure or array
436 // index.
Chris Lattner46fa04b2005-01-08 19:45:31 +0000437 unsigned Val =
438 (unsigned)cast<ConstantInt>(GEP->getOperand(2))->getRawValue();
Chris Lattnerabab0712004-10-08 17:32:09 +0000439 if (Val >= NewGlobals.size()) Val = 0; // Out of bound array access.
440
Chris Lattner004e2502004-10-11 05:54:41 +0000441 Value *NewPtr = NewGlobals[Val];
Chris Lattnerabab0712004-10-08 17:32:09 +0000442
443 // Form a shorter GEP if needed.
Chris Lattner004e2502004-10-11 05:54:41 +0000444 if (GEP->getNumOperands() > 3)
445 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEP)) {
446 std::vector<Constant*> Idxs;
447 Idxs.push_back(NullInt);
448 for (unsigned i = 3, e = CE->getNumOperands(); i != e; ++i)
449 Idxs.push_back(CE->getOperand(i));
450 NewPtr = ConstantExpr::getGetElementPtr(cast<Constant>(NewPtr), Idxs);
451 } else {
452 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(GEP);
453 std::vector<Value*> Idxs;
454 Idxs.push_back(NullInt);
455 for (unsigned i = 3, e = GEPI->getNumOperands(); i != e; ++i)
456 Idxs.push_back(GEPI->getOperand(i));
457 NewPtr = new GetElementPtrInst(NewPtr, Idxs,
458 GEPI->getName()+"."+utostr(Val), GEPI);
459 }
460 GEP->replaceAllUsesWith(NewPtr);
461
462 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(GEP))
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000463 GEPI->eraseFromParent();
Chris Lattner004e2502004-10-11 05:54:41 +0000464 else
465 cast<ConstantExpr>(GEP)->destroyConstant();
Chris Lattnerabab0712004-10-08 17:32:09 +0000466 }
467
Chris Lattner73ad73e2004-10-08 20:25:55 +0000468 // Delete the old global, now that it is dead.
469 Globals.erase(GV);
Chris Lattnerabab0712004-10-08 17:32:09 +0000470 ++NumSRA;
Chris Lattner004e2502004-10-11 05:54:41 +0000471
472 // Loop over the new globals array deleting any globals that are obviously
473 // dead. This can arise due to scalarization of a structure or an array that
474 // has elements that are dead.
475 unsigned FirstGlobal = 0;
476 for (unsigned i = 0, e = NewGlobals.size(); i != e; ++i)
477 if (NewGlobals[i]->use_empty()) {
478 Globals.erase(NewGlobals[i]);
479 if (FirstGlobal == i) ++FirstGlobal;
480 }
481
482 return FirstGlobal != NewGlobals.size() ? NewGlobals[FirstGlobal] : 0;
Chris Lattnerabab0712004-10-08 17:32:09 +0000483}
484
Chris Lattner09a52722004-10-09 21:48:45 +0000485/// AllUsesOfValueWillTrapIfNull - Return true if all users of the specified
486/// value will trap if the value is dynamically null.
487static bool AllUsesOfValueWillTrapIfNull(Value *V) {
488 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
489 if (isa<LoadInst>(*UI)) {
490 // Will trap.
491 } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
492 if (SI->getOperand(0) == V) {
493 //std::cerr << "NONTRAPPING USE: " << **UI;
494 return false; // Storing the value.
495 }
496 } else if (CallInst *CI = dyn_cast<CallInst>(*UI)) {
497 if (CI->getOperand(0) != V) {
498 //std::cerr << "NONTRAPPING USE: " << **UI;
499 return false; // Not calling the ptr
500 }
501 } else if (InvokeInst *II = dyn_cast<InvokeInst>(*UI)) {
502 if (II->getOperand(0) != V) {
503 //std::cerr << "NONTRAPPING USE: " << **UI;
504 return false; // Not calling the ptr
505 }
506 } else if (CastInst *CI = dyn_cast<CastInst>(*UI)) {
507 if (!AllUsesOfValueWillTrapIfNull(CI)) return false;
508 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(*UI)) {
509 if (!AllUsesOfValueWillTrapIfNull(GEPI)) return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000510 } else if (isa<SetCondInst>(*UI) &&
Chris Lattnerfe9abf92004-10-22 06:43:28 +0000511 isa<ConstantPointerNull>(UI->getOperand(1))) {
512 // Ignore setcc X, null
Chris Lattner09a52722004-10-09 21:48:45 +0000513 } else {
514 //std::cerr << "NONTRAPPING USE: " << **UI;
515 return false;
516 }
517 return true;
518}
519
520/// AllUsesOfLoadedValueWillTrapIfNull - Return true if all uses of any loads
Chris Lattnerfe9abf92004-10-22 06:43:28 +0000521/// from GV will trap if the loaded value is null. Note that this also permits
522/// comparisons of the loaded value against null, as a special case.
Chris Lattner09a52722004-10-09 21:48:45 +0000523static bool AllUsesOfLoadedValueWillTrapIfNull(GlobalVariable *GV) {
524 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI!=E; ++UI)
525 if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
526 if (!AllUsesOfValueWillTrapIfNull(LI))
527 return false;
528 } else if (isa<StoreInst>(*UI)) {
529 // Ignore stores to the global.
530 } else {
531 // We don't know or understand this user, bail out.
532 //std::cerr << "UNKNOWN USER OF GLOBAL!: " << **UI;
533 return false;
534 }
535
536 return true;
537}
538
Chris Lattnere42eb312004-10-10 23:14:11 +0000539static bool OptimizeAwayTrappingUsesOfValue(Value *V, Constant *NewV) {
540 bool Changed = false;
541 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ) {
542 Instruction *I = cast<Instruction>(*UI++);
543 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
544 LI->setOperand(0, NewV);
545 Changed = true;
546 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
547 if (SI->getOperand(1) == V) {
548 SI->setOperand(1, NewV);
549 Changed = true;
550 }
551 } else if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
552 if (I->getOperand(0) == V) {
553 // Calling through the pointer! Turn into a direct call, but be careful
554 // that the pointer is not also being passed as an argument.
555 I->setOperand(0, NewV);
556 Changed = true;
557 bool PassedAsArg = false;
558 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i)
559 if (I->getOperand(i) == V) {
560 PassedAsArg = true;
561 I->setOperand(i, NewV);
562 }
563
564 if (PassedAsArg) {
565 // Being passed as an argument also. Be careful to not invalidate UI!
566 UI = V->use_begin();
567 }
568 }
569 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
570 Changed |= OptimizeAwayTrappingUsesOfValue(CI,
571 ConstantExpr::getCast(NewV, CI->getType()));
572 if (CI->use_empty()) {
573 Changed = true;
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000574 CI->eraseFromParent();
Chris Lattnere42eb312004-10-10 23:14:11 +0000575 }
576 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
577 // Should handle GEP here.
578 std::vector<Constant*> Indices;
579 Indices.reserve(GEPI->getNumOperands()-1);
580 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
581 if (Constant *C = dyn_cast<Constant>(GEPI->getOperand(i)))
582 Indices.push_back(C);
583 else
584 break;
585 if (Indices.size() == GEPI->getNumOperands()-1)
586 Changed |= OptimizeAwayTrappingUsesOfValue(GEPI,
587 ConstantExpr::getGetElementPtr(NewV, Indices));
588 if (GEPI->use_empty()) {
589 Changed = true;
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000590 GEPI->eraseFromParent();
Chris Lattnere42eb312004-10-10 23:14:11 +0000591 }
592 }
593 }
594
595 return Changed;
596}
597
598
599/// OptimizeAwayTrappingUsesOfLoads - The specified global has only one non-null
600/// value stored into it. If there are uses of the loaded value that would trap
601/// if the loaded value is dynamically null, then we know that they cannot be
602/// reachable with a null optimize away the load.
603static bool OptimizeAwayTrappingUsesOfLoads(GlobalVariable *GV, Constant *LV) {
604 std::vector<LoadInst*> Loads;
605 bool Changed = false;
606
607 // Replace all uses of loads with uses of uses of the stored value.
608 for (Value::use_iterator GUI = GV->use_begin(), E = GV->use_end();
609 GUI != E; ++GUI)
610 if (LoadInst *LI = dyn_cast<LoadInst>(*GUI)) {
611 Loads.push_back(LI);
612 Changed |= OptimizeAwayTrappingUsesOfValue(LI, LV);
613 } else {
614 assert(isa<StoreInst>(*GUI) && "Only expect load and stores!");
615 }
616
617 if (Changed) {
618 DEBUG(std::cerr << "OPTIMIZED LOADS FROM STORED ONCE POINTER: " << *GV);
619 ++NumGlobUses;
620 }
621
622 // Delete all of the loads we can, keeping track of whether we nuked them all!
623 bool AllLoadsGone = true;
624 while (!Loads.empty()) {
625 LoadInst *L = Loads.back();
626 if (L->use_empty()) {
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000627 L->eraseFromParent();
Chris Lattnere42eb312004-10-10 23:14:11 +0000628 Changed = true;
629 } else {
630 AllLoadsGone = false;
631 }
632 Loads.pop_back();
633 }
634
635 // If we nuked all of the loads, then none of the stores are needed either,
636 // nor is the global.
637 if (AllLoadsGone) {
638 DEBUG(std::cerr << " *** GLOBAL NOW DEAD!\n");
639 CleanupConstantGlobalUsers(GV, 0);
640 if (GV->use_empty()) {
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000641 GV->eraseFromParent();
Chris Lattnere42eb312004-10-10 23:14:11 +0000642 ++NumDeleted;
643 }
644 Changed = true;
645 }
646 return Changed;
647}
648
Chris Lattner004e2502004-10-11 05:54:41 +0000649/// ConstantPropUsersOf - Walk the use list of V, constant folding all of the
650/// instructions that are foldable.
651static void ConstantPropUsersOf(Value *V) {
652 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; )
653 if (Instruction *I = dyn_cast<Instruction>(*UI++))
654 if (Constant *NewC = ConstantFoldInstruction(I)) {
655 I->replaceAllUsesWith(NewC);
656
Chris Lattnerd6a44922005-02-01 01:23:31 +0000657 // Advance UI to the next non-I use to avoid invalidating it!
658 // Instructions could multiply use V.
659 while (UI != E && *UI == I)
Chris Lattner004e2502004-10-11 05:54:41 +0000660 ++UI;
Chris Lattnerd6a44922005-02-01 01:23:31 +0000661 I->eraseFromParent();
Chris Lattner004e2502004-10-11 05:54:41 +0000662 }
663}
664
665/// OptimizeGlobalAddressOfMalloc - This function takes the specified global
666/// variable, and transforms the program as if it always contained the result of
667/// the specified malloc. Because it is always the result of the specified
668/// malloc, there is no reason to actually DO the malloc. Instead, turn the
669/// malloc into a global, and any laods of GV as uses of the new global.
670static GlobalVariable *OptimizeGlobalAddressOfMalloc(GlobalVariable *GV,
671 MallocInst *MI) {
672 DEBUG(std::cerr << "PROMOTING MALLOC GLOBAL: " << *GV << " MALLOC = " <<*MI);
673 ConstantInt *NElements = cast<ConstantInt>(MI->getArraySize());
674
675 if (NElements->getRawValue() != 1) {
676 // If we have an array allocation, transform it to a single element
677 // allocation to make the code below simpler.
678 Type *NewTy = ArrayType::get(MI->getAllocatedType(),
Chris Lattner46fa04b2005-01-08 19:45:31 +0000679 (unsigned)NElements->getRawValue());
Chris Lattner004e2502004-10-11 05:54:41 +0000680 MallocInst *NewMI =
681 new MallocInst(NewTy, Constant::getNullValue(Type::UIntTy),
Nate Begeman848622f2005-11-05 09:21:28 +0000682 MI->getAlignment(), MI->getName(), MI);
Chris Lattner004e2502004-10-11 05:54:41 +0000683 std::vector<Value*> Indices;
684 Indices.push_back(Constant::getNullValue(Type::IntTy));
685 Indices.push_back(Indices[0]);
686 Value *NewGEP = new GetElementPtrInst(NewMI, Indices,
687 NewMI->getName()+".el0", MI);
688 MI->replaceAllUsesWith(NewGEP);
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000689 MI->eraseFromParent();
Chris Lattner004e2502004-10-11 05:54:41 +0000690 MI = NewMI;
691 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000692
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000693 // Create the new global variable. The contents of the malloc'd memory is
694 // undefined, so initialize with an undef value.
695 Constant *Init = UndefValue::get(MI->getAllocatedType());
Chris Lattner004e2502004-10-11 05:54:41 +0000696 GlobalVariable *NewGV = new GlobalVariable(MI->getAllocatedType(), false,
697 GlobalValue::InternalLinkage, Init,
698 GV->getName()+".body");
699 GV->getParent()->getGlobalList().insert(GV, NewGV);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000700
Chris Lattner004e2502004-10-11 05:54:41 +0000701 // Anything that used the malloc now uses the global directly.
702 MI->replaceAllUsesWith(NewGV);
Chris Lattner004e2502004-10-11 05:54:41 +0000703
704 Constant *RepValue = NewGV;
705 if (NewGV->getType() != GV->getType()->getElementType())
706 RepValue = ConstantExpr::getCast(RepValue, GV->getType()->getElementType());
707
Chris Lattnerfe9abf92004-10-22 06:43:28 +0000708 // If there is a comparison against null, we will insert a global bool to
709 // keep track of whether the global was initialized yet or not.
Misha Brukmanb1c93172005-04-21 23:48:37 +0000710 GlobalVariable *InitBool =
711 new GlobalVariable(Type::BoolTy, false, GlobalValue::InternalLinkage,
Chris Lattner3b181392004-12-02 06:25:58 +0000712 ConstantBool::False, GV->getName()+".init");
713 bool InitBoolUsed = false;
Chris Lattnerfe9abf92004-10-22 06:43:28 +0000714
Chris Lattner004e2502004-10-11 05:54:41 +0000715 // Loop over all uses of GV, processing them in turn.
Chris Lattner3b181392004-12-02 06:25:58 +0000716 std::vector<StoreInst*> Stores;
Chris Lattner004e2502004-10-11 05:54:41 +0000717 while (!GV->use_empty())
718 if (LoadInst *LI = dyn_cast<LoadInst>(GV->use_back())) {
Chris Lattnerfe9abf92004-10-22 06:43:28 +0000719 while (!LI->use_empty()) {
Chris Lattnerd6a44922005-02-01 01:23:31 +0000720 Use &LoadUse = LI->use_begin().getUse();
Chris Lattnerfe9abf92004-10-22 06:43:28 +0000721 if (!isa<SetCondInst>(LoadUse.getUser()))
722 LoadUse = RepValue;
723 else {
Chris Lattnerfe9abf92004-10-22 06:43:28 +0000724 // Replace the setcc X, 0 with a use of the bool value.
725 SetCondInst *SCI = cast<SetCondInst>(LoadUse.getUser());
726 Value *LV = new LoadInst(InitBool, InitBool->getName()+".val", SCI);
Chris Lattner3b181392004-12-02 06:25:58 +0000727 InitBoolUsed = true;
Chris Lattnerfe9abf92004-10-22 06:43:28 +0000728 switch (SCI->getOpcode()) {
729 default: assert(0 && "Unknown opcode!");
730 case Instruction::SetLT:
731 LV = ConstantBool::False; // X < null -> always false
732 break;
733 case Instruction::SetEQ:
734 case Instruction::SetLE:
735 LV = BinaryOperator::createNot(LV, "notinit", SCI);
736 break;
737 case Instruction::SetNE:
738 case Instruction::SetGE:
739 case Instruction::SetGT:
740 break; // no change.
741 }
742 SCI->replaceAllUsesWith(LV);
743 SCI->eraseFromParent();
744 }
745 }
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000746 LI->eraseFromParent();
Chris Lattner004e2502004-10-11 05:54:41 +0000747 } else {
748 StoreInst *SI = cast<StoreInst>(GV->use_back());
Chris Lattner3b181392004-12-02 06:25:58 +0000749 // The global is initialized when the store to it occurs.
750 new StoreInst(ConstantBool::True, InitBool, SI);
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000751 SI->eraseFromParent();
Chris Lattner004e2502004-10-11 05:54:41 +0000752 }
753
Chris Lattner3b181392004-12-02 06:25:58 +0000754 // If the initialization boolean was used, insert it, otherwise delete it.
755 if (!InitBoolUsed) {
756 while (!InitBool->use_empty()) // Delete initializations
757 cast<Instruction>(InitBool->use_back())->eraseFromParent();
758 delete InitBool;
759 } else
760 GV->getParent()->getGlobalList().insert(GV, InitBool);
761
762
Chris Lattnerfe9abf92004-10-22 06:43:28 +0000763 // Now the GV is dead, nuke it and the malloc.
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000764 GV->eraseFromParent();
Chris Lattnerfe9abf92004-10-22 06:43:28 +0000765 MI->eraseFromParent();
Chris Lattner004e2502004-10-11 05:54:41 +0000766
767 // To further other optimizations, loop over all users of NewGV and try to
768 // constant prop them. This will promote GEP instructions with constant
769 // indices into GEP constant-exprs, which will allow global-opt to hack on it.
770 ConstantPropUsersOf(NewGV);
771 if (RepValue != NewGV)
772 ConstantPropUsersOf(RepValue);
773
774 return NewGV;
775}
Chris Lattnere42eb312004-10-10 23:14:11 +0000776
Chris Lattnerc0677c02004-12-02 07:11:07 +0000777/// ValueIsOnlyUsedLocallyOrStoredToOneGlobal - Scan the use-list of V checking
778/// to make sure that there are no complex uses of V. We permit simple things
779/// like dereferencing the pointer, but not storing through the address, unless
780/// it is to the specified global.
781static bool ValueIsOnlyUsedLocallyOrStoredToOneGlobal(Instruction *V,
782 GlobalVariable *GV) {
783 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;++UI)
784 if (isa<LoadInst>(*UI) || isa<SetCondInst>(*UI)) {
785 // Fine, ignore.
786 } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
787 if (SI->getOperand(0) == V && SI->getOperand(1) != GV)
788 return false; // Storing the pointer itself... bad.
789 // Otherwise, storing through it, or storing into GV... fine.
790 } else if (isa<GetElementPtrInst>(*UI) || isa<SelectInst>(*UI)) {
791 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(cast<Instruction>(*UI),GV))
792 return false;
793 } else {
794 return false;
795 }
796 return true;
797
798}
799
Chris Lattner09a52722004-10-09 21:48:45 +0000800// OptimizeOnceStoredGlobal - Try to optimize globals based on the knowledge
801// that only one value (besides its initializer) is ever stored to the global.
Chris Lattner004e2502004-10-11 05:54:41 +0000802static bool OptimizeOnceStoredGlobal(GlobalVariable *GV, Value *StoredOnceVal,
Chris Lattner531f9e92005-03-15 04:54:21 +0000803 Module::global_iterator &GVI, TargetData &TD) {
Chris Lattner09a52722004-10-09 21:48:45 +0000804 if (CastInst *CI = dyn_cast<CastInst>(StoredOnceVal))
805 StoredOnceVal = CI->getOperand(0);
806 else if (GetElementPtrInst *GEPI =dyn_cast<GetElementPtrInst>(StoredOnceVal)){
Chris Lattnere42eb312004-10-10 23:14:11 +0000807 // "getelementptr Ptr, 0, 0, 0" is really just a cast.
Chris Lattner09a52722004-10-09 21:48:45 +0000808 bool IsJustACast = true;
809 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
810 if (!isa<Constant>(GEPI->getOperand(i)) ||
811 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
812 IsJustACast = false;
813 break;
814 }
815 if (IsJustACast)
816 StoredOnceVal = GEPI->getOperand(0);
817 }
818
Chris Lattnere42eb312004-10-10 23:14:11 +0000819 // If we are dealing with a pointer global that is initialized to null and
820 // only has one (non-null) value stored into it, then we can optimize any
821 // users of the loaded value (often calls and loads) that would trap if the
822 // value was null.
Chris Lattner09a52722004-10-09 21:48:45 +0000823 if (isa<PointerType>(GV->getInitializer()->getType()) &&
824 GV->getInitializer()->isNullValue()) {
Chris Lattnere42eb312004-10-10 23:14:11 +0000825 if (Constant *SOVC = dyn_cast<Constant>(StoredOnceVal)) {
826 if (GV->getInitializer()->getType() != SOVC->getType())
827 SOVC = ConstantExpr::getCast(SOVC, GV->getInitializer()->getType());
Misha Brukmanb1c93172005-04-21 23:48:37 +0000828
Chris Lattnere42eb312004-10-10 23:14:11 +0000829 // Optimize away any trapping uses of the loaded value.
830 if (OptimizeAwayTrappingUsesOfLoads(GV, SOVC))
Chris Lattner604ed7a2004-10-10 17:07:12 +0000831 return true;
Chris Lattner004e2502004-10-11 05:54:41 +0000832 } else if (MallocInst *MI = dyn_cast<MallocInst>(StoredOnceVal)) {
833 // If we have a global that is only initialized with a fixed size malloc,
834 // and if all users of the malloc trap, and if the malloc'd address is not
835 // put anywhere else, transform the program to use global memory instead
836 // of malloc'd memory. This eliminates dynamic allocation (good) and
837 // exposes the resultant global to further GlobalOpt (even better). Note
838 // that we restrict this transformation to only working on small
839 // allocations (2048 bytes currently), as we don't want to introduce a 16M
840 // global or something.
841 if (ConstantInt *NElements = dyn_cast<ConstantInt>(MI->getArraySize()))
842 if (MI->getAllocatedType()->isSized() &&
843 NElements->getRawValue()*
844 TD.getTypeSize(MI->getAllocatedType()) < 2048 &&
Chris Lattnerc0677c02004-12-02 07:11:07 +0000845 AllUsesOfLoadedValueWillTrapIfNull(GV) &&
846 ValueIsOnlyUsedLocallyOrStoredToOneGlobal(MI, GV)) {
Chris Lattner004e2502004-10-11 05:54:41 +0000847 GVI = OptimizeGlobalAddressOfMalloc(GV, MI);
848 return true;
849 }
Chris Lattnere42eb312004-10-10 23:14:11 +0000850 }
Chris Lattner09a52722004-10-09 21:48:45 +0000851 }
Chris Lattner004e2502004-10-11 05:54:41 +0000852
Chris Lattner09a52722004-10-09 21:48:45 +0000853 return false;
854}
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000855
Chris Lattner40e4cec2004-12-12 05:53:50 +0000856/// ShrinkGlobalToBoolean - At this point, we have learned that the only two
Misha Brukmanb1c93172005-04-21 23:48:37 +0000857/// values ever stored into GV are its initializer and OtherVal.
Chris Lattner40e4cec2004-12-12 05:53:50 +0000858static void ShrinkGlobalToBoolean(GlobalVariable *GV, Constant *OtherVal) {
859 // Create the new global, initializing it to false.
860 GlobalVariable *NewGV = new GlobalVariable(Type::BoolTy, false,
861 GlobalValue::InternalLinkage, ConstantBool::False, GV->getName()+".b");
862 GV->getParent()->getGlobalList().insert(GV, NewGV);
863
864 Constant *InitVal = GV->getInitializer();
865 assert(InitVal->getType() != Type::BoolTy && "No reason to shrink to bool!");
866
867 // If initialized to zero and storing one into the global, we can use a cast
868 // instead of a select to synthesize the desired value.
869 bool IsOneZero = false;
870 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal))
871 IsOneZero = InitVal->isNullValue() && CI->equalsInt(1);
872
873 while (!GV->use_empty()) {
874 Instruction *UI = cast<Instruction>(GV->use_back());
875 if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
876 // Change the store into a boolean store.
877 bool StoringOther = SI->getOperand(0) == OtherVal;
878 // Only do this if we weren't storing a loaded value.
Chris Lattner745196a2004-12-12 19:34:41 +0000879 Value *StoreVal;
Chris Lattner40e4cec2004-12-12 05:53:50 +0000880 if (StoringOther || SI->getOperand(0) == InitVal)
Chris Lattner745196a2004-12-12 19:34:41 +0000881 StoreVal = ConstantBool::get(StoringOther);
882 else {
883 // Otherwise, we are storing a previously loaded copy. To do this,
884 // change the copy from copying the original value to just copying the
885 // bool.
886 Instruction *StoredVal = cast<Instruction>(SI->getOperand(0));
887
888 // If we're already replaced the input, StoredVal will be a cast or
889 // select instruction. If not, it will be a load of the original
890 // global.
891 if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
892 assert(LI->getOperand(0) == GV && "Not a copy!");
893 // Insert a new load, to preserve the saved value.
894 StoreVal = new LoadInst(NewGV, LI->getName()+".b", LI);
895 } else {
896 assert((isa<CastInst>(StoredVal) || isa<SelectInst>(StoredVal)) &&
897 "This is not a form that we understand!");
898 StoreVal = StoredVal->getOperand(0);
899 assert(isa<LoadInst>(StoreVal) && "Not a load of NewGV!");
900 }
901 }
902 new StoreInst(StoreVal, NewGV, SI);
903 } else if (!UI->use_empty()) {
Chris Lattner40e4cec2004-12-12 05:53:50 +0000904 // Change the load into a load of bool then a select.
905 LoadInst *LI = cast<LoadInst>(UI);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000906
Chris Lattner40e4cec2004-12-12 05:53:50 +0000907 std::string Name = LI->getName(); LI->setName("");
908 LoadInst *NLI = new LoadInst(NewGV, Name+".b", LI);
909 Value *NSI;
910 if (IsOneZero)
911 NSI = new CastInst(NLI, LI->getType(), Name, LI);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000912 else
Chris Lattner40e4cec2004-12-12 05:53:50 +0000913 NSI = new SelectInst(NLI, OtherVal, InitVal, Name, LI);
914 LI->replaceAllUsesWith(NSI);
915 }
916 UI->eraseFromParent();
917 }
918
919 GV->eraseFromParent();
920}
921
922
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000923/// ProcessInternalGlobal - Analyze the specified global variable and optimize
924/// it if possible. If we make a change, return true.
Chris Lattner004e2502004-10-11 05:54:41 +0000925bool GlobalOpt::ProcessInternalGlobal(GlobalVariable *GV,
Chris Lattner531f9e92005-03-15 04:54:21 +0000926 Module::global_iterator &GVI) {
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000927 std::set<PHINode*> PHIUsers;
928 GlobalStatus GS;
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000929 GV->removeDeadConstantUsers();
930
931 if (GV->use_empty()) {
932 DEBUG(std::cerr << "GLOBAL DEAD: " << *GV);
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000933 GV->eraseFromParent();
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000934 ++NumDeleted;
935 return true;
936 }
937
938 if (!AnalyzeGlobal(GV, GS, PHIUsers)) {
Alkis Evlogimenosc4a44c62005-02-10 18:36:30 +0000939 // If this is a first class global and has only one accessing function
940 // and this function is main (which we know is not recursive we can make
941 // this global a local variable) we replace the global with a local alloca
942 // in this function.
943 //
944 // NOTE: It doesn't make sense to promote non first class types since we
945 // are just replacing static memory to stack memory.
946 if (!GS.HasMultipleAccessingFunctions &&
Chris Lattner50bdfcb2005-06-15 21:11:48 +0000947 GS.AccessingFunction && !GS.HasNonInstructionUser &&
Alkis Evlogimenosc4a44c62005-02-10 18:36:30 +0000948 GV->getType()->getElementType()->isFirstClassType() &&
949 GS.AccessingFunction->getName() == "main" &&
950 GS.AccessingFunction->hasExternalLinkage()) {
951 DEBUG(std::cerr << "LOCALIZING GLOBAL: " << *GV);
952 Instruction* FirstI = GS.AccessingFunction->getEntryBlock().begin();
953 const Type* ElemTy = GV->getType()->getElementType();
Nate Begeman848622f2005-11-05 09:21:28 +0000954 // FIXME: Pass Global's alignment when globals have alignment
Alkis Evlogimenosc4a44c62005-02-10 18:36:30 +0000955 AllocaInst* Alloca = new AllocaInst(ElemTy, NULL, GV->getName(), FirstI);
956 if (!isa<UndefValue>(GV->getInitializer()))
957 new StoreInst(GV->getInitializer(), Alloca, FirstI);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000958
Alkis Evlogimenosc4a44c62005-02-10 18:36:30 +0000959 GV->replaceAllUsesWith(Alloca);
960 GV->eraseFromParent();
961 ++NumLocalized;
962 return true;
963 }
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000964 // If the global is never loaded (but may be stored to), it is dead.
965 // Delete it now.
966 if (!GS.isLoaded) {
967 DEBUG(std::cerr << "GLOBAL NEVER LOADED: " << *GV);
Chris Lattnerf369b382004-10-09 03:32:52 +0000968
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000969 // Delete any stores we can find to the global. We may not be able to
970 // make it completely dead though.
Chris Lattnercb9f1522004-10-10 16:43:46 +0000971 bool Changed = CleanupConstantGlobalUsers(GV, GV->getInitializer());
Chris Lattnerf369b382004-10-09 03:32:52 +0000972
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000973 // If the global is dead now, delete it.
974 if (GV->use_empty()) {
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000975 GV->eraseFromParent();
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000976 ++NumDeleted;
Chris Lattnerf369b382004-10-09 03:32:52 +0000977 Changed = true;
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000978 }
Chris Lattnerf369b382004-10-09 03:32:52 +0000979 return Changed;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000980
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000981 } else if (GS.StoredType <= GlobalStatus::isInitializerStored) {
982 DEBUG(std::cerr << "MARKING CONSTANT: " << *GV);
983 GV->setConstant(true);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000984
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000985 // Clean up any obviously simplifiable users now.
986 CleanupConstantGlobalUsers(GV, GV->getInitializer());
Misha Brukmanb1c93172005-04-21 23:48:37 +0000987
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000988 // If the global is dead now, just nuke it.
989 if (GV->use_empty()) {
990 DEBUG(std::cerr << " *** Marking constant allowed us to simplify "
991 "all users and delete global!\n");
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000992 GV->eraseFromParent();
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000993 ++NumDeleted;
994 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000995
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000996 ++NumMarked;
997 return true;
998 } else if (!GS.isNotSuitableForSRA &&
999 !GV->getInitializer()->getType()->isFirstClassType()) {
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001000 if (GlobalVariable *FirstNewGV = SRAGlobal(GV)) {
1001 GVI = FirstNewGV; // Don't skip the newly produced globals!
1002 return true;
1003 }
Chris Lattner09a52722004-10-09 21:48:45 +00001004 } else if (GS.StoredType == GlobalStatus::isStoredOnce) {
Chris Lattner40e4cec2004-12-12 05:53:50 +00001005 // If the initial value for the global was an undef value, and if only
1006 // one other value was stored into it, we can just change the
1007 // initializer to be an undef value, then delete all stores to the
1008 // global. This allows us to mark it constant.
1009 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
1010 if (isa<UndefValue>(GV->getInitializer())) {
1011 // Change the initial value here.
1012 GV->setInitializer(SOVConstant);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001013
Chris Lattner40e4cec2004-12-12 05:53:50 +00001014 // Clean up any obviously simplifiable users now.
1015 CleanupConstantGlobalUsers(GV, GV->getInitializer());
Misha Brukmanb1c93172005-04-21 23:48:37 +00001016
Chris Lattner40e4cec2004-12-12 05:53:50 +00001017 if (GV->use_empty()) {
1018 DEBUG(std::cerr << " *** Substituting initializer allowed us to "
1019 "simplify all users and delete global!\n");
1020 GV->eraseFromParent();
1021 ++NumDeleted;
1022 } else {
1023 GVI = GV;
1024 }
1025 ++NumSubstitute;
1026 return true;
Chris Lattner8e71c6a2004-10-16 18:09:00 +00001027 }
Chris Lattner8e71c6a2004-10-16 18:09:00 +00001028
Chris Lattner09a52722004-10-09 21:48:45 +00001029 // Try to optimize globals based on the knowledge that only one value
1030 // (besides its initializer) is ever stored to the global.
Chris Lattner004e2502004-10-11 05:54:41 +00001031 if (OptimizeOnceStoredGlobal(GV, GS.StoredOnceValue, GVI,
1032 getAnalysis<TargetData>()))
Chris Lattner09a52722004-10-09 21:48:45 +00001033 return true;
Chris Lattner40e4cec2004-12-12 05:53:50 +00001034
1035 // Otherwise, if the global was not a boolean, we can shrink it to be a
1036 // boolean.
1037 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
Chris Lattner1cbd5be2004-12-12 06:03:06 +00001038 if (GV->getType()->getElementType() != Type::BoolTy &&
1039 !GV->getType()->getElementType()->isFloatingPoint()) {
Chris Lattner40e4cec2004-12-12 05:53:50 +00001040 DEBUG(std::cerr << " *** SHRINKING TO BOOL: " << *GV);
1041 ShrinkGlobalToBoolean(GV, SOVConstant);
1042 ++NumShrunkToBool;
1043 return true;
1044 }
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001045 }
1046 }
1047 return false;
1048}
1049
Chris Lattnera4c80222005-05-08 22:18:06 +00001050/// OnlyCalledDirectly - Return true if the specified function is only called
1051/// directly. In other words, its address is never taken.
1052static bool OnlyCalledDirectly(Function *F) {
1053 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
1054 Instruction *User = dyn_cast<Instruction>(*UI);
1055 if (!User) return false;
1056 if (!isa<CallInst>(User) && !isa<InvokeInst>(User)) return false;
1057
1058 // See if the function address is passed as an argument.
1059 for (unsigned i = 1, e = User->getNumOperands(); i != e; ++i)
1060 if (User->getOperand(i) == F) return false;
1061 }
1062 return true;
1063}
1064
1065/// ChangeCalleesToFastCall - Walk all of the direct calls of the specified
1066/// function, changing them to FastCC.
1067static void ChangeCalleesToFastCall(Function *F) {
1068 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
1069 Instruction *User = cast<Instruction>(*UI);
1070 if (CallInst *CI = dyn_cast<CallInst>(User))
1071 CI->setCallingConv(CallingConv::Fast);
1072 else
1073 cast<InvokeInst>(User)->setCallingConv(CallingConv::Fast);
1074 }
1075}
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001076
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001077bool GlobalOpt::OptimizeFunctions(Module &M) {
1078 bool Changed = false;
1079 // Optimize functions.
1080 for (Module::iterator FI = M.begin(), E = M.end(); FI != E; ) {
1081 Function *F = FI++;
1082 F->removeDeadConstantUsers();
1083 if (F->use_empty() && (F->hasInternalLinkage() ||
1084 F->hasLinkOnceLinkage())) {
1085 M.getFunctionList().erase(F);
1086 Changed = true;
1087 ++NumFnDeleted;
1088 } else if (F->hasInternalLinkage() &&
1089 F->getCallingConv() == CallingConv::C && !F->isVarArg() &&
1090 OnlyCalledDirectly(F)) {
1091 // If this function has C calling conventions, is not a varargs
1092 // function, and is only called directly, promote it to use the Fast
1093 // calling convention.
1094 F->setCallingConv(CallingConv::Fast);
1095 ChangeCalleesToFastCall(F);
1096 ++NumFastCallFns;
1097 Changed = true;
1098 }
1099 }
1100 return Changed;
1101}
1102
1103bool GlobalOpt::OptimizeGlobalVars(Module &M) {
1104 bool Changed = false;
1105 for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
1106 GVI != E; ) {
1107 GlobalVariable *GV = GVI++;
1108 if (!GV->isConstant() && GV->hasInternalLinkage() &&
1109 GV->hasInitializer())
1110 Changed |= ProcessInternalGlobal(GV, GVI);
1111 }
1112 return Changed;
1113}
1114
1115/// FindGlobalCtors - Find the llvm.globalctors list, verifying that all
1116/// initializers have an init priority of 65535.
1117GlobalVariable *GlobalOpt::FindGlobalCtors(Module &M) {
Alkis Evlogimenoscb67b652005-10-25 11:18:06 +00001118 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1119 I != E; ++I)
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001120 if (I->getName() == "llvm.global_ctors") {
1121 // Found it, verify it's an array of { int, void()* }.
1122 const ArrayType *ATy =dyn_cast<ArrayType>(I->getType()->getElementType());
1123 if (!ATy) return 0;
1124 const StructType *STy = dyn_cast<StructType>(ATy->getElementType());
1125 if (!STy || STy->getNumElements() != 2 ||
1126 STy->getElementType(0) != Type::IntTy) return 0;
1127 const PointerType *PFTy = dyn_cast<PointerType>(STy->getElementType(1));
1128 if (!PFTy) return 0;
1129 const FunctionType *FTy = dyn_cast<FunctionType>(PFTy->getElementType());
1130 if (!FTy || FTy->getReturnType() != Type::VoidTy || FTy->isVarArg() ||
1131 FTy->getNumParams() != 0)
1132 return 0;
1133
1134 // Verify that the initializer is simple enough for us to handle.
1135 if (!I->hasInitializer()) return 0;
1136 ConstantArray *CA = dyn_cast<ConstantArray>(I->getInitializer());
1137 if (!CA) return 0;
1138 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1139 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(CA->getOperand(i))) {
Chris Lattner838bdc12005-09-26 02:19:27 +00001140 if (isa<ConstantPointerNull>(CS->getOperand(1)))
1141 continue;
1142
1143 // Must have a function or null ptr.
1144 if (!isa<Function>(CS->getOperand(1)))
1145 return 0;
1146
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001147 // Init priority must be standard.
1148 ConstantInt *CI = dyn_cast<ConstantInt>(CS->getOperand(0));
1149 if (!CI || CI->getRawValue() != 65535)
1150 return 0;
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001151 } else {
1152 return 0;
1153 }
1154
1155 return I;
1156 }
1157 return 0;
1158}
1159
Chris Lattner696beef2005-09-26 02:31:18 +00001160/// ParseGlobalCtors - Given a llvm.global_ctors list that we can understand,
1161/// return a list of the functions and null terminator as a vector.
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001162static std::vector<Function*> ParseGlobalCtors(GlobalVariable *GV) {
1163 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
1164 std::vector<Function*> Result;
1165 Result.reserve(CA->getNumOperands());
1166 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i) {
1167 ConstantStruct *CS = cast<ConstantStruct>(CA->getOperand(i));
1168 Result.push_back(dyn_cast<Function>(CS->getOperand(1)));
1169 }
1170 return Result;
1171}
1172
Chris Lattner696beef2005-09-26 02:31:18 +00001173/// InstallGlobalCtors - Given a specified llvm.global_ctors list, install the
1174/// specified array, returning the new global to use.
1175static GlobalVariable *InstallGlobalCtors(GlobalVariable *GCL,
1176 const std::vector<Function*> &Ctors) {
1177 // If we made a change, reassemble the initializer list.
1178 std::vector<Constant*> CSVals;
1179 CSVals.push_back(ConstantSInt::get(Type::IntTy, 65535));
1180 CSVals.push_back(0);
1181
1182 // Create the new init list.
1183 std::vector<Constant*> CAList;
1184 for (unsigned i = 0, e = Ctors.size(); i != e; ++i) {
Chris Lattner99e23fa2005-09-26 04:44:35 +00001185 if (Ctors[i]) {
Chris Lattner696beef2005-09-26 02:31:18 +00001186 CSVals[1] = Ctors[i];
Chris Lattner99e23fa2005-09-26 04:44:35 +00001187 } else {
Chris Lattner696beef2005-09-26 02:31:18 +00001188 const Type *FTy = FunctionType::get(Type::VoidTy,
1189 std::vector<const Type*>(), false);
1190 const PointerType *PFTy = PointerType::get(FTy);
1191 CSVals[1] = Constant::getNullValue(PFTy);
1192 CSVals[0] = ConstantSInt::get(Type::IntTy, 2147483647);
1193 }
1194 CAList.push_back(ConstantStruct::get(CSVals));
1195 }
1196
1197 // Create the array initializer.
1198 const Type *StructTy =
1199 cast<ArrayType>(GCL->getType()->getElementType())->getElementType();
1200 Constant *CA = ConstantArray::get(ArrayType::get(StructTy, CAList.size()),
1201 CAList);
1202
1203 // If we didn't change the number of elements, don't create a new GV.
1204 if (CA->getType() == GCL->getInitializer()->getType()) {
1205 GCL->setInitializer(CA);
1206 return GCL;
1207 }
1208
1209 // Create the new global and insert it next to the existing list.
1210 GlobalVariable *NGV = new GlobalVariable(CA->getType(), GCL->isConstant(),
1211 GCL->getLinkage(), CA,
1212 GCL->getName());
1213 GCL->setName("");
1214 GCL->getParent()->getGlobalList().insert(GCL, NGV);
1215
1216 // Nuke the old list, replacing any uses with the new one.
1217 if (!GCL->use_empty()) {
1218 Constant *V = NGV;
1219 if (V->getType() != GCL->getType())
1220 V = ConstantExpr::getCast(V, GCL->getType());
1221 GCL->replaceAllUsesWith(V);
1222 }
1223 GCL->eraseFromParent();
1224
1225 if (Ctors.size())
1226 return NGV;
1227 else
1228 return 0;
1229}
Chris Lattner99e23fa2005-09-26 04:44:35 +00001230
1231
1232static Constant *getVal(std::map<Value*, Constant*> &ComputedValues,
1233 Value *V) {
1234 if (Constant *CV = dyn_cast<Constant>(V)) return CV;
1235 Constant *R = ComputedValues[V];
1236 assert(R && "Reference to an uncomputed value!");
1237 return R;
1238}
1239
1240/// isSimpleEnoughPointerToCommit - Return true if this constant is simple
1241/// enough for us to understand. In particular, if it is a cast of something,
1242/// we punt. We basically just support direct accesses to globals and GEP's of
1243/// globals. This should be kept up to date with CommitValueTo.
1244static bool isSimpleEnoughPointerToCommit(Constant *C) {
Chris Lattner29b27802005-09-27 04:50:03 +00001245 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
1246 if (!GV->hasExternalLinkage() && !GV->hasInternalLinkage())
1247 return false; // do not allow weak/linkonce linkage.
Chris Lattner99e23fa2005-09-26 04:44:35 +00001248 return !GV->isExternal(); // reject external globals.
Chris Lattner29b27802005-09-27 04:50:03 +00001249 }
Chris Lattner46af55e2005-09-26 06:52:44 +00001250 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
1251 // Handle a constantexpr gep.
1252 if (CE->getOpcode() == Instruction::GetElementPtr &&
1253 isa<GlobalVariable>(CE->getOperand(0))) {
1254 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
Chris Lattner29b27802005-09-27 04:50:03 +00001255 if (!GV->hasExternalLinkage() && !GV->hasInternalLinkage())
1256 return false; // do not allow weak/linkonce linkage.
Chris Lattner46af55e2005-09-26 06:52:44 +00001257 return GV->hasInitializer() &&
1258 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
1259 }
Chris Lattner99e23fa2005-09-26 04:44:35 +00001260 return false;
1261}
1262
Chris Lattner46af55e2005-09-26 06:52:44 +00001263/// EvaluateStoreInto - Evaluate a piece of a constantexpr store into a global
1264/// initializer. This returns 'Init' modified to reflect 'Val' stored into it.
1265/// At this point, the GEP operands of Addr [0, OpNo) have been stepped into.
1266static Constant *EvaluateStoreInto(Constant *Init, Constant *Val,
1267 ConstantExpr *Addr, unsigned OpNo) {
1268 // Base case of the recursion.
1269 if (OpNo == Addr->getNumOperands()) {
1270 assert(Val->getType() == Init->getType() && "Type mismatch!");
1271 return Val;
1272 }
1273
1274 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
1275 std::vector<Constant*> Elts;
1276
1277 // Break up the constant into its elements.
1278 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
1279 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i)
1280 Elts.push_back(CS->getOperand(i));
1281 } else if (isa<ConstantAggregateZero>(Init)) {
1282 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
1283 Elts.push_back(Constant::getNullValue(STy->getElementType(i)));
1284 } else if (isa<UndefValue>(Init)) {
1285 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
1286 Elts.push_back(UndefValue::get(STy->getElementType(i)));
1287 } else {
1288 assert(0 && "This code is out of sync with "
1289 " ConstantFoldLoadThroughGEPConstantExpr");
1290 }
1291
1292 // Replace the element that we are supposed to.
1293 ConstantUInt *CU = cast<ConstantUInt>(Addr->getOperand(OpNo));
1294 assert(CU->getValue() < STy->getNumElements() &&
1295 "Struct index out of range!");
1296 unsigned Idx = (unsigned)CU->getValue();
1297 Elts[Idx] = EvaluateStoreInto(Elts[Idx], Val, Addr, OpNo+1);
1298
1299 // Return the modified struct.
1300 return ConstantStruct::get(Elts);
1301 } else {
1302 ConstantInt *CI = cast<ConstantInt>(Addr->getOperand(OpNo));
1303 const ArrayType *ATy = cast<ArrayType>(Init->getType());
1304
1305 // Break up the array into elements.
1306 std::vector<Constant*> Elts;
1307 if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
1308 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1309 Elts.push_back(CA->getOperand(i));
1310 } else if (isa<ConstantAggregateZero>(Init)) {
1311 Constant *Elt = Constant::getNullValue(ATy->getElementType());
1312 Elts.assign(ATy->getNumElements(), Elt);
1313 } else if (isa<UndefValue>(Init)) {
1314 Constant *Elt = UndefValue::get(ATy->getElementType());
1315 Elts.assign(ATy->getNumElements(), Elt);
1316 } else {
1317 assert(0 && "This code is out of sync with "
1318 " ConstantFoldLoadThroughGEPConstantExpr");
1319 }
1320
1321 assert((uint64_t)CI->getRawValue() < ATy->getNumElements());
1322 Elts[(uint64_t)CI->getRawValue()] =
1323 EvaluateStoreInto(Elts[(uint64_t)CI->getRawValue()], Val, Addr, OpNo+1);
1324 return ConstantArray::get(ATy, Elts);
1325 }
1326}
1327
Chris Lattner99e23fa2005-09-26 04:44:35 +00001328/// CommitValueTo - We have decided that Addr (which satisfies the predicate
1329/// isSimpleEnoughPointerToCommit) should get Val as its value. Make it happen.
1330static void CommitValueTo(Constant *Val, Constant *Addr) {
Chris Lattner46af55e2005-09-26 06:52:44 +00001331 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Addr)) {
1332 assert(GV->hasInitializer());
1333 GV->setInitializer(Val);
1334 return;
1335 }
1336
1337 ConstantExpr *CE = cast<ConstantExpr>(Addr);
1338 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
1339
1340 Constant *Init = GV->getInitializer();
1341 Init = EvaluateStoreInto(Init, Val, CE, 2);
1342 GV->setInitializer(Init);
Chris Lattner99e23fa2005-09-26 04:44:35 +00001343}
1344
Chris Lattnerb0096632005-09-26 05:16:34 +00001345/// ComputeLoadResult - Return the value that would be computed by a load from
1346/// P after the stores reflected by 'memory' have been performed. If we can't
1347/// decide, return null.
Chris Lattner4b05c322005-09-26 05:15:37 +00001348static Constant *ComputeLoadResult(Constant *P,
1349 const std::map<Constant*, Constant*> &Memory) {
1350 // If this memory location has been recently stored, use the stored value: it
1351 // is the most up-to-date.
1352 std::map<Constant*, Constant*>::const_iterator I = Memory.find(P);
1353 if (I != Memory.end()) return I->second;
1354
1355 // Access it.
1356 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(P)) {
1357 if (GV->hasInitializer())
1358 return GV->getInitializer();
1359 return 0;
Chris Lattner4b05c322005-09-26 05:15:37 +00001360 }
Chris Lattner46af55e2005-09-26 06:52:44 +00001361
1362 // Handle a constantexpr getelementptr.
1363 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(P))
1364 if (CE->getOpcode() == Instruction::GetElementPtr &&
1365 isa<GlobalVariable>(CE->getOperand(0))) {
1366 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
1367 if (GV->hasInitializer())
1368 return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
1369 }
1370
1371 return 0; // don't know how to evaluate.
Chris Lattner4b05c322005-09-26 05:15:37 +00001372}
1373
Chris Lattnerda1889b2005-09-27 04:27:01 +00001374/// EvaluateFunction - Evaluate a call to function F, returning true if
1375/// successful, false if we can't evaluate it. ActualArgs contains the formal
1376/// arguments for the function.
Chris Lattner65a3a092005-09-27 04:45:34 +00001377static bool EvaluateFunction(Function *F, Constant *&RetVal,
Chris Lattnerda1889b2005-09-27 04:27:01 +00001378 const std::vector<Constant*> &ActualArgs,
1379 std::vector<Function*> &CallStack,
1380 std::map<Constant*, Constant*> &MutatedMemory,
1381 std::vector<GlobalVariable*> &AllocaTmps) {
Chris Lattner65a3a092005-09-27 04:45:34 +00001382 // Check to see if this function is already executing (recursion). If so,
1383 // bail out. TODO: we might want to accept limited recursion.
1384 if (std::find(CallStack.begin(), CallStack.end(), F) != CallStack.end())
1385 return false;
1386
1387 CallStack.push_back(F);
1388
Chris Lattner99e23fa2005-09-26 04:44:35 +00001389 /// Values - As we compute SSA register values, we store their contents here.
1390 std::map<Value*, Constant*> Values;
Chris Lattner65a3a092005-09-27 04:45:34 +00001391
1392 // Initialize arguments to the incoming values specified.
1393 unsigned ArgNo = 0;
1394 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); AI != E;
1395 ++AI, ++ArgNo)
1396 Values[AI] = ActualArgs[ArgNo];
Chris Lattnerda1889b2005-09-27 04:27:01 +00001397
Chris Lattner3e9ea5f2005-09-26 04:57:38 +00001398 /// ExecutedBlocks - We only handle non-looping, non-recursive code. As such,
1399 /// we can only evaluate any one basic block at most once. This set keeps
1400 /// track of what we have executed so we can detect recursive cases etc.
1401 std::set<BasicBlock*> ExecutedBlocks;
Chris Lattner6bf2cd52005-09-26 17:07:09 +00001402
Chris Lattner99e23fa2005-09-26 04:44:35 +00001403 // CurInst - The current instruction we're evaluating.
1404 BasicBlock::iterator CurInst = F->begin()->begin();
1405
1406 // This is the main evaluation loop.
1407 while (1) {
1408 Constant *InstResult = 0;
1409
1410 if (StoreInst *SI = dyn_cast<StoreInst>(CurInst)) {
Chris Lattner65a3a092005-09-27 04:45:34 +00001411 if (SI->isVolatile()) return false; // no volatile accesses.
Chris Lattner99e23fa2005-09-26 04:44:35 +00001412 Constant *Ptr = getVal(Values, SI->getOperand(1));
1413 if (!isSimpleEnoughPointerToCommit(Ptr))
1414 // If this is too complex for us to commit, reject it.
Chris Lattner65a3a092005-09-27 04:45:34 +00001415 return false;
Chris Lattner99e23fa2005-09-26 04:44:35 +00001416 Constant *Val = getVal(Values, SI->getOperand(0));
1417 MutatedMemory[Ptr] = Val;
1418 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CurInst)) {
1419 InstResult = ConstantExpr::get(BO->getOpcode(),
1420 getVal(Values, BO->getOperand(0)),
1421 getVal(Values, BO->getOperand(1)));
1422 } else if (ShiftInst *SI = dyn_cast<ShiftInst>(CurInst)) {
1423 InstResult = ConstantExpr::get(SI->getOpcode(),
1424 getVal(Values, SI->getOperand(0)),
1425 getVal(Values, SI->getOperand(1)));
1426 } else if (CastInst *CI = dyn_cast<CastInst>(CurInst)) {
1427 InstResult = ConstantExpr::getCast(getVal(Values, CI->getOperand(0)),
1428 CI->getType());
1429 } else if (SelectInst *SI = dyn_cast<SelectInst>(CurInst)) {
1430 InstResult = ConstantExpr::getSelect(getVal(Values, SI->getOperand(0)),
1431 getVal(Values, SI->getOperand(1)),
1432 getVal(Values, SI->getOperand(2)));
Chris Lattner4b05c322005-09-26 05:15:37 +00001433 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurInst)) {
1434 Constant *P = getVal(Values, GEP->getOperand(0));
1435 std::vector<Constant*> GEPOps;
1436 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
1437 GEPOps.push_back(getVal(Values, GEP->getOperand(i)));
1438 InstResult = ConstantExpr::getGetElementPtr(P, GEPOps);
1439 } else if (LoadInst *LI = dyn_cast<LoadInst>(CurInst)) {
Chris Lattner65a3a092005-09-27 04:45:34 +00001440 if (LI->isVolatile()) return false; // no volatile accesses.
Chris Lattner4b05c322005-09-26 05:15:37 +00001441 InstResult = ComputeLoadResult(getVal(Values, LI->getOperand(0)),
1442 MutatedMemory);
Chris Lattner65a3a092005-09-27 04:45:34 +00001443 if (InstResult == 0) return false; // Could not evaluate load.
Chris Lattner6bf2cd52005-09-26 17:07:09 +00001444 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(CurInst)) {
Chris Lattner65a3a092005-09-27 04:45:34 +00001445 if (AI->isArrayAllocation()) return false; // Cannot handle array allocs.
Chris Lattner6bf2cd52005-09-26 17:07:09 +00001446 const Type *Ty = AI->getType()->getElementType();
1447 AllocaTmps.push_back(new GlobalVariable(Ty, false,
1448 GlobalValue::InternalLinkage,
1449 UndefValue::get(Ty),
1450 AI->getName()));
Chris Lattner65a3a092005-09-27 04:45:34 +00001451 InstResult = AllocaTmps.back();
1452 } else if (CallInst *CI = dyn_cast<CallInst>(CurInst)) {
1453 // Resolve function pointers.
1454 Function *Callee = dyn_cast<Function>(getVal(Values, CI->getOperand(0)));
1455 if (!Callee) return false; // Cannot resolve.
Chris Lattner3d27e7f2005-09-27 05:02:43 +00001456
Chris Lattner65a3a092005-09-27 04:45:34 +00001457 std::vector<Constant*> Formals;
1458 for (unsigned i = 1, e = CI->getNumOperands(); i != e; ++i)
1459 Formals.push_back(getVal(Values, CI->getOperand(i)));
Chris Lattner65a3a092005-09-27 04:45:34 +00001460
Chris Lattner3d27e7f2005-09-27 05:02:43 +00001461 if (Callee->isExternal()) {
1462 // If this is a function we can constant fold, do it.
1463 if (Constant *C = ConstantFoldCall(Callee, Formals)) {
1464 InstResult = C;
1465 } else {
1466 return false;
1467 }
1468 } else {
1469 if (Callee->getFunctionType()->isVarArg())
1470 return false;
1471
1472 Constant *RetVal;
1473
1474 // Execute the call, if successful, use the return value.
1475 if (!EvaluateFunction(Callee, RetVal, Formals, CallStack,
1476 MutatedMemory, AllocaTmps))
1477 return false;
1478 InstResult = RetVal;
1479 }
Chris Lattner3e9ea5f2005-09-26 04:57:38 +00001480 } else if (TerminatorInst *TI = dyn_cast<TerminatorInst>(CurInst)) {
1481 BasicBlock *NewBB = 0;
1482 if (BranchInst *BI = dyn_cast<BranchInst>(CurInst)) {
1483 if (BI->isUnconditional()) {
1484 NewBB = BI->getSuccessor(0);
1485 } else {
1486 ConstantBool *Cond =
1487 dyn_cast<ConstantBool>(getVal(Values, BI->getCondition()));
Chris Lattner65a3a092005-09-27 04:45:34 +00001488 if (!Cond) return false; // Cannot determine.
Chris Lattner3e9ea5f2005-09-26 04:57:38 +00001489 NewBB = BI->getSuccessor(!Cond->getValue());
1490 }
1491 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(CurInst)) {
1492 ConstantInt *Val =
1493 dyn_cast<ConstantInt>(getVal(Values, SI->getCondition()));
Chris Lattner65a3a092005-09-27 04:45:34 +00001494 if (!Val) return false; // Cannot determine.
Chris Lattner3e9ea5f2005-09-26 04:57:38 +00001495 NewBB = SI->getSuccessor(SI->findCaseValue(Val));
1496 } else if (ReturnInst *RI = dyn_cast<ReturnInst>(CurInst)) {
Chris Lattner65a3a092005-09-27 04:45:34 +00001497 if (RI->getNumOperands())
1498 RetVal = getVal(Values, RI->getOperand(0));
1499
1500 CallStack.pop_back(); // return from fn.
Chris Lattnerda1889b2005-09-27 04:27:01 +00001501 return true; // We succeeded at evaluating this ctor!
Chris Lattner3e9ea5f2005-09-26 04:57:38 +00001502 } else {
Chris Lattner65a3a092005-09-27 04:45:34 +00001503 // invoke, unwind, unreachable.
1504 return false; // Cannot handle this terminator.
Chris Lattner3e9ea5f2005-09-26 04:57:38 +00001505 }
1506
1507 // Okay, we succeeded in evaluating this control flow. See if we have
Chris Lattner65a3a092005-09-27 04:45:34 +00001508 // executed the new block before. If so, we have a looping function,
1509 // which we cannot evaluate in reasonable time.
Chris Lattner3e9ea5f2005-09-26 04:57:38 +00001510 if (!ExecutedBlocks.insert(NewBB).second)
Chris Lattner65a3a092005-09-27 04:45:34 +00001511 return false; // looped!
Chris Lattner3e9ea5f2005-09-26 04:57:38 +00001512
1513 // Okay, we have never been in this block before. Check to see if there
1514 // are any PHI nodes. If so, evaluate them with information about where
1515 // we came from.
1516 BasicBlock *OldBB = CurInst->getParent();
1517 CurInst = NewBB->begin();
1518 PHINode *PN;
1519 for (; (PN = dyn_cast<PHINode>(CurInst)); ++CurInst)
1520 Values[PN] = getVal(Values, PN->getIncomingValueForBlock(OldBB));
1521
1522 // Do NOT increment CurInst. We know that the terminator had no value.
1523 continue;
Chris Lattner99e23fa2005-09-26 04:44:35 +00001524 } else {
Chris Lattner99e23fa2005-09-26 04:44:35 +00001525 // Did not know how to evaluate this!
Chris Lattner65a3a092005-09-27 04:45:34 +00001526 return false;
Chris Lattner99e23fa2005-09-26 04:44:35 +00001527 }
1528
1529 if (!CurInst->use_empty())
1530 Values[CurInst] = InstResult;
1531
1532 // Advance program counter.
1533 ++CurInst;
1534 }
Chris Lattnerda1889b2005-09-27 04:27:01 +00001535}
1536
1537/// EvaluateStaticConstructor - Evaluate static constructors in the function, if
1538/// we can. Return true if we can, false otherwise.
1539static bool EvaluateStaticConstructor(Function *F) {
1540 /// MutatedMemory - For each store we execute, we update this map. Loads
1541 /// check this to get the most up-to-date value. If evaluation is successful,
1542 /// this state is committed to the process.
1543 std::map<Constant*, Constant*> MutatedMemory;
1544
1545 /// AllocaTmps - To 'execute' an alloca, we create a temporary global variable
1546 /// to represent its body. This vector is needed so we can delete the
1547 /// temporary globals when we are done.
1548 std::vector<GlobalVariable*> AllocaTmps;
1549
1550 /// CallStack - This is used to detect recursion. In pathological situations
1551 /// we could hit exponential behavior, but at least there is nothing
1552 /// unbounded.
1553 std::vector<Function*> CallStack;
1554
1555 // Call the function.
Chris Lattner65a3a092005-09-27 04:45:34 +00001556 Constant *RetValDummy;
1557 bool EvalSuccess = EvaluateFunction(F, RetValDummy, std::vector<Constant*>(),
1558 CallStack, MutatedMemory, AllocaTmps);
Chris Lattnerda1889b2005-09-27 04:27:01 +00001559 if (EvalSuccess) {
Chris Lattner6bf2cd52005-09-26 17:07:09 +00001560 // We succeeded at evaluation: commit the result.
1561 DEBUG(std::cerr << "FULLY EVALUATED GLOBAL CTOR FUNCTION '" <<
Chris Lattnerda1889b2005-09-27 04:27:01 +00001562 F->getName() << "' to " << MutatedMemory.size() << " stores.\n");
Chris Lattner6bf2cd52005-09-26 17:07:09 +00001563 for (std::map<Constant*, Constant*>::iterator I = MutatedMemory.begin(),
1564 E = MutatedMemory.end(); I != E; ++I)
1565 CommitValueTo(I->second, I->first);
1566 }
Chris Lattner99e23fa2005-09-26 04:44:35 +00001567
Chris Lattner6bf2cd52005-09-26 17:07:09 +00001568 // At this point, we are done interpreting. If we created any 'alloca'
1569 // temporaries, release them now.
1570 while (!AllocaTmps.empty()) {
1571 GlobalVariable *Tmp = AllocaTmps.back();
1572 AllocaTmps.pop_back();
Chris Lattnerda1889b2005-09-27 04:27:01 +00001573
Chris Lattner6bf2cd52005-09-26 17:07:09 +00001574 // If there are still users of the alloca, the program is doing something
1575 // silly, e.g. storing the address of the alloca somewhere and using it
1576 // later. Since this is undefined, we'll just make it be null.
1577 if (!Tmp->use_empty())
1578 Tmp->replaceAllUsesWith(Constant::getNullValue(Tmp->getType()));
1579 delete Tmp;
1580 }
Chris Lattner46d9ff082005-09-26 07:34:35 +00001581
Chris Lattnerda1889b2005-09-27 04:27:01 +00001582 return EvalSuccess;
Chris Lattner99e23fa2005-09-26 04:44:35 +00001583}
1584
Chris Lattner696beef2005-09-26 02:31:18 +00001585
Chris Lattnerda1889b2005-09-27 04:27:01 +00001586
1587
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001588/// OptimizeGlobalCtorsList - Simplify and evaluation global ctors if possible.
1589/// Return true if anything changed.
1590bool GlobalOpt::OptimizeGlobalCtorsList(GlobalVariable *&GCL) {
1591 std::vector<Function*> Ctors = ParseGlobalCtors(GCL);
1592 bool MadeChange = false;
1593 if (Ctors.empty()) return false;
1594
1595 // Loop over global ctors, optimizing them when we can.
1596 for (unsigned i = 0; i != Ctors.size(); ++i) {
1597 Function *F = Ctors[i];
1598 // Found a null terminator in the middle of the list, prune off the rest of
1599 // the list.
Chris Lattner838bdc12005-09-26 02:19:27 +00001600 if (F == 0) {
1601 if (i != Ctors.size()-1) {
1602 Ctors.resize(i+1);
1603 MadeChange = true;
1604 }
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001605 break;
1606 }
1607
Chris Lattner99e23fa2005-09-26 04:44:35 +00001608 // We cannot simplify external ctor functions.
1609 if (F->empty()) continue;
1610
1611 // If we can evaluate the ctor at compile time, do.
1612 if (EvaluateStaticConstructor(F)) {
1613 Ctors.erase(Ctors.begin()+i);
1614 MadeChange = true;
1615 --i;
1616 ++NumCtorsEvaluated;
1617 continue;
1618 }
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001619 }
1620
1621 if (!MadeChange) return false;
1622
Chris Lattner696beef2005-09-26 02:31:18 +00001623 GCL = InstallGlobalCtors(GCL, Ctors);
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001624 return true;
1625}
1626
1627
Chris Lattner25db5802004-10-07 04:16:33 +00001628bool GlobalOpt::runOnModule(Module &M) {
1629 bool Changed = false;
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001630
1631 // Try to find the llvm.globalctors list.
1632 GlobalVariable *GlobalCtors = FindGlobalCtors(M);
Chris Lattner25db5802004-10-07 04:16:33 +00001633
Chris Lattner25db5802004-10-07 04:16:33 +00001634 bool LocalChange = true;
1635 while (LocalChange) {
1636 LocalChange = false;
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001637
1638 // Delete functions that are trivially dead, ccc -> fastcc
1639 LocalChange |= OptimizeFunctions(M);
1640
1641 // Optimize global_ctors list.
1642 if (GlobalCtors)
1643 LocalChange |= OptimizeGlobalCtorsList(GlobalCtors);
1644
1645 // Optimize non-address-taken globals.
1646 LocalChange |= OptimizeGlobalVars(M);
Chris Lattner25db5802004-10-07 04:16:33 +00001647 Changed |= LocalChange;
1648 }
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001649
1650 // TODO: Move all global ctors functions to the end of the module for code
1651 // layout.
1652
Chris Lattner25db5802004-10-07 04:16:33 +00001653 return Changed;
1654}