blob: 9ac36548708abcb4fde55a737bf880afe0a9e5fa [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"
Chris Lattner024f4ab2007-01-30 23:46:24 +000025#include "llvm/Analysis/ConstantFolding.h"
Chris Lattner004e2502004-10-11 05:54:41 +000026#include "llvm/Target/TargetData.h"
Reid Spencer557ab152007-02-05 23:32:05 +000027#include "llvm/Support/Compiler.h"
Chris Lattner024f4ab2007-01-30 23:46:24 +000028#include "llvm/Support/Debug.h"
Chris Lattnerf96f4a82007-01-31 04:40:53 +000029#include "llvm/ADT/SmallVector.h"
Chris Lattner25db5802004-10-07 04:16:33 +000030#include "llvm/ADT/Statistic.h"
Chris Lattnerabab0712004-10-08 17:32:09 +000031#include "llvm/ADT/StringExtras.h"
Chris Lattner25db5802004-10-07 04:16:33 +000032#include <algorithm>
Chris Lattnerc597b8a2006-01-22 23:32:06 +000033#include <set>
Chris Lattner25db5802004-10-07 04:16:33 +000034using namespace llvm;
35
Chris Lattner1631bcb2006-12-19 22:09:18 +000036STATISTIC(NumMarked , "Number of globals marked constant");
37STATISTIC(NumSRA , "Number of aggregate globals broken into scalars");
38STATISTIC(NumHeapSRA , "Number of heap objects SRA'd");
39STATISTIC(NumSubstitute,"Number of globals with initializers stored into them");
40STATISTIC(NumDeleted , "Number of globals deleted");
41STATISTIC(NumFnDeleted , "Number of functions deleted");
42STATISTIC(NumGlobUses , "Number of global uses devirtualized");
43STATISTIC(NumLocalized , "Number of globals localized");
44STATISTIC(NumShrunkToBool , "Number of global vars shrunk to booleans");
45STATISTIC(NumFastCallFns , "Number of functions converted to fastcc");
46STATISTIC(NumCtorsEvaluated, "Number of static ctors evaluated");
Chris Lattner25db5802004-10-07 04:16:33 +000047
Chris Lattner1631bcb2006-12-19 22:09:18 +000048namespace {
Reid Spencer557ab152007-02-05 23:32:05 +000049 struct VISIBILITY_HIDDEN GlobalOpt : public ModulePass {
Chris Lattner004e2502004-10-11 05:54:41 +000050 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
51 AU.addRequired<TargetData>();
52 }
Misha Brukmanb1c93172005-04-21 23:48:37 +000053
Chris Lattner25db5802004-10-07 04:16:33 +000054 bool runOnModule(Module &M);
Chris Lattner004e2502004-10-11 05:54:41 +000055
56 private:
Chris Lattner41b6a5a2005-09-26 01:43:45 +000057 GlobalVariable *FindGlobalCtors(Module &M);
58 bool OptimizeFunctions(Module &M);
59 bool OptimizeGlobalVars(Module &M);
60 bool OptimizeGlobalCtorsList(GlobalVariable *&GCL);
Chris Lattnerc2d3d312006-08-27 22:42:52 +000061 bool ProcessInternalGlobal(GlobalVariable *GV,Module::global_iterator &GVI);
Chris Lattner25db5802004-10-07 04:16:33 +000062 };
63
Chris Lattnerc2d3d312006-08-27 22:42:52 +000064 RegisterPass<GlobalOpt> X("globalopt", "Global Variable Optimizer");
Chris Lattner25db5802004-10-07 04:16:33 +000065}
66
67ModulePass *llvm::createGlobalOptimizerPass() { return new GlobalOpt(); }
68
69/// GlobalStatus - As we analyze each global, keep track of some information
70/// about it. If we find out that the address of the global is taken, none of
Chris Lattner617f1a32004-10-07 21:30:30 +000071/// this info will be accurate.
Reid Spencer557ab152007-02-05 23:32:05 +000072struct VISIBILITY_HIDDEN GlobalStatus {
Chris Lattner617f1a32004-10-07 21:30:30 +000073 /// isLoaded - True if the global is ever loaded. If the global isn't ever
74 /// loaded it can be deleted.
Chris Lattner25db5802004-10-07 04:16:33 +000075 bool isLoaded;
Chris Lattner617f1a32004-10-07 21:30:30 +000076
77 /// StoredType - Keep track of what stores to the global look like.
78 ///
Chris Lattner25db5802004-10-07 04:16:33 +000079 enum StoredType {
Chris Lattner617f1a32004-10-07 21:30:30 +000080 /// NotStored - There is no store to this global. It can thus be marked
81 /// constant.
82 NotStored,
83
84 /// isInitializerStored - This global is stored to, but the only thing
85 /// stored is the constant it was initialized with. This is only tracked
86 /// for scalar globals.
87 isInitializerStored,
88
89 /// isStoredOnce - This global is stored to, but only its initializer and
90 /// one other value is ever stored to it. If this global isStoredOnce, we
91 /// track the value stored to it in StoredOnceValue below. This is only
92 /// tracked for scalar globals.
93 isStoredOnce,
94
95 /// isStored - This global is stored to by multiple values or something else
96 /// that we cannot track.
97 isStored
Chris Lattner25db5802004-10-07 04:16:33 +000098 } StoredType;
Chris Lattner617f1a32004-10-07 21:30:30 +000099
100 /// StoredOnceValue - If only one value (besides the initializer constant) is
101 /// ever stored to this global, keep track of what value it is.
102 Value *StoredOnceValue;
103
Chris Lattner5a0bd612006-11-01 18:03:33 +0000104 /// AccessingFunction/HasMultipleAccessingFunctions - These start out
105 /// null/false. When the first accessing function is noticed, it is recorded.
106 /// When a second different accessing function is noticed,
107 /// HasMultipleAccessingFunctions is set to true.
Alkis Evlogimenosc4a44c62005-02-10 18:36:30 +0000108 Function *AccessingFunction;
109 bool HasMultipleAccessingFunctions;
110
Chris Lattner5a0bd612006-11-01 18:03:33 +0000111 /// HasNonInstructionUser - Set to true if this global has a user that is not
112 /// an instruction (e.g. a constant expr or GV initializer).
Chris Lattner50bdfcb2005-06-15 21:11:48 +0000113 bool HasNonInstructionUser;
114
Chris Lattner5a0bd612006-11-01 18:03:33 +0000115 /// HasPHIUser - Set to true if this global has a user that is a PHI node.
116 bool HasPHIUser;
117
Chris Lattner617f1a32004-10-07 21:30:30 +0000118 /// isNotSuitableForSRA - Keep track of whether any SRA preventing users of
119 /// the global exist. Such users include GEP instruction with variable
120 /// indexes, and non-gep/load/store users like constant expr casts.
Chris Lattner25db5802004-10-07 04:16:33 +0000121 bool isNotSuitableForSRA;
122
Chris Lattner617f1a32004-10-07 21:30:30 +0000123 GlobalStatus() : isLoaded(false), StoredType(NotStored), StoredOnceValue(0),
Alkis Evlogimenosc4a44c62005-02-10 18:36:30 +0000124 AccessingFunction(0), HasMultipleAccessingFunctions(false),
Chris Lattner5a0bd612006-11-01 18:03:33 +0000125 HasNonInstructionUser(false), HasPHIUser(false),
126 isNotSuitableForSRA(false) {}
Chris Lattner25db5802004-10-07 04:16:33 +0000127};
128
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000129
130
131/// ConstantIsDead - Return true if the specified constant is (transitively)
132/// dead. The constant may be used by other constants (e.g. constant arrays and
133/// constant exprs) as long as they are dead, but it cannot be used by anything
134/// else.
135static bool ConstantIsDead(Constant *C) {
136 if (isa<GlobalValue>(C)) return false;
137
138 for (Value::use_iterator UI = C->use_begin(), E = C->use_end(); UI != E; ++UI)
139 if (Constant *CU = dyn_cast<Constant>(*UI)) {
140 if (!ConstantIsDead(CU)) return false;
141 } else
142 return false;
143 return true;
144}
145
146
Chris Lattner25db5802004-10-07 04:16:33 +0000147/// AnalyzeGlobal - Look at all uses of the global and fill in the GlobalStatus
148/// structure. If the global has its address taken, return true to indicate we
149/// can't do anything with it.
150///
151static bool AnalyzeGlobal(Value *V, GlobalStatus &GS,
152 std::set<PHINode*> &PHIUsers) {
153 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
154 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(*UI)) {
Chris Lattner50bdfcb2005-06-15 21:11:48 +0000155 GS.HasNonInstructionUser = true;
156
Chris Lattner25db5802004-10-07 04:16:33 +0000157 if (AnalyzeGlobal(CE, GS, PHIUsers)) return true;
158 if (CE->getOpcode() != Instruction::GetElementPtr)
159 GS.isNotSuitableForSRA = true;
Chris Lattnerabab0712004-10-08 17:32:09 +0000160 else if (!GS.isNotSuitableForSRA) {
161 // Check to see if this ConstantExpr GEP is SRA'able. In particular, we
162 // don't like < 3 operand CE's, and we don't like non-constant integer
163 // indices.
164 if (CE->getNumOperands() < 3 || !CE->getOperand(1)->isNullValue())
165 GS.isNotSuitableForSRA = true;
166 else {
167 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
168 if (!isa<ConstantInt>(CE->getOperand(i))) {
169 GS.isNotSuitableForSRA = true;
170 break;
171 }
172 }
173 }
174
Chris Lattner25db5802004-10-07 04:16:33 +0000175 } else if (Instruction *I = dyn_cast<Instruction>(*UI)) {
Alkis Evlogimenosc4a44c62005-02-10 18:36:30 +0000176 if (!GS.HasMultipleAccessingFunctions) {
177 Function *F = I->getParent()->getParent();
178 if (GS.AccessingFunction == 0)
179 GS.AccessingFunction = F;
180 else if (GS.AccessingFunction != F)
181 GS.HasMultipleAccessingFunctions = true;
182 }
Chris Lattner25db5802004-10-07 04:16:33 +0000183 if (isa<LoadInst>(I)) {
184 GS.isLoaded = true;
185 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Chris Lattner02b6c912004-10-07 06:01:25 +0000186 // Don't allow a store OF the address, only stores TO the address.
187 if (SI->getOperand(0) == V) return true;
188
Chris Lattner617f1a32004-10-07 21:30:30 +0000189 // If this is a direct store to the global (i.e., the global is a scalar
190 // value, not an aggregate), keep more specific information about
191 // stores.
192 if (GS.StoredType != GlobalStatus::isStored)
193 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(SI->getOperand(1))){
Chris Lattner28eeb732004-11-14 20:50:30 +0000194 Value *StoredVal = SI->getOperand(0);
195 if (StoredVal == GV->getInitializer()) {
196 if (GS.StoredType < GlobalStatus::isInitializerStored)
197 GS.StoredType = GlobalStatus::isInitializerStored;
198 } else if (isa<LoadInst>(StoredVal) &&
199 cast<LoadInst>(StoredVal)->getOperand(0) == GV) {
200 // G = G
Chris Lattner617f1a32004-10-07 21:30:30 +0000201 if (GS.StoredType < GlobalStatus::isInitializerStored)
202 GS.StoredType = GlobalStatus::isInitializerStored;
203 } else if (GS.StoredType < GlobalStatus::isStoredOnce) {
204 GS.StoredType = GlobalStatus::isStoredOnce;
Chris Lattner28eeb732004-11-14 20:50:30 +0000205 GS.StoredOnceValue = StoredVal;
Chris Lattner617f1a32004-10-07 21:30:30 +0000206 } else if (GS.StoredType == GlobalStatus::isStoredOnce &&
Chris Lattner28eeb732004-11-14 20:50:30 +0000207 GS.StoredOnceValue == StoredVal) {
Chris Lattner617f1a32004-10-07 21:30:30 +0000208 // noop.
209 } else {
210 GS.StoredType = GlobalStatus::isStored;
211 }
212 } else {
Chris Lattner25db5802004-10-07 04:16:33 +0000213 GS.StoredType = GlobalStatus::isStored;
Chris Lattner617f1a32004-10-07 21:30:30 +0000214 }
Chris Lattner7561ca12005-02-27 18:58:52 +0000215 } else if (isa<GetElementPtrInst>(I)) {
Chris Lattner25db5802004-10-07 04:16:33 +0000216 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Chris Lattner004e2502004-10-11 05:54:41 +0000217
218 // If the first two indices are constants, this can be SRA'd.
219 if (isa<GlobalVariable>(I->getOperand(0))) {
220 if (I->getNumOperands() < 3 || !isa<Constant>(I->getOperand(1)) ||
Misha Brukmanb1c93172005-04-21 23:48:37 +0000221 !cast<Constant>(I->getOperand(1))->isNullValue() ||
Chris Lattner004e2502004-10-11 05:54:41 +0000222 !isa<ConstantInt>(I->getOperand(2)))
223 GS.isNotSuitableForSRA = true;
224 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(I->getOperand(0))){
225 if (CE->getOpcode() != Instruction::GetElementPtr ||
226 CE->getNumOperands() < 3 || I->getNumOperands() < 2 ||
227 !isa<Constant>(I->getOperand(0)) ||
228 !cast<Constant>(I->getOperand(0))->isNullValue())
229 GS.isNotSuitableForSRA = true;
230 } else {
231 GS.isNotSuitableForSRA = true;
232 }
Chris Lattner7561ca12005-02-27 18:58:52 +0000233 } else if (isa<SelectInst>(I)) {
Chris Lattner25db5802004-10-07 04:16:33 +0000234 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
235 GS.isNotSuitableForSRA = true;
236 } else if (PHINode *PN = dyn_cast<PHINode>(I)) {
237 // PHI nodes we can check just like select or GEP instructions, but we
238 // have to be careful about infinite recursion.
239 if (PHIUsers.insert(PN).second) // Not already visited.
240 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
241 GS.isNotSuitableForSRA = true;
Chris Lattner5a0bd612006-11-01 18:03:33 +0000242 GS.HasPHIUser = true;
Reid Spencer266e42b2006-12-23 06:05:41 +0000243 } else if (isa<CmpInst>(I)) {
Chris Lattner25db5802004-10-07 04:16:33 +0000244 GS.isNotSuitableForSRA = true;
Chris Lattner7561ca12005-02-27 18:58:52 +0000245 } else if (isa<MemCpyInst>(I) || isa<MemMoveInst>(I)) {
246 if (I->getOperand(1) == V)
247 GS.StoredType = GlobalStatus::isStored;
248 if (I->getOperand(2) == V)
249 GS.isLoaded = true;
250 GS.isNotSuitableForSRA = true;
251 } else if (isa<MemSetInst>(I)) {
252 assert(I->getOperand(1) == V && "Memset only takes one pointer!");
253 GS.StoredType = GlobalStatus::isStored;
254 GS.isNotSuitableForSRA = true;
Chris Lattner25db5802004-10-07 04:16:33 +0000255 } else {
256 return true; // Any other non-load instruction might take address!
257 }
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000258 } else if (Constant *C = dyn_cast<Constant>(*UI)) {
Chris Lattner50bdfcb2005-06-15 21:11:48 +0000259 GS.HasNonInstructionUser = true;
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000260 // We might have a dead and dangling constant hanging off of here.
261 if (!ConstantIsDead(C))
262 return true;
Chris Lattner25db5802004-10-07 04:16:33 +0000263 } else {
Chris Lattner50bdfcb2005-06-15 21:11:48 +0000264 GS.HasNonInstructionUser = true;
265 // Otherwise must be some other user.
Chris Lattner25db5802004-10-07 04:16:33 +0000266 return true;
267 }
268
269 return false;
270}
271
Chris Lattnerabab0712004-10-08 17:32:09 +0000272static Constant *getAggregateConstantElement(Constant *Agg, Constant *Idx) {
273 ConstantInt *CI = dyn_cast<ConstantInt>(Idx);
274 if (!CI) return 0;
Reid Spencere0fc4df2006-10-20 07:07:24 +0000275 unsigned IdxV = CI->getZExtValue();
Chris Lattner25db5802004-10-07 04:16:33 +0000276
Chris Lattnerabab0712004-10-08 17:32:09 +0000277 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Agg)) {
278 if (IdxV < CS->getNumOperands()) return CS->getOperand(IdxV);
279 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Agg)) {
280 if (IdxV < CA->getNumOperands()) return CA->getOperand(IdxV);
Reid Spencerd84d35b2007-02-15 02:26:10 +0000281 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Agg)) {
Chris Lattnerabab0712004-10-08 17:32:09 +0000282 if (IdxV < CP->getNumOperands()) return CP->getOperand(IdxV);
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000283 } else if (isa<ConstantAggregateZero>(Agg)) {
Chris Lattnerabab0712004-10-08 17:32:09 +0000284 if (const StructType *STy = dyn_cast<StructType>(Agg->getType())) {
285 if (IdxV < STy->getNumElements())
286 return Constant::getNullValue(STy->getElementType(IdxV));
287 } else if (const SequentialType *STy =
288 dyn_cast<SequentialType>(Agg->getType())) {
289 return Constant::getNullValue(STy->getElementType());
290 }
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000291 } else if (isa<UndefValue>(Agg)) {
292 if (const StructType *STy = dyn_cast<StructType>(Agg->getType())) {
293 if (IdxV < STy->getNumElements())
294 return UndefValue::get(STy->getElementType(IdxV));
295 } else if (const SequentialType *STy =
296 dyn_cast<SequentialType>(Agg->getType())) {
297 return UndefValue::get(STy->getElementType());
298 }
Chris Lattnerabab0712004-10-08 17:32:09 +0000299 }
300 return 0;
301}
Chris Lattner25db5802004-10-07 04:16:33 +0000302
Chris Lattner25db5802004-10-07 04:16:33 +0000303
304/// CleanupConstantGlobalUsers - We just marked GV constant. Loop over all
305/// users of the global, cleaning up the obvious ones. This is largely just a
Chris Lattnercb9f1522004-10-10 16:43:46 +0000306/// quick scan over the use list to clean up the easy and obvious cruft. This
307/// returns true if it made a change.
308static bool CleanupConstantGlobalUsers(Value *V, Constant *Init) {
309 bool Changed = false;
Chris Lattner25db5802004-10-07 04:16:33 +0000310 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;) {
311 User *U = *UI++;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000312
Chris Lattner25db5802004-10-07 04:16:33 +0000313 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
Chris Lattner7561ca12005-02-27 18:58:52 +0000314 if (Init) {
315 // Replace the load with the initializer.
316 LI->replaceAllUsesWith(Init);
317 LI->eraseFromParent();
318 Changed = true;
319 }
Chris Lattner25db5802004-10-07 04:16:33 +0000320 } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
321 // Store must be unreachable or storing Init into the global.
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000322 SI->eraseFromParent();
Chris Lattnercb9f1522004-10-10 16:43:46 +0000323 Changed = true;
Chris Lattner25db5802004-10-07 04:16:33 +0000324 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
325 if (CE->getOpcode() == Instruction::GetElementPtr) {
Chris Lattner46d9ff082005-09-26 07:34:35 +0000326 Constant *SubInit = 0;
327 if (Init)
328 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
Chris Lattner7561ca12005-02-27 18:58:52 +0000329 Changed |= CleanupConstantGlobalUsers(CE, SubInit);
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000330 } else if (CE->getOpcode() == Instruction::BitCast &&
Chris Lattner7561ca12005-02-27 18:58:52 +0000331 isa<PointerType>(CE->getType())) {
332 // Pointer cast, delete any stores and memsets to the global.
333 Changed |= CleanupConstantGlobalUsers(CE, 0);
334 }
335
336 if (CE->use_empty()) {
337 CE->destroyConstant();
338 Changed = true;
Chris Lattner25db5802004-10-07 04:16:33 +0000339 }
340 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
Chris Lattner61ff32c2005-09-26 05:34:07 +0000341 Constant *SubInit = 0;
Chris Lattner46af55e2005-09-26 06:52:44 +0000342 ConstantExpr *CE =
343 dyn_cast_or_null<ConstantExpr>(ConstantFoldInstruction(GEP));
Chris Lattnereb953f02005-09-27 22:28:11 +0000344 if (Init && CE && CE->getOpcode() == Instruction::GetElementPtr)
Chris Lattner61ff32c2005-09-26 05:34:07 +0000345 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
Chris Lattner7561ca12005-02-27 18:58:52 +0000346 Changed |= CleanupConstantGlobalUsers(GEP, SubInit);
Chris Lattnera0e769c2004-10-10 16:47:33 +0000347
Chris Lattnercb9f1522004-10-10 16:43:46 +0000348 if (GEP->use_empty()) {
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000349 GEP->eraseFromParent();
Chris Lattnercb9f1522004-10-10 16:43:46 +0000350 Changed = true;
351 }
Chris Lattner7561ca12005-02-27 18:58:52 +0000352 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U)) { // memset/cpy/mv
353 if (MI->getRawDest() == V) {
354 MI->eraseFromParent();
355 Changed = true;
356 }
357
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000358 } else if (Constant *C = dyn_cast<Constant>(U)) {
359 // If we have a chain of dead constantexprs or other things dangling from
360 // us, and if they are all dead, nuke them without remorse.
361 if (ConstantIsDead(C)) {
362 C->destroyConstant();
Chris Lattner7561ca12005-02-27 18:58:52 +0000363 // This could have invalidated UI, start over from scratch.
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000364 CleanupConstantGlobalUsers(V, Init);
Chris Lattnercb9f1522004-10-10 16:43:46 +0000365 return true;
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000366 }
Chris Lattner25db5802004-10-07 04:16:33 +0000367 }
368 }
Chris Lattnercb9f1522004-10-10 16:43:46 +0000369 return Changed;
Chris Lattner25db5802004-10-07 04:16:33 +0000370}
371
Chris Lattnerabab0712004-10-08 17:32:09 +0000372/// SRAGlobal - Perform scalar replacement of aggregates on the specified global
373/// variable. This opens the door for other optimizations by exposing the
374/// behavior of the program in a more fine-grained way. We have determined that
375/// this transformation is safe already. We return the first global variable we
376/// insert so that the caller can reprocess it.
377static GlobalVariable *SRAGlobal(GlobalVariable *GV) {
378 assert(GV->hasInternalLinkage() && !GV->isConstant());
379 Constant *Init = GV->getInitializer();
380 const Type *Ty = Init->getType();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000381
Chris Lattnerabab0712004-10-08 17:32:09 +0000382 std::vector<GlobalVariable*> NewGlobals;
383 Module::GlobalListType &Globals = GV->getParent()->getGlobalList();
384
385 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
386 NewGlobals.reserve(STy->getNumElements());
387 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
388 Constant *In = getAggregateConstantElement(Init,
Reid Spencerc635f472006-12-31 05:48:39 +0000389 ConstantInt::get(Type::Int32Ty, i));
Chris Lattnerabab0712004-10-08 17:32:09 +0000390 assert(In && "Couldn't get element of initializer?");
391 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(i), false,
392 GlobalVariable::InternalLinkage,
Lauro Ramos Venancio749e4662007-04-12 18:32:50 +0000393 In, GV->getName()+"."+utostr(i),
394 (Module *)NULL,
395 GV->isThreadLocal());
Chris Lattnerabab0712004-10-08 17:32:09 +0000396 Globals.insert(GV, NGV);
397 NewGlobals.push_back(NGV);
398 }
399 } else if (const SequentialType *STy = dyn_cast<SequentialType>(Ty)) {
400 unsigned NumElements = 0;
401 if (const ArrayType *ATy = dyn_cast<ArrayType>(STy))
402 NumElements = ATy->getNumElements();
Reid Spencerd84d35b2007-02-15 02:26:10 +0000403 else if (const VectorType *PTy = dyn_cast<VectorType>(STy))
Chris Lattnerabab0712004-10-08 17:32:09 +0000404 NumElements = PTy->getNumElements();
405 else
406 assert(0 && "Unknown aggregate sequential type!");
407
Chris Lattner25169ca2005-02-23 16:53:04 +0000408 if (NumElements > 16 && GV->hasNUsesOrMore(16))
Chris Lattnerd6a44922005-02-01 01:23:31 +0000409 return 0; // It's not worth it.
Chris Lattnerabab0712004-10-08 17:32:09 +0000410 NewGlobals.reserve(NumElements);
411 for (unsigned i = 0, e = NumElements; i != e; ++i) {
412 Constant *In = getAggregateConstantElement(Init,
Reid Spencerc635f472006-12-31 05:48:39 +0000413 ConstantInt::get(Type::Int32Ty, i));
Chris Lattnerabab0712004-10-08 17:32:09 +0000414 assert(In && "Couldn't get element of initializer?");
415
416 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(), false,
417 GlobalVariable::InternalLinkage,
Lauro Ramos Venancio749e4662007-04-12 18:32:50 +0000418 In, GV->getName()+"."+utostr(i),
419 (Module *)NULL,
420 GV->isThreadLocal());
Chris Lattnerabab0712004-10-08 17:32:09 +0000421 Globals.insert(GV, NGV);
422 NewGlobals.push_back(NGV);
423 }
424 }
425
426 if (NewGlobals.empty())
427 return 0;
428
Bill Wendling8f13b5c2006-11-26 10:02:32 +0000429 DOUT << "PERFORMING GLOBAL SRA ON: " << *GV;
Chris Lattner004e2502004-10-11 05:54:41 +0000430
Reid Spencerc635f472006-12-31 05:48:39 +0000431 Constant *NullInt = Constant::getNullValue(Type::Int32Ty);
Chris Lattnerabab0712004-10-08 17:32:09 +0000432
433 // Loop over all of the uses of the global, replacing the constantexpr geps,
434 // with smaller constantexpr geps or direct references.
435 while (!GV->use_empty()) {
Chris Lattner004e2502004-10-11 05:54:41 +0000436 User *GEP = GV->use_back();
437 assert(((isa<ConstantExpr>(GEP) &&
438 cast<ConstantExpr>(GEP)->getOpcode()==Instruction::GetElementPtr)||
439 isa<GetElementPtrInst>(GEP)) && "NonGEP CE's are not SRAable!");
Misha Brukmanb1c93172005-04-21 23:48:37 +0000440
Chris Lattnerabab0712004-10-08 17:32:09 +0000441 // Ignore the 1th operand, which has to be zero or else the program is quite
442 // broken (undefined). Get the 2nd operand, which is the structure or array
443 // index.
Reid Spencere0fc4df2006-10-20 07:07:24 +0000444 unsigned Val = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
Chris Lattnerabab0712004-10-08 17:32:09 +0000445 if (Val >= NewGlobals.size()) Val = 0; // Out of bound array access.
446
Chris Lattner004e2502004-10-11 05:54:41 +0000447 Value *NewPtr = NewGlobals[Val];
Chris Lattnerabab0712004-10-08 17:32:09 +0000448
449 // Form a shorter GEP if needed.
Chris Lattner004e2502004-10-11 05:54:41 +0000450 if (GEP->getNumOperands() > 3)
451 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEP)) {
Chris Lattnerf96f4a82007-01-31 04:40:53 +0000452 SmallVector<Constant*, 8> Idxs;
Chris Lattner004e2502004-10-11 05:54:41 +0000453 Idxs.push_back(NullInt);
454 for (unsigned i = 3, e = CE->getNumOperands(); i != e; ++i)
455 Idxs.push_back(CE->getOperand(i));
Chris Lattnerf96f4a82007-01-31 04:40:53 +0000456 NewPtr = ConstantExpr::getGetElementPtr(cast<Constant>(NewPtr),
457 &Idxs[0], Idxs.size());
Chris Lattner004e2502004-10-11 05:54:41 +0000458 } else {
459 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(GEP);
Chris Lattner927653f2007-01-31 19:59:55 +0000460 SmallVector<Value*, 8> Idxs;
Chris Lattner004e2502004-10-11 05:54:41 +0000461 Idxs.push_back(NullInt);
462 for (unsigned i = 3, e = GEPI->getNumOperands(); i != e; ++i)
463 Idxs.push_back(GEPI->getOperand(i));
Chris Lattner927653f2007-01-31 19:59:55 +0000464 NewPtr = new GetElementPtrInst(NewPtr, &Idxs[0], Idxs.size(),
Chris Lattner004e2502004-10-11 05:54:41 +0000465 GEPI->getName()+"."+utostr(Val), GEPI);
466 }
467 GEP->replaceAllUsesWith(NewPtr);
468
469 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(GEP))
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000470 GEPI->eraseFromParent();
Chris Lattner004e2502004-10-11 05:54:41 +0000471 else
472 cast<ConstantExpr>(GEP)->destroyConstant();
Chris Lattnerabab0712004-10-08 17:32:09 +0000473 }
474
Chris Lattner73ad73e2004-10-08 20:25:55 +0000475 // Delete the old global, now that it is dead.
476 Globals.erase(GV);
Chris Lattnerabab0712004-10-08 17:32:09 +0000477 ++NumSRA;
Chris Lattner004e2502004-10-11 05:54:41 +0000478
479 // Loop over the new globals array deleting any globals that are obviously
480 // dead. This can arise due to scalarization of a structure or an array that
481 // has elements that are dead.
482 unsigned FirstGlobal = 0;
483 for (unsigned i = 0, e = NewGlobals.size(); i != e; ++i)
484 if (NewGlobals[i]->use_empty()) {
485 Globals.erase(NewGlobals[i]);
486 if (FirstGlobal == i) ++FirstGlobal;
487 }
488
489 return FirstGlobal != NewGlobals.size() ? NewGlobals[FirstGlobal] : 0;
Chris Lattnerabab0712004-10-08 17:32:09 +0000490}
491
Chris Lattner09a52722004-10-09 21:48:45 +0000492/// AllUsesOfValueWillTrapIfNull - Return true if all users of the specified
493/// value will trap if the value is dynamically null.
494static bool AllUsesOfValueWillTrapIfNull(Value *V) {
495 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
496 if (isa<LoadInst>(*UI)) {
497 // Will trap.
498 } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
499 if (SI->getOperand(0) == V) {
Bill Wendlingf3baad32006-12-07 01:30:32 +0000500 //cerr << "NONTRAPPING USE: " << **UI;
Chris Lattner09a52722004-10-09 21:48:45 +0000501 return false; // Storing the value.
502 }
503 } else if (CallInst *CI = dyn_cast<CallInst>(*UI)) {
504 if (CI->getOperand(0) != V) {
Bill Wendlingf3baad32006-12-07 01:30:32 +0000505 //cerr << "NONTRAPPING USE: " << **UI;
Chris Lattner09a52722004-10-09 21:48:45 +0000506 return false; // Not calling the ptr
507 }
508 } else if (InvokeInst *II = dyn_cast<InvokeInst>(*UI)) {
509 if (II->getOperand(0) != V) {
Bill Wendlingf3baad32006-12-07 01:30:32 +0000510 //cerr << "NONTRAPPING USE: " << **UI;
Chris Lattner09a52722004-10-09 21:48:45 +0000511 return false; // Not calling the ptr
512 }
513 } else if (CastInst *CI = dyn_cast<CastInst>(*UI)) {
514 if (!AllUsesOfValueWillTrapIfNull(CI)) return false;
515 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(*UI)) {
516 if (!AllUsesOfValueWillTrapIfNull(GEPI)) return false;
Reid Spencer266e42b2006-12-23 06:05:41 +0000517 } else if (isa<ICmpInst>(*UI) &&
Chris Lattnerfe9abf92004-10-22 06:43:28 +0000518 isa<ConstantPointerNull>(UI->getOperand(1))) {
519 // Ignore setcc X, null
Chris Lattner09a52722004-10-09 21:48:45 +0000520 } else {
Bill Wendlingf3baad32006-12-07 01:30:32 +0000521 //cerr << "NONTRAPPING USE: " << **UI;
Chris Lattner09a52722004-10-09 21:48:45 +0000522 return false;
523 }
524 return true;
525}
526
527/// AllUsesOfLoadedValueWillTrapIfNull - Return true if all uses of any loads
Chris Lattnerfe9abf92004-10-22 06:43:28 +0000528/// from GV will trap if the loaded value is null. Note that this also permits
529/// comparisons of the loaded value against null, as a special case.
Chris Lattner09a52722004-10-09 21:48:45 +0000530static bool AllUsesOfLoadedValueWillTrapIfNull(GlobalVariable *GV) {
531 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI!=E; ++UI)
532 if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
533 if (!AllUsesOfValueWillTrapIfNull(LI))
534 return false;
535 } else if (isa<StoreInst>(*UI)) {
536 // Ignore stores to the global.
537 } else {
538 // We don't know or understand this user, bail out.
Bill Wendlingf3baad32006-12-07 01:30:32 +0000539 //cerr << "UNKNOWN USER OF GLOBAL!: " << **UI;
Chris Lattner09a52722004-10-09 21:48:45 +0000540 return false;
541 }
542
543 return true;
544}
545
Chris Lattnere42eb312004-10-10 23:14:11 +0000546static bool OptimizeAwayTrappingUsesOfValue(Value *V, Constant *NewV) {
547 bool Changed = false;
548 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ) {
549 Instruction *I = cast<Instruction>(*UI++);
550 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
551 LI->setOperand(0, NewV);
552 Changed = true;
553 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
554 if (SI->getOperand(1) == V) {
555 SI->setOperand(1, NewV);
556 Changed = true;
557 }
558 } else if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
559 if (I->getOperand(0) == V) {
560 // Calling through the pointer! Turn into a direct call, but be careful
561 // that the pointer is not also being passed as an argument.
562 I->setOperand(0, NewV);
563 Changed = true;
564 bool PassedAsArg = false;
565 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i)
566 if (I->getOperand(i) == V) {
567 PassedAsArg = true;
568 I->setOperand(i, NewV);
569 }
570
571 if (PassedAsArg) {
572 // Being passed as an argument also. Be careful to not invalidate UI!
573 UI = V->use_begin();
574 }
575 }
576 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
577 Changed |= OptimizeAwayTrappingUsesOfValue(CI,
Chris Lattner3ede00b2006-11-30 17:32:29 +0000578 ConstantExpr::getCast(CI->getOpcode(),
579 NewV, CI->getType()));
Chris Lattnere42eb312004-10-10 23:14:11 +0000580 if (CI->use_empty()) {
581 Changed = true;
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000582 CI->eraseFromParent();
Chris Lattnere42eb312004-10-10 23:14:11 +0000583 }
584 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
585 // Should handle GEP here.
Chris Lattnerf96f4a82007-01-31 04:40:53 +0000586 SmallVector<Constant*, 8> Idxs;
587 Idxs.reserve(GEPI->getNumOperands()-1);
Chris Lattnere42eb312004-10-10 23:14:11 +0000588 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
589 if (Constant *C = dyn_cast<Constant>(GEPI->getOperand(i)))
Chris Lattnerf96f4a82007-01-31 04:40:53 +0000590 Idxs.push_back(C);
Chris Lattnere42eb312004-10-10 23:14:11 +0000591 else
592 break;
Chris Lattnerf96f4a82007-01-31 04:40:53 +0000593 if (Idxs.size() == GEPI->getNumOperands()-1)
Chris Lattnere42eb312004-10-10 23:14:11 +0000594 Changed |= OptimizeAwayTrappingUsesOfValue(GEPI,
Chris Lattnerf96f4a82007-01-31 04:40:53 +0000595 ConstantExpr::getGetElementPtr(NewV, &Idxs[0],
596 Idxs.size()));
Chris Lattnere42eb312004-10-10 23:14:11 +0000597 if (GEPI->use_empty()) {
598 Changed = true;
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000599 GEPI->eraseFromParent();
Chris Lattnere42eb312004-10-10 23:14:11 +0000600 }
601 }
602 }
603
604 return Changed;
605}
606
607
608/// OptimizeAwayTrappingUsesOfLoads - The specified global has only one non-null
609/// value stored into it. If there are uses of the loaded value that would trap
610/// if the loaded value is dynamically null, then we know that they cannot be
611/// reachable with a null optimize away the load.
612static bool OptimizeAwayTrappingUsesOfLoads(GlobalVariable *GV, Constant *LV) {
613 std::vector<LoadInst*> Loads;
614 bool Changed = false;
615
616 // Replace all uses of loads with uses of uses of the stored value.
617 for (Value::use_iterator GUI = GV->use_begin(), E = GV->use_end();
618 GUI != E; ++GUI)
619 if (LoadInst *LI = dyn_cast<LoadInst>(*GUI)) {
620 Loads.push_back(LI);
621 Changed |= OptimizeAwayTrappingUsesOfValue(LI, LV);
622 } else {
623 assert(isa<StoreInst>(*GUI) && "Only expect load and stores!");
624 }
625
626 if (Changed) {
Bill Wendling8f13b5c2006-11-26 10:02:32 +0000627 DOUT << "OPTIMIZED LOADS FROM STORED ONCE POINTER: " << *GV;
Chris Lattnere42eb312004-10-10 23:14:11 +0000628 ++NumGlobUses;
629 }
630
631 // Delete all of the loads we can, keeping track of whether we nuked them all!
632 bool AllLoadsGone = true;
633 while (!Loads.empty()) {
634 LoadInst *L = Loads.back();
635 if (L->use_empty()) {
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000636 L->eraseFromParent();
Chris Lattnere42eb312004-10-10 23:14:11 +0000637 Changed = true;
638 } else {
639 AllLoadsGone = false;
640 }
641 Loads.pop_back();
642 }
643
644 // If we nuked all of the loads, then none of the stores are needed either,
645 // nor is the global.
646 if (AllLoadsGone) {
Bill Wendling8f13b5c2006-11-26 10:02:32 +0000647 DOUT << " *** GLOBAL NOW DEAD!\n";
Chris Lattnere42eb312004-10-10 23:14:11 +0000648 CleanupConstantGlobalUsers(GV, 0);
649 if (GV->use_empty()) {
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000650 GV->eraseFromParent();
Chris Lattnere42eb312004-10-10 23:14:11 +0000651 ++NumDeleted;
652 }
653 Changed = true;
654 }
655 return Changed;
656}
657
Chris Lattner004e2502004-10-11 05:54:41 +0000658/// ConstantPropUsersOf - Walk the use list of V, constant folding all of the
659/// instructions that are foldable.
660static void ConstantPropUsersOf(Value *V) {
661 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; )
662 if (Instruction *I = dyn_cast<Instruction>(*UI++))
663 if (Constant *NewC = ConstantFoldInstruction(I)) {
664 I->replaceAllUsesWith(NewC);
665
Chris Lattnerd6a44922005-02-01 01:23:31 +0000666 // Advance UI to the next non-I use to avoid invalidating it!
667 // Instructions could multiply use V.
668 while (UI != E && *UI == I)
Chris Lattner004e2502004-10-11 05:54:41 +0000669 ++UI;
Chris Lattnerd6a44922005-02-01 01:23:31 +0000670 I->eraseFromParent();
Chris Lattner004e2502004-10-11 05:54:41 +0000671 }
672}
673
674/// OptimizeGlobalAddressOfMalloc - This function takes the specified global
675/// variable, and transforms the program as if it always contained the result of
676/// the specified malloc. Because it is always the result of the specified
677/// malloc, there is no reason to actually DO the malloc. Instead, turn the
Chris Lattner3ede00b2006-11-30 17:32:29 +0000678/// malloc into a global, and any loads of GV as uses of the new global.
Chris Lattner004e2502004-10-11 05:54:41 +0000679static GlobalVariable *OptimizeGlobalAddressOfMalloc(GlobalVariable *GV,
680 MallocInst *MI) {
Bill Wendling8f13b5c2006-11-26 10:02:32 +0000681 DOUT << "PROMOTING MALLOC GLOBAL: " << *GV << " MALLOC = " << *MI;
Chris Lattner004e2502004-10-11 05:54:41 +0000682 ConstantInt *NElements = cast<ConstantInt>(MI->getArraySize());
683
Reid Spencere0fc4df2006-10-20 07:07:24 +0000684 if (NElements->getZExtValue() != 1) {
Chris Lattner004e2502004-10-11 05:54:41 +0000685 // If we have an array allocation, transform it to a single element
686 // allocation to make the code below simpler.
687 Type *NewTy = ArrayType::get(MI->getAllocatedType(),
Reid Spencere0fc4df2006-10-20 07:07:24 +0000688 NElements->getZExtValue());
Chris Lattner004e2502004-10-11 05:54:41 +0000689 MallocInst *NewMI =
Reid Spencerc635f472006-12-31 05:48:39 +0000690 new MallocInst(NewTy, Constant::getNullValue(Type::Int32Ty),
Nate Begeman848622f2005-11-05 09:21:28 +0000691 MI->getAlignment(), MI->getName(), MI);
Chris Lattner927653f2007-01-31 19:59:55 +0000692 Value* Indices[2];
693 Indices[0] = Indices[1] = Constant::getNullValue(Type::Int32Ty);
694 Value *NewGEP = new GetElementPtrInst(NewMI, Indices, 2,
Chris Lattner004e2502004-10-11 05:54:41 +0000695 NewMI->getName()+".el0", MI);
696 MI->replaceAllUsesWith(NewGEP);
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000697 MI->eraseFromParent();
Chris Lattner004e2502004-10-11 05:54:41 +0000698 MI = NewMI;
699 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000700
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000701 // Create the new global variable. The contents of the malloc'd memory is
702 // undefined, so initialize with an undef value.
703 Constant *Init = UndefValue::get(MI->getAllocatedType());
Chris Lattner004e2502004-10-11 05:54:41 +0000704 GlobalVariable *NewGV = new GlobalVariable(MI->getAllocatedType(), false,
705 GlobalValue::InternalLinkage, Init,
Lauro Ramos Venancio749e4662007-04-12 18:32:50 +0000706 GV->getName()+".body",
707 (Module *)NULL,
708 GV->isThreadLocal());
Chris Lattner004e2502004-10-11 05:54:41 +0000709 GV->getParent()->getGlobalList().insert(GV, NewGV);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000710
Chris Lattner004e2502004-10-11 05:54:41 +0000711 // Anything that used the malloc now uses the global directly.
712 MI->replaceAllUsesWith(NewGV);
Chris Lattner004e2502004-10-11 05:54:41 +0000713
714 Constant *RepValue = NewGV;
715 if (NewGV->getType() != GV->getType()->getElementType())
Reid Spencerbb65ebf2006-12-12 23:36:14 +0000716 RepValue = ConstantExpr::getBitCast(RepValue,
717 GV->getType()->getElementType());
Chris Lattner004e2502004-10-11 05:54:41 +0000718
Chris Lattnerfe9abf92004-10-22 06:43:28 +0000719 // If there is a comparison against null, we will insert a global bool to
720 // keep track of whether the global was initialized yet or not.
Misha Brukmanb1c93172005-04-21 23:48:37 +0000721 GlobalVariable *InitBool =
Reid Spencer542964f2007-01-11 18:21:29 +0000722 new GlobalVariable(Type::Int1Ty, false, GlobalValue::InternalLinkage,
Lauro Ramos Venancio749e4662007-04-12 18:32:50 +0000723 ConstantInt::getFalse(), GV->getName()+".init",
724 (Module *)NULL, GV->isThreadLocal());
Chris Lattner3b181392004-12-02 06:25:58 +0000725 bool InitBoolUsed = false;
Chris Lattnerfe9abf92004-10-22 06:43:28 +0000726
Chris Lattner004e2502004-10-11 05:54:41 +0000727 // Loop over all uses of GV, processing them in turn.
Chris Lattner3b181392004-12-02 06:25:58 +0000728 std::vector<StoreInst*> Stores;
Chris Lattner004e2502004-10-11 05:54:41 +0000729 while (!GV->use_empty())
730 if (LoadInst *LI = dyn_cast<LoadInst>(GV->use_back())) {
Chris Lattnerfe9abf92004-10-22 06:43:28 +0000731 while (!LI->use_empty()) {
Chris Lattnerd6a44922005-02-01 01:23:31 +0000732 Use &LoadUse = LI->use_begin().getUse();
Reid Spencer266e42b2006-12-23 06:05:41 +0000733 if (!isa<ICmpInst>(LoadUse.getUser()))
Chris Lattnerfe9abf92004-10-22 06:43:28 +0000734 LoadUse = RepValue;
735 else {
Reid Spencer266e42b2006-12-23 06:05:41 +0000736 ICmpInst *CI = cast<ICmpInst>(LoadUse.getUser());
737 // Replace the cmp X, 0 with a use of the bool value.
738 Value *LV = new LoadInst(InitBool, InitBool->getName()+".val", CI);
Chris Lattner3b181392004-12-02 06:25:58 +0000739 InitBoolUsed = true;
Reid Spencer266e42b2006-12-23 06:05:41 +0000740 switch (CI->getPredicate()) {
741 default: assert(0 && "Unknown ICmp Predicate!");
742 case ICmpInst::ICMP_ULT:
743 case ICmpInst::ICMP_SLT:
Zhou Sheng75b871f2007-01-11 12:24:14 +0000744 LV = ConstantInt::getFalse(); // X < null -> always false
Chris Lattnerfe9abf92004-10-22 06:43:28 +0000745 break;
Reid Spencer266e42b2006-12-23 06:05:41 +0000746 case ICmpInst::ICMP_ULE:
747 case ICmpInst::ICMP_SLE:
748 case ICmpInst::ICMP_EQ:
749 LV = BinaryOperator::createNot(LV, "notinit", CI);
Chris Lattnerfe9abf92004-10-22 06:43:28 +0000750 break;
Reid Spencer266e42b2006-12-23 06:05:41 +0000751 case ICmpInst::ICMP_NE:
752 case ICmpInst::ICMP_UGE:
753 case ICmpInst::ICMP_SGE:
754 case ICmpInst::ICMP_UGT:
755 case ICmpInst::ICMP_SGT:
Chris Lattnerfe9abf92004-10-22 06:43:28 +0000756 break; // no change.
757 }
Reid Spencer266e42b2006-12-23 06:05:41 +0000758 CI->replaceAllUsesWith(LV);
759 CI->eraseFromParent();
Chris Lattnerfe9abf92004-10-22 06:43:28 +0000760 }
761 }
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000762 LI->eraseFromParent();
Chris Lattner004e2502004-10-11 05:54:41 +0000763 } else {
764 StoreInst *SI = cast<StoreInst>(GV->use_back());
Chris Lattner3b181392004-12-02 06:25:58 +0000765 // The global is initialized when the store to it occurs.
Zhou Sheng75b871f2007-01-11 12:24:14 +0000766 new StoreInst(ConstantInt::getTrue(), InitBool, SI);
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000767 SI->eraseFromParent();
Chris Lattner004e2502004-10-11 05:54:41 +0000768 }
769
Chris Lattner3b181392004-12-02 06:25:58 +0000770 // If the initialization boolean was used, insert it, otherwise delete it.
771 if (!InitBoolUsed) {
772 while (!InitBool->use_empty()) // Delete initializations
773 cast<Instruction>(InitBool->use_back())->eraseFromParent();
774 delete InitBool;
775 } else
776 GV->getParent()->getGlobalList().insert(GV, InitBool);
777
778
Chris Lattnerfe9abf92004-10-22 06:43:28 +0000779 // Now the GV is dead, nuke it and the malloc.
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000780 GV->eraseFromParent();
Chris Lattnerfe9abf92004-10-22 06:43:28 +0000781 MI->eraseFromParent();
Chris Lattner004e2502004-10-11 05:54:41 +0000782
783 // To further other optimizations, loop over all users of NewGV and try to
784 // constant prop them. This will promote GEP instructions with constant
785 // indices into GEP constant-exprs, which will allow global-opt to hack on it.
786 ConstantPropUsersOf(NewGV);
787 if (RepValue != NewGV)
788 ConstantPropUsersOf(RepValue);
789
790 return NewGV;
791}
Chris Lattnere42eb312004-10-10 23:14:11 +0000792
Chris Lattnerc0677c02004-12-02 07:11:07 +0000793/// ValueIsOnlyUsedLocallyOrStoredToOneGlobal - Scan the use-list of V checking
794/// to make sure that there are no complex uses of V. We permit simple things
795/// like dereferencing the pointer, but not storing through the address, unless
796/// it is to the specified global.
797static bool ValueIsOnlyUsedLocallyOrStoredToOneGlobal(Instruction *V,
798 GlobalVariable *GV) {
799 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;++UI)
Reid Spencer266e42b2006-12-23 06:05:41 +0000800 if (isa<LoadInst>(*UI) || isa<CmpInst>(*UI)) {
Chris Lattnerc0677c02004-12-02 07:11:07 +0000801 // Fine, ignore.
802 } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
803 if (SI->getOperand(0) == V && SI->getOperand(1) != GV)
804 return false; // Storing the pointer itself... bad.
805 // Otherwise, storing through it, or storing into GV... fine.
806 } else if (isa<GetElementPtrInst>(*UI) || isa<SelectInst>(*UI)) {
807 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(cast<Instruction>(*UI),GV))
808 return false;
809 } else {
810 return false;
811 }
812 return true;
Chris Lattnerc0677c02004-12-02 07:11:07 +0000813}
814
Chris Lattner24d3d422006-09-30 23:32:09 +0000815/// ReplaceUsesOfMallocWithGlobal - The Alloc pointer is stored into GV
816/// somewhere. Transform all uses of the allocation into loads from the
817/// global and uses of the resultant pointer. Further, delete the store into
818/// GV. This assumes that these value pass the
819/// 'ValueIsOnlyUsedLocallyOrStoredToOneGlobal' predicate.
820static void ReplaceUsesOfMallocWithGlobal(Instruction *Alloc,
821 GlobalVariable *GV) {
822 while (!Alloc->use_empty()) {
823 Instruction *U = Alloc->use_back();
824 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
825 // If this is the store of the allocation into the global, remove it.
826 if (SI->getOperand(1) == GV) {
827 SI->eraseFromParent();
828 continue;
829 }
830 }
831
832 // Insert a load from the global, and use it instead of the malloc.
833 Value *NL = new LoadInst(GV, GV->getName()+".val", U);
834 U->replaceUsesOfWith(Alloc, NL);
835 }
836}
837
838/// GlobalLoadUsesSimpleEnoughForHeapSRA - If all users of values loaded from
839/// GV are simple enough to perform HeapSRA, return true.
840static bool GlobalLoadUsesSimpleEnoughForHeapSRA(GlobalVariable *GV) {
841 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI != E;
842 ++UI)
843 if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
844 // We permit two users of the load: setcc comparing against the null
845 // pointer, and a getelementptr of a specific form.
846 for (Value::use_iterator UI = LI->use_begin(), E = LI->use_end(); UI != E;
847 ++UI) {
848 // Comparison against null is ok.
Reid Spencer266e42b2006-12-23 06:05:41 +0000849 if (ICmpInst *ICI = dyn_cast<ICmpInst>(*UI)) {
850 if (!isa<ConstantPointerNull>(ICI->getOperand(1)))
Chris Lattner24d3d422006-09-30 23:32:09 +0000851 return false;
852 continue;
853 }
854
855 // getelementptr is also ok, but only a simple form.
856 GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(*UI);
857 if (!GEPI) return false;
858
859 // Must index into the array and into the struct.
860 if (GEPI->getNumOperands() < 3)
861 return false;
862
863 // Otherwise the GEP is ok.
864 continue;
865 }
866 }
867 return true;
868}
869
870/// RewriteUsesOfLoadForHeapSRoA - We are performing Heap SRoA on a global. Ptr
871/// is a value loaded from the global. Eliminate all uses of Ptr, making them
872/// use FieldGlobals instead. All uses of loaded values satisfy
873/// GlobalLoadUsesSimpleEnoughForHeapSRA.
874static void RewriteUsesOfLoadForHeapSRoA(LoadInst *Ptr,
875 const std::vector<GlobalVariable*> &FieldGlobals) {
876 std::vector<Value *> InsertedLoadsForPtr;
877 //InsertedLoadsForPtr.resize(FieldGlobals.size());
878 while (!Ptr->use_empty()) {
879 Instruction *User = Ptr->use_back();
880
881 // If this is a comparison against null, handle it.
Reid Spencer266e42b2006-12-23 06:05:41 +0000882 if (ICmpInst *SCI = dyn_cast<ICmpInst>(User)) {
Chris Lattner24d3d422006-09-30 23:32:09 +0000883 assert(isa<ConstantPointerNull>(SCI->getOperand(1)));
884 // If we have a setcc of the loaded pointer, we can use a setcc of any
885 // field.
886 Value *NPtr;
887 if (InsertedLoadsForPtr.empty()) {
888 NPtr = new LoadInst(FieldGlobals[0], Ptr->getName()+".f0", Ptr);
889 InsertedLoadsForPtr.push_back(Ptr);
890 } else {
891 NPtr = InsertedLoadsForPtr.back();
892 }
893
Reid Spencer266e42b2006-12-23 06:05:41 +0000894 Value *New = new ICmpInst(SCI->getPredicate(), NPtr,
895 Constant::getNullValue(NPtr->getType()),
896 SCI->getName(), SCI);
Chris Lattner24d3d422006-09-30 23:32:09 +0000897 SCI->replaceAllUsesWith(New);
898 SCI->eraseFromParent();
899 continue;
900 }
901
902 // Otherwise, this should be: 'getelementptr Ptr, Idx, uint FieldNo ...'
903 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(User);
Reid Spencere0fc4df2006-10-20 07:07:24 +0000904 assert(GEPI->getNumOperands() >= 3 && isa<ConstantInt>(GEPI->getOperand(2))
Chris Lattner24d3d422006-09-30 23:32:09 +0000905 && "Unexpected GEPI!");
906
907 // Load the pointer for this field.
Reid Spencere0fc4df2006-10-20 07:07:24 +0000908 unsigned FieldNo = cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue();
Chris Lattner24d3d422006-09-30 23:32:09 +0000909 if (InsertedLoadsForPtr.size() <= FieldNo)
910 InsertedLoadsForPtr.resize(FieldNo+1);
911 if (InsertedLoadsForPtr[FieldNo] == 0)
912 InsertedLoadsForPtr[FieldNo] = new LoadInst(FieldGlobals[FieldNo],
913 Ptr->getName()+".f" +
914 utostr(FieldNo), Ptr);
915 Value *NewPtr = InsertedLoadsForPtr[FieldNo];
916
917 // Create the new GEP idx vector.
Chris Lattnera7315132007-02-12 22:56:41 +0000918 SmallVector<Value*, 8> GEPIdx;
Chris Lattner24d3d422006-09-30 23:32:09 +0000919 GEPIdx.push_back(GEPI->getOperand(1));
Chris Lattnera7315132007-02-12 22:56:41 +0000920 GEPIdx.append(GEPI->op_begin()+3, GEPI->op_end());
Chris Lattner24d3d422006-09-30 23:32:09 +0000921
Chris Lattnera7315132007-02-12 22:56:41 +0000922 Value *NGEPI = new GetElementPtrInst(NewPtr, &GEPIdx[0], GEPIdx.size(),
923 GEPI->getName(), GEPI);
Chris Lattner24d3d422006-09-30 23:32:09 +0000924 GEPI->replaceAllUsesWith(NGEPI);
925 GEPI->eraseFromParent();
926 }
927}
928
929/// PerformHeapAllocSRoA - MI is an allocation of an array of structures. Break
930/// it up into multiple allocations of arrays of the fields.
931static GlobalVariable *PerformHeapAllocSRoA(GlobalVariable *GV, MallocInst *MI){
Bill Wendling8f13b5c2006-11-26 10:02:32 +0000932 DOUT << "SROA HEAP ALLOC: " << *GV << " MALLOC = " << *MI;
Chris Lattner24d3d422006-09-30 23:32:09 +0000933 const StructType *STy = cast<StructType>(MI->getAllocatedType());
934
935 // There is guaranteed to be at least one use of the malloc (storing
936 // it into GV). If there are other uses, change them to be uses of
937 // the global to simplify later code. This also deletes the store
938 // into GV.
939 ReplaceUsesOfMallocWithGlobal(MI, GV);
940
941 // Okay, at this point, there are no users of the malloc. Insert N
942 // new mallocs at the same place as MI, and N globals.
943 std::vector<GlobalVariable*> FieldGlobals;
944 std::vector<MallocInst*> FieldMallocs;
945
946 for (unsigned FieldNo = 0, e = STy->getNumElements(); FieldNo != e;++FieldNo){
947 const Type *FieldTy = STy->getElementType(FieldNo);
948 const Type *PFieldTy = PointerType::get(FieldTy);
949
950 GlobalVariable *NGV =
951 new GlobalVariable(PFieldTy, false, GlobalValue::InternalLinkage,
952 Constant::getNullValue(PFieldTy),
Lauro Ramos Venancio749e4662007-04-12 18:32:50 +0000953 GV->getName() + ".f" + utostr(FieldNo), GV,
954 GV->isThreadLocal());
Chris Lattner24d3d422006-09-30 23:32:09 +0000955 FieldGlobals.push_back(NGV);
956
957 MallocInst *NMI = new MallocInst(FieldTy, MI->getArraySize(),
958 MI->getName() + ".f" + utostr(FieldNo),MI);
959 FieldMallocs.push_back(NMI);
960 new StoreInst(NMI, NGV, MI);
961 }
962
963 // The tricky aspect of this transformation is handling the case when malloc
964 // fails. In the original code, malloc failing would set the result pointer
965 // of malloc to null. In this case, some mallocs could succeed and others
966 // could fail. As such, we emit code that looks like this:
967 // F0 = malloc(field0)
968 // F1 = malloc(field1)
969 // F2 = malloc(field2)
970 // if (F0 == 0 || F1 == 0 || F2 == 0) {
971 // if (F0) { free(F0); F0 = 0; }
972 // if (F1) { free(F1); F1 = 0; }
973 // if (F2) { free(F2); F2 = 0; }
974 // }
975 Value *RunningOr = 0;
976 for (unsigned i = 0, e = FieldMallocs.size(); i != e; ++i) {
Reid Spencer266e42b2006-12-23 06:05:41 +0000977 Value *Cond = new ICmpInst(ICmpInst::ICMP_EQ, FieldMallocs[i],
Chris Lattner24d3d422006-09-30 23:32:09 +0000978 Constant::getNullValue(FieldMallocs[i]->getType()),
979 "isnull", MI);
980 if (!RunningOr)
981 RunningOr = Cond; // First seteq
982 else
983 RunningOr = BinaryOperator::createOr(RunningOr, Cond, "tmp", MI);
984 }
985
986 // Split the basic block at the old malloc.
987 BasicBlock *OrigBB = MI->getParent();
988 BasicBlock *ContBB = OrigBB->splitBasicBlock(MI, "malloc_cont");
989
990 // Create the block to check the first condition. Put all these blocks at the
991 // end of the function as they are unlikely to be executed.
992 BasicBlock *NullPtrBlock = new BasicBlock("malloc_ret_null",
993 OrigBB->getParent());
994
995 // Remove the uncond branch from OrigBB to ContBB, turning it into a cond
996 // branch on RunningOr.
997 OrigBB->getTerminator()->eraseFromParent();
998 new BranchInst(NullPtrBlock, ContBB, RunningOr, OrigBB);
999
1000 // Within the NullPtrBlock, we need to emit a comparison and branch for each
1001 // pointer, because some may be null while others are not.
1002 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
1003 Value *GVVal = new LoadInst(FieldGlobals[i], "tmp", NullPtrBlock);
Reid Spencer266e42b2006-12-23 06:05:41 +00001004 Value *Cmp = new ICmpInst(ICmpInst::ICMP_NE, GVVal,
1005 Constant::getNullValue(GVVal->getType()),
1006 "tmp", NullPtrBlock);
Chris Lattner24d3d422006-09-30 23:32:09 +00001007 BasicBlock *FreeBlock = new BasicBlock("free_it", OrigBB->getParent());
1008 BasicBlock *NextBlock = new BasicBlock("next", OrigBB->getParent());
1009 new BranchInst(FreeBlock, NextBlock, Cmp, NullPtrBlock);
1010
1011 // Fill in FreeBlock.
1012 new FreeInst(GVVal, FreeBlock);
1013 new StoreInst(Constant::getNullValue(GVVal->getType()), FieldGlobals[i],
1014 FreeBlock);
1015 new BranchInst(NextBlock, FreeBlock);
1016
1017 NullPtrBlock = NextBlock;
1018 }
1019
1020 new BranchInst(ContBB, NullPtrBlock);
1021
1022
1023 // MI is no longer needed, remove it.
1024 MI->eraseFromParent();
1025
1026
1027 // Okay, the malloc site is completely handled. All of the uses of GV are now
1028 // loads, and all uses of those loads are simple. Rewrite them to use loads
1029 // of the per-field globals instead.
1030 while (!GV->use_empty()) {
Chris Lattner8571caa2007-01-09 23:29:37 +00001031 if (LoadInst *LI = dyn_cast<LoadInst>(GV->use_back())) {
1032 RewriteUsesOfLoadForHeapSRoA(LI, FieldGlobals);
1033 LI->eraseFromParent();
1034 } else {
1035 // Must be a store of null.
1036 StoreInst *SI = cast<StoreInst>(GV->use_back());
1037 assert(isa<Constant>(SI->getOperand(0)) &&
1038 cast<Constant>(SI->getOperand(0))->isNullValue() &&
1039 "Unexpected heap-sra user!");
1040
1041 // Insert a store of null into each global.
1042 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
1043 Constant *Null =
1044 Constant::getNullValue(FieldGlobals[i]->getType()->getElementType());
1045 new StoreInst(Null, FieldGlobals[i], SI);
1046 }
1047 // Erase the original store.
1048 SI->eraseFromParent();
1049 }
Chris Lattner24d3d422006-09-30 23:32:09 +00001050 }
1051
1052 // The old global is now dead, remove it.
1053 GV->eraseFromParent();
1054
1055 ++NumHeapSRA;
1056 return FieldGlobals[0];
1057}
1058
1059
Chris Lattner09a52722004-10-09 21:48:45 +00001060// OptimizeOnceStoredGlobal - Try to optimize globals based on the knowledge
1061// that only one value (besides its initializer) is ever stored to the global.
Chris Lattner004e2502004-10-11 05:54:41 +00001062static bool OptimizeOnceStoredGlobal(GlobalVariable *GV, Value *StoredOnceVal,
Chris Lattnerc2d3d312006-08-27 22:42:52 +00001063 Module::global_iterator &GVI,
1064 TargetData &TD) {
Chris Lattner09a52722004-10-09 21:48:45 +00001065 if (CastInst *CI = dyn_cast<CastInst>(StoredOnceVal))
1066 StoredOnceVal = CI->getOperand(0);
1067 else if (GetElementPtrInst *GEPI =dyn_cast<GetElementPtrInst>(StoredOnceVal)){
Chris Lattnere42eb312004-10-10 23:14:11 +00001068 // "getelementptr Ptr, 0, 0, 0" is really just a cast.
Chris Lattner09a52722004-10-09 21:48:45 +00001069 bool IsJustACast = true;
1070 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
1071 if (!isa<Constant>(GEPI->getOperand(i)) ||
1072 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
1073 IsJustACast = false;
1074 break;
1075 }
1076 if (IsJustACast)
1077 StoredOnceVal = GEPI->getOperand(0);
1078 }
1079
Chris Lattnere42eb312004-10-10 23:14:11 +00001080 // If we are dealing with a pointer global that is initialized to null and
1081 // only has one (non-null) value stored into it, then we can optimize any
1082 // users of the loaded value (often calls and loads) that would trap if the
1083 // value was null.
Chris Lattner09a52722004-10-09 21:48:45 +00001084 if (isa<PointerType>(GV->getInitializer()->getType()) &&
1085 GV->getInitializer()->isNullValue()) {
Chris Lattnere42eb312004-10-10 23:14:11 +00001086 if (Constant *SOVC = dyn_cast<Constant>(StoredOnceVal)) {
1087 if (GV->getInitializer()->getType() != SOVC->getType())
Reid Spencerbb65ebf2006-12-12 23:36:14 +00001088 SOVC = ConstantExpr::getBitCast(SOVC, GV->getInitializer()->getType());
Misha Brukmanb1c93172005-04-21 23:48:37 +00001089
Chris Lattnere42eb312004-10-10 23:14:11 +00001090 // Optimize away any trapping uses of the loaded value.
1091 if (OptimizeAwayTrappingUsesOfLoads(GV, SOVC))
Chris Lattner604ed7a2004-10-10 17:07:12 +00001092 return true;
Chris Lattner004e2502004-10-11 05:54:41 +00001093 } else if (MallocInst *MI = dyn_cast<MallocInst>(StoredOnceVal)) {
Chris Lattner80a01ef2006-09-30 19:40:30 +00001094 // If this is a malloc of an abstract type, don't touch it.
1095 if (!MI->getAllocatedType()->isSized())
1096 return false;
1097
Chris Lattner24d3d422006-09-30 23:32:09 +00001098 // We can't optimize this global unless all uses of it are *known* to be
1099 // of the malloc value, not of the null initializer value (consider a use
1100 // that compares the global's value against zero to see if the malloc has
1101 // been reached). To do this, we check to see if all uses of the global
1102 // would trap if the global were null: this proves that they must all
1103 // happen after the malloc.
1104 if (!AllUsesOfLoadedValueWillTrapIfNull(GV))
1105 return false;
1106
1107 // We can't optimize this if the malloc itself is used in a complex way,
1108 // for example, being stored into multiple globals. This allows the
1109 // malloc to be stored into the specified global, loaded setcc'd, and
1110 // GEP'd. These are all things we could transform to using the global
1111 // for.
1112 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(MI, GV))
1113 return false;
1114
1115
Chris Lattner004e2502004-10-11 05:54:41 +00001116 // If we have a global that is only initialized with a fixed size malloc,
Chris Lattner24d3d422006-09-30 23:32:09 +00001117 // transform the program to use global memory instead of malloc'd memory.
1118 // This eliminates dynamic allocation, avoids an indirection accessing the
1119 // data, and exposes the resultant global to further GlobalOpt.
Chris Lattner80a01ef2006-09-30 19:40:30 +00001120 if (ConstantInt *NElements = dyn_cast<ConstantInt>(MI->getArraySize())) {
Chris Lattner24d3d422006-09-30 23:32:09 +00001121 // Restrict this transformation to only working on small allocations
1122 // (2048 bytes currently), as we don't want to introduce a 16M global or
1123 // something.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001124 if (NElements->getZExtValue()*
Chris Lattner24d3d422006-09-30 23:32:09 +00001125 TD.getTypeSize(MI->getAllocatedType()) < 2048) {
Chris Lattner004e2502004-10-11 05:54:41 +00001126 GVI = OptimizeGlobalAddressOfMalloc(GV, MI);
1127 return true;
1128 }
Chris Lattner80a01ef2006-09-30 19:40:30 +00001129 }
Chris Lattner24d3d422006-09-30 23:32:09 +00001130
1131 // If the allocation is an array of structures, consider transforming this
1132 // into multiple malloc'd arrays, one for each field. This is basically
1133 // SRoA for malloc'd memory.
1134 if (const StructType *AllocTy =
1135 dyn_cast<StructType>(MI->getAllocatedType())) {
1136 // This the structure has an unreasonable number of fields, leave it
1137 // alone.
1138 if (AllocTy->getNumElements() <= 16 && AllocTy->getNumElements() > 0 &&
1139 GlobalLoadUsesSimpleEnoughForHeapSRA(GV)) {
1140 GVI = PerformHeapAllocSRoA(GV, MI);
1141 return true;
1142 }
1143 }
Chris Lattnere42eb312004-10-10 23:14:11 +00001144 }
Chris Lattner09a52722004-10-09 21:48:45 +00001145 }
Chris Lattner004e2502004-10-11 05:54:41 +00001146
Chris Lattner09a52722004-10-09 21:48:45 +00001147 return false;
1148}
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001149
Chris Lattner40e4cec2004-12-12 05:53:50 +00001150/// ShrinkGlobalToBoolean - At this point, we have learned that the only two
Misha Brukmanb1c93172005-04-21 23:48:37 +00001151/// values ever stored into GV are its initializer and OtherVal.
Chris Lattner40e4cec2004-12-12 05:53:50 +00001152static void ShrinkGlobalToBoolean(GlobalVariable *GV, Constant *OtherVal) {
1153 // Create the new global, initializing it to false.
Reid Spencer542964f2007-01-11 18:21:29 +00001154 GlobalVariable *NewGV = new GlobalVariable(Type::Int1Ty, false,
Zhou Sheng75b871f2007-01-11 12:24:14 +00001155 GlobalValue::InternalLinkage, ConstantInt::getFalse(),
Lauro Ramos Venancio749e4662007-04-12 18:32:50 +00001156 GV->getName()+".b",
1157 (Module *)NULL,
1158 GV->isThreadLocal());
Chris Lattner40e4cec2004-12-12 05:53:50 +00001159 GV->getParent()->getGlobalList().insert(GV, NewGV);
1160
1161 Constant *InitVal = GV->getInitializer();
Reid Spencer542964f2007-01-11 18:21:29 +00001162 assert(InitVal->getType() != Type::Int1Ty && "No reason to shrink to bool!");
Chris Lattner40e4cec2004-12-12 05:53:50 +00001163
1164 // If initialized to zero and storing one into the global, we can use a cast
1165 // instead of a select to synthesize the desired value.
1166 bool IsOneZero = false;
1167 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal))
Reid Spencer2e54a152007-03-02 00:28:52 +00001168 IsOneZero = InitVal->isNullValue() && CI->isOne();
Chris Lattner40e4cec2004-12-12 05:53:50 +00001169
1170 while (!GV->use_empty()) {
1171 Instruction *UI = cast<Instruction>(GV->use_back());
1172 if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
1173 // Change the store into a boolean store.
1174 bool StoringOther = SI->getOperand(0) == OtherVal;
1175 // Only do this if we weren't storing a loaded value.
Chris Lattner745196a2004-12-12 19:34:41 +00001176 Value *StoreVal;
Chris Lattner40e4cec2004-12-12 05:53:50 +00001177 if (StoringOther || SI->getOperand(0) == InitVal)
Reid Spencercddc9df2007-01-12 04:24:46 +00001178 StoreVal = ConstantInt::get(Type::Int1Ty, StoringOther);
Chris Lattner745196a2004-12-12 19:34:41 +00001179 else {
1180 // Otherwise, we are storing a previously loaded copy. To do this,
1181 // change the copy from copying the original value to just copying the
1182 // bool.
1183 Instruction *StoredVal = cast<Instruction>(SI->getOperand(0));
1184
1185 // If we're already replaced the input, StoredVal will be a cast or
1186 // select instruction. If not, it will be a load of the original
1187 // global.
1188 if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
1189 assert(LI->getOperand(0) == GV && "Not a copy!");
1190 // Insert a new load, to preserve the saved value.
1191 StoreVal = new LoadInst(NewGV, LI->getName()+".b", LI);
1192 } else {
1193 assert((isa<CastInst>(StoredVal) || isa<SelectInst>(StoredVal)) &&
1194 "This is not a form that we understand!");
1195 StoreVal = StoredVal->getOperand(0);
1196 assert(isa<LoadInst>(StoreVal) && "Not a load of NewGV!");
1197 }
1198 }
1199 new StoreInst(StoreVal, NewGV, SI);
1200 } else if (!UI->use_empty()) {
Chris Lattner40e4cec2004-12-12 05:53:50 +00001201 // Change the load into a load of bool then a select.
1202 LoadInst *LI = cast<LoadInst>(UI);
Chris Lattner8d4c36b2007-02-11 01:08:35 +00001203 LoadInst *NLI = new LoadInst(NewGV, LI->getName()+".b", LI);
Chris Lattner40e4cec2004-12-12 05:53:50 +00001204 Value *NSI;
1205 if (IsOneZero)
Chris Lattner8d4c36b2007-02-11 01:08:35 +00001206 NSI = new ZExtInst(NLI, LI->getType(), "", LI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001207 else
Chris Lattner8d4c36b2007-02-11 01:08:35 +00001208 NSI = new SelectInst(NLI, OtherVal, InitVal, "", LI);
1209 NSI->takeName(LI);
Chris Lattner40e4cec2004-12-12 05:53:50 +00001210 LI->replaceAllUsesWith(NSI);
1211 }
1212 UI->eraseFromParent();
1213 }
1214
1215 GV->eraseFromParent();
1216}
1217
1218
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001219/// ProcessInternalGlobal - Analyze the specified global variable and optimize
1220/// it if possible. If we make a change, return true.
Chris Lattner004e2502004-10-11 05:54:41 +00001221bool GlobalOpt::ProcessInternalGlobal(GlobalVariable *GV,
Chris Lattner531f9e92005-03-15 04:54:21 +00001222 Module::global_iterator &GVI) {
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001223 std::set<PHINode*> PHIUsers;
1224 GlobalStatus GS;
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001225 GV->removeDeadConstantUsers();
1226
1227 if (GV->use_empty()) {
Bill Wendling8f13b5c2006-11-26 10:02:32 +00001228 DOUT << "GLOBAL DEAD: " << *GV;
Chris Lattner8e71c6a2004-10-16 18:09:00 +00001229 GV->eraseFromParent();
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001230 ++NumDeleted;
1231 return true;
1232 }
1233
1234 if (!AnalyzeGlobal(GV, GS, PHIUsers)) {
Chris Lattner80a01ef2006-09-30 19:40:30 +00001235#if 0
Bill Wendlingf3baad32006-12-07 01:30:32 +00001236 cerr << "Global: " << *GV;
1237 cerr << " isLoaded = " << GS.isLoaded << "\n";
1238 cerr << " StoredType = ";
Chris Lattner80a01ef2006-09-30 19:40:30 +00001239 switch (GS.StoredType) {
Bill Wendlingf3baad32006-12-07 01:30:32 +00001240 case GlobalStatus::NotStored: cerr << "NEVER STORED\n"; break;
1241 case GlobalStatus::isInitializerStored: cerr << "INIT STORED\n"; break;
1242 case GlobalStatus::isStoredOnce: cerr << "STORED ONCE\n"; break;
1243 case GlobalStatus::isStored: cerr << "stored\n"; break;
Chris Lattner80a01ef2006-09-30 19:40:30 +00001244 }
1245 if (GS.StoredType == GlobalStatus::isStoredOnce && GS.StoredOnceValue)
Bill Wendlingf3baad32006-12-07 01:30:32 +00001246 cerr << " StoredOnceValue = " << *GS.StoredOnceValue << "\n";
Chris Lattner80a01ef2006-09-30 19:40:30 +00001247 if (GS.AccessingFunction && !GS.HasMultipleAccessingFunctions)
Bill Wendlingf3baad32006-12-07 01:30:32 +00001248 cerr << " AccessingFunction = " << GS.AccessingFunction->getName()
Chris Lattner80a01ef2006-09-30 19:40:30 +00001249 << "\n";
Bill Wendlingf3baad32006-12-07 01:30:32 +00001250 cerr << " HasMultipleAccessingFunctions = "
Chris Lattner80a01ef2006-09-30 19:40:30 +00001251 << GS.HasMultipleAccessingFunctions << "\n";
Bill Wendlingf3baad32006-12-07 01:30:32 +00001252 cerr << " HasNonInstructionUser = " << GS.HasNonInstructionUser<<"\n";
1253 cerr << " isNotSuitableForSRA = " << GS.isNotSuitableForSRA << "\n";
1254 cerr << "\n";
Chris Lattner80a01ef2006-09-30 19:40:30 +00001255#endif
1256
Alkis Evlogimenosc4a44c62005-02-10 18:36:30 +00001257 // If this is a first class global and has only one accessing function
1258 // and this function is main (which we know is not recursive we can make
1259 // this global a local variable) we replace the global with a local alloca
1260 // in this function.
1261 //
1262 // NOTE: It doesn't make sense to promote non first class types since we
1263 // are just replacing static memory to stack memory.
1264 if (!GS.HasMultipleAccessingFunctions &&
Chris Lattner50bdfcb2005-06-15 21:11:48 +00001265 GS.AccessingFunction && !GS.HasNonInstructionUser &&
Alkis Evlogimenosc4a44c62005-02-10 18:36:30 +00001266 GV->getType()->getElementType()->isFirstClassType() &&
1267 GS.AccessingFunction->getName() == "main" &&
1268 GS.AccessingFunction->hasExternalLinkage()) {
Bill Wendling8f13b5c2006-11-26 10:02:32 +00001269 DOUT << "LOCALIZING GLOBAL: " << *GV;
Alkis Evlogimenosc4a44c62005-02-10 18:36:30 +00001270 Instruction* FirstI = GS.AccessingFunction->getEntryBlock().begin();
1271 const Type* ElemTy = GV->getType()->getElementType();
Nate Begeman848622f2005-11-05 09:21:28 +00001272 // FIXME: Pass Global's alignment when globals have alignment
Alkis Evlogimenosc4a44c62005-02-10 18:36:30 +00001273 AllocaInst* Alloca = new AllocaInst(ElemTy, NULL, GV->getName(), FirstI);
1274 if (!isa<UndefValue>(GV->getInitializer()))
1275 new StoreInst(GV->getInitializer(), Alloca, FirstI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001276
Alkis Evlogimenosc4a44c62005-02-10 18:36:30 +00001277 GV->replaceAllUsesWith(Alloca);
1278 GV->eraseFromParent();
1279 ++NumLocalized;
1280 return true;
1281 }
Chris Lattner80a01ef2006-09-30 19:40:30 +00001282
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001283 // If the global is never loaded (but may be stored to), it is dead.
1284 // Delete it now.
1285 if (!GS.isLoaded) {
Bill Wendling8f13b5c2006-11-26 10:02:32 +00001286 DOUT << "GLOBAL NEVER LOADED: " << *GV;
Chris Lattnerf369b382004-10-09 03:32:52 +00001287
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001288 // Delete any stores we can find to the global. We may not be able to
1289 // make it completely dead though.
Chris Lattnercb9f1522004-10-10 16:43:46 +00001290 bool Changed = CleanupConstantGlobalUsers(GV, GV->getInitializer());
Chris Lattnerf369b382004-10-09 03:32:52 +00001291
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001292 // If the global is dead now, delete it.
1293 if (GV->use_empty()) {
Chris Lattner8e71c6a2004-10-16 18:09:00 +00001294 GV->eraseFromParent();
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001295 ++NumDeleted;
Chris Lattnerf369b382004-10-09 03:32:52 +00001296 Changed = true;
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001297 }
Chris Lattnerf369b382004-10-09 03:32:52 +00001298 return Changed;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001299
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001300 } else if (GS.StoredType <= GlobalStatus::isInitializerStored) {
Bill Wendling8f13b5c2006-11-26 10:02:32 +00001301 DOUT << "MARKING CONSTANT: " << *GV;
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001302 GV->setConstant(true);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001303
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001304 // Clean up any obviously simplifiable users now.
1305 CleanupConstantGlobalUsers(GV, GV->getInitializer());
Misha Brukmanb1c93172005-04-21 23:48:37 +00001306
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001307 // If the global is dead now, just nuke it.
1308 if (GV->use_empty()) {
Bill Wendling8f13b5c2006-11-26 10:02:32 +00001309 DOUT << " *** Marking constant allowed us to simplify "
1310 << "all users and delete global!\n";
Chris Lattner8e71c6a2004-10-16 18:09:00 +00001311 GV->eraseFromParent();
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001312 ++NumDeleted;
1313 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001314
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001315 ++NumMarked;
1316 return true;
1317 } else if (!GS.isNotSuitableForSRA &&
1318 !GV->getInitializer()->getType()->isFirstClassType()) {
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001319 if (GlobalVariable *FirstNewGV = SRAGlobal(GV)) {
1320 GVI = FirstNewGV; // Don't skip the newly produced globals!
1321 return true;
1322 }
Chris Lattner09a52722004-10-09 21:48:45 +00001323 } else if (GS.StoredType == GlobalStatus::isStoredOnce) {
Chris Lattner40e4cec2004-12-12 05:53:50 +00001324 // If the initial value for the global was an undef value, and if only
1325 // one other value was stored into it, we can just change the
1326 // initializer to be an undef value, then delete all stores to the
1327 // global. This allows us to mark it constant.
1328 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
1329 if (isa<UndefValue>(GV->getInitializer())) {
1330 // Change the initial value here.
1331 GV->setInitializer(SOVConstant);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001332
Chris Lattner40e4cec2004-12-12 05:53:50 +00001333 // Clean up any obviously simplifiable users now.
1334 CleanupConstantGlobalUsers(GV, GV->getInitializer());
Misha Brukmanb1c93172005-04-21 23:48:37 +00001335
Chris Lattner40e4cec2004-12-12 05:53:50 +00001336 if (GV->use_empty()) {
Bill Wendling8f13b5c2006-11-26 10:02:32 +00001337 DOUT << " *** Substituting initializer allowed us to "
1338 << "simplify all users and delete global!\n";
Chris Lattner40e4cec2004-12-12 05:53:50 +00001339 GV->eraseFromParent();
1340 ++NumDeleted;
1341 } else {
1342 GVI = GV;
1343 }
1344 ++NumSubstitute;
1345 return true;
Chris Lattner8e71c6a2004-10-16 18:09:00 +00001346 }
Chris Lattner8e71c6a2004-10-16 18:09:00 +00001347
Chris Lattner09a52722004-10-09 21:48:45 +00001348 // Try to optimize globals based on the knowledge that only one value
1349 // (besides its initializer) is ever stored to the global.
Chris Lattner004e2502004-10-11 05:54:41 +00001350 if (OptimizeOnceStoredGlobal(GV, GS.StoredOnceValue, GVI,
1351 getAnalysis<TargetData>()))
Chris Lattner09a52722004-10-09 21:48:45 +00001352 return true;
Chris Lattner40e4cec2004-12-12 05:53:50 +00001353
1354 // Otherwise, if the global was not a boolean, we can shrink it to be a
1355 // boolean.
1356 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
Reid Spencer542964f2007-01-11 18:21:29 +00001357 if (GV->getType()->getElementType() != Type::Int1Ty &&
Chris Lattner5a0bd612006-11-01 18:03:33 +00001358 !GV->getType()->getElementType()->isFloatingPoint() &&
Reid Spencerd84d35b2007-02-15 02:26:10 +00001359 !isa<VectorType>(GV->getType()->getElementType()) &&
Chris Lattner1a9a7602007-04-05 21:09:42 +00001360 !GS.HasPHIUser && !GS.isNotSuitableForSRA) {
Bill Wendling8f13b5c2006-11-26 10:02:32 +00001361 DOUT << " *** SHRINKING TO BOOL: " << *GV;
Chris Lattner40e4cec2004-12-12 05:53:50 +00001362 ShrinkGlobalToBoolean(GV, SOVConstant);
1363 ++NumShrunkToBool;
1364 return true;
1365 }
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001366 }
1367 }
1368 return false;
1369}
1370
Chris Lattnera4c80222005-05-08 22:18:06 +00001371/// OnlyCalledDirectly - Return true if the specified function is only called
1372/// directly. In other words, its address is never taken.
1373static bool OnlyCalledDirectly(Function *F) {
1374 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
1375 Instruction *User = dyn_cast<Instruction>(*UI);
1376 if (!User) return false;
1377 if (!isa<CallInst>(User) && !isa<InvokeInst>(User)) return false;
1378
1379 // See if the function address is passed as an argument.
1380 for (unsigned i = 1, e = User->getNumOperands(); i != e; ++i)
1381 if (User->getOperand(i) == F) return false;
1382 }
1383 return true;
1384}
1385
1386/// ChangeCalleesToFastCall - Walk all of the direct calls of the specified
1387/// function, changing them to FastCC.
1388static void ChangeCalleesToFastCall(Function *F) {
1389 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
1390 Instruction *User = cast<Instruction>(*UI);
1391 if (CallInst *CI = dyn_cast<CallInst>(User))
1392 CI->setCallingConv(CallingConv::Fast);
1393 else
1394 cast<InvokeInst>(User)->setCallingConv(CallingConv::Fast);
1395 }
1396}
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001397
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001398bool GlobalOpt::OptimizeFunctions(Module &M) {
1399 bool Changed = false;
1400 // Optimize functions.
1401 for (Module::iterator FI = M.begin(), E = M.end(); FI != E; ) {
1402 Function *F = FI++;
1403 F->removeDeadConstantUsers();
1404 if (F->use_empty() && (F->hasInternalLinkage() ||
1405 F->hasLinkOnceLinkage())) {
1406 M.getFunctionList().erase(F);
1407 Changed = true;
1408 ++NumFnDeleted;
1409 } else if (F->hasInternalLinkage() &&
1410 F->getCallingConv() == CallingConv::C && !F->isVarArg() &&
1411 OnlyCalledDirectly(F)) {
1412 // If this function has C calling conventions, is not a varargs
1413 // function, and is only called directly, promote it to use the Fast
1414 // calling convention.
1415 F->setCallingConv(CallingConv::Fast);
1416 ChangeCalleesToFastCall(F);
1417 ++NumFastCallFns;
1418 Changed = true;
1419 }
1420 }
1421 return Changed;
1422}
1423
1424bool GlobalOpt::OptimizeGlobalVars(Module &M) {
1425 bool Changed = false;
1426 for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
1427 GVI != E; ) {
1428 GlobalVariable *GV = GVI++;
1429 if (!GV->isConstant() && GV->hasInternalLinkage() &&
1430 GV->hasInitializer())
1431 Changed |= ProcessInternalGlobal(GV, GVI);
1432 }
1433 return Changed;
1434}
1435
1436/// FindGlobalCtors - Find the llvm.globalctors list, verifying that all
1437/// initializers have an init priority of 65535.
1438GlobalVariable *GlobalOpt::FindGlobalCtors(Module &M) {
Alkis Evlogimenoscb67b652005-10-25 11:18:06 +00001439 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1440 I != E; ++I)
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001441 if (I->getName() == "llvm.global_ctors") {
1442 // Found it, verify it's an array of { int, void()* }.
1443 const ArrayType *ATy =dyn_cast<ArrayType>(I->getType()->getElementType());
1444 if (!ATy) return 0;
1445 const StructType *STy = dyn_cast<StructType>(ATy->getElementType());
1446 if (!STy || STy->getNumElements() != 2 ||
Reid Spencerc635f472006-12-31 05:48:39 +00001447 STy->getElementType(0) != Type::Int32Ty) return 0;
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001448 const PointerType *PFTy = dyn_cast<PointerType>(STy->getElementType(1));
1449 if (!PFTy) return 0;
1450 const FunctionType *FTy = dyn_cast<FunctionType>(PFTy->getElementType());
1451 if (!FTy || FTy->getReturnType() != Type::VoidTy || FTy->isVarArg() ||
1452 FTy->getNumParams() != 0)
1453 return 0;
1454
1455 // Verify that the initializer is simple enough for us to handle.
1456 if (!I->hasInitializer()) return 0;
1457 ConstantArray *CA = dyn_cast<ConstantArray>(I->getInitializer());
1458 if (!CA) return 0;
1459 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1460 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(CA->getOperand(i))) {
Chris Lattner838bdc12005-09-26 02:19:27 +00001461 if (isa<ConstantPointerNull>(CS->getOperand(1)))
1462 continue;
1463
1464 // Must have a function or null ptr.
1465 if (!isa<Function>(CS->getOperand(1)))
1466 return 0;
1467
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001468 // Init priority must be standard.
1469 ConstantInt *CI = dyn_cast<ConstantInt>(CS->getOperand(0));
Reid Spencere0fc4df2006-10-20 07:07:24 +00001470 if (!CI || CI->getZExtValue() != 65535)
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001471 return 0;
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001472 } else {
1473 return 0;
1474 }
1475
1476 return I;
1477 }
1478 return 0;
1479}
1480
Chris Lattner696beef2005-09-26 02:31:18 +00001481/// ParseGlobalCtors - Given a llvm.global_ctors list that we can understand,
1482/// return a list of the functions and null terminator as a vector.
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001483static std::vector<Function*> ParseGlobalCtors(GlobalVariable *GV) {
1484 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
1485 std::vector<Function*> Result;
1486 Result.reserve(CA->getNumOperands());
1487 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i) {
1488 ConstantStruct *CS = cast<ConstantStruct>(CA->getOperand(i));
1489 Result.push_back(dyn_cast<Function>(CS->getOperand(1)));
1490 }
1491 return Result;
1492}
1493
Chris Lattner696beef2005-09-26 02:31:18 +00001494/// InstallGlobalCtors - Given a specified llvm.global_ctors list, install the
1495/// specified array, returning the new global to use.
1496static GlobalVariable *InstallGlobalCtors(GlobalVariable *GCL,
1497 const std::vector<Function*> &Ctors) {
1498 // If we made a change, reassemble the initializer list.
1499 std::vector<Constant*> CSVals;
Reid Spencerc635f472006-12-31 05:48:39 +00001500 CSVals.push_back(ConstantInt::get(Type::Int32Ty, 65535));
Chris Lattner696beef2005-09-26 02:31:18 +00001501 CSVals.push_back(0);
1502
1503 // Create the new init list.
1504 std::vector<Constant*> CAList;
1505 for (unsigned i = 0, e = Ctors.size(); i != e; ++i) {
Chris Lattner99e23fa2005-09-26 04:44:35 +00001506 if (Ctors[i]) {
Chris Lattner696beef2005-09-26 02:31:18 +00001507 CSVals[1] = Ctors[i];
Chris Lattner99e23fa2005-09-26 04:44:35 +00001508 } else {
Chris Lattner696beef2005-09-26 02:31:18 +00001509 const Type *FTy = FunctionType::get(Type::VoidTy,
1510 std::vector<const Type*>(), false);
1511 const PointerType *PFTy = PointerType::get(FTy);
1512 CSVals[1] = Constant::getNullValue(PFTy);
Reid Spencerc635f472006-12-31 05:48:39 +00001513 CSVals[0] = ConstantInt::get(Type::Int32Ty, 2147483647);
Chris Lattner696beef2005-09-26 02:31:18 +00001514 }
1515 CAList.push_back(ConstantStruct::get(CSVals));
1516 }
1517
1518 // Create the array initializer.
1519 const Type *StructTy =
1520 cast<ArrayType>(GCL->getType()->getElementType())->getElementType();
1521 Constant *CA = ConstantArray::get(ArrayType::get(StructTy, CAList.size()),
1522 CAList);
1523
1524 // If we didn't change the number of elements, don't create a new GV.
1525 if (CA->getType() == GCL->getInitializer()->getType()) {
1526 GCL->setInitializer(CA);
1527 return GCL;
1528 }
1529
1530 // Create the new global and insert it next to the existing list.
1531 GlobalVariable *NGV = new GlobalVariable(CA->getType(), GCL->isConstant(),
Lauro Ramos Venancio749e4662007-04-12 18:32:50 +00001532 GCL->getLinkage(), CA, "",
1533 (Module *)NULL,
1534 GCL->isThreadLocal());
Chris Lattner696beef2005-09-26 02:31:18 +00001535 GCL->getParent()->getGlobalList().insert(GCL, NGV);
Chris Lattner8d4c36b2007-02-11 01:08:35 +00001536 NGV->takeName(GCL);
Chris Lattner696beef2005-09-26 02:31:18 +00001537
1538 // Nuke the old list, replacing any uses with the new one.
1539 if (!GCL->use_empty()) {
1540 Constant *V = NGV;
1541 if (V->getType() != GCL->getType())
Reid Spencerbb65ebf2006-12-12 23:36:14 +00001542 V = ConstantExpr::getBitCast(V, GCL->getType());
Chris Lattner696beef2005-09-26 02:31:18 +00001543 GCL->replaceAllUsesWith(V);
1544 }
1545 GCL->eraseFromParent();
1546
1547 if (Ctors.size())
1548 return NGV;
1549 else
1550 return 0;
1551}
Chris Lattner99e23fa2005-09-26 04:44:35 +00001552
1553
1554static Constant *getVal(std::map<Value*, Constant*> &ComputedValues,
1555 Value *V) {
1556 if (Constant *CV = dyn_cast<Constant>(V)) return CV;
1557 Constant *R = ComputedValues[V];
1558 assert(R && "Reference to an uncomputed value!");
1559 return R;
1560}
1561
1562/// isSimpleEnoughPointerToCommit - Return true if this constant is simple
1563/// enough for us to understand. In particular, if it is a cast of something,
1564/// we punt. We basically just support direct accesses to globals and GEP's of
1565/// globals. This should be kept up to date with CommitValueTo.
1566static bool isSimpleEnoughPointerToCommit(Constant *C) {
Chris Lattner29b27802005-09-27 04:50:03 +00001567 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
1568 if (!GV->hasExternalLinkage() && !GV->hasInternalLinkage())
Anton Korobeynikovd61d39e2006-09-14 18:23:27 +00001569 return false; // do not allow weak/linkonce/dllimport/dllexport linkage.
Reid Spencer5301e7c2007-01-30 20:08:39 +00001570 return !GV->isDeclaration(); // reject external globals.
Chris Lattner29b27802005-09-27 04:50:03 +00001571 }
Chris Lattner46af55e2005-09-26 06:52:44 +00001572 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
1573 // Handle a constantexpr gep.
1574 if (CE->getOpcode() == Instruction::GetElementPtr &&
1575 isa<GlobalVariable>(CE->getOperand(0))) {
1576 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
Chris Lattner29b27802005-09-27 04:50:03 +00001577 if (!GV->hasExternalLinkage() && !GV->hasInternalLinkage())
Anton Korobeynikovd61d39e2006-09-14 18:23:27 +00001578 return false; // do not allow weak/linkonce/dllimport/dllexport linkage.
Chris Lattner46af55e2005-09-26 06:52:44 +00001579 return GV->hasInitializer() &&
1580 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
1581 }
Chris Lattner99e23fa2005-09-26 04:44:35 +00001582 return false;
1583}
1584
Chris Lattner46af55e2005-09-26 06:52:44 +00001585/// EvaluateStoreInto - Evaluate a piece of a constantexpr store into a global
1586/// initializer. This returns 'Init' modified to reflect 'Val' stored into it.
1587/// At this point, the GEP operands of Addr [0, OpNo) have been stepped into.
1588static Constant *EvaluateStoreInto(Constant *Init, Constant *Val,
1589 ConstantExpr *Addr, unsigned OpNo) {
1590 // Base case of the recursion.
1591 if (OpNo == Addr->getNumOperands()) {
1592 assert(Val->getType() == Init->getType() && "Type mismatch!");
1593 return Val;
1594 }
1595
1596 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
1597 std::vector<Constant*> Elts;
1598
1599 // Break up the constant into its elements.
1600 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
1601 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i)
1602 Elts.push_back(CS->getOperand(i));
1603 } else if (isa<ConstantAggregateZero>(Init)) {
1604 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
1605 Elts.push_back(Constant::getNullValue(STy->getElementType(i)));
1606 } else if (isa<UndefValue>(Init)) {
1607 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
1608 Elts.push_back(UndefValue::get(STy->getElementType(i)));
1609 } else {
1610 assert(0 && "This code is out of sync with "
1611 " ConstantFoldLoadThroughGEPConstantExpr");
1612 }
1613
1614 // Replace the element that we are supposed to.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001615 ConstantInt *CU = cast<ConstantInt>(Addr->getOperand(OpNo));
1616 unsigned Idx = CU->getZExtValue();
1617 assert(Idx < STy->getNumElements() && "Struct index out of range!");
Chris Lattner46af55e2005-09-26 06:52:44 +00001618 Elts[Idx] = EvaluateStoreInto(Elts[Idx], Val, Addr, OpNo+1);
1619
1620 // Return the modified struct.
1621 return ConstantStruct::get(Elts);
1622 } else {
1623 ConstantInt *CI = cast<ConstantInt>(Addr->getOperand(OpNo));
1624 const ArrayType *ATy = cast<ArrayType>(Init->getType());
1625
1626 // Break up the array into elements.
1627 std::vector<Constant*> Elts;
1628 if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
1629 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1630 Elts.push_back(CA->getOperand(i));
1631 } else if (isa<ConstantAggregateZero>(Init)) {
1632 Constant *Elt = Constant::getNullValue(ATy->getElementType());
1633 Elts.assign(ATy->getNumElements(), Elt);
1634 } else if (isa<UndefValue>(Init)) {
1635 Constant *Elt = UndefValue::get(ATy->getElementType());
1636 Elts.assign(ATy->getNumElements(), Elt);
1637 } else {
1638 assert(0 && "This code is out of sync with "
1639 " ConstantFoldLoadThroughGEPConstantExpr");
1640 }
1641
Reid Spencere0fc4df2006-10-20 07:07:24 +00001642 assert(CI->getZExtValue() < ATy->getNumElements());
1643 Elts[CI->getZExtValue()] =
1644 EvaluateStoreInto(Elts[CI->getZExtValue()], Val, Addr, OpNo+1);
Chris Lattner46af55e2005-09-26 06:52:44 +00001645 return ConstantArray::get(ATy, Elts);
1646 }
1647}
1648
Chris Lattner99e23fa2005-09-26 04:44:35 +00001649/// CommitValueTo - We have decided that Addr (which satisfies the predicate
1650/// isSimpleEnoughPointerToCommit) should get Val as its value. Make it happen.
1651static void CommitValueTo(Constant *Val, Constant *Addr) {
Chris Lattner46af55e2005-09-26 06:52:44 +00001652 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Addr)) {
1653 assert(GV->hasInitializer());
1654 GV->setInitializer(Val);
1655 return;
1656 }
1657
1658 ConstantExpr *CE = cast<ConstantExpr>(Addr);
1659 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
1660
1661 Constant *Init = GV->getInitializer();
1662 Init = EvaluateStoreInto(Init, Val, CE, 2);
1663 GV->setInitializer(Init);
Chris Lattner99e23fa2005-09-26 04:44:35 +00001664}
1665
Chris Lattnerb0096632005-09-26 05:16:34 +00001666/// ComputeLoadResult - Return the value that would be computed by a load from
1667/// P after the stores reflected by 'memory' have been performed. If we can't
1668/// decide, return null.
Chris Lattner4b05c322005-09-26 05:15:37 +00001669static Constant *ComputeLoadResult(Constant *P,
1670 const std::map<Constant*, Constant*> &Memory) {
1671 // If this memory location has been recently stored, use the stored value: it
1672 // is the most up-to-date.
1673 std::map<Constant*, Constant*>::const_iterator I = Memory.find(P);
1674 if (I != Memory.end()) return I->second;
1675
1676 // Access it.
1677 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(P)) {
1678 if (GV->hasInitializer())
1679 return GV->getInitializer();
1680 return 0;
Chris Lattner4b05c322005-09-26 05:15:37 +00001681 }
Chris Lattner46af55e2005-09-26 06:52:44 +00001682
1683 // Handle a constantexpr getelementptr.
1684 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(P))
1685 if (CE->getOpcode() == Instruction::GetElementPtr &&
1686 isa<GlobalVariable>(CE->getOperand(0))) {
1687 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
1688 if (GV->hasInitializer())
1689 return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
1690 }
1691
1692 return 0; // don't know how to evaluate.
Chris Lattner4b05c322005-09-26 05:15:37 +00001693}
1694
Chris Lattnerda1889b2005-09-27 04:27:01 +00001695/// EvaluateFunction - Evaluate a call to function F, returning true if
1696/// successful, false if we can't evaluate it. ActualArgs contains the formal
1697/// arguments for the function.
Chris Lattner65a3a092005-09-27 04:45:34 +00001698static bool EvaluateFunction(Function *F, Constant *&RetVal,
Chris Lattnerda1889b2005-09-27 04:27:01 +00001699 const std::vector<Constant*> &ActualArgs,
1700 std::vector<Function*> &CallStack,
1701 std::map<Constant*, Constant*> &MutatedMemory,
1702 std::vector<GlobalVariable*> &AllocaTmps) {
Chris Lattner65a3a092005-09-27 04:45:34 +00001703 // Check to see if this function is already executing (recursion). If so,
1704 // bail out. TODO: we might want to accept limited recursion.
1705 if (std::find(CallStack.begin(), CallStack.end(), F) != CallStack.end())
1706 return false;
1707
1708 CallStack.push_back(F);
1709
Chris Lattner99e23fa2005-09-26 04:44:35 +00001710 /// Values - As we compute SSA register values, we store their contents here.
1711 std::map<Value*, Constant*> Values;
Chris Lattner65a3a092005-09-27 04:45:34 +00001712
1713 // Initialize arguments to the incoming values specified.
1714 unsigned ArgNo = 0;
1715 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); AI != E;
1716 ++AI, ++ArgNo)
1717 Values[AI] = ActualArgs[ArgNo];
Chris Lattnerda1889b2005-09-27 04:27:01 +00001718
Chris Lattner3e9ea5f2005-09-26 04:57:38 +00001719 /// ExecutedBlocks - We only handle non-looping, non-recursive code. As such,
1720 /// we can only evaluate any one basic block at most once. This set keeps
1721 /// track of what we have executed so we can detect recursive cases etc.
1722 std::set<BasicBlock*> ExecutedBlocks;
Chris Lattner6bf2cd52005-09-26 17:07:09 +00001723
Chris Lattner99e23fa2005-09-26 04:44:35 +00001724 // CurInst - The current instruction we're evaluating.
1725 BasicBlock::iterator CurInst = F->begin()->begin();
1726
1727 // This is the main evaluation loop.
1728 while (1) {
1729 Constant *InstResult = 0;
1730
1731 if (StoreInst *SI = dyn_cast<StoreInst>(CurInst)) {
Chris Lattner65a3a092005-09-27 04:45:34 +00001732 if (SI->isVolatile()) return false; // no volatile accesses.
Chris Lattner99e23fa2005-09-26 04:44:35 +00001733 Constant *Ptr = getVal(Values, SI->getOperand(1));
1734 if (!isSimpleEnoughPointerToCommit(Ptr))
1735 // If this is too complex for us to commit, reject it.
Chris Lattner65a3a092005-09-27 04:45:34 +00001736 return false;
Chris Lattner99e23fa2005-09-26 04:44:35 +00001737 Constant *Val = getVal(Values, SI->getOperand(0));
1738 MutatedMemory[Ptr] = Val;
1739 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CurInst)) {
1740 InstResult = ConstantExpr::get(BO->getOpcode(),
1741 getVal(Values, BO->getOperand(0)),
1742 getVal(Values, BO->getOperand(1)));
Reid Spencer266e42b2006-12-23 06:05:41 +00001743 } else if (CmpInst *CI = dyn_cast<CmpInst>(CurInst)) {
1744 InstResult = ConstantExpr::getCompare(CI->getPredicate(),
1745 getVal(Values, CI->getOperand(0)),
1746 getVal(Values, CI->getOperand(1)));
Chris Lattner99e23fa2005-09-26 04:44:35 +00001747 } else if (CastInst *CI = dyn_cast<CastInst>(CurInst)) {
Chris Lattner0390b9e2006-11-30 17:26:08 +00001748 InstResult = ConstantExpr::getCast(CI->getOpcode(),
1749 getVal(Values, CI->getOperand(0)),
Chris Lattner99e23fa2005-09-26 04:44:35 +00001750 CI->getType());
1751 } else if (SelectInst *SI = dyn_cast<SelectInst>(CurInst)) {
1752 InstResult = ConstantExpr::getSelect(getVal(Values, SI->getOperand(0)),
1753 getVal(Values, SI->getOperand(1)),
1754 getVal(Values, SI->getOperand(2)));
Chris Lattner4b05c322005-09-26 05:15:37 +00001755 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurInst)) {
1756 Constant *P = getVal(Values, GEP->getOperand(0));
Chris Lattnerf96f4a82007-01-31 04:40:53 +00001757 SmallVector<Constant*, 8> GEPOps;
Chris Lattner4b05c322005-09-26 05:15:37 +00001758 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
1759 GEPOps.push_back(getVal(Values, GEP->getOperand(i)));
Chris Lattnerf96f4a82007-01-31 04:40:53 +00001760 InstResult = ConstantExpr::getGetElementPtr(P, &GEPOps[0], GEPOps.size());
Chris Lattner4b05c322005-09-26 05:15:37 +00001761 } else if (LoadInst *LI = dyn_cast<LoadInst>(CurInst)) {
Chris Lattner65a3a092005-09-27 04:45:34 +00001762 if (LI->isVolatile()) return false; // no volatile accesses.
Chris Lattner4b05c322005-09-26 05:15:37 +00001763 InstResult = ComputeLoadResult(getVal(Values, LI->getOperand(0)),
1764 MutatedMemory);
Chris Lattner65a3a092005-09-27 04:45:34 +00001765 if (InstResult == 0) return false; // Could not evaluate load.
Chris Lattner6bf2cd52005-09-26 17:07:09 +00001766 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(CurInst)) {
Chris Lattner65a3a092005-09-27 04:45:34 +00001767 if (AI->isArrayAllocation()) return false; // Cannot handle array allocs.
Chris Lattner6bf2cd52005-09-26 17:07:09 +00001768 const Type *Ty = AI->getType()->getElementType();
1769 AllocaTmps.push_back(new GlobalVariable(Ty, false,
1770 GlobalValue::InternalLinkage,
1771 UndefValue::get(Ty),
1772 AI->getName()));
Chris Lattner65a3a092005-09-27 04:45:34 +00001773 InstResult = AllocaTmps.back();
1774 } else if (CallInst *CI = dyn_cast<CallInst>(CurInst)) {
Chris Lattnerfd2e13b2006-07-07 21:37:01 +00001775 // Cannot handle inline asm.
1776 if (isa<InlineAsm>(CI->getOperand(0))) return false;
1777
Chris Lattner65a3a092005-09-27 04:45:34 +00001778 // Resolve function pointers.
1779 Function *Callee = dyn_cast<Function>(getVal(Values, CI->getOperand(0)));
1780 if (!Callee) return false; // Cannot resolve.
Chris Lattner3d27e7f2005-09-27 05:02:43 +00001781
Chris Lattner65a3a092005-09-27 04:45:34 +00001782 std::vector<Constant*> Formals;
1783 for (unsigned i = 1, e = CI->getNumOperands(); i != e; ++i)
1784 Formals.push_back(getVal(Values, CI->getOperand(i)));
Chris Lattner65a3a092005-09-27 04:45:34 +00001785
Reid Spencer5301e7c2007-01-30 20:08:39 +00001786 if (Callee->isDeclaration()) {
Chris Lattner3d27e7f2005-09-27 05:02:43 +00001787 // If this is a function we can constant fold, do it.
Chris Lattner6fc4b462007-01-30 23:14:52 +00001788 if (Constant *C = ConstantFoldCall(Callee, &Formals[0],
1789 Formals.size())) {
Chris Lattner3d27e7f2005-09-27 05:02:43 +00001790 InstResult = C;
1791 } else {
1792 return false;
1793 }
1794 } else {
1795 if (Callee->getFunctionType()->isVarArg())
1796 return false;
1797
1798 Constant *RetVal;
1799
1800 // Execute the call, if successful, use the return value.
1801 if (!EvaluateFunction(Callee, RetVal, Formals, CallStack,
1802 MutatedMemory, AllocaTmps))
1803 return false;
1804 InstResult = RetVal;
1805 }
Reid Spencerde46e482006-11-02 20:25:50 +00001806 } else if (isa<TerminatorInst>(CurInst)) {
Chris Lattner3e9ea5f2005-09-26 04:57:38 +00001807 BasicBlock *NewBB = 0;
1808 if (BranchInst *BI = dyn_cast<BranchInst>(CurInst)) {
1809 if (BI->isUnconditional()) {
1810 NewBB = BI->getSuccessor(0);
1811 } else {
Zhou Sheng75b871f2007-01-11 12:24:14 +00001812 ConstantInt *Cond =
1813 dyn_cast<ConstantInt>(getVal(Values, BI->getCondition()));
Chris Lattner15649082007-01-12 18:30:11 +00001814 if (!Cond) return false; // Cannot determine.
Zhou Sheng75b871f2007-01-11 12:24:14 +00001815
Reid Spencercddc9df2007-01-12 04:24:46 +00001816 NewBB = BI->getSuccessor(!Cond->getZExtValue());
Chris Lattner3e9ea5f2005-09-26 04:57:38 +00001817 }
1818 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(CurInst)) {
1819 ConstantInt *Val =
1820 dyn_cast<ConstantInt>(getVal(Values, SI->getCondition()));
Chris Lattner65a3a092005-09-27 04:45:34 +00001821 if (!Val) return false; // Cannot determine.
Chris Lattner3e9ea5f2005-09-26 04:57:38 +00001822 NewBB = SI->getSuccessor(SI->findCaseValue(Val));
1823 } else if (ReturnInst *RI = dyn_cast<ReturnInst>(CurInst)) {
Chris Lattner65a3a092005-09-27 04:45:34 +00001824 if (RI->getNumOperands())
1825 RetVal = getVal(Values, RI->getOperand(0));
1826
1827 CallStack.pop_back(); // return from fn.
Chris Lattnerda1889b2005-09-27 04:27:01 +00001828 return true; // We succeeded at evaluating this ctor!
Chris Lattner3e9ea5f2005-09-26 04:57:38 +00001829 } else {
Chris Lattner65a3a092005-09-27 04:45:34 +00001830 // invoke, unwind, unreachable.
1831 return false; // Cannot handle this terminator.
Chris Lattner3e9ea5f2005-09-26 04:57:38 +00001832 }
1833
1834 // Okay, we succeeded in evaluating this control flow. See if we have
Chris Lattner65a3a092005-09-27 04:45:34 +00001835 // executed the new block before. If so, we have a looping function,
1836 // which we cannot evaluate in reasonable time.
Chris Lattner3e9ea5f2005-09-26 04:57:38 +00001837 if (!ExecutedBlocks.insert(NewBB).second)
Chris Lattner65a3a092005-09-27 04:45:34 +00001838 return false; // looped!
Chris Lattner3e9ea5f2005-09-26 04:57:38 +00001839
1840 // Okay, we have never been in this block before. Check to see if there
1841 // are any PHI nodes. If so, evaluate them with information about where
1842 // we came from.
1843 BasicBlock *OldBB = CurInst->getParent();
1844 CurInst = NewBB->begin();
1845 PHINode *PN;
1846 for (; (PN = dyn_cast<PHINode>(CurInst)); ++CurInst)
1847 Values[PN] = getVal(Values, PN->getIncomingValueForBlock(OldBB));
1848
1849 // Do NOT increment CurInst. We know that the terminator had no value.
1850 continue;
Chris Lattner99e23fa2005-09-26 04:44:35 +00001851 } else {
Chris Lattner99e23fa2005-09-26 04:44:35 +00001852 // Did not know how to evaluate this!
Chris Lattner65a3a092005-09-27 04:45:34 +00001853 return false;
Chris Lattner99e23fa2005-09-26 04:44:35 +00001854 }
1855
1856 if (!CurInst->use_empty())
1857 Values[CurInst] = InstResult;
1858
1859 // Advance program counter.
1860 ++CurInst;
1861 }
Chris Lattnerda1889b2005-09-27 04:27:01 +00001862}
1863
1864/// EvaluateStaticConstructor - Evaluate static constructors in the function, if
1865/// we can. Return true if we can, false otherwise.
1866static bool EvaluateStaticConstructor(Function *F) {
1867 /// MutatedMemory - For each store we execute, we update this map. Loads
1868 /// check this to get the most up-to-date value. If evaluation is successful,
1869 /// this state is committed to the process.
1870 std::map<Constant*, Constant*> MutatedMemory;
1871
1872 /// AllocaTmps - To 'execute' an alloca, we create a temporary global variable
1873 /// to represent its body. This vector is needed so we can delete the
1874 /// temporary globals when we are done.
1875 std::vector<GlobalVariable*> AllocaTmps;
1876
1877 /// CallStack - This is used to detect recursion. In pathological situations
1878 /// we could hit exponential behavior, but at least there is nothing
1879 /// unbounded.
1880 std::vector<Function*> CallStack;
1881
1882 // Call the function.
Chris Lattner65a3a092005-09-27 04:45:34 +00001883 Constant *RetValDummy;
1884 bool EvalSuccess = EvaluateFunction(F, RetValDummy, std::vector<Constant*>(),
1885 CallStack, MutatedMemory, AllocaTmps);
Chris Lattnerda1889b2005-09-27 04:27:01 +00001886 if (EvalSuccess) {
Chris Lattner6bf2cd52005-09-26 17:07:09 +00001887 // We succeeded at evaluation: commit the result.
Bill Wendling8f13b5c2006-11-26 10:02:32 +00001888 DOUT << "FULLY EVALUATED GLOBAL CTOR FUNCTION '"
1889 << F->getName() << "' to " << MutatedMemory.size()
1890 << " stores.\n";
Chris Lattner6bf2cd52005-09-26 17:07:09 +00001891 for (std::map<Constant*, Constant*>::iterator I = MutatedMemory.begin(),
1892 E = MutatedMemory.end(); I != E; ++I)
1893 CommitValueTo(I->second, I->first);
1894 }
Chris Lattner99e23fa2005-09-26 04:44:35 +00001895
Chris Lattner6bf2cd52005-09-26 17:07:09 +00001896 // At this point, we are done interpreting. If we created any 'alloca'
1897 // temporaries, release them now.
1898 while (!AllocaTmps.empty()) {
1899 GlobalVariable *Tmp = AllocaTmps.back();
1900 AllocaTmps.pop_back();
Chris Lattnerda1889b2005-09-27 04:27:01 +00001901
Chris Lattner6bf2cd52005-09-26 17:07:09 +00001902 // If there are still users of the alloca, the program is doing something
1903 // silly, e.g. storing the address of the alloca somewhere and using it
1904 // later. Since this is undefined, we'll just make it be null.
1905 if (!Tmp->use_empty())
1906 Tmp->replaceAllUsesWith(Constant::getNullValue(Tmp->getType()));
1907 delete Tmp;
1908 }
Chris Lattner46d9ff082005-09-26 07:34:35 +00001909
Chris Lattnerda1889b2005-09-27 04:27:01 +00001910 return EvalSuccess;
Chris Lattner99e23fa2005-09-26 04:44:35 +00001911}
1912
Chris Lattner696beef2005-09-26 02:31:18 +00001913
Chris Lattnerda1889b2005-09-27 04:27:01 +00001914
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001915/// OptimizeGlobalCtorsList - Simplify and evaluation global ctors if possible.
1916/// Return true if anything changed.
1917bool GlobalOpt::OptimizeGlobalCtorsList(GlobalVariable *&GCL) {
1918 std::vector<Function*> Ctors = ParseGlobalCtors(GCL);
1919 bool MadeChange = false;
1920 if (Ctors.empty()) return false;
1921
1922 // Loop over global ctors, optimizing them when we can.
1923 for (unsigned i = 0; i != Ctors.size(); ++i) {
1924 Function *F = Ctors[i];
1925 // Found a null terminator in the middle of the list, prune off the rest of
1926 // the list.
Chris Lattner838bdc12005-09-26 02:19:27 +00001927 if (F == 0) {
1928 if (i != Ctors.size()-1) {
1929 Ctors.resize(i+1);
1930 MadeChange = true;
1931 }
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001932 break;
1933 }
1934
Chris Lattner99e23fa2005-09-26 04:44:35 +00001935 // We cannot simplify external ctor functions.
1936 if (F->empty()) continue;
1937
1938 // If we can evaluate the ctor at compile time, do.
1939 if (EvaluateStaticConstructor(F)) {
1940 Ctors.erase(Ctors.begin()+i);
1941 MadeChange = true;
1942 --i;
1943 ++NumCtorsEvaluated;
1944 continue;
1945 }
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001946 }
1947
1948 if (!MadeChange) return false;
1949
Chris Lattner696beef2005-09-26 02:31:18 +00001950 GCL = InstallGlobalCtors(GCL, Ctors);
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001951 return true;
1952}
1953
1954
Chris Lattner25db5802004-10-07 04:16:33 +00001955bool GlobalOpt::runOnModule(Module &M) {
1956 bool Changed = false;
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001957
1958 // Try to find the llvm.globalctors list.
1959 GlobalVariable *GlobalCtors = FindGlobalCtors(M);
Chris Lattner25db5802004-10-07 04:16:33 +00001960
Chris Lattner25db5802004-10-07 04:16:33 +00001961 bool LocalChange = true;
1962 while (LocalChange) {
1963 LocalChange = false;
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001964
1965 // Delete functions that are trivially dead, ccc -> fastcc
1966 LocalChange |= OptimizeFunctions(M);
1967
1968 // Optimize global_ctors list.
1969 if (GlobalCtors)
1970 LocalChange |= OptimizeGlobalCtorsList(GlobalCtors);
1971
1972 // Optimize non-address-taken globals.
1973 LocalChange |= OptimizeGlobalVars(M);
Chris Lattner25db5802004-10-07 04:16:33 +00001974 Changed |= LocalChange;
1975 }
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001976
1977 // TODO: Move all global ctors functions to the end of the module for code
1978 // layout.
1979
Chris Lattner25db5802004-10-07 04:16:33 +00001980 return Changed;
1981}