blob: 425bcc588bdfbe8a0d1ed0c0128598cc7699aea9 [file] [log] [blame]
Chris Lattner25db5802004-10-07 04:16:33 +00001//===- GlobalOpt.cpp - Optimize Global Variables --------------------------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
Chris Lattner25db5802004-10-07 04:16:33 +00003// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007//
Chris Lattner25db5802004-10-07 04:16:33 +00008//===----------------------------------------------------------------------===//
9//
10// This pass transforms simple global variables that never have their address
11// taken. If obviously true, it marks read/write globals as constant, deletes
12// variables only stored to, etc.
13//
14//===----------------------------------------------------------------------===//
15
16#define DEBUG_TYPE "globalopt"
17#include "llvm/Transforms/IPO.h"
Chris Lattnera4c80222005-05-08 22:18:06 +000018#include "llvm/CallingConv.h"
Chris Lattner25db5802004-10-07 04:16:33 +000019#include "llvm/Constants.h"
20#include "llvm/DerivedTypes.h"
21#include "llvm/Instructions.h"
Chris Lattner7561ca12005-02-27 18:58:52 +000022#include "llvm/IntrinsicInst.h"
Chris Lattner25db5802004-10-07 04:16:33 +000023#include "llvm/Module.h"
24#include "llvm/Pass.h"
25#include "llvm/Support/Debug.h"
Chris Lattner004e2502004-10-11 05:54:41 +000026#include "llvm/Target/TargetData.h"
27#include "llvm/Transforms/Utils/Local.h"
Chris Lattner25db5802004-10-07 04:16:33 +000028#include "llvm/ADT/Statistic.h"
Chris Lattnerabab0712004-10-08 17:32:09 +000029#include "llvm/ADT/StringExtras.h"
Chris Lattner25db5802004-10-07 04:16:33 +000030#include <algorithm>
Chris Lattnerc597b8a2006-01-22 23:32:06 +000031#include <set>
Chris Lattner25db5802004-10-07 04:16:33 +000032using namespace llvm;
33
Chris Lattner1631bcb2006-12-19 22:09:18 +000034STATISTIC(NumMarked , "Number of globals marked constant");
35STATISTIC(NumSRA , "Number of aggregate globals broken into scalars");
36STATISTIC(NumHeapSRA , "Number of heap objects SRA'd");
37STATISTIC(NumSubstitute,"Number of globals with initializers stored into them");
38STATISTIC(NumDeleted , "Number of globals deleted");
39STATISTIC(NumFnDeleted , "Number of functions deleted");
40STATISTIC(NumGlobUses , "Number of global uses devirtualized");
41STATISTIC(NumLocalized , "Number of globals localized");
42STATISTIC(NumShrunkToBool , "Number of global vars shrunk to booleans");
43STATISTIC(NumFastCallFns , "Number of functions converted to fastcc");
44STATISTIC(NumCtorsEvaluated, "Number of static ctors evaluated");
Chris Lattner25db5802004-10-07 04:16:33 +000045
Chris Lattner1631bcb2006-12-19 22:09:18 +000046namespace {
Chris Lattner25db5802004-10-07 04:16:33 +000047 struct GlobalOpt : public ModulePass {
Chris Lattner004e2502004-10-11 05:54:41 +000048 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
49 AU.addRequired<TargetData>();
50 }
Misha Brukmanb1c93172005-04-21 23:48:37 +000051
Chris Lattner25db5802004-10-07 04:16:33 +000052 bool runOnModule(Module &M);
Chris Lattner004e2502004-10-11 05:54:41 +000053
54 private:
Chris Lattner41b6a5a2005-09-26 01:43:45 +000055 GlobalVariable *FindGlobalCtors(Module &M);
56 bool OptimizeFunctions(Module &M);
57 bool OptimizeGlobalVars(Module &M);
58 bool OptimizeGlobalCtorsList(GlobalVariable *&GCL);
Chris Lattnerc2d3d312006-08-27 22:42:52 +000059 bool ProcessInternalGlobal(GlobalVariable *GV,Module::global_iterator &GVI);
Chris Lattner25db5802004-10-07 04:16:33 +000060 };
61
Chris Lattnerc2d3d312006-08-27 22:42:52 +000062 RegisterPass<GlobalOpt> X("globalopt", "Global Variable Optimizer");
Chris Lattner25db5802004-10-07 04:16:33 +000063}
64
65ModulePass *llvm::createGlobalOptimizerPass() { return new GlobalOpt(); }
66
67/// GlobalStatus - As we analyze each global, keep track of some information
68/// about it. If we find out that the address of the global is taken, none of
Chris Lattner617f1a32004-10-07 21:30:30 +000069/// this info will be accurate.
Chris Lattner25db5802004-10-07 04:16:33 +000070struct GlobalStatus {
Chris Lattner617f1a32004-10-07 21:30:30 +000071 /// isLoaded - True if the global is ever loaded. If the global isn't ever
72 /// loaded it can be deleted.
Chris Lattner25db5802004-10-07 04:16:33 +000073 bool isLoaded;
Chris Lattner617f1a32004-10-07 21:30:30 +000074
75 /// StoredType - Keep track of what stores to the global look like.
76 ///
Chris Lattner25db5802004-10-07 04:16:33 +000077 enum StoredType {
Chris Lattner617f1a32004-10-07 21:30:30 +000078 /// NotStored - There is no store to this global. It can thus be marked
79 /// constant.
80 NotStored,
81
82 /// isInitializerStored - This global is stored to, but the only thing
83 /// stored is the constant it was initialized with. This is only tracked
84 /// for scalar globals.
85 isInitializerStored,
86
87 /// isStoredOnce - This global is stored to, but only its initializer and
88 /// one other value is ever stored to it. If this global isStoredOnce, we
89 /// track the value stored to it in StoredOnceValue below. This is only
90 /// tracked for scalar globals.
91 isStoredOnce,
92
93 /// isStored - This global is stored to by multiple values or something else
94 /// that we cannot track.
95 isStored
Chris Lattner25db5802004-10-07 04:16:33 +000096 } StoredType;
Chris Lattner617f1a32004-10-07 21:30:30 +000097
98 /// StoredOnceValue - If only one value (besides the initializer constant) is
99 /// ever stored to this global, keep track of what value it is.
100 Value *StoredOnceValue;
101
Chris Lattner5a0bd612006-11-01 18:03:33 +0000102 /// AccessingFunction/HasMultipleAccessingFunctions - These start out
103 /// null/false. When the first accessing function is noticed, it is recorded.
104 /// When a second different accessing function is noticed,
105 /// HasMultipleAccessingFunctions is set to true.
Alkis Evlogimenosc4a44c62005-02-10 18:36:30 +0000106 Function *AccessingFunction;
107 bool HasMultipleAccessingFunctions;
108
Chris Lattner5a0bd612006-11-01 18:03:33 +0000109 /// HasNonInstructionUser - Set to true if this global has a user that is not
110 /// an instruction (e.g. a constant expr or GV initializer).
Chris Lattner50bdfcb2005-06-15 21:11:48 +0000111 bool HasNonInstructionUser;
112
Chris Lattner5a0bd612006-11-01 18:03:33 +0000113 /// HasPHIUser - Set to true if this global has a user that is a PHI node.
114 bool HasPHIUser;
115
Chris Lattner617f1a32004-10-07 21:30:30 +0000116 /// isNotSuitableForSRA - Keep track of whether any SRA preventing users of
117 /// the global exist. Such users include GEP instruction with variable
118 /// indexes, and non-gep/load/store users like constant expr casts.
Chris Lattner25db5802004-10-07 04:16:33 +0000119 bool isNotSuitableForSRA;
120
Chris Lattner617f1a32004-10-07 21:30:30 +0000121 GlobalStatus() : isLoaded(false), StoredType(NotStored), StoredOnceValue(0),
Alkis Evlogimenosc4a44c62005-02-10 18:36:30 +0000122 AccessingFunction(0), HasMultipleAccessingFunctions(false),
Chris Lattner5a0bd612006-11-01 18:03:33 +0000123 HasNonInstructionUser(false), HasPHIUser(false),
124 isNotSuitableForSRA(false) {}
Chris Lattner25db5802004-10-07 04:16:33 +0000125};
126
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000127
128
129/// ConstantIsDead - Return true if the specified constant is (transitively)
130/// dead. The constant may be used by other constants (e.g. constant arrays and
131/// constant exprs) as long as they are dead, but it cannot be used by anything
132/// else.
133static bool ConstantIsDead(Constant *C) {
134 if (isa<GlobalValue>(C)) return false;
135
136 for (Value::use_iterator UI = C->use_begin(), E = C->use_end(); UI != E; ++UI)
137 if (Constant *CU = dyn_cast<Constant>(*UI)) {
138 if (!ConstantIsDead(CU)) return false;
139 } else
140 return false;
141 return true;
142}
143
144
Chris Lattner25db5802004-10-07 04:16:33 +0000145/// AnalyzeGlobal - Look at all uses of the global and fill in the GlobalStatus
146/// structure. If the global has its address taken, return true to indicate we
147/// can't do anything with it.
148///
149static bool AnalyzeGlobal(Value *V, GlobalStatus &GS,
150 std::set<PHINode*> &PHIUsers) {
151 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
152 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(*UI)) {
Chris Lattner50bdfcb2005-06-15 21:11:48 +0000153 GS.HasNonInstructionUser = true;
154
Chris Lattner25db5802004-10-07 04:16:33 +0000155 if (AnalyzeGlobal(CE, GS, PHIUsers)) return true;
156 if (CE->getOpcode() != Instruction::GetElementPtr)
157 GS.isNotSuitableForSRA = true;
Chris Lattnerabab0712004-10-08 17:32:09 +0000158 else if (!GS.isNotSuitableForSRA) {
159 // Check to see if this ConstantExpr GEP is SRA'able. In particular, we
160 // don't like < 3 operand CE's, and we don't like non-constant integer
161 // indices.
162 if (CE->getNumOperands() < 3 || !CE->getOperand(1)->isNullValue())
163 GS.isNotSuitableForSRA = true;
164 else {
165 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
166 if (!isa<ConstantInt>(CE->getOperand(i))) {
167 GS.isNotSuitableForSRA = true;
168 break;
169 }
170 }
171 }
172
Chris Lattner25db5802004-10-07 04:16:33 +0000173 } else if (Instruction *I = dyn_cast<Instruction>(*UI)) {
Alkis Evlogimenosc4a44c62005-02-10 18:36:30 +0000174 if (!GS.HasMultipleAccessingFunctions) {
175 Function *F = I->getParent()->getParent();
176 if (GS.AccessingFunction == 0)
177 GS.AccessingFunction = F;
178 else if (GS.AccessingFunction != F)
179 GS.HasMultipleAccessingFunctions = true;
180 }
Chris Lattner25db5802004-10-07 04:16:33 +0000181 if (isa<LoadInst>(I)) {
182 GS.isLoaded = true;
183 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Chris Lattner02b6c912004-10-07 06:01:25 +0000184 // Don't allow a store OF the address, only stores TO the address.
185 if (SI->getOperand(0) == V) return true;
186
Chris Lattner617f1a32004-10-07 21:30:30 +0000187 // If this is a direct store to the global (i.e., the global is a scalar
188 // value, not an aggregate), keep more specific information about
189 // stores.
190 if (GS.StoredType != GlobalStatus::isStored)
191 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(SI->getOperand(1))){
Chris Lattner28eeb732004-11-14 20:50:30 +0000192 Value *StoredVal = SI->getOperand(0);
193 if (StoredVal == GV->getInitializer()) {
194 if (GS.StoredType < GlobalStatus::isInitializerStored)
195 GS.StoredType = GlobalStatus::isInitializerStored;
196 } else if (isa<LoadInst>(StoredVal) &&
197 cast<LoadInst>(StoredVal)->getOperand(0) == GV) {
198 // G = G
Chris Lattner617f1a32004-10-07 21:30:30 +0000199 if (GS.StoredType < GlobalStatus::isInitializerStored)
200 GS.StoredType = GlobalStatus::isInitializerStored;
201 } else if (GS.StoredType < GlobalStatus::isStoredOnce) {
202 GS.StoredType = GlobalStatus::isStoredOnce;
Chris Lattner28eeb732004-11-14 20:50:30 +0000203 GS.StoredOnceValue = StoredVal;
Chris Lattner617f1a32004-10-07 21:30:30 +0000204 } else if (GS.StoredType == GlobalStatus::isStoredOnce &&
Chris Lattner28eeb732004-11-14 20:50:30 +0000205 GS.StoredOnceValue == StoredVal) {
Chris Lattner617f1a32004-10-07 21:30:30 +0000206 // noop.
207 } else {
208 GS.StoredType = GlobalStatus::isStored;
209 }
210 } else {
Chris Lattner25db5802004-10-07 04:16:33 +0000211 GS.StoredType = GlobalStatus::isStored;
Chris Lattner617f1a32004-10-07 21:30:30 +0000212 }
Chris Lattner7561ca12005-02-27 18:58:52 +0000213 } else if (isa<GetElementPtrInst>(I)) {
Chris Lattner25db5802004-10-07 04:16:33 +0000214 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Chris Lattner004e2502004-10-11 05:54:41 +0000215
216 // If the first two indices are constants, this can be SRA'd.
217 if (isa<GlobalVariable>(I->getOperand(0))) {
218 if (I->getNumOperands() < 3 || !isa<Constant>(I->getOperand(1)) ||
Misha Brukmanb1c93172005-04-21 23:48:37 +0000219 !cast<Constant>(I->getOperand(1))->isNullValue() ||
Chris Lattner004e2502004-10-11 05:54:41 +0000220 !isa<ConstantInt>(I->getOperand(2)))
221 GS.isNotSuitableForSRA = true;
222 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(I->getOperand(0))){
223 if (CE->getOpcode() != Instruction::GetElementPtr ||
224 CE->getNumOperands() < 3 || I->getNumOperands() < 2 ||
225 !isa<Constant>(I->getOperand(0)) ||
226 !cast<Constant>(I->getOperand(0))->isNullValue())
227 GS.isNotSuitableForSRA = true;
228 } else {
229 GS.isNotSuitableForSRA = true;
230 }
Chris Lattner7561ca12005-02-27 18:58:52 +0000231 } else if (isa<SelectInst>(I)) {
Chris Lattner25db5802004-10-07 04:16:33 +0000232 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
233 GS.isNotSuitableForSRA = true;
234 } else if (PHINode *PN = dyn_cast<PHINode>(I)) {
235 // PHI nodes we can check just like select or GEP instructions, but we
236 // have to be careful about infinite recursion.
237 if (PHIUsers.insert(PN).second) // Not already visited.
238 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
239 GS.isNotSuitableForSRA = true;
Chris Lattner5a0bd612006-11-01 18:03:33 +0000240 GS.HasPHIUser = true;
Chris Lattner25db5802004-10-07 04:16:33 +0000241 } else if (isa<SetCondInst>(I)) {
242 GS.isNotSuitableForSRA = true;
Chris Lattner7561ca12005-02-27 18:58:52 +0000243 } else if (isa<MemCpyInst>(I) || isa<MemMoveInst>(I)) {
244 if (I->getOperand(1) == V)
245 GS.StoredType = GlobalStatus::isStored;
246 if (I->getOperand(2) == V)
247 GS.isLoaded = true;
248 GS.isNotSuitableForSRA = true;
249 } else if (isa<MemSetInst>(I)) {
250 assert(I->getOperand(1) == V && "Memset only takes one pointer!");
251 GS.StoredType = GlobalStatus::isStored;
252 GS.isNotSuitableForSRA = true;
Chris Lattner25db5802004-10-07 04:16:33 +0000253 } else {
254 return true; // Any other non-load instruction might take address!
255 }
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000256 } else if (Constant *C = dyn_cast<Constant>(*UI)) {
Chris Lattner50bdfcb2005-06-15 21:11:48 +0000257 GS.HasNonInstructionUser = true;
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000258 // We might have a dead and dangling constant hanging off of here.
259 if (!ConstantIsDead(C))
260 return true;
Chris Lattner25db5802004-10-07 04:16:33 +0000261 } else {
Chris Lattner50bdfcb2005-06-15 21:11:48 +0000262 GS.HasNonInstructionUser = true;
263 // Otherwise must be some other user.
Chris Lattner25db5802004-10-07 04:16:33 +0000264 return true;
265 }
266
267 return false;
268}
269
Chris Lattnerabab0712004-10-08 17:32:09 +0000270static Constant *getAggregateConstantElement(Constant *Agg, Constant *Idx) {
271 ConstantInt *CI = dyn_cast<ConstantInt>(Idx);
272 if (!CI) return 0;
Reid Spencere0fc4df2006-10-20 07:07:24 +0000273 unsigned IdxV = CI->getZExtValue();
Chris Lattner25db5802004-10-07 04:16:33 +0000274
Chris Lattnerabab0712004-10-08 17:32:09 +0000275 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Agg)) {
276 if (IdxV < CS->getNumOperands()) return CS->getOperand(IdxV);
277 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Agg)) {
278 if (IdxV < CA->getNumOperands()) return CA->getOperand(IdxV);
279 } else if (ConstantPacked *CP = dyn_cast<ConstantPacked>(Agg)) {
280 if (IdxV < CP->getNumOperands()) return CP->getOperand(IdxV);
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000281 } else if (isa<ConstantAggregateZero>(Agg)) {
Chris Lattnerabab0712004-10-08 17:32:09 +0000282 if (const StructType *STy = dyn_cast<StructType>(Agg->getType())) {
283 if (IdxV < STy->getNumElements())
284 return Constant::getNullValue(STy->getElementType(IdxV));
285 } else if (const SequentialType *STy =
286 dyn_cast<SequentialType>(Agg->getType())) {
287 return Constant::getNullValue(STy->getElementType());
288 }
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000289 } else if (isa<UndefValue>(Agg)) {
290 if (const StructType *STy = dyn_cast<StructType>(Agg->getType())) {
291 if (IdxV < STy->getNumElements())
292 return UndefValue::get(STy->getElementType(IdxV));
293 } else if (const SequentialType *STy =
294 dyn_cast<SequentialType>(Agg->getType())) {
295 return UndefValue::get(STy->getElementType());
296 }
Chris Lattnerabab0712004-10-08 17:32:09 +0000297 }
298 return 0;
299}
Chris Lattner25db5802004-10-07 04:16:33 +0000300
Chris Lattner25db5802004-10-07 04:16:33 +0000301
302/// CleanupConstantGlobalUsers - We just marked GV constant. Loop over all
303/// users of the global, cleaning up the obvious ones. This is largely just a
Chris Lattnercb9f1522004-10-10 16:43:46 +0000304/// quick scan over the use list to clean up the easy and obvious cruft. This
305/// returns true if it made a change.
306static bool CleanupConstantGlobalUsers(Value *V, Constant *Init) {
307 bool Changed = false;
Chris Lattner25db5802004-10-07 04:16:33 +0000308 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;) {
309 User *U = *UI++;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000310
Chris Lattner25db5802004-10-07 04:16:33 +0000311 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
Chris Lattner7561ca12005-02-27 18:58:52 +0000312 if (Init) {
313 // Replace the load with the initializer.
314 LI->replaceAllUsesWith(Init);
315 LI->eraseFromParent();
316 Changed = true;
317 }
Chris Lattner25db5802004-10-07 04:16:33 +0000318 } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
319 // Store must be unreachable or storing Init into the global.
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000320 SI->eraseFromParent();
Chris Lattnercb9f1522004-10-10 16:43:46 +0000321 Changed = true;
Chris Lattner25db5802004-10-07 04:16:33 +0000322 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
323 if (CE->getOpcode() == Instruction::GetElementPtr) {
Chris Lattner46d9ff082005-09-26 07:34:35 +0000324 Constant *SubInit = 0;
325 if (Init)
326 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
Chris Lattner7561ca12005-02-27 18:58:52 +0000327 Changed |= CleanupConstantGlobalUsers(CE, SubInit);
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000328 } else if (CE->getOpcode() == Instruction::BitCast &&
Chris Lattner7561ca12005-02-27 18:58:52 +0000329 isa<PointerType>(CE->getType())) {
330 // Pointer cast, delete any stores and memsets to the global.
331 Changed |= CleanupConstantGlobalUsers(CE, 0);
332 }
333
334 if (CE->use_empty()) {
335 CE->destroyConstant();
336 Changed = true;
Chris Lattner25db5802004-10-07 04:16:33 +0000337 }
338 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
Chris Lattner61ff32c2005-09-26 05:34:07 +0000339 Constant *SubInit = 0;
Chris Lattner46af55e2005-09-26 06:52:44 +0000340 ConstantExpr *CE =
341 dyn_cast_or_null<ConstantExpr>(ConstantFoldInstruction(GEP));
Chris Lattnereb953f02005-09-27 22:28:11 +0000342 if (Init && CE && CE->getOpcode() == Instruction::GetElementPtr)
Chris Lattner61ff32c2005-09-26 05:34:07 +0000343 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
Chris Lattner7561ca12005-02-27 18:58:52 +0000344 Changed |= CleanupConstantGlobalUsers(GEP, SubInit);
Chris Lattnera0e769c2004-10-10 16:47:33 +0000345
Chris Lattnercb9f1522004-10-10 16:43:46 +0000346 if (GEP->use_empty()) {
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000347 GEP->eraseFromParent();
Chris Lattnercb9f1522004-10-10 16:43:46 +0000348 Changed = true;
349 }
Chris Lattner7561ca12005-02-27 18:58:52 +0000350 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U)) { // memset/cpy/mv
351 if (MI->getRawDest() == V) {
352 MI->eraseFromParent();
353 Changed = true;
354 }
355
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000356 } else if (Constant *C = dyn_cast<Constant>(U)) {
357 // If we have a chain of dead constantexprs or other things dangling from
358 // us, and if they are all dead, nuke them without remorse.
359 if (ConstantIsDead(C)) {
360 C->destroyConstant();
Chris Lattner7561ca12005-02-27 18:58:52 +0000361 // This could have invalidated UI, start over from scratch.
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000362 CleanupConstantGlobalUsers(V, Init);
Chris Lattnercb9f1522004-10-10 16:43:46 +0000363 return true;
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000364 }
Chris Lattner25db5802004-10-07 04:16:33 +0000365 }
366 }
Chris Lattnercb9f1522004-10-10 16:43:46 +0000367 return Changed;
Chris Lattner25db5802004-10-07 04:16:33 +0000368}
369
Chris Lattnerabab0712004-10-08 17:32:09 +0000370/// SRAGlobal - Perform scalar replacement of aggregates on the specified global
371/// variable. This opens the door for other optimizations by exposing the
372/// behavior of the program in a more fine-grained way. We have determined that
373/// this transformation is safe already. We return the first global variable we
374/// insert so that the caller can reprocess it.
375static GlobalVariable *SRAGlobal(GlobalVariable *GV) {
376 assert(GV->hasInternalLinkage() && !GV->isConstant());
377 Constant *Init = GV->getInitializer();
378 const Type *Ty = Init->getType();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000379
Chris Lattnerabab0712004-10-08 17:32:09 +0000380 std::vector<GlobalVariable*> NewGlobals;
381 Module::GlobalListType &Globals = GV->getParent()->getGlobalList();
382
383 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
384 NewGlobals.reserve(STy->getNumElements());
385 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
386 Constant *In = getAggregateConstantElement(Init,
Reid Spencere0fc4df2006-10-20 07:07:24 +0000387 ConstantInt::get(Type::UIntTy, i));
Chris Lattnerabab0712004-10-08 17:32:09 +0000388 assert(In && "Couldn't get element of initializer?");
389 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(i), false,
390 GlobalVariable::InternalLinkage,
391 In, GV->getName()+"."+utostr(i));
392 Globals.insert(GV, NGV);
393 NewGlobals.push_back(NGV);
394 }
395 } else if (const SequentialType *STy = dyn_cast<SequentialType>(Ty)) {
396 unsigned NumElements = 0;
397 if (const ArrayType *ATy = dyn_cast<ArrayType>(STy))
398 NumElements = ATy->getNumElements();
399 else if (const PackedType *PTy = dyn_cast<PackedType>(STy))
400 NumElements = PTy->getNumElements();
401 else
402 assert(0 && "Unknown aggregate sequential type!");
403
Chris Lattner25169ca2005-02-23 16:53:04 +0000404 if (NumElements > 16 && GV->hasNUsesOrMore(16))
Chris Lattnerd6a44922005-02-01 01:23:31 +0000405 return 0; // It's not worth it.
Chris Lattnerabab0712004-10-08 17:32:09 +0000406 NewGlobals.reserve(NumElements);
407 for (unsigned i = 0, e = NumElements; i != e; ++i) {
408 Constant *In = getAggregateConstantElement(Init,
Reid Spencere0fc4df2006-10-20 07:07:24 +0000409 ConstantInt::get(Type::UIntTy, i));
Chris Lattnerabab0712004-10-08 17:32:09 +0000410 assert(In && "Couldn't get element of initializer?");
411
412 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(), false,
413 GlobalVariable::InternalLinkage,
414 In, GV->getName()+"."+utostr(i));
415 Globals.insert(GV, NGV);
416 NewGlobals.push_back(NGV);
417 }
418 }
419
420 if (NewGlobals.empty())
421 return 0;
422
Bill Wendling8f13b5c2006-11-26 10:02:32 +0000423 DOUT << "PERFORMING GLOBAL SRA ON: " << *GV;
Chris Lattner004e2502004-10-11 05:54:41 +0000424
Chris Lattnerabab0712004-10-08 17:32:09 +0000425 Constant *NullInt = Constant::getNullValue(Type::IntTy);
426
427 // Loop over all of the uses of the global, replacing the constantexpr geps,
428 // with smaller constantexpr geps or direct references.
429 while (!GV->use_empty()) {
Chris Lattner004e2502004-10-11 05:54:41 +0000430 User *GEP = GV->use_back();
431 assert(((isa<ConstantExpr>(GEP) &&
432 cast<ConstantExpr>(GEP)->getOpcode()==Instruction::GetElementPtr)||
433 isa<GetElementPtrInst>(GEP)) && "NonGEP CE's are not SRAable!");
Misha Brukmanb1c93172005-04-21 23:48:37 +0000434
Chris Lattnerabab0712004-10-08 17:32:09 +0000435 // Ignore the 1th operand, which has to be zero or else the program is quite
436 // broken (undefined). Get the 2nd operand, which is the structure or array
437 // index.
Reid Spencere0fc4df2006-10-20 07:07:24 +0000438 unsigned Val = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
Chris Lattnerabab0712004-10-08 17:32:09 +0000439 if (Val >= NewGlobals.size()) Val = 0; // Out of bound array access.
440
Chris Lattner004e2502004-10-11 05:54:41 +0000441 Value *NewPtr = NewGlobals[Val];
Chris Lattnerabab0712004-10-08 17:32:09 +0000442
443 // Form a shorter GEP if needed.
Chris Lattner004e2502004-10-11 05:54:41 +0000444 if (GEP->getNumOperands() > 3)
445 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEP)) {
446 std::vector<Constant*> Idxs;
447 Idxs.push_back(NullInt);
448 for (unsigned i = 3, e = CE->getNumOperands(); i != e; ++i)
449 Idxs.push_back(CE->getOperand(i));
450 NewPtr = ConstantExpr::getGetElementPtr(cast<Constant>(NewPtr), Idxs);
451 } else {
452 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(GEP);
453 std::vector<Value*> Idxs;
454 Idxs.push_back(NullInt);
455 for (unsigned i = 3, e = GEPI->getNumOperands(); i != e; ++i)
456 Idxs.push_back(GEPI->getOperand(i));
457 NewPtr = new GetElementPtrInst(NewPtr, Idxs,
458 GEPI->getName()+"."+utostr(Val), GEPI);
459 }
460 GEP->replaceAllUsesWith(NewPtr);
461
462 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(GEP))
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000463 GEPI->eraseFromParent();
Chris Lattner004e2502004-10-11 05:54:41 +0000464 else
465 cast<ConstantExpr>(GEP)->destroyConstant();
Chris Lattnerabab0712004-10-08 17:32:09 +0000466 }
467
Chris Lattner73ad73e2004-10-08 20:25:55 +0000468 // Delete the old global, now that it is dead.
469 Globals.erase(GV);
Chris Lattnerabab0712004-10-08 17:32:09 +0000470 ++NumSRA;
Chris Lattner004e2502004-10-11 05:54:41 +0000471
472 // Loop over the new globals array deleting any globals that are obviously
473 // dead. This can arise due to scalarization of a structure or an array that
474 // has elements that are dead.
475 unsigned FirstGlobal = 0;
476 for (unsigned i = 0, e = NewGlobals.size(); i != e; ++i)
477 if (NewGlobals[i]->use_empty()) {
478 Globals.erase(NewGlobals[i]);
479 if (FirstGlobal == i) ++FirstGlobal;
480 }
481
482 return FirstGlobal != NewGlobals.size() ? NewGlobals[FirstGlobal] : 0;
Chris Lattnerabab0712004-10-08 17:32:09 +0000483}
484
Chris Lattner09a52722004-10-09 21:48:45 +0000485/// AllUsesOfValueWillTrapIfNull - Return true if all users of the specified
486/// value will trap if the value is dynamically null.
487static bool AllUsesOfValueWillTrapIfNull(Value *V) {
488 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
489 if (isa<LoadInst>(*UI)) {
490 // Will trap.
491 } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
492 if (SI->getOperand(0) == V) {
Bill Wendlingf3baad32006-12-07 01:30:32 +0000493 //cerr << "NONTRAPPING USE: " << **UI;
Chris Lattner09a52722004-10-09 21:48:45 +0000494 return false; // Storing the value.
495 }
496 } else if (CallInst *CI = dyn_cast<CallInst>(*UI)) {
497 if (CI->getOperand(0) != V) {
Bill Wendlingf3baad32006-12-07 01:30:32 +0000498 //cerr << "NONTRAPPING USE: " << **UI;
Chris Lattner09a52722004-10-09 21:48:45 +0000499 return false; // Not calling the ptr
500 }
501 } else if (InvokeInst *II = dyn_cast<InvokeInst>(*UI)) {
502 if (II->getOperand(0) != V) {
Bill Wendlingf3baad32006-12-07 01:30:32 +0000503 //cerr << "NONTRAPPING USE: " << **UI;
Chris Lattner09a52722004-10-09 21:48:45 +0000504 return false; // Not calling the ptr
505 }
506 } else if (CastInst *CI = dyn_cast<CastInst>(*UI)) {
507 if (!AllUsesOfValueWillTrapIfNull(CI)) return false;
508 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(*UI)) {
509 if (!AllUsesOfValueWillTrapIfNull(GEPI)) return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000510 } else if (isa<SetCondInst>(*UI) &&
Chris Lattnerfe9abf92004-10-22 06:43:28 +0000511 isa<ConstantPointerNull>(UI->getOperand(1))) {
512 // Ignore setcc X, null
Chris Lattner09a52722004-10-09 21:48:45 +0000513 } else {
Bill Wendlingf3baad32006-12-07 01:30:32 +0000514 //cerr << "NONTRAPPING USE: " << **UI;
Chris Lattner09a52722004-10-09 21:48:45 +0000515 return false;
516 }
517 return true;
518}
519
520/// AllUsesOfLoadedValueWillTrapIfNull - Return true if all uses of any loads
Chris Lattnerfe9abf92004-10-22 06:43:28 +0000521/// from GV will trap if the loaded value is null. Note that this also permits
522/// comparisons of the loaded value against null, as a special case.
Chris Lattner09a52722004-10-09 21:48:45 +0000523static bool AllUsesOfLoadedValueWillTrapIfNull(GlobalVariable *GV) {
524 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI!=E; ++UI)
525 if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
526 if (!AllUsesOfValueWillTrapIfNull(LI))
527 return false;
528 } else if (isa<StoreInst>(*UI)) {
529 // Ignore stores to the global.
530 } else {
531 // We don't know or understand this user, bail out.
Bill Wendlingf3baad32006-12-07 01:30:32 +0000532 //cerr << "UNKNOWN USER OF GLOBAL!: " << **UI;
Chris Lattner09a52722004-10-09 21:48:45 +0000533 return false;
534 }
535
536 return true;
537}
538
Chris Lattnere42eb312004-10-10 23:14:11 +0000539static bool OptimizeAwayTrappingUsesOfValue(Value *V, Constant *NewV) {
540 bool Changed = false;
541 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ) {
542 Instruction *I = cast<Instruction>(*UI++);
543 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
544 LI->setOperand(0, NewV);
545 Changed = true;
546 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
547 if (SI->getOperand(1) == V) {
548 SI->setOperand(1, NewV);
549 Changed = true;
550 }
551 } else if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
552 if (I->getOperand(0) == V) {
553 // Calling through the pointer! Turn into a direct call, but be careful
554 // that the pointer is not also being passed as an argument.
555 I->setOperand(0, NewV);
556 Changed = true;
557 bool PassedAsArg = false;
558 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i)
559 if (I->getOperand(i) == V) {
560 PassedAsArg = true;
561 I->setOperand(i, NewV);
562 }
563
564 if (PassedAsArg) {
565 // Being passed as an argument also. Be careful to not invalidate UI!
566 UI = V->use_begin();
567 }
568 }
569 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
570 Changed |= OptimizeAwayTrappingUsesOfValue(CI,
Chris Lattner3ede00b2006-11-30 17:32:29 +0000571 ConstantExpr::getCast(CI->getOpcode(),
572 NewV, CI->getType()));
Chris Lattnere42eb312004-10-10 23:14:11 +0000573 if (CI->use_empty()) {
574 Changed = true;
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000575 CI->eraseFromParent();
Chris Lattnere42eb312004-10-10 23:14:11 +0000576 }
577 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
578 // Should handle GEP here.
579 std::vector<Constant*> Indices;
580 Indices.reserve(GEPI->getNumOperands()-1);
581 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
582 if (Constant *C = dyn_cast<Constant>(GEPI->getOperand(i)))
583 Indices.push_back(C);
584 else
585 break;
586 if (Indices.size() == GEPI->getNumOperands()-1)
587 Changed |= OptimizeAwayTrappingUsesOfValue(GEPI,
588 ConstantExpr::getGetElementPtr(NewV, Indices));
589 if (GEPI->use_empty()) {
590 Changed = true;
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000591 GEPI->eraseFromParent();
Chris Lattnere42eb312004-10-10 23:14:11 +0000592 }
593 }
594 }
595
596 return Changed;
597}
598
599
600/// OptimizeAwayTrappingUsesOfLoads - The specified global has only one non-null
601/// value stored into it. If there are uses of the loaded value that would trap
602/// if the loaded value is dynamically null, then we know that they cannot be
603/// reachable with a null optimize away the load.
604static bool OptimizeAwayTrappingUsesOfLoads(GlobalVariable *GV, Constant *LV) {
605 std::vector<LoadInst*> Loads;
606 bool Changed = false;
607
608 // Replace all uses of loads with uses of uses of the stored value.
609 for (Value::use_iterator GUI = GV->use_begin(), E = GV->use_end();
610 GUI != E; ++GUI)
611 if (LoadInst *LI = dyn_cast<LoadInst>(*GUI)) {
612 Loads.push_back(LI);
613 Changed |= OptimizeAwayTrappingUsesOfValue(LI, LV);
614 } else {
615 assert(isa<StoreInst>(*GUI) && "Only expect load and stores!");
616 }
617
618 if (Changed) {
Bill Wendling8f13b5c2006-11-26 10:02:32 +0000619 DOUT << "OPTIMIZED LOADS FROM STORED ONCE POINTER: " << *GV;
Chris Lattnere42eb312004-10-10 23:14:11 +0000620 ++NumGlobUses;
621 }
622
623 // Delete all of the loads we can, keeping track of whether we nuked them all!
624 bool AllLoadsGone = true;
625 while (!Loads.empty()) {
626 LoadInst *L = Loads.back();
627 if (L->use_empty()) {
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000628 L->eraseFromParent();
Chris Lattnere42eb312004-10-10 23:14:11 +0000629 Changed = true;
630 } else {
631 AllLoadsGone = false;
632 }
633 Loads.pop_back();
634 }
635
636 // If we nuked all of the loads, then none of the stores are needed either,
637 // nor is the global.
638 if (AllLoadsGone) {
Bill Wendling8f13b5c2006-11-26 10:02:32 +0000639 DOUT << " *** GLOBAL NOW DEAD!\n";
Chris Lattnere42eb312004-10-10 23:14:11 +0000640 CleanupConstantGlobalUsers(GV, 0);
641 if (GV->use_empty()) {
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000642 GV->eraseFromParent();
Chris Lattnere42eb312004-10-10 23:14:11 +0000643 ++NumDeleted;
644 }
645 Changed = true;
646 }
647 return Changed;
648}
649
Chris Lattner004e2502004-10-11 05:54:41 +0000650/// ConstantPropUsersOf - Walk the use list of V, constant folding all of the
651/// instructions that are foldable.
652static void ConstantPropUsersOf(Value *V) {
653 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; )
654 if (Instruction *I = dyn_cast<Instruction>(*UI++))
655 if (Constant *NewC = ConstantFoldInstruction(I)) {
656 I->replaceAllUsesWith(NewC);
657
Chris Lattnerd6a44922005-02-01 01:23:31 +0000658 // Advance UI to the next non-I use to avoid invalidating it!
659 // Instructions could multiply use V.
660 while (UI != E && *UI == I)
Chris Lattner004e2502004-10-11 05:54:41 +0000661 ++UI;
Chris Lattnerd6a44922005-02-01 01:23:31 +0000662 I->eraseFromParent();
Chris Lattner004e2502004-10-11 05:54:41 +0000663 }
664}
665
666/// OptimizeGlobalAddressOfMalloc - This function takes the specified global
667/// variable, and transforms the program as if it always contained the result of
668/// the specified malloc. Because it is always the result of the specified
669/// malloc, there is no reason to actually DO the malloc. Instead, turn the
Chris Lattner3ede00b2006-11-30 17:32:29 +0000670/// malloc into a global, and any loads of GV as uses of the new global.
Chris Lattner004e2502004-10-11 05:54:41 +0000671static GlobalVariable *OptimizeGlobalAddressOfMalloc(GlobalVariable *GV,
672 MallocInst *MI) {
Bill Wendling8f13b5c2006-11-26 10:02:32 +0000673 DOUT << "PROMOTING MALLOC GLOBAL: " << *GV << " MALLOC = " << *MI;
Chris Lattner004e2502004-10-11 05:54:41 +0000674 ConstantInt *NElements = cast<ConstantInt>(MI->getArraySize());
675
Reid Spencere0fc4df2006-10-20 07:07:24 +0000676 if (NElements->getZExtValue() != 1) {
Chris Lattner004e2502004-10-11 05:54:41 +0000677 // If we have an array allocation, transform it to a single element
678 // allocation to make the code below simpler.
679 Type *NewTy = ArrayType::get(MI->getAllocatedType(),
Reid Spencere0fc4df2006-10-20 07:07:24 +0000680 NElements->getZExtValue());
Chris Lattner004e2502004-10-11 05:54:41 +0000681 MallocInst *NewMI =
682 new MallocInst(NewTy, Constant::getNullValue(Type::UIntTy),
Nate Begeman848622f2005-11-05 09:21:28 +0000683 MI->getAlignment(), MI->getName(), MI);
Chris Lattner004e2502004-10-11 05:54:41 +0000684 std::vector<Value*> Indices;
685 Indices.push_back(Constant::getNullValue(Type::IntTy));
686 Indices.push_back(Indices[0]);
687 Value *NewGEP = new GetElementPtrInst(NewMI, Indices,
688 NewMI->getName()+".el0", MI);
689 MI->replaceAllUsesWith(NewGEP);
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000690 MI->eraseFromParent();
Chris Lattner004e2502004-10-11 05:54:41 +0000691 MI = NewMI;
692 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000693
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000694 // Create the new global variable. The contents of the malloc'd memory is
695 // undefined, so initialize with an undef value.
696 Constant *Init = UndefValue::get(MI->getAllocatedType());
Chris Lattner004e2502004-10-11 05:54:41 +0000697 GlobalVariable *NewGV = new GlobalVariable(MI->getAllocatedType(), false,
698 GlobalValue::InternalLinkage, Init,
699 GV->getName()+".body");
700 GV->getParent()->getGlobalList().insert(GV, NewGV);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000701
Chris Lattner004e2502004-10-11 05:54:41 +0000702 // Anything that used the malloc now uses the global directly.
703 MI->replaceAllUsesWith(NewGV);
Chris Lattner004e2502004-10-11 05:54:41 +0000704
705 Constant *RepValue = NewGV;
706 if (NewGV->getType() != GV->getType()->getElementType())
Reid Spencerbb65ebf2006-12-12 23:36:14 +0000707 RepValue = ConstantExpr::getBitCast(RepValue,
708 GV->getType()->getElementType());
Chris Lattner004e2502004-10-11 05:54:41 +0000709
Chris Lattnerfe9abf92004-10-22 06:43:28 +0000710 // If there is a comparison against null, we will insert a global bool to
711 // keep track of whether the global was initialized yet or not.
Misha Brukmanb1c93172005-04-21 23:48:37 +0000712 GlobalVariable *InitBool =
713 new GlobalVariable(Type::BoolTy, false, GlobalValue::InternalLinkage,
Chris Lattner6ab03f62006-09-28 23:35:22 +0000714 ConstantBool::getFalse(), GV->getName()+".init");
Chris Lattner3b181392004-12-02 06:25:58 +0000715 bool InitBoolUsed = false;
Chris Lattnerfe9abf92004-10-22 06:43:28 +0000716
Chris Lattner004e2502004-10-11 05:54:41 +0000717 // Loop over all uses of GV, processing them in turn.
Chris Lattner3b181392004-12-02 06:25:58 +0000718 std::vector<StoreInst*> Stores;
Chris Lattner004e2502004-10-11 05:54:41 +0000719 while (!GV->use_empty())
720 if (LoadInst *LI = dyn_cast<LoadInst>(GV->use_back())) {
Chris Lattnerfe9abf92004-10-22 06:43:28 +0000721 while (!LI->use_empty()) {
Chris Lattnerd6a44922005-02-01 01:23:31 +0000722 Use &LoadUse = LI->use_begin().getUse();
Chris Lattnerfe9abf92004-10-22 06:43:28 +0000723 if (!isa<SetCondInst>(LoadUse.getUser()))
724 LoadUse = RepValue;
725 else {
Chris Lattnerfe9abf92004-10-22 06:43:28 +0000726 // Replace the setcc X, 0 with a use of the bool value.
727 SetCondInst *SCI = cast<SetCondInst>(LoadUse.getUser());
728 Value *LV = new LoadInst(InitBool, InitBool->getName()+".val", SCI);
Chris Lattner3b181392004-12-02 06:25:58 +0000729 InitBoolUsed = true;
Chris Lattnerfe9abf92004-10-22 06:43:28 +0000730 switch (SCI->getOpcode()) {
731 default: assert(0 && "Unknown opcode!");
732 case Instruction::SetLT:
Chris Lattner6ab03f62006-09-28 23:35:22 +0000733 LV = ConstantBool::getFalse(); // X < null -> always false
Chris Lattnerfe9abf92004-10-22 06:43:28 +0000734 break;
735 case Instruction::SetEQ:
736 case Instruction::SetLE:
737 LV = BinaryOperator::createNot(LV, "notinit", SCI);
738 break;
739 case Instruction::SetNE:
740 case Instruction::SetGE:
741 case Instruction::SetGT:
742 break; // no change.
743 }
744 SCI->replaceAllUsesWith(LV);
745 SCI->eraseFromParent();
746 }
747 }
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000748 LI->eraseFromParent();
Chris Lattner004e2502004-10-11 05:54:41 +0000749 } else {
750 StoreInst *SI = cast<StoreInst>(GV->use_back());
Chris Lattner3b181392004-12-02 06:25:58 +0000751 // The global is initialized when the store to it occurs.
Chris Lattner6ab03f62006-09-28 23:35:22 +0000752 new StoreInst(ConstantBool::getTrue(), InitBool, SI);
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000753 SI->eraseFromParent();
Chris Lattner004e2502004-10-11 05:54:41 +0000754 }
755
Chris Lattner3b181392004-12-02 06:25:58 +0000756 // If the initialization boolean was used, insert it, otherwise delete it.
757 if (!InitBoolUsed) {
758 while (!InitBool->use_empty()) // Delete initializations
759 cast<Instruction>(InitBool->use_back())->eraseFromParent();
760 delete InitBool;
761 } else
762 GV->getParent()->getGlobalList().insert(GV, InitBool);
763
764
Chris Lattnerfe9abf92004-10-22 06:43:28 +0000765 // Now the GV is dead, nuke it and the malloc.
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000766 GV->eraseFromParent();
Chris Lattnerfe9abf92004-10-22 06:43:28 +0000767 MI->eraseFromParent();
Chris Lattner004e2502004-10-11 05:54:41 +0000768
769 // To further other optimizations, loop over all users of NewGV and try to
770 // constant prop them. This will promote GEP instructions with constant
771 // indices into GEP constant-exprs, which will allow global-opt to hack on it.
772 ConstantPropUsersOf(NewGV);
773 if (RepValue != NewGV)
774 ConstantPropUsersOf(RepValue);
775
776 return NewGV;
777}
Chris Lattnere42eb312004-10-10 23:14:11 +0000778
Chris Lattnerc0677c02004-12-02 07:11:07 +0000779/// ValueIsOnlyUsedLocallyOrStoredToOneGlobal - Scan the use-list of V checking
780/// to make sure that there are no complex uses of V. We permit simple things
781/// like dereferencing the pointer, but not storing through the address, unless
782/// it is to the specified global.
783static bool ValueIsOnlyUsedLocallyOrStoredToOneGlobal(Instruction *V,
784 GlobalVariable *GV) {
785 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;++UI)
786 if (isa<LoadInst>(*UI) || isa<SetCondInst>(*UI)) {
787 // Fine, ignore.
788 } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
789 if (SI->getOperand(0) == V && SI->getOperand(1) != GV)
790 return false; // Storing the pointer itself... bad.
791 // Otherwise, storing through it, or storing into GV... fine.
792 } else if (isa<GetElementPtrInst>(*UI) || isa<SelectInst>(*UI)) {
793 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(cast<Instruction>(*UI),GV))
794 return false;
795 } else {
796 return false;
797 }
798 return true;
Chris Lattnerc0677c02004-12-02 07:11:07 +0000799}
800
Chris Lattner24d3d422006-09-30 23:32:09 +0000801/// ReplaceUsesOfMallocWithGlobal - The Alloc pointer is stored into GV
802/// somewhere. Transform all uses of the allocation into loads from the
803/// global and uses of the resultant pointer. Further, delete the store into
804/// GV. This assumes that these value pass the
805/// 'ValueIsOnlyUsedLocallyOrStoredToOneGlobal' predicate.
806static void ReplaceUsesOfMallocWithGlobal(Instruction *Alloc,
807 GlobalVariable *GV) {
808 while (!Alloc->use_empty()) {
809 Instruction *U = Alloc->use_back();
810 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
811 // If this is the store of the allocation into the global, remove it.
812 if (SI->getOperand(1) == GV) {
813 SI->eraseFromParent();
814 continue;
815 }
816 }
817
818 // Insert a load from the global, and use it instead of the malloc.
819 Value *NL = new LoadInst(GV, GV->getName()+".val", U);
820 U->replaceUsesOfWith(Alloc, NL);
821 }
822}
823
824/// GlobalLoadUsesSimpleEnoughForHeapSRA - If all users of values loaded from
825/// GV are simple enough to perform HeapSRA, return true.
826static bool GlobalLoadUsesSimpleEnoughForHeapSRA(GlobalVariable *GV) {
827 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI != E;
828 ++UI)
829 if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
830 // We permit two users of the load: setcc comparing against the null
831 // pointer, and a getelementptr of a specific form.
832 for (Value::use_iterator UI = LI->use_begin(), E = LI->use_end(); UI != E;
833 ++UI) {
834 // Comparison against null is ok.
835 if (SetCondInst *SCI = dyn_cast<SetCondInst>(*UI)) {
836 if (!isa<ConstantPointerNull>(SCI->getOperand(1)))
837 return false;
838 continue;
839 }
840
841 // getelementptr is also ok, but only a simple form.
842 GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(*UI);
843 if (!GEPI) return false;
844
845 // Must index into the array and into the struct.
846 if (GEPI->getNumOperands() < 3)
847 return false;
848
849 // Otherwise the GEP is ok.
850 continue;
851 }
852 }
853 return true;
854}
855
856/// RewriteUsesOfLoadForHeapSRoA - We are performing Heap SRoA on a global. Ptr
857/// is a value loaded from the global. Eliminate all uses of Ptr, making them
858/// use FieldGlobals instead. All uses of loaded values satisfy
859/// GlobalLoadUsesSimpleEnoughForHeapSRA.
860static void RewriteUsesOfLoadForHeapSRoA(LoadInst *Ptr,
861 const std::vector<GlobalVariable*> &FieldGlobals) {
862 std::vector<Value *> InsertedLoadsForPtr;
863 //InsertedLoadsForPtr.resize(FieldGlobals.size());
864 while (!Ptr->use_empty()) {
865 Instruction *User = Ptr->use_back();
866
867 // If this is a comparison against null, handle it.
868 if (SetCondInst *SCI = dyn_cast<SetCondInst>(User)) {
869 assert(isa<ConstantPointerNull>(SCI->getOperand(1)));
870 // If we have a setcc of the loaded pointer, we can use a setcc of any
871 // field.
872 Value *NPtr;
873 if (InsertedLoadsForPtr.empty()) {
874 NPtr = new LoadInst(FieldGlobals[0], Ptr->getName()+".f0", Ptr);
875 InsertedLoadsForPtr.push_back(Ptr);
876 } else {
877 NPtr = InsertedLoadsForPtr.back();
878 }
879
880 Value *New = new SetCondInst(SCI->getOpcode(), NPtr,
881 Constant::getNullValue(NPtr->getType()),
882 SCI->getName(), SCI);
883 SCI->replaceAllUsesWith(New);
884 SCI->eraseFromParent();
885 continue;
886 }
887
888 // Otherwise, this should be: 'getelementptr Ptr, Idx, uint FieldNo ...'
889 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(User);
Reid Spencere0fc4df2006-10-20 07:07:24 +0000890 assert(GEPI->getNumOperands() >= 3 && isa<ConstantInt>(GEPI->getOperand(2))
891 && GEPI->getOperand(2)->getType()->isUnsigned()
Chris Lattner24d3d422006-09-30 23:32:09 +0000892 && "Unexpected GEPI!");
893
894 // Load the pointer for this field.
Reid Spencere0fc4df2006-10-20 07:07:24 +0000895 unsigned FieldNo = cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue();
Chris Lattner24d3d422006-09-30 23:32:09 +0000896 if (InsertedLoadsForPtr.size() <= FieldNo)
897 InsertedLoadsForPtr.resize(FieldNo+1);
898 if (InsertedLoadsForPtr[FieldNo] == 0)
899 InsertedLoadsForPtr[FieldNo] = new LoadInst(FieldGlobals[FieldNo],
900 Ptr->getName()+".f" +
901 utostr(FieldNo), Ptr);
902 Value *NewPtr = InsertedLoadsForPtr[FieldNo];
903
904 // Create the new GEP idx vector.
905 std::vector<Value*> GEPIdx;
906 GEPIdx.push_back(GEPI->getOperand(1));
907 GEPIdx.insert(GEPIdx.end(), GEPI->op_begin()+3, GEPI->op_end());
908
909 Value *NGEPI = new GetElementPtrInst(NewPtr, GEPIdx, GEPI->getName(), GEPI);
910 GEPI->replaceAllUsesWith(NGEPI);
911 GEPI->eraseFromParent();
912 }
913}
914
915/// PerformHeapAllocSRoA - MI is an allocation of an array of structures. Break
916/// it up into multiple allocations of arrays of the fields.
917static GlobalVariable *PerformHeapAllocSRoA(GlobalVariable *GV, MallocInst *MI){
Bill Wendling8f13b5c2006-11-26 10:02:32 +0000918 DOUT << "SROA HEAP ALLOC: " << *GV << " MALLOC = " << *MI;
Chris Lattner24d3d422006-09-30 23:32:09 +0000919 const StructType *STy = cast<StructType>(MI->getAllocatedType());
920
921 // There is guaranteed to be at least one use of the malloc (storing
922 // it into GV). If there are other uses, change them to be uses of
923 // the global to simplify later code. This also deletes the store
924 // into GV.
925 ReplaceUsesOfMallocWithGlobal(MI, GV);
926
927 // Okay, at this point, there are no users of the malloc. Insert N
928 // new mallocs at the same place as MI, and N globals.
929 std::vector<GlobalVariable*> FieldGlobals;
930 std::vector<MallocInst*> FieldMallocs;
931
932 for (unsigned FieldNo = 0, e = STy->getNumElements(); FieldNo != e;++FieldNo){
933 const Type *FieldTy = STy->getElementType(FieldNo);
934 const Type *PFieldTy = PointerType::get(FieldTy);
935
936 GlobalVariable *NGV =
937 new GlobalVariable(PFieldTy, false, GlobalValue::InternalLinkage,
938 Constant::getNullValue(PFieldTy),
939 GV->getName() + ".f" + utostr(FieldNo), GV);
940 FieldGlobals.push_back(NGV);
941
942 MallocInst *NMI = new MallocInst(FieldTy, MI->getArraySize(),
943 MI->getName() + ".f" + utostr(FieldNo),MI);
944 FieldMallocs.push_back(NMI);
945 new StoreInst(NMI, NGV, MI);
946 }
947
948 // The tricky aspect of this transformation is handling the case when malloc
949 // fails. In the original code, malloc failing would set the result pointer
950 // of malloc to null. In this case, some mallocs could succeed and others
951 // could fail. As such, we emit code that looks like this:
952 // F0 = malloc(field0)
953 // F1 = malloc(field1)
954 // F2 = malloc(field2)
955 // if (F0 == 0 || F1 == 0 || F2 == 0) {
956 // if (F0) { free(F0); F0 = 0; }
957 // if (F1) { free(F1); F1 = 0; }
958 // if (F2) { free(F2); F2 = 0; }
959 // }
960 Value *RunningOr = 0;
961 for (unsigned i = 0, e = FieldMallocs.size(); i != e; ++i) {
962 Value *Cond = new SetCondInst(Instruction::SetEQ, FieldMallocs[i],
963 Constant::getNullValue(FieldMallocs[i]->getType()),
964 "isnull", MI);
965 if (!RunningOr)
966 RunningOr = Cond; // First seteq
967 else
968 RunningOr = BinaryOperator::createOr(RunningOr, Cond, "tmp", MI);
969 }
970
971 // Split the basic block at the old malloc.
972 BasicBlock *OrigBB = MI->getParent();
973 BasicBlock *ContBB = OrigBB->splitBasicBlock(MI, "malloc_cont");
974
975 // Create the block to check the first condition. Put all these blocks at the
976 // end of the function as they are unlikely to be executed.
977 BasicBlock *NullPtrBlock = new BasicBlock("malloc_ret_null",
978 OrigBB->getParent());
979
980 // Remove the uncond branch from OrigBB to ContBB, turning it into a cond
981 // branch on RunningOr.
982 OrigBB->getTerminator()->eraseFromParent();
983 new BranchInst(NullPtrBlock, ContBB, RunningOr, OrigBB);
984
985 // Within the NullPtrBlock, we need to emit a comparison and branch for each
986 // pointer, because some may be null while others are not.
987 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
988 Value *GVVal = new LoadInst(FieldGlobals[i], "tmp", NullPtrBlock);
989 Value *Cmp = new SetCondInst(Instruction::SetNE, GVVal,
990 Constant::getNullValue(GVVal->getType()),
991 "tmp", NullPtrBlock);
992 BasicBlock *FreeBlock = new BasicBlock("free_it", OrigBB->getParent());
993 BasicBlock *NextBlock = new BasicBlock("next", OrigBB->getParent());
994 new BranchInst(FreeBlock, NextBlock, Cmp, NullPtrBlock);
995
996 // Fill in FreeBlock.
997 new FreeInst(GVVal, FreeBlock);
998 new StoreInst(Constant::getNullValue(GVVal->getType()), FieldGlobals[i],
999 FreeBlock);
1000 new BranchInst(NextBlock, FreeBlock);
1001
1002 NullPtrBlock = NextBlock;
1003 }
1004
1005 new BranchInst(ContBB, NullPtrBlock);
1006
1007
1008 // MI is no longer needed, remove it.
1009 MI->eraseFromParent();
1010
1011
1012 // Okay, the malloc site is completely handled. All of the uses of GV are now
1013 // loads, and all uses of those loads are simple. Rewrite them to use loads
1014 // of the per-field globals instead.
1015 while (!GV->use_empty()) {
1016 LoadInst *LI = cast<LoadInst>(GV->use_back());
1017 RewriteUsesOfLoadForHeapSRoA(LI, FieldGlobals);
1018 LI->eraseFromParent();
1019 }
1020
1021 // The old global is now dead, remove it.
1022 GV->eraseFromParent();
1023
1024 ++NumHeapSRA;
1025 return FieldGlobals[0];
1026}
1027
1028
Chris Lattner09a52722004-10-09 21:48:45 +00001029// OptimizeOnceStoredGlobal - Try to optimize globals based on the knowledge
1030// that only one value (besides its initializer) is ever stored to the global.
Chris Lattner004e2502004-10-11 05:54:41 +00001031static bool OptimizeOnceStoredGlobal(GlobalVariable *GV, Value *StoredOnceVal,
Chris Lattnerc2d3d312006-08-27 22:42:52 +00001032 Module::global_iterator &GVI,
1033 TargetData &TD) {
Chris Lattner09a52722004-10-09 21:48:45 +00001034 if (CastInst *CI = dyn_cast<CastInst>(StoredOnceVal))
1035 StoredOnceVal = CI->getOperand(0);
1036 else if (GetElementPtrInst *GEPI =dyn_cast<GetElementPtrInst>(StoredOnceVal)){
Chris Lattnere42eb312004-10-10 23:14:11 +00001037 // "getelementptr Ptr, 0, 0, 0" is really just a cast.
Chris Lattner09a52722004-10-09 21:48:45 +00001038 bool IsJustACast = true;
1039 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
1040 if (!isa<Constant>(GEPI->getOperand(i)) ||
1041 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
1042 IsJustACast = false;
1043 break;
1044 }
1045 if (IsJustACast)
1046 StoredOnceVal = GEPI->getOperand(0);
1047 }
1048
Chris Lattnere42eb312004-10-10 23:14:11 +00001049 // If we are dealing with a pointer global that is initialized to null and
1050 // only has one (non-null) value stored into it, then we can optimize any
1051 // users of the loaded value (often calls and loads) that would trap if the
1052 // value was null.
Chris Lattner09a52722004-10-09 21:48:45 +00001053 if (isa<PointerType>(GV->getInitializer()->getType()) &&
1054 GV->getInitializer()->isNullValue()) {
Chris Lattnere42eb312004-10-10 23:14:11 +00001055 if (Constant *SOVC = dyn_cast<Constant>(StoredOnceVal)) {
1056 if (GV->getInitializer()->getType() != SOVC->getType())
Reid Spencerbb65ebf2006-12-12 23:36:14 +00001057 SOVC = ConstantExpr::getBitCast(SOVC, GV->getInitializer()->getType());
Misha Brukmanb1c93172005-04-21 23:48:37 +00001058
Chris Lattnere42eb312004-10-10 23:14:11 +00001059 // Optimize away any trapping uses of the loaded value.
1060 if (OptimizeAwayTrappingUsesOfLoads(GV, SOVC))
Chris Lattner604ed7a2004-10-10 17:07:12 +00001061 return true;
Chris Lattner004e2502004-10-11 05:54:41 +00001062 } else if (MallocInst *MI = dyn_cast<MallocInst>(StoredOnceVal)) {
Chris Lattner80a01ef2006-09-30 19:40:30 +00001063 // If this is a malloc of an abstract type, don't touch it.
1064 if (!MI->getAllocatedType()->isSized())
1065 return false;
1066
Chris Lattner24d3d422006-09-30 23:32:09 +00001067 // We can't optimize this global unless all uses of it are *known* to be
1068 // of the malloc value, not of the null initializer value (consider a use
1069 // that compares the global's value against zero to see if the malloc has
1070 // been reached). To do this, we check to see if all uses of the global
1071 // would trap if the global were null: this proves that they must all
1072 // happen after the malloc.
1073 if (!AllUsesOfLoadedValueWillTrapIfNull(GV))
1074 return false;
1075
1076 // We can't optimize this if the malloc itself is used in a complex way,
1077 // for example, being stored into multiple globals. This allows the
1078 // malloc to be stored into the specified global, loaded setcc'd, and
1079 // GEP'd. These are all things we could transform to using the global
1080 // for.
1081 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(MI, GV))
1082 return false;
1083
1084
Chris Lattner004e2502004-10-11 05:54:41 +00001085 // If we have a global that is only initialized with a fixed size malloc,
Chris Lattner24d3d422006-09-30 23:32:09 +00001086 // transform the program to use global memory instead of malloc'd memory.
1087 // This eliminates dynamic allocation, avoids an indirection accessing the
1088 // data, and exposes the resultant global to further GlobalOpt.
Chris Lattner80a01ef2006-09-30 19:40:30 +00001089 if (ConstantInt *NElements = dyn_cast<ConstantInt>(MI->getArraySize())) {
Chris Lattner24d3d422006-09-30 23:32:09 +00001090 // Restrict this transformation to only working on small allocations
1091 // (2048 bytes currently), as we don't want to introduce a 16M global or
1092 // something.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001093 if (NElements->getZExtValue()*
Chris Lattner24d3d422006-09-30 23:32:09 +00001094 TD.getTypeSize(MI->getAllocatedType()) < 2048) {
Chris Lattner004e2502004-10-11 05:54:41 +00001095 GVI = OptimizeGlobalAddressOfMalloc(GV, MI);
1096 return true;
1097 }
Chris Lattner80a01ef2006-09-30 19:40:30 +00001098 }
Chris Lattner24d3d422006-09-30 23:32:09 +00001099
1100 // If the allocation is an array of structures, consider transforming this
1101 // into multiple malloc'd arrays, one for each field. This is basically
1102 // SRoA for malloc'd memory.
1103 if (const StructType *AllocTy =
1104 dyn_cast<StructType>(MI->getAllocatedType())) {
1105 // This the structure has an unreasonable number of fields, leave it
1106 // alone.
1107 if (AllocTy->getNumElements() <= 16 && AllocTy->getNumElements() > 0 &&
1108 GlobalLoadUsesSimpleEnoughForHeapSRA(GV)) {
1109 GVI = PerformHeapAllocSRoA(GV, MI);
1110 return true;
1111 }
1112 }
Chris Lattnere42eb312004-10-10 23:14:11 +00001113 }
Chris Lattner09a52722004-10-09 21:48:45 +00001114 }
Chris Lattner004e2502004-10-11 05:54:41 +00001115
Chris Lattner09a52722004-10-09 21:48:45 +00001116 return false;
1117}
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001118
Chris Lattner40e4cec2004-12-12 05:53:50 +00001119/// ShrinkGlobalToBoolean - At this point, we have learned that the only two
Misha Brukmanb1c93172005-04-21 23:48:37 +00001120/// values ever stored into GV are its initializer and OtherVal.
Chris Lattner40e4cec2004-12-12 05:53:50 +00001121static void ShrinkGlobalToBoolean(GlobalVariable *GV, Constant *OtherVal) {
1122 // Create the new global, initializing it to false.
1123 GlobalVariable *NewGV = new GlobalVariable(Type::BoolTy, false,
Chris Lattner6ab03f62006-09-28 23:35:22 +00001124 GlobalValue::InternalLinkage, ConstantBool::getFalse(),
1125 GV->getName()+".b");
Chris Lattner40e4cec2004-12-12 05:53:50 +00001126 GV->getParent()->getGlobalList().insert(GV, NewGV);
1127
1128 Constant *InitVal = GV->getInitializer();
1129 assert(InitVal->getType() != Type::BoolTy && "No reason to shrink to bool!");
1130
1131 // If initialized to zero and storing one into the global, we can use a cast
1132 // instead of a select to synthesize the desired value.
1133 bool IsOneZero = false;
1134 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal))
1135 IsOneZero = InitVal->isNullValue() && CI->equalsInt(1);
1136
1137 while (!GV->use_empty()) {
1138 Instruction *UI = cast<Instruction>(GV->use_back());
1139 if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
1140 // Change the store into a boolean store.
1141 bool StoringOther = SI->getOperand(0) == OtherVal;
1142 // Only do this if we weren't storing a loaded value.
Chris Lattner745196a2004-12-12 19:34:41 +00001143 Value *StoreVal;
Chris Lattner40e4cec2004-12-12 05:53:50 +00001144 if (StoringOther || SI->getOperand(0) == InitVal)
Chris Lattner745196a2004-12-12 19:34:41 +00001145 StoreVal = ConstantBool::get(StoringOther);
1146 else {
1147 // Otherwise, we are storing a previously loaded copy. To do this,
1148 // change the copy from copying the original value to just copying the
1149 // bool.
1150 Instruction *StoredVal = cast<Instruction>(SI->getOperand(0));
1151
1152 // If we're already replaced the input, StoredVal will be a cast or
1153 // select instruction. If not, it will be a load of the original
1154 // global.
1155 if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
1156 assert(LI->getOperand(0) == GV && "Not a copy!");
1157 // Insert a new load, to preserve the saved value.
1158 StoreVal = new LoadInst(NewGV, LI->getName()+".b", LI);
1159 } else {
1160 assert((isa<CastInst>(StoredVal) || isa<SelectInst>(StoredVal)) &&
1161 "This is not a form that we understand!");
1162 StoreVal = StoredVal->getOperand(0);
1163 assert(isa<LoadInst>(StoreVal) && "Not a load of NewGV!");
1164 }
1165 }
1166 new StoreInst(StoreVal, NewGV, SI);
1167 } else if (!UI->use_empty()) {
Chris Lattner40e4cec2004-12-12 05:53:50 +00001168 // Change the load into a load of bool then a select.
1169 LoadInst *LI = cast<LoadInst>(UI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001170
Chris Lattner40e4cec2004-12-12 05:53:50 +00001171 std::string Name = LI->getName(); LI->setName("");
1172 LoadInst *NLI = new LoadInst(NewGV, Name+".b", LI);
1173 Value *NSI;
1174 if (IsOneZero)
Chris Lattnerc8978c52006-11-30 17:35:08 +00001175 NSI = new ZExtInst(NLI, LI->getType(), Name, LI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001176 else
Chris Lattner40e4cec2004-12-12 05:53:50 +00001177 NSI = new SelectInst(NLI, OtherVal, InitVal, Name, LI);
1178 LI->replaceAllUsesWith(NSI);
1179 }
1180 UI->eraseFromParent();
1181 }
1182
1183 GV->eraseFromParent();
1184}
1185
1186
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001187/// ProcessInternalGlobal - Analyze the specified global variable and optimize
1188/// it if possible. If we make a change, return true.
Chris Lattner004e2502004-10-11 05:54:41 +00001189bool GlobalOpt::ProcessInternalGlobal(GlobalVariable *GV,
Chris Lattner531f9e92005-03-15 04:54:21 +00001190 Module::global_iterator &GVI) {
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001191 std::set<PHINode*> PHIUsers;
1192 GlobalStatus GS;
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001193 GV->removeDeadConstantUsers();
1194
1195 if (GV->use_empty()) {
Bill Wendling8f13b5c2006-11-26 10:02:32 +00001196 DOUT << "GLOBAL DEAD: " << *GV;
Chris Lattner8e71c6a2004-10-16 18:09:00 +00001197 GV->eraseFromParent();
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001198 ++NumDeleted;
1199 return true;
1200 }
1201
1202 if (!AnalyzeGlobal(GV, GS, PHIUsers)) {
Chris Lattner80a01ef2006-09-30 19:40:30 +00001203#if 0
Bill Wendlingf3baad32006-12-07 01:30:32 +00001204 cerr << "Global: " << *GV;
1205 cerr << " isLoaded = " << GS.isLoaded << "\n";
1206 cerr << " StoredType = ";
Chris Lattner80a01ef2006-09-30 19:40:30 +00001207 switch (GS.StoredType) {
Bill Wendlingf3baad32006-12-07 01:30:32 +00001208 case GlobalStatus::NotStored: cerr << "NEVER STORED\n"; break;
1209 case GlobalStatus::isInitializerStored: cerr << "INIT STORED\n"; break;
1210 case GlobalStatus::isStoredOnce: cerr << "STORED ONCE\n"; break;
1211 case GlobalStatus::isStored: cerr << "stored\n"; break;
Chris Lattner80a01ef2006-09-30 19:40:30 +00001212 }
1213 if (GS.StoredType == GlobalStatus::isStoredOnce && GS.StoredOnceValue)
Bill Wendlingf3baad32006-12-07 01:30:32 +00001214 cerr << " StoredOnceValue = " << *GS.StoredOnceValue << "\n";
Chris Lattner80a01ef2006-09-30 19:40:30 +00001215 if (GS.AccessingFunction && !GS.HasMultipleAccessingFunctions)
Bill Wendlingf3baad32006-12-07 01:30:32 +00001216 cerr << " AccessingFunction = " << GS.AccessingFunction->getName()
Chris Lattner80a01ef2006-09-30 19:40:30 +00001217 << "\n";
Bill Wendlingf3baad32006-12-07 01:30:32 +00001218 cerr << " HasMultipleAccessingFunctions = "
Chris Lattner80a01ef2006-09-30 19:40:30 +00001219 << GS.HasMultipleAccessingFunctions << "\n";
Bill Wendlingf3baad32006-12-07 01:30:32 +00001220 cerr << " HasNonInstructionUser = " << GS.HasNonInstructionUser<<"\n";
1221 cerr << " isNotSuitableForSRA = " << GS.isNotSuitableForSRA << "\n";
1222 cerr << "\n";
Chris Lattner80a01ef2006-09-30 19:40:30 +00001223#endif
1224
Alkis Evlogimenosc4a44c62005-02-10 18:36:30 +00001225 // If this is a first class global and has only one accessing function
1226 // and this function is main (which we know is not recursive we can make
1227 // this global a local variable) we replace the global with a local alloca
1228 // in this function.
1229 //
1230 // NOTE: It doesn't make sense to promote non first class types since we
1231 // are just replacing static memory to stack memory.
1232 if (!GS.HasMultipleAccessingFunctions &&
Chris Lattner50bdfcb2005-06-15 21:11:48 +00001233 GS.AccessingFunction && !GS.HasNonInstructionUser &&
Alkis Evlogimenosc4a44c62005-02-10 18:36:30 +00001234 GV->getType()->getElementType()->isFirstClassType() &&
1235 GS.AccessingFunction->getName() == "main" &&
1236 GS.AccessingFunction->hasExternalLinkage()) {
Bill Wendling8f13b5c2006-11-26 10:02:32 +00001237 DOUT << "LOCALIZING GLOBAL: " << *GV;
Alkis Evlogimenosc4a44c62005-02-10 18:36:30 +00001238 Instruction* FirstI = GS.AccessingFunction->getEntryBlock().begin();
1239 const Type* ElemTy = GV->getType()->getElementType();
Nate Begeman848622f2005-11-05 09:21:28 +00001240 // FIXME: Pass Global's alignment when globals have alignment
Alkis Evlogimenosc4a44c62005-02-10 18:36:30 +00001241 AllocaInst* Alloca = new AllocaInst(ElemTy, NULL, GV->getName(), FirstI);
1242 if (!isa<UndefValue>(GV->getInitializer()))
1243 new StoreInst(GV->getInitializer(), Alloca, FirstI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001244
Alkis Evlogimenosc4a44c62005-02-10 18:36:30 +00001245 GV->replaceAllUsesWith(Alloca);
1246 GV->eraseFromParent();
1247 ++NumLocalized;
1248 return true;
1249 }
Chris Lattner80a01ef2006-09-30 19:40:30 +00001250
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001251 // If the global is never loaded (but may be stored to), it is dead.
1252 // Delete it now.
1253 if (!GS.isLoaded) {
Bill Wendling8f13b5c2006-11-26 10:02:32 +00001254 DOUT << "GLOBAL NEVER LOADED: " << *GV;
Chris Lattnerf369b382004-10-09 03:32:52 +00001255
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001256 // Delete any stores we can find to the global. We may not be able to
1257 // make it completely dead though.
Chris Lattnercb9f1522004-10-10 16:43:46 +00001258 bool Changed = CleanupConstantGlobalUsers(GV, GV->getInitializer());
Chris Lattnerf369b382004-10-09 03:32:52 +00001259
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001260 // If the global is dead now, delete it.
1261 if (GV->use_empty()) {
Chris Lattner8e71c6a2004-10-16 18:09:00 +00001262 GV->eraseFromParent();
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001263 ++NumDeleted;
Chris Lattnerf369b382004-10-09 03:32:52 +00001264 Changed = true;
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001265 }
Chris Lattnerf369b382004-10-09 03:32:52 +00001266 return Changed;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001267
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001268 } else if (GS.StoredType <= GlobalStatus::isInitializerStored) {
Bill Wendling8f13b5c2006-11-26 10:02:32 +00001269 DOUT << "MARKING CONSTANT: " << *GV;
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001270 GV->setConstant(true);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001271
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001272 // Clean up any obviously simplifiable users now.
1273 CleanupConstantGlobalUsers(GV, GV->getInitializer());
Misha Brukmanb1c93172005-04-21 23:48:37 +00001274
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001275 // If the global is dead now, just nuke it.
1276 if (GV->use_empty()) {
Bill Wendling8f13b5c2006-11-26 10:02:32 +00001277 DOUT << " *** Marking constant allowed us to simplify "
1278 << "all users and delete global!\n";
Chris Lattner8e71c6a2004-10-16 18:09:00 +00001279 GV->eraseFromParent();
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001280 ++NumDeleted;
1281 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001282
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001283 ++NumMarked;
1284 return true;
1285 } else if (!GS.isNotSuitableForSRA &&
1286 !GV->getInitializer()->getType()->isFirstClassType()) {
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001287 if (GlobalVariable *FirstNewGV = SRAGlobal(GV)) {
1288 GVI = FirstNewGV; // Don't skip the newly produced globals!
1289 return true;
1290 }
Chris Lattner09a52722004-10-09 21:48:45 +00001291 } else if (GS.StoredType == GlobalStatus::isStoredOnce) {
Chris Lattner40e4cec2004-12-12 05:53:50 +00001292 // If the initial value for the global was an undef value, and if only
1293 // one other value was stored into it, we can just change the
1294 // initializer to be an undef value, then delete all stores to the
1295 // global. This allows us to mark it constant.
1296 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
1297 if (isa<UndefValue>(GV->getInitializer())) {
1298 // Change the initial value here.
1299 GV->setInitializer(SOVConstant);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001300
Chris Lattner40e4cec2004-12-12 05:53:50 +00001301 // Clean up any obviously simplifiable users now.
1302 CleanupConstantGlobalUsers(GV, GV->getInitializer());
Misha Brukmanb1c93172005-04-21 23:48:37 +00001303
Chris Lattner40e4cec2004-12-12 05:53:50 +00001304 if (GV->use_empty()) {
Bill Wendling8f13b5c2006-11-26 10:02:32 +00001305 DOUT << " *** Substituting initializer allowed us to "
1306 << "simplify all users and delete global!\n";
Chris Lattner40e4cec2004-12-12 05:53:50 +00001307 GV->eraseFromParent();
1308 ++NumDeleted;
1309 } else {
1310 GVI = GV;
1311 }
1312 ++NumSubstitute;
1313 return true;
Chris Lattner8e71c6a2004-10-16 18:09:00 +00001314 }
Chris Lattner8e71c6a2004-10-16 18:09:00 +00001315
Chris Lattner09a52722004-10-09 21:48:45 +00001316 // Try to optimize globals based on the knowledge that only one value
1317 // (besides its initializer) is ever stored to the global.
Chris Lattner004e2502004-10-11 05:54:41 +00001318 if (OptimizeOnceStoredGlobal(GV, GS.StoredOnceValue, GVI,
1319 getAnalysis<TargetData>()))
Chris Lattner09a52722004-10-09 21:48:45 +00001320 return true;
Chris Lattner40e4cec2004-12-12 05:53:50 +00001321
1322 // Otherwise, if the global was not a boolean, we can shrink it to be a
1323 // boolean.
1324 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
Chris Lattner1cbd5be2004-12-12 06:03:06 +00001325 if (GV->getType()->getElementType() != Type::BoolTy &&
Chris Lattner5a0bd612006-11-01 18:03:33 +00001326 !GV->getType()->getElementType()->isFloatingPoint() &&
1327 !GS.HasPHIUser) {
Bill Wendling8f13b5c2006-11-26 10:02:32 +00001328 DOUT << " *** SHRINKING TO BOOL: " << *GV;
Chris Lattner40e4cec2004-12-12 05:53:50 +00001329 ShrinkGlobalToBoolean(GV, SOVConstant);
1330 ++NumShrunkToBool;
1331 return true;
1332 }
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001333 }
1334 }
1335 return false;
1336}
1337
Chris Lattnera4c80222005-05-08 22:18:06 +00001338/// OnlyCalledDirectly - Return true if the specified function is only called
1339/// directly. In other words, its address is never taken.
1340static bool OnlyCalledDirectly(Function *F) {
1341 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
1342 Instruction *User = dyn_cast<Instruction>(*UI);
1343 if (!User) return false;
1344 if (!isa<CallInst>(User) && !isa<InvokeInst>(User)) return false;
1345
1346 // See if the function address is passed as an argument.
1347 for (unsigned i = 1, e = User->getNumOperands(); i != e; ++i)
1348 if (User->getOperand(i) == F) return false;
1349 }
1350 return true;
1351}
1352
1353/// ChangeCalleesToFastCall - Walk all of the direct calls of the specified
1354/// function, changing them to FastCC.
1355static void ChangeCalleesToFastCall(Function *F) {
1356 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
1357 Instruction *User = cast<Instruction>(*UI);
1358 if (CallInst *CI = dyn_cast<CallInst>(User))
1359 CI->setCallingConv(CallingConv::Fast);
1360 else
1361 cast<InvokeInst>(User)->setCallingConv(CallingConv::Fast);
1362 }
1363}
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001364
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001365bool GlobalOpt::OptimizeFunctions(Module &M) {
1366 bool Changed = false;
1367 // Optimize functions.
1368 for (Module::iterator FI = M.begin(), E = M.end(); FI != E; ) {
1369 Function *F = FI++;
1370 F->removeDeadConstantUsers();
1371 if (F->use_empty() && (F->hasInternalLinkage() ||
1372 F->hasLinkOnceLinkage())) {
1373 M.getFunctionList().erase(F);
1374 Changed = true;
1375 ++NumFnDeleted;
1376 } else if (F->hasInternalLinkage() &&
1377 F->getCallingConv() == CallingConv::C && !F->isVarArg() &&
1378 OnlyCalledDirectly(F)) {
1379 // If this function has C calling conventions, is not a varargs
1380 // function, and is only called directly, promote it to use the Fast
1381 // calling convention.
1382 F->setCallingConv(CallingConv::Fast);
1383 ChangeCalleesToFastCall(F);
1384 ++NumFastCallFns;
1385 Changed = true;
1386 }
1387 }
1388 return Changed;
1389}
1390
1391bool GlobalOpt::OptimizeGlobalVars(Module &M) {
1392 bool Changed = false;
1393 for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
1394 GVI != E; ) {
1395 GlobalVariable *GV = GVI++;
1396 if (!GV->isConstant() && GV->hasInternalLinkage() &&
1397 GV->hasInitializer())
1398 Changed |= ProcessInternalGlobal(GV, GVI);
1399 }
1400 return Changed;
1401}
1402
1403/// FindGlobalCtors - Find the llvm.globalctors list, verifying that all
1404/// initializers have an init priority of 65535.
1405GlobalVariable *GlobalOpt::FindGlobalCtors(Module &M) {
Alkis Evlogimenoscb67b652005-10-25 11:18:06 +00001406 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1407 I != E; ++I)
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001408 if (I->getName() == "llvm.global_ctors") {
1409 // Found it, verify it's an array of { int, void()* }.
1410 const ArrayType *ATy =dyn_cast<ArrayType>(I->getType()->getElementType());
1411 if (!ATy) return 0;
1412 const StructType *STy = dyn_cast<StructType>(ATy->getElementType());
1413 if (!STy || STy->getNumElements() != 2 ||
1414 STy->getElementType(0) != Type::IntTy) return 0;
1415 const PointerType *PFTy = dyn_cast<PointerType>(STy->getElementType(1));
1416 if (!PFTy) return 0;
1417 const FunctionType *FTy = dyn_cast<FunctionType>(PFTy->getElementType());
1418 if (!FTy || FTy->getReturnType() != Type::VoidTy || FTy->isVarArg() ||
1419 FTy->getNumParams() != 0)
1420 return 0;
1421
1422 // Verify that the initializer is simple enough for us to handle.
1423 if (!I->hasInitializer()) return 0;
1424 ConstantArray *CA = dyn_cast<ConstantArray>(I->getInitializer());
1425 if (!CA) return 0;
1426 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1427 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(CA->getOperand(i))) {
Chris Lattner838bdc12005-09-26 02:19:27 +00001428 if (isa<ConstantPointerNull>(CS->getOperand(1)))
1429 continue;
1430
1431 // Must have a function or null ptr.
1432 if (!isa<Function>(CS->getOperand(1)))
1433 return 0;
1434
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001435 // Init priority must be standard.
1436 ConstantInt *CI = dyn_cast<ConstantInt>(CS->getOperand(0));
Reid Spencere0fc4df2006-10-20 07:07:24 +00001437 if (!CI || CI->getZExtValue() != 65535)
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001438 return 0;
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001439 } else {
1440 return 0;
1441 }
1442
1443 return I;
1444 }
1445 return 0;
1446}
1447
Chris Lattner696beef2005-09-26 02:31:18 +00001448/// ParseGlobalCtors - Given a llvm.global_ctors list that we can understand,
1449/// return a list of the functions and null terminator as a vector.
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001450static std::vector<Function*> ParseGlobalCtors(GlobalVariable *GV) {
1451 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
1452 std::vector<Function*> Result;
1453 Result.reserve(CA->getNumOperands());
1454 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i) {
1455 ConstantStruct *CS = cast<ConstantStruct>(CA->getOperand(i));
1456 Result.push_back(dyn_cast<Function>(CS->getOperand(1)));
1457 }
1458 return Result;
1459}
1460
Chris Lattner696beef2005-09-26 02:31:18 +00001461/// InstallGlobalCtors - Given a specified llvm.global_ctors list, install the
1462/// specified array, returning the new global to use.
1463static GlobalVariable *InstallGlobalCtors(GlobalVariable *GCL,
1464 const std::vector<Function*> &Ctors) {
1465 // If we made a change, reassemble the initializer list.
1466 std::vector<Constant*> CSVals;
Reid Spencere0fc4df2006-10-20 07:07:24 +00001467 CSVals.push_back(ConstantInt::get(Type::IntTy, 65535));
Chris Lattner696beef2005-09-26 02:31:18 +00001468 CSVals.push_back(0);
1469
1470 // Create the new init list.
1471 std::vector<Constant*> CAList;
1472 for (unsigned i = 0, e = Ctors.size(); i != e; ++i) {
Chris Lattner99e23fa2005-09-26 04:44:35 +00001473 if (Ctors[i]) {
Chris Lattner696beef2005-09-26 02:31:18 +00001474 CSVals[1] = Ctors[i];
Chris Lattner99e23fa2005-09-26 04:44:35 +00001475 } else {
Chris Lattner696beef2005-09-26 02:31:18 +00001476 const Type *FTy = FunctionType::get(Type::VoidTy,
1477 std::vector<const Type*>(), false);
1478 const PointerType *PFTy = PointerType::get(FTy);
1479 CSVals[1] = Constant::getNullValue(PFTy);
Reid Spencere0fc4df2006-10-20 07:07:24 +00001480 CSVals[0] = ConstantInt::get(Type::IntTy, 2147483647);
Chris Lattner696beef2005-09-26 02:31:18 +00001481 }
1482 CAList.push_back(ConstantStruct::get(CSVals));
1483 }
1484
1485 // Create the array initializer.
1486 const Type *StructTy =
1487 cast<ArrayType>(GCL->getType()->getElementType())->getElementType();
1488 Constant *CA = ConstantArray::get(ArrayType::get(StructTy, CAList.size()),
1489 CAList);
1490
1491 // If we didn't change the number of elements, don't create a new GV.
1492 if (CA->getType() == GCL->getInitializer()->getType()) {
1493 GCL->setInitializer(CA);
1494 return GCL;
1495 }
1496
1497 // Create the new global and insert it next to the existing list.
1498 GlobalVariable *NGV = new GlobalVariable(CA->getType(), GCL->isConstant(),
1499 GCL->getLinkage(), CA,
1500 GCL->getName());
1501 GCL->setName("");
1502 GCL->getParent()->getGlobalList().insert(GCL, NGV);
1503
1504 // Nuke the old list, replacing any uses with the new one.
1505 if (!GCL->use_empty()) {
1506 Constant *V = NGV;
1507 if (V->getType() != GCL->getType())
Reid Spencerbb65ebf2006-12-12 23:36:14 +00001508 V = ConstantExpr::getBitCast(V, GCL->getType());
Chris Lattner696beef2005-09-26 02:31:18 +00001509 GCL->replaceAllUsesWith(V);
1510 }
1511 GCL->eraseFromParent();
1512
1513 if (Ctors.size())
1514 return NGV;
1515 else
1516 return 0;
1517}
Chris Lattner99e23fa2005-09-26 04:44:35 +00001518
1519
1520static Constant *getVal(std::map<Value*, Constant*> &ComputedValues,
1521 Value *V) {
1522 if (Constant *CV = dyn_cast<Constant>(V)) return CV;
1523 Constant *R = ComputedValues[V];
1524 assert(R && "Reference to an uncomputed value!");
1525 return R;
1526}
1527
1528/// isSimpleEnoughPointerToCommit - Return true if this constant is simple
1529/// enough for us to understand. In particular, if it is a cast of something,
1530/// we punt. We basically just support direct accesses to globals and GEP's of
1531/// globals. This should be kept up to date with CommitValueTo.
1532static bool isSimpleEnoughPointerToCommit(Constant *C) {
Chris Lattner29b27802005-09-27 04:50:03 +00001533 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
1534 if (!GV->hasExternalLinkage() && !GV->hasInternalLinkage())
Anton Korobeynikovd61d39e2006-09-14 18:23:27 +00001535 return false; // do not allow weak/linkonce/dllimport/dllexport linkage.
Chris Lattner99e23fa2005-09-26 04:44:35 +00001536 return !GV->isExternal(); // reject external globals.
Chris Lattner29b27802005-09-27 04:50:03 +00001537 }
Chris Lattner46af55e2005-09-26 06:52:44 +00001538 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
1539 // Handle a constantexpr gep.
1540 if (CE->getOpcode() == Instruction::GetElementPtr &&
1541 isa<GlobalVariable>(CE->getOperand(0))) {
1542 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
Chris Lattner29b27802005-09-27 04:50:03 +00001543 if (!GV->hasExternalLinkage() && !GV->hasInternalLinkage())
Anton Korobeynikovd61d39e2006-09-14 18:23:27 +00001544 return false; // do not allow weak/linkonce/dllimport/dllexport linkage.
Chris Lattner46af55e2005-09-26 06:52:44 +00001545 return GV->hasInitializer() &&
1546 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
1547 }
Chris Lattner99e23fa2005-09-26 04:44:35 +00001548 return false;
1549}
1550
Chris Lattner46af55e2005-09-26 06:52:44 +00001551/// EvaluateStoreInto - Evaluate a piece of a constantexpr store into a global
1552/// initializer. This returns 'Init' modified to reflect 'Val' stored into it.
1553/// At this point, the GEP operands of Addr [0, OpNo) have been stepped into.
1554static Constant *EvaluateStoreInto(Constant *Init, Constant *Val,
1555 ConstantExpr *Addr, unsigned OpNo) {
1556 // Base case of the recursion.
1557 if (OpNo == Addr->getNumOperands()) {
1558 assert(Val->getType() == Init->getType() && "Type mismatch!");
1559 return Val;
1560 }
1561
1562 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
1563 std::vector<Constant*> Elts;
1564
1565 // Break up the constant into its elements.
1566 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
1567 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i)
1568 Elts.push_back(CS->getOperand(i));
1569 } else if (isa<ConstantAggregateZero>(Init)) {
1570 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
1571 Elts.push_back(Constant::getNullValue(STy->getElementType(i)));
1572 } else if (isa<UndefValue>(Init)) {
1573 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
1574 Elts.push_back(UndefValue::get(STy->getElementType(i)));
1575 } else {
1576 assert(0 && "This code is out of sync with "
1577 " ConstantFoldLoadThroughGEPConstantExpr");
1578 }
1579
1580 // Replace the element that we are supposed to.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001581 ConstantInt *CU = cast<ConstantInt>(Addr->getOperand(OpNo));
1582 unsigned Idx = CU->getZExtValue();
1583 assert(Idx < STy->getNumElements() && "Struct index out of range!");
Chris Lattner46af55e2005-09-26 06:52:44 +00001584 Elts[Idx] = EvaluateStoreInto(Elts[Idx], Val, Addr, OpNo+1);
1585
1586 // Return the modified struct.
1587 return ConstantStruct::get(Elts);
1588 } else {
1589 ConstantInt *CI = cast<ConstantInt>(Addr->getOperand(OpNo));
1590 const ArrayType *ATy = cast<ArrayType>(Init->getType());
1591
1592 // Break up the array into elements.
1593 std::vector<Constant*> Elts;
1594 if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
1595 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1596 Elts.push_back(CA->getOperand(i));
1597 } else if (isa<ConstantAggregateZero>(Init)) {
1598 Constant *Elt = Constant::getNullValue(ATy->getElementType());
1599 Elts.assign(ATy->getNumElements(), Elt);
1600 } else if (isa<UndefValue>(Init)) {
1601 Constant *Elt = UndefValue::get(ATy->getElementType());
1602 Elts.assign(ATy->getNumElements(), Elt);
1603 } else {
1604 assert(0 && "This code is out of sync with "
1605 " ConstantFoldLoadThroughGEPConstantExpr");
1606 }
1607
Reid Spencere0fc4df2006-10-20 07:07:24 +00001608 assert(CI->getZExtValue() < ATy->getNumElements());
1609 Elts[CI->getZExtValue()] =
1610 EvaluateStoreInto(Elts[CI->getZExtValue()], Val, Addr, OpNo+1);
Chris Lattner46af55e2005-09-26 06:52:44 +00001611 return ConstantArray::get(ATy, Elts);
1612 }
1613}
1614
Chris Lattner99e23fa2005-09-26 04:44:35 +00001615/// CommitValueTo - We have decided that Addr (which satisfies the predicate
1616/// isSimpleEnoughPointerToCommit) should get Val as its value. Make it happen.
1617static void CommitValueTo(Constant *Val, Constant *Addr) {
Chris Lattner46af55e2005-09-26 06:52:44 +00001618 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Addr)) {
1619 assert(GV->hasInitializer());
1620 GV->setInitializer(Val);
1621 return;
1622 }
1623
1624 ConstantExpr *CE = cast<ConstantExpr>(Addr);
1625 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
1626
1627 Constant *Init = GV->getInitializer();
1628 Init = EvaluateStoreInto(Init, Val, CE, 2);
1629 GV->setInitializer(Init);
Chris Lattner99e23fa2005-09-26 04:44:35 +00001630}
1631
Chris Lattnerb0096632005-09-26 05:16:34 +00001632/// ComputeLoadResult - Return the value that would be computed by a load from
1633/// P after the stores reflected by 'memory' have been performed. If we can't
1634/// decide, return null.
Chris Lattner4b05c322005-09-26 05:15:37 +00001635static Constant *ComputeLoadResult(Constant *P,
1636 const std::map<Constant*, Constant*> &Memory) {
1637 // If this memory location has been recently stored, use the stored value: it
1638 // is the most up-to-date.
1639 std::map<Constant*, Constant*>::const_iterator I = Memory.find(P);
1640 if (I != Memory.end()) return I->second;
1641
1642 // Access it.
1643 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(P)) {
1644 if (GV->hasInitializer())
1645 return GV->getInitializer();
1646 return 0;
Chris Lattner4b05c322005-09-26 05:15:37 +00001647 }
Chris Lattner46af55e2005-09-26 06:52:44 +00001648
1649 // Handle a constantexpr getelementptr.
1650 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(P))
1651 if (CE->getOpcode() == Instruction::GetElementPtr &&
1652 isa<GlobalVariable>(CE->getOperand(0))) {
1653 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
1654 if (GV->hasInitializer())
1655 return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
1656 }
1657
1658 return 0; // don't know how to evaluate.
Chris Lattner4b05c322005-09-26 05:15:37 +00001659}
1660
Chris Lattnerda1889b2005-09-27 04:27:01 +00001661/// EvaluateFunction - Evaluate a call to function F, returning true if
1662/// successful, false if we can't evaluate it. ActualArgs contains the formal
1663/// arguments for the function.
Chris Lattner65a3a092005-09-27 04:45:34 +00001664static bool EvaluateFunction(Function *F, Constant *&RetVal,
Chris Lattnerda1889b2005-09-27 04:27:01 +00001665 const std::vector<Constant*> &ActualArgs,
1666 std::vector<Function*> &CallStack,
1667 std::map<Constant*, Constant*> &MutatedMemory,
1668 std::vector<GlobalVariable*> &AllocaTmps) {
Chris Lattner65a3a092005-09-27 04:45:34 +00001669 // Check to see if this function is already executing (recursion). If so,
1670 // bail out. TODO: we might want to accept limited recursion.
1671 if (std::find(CallStack.begin(), CallStack.end(), F) != CallStack.end())
1672 return false;
1673
1674 CallStack.push_back(F);
1675
Chris Lattner99e23fa2005-09-26 04:44:35 +00001676 /// Values - As we compute SSA register values, we store their contents here.
1677 std::map<Value*, Constant*> Values;
Chris Lattner65a3a092005-09-27 04:45:34 +00001678
1679 // Initialize arguments to the incoming values specified.
1680 unsigned ArgNo = 0;
1681 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); AI != E;
1682 ++AI, ++ArgNo)
1683 Values[AI] = ActualArgs[ArgNo];
Chris Lattnerda1889b2005-09-27 04:27:01 +00001684
Chris Lattner3e9ea5f2005-09-26 04:57:38 +00001685 /// ExecutedBlocks - We only handle non-looping, non-recursive code. As such,
1686 /// we can only evaluate any one basic block at most once. This set keeps
1687 /// track of what we have executed so we can detect recursive cases etc.
1688 std::set<BasicBlock*> ExecutedBlocks;
Chris Lattner6bf2cd52005-09-26 17:07:09 +00001689
Chris Lattner99e23fa2005-09-26 04:44:35 +00001690 // CurInst - The current instruction we're evaluating.
1691 BasicBlock::iterator CurInst = F->begin()->begin();
1692
1693 // This is the main evaluation loop.
1694 while (1) {
1695 Constant *InstResult = 0;
1696
1697 if (StoreInst *SI = dyn_cast<StoreInst>(CurInst)) {
Chris Lattner65a3a092005-09-27 04:45:34 +00001698 if (SI->isVolatile()) return false; // no volatile accesses.
Chris Lattner99e23fa2005-09-26 04:44:35 +00001699 Constant *Ptr = getVal(Values, SI->getOperand(1));
1700 if (!isSimpleEnoughPointerToCommit(Ptr))
1701 // If this is too complex for us to commit, reject it.
Chris Lattner65a3a092005-09-27 04:45:34 +00001702 return false;
Chris Lattner99e23fa2005-09-26 04:44:35 +00001703 Constant *Val = getVal(Values, SI->getOperand(0));
1704 MutatedMemory[Ptr] = Val;
1705 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CurInst)) {
1706 InstResult = ConstantExpr::get(BO->getOpcode(),
1707 getVal(Values, BO->getOperand(0)),
1708 getVal(Values, BO->getOperand(1)));
1709 } else if (ShiftInst *SI = dyn_cast<ShiftInst>(CurInst)) {
1710 InstResult = ConstantExpr::get(SI->getOpcode(),
1711 getVal(Values, SI->getOperand(0)),
1712 getVal(Values, SI->getOperand(1)));
1713 } else if (CastInst *CI = dyn_cast<CastInst>(CurInst)) {
Chris Lattner0390b9e2006-11-30 17:26:08 +00001714 InstResult = ConstantExpr::getCast(CI->getOpcode(),
1715 getVal(Values, CI->getOperand(0)),
Chris Lattner99e23fa2005-09-26 04:44:35 +00001716 CI->getType());
1717 } else if (SelectInst *SI = dyn_cast<SelectInst>(CurInst)) {
1718 InstResult = ConstantExpr::getSelect(getVal(Values, SI->getOperand(0)),
1719 getVal(Values, SI->getOperand(1)),
1720 getVal(Values, SI->getOperand(2)));
Chris Lattner4b05c322005-09-26 05:15:37 +00001721 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurInst)) {
1722 Constant *P = getVal(Values, GEP->getOperand(0));
1723 std::vector<Constant*> GEPOps;
1724 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
1725 GEPOps.push_back(getVal(Values, GEP->getOperand(i)));
1726 InstResult = ConstantExpr::getGetElementPtr(P, GEPOps);
1727 } else if (LoadInst *LI = dyn_cast<LoadInst>(CurInst)) {
Chris Lattner65a3a092005-09-27 04:45:34 +00001728 if (LI->isVolatile()) return false; // no volatile accesses.
Chris Lattner4b05c322005-09-26 05:15:37 +00001729 InstResult = ComputeLoadResult(getVal(Values, LI->getOperand(0)),
1730 MutatedMemory);
Chris Lattner65a3a092005-09-27 04:45:34 +00001731 if (InstResult == 0) return false; // Could not evaluate load.
Chris Lattner6bf2cd52005-09-26 17:07:09 +00001732 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(CurInst)) {
Chris Lattner65a3a092005-09-27 04:45:34 +00001733 if (AI->isArrayAllocation()) return false; // Cannot handle array allocs.
Chris Lattner6bf2cd52005-09-26 17:07:09 +00001734 const Type *Ty = AI->getType()->getElementType();
1735 AllocaTmps.push_back(new GlobalVariable(Ty, false,
1736 GlobalValue::InternalLinkage,
1737 UndefValue::get(Ty),
1738 AI->getName()));
Chris Lattner65a3a092005-09-27 04:45:34 +00001739 InstResult = AllocaTmps.back();
1740 } else if (CallInst *CI = dyn_cast<CallInst>(CurInst)) {
Chris Lattnerfd2e13b2006-07-07 21:37:01 +00001741 // Cannot handle inline asm.
1742 if (isa<InlineAsm>(CI->getOperand(0))) return false;
1743
Chris Lattner65a3a092005-09-27 04:45:34 +00001744 // Resolve function pointers.
1745 Function *Callee = dyn_cast<Function>(getVal(Values, CI->getOperand(0)));
1746 if (!Callee) return false; // Cannot resolve.
Chris Lattner3d27e7f2005-09-27 05:02:43 +00001747
Chris Lattner65a3a092005-09-27 04:45:34 +00001748 std::vector<Constant*> Formals;
1749 for (unsigned i = 1, e = CI->getNumOperands(); i != e; ++i)
1750 Formals.push_back(getVal(Values, CI->getOperand(i)));
Chris Lattner65a3a092005-09-27 04:45:34 +00001751
Chris Lattner3d27e7f2005-09-27 05:02:43 +00001752 if (Callee->isExternal()) {
1753 // If this is a function we can constant fold, do it.
1754 if (Constant *C = ConstantFoldCall(Callee, Formals)) {
1755 InstResult = C;
1756 } else {
1757 return false;
1758 }
1759 } else {
1760 if (Callee->getFunctionType()->isVarArg())
1761 return false;
1762
1763 Constant *RetVal;
1764
1765 // Execute the call, if successful, use the return value.
1766 if (!EvaluateFunction(Callee, RetVal, Formals, CallStack,
1767 MutatedMemory, AllocaTmps))
1768 return false;
1769 InstResult = RetVal;
1770 }
Reid Spencerde46e482006-11-02 20:25:50 +00001771 } else if (isa<TerminatorInst>(CurInst)) {
Chris Lattner3e9ea5f2005-09-26 04:57:38 +00001772 BasicBlock *NewBB = 0;
1773 if (BranchInst *BI = dyn_cast<BranchInst>(CurInst)) {
1774 if (BI->isUnconditional()) {
1775 NewBB = BI->getSuccessor(0);
1776 } else {
1777 ConstantBool *Cond =
1778 dyn_cast<ConstantBool>(getVal(Values, BI->getCondition()));
Chris Lattner65a3a092005-09-27 04:45:34 +00001779 if (!Cond) return false; // Cannot determine.
Chris Lattner3e9ea5f2005-09-26 04:57:38 +00001780 NewBB = BI->getSuccessor(!Cond->getValue());
1781 }
1782 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(CurInst)) {
1783 ConstantInt *Val =
1784 dyn_cast<ConstantInt>(getVal(Values, SI->getCondition()));
Chris Lattner65a3a092005-09-27 04:45:34 +00001785 if (!Val) return false; // Cannot determine.
Chris Lattner3e9ea5f2005-09-26 04:57:38 +00001786 NewBB = SI->getSuccessor(SI->findCaseValue(Val));
1787 } else if (ReturnInst *RI = dyn_cast<ReturnInst>(CurInst)) {
Chris Lattner65a3a092005-09-27 04:45:34 +00001788 if (RI->getNumOperands())
1789 RetVal = getVal(Values, RI->getOperand(0));
1790
1791 CallStack.pop_back(); // return from fn.
Chris Lattnerda1889b2005-09-27 04:27:01 +00001792 return true; // We succeeded at evaluating this ctor!
Chris Lattner3e9ea5f2005-09-26 04:57:38 +00001793 } else {
Chris Lattner65a3a092005-09-27 04:45:34 +00001794 // invoke, unwind, unreachable.
1795 return false; // Cannot handle this terminator.
Chris Lattner3e9ea5f2005-09-26 04:57:38 +00001796 }
1797
1798 // Okay, we succeeded in evaluating this control flow. See if we have
Chris Lattner65a3a092005-09-27 04:45:34 +00001799 // executed the new block before. If so, we have a looping function,
1800 // which we cannot evaluate in reasonable time.
Chris Lattner3e9ea5f2005-09-26 04:57:38 +00001801 if (!ExecutedBlocks.insert(NewBB).second)
Chris Lattner65a3a092005-09-27 04:45:34 +00001802 return false; // looped!
Chris Lattner3e9ea5f2005-09-26 04:57:38 +00001803
1804 // Okay, we have never been in this block before. Check to see if there
1805 // are any PHI nodes. If so, evaluate them with information about where
1806 // we came from.
1807 BasicBlock *OldBB = CurInst->getParent();
1808 CurInst = NewBB->begin();
1809 PHINode *PN;
1810 for (; (PN = dyn_cast<PHINode>(CurInst)); ++CurInst)
1811 Values[PN] = getVal(Values, PN->getIncomingValueForBlock(OldBB));
1812
1813 // Do NOT increment CurInst. We know that the terminator had no value.
1814 continue;
Chris Lattner99e23fa2005-09-26 04:44:35 +00001815 } else {
Chris Lattner99e23fa2005-09-26 04:44:35 +00001816 // Did not know how to evaluate this!
Chris Lattner65a3a092005-09-27 04:45:34 +00001817 return false;
Chris Lattner99e23fa2005-09-26 04:44:35 +00001818 }
1819
1820 if (!CurInst->use_empty())
1821 Values[CurInst] = InstResult;
1822
1823 // Advance program counter.
1824 ++CurInst;
1825 }
Chris Lattnerda1889b2005-09-27 04:27:01 +00001826}
1827
1828/// EvaluateStaticConstructor - Evaluate static constructors in the function, if
1829/// we can. Return true if we can, false otherwise.
1830static bool EvaluateStaticConstructor(Function *F) {
1831 /// MutatedMemory - For each store we execute, we update this map. Loads
1832 /// check this to get the most up-to-date value. If evaluation is successful,
1833 /// this state is committed to the process.
1834 std::map<Constant*, Constant*> MutatedMemory;
1835
1836 /// AllocaTmps - To 'execute' an alloca, we create a temporary global variable
1837 /// to represent its body. This vector is needed so we can delete the
1838 /// temporary globals when we are done.
1839 std::vector<GlobalVariable*> AllocaTmps;
1840
1841 /// CallStack - This is used to detect recursion. In pathological situations
1842 /// we could hit exponential behavior, but at least there is nothing
1843 /// unbounded.
1844 std::vector<Function*> CallStack;
1845
1846 // Call the function.
Chris Lattner65a3a092005-09-27 04:45:34 +00001847 Constant *RetValDummy;
1848 bool EvalSuccess = EvaluateFunction(F, RetValDummy, std::vector<Constant*>(),
1849 CallStack, MutatedMemory, AllocaTmps);
Chris Lattnerda1889b2005-09-27 04:27:01 +00001850 if (EvalSuccess) {
Chris Lattner6bf2cd52005-09-26 17:07:09 +00001851 // We succeeded at evaluation: commit the result.
Bill Wendling8f13b5c2006-11-26 10:02:32 +00001852 DOUT << "FULLY EVALUATED GLOBAL CTOR FUNCTION '"
1853 << F->getName() << "' to " << MutatedMemory.size()
1854 << " stores.\n";
Chris Lattner6bf2cd52005-09-26 17:07:09 +00001855 for (std::map<Constant*, Constant*>::iterator I = MutatedMemory.begin(),
1856 E = MutatedMemory.end(); I != E; ++I)
1857 CommitValueTo(I->second, I->first);
1858 }
Chris Lattner99e23fa2005-09-26 04:44:35 +00001859
Chris Lattner6bf2cd52005-09-26 17:07:09 +00001860 // At this point, we are done interpreting. If we created any 'alloca'
1861 // temporaries, release them now.
1862 while (!AllocaTmps.empty()) {
1863 GlobalVariable *Tmp = AllocaTmps.back();
1864 AllocaTmps.pop_back();
Chris Lattnerda1889b2005-09-27 04:27:01 +00001865
Chris Lattner6bf2cd52005-09-26 17:07:09 +00001866 // If there are still users of the alloca, the program is doing something
1867 // silly, e.g. storing the address of the alloca somewhere and using it
1868 // later. Since this is undefined, we'll just make it be null.
1869 if (!Tmp->use_empty())
1870 Tmp->replaceAllUsesWith(Constant::getNullValue(Tmp->getType()));
1871 delete Tmp;
1872 }
Chris Lattner46d9ff082005-09-26 07:34:35 +00001873
Chris Lattnerda1889b2005-09-27 04:27:01 +00001874 return EvalSuccess;
Chris Lattner99e23fa2005-09-26 04:44:35 +00001875}
1876
Chris Lattner696beef2005-09-26 02:31:18 +00001877
Chris Lattnerda1889b2005-09-27 04:27:01 +00001878
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001879/// OptimizeGlobalCtorsList - Simplify and evaluation global ctors if possible.
1880/// Return true if anything changed.
1881bool GlobalOpt::OptimizeGlobalCtorsList(GlobalVariable *&GCL) {
1882 std::vector<Function*> Ctors = ParseGlobalCtors(GCL);
1883 bool MadeChange = false;
1884 if (Ctors.empty()) return false;
1885
1886 // Loop over global ctors, optimizing them when we can.
1887 for (unsigned i = 0; i != Ctors.size(); ++i) {
1888 Function *F = Ctors[i];
1889 // Found a null terminator in the middle of the list, prune off the rest of
1890 // the list.
Chris Lattner838bdc12005-09-26 02:19:27 +00001891 if (F == 0) {
1892 if (i != Ctors.size()-1) {
1893 Ctors.resize(i+1);
1894 MadeChange = true;
1895 }
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001896 break;
1897 }
1898
Chris Lattner99e23fa2005-09-26 04:44:35 +00001899 // We cannot simplify external ctor functions.
1900 if (F->empty()) continue;
1901
1902 // If we can evaluate the ctor at compile time, do.
1903 if (EvaluateStaticConstructor(F)) {
1904 Ctors.erase(Ctors.begin()+i);
1905 MadeChange = true;
1906 --i;
1907 ++NumCtorsEvaluated;
1908 continue;
1909 }
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001910 }
1911
1912 if (!MadeChange) return false;
1913
Chris Lattner696beef2005-09-26 02:31:18 +00001914 GCL = InstallGlobalCtors(GCL, Ctors);
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001915 return true;
1916}
1917
1918
Chris Lattner25db5802004-10-07 04:16:33 +00001919bool GlobalOpt::runOnModule(Module &M) {
1920 bool Changed = false;
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001921
1922 // Try to find the llvm.globalctors list.
1923 GlobalVariable *GlobalCtors = FindGlobalCtors(M);
Chris Lattner25db5802004-10-07 04:16:33 +00001924
Chris Lattner25db5802004-10-07 04:16:33 +00001925 bool LocalChange = true;
1926 while (LocalChange) {
1927 LocalChange = false;
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001928
1929 // Delete functions that are trivially dead, ccc -> fastcc
1930 LocalChange |= OptimizeFunctions(M);
1931
1932 // Optimize global_ctors list.
1933 if (GlobalCtors)
1934 LocalChange |= OptimizeGlobalCtorsList(GlobalCtors);
1935
1936 // Optimize non-address-taken globals.
1937 LocalChange |= OptimizeGlobalVars(M);
Chris Lattner25db5802004-10-07 04:16:33 +00001938 Changed |= LocalChange;
1939 }
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001940
1941 // TODO: Move all global ctors functions to the end of the module for code
1942 // layout.
1943
Chris Lattner25db5802004-10-07 04:16:33 +00001944 return Changed;
1945}