blob: 826f81e5932096233872aa6f1a945642dd2a8108 [file] [log] [blame]
Chris Lattner7a90b682004-10-07 04:16:33 +00001//===- GlobalOpt.cpp - Optimize Global Variables --------------------------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
Chris Lattner079236d2004-02-25 21:34:36 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
Chris Lattner079236d2004-02-25 21:34:36 +00008//===----------------------------------------------------------------------===//
9//
Chris Lattner7a90b682004-10-07 04:16:33 +000010// This pass transforms simple global variables that never have their address
11// taken. If obviously true, it marks read/write globals as constant, deletes
12// variables only stored to, etc.
Chris Lattner079236d2004-02-25 21:34:36 +000013//
14//===----------------------------------------------------------------------===//
15
Chris Lattner7a90b682004-10-07 04:16:33 +000016#define DEBUG_TYPE "globalopt"
Chris Lattner079236d2004-02-25 21:34:36 +000017#include "llvm/Transforms/IPO.h"
Chris Lattnerfb217ad2005-05-08 22:18:06 +000018#include "llvm/CallingConv.h"
Chris Lattner079236d2004-02-25 21:34:36 +000019#include "llvm/Constants.h"
Chris Lattner7a90b682004-10-07 04:16:33 +000020#include "llvm/DerivedTypes.h"
Chris Lattner7d90a272004-02-27 18:09:25 +000021#include "llvm/Instructions.h"
Chris Lattner35c81b02005-02-27 18:58:52 +000022#include "llvm/IntrinsicInst.h"
Chris Lattner079236d2004-02-25 21:34:36 +000023#include "llvm/Module.h"
24#include "llvm/Pass.h"
Chris Lattner79066fa2007-01-30 23:46:24 +000025#include "llvm/Analysis/ConstantFolding.h"
Chris Lattner30ba5692004-10-11 05:54:41 +000026#include "llvm/Target/TargetData.h"
Reid Spencer9133fe22007-02-05 23:32:05 +000027#include "llvm/Support/Compiler.h"
Chris Lattner79066fa2007-01-30 23:46:24 +000028#include "llvm/Support/Debug.h"
Chris Lattner81686182007-09-13 16:30:19 +000029#include "llvm/ADT/SmallPtrSet.h"
Chris Lattner55eb1c42007-01-31 04:40:53 +000030#include "llvm/ADT/SmallVector.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000031#include "llvm/ADT/Statistic.h"
Chris Lattner670c8892004-10-08 17:32:09 +000032#include "llvm/ADT/StringExtras.h"
Chris Lattnere47ba742004-10-06 20:57:02 +000033#include <algorithm>
Chris Lattnerdac58ad2006-01-22 23:32:06 +000034#include <set>
Chris Lattner079236d2004-02-25 21:34:36 +000035using namespace llvm;
36
Chris Lattner86453c52006-12-19 22:09:18 +000037STATISTIC(NumMarked , "Number of globals marked constant");
38STATISTIC(NumSRA , "Number of aggregate globals broken into scalars");
39STATISTIC(NumHeapSRA , "Number of heap objects SRA'd");
40STATISTIC(NumSubstitute,"Number of globals with initializers stored into them");
41STATISTIC(NumDeleted , "Number of globals deleted");
42STATISTIC(NumFnDeleted , "Number of functions deleted");
43STATISTIC(NumGlobUses , "Number of global uses devirtualized");
44STATISTIC(NumLocalized , "Number of globals localized");
45STATISTIC(NumShrunkToBool , "Number of global vars shrunk to booleans");
46STATISTIC(NumFastCallFns , "Number of functions converted to fastcc");
47STATISTIC(NumCtorsEvaluated, "Number of static ctors evaluated");
Chris Lattner079236d2004-02-25 21:34:36 +000048
Chris Lattner86453c52006-12-19 22:09:18 +000049namespace {
Reid Spencer9133fe22007-02-05 23:32:05 +000050 struct VISIBILITY_HIDDEN GlobalOpt : public ModulePass {
Chris Lattner30ba5692004-10-11 05:54:41 +000051 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
52 AU.addRequired<TargetData>();
53 }
Nick Lewyckyecd94c82007-05-06 13:37:16 +000054 static char ID; // Pass identification, replacement for typeid
Devang Patel794fd752007-05-01 21:15:47 +000055 GlobalOpt() : ModulePass((intptr_t)&ID) {}
Misha Brukmanfd939082005-04-21 23:48:37 +000056
Chris Lattnerb12914b2004-09-20 04:48:05 +000057 bool runOnModule(Module &M);
Chris Lattner30ba5692004-10-11 05:54:41 +000058
59 private:
Chris Lattnerb1ab4582005-09-26 01:43:45 +000060 GlobalVariable *FindGlobalCtors(Module &M);
61 bool OptimizeFunctions(Module &M);
62 bool OptimizeGlobalVars(Module &M);
63 bool OptimizeGlobalCtorsList(GlobalVariable *&GCL);
Chris Lattner7f8897f2006-08-27 22:42:52 +000064 bool ProcessInternalGlobal(GlobalVariable *GV,Module::global_iterator &GVI);
Chris Lattner079236d2004-02-25 21:34:36 +000065 };
66
Devang Patel19974732007-05-03 01:11:54 +000067 char GlobalOpt::ID = 0;
Chris Lattner7f8897f2006-08-27 22:42:52 +000068 RegisterPass<GlobalOpt> X("globalopt", "Global Variable Optimizer");
Chris Lattner079236d2004-02-25 21:34:36 +000069}
70
Chris Lattner7a90b682004-10-07 04:16:33 +000071ModulePass *llvm::createGlobalOptimizerPass() { return new GlobalOpt(); }
Chris Lattner079236d2004-02-25 21:34:36 +000072
Chris Lattner7a90b682004-10-07 04:16:33 +000073/// GlobalStatus - As we analyze each global, keep track of some information
74/// about it. If we find out that the address of the global is taken, none of
Chris Lattnercf4d2a52004-10-07 21:30:30 +000075/// this info will be accurate.
Reid Spencer9133fe22007-02-05 23:32:05 +000076struct VISIBILITY_HIDDEN GlobalStatus {
Chris Lattnercf4d2a52004-10-07 21:30:30 +000077 /// isLoaded - True if the global is ever loaded. If the global isn't ever
78 /// loaded it can be deleted.
Chris Lattner7a90b682004-10-07 04:16:33 +000079 bool isLoaded;
Chris Lattnercf4d2a52004-10-07 21:30:30 +000080
81 /// StoredType - Keep track of what stores to the global look like.
82 ///
Chris Lattner7a90b682004-10-07 04:16:33 +000083 enum StoredType {
Chris Lattnercf4d2a52004-10-07 21:30:30 +000084 /// NotStored - There is no store to this global. It can thus be marked
85 /// constant.
86 NotStored,
87
88 /// isInitializerStored - This global is stored to, but the only thing
89 /// stored is the constant it was initialized with. This is only tracked
90 /// for scalar globals.
91 isInitializerStored,
92
93 /// isStoredOnce - This global is stored to, but only its initializer and
94 /// one other value is ever stored to it. If this global isStoredOnce, we
95 /// track the value stored to it in StoredOnceValue below. This is only
96 /// tracked for scalar globals.
97 isStoredOnce,
98
99 /// isStored - This global is stored to by multiple values or something else
100 /// that we cannot track.
101 isStored
Chris Lattner7a90b682004-10-07 04:16:33 +0000102 } StoredType;
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000103
104 /// StoredOnceValue - If only one value (besides the initializer constant) is
105 /// ever stored to this global, keep track of what value it is.
106 Value *StoredOnceValue;
107
Chris Lattner25de4e52006-11-01 18:03:33 +0000108 /// AccessingFunction/HasMultipleAccessingFunctions - These start out
109 /// null/false. When the first accessing function is noticed, it is recorded.
110 /// When a second different accessing function is noticed,
111 /// HasMultipleAccessingFunctions is set to true.
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +0000112 Function *AccessingFunction;
113 bool HasMultipleAccessingFunctions;
114
Chris Lattner25de4e52006-11-01 18:03:33 +0000115 /// HasNonInstructionUser - Set to true if this global has a user that is not
116 /// an instruction (e.g. a constant expr or GV initializer).
Chris Lattner553ca522005-06-15 21:11:48 +0000117 bool HasNonInstructionUser;
118
Chris Lattner25de4e52006-11-01 18:03:33 +0000119 /// HasPHIUser - Set to true if this global has a user that is a PHI node.
120 bool HasPHIUser;
121
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000122 GlobalStatus() : isLoaded(false), StoredType(NotStored), StoredOnceValue(0),
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +0000123 AccessingFunction(0), HasMultipleAccessingFunctions(false),
Chris Lattner6a93fc02008-01-14 01:32:52 +0000124 HasNonInstructionUser(false), HasPHIUser(false) {}
Chris Lattner7a90b682004-10-07 04:16:33 +0000125};
Chris Lattnere47ba742004-10-06 20:57:02 +0000126
Chris Lattnera4be1dc2004-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 Lattner7a90b682004-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.
Chris Lattner079236d2004-02-25 21:34:36 +0000148///
Chris Lattner7a90b682004-10-07 04:16:33 +0000149static bool AnalyzeGlobal(Value *V, GlobalStatus &GS,
150 std::set<PHINode*> &PHIUsers) {
Chris Lattner079236d2004-02-25 21:34:36 +0000151 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
Chris Lattner96940cb2004-07-18 19:56:20 +0000152 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(*UI)) {
Chris Lattner553ca522005-06-15 21:11:48 +0000153 GS.HasNonInstructionUser = true;
154
Chris Lattner7a90b682004-10-07 04:16:33 +0000155 if (AnalyzeGlobal(CE, GS, PHIUsers)) return true;
Chris Lattner670c8892004-10-08 17:32:09 +0000156
Chris Lattner079236d2004-02-25 21:34:36 +0000157 } else if (Instruction *I = dyn_cast<Instruction>(*UI)) {
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +0000158 if (!GS.HasMultipleAccessingFunctions) {
159 Function *F = I->getParent()->getParent();
160 if (GS.AccessingFunction == 0)
161 GS.AccessingFunction = F;
162 else if (GS.AccessingFunction != F)
163 GS.HasMultipleAccessingFunctions = true;
164 }
Chris Lattner7a90b682004-10-07 04:16:33 +0000165 if (isa<LoadInst>(I)) {
166 GS.isLoaded = true;
167 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Chris Lattner36025492004-10-07 06:01:25 +0000168 // Don't allow a store OF the address, only stores TO the address.
169 if (SI->getOperand(0) == V) return true;
170
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000171 // If this is a direct store to the global (i.e., the global is a scalar
172 // value, not an aggregate), keep more specific information about
173 // stores.
174 if (GS.StoredType != GlobalStatus::isStored)
175 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(SI->getOperand(1))){
Chris Lattnerbd38edf2004-11-14 20:50:30 +0000176 Value *StoredVal = SI->getOperand(0);
177 if (StoredVal == GV->getInitializer()) {
178 if (GS.StoredType < GlobalStatus::isInitializerStored)
179 GS.StoredType = GlobalStatus::isInitializerStored;
180 } else if (isa<LoadInst>(StoredVal) &&
181 cast<LoadInst>(StoredVal)->getOperand(0) == GV) {
182 // G = G
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000183 if (GS.StoredType < GlobalStatus::isInitializerStored)
184 GS.StoredType = GlobalStatus::isInitializerStored;
185 } else if (GS.StoredType < GlobalStatus::isStoredOnce) {
186 GS.StoredType = GlobalStatus::isStoredOnce;
Chris Lattnerbd38edf2004-11-14 20:50:30 +0000187 GS.StoredOnceValue = StoredVal;
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000188 } else if (GS.StoredType == GlobalStatus::isStoredOnce &&
Chris Lattnerbd38edf2004-11-14 20:50:30 +0000189 GS.StoredOnceValue == StoredVal) {
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000190 // noop.
191 } else {
192 GS.StoredType = GlobalStatus::isStored;
193 }
194 } else {
Chris Lattner7a90b682004-10-07 04:16:33 +0000195 GS.StoredType = GlobalStatus::isStored;
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000196 }
Chris Lattner35c81b02005-02-27 18:58:52 +0000197 } else if (isa<GetElementPtrInst>(I)) {
Chris Lattner7a90b682004-10-07 04:16:33 +0000198 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Chris Lattner35c81b02005-02-27 18:58:52 +0000199 } else if (isa<SelectInst>(I)) {
Chris Lattner7a90b682004-10-07 04:16:33 +0000200 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Chris Lattner7a90b682004-10-07 04:16:33 +0000201 } else if (PHINode *PN = dyn_cast<PHINode>(I)) {
202 // PHI nodes we can check just like select or GEP instructions, but we
203 // have to be careful about infinite recursion.
204 if (PHIUsers.insert(PN).second) // Not already visited.
205 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Chris Lattner25de4e52006-11-01 18:03:33 +0000206 GS.HasPHIUser = true;
Reid Spencere4d87aa2006-12-23 06:05:41 +0000207 } else if (isa<CmpInst>(I)) {
Chris Lattner35c81b02005-02-27 18:58:52 +0000208 } else if (isa<MemCpyInst>(I) || isa<MemMoveInst>(I)) {
209 if (I->getOperand(1) == V)
210 GS.StoredType = GlobalStatus::isStored;
211 if (I->getOperand(2) == V)
212 GS.isLoaded = true;
Chris Lattner35c81b02005-02-27 18:58:52 +0000213 } else if (isa<MemSetInst>(I)) {
214 assert(I->getOperand(1) == V && "Memset only takes one pointer!");
215 GS.StoredType = GlobalStatus::isStored;
Chris Lattner7a90b682004-10-07 04:16:33 +0000216 } else {
217 return true; // Any other non-load instruction might take address!
Chris Lattner9ce30002004-07-20 03:58:07 +0000218 }
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000219 } else if (Constant *C = dyn_cast<Constant>(*UI)) {
Chris Lattner553ca522005-06-15 21:11:48 +0000220 GS.HasNonInstructionUser = true;
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000221 // We might have a dead and dangling constant hanging off of here.
222 if (!ConstantIsDead(C))
223 return true;
Chris Lattner079236d2004-02-25 21:34:36 +0000224 } else {
Chris Lattner553ca522005-06-15 21:11:48 +0000225 GS.HasNonInstructionUser = true;
226 // Otherwise must be some other user.
Chris Lattner079236d2004-02-25 21:34:36 +0000227 return true;
228 }
229
230 return false;
231}
232
Chris Lattner670c8892004-10-08 17:32:09 +0000233static Constant *getAggregateConstantElement(Constant *Agg, Constant *Idx) {
234 ConstantInt *CI = dyn_cast<ConstantInt>(Idx);
235 if (!CI) return 0;
Reid Spencerb83eb642006-10-20 07:07:24 +0000236 unsigned IdxV = CI->getZExtValue();
Chris Lattner7a90b682004-10-07 04:16:33 +0000237
Chris Lattner670c8892004-10-08 17:32:09 +0000238 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Agg)) {
239 if (IdxV < CS->getNumOperands()) return CS->getOperand(IdxV);
240 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Agg)) {
241 if (IdxV < CA->getNumOperands()) return CA->getOperand(IdxV);
Reid Spencer9d6565a2007-02-15 02:26:10 +0000242 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Agg)) {
Chris Lattner670c8892004-10-08 17:32:09 +0000243 if (IdxV < CP->getNumOperands()) return CP->getOperand(IdxV);
Chris Lattner7a7ed022004-10-16 18:09:00 +0000244 } else if (isa<ConstantAggregateZero>(Agg)) {
Chris Lattner670c8892004-10-08 17:32:09 +0000245 if (const StructType *STy = dyn_cast<StructType>(Agg->getType())) {
246 if (IdxV < STy->getNumElements())
247 return Constant::getNullValue(STy->getElementType(IdxV));
248 } else if (const SequentialType *STy =
249 dyn_cast<SequentialType>(Agg->getType())) {
250 return Constant::getNullValue(STy->getElementType());
251 }
Chris Lattner7a7ed022004-10-16 18:09:00 +0000252 } else if (isa<UndefValue>(Agg)) {
253 if (const StructType *STy = dyn_cast<StructType>(Agg->getType())) {
254 if (IdxV < STy->getNumElements())
255 return UndefValue::get(STy->getElementType(IdxV));
256 } else if (const SequentialType *STy =
257 dyn_cast<SequentialType>(Agg->getType())) {
258 return UndefValue::get(STy->getElementType());
259 }
Chris Lattner670c8892004-10-08 17:32:09 +0000260 }
261 return 0;
262}
Chris Lattner7a90b682004-10-07 04:16:33 +0000263
Chris Lattner7a90b682004-10-07 04:16:33 +0000264
Chris Lattnere47ba742004-10-06 20:57:02 +0000265/// CleanupConstantGlobalUsers - We just marked GV constant. Loop over all
266/// users of the global, cleaning up the obvious ones. This is largely just a
Chris Lattner031955d2004-10-10 16:43:46 +0000267/// quick scan over the use list to clean up the easy and obvious cruft. This
268/// returns true if it made a change.
269static bool CleanupConstantGlobalUsers(Value *V, Constant *Init) {
270 bool Changed = false;
Chris Lattner7a90b682004-10-07 04:16:33 +0000271 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;) {
272 User *U = *UI++;
Misha Brukmanfd939082005-04-21 23:48:37 +0000273
Chris Lattner7a90b682004-10-07 04:16:33 +0000274 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
Chris Lattner35c81b02005-02-27 18:58:52 +0000275 if (Init) {
276 // Replace the load with the initializer.
277 LI->replaceAllUsesWith(Init);
278 LI->eraseFromParent();
279 Changed = true;
280 }
Chris Lattner7a90b682004-10-07 04:16:33 +0000281 } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
Chris Lattnere47ba742004-10-06 20:57:02 +0000282 // Store must be unreachable or storing Init into the global.
Chris Lattner7a7ed022004-10-16 18:09:00 +0000283 SI->eraseFromParent();
Chris Lattner031955d2004-10-10 16:43:46 +0000284 Changed = true;
Chris Lattner7a90b682004-10-07 04:16:33 +0000285 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
286 if (CE->getOpcode() == Instruction::GetElementPtr) {
Chris Lattneraae4a1c2005-09-26 07:34:35 +0000287 Constant *SubInit = 0;
288 if (Init)
289 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
Chris Lattner35c81b02005-02-27 18:58:52 +0000290 Changed |= CleanupConstantGlobalUsers(CE, SubInit);
Reid Spencer3da59db2006-11-27 01:05:10 +0000291 } else if (CE->getOpcode() == Instruction::BitCast &&
Chris Lattner35c81b02005-02-27 18:58:52 +0000292 isa<PointerType>(CE->getType())) {
293 // Pointer cast, delete any stores and memsets to the global.
294 Changed |= CleanupConstantGlobalUsers(CE, 0);
295 }
296
297 if (CE->use_empty()) {
298 CE->destroyConstant();
299 Changed = true;
Chris Lattner7a90b682004-10-07 04:16:33 +0000300 }
301 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
Chris Lattner7b52fe72007-11-09 17:33:02 +0000302 // Do not transform "gepinst (gep constexpr (GV))" here, because forming
303 // "gepconstexpr (gep constexpr (GV))" will cause the two gep's to fold
304 // and will invalidate our notion of what Init is.
Chris Lattner19450242007-11-13 21:46:23 +0000305 Constant *SubInit = 0;
Chris Lattner7b52fe72007-11-09 17:33:02 +0000306 if (!isa<ConstantExpr>(GEP->getOperand(0))) {
307 ConstantExpr *CE =
308 dyn_cast_or_null<ConstantExpr>(ConstantFoldInstruction(GEP));
309 if (Init && CE && CE->getOpcode() == Instruction::GetElementPtr)
Chris Lattner19450242007-11-13 21:46:23 +0000310 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
Chris Lattner7b52fe72007-11-09 17:33:02 +0000311 }
Chris Lattner19450242007-11-13 21:46:23 +0000312 Changed |= CleanupConstantGlobalUsers(GEP, SubInit);
Chris Lattnerc4d81b02004-10-10 16:47:33 +0000313
Chris Lattner031955d2004-10-10 16:43:46 +0000314 if (GEP->use_empty()) {
Chris Lattner7a7ed022004-10-16 18:09:00 +0000315 GEP->eraseFromParent();
Chris Lattner031955d2004-10-10 16:43:46 +0000316 Changed = true;
317 }
Chris Lattner35c81b02005-02-27 18:58:52 +0000318 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U)) { // memset/cpy/mv
319 if (MI->getRawDest() == V) {
320 MI->eraseFromParent();
321 Changed = true;
322 }
323
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000324 } else if (Constant *C = dyn_cast<Constant>(U)) {
325 // If we have a chain of dead constantexprs or other things dangling from
326 // us, and if they are all dead, nuke them without remorse.
327 if (ConstantIsDead(C)) {
328 C->destroyConstant();
Chris Lattner35c81b02005-02-27 18:58:52 +0000329 // This could have invalidated UI, start over from scratch.
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000330 CleanupConstantGlobalUsers(V, Init);
Chris Lattner031955d2004-10-10 16:43:46 +0000331 return true;
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000332 }
Chris Lattnere47ba742004-10-06 20:57:02 +0000333 }
334 }
Chris Lattner031955d2004-10-10 16:43:46 +0000335 return Changed;
Chris Lattnere47ba742004-10-06 20:57:02 +0000336}
337
Chris Lattner727c2102008-01-14 01:31:05 +0000338
339/// UsersSafeToSRA - Look at all uses of the global and decide whether it is
340/// safe for us to perform this transformation.
341///
342static bool UsersSafeToSRA(Value *V) {
343 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;++UI){
344 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(*UI)) {
345 if (CE->getOpcode() != Instruction::GetElementPtr)
346 return false;
347
348 // Check to see if this ConstantExpr GEP is SRA'able. In particular, we
349 // don't like < 3 operand CE's, and we don't like non-constant integer
350 // indices.
351 if (CE->getNumOperands() < 3 || !CE->getOperand(1)->isNullValue())
352 return false;
353
354 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
355 if (!isa<ConstantInt>(CE->getOperand(i)))
356 return false;
357
358 if (!UsersSafeToSRA(CE)) return false;
359 continue;
360 }
361
362 if (Instruction *I = dyn_cast<Instruction>(*UI)) {
363 if (isa<LoadInst>(I)) continue;
364
365 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
366 // Don't allow a store OF the address, only stores TO the address.
367 if (SI->getOperand(0) == V) return false;
368 continue;
369 }
370
371 if (isa<GetElementPtrInst>(I)) {
372 if (!UsersSafeToSRA(I)) return false;
373
374 // If the first two indices are constants, this can be SRA'd.
375 if (isa<GlobalVariable>(I->getOperand(0))) {
376 if (I->getNumOperands() < 3 || !isa<Constant>(I->getOperand(1)) ||
377 !cast<Constant>(I->getOperand(1))->isNullValue() ||
378 !isa<ConstantInt>(I->getOperand(2)))
379 return false;
380 continue;
381 }
382
383 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(I->getOperand(0))){
384 if (CE->getOpcode() != Instruction::GetElementPtr ||
385 CE->getNumOperands() < 3 || I->getNumOperands() < 2 ||
386 !isa<Constant>(I->getOperand(0)) ||
387 !cast<Constant>(I->getOperand(0))->isNullValue())
388 return false;
389 continue;
390 }
391 return false;
392 }
393 return false; // Any other instruction is not safe.
394 }
395 if (Constant *C = dyn_cast<Constant>(*UI)) {
396 // We might have a dead and dangling constant hanging off of here.
397 if (!ConstantIsDead(C))
398 return false;
399 continue;
400 }
401 // Otherwise must be some other user.
402 return false;
403 }
404
405 return true;
406}
407
Chris Lattner670c8892004-10-08 17:32:09 +0000408/// SRAGlobal - Perform scalar replacement of aggregates on the specified global
409/// variable. This opens the door for other optimizations by exposing the
410/// behavior of the program in a more fine-grained way. We have determined that
411/// this transformation is safe already. We return the first global variable we
412/// insert so that the caller can reprocess it.
413static GlobalVariable *SRAGlobal(GlobalVariable *GV) {
Chris Lattner727c2102008-01-14 01:31:05 +0000414 // Make sure this global only has simple uses that we can SRA.
415 if (!UsersSafeToSRA(GV))
416 return 0;
417
Chris Lattner670c8892004-10-08 17:32:09 +0000418 assert(GV->hasInternalLinkage() && !GV->isConstant());
419 Constant *Init = GV->getInitializer();
420 const Type *Ty = Init->getType();
Misha Brukmanfd939082005-04-21 23:48:37 +0000421
Chris Lattner670c8892004-10-08 17:32:09 +0000422 std::vector<GlobalVariable*> NewGlobals;
423 Module::GlobalListType &Globals = GV->getParent()->getGlobalList();
424
425 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
426 NewGlobals.reserve(STy->getNumElements());
427 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
428 Constant *In = getAggregateConstantElement(Init,
Reid Spencerc5b206b2006-12-31 05:48:39 +0000429 ConstantInt::get(Type::Int32Ty, i));
Chris Lattner670c8892004-10-08 17:32:09 +0000430 assert(In && "Couldn't get element of initializer?");
431 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(i), false,
432 GlobalVariable::InternalLinkage,
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +0000433 In, GV->getName()+"."+utostr(i),
434 (Module *)NULL,
435 GV->isThreadLocal());
Chris Lattner670c8892004-10-08 17:32:09 +0000436 Globals.insert(GV, NGV);
437 NewGlobals.push_back(NGV);
438 }
439 } else if (const SequentialType *STy = dyn_cast<SequentialType>(Ty)) {
440 unsigned NumElements = 0;
441 if (const ArrayType *ATy = dyn_cast<ArrayType>(STy))
442 NumElements = ATy->getNumElements();
Reid Spencer9d6565a2007-02-15 02:26:10 +0000443 else if (const VectorType *PTy = dyn_cast<VectorType>(STy))
Chris Lattner670c8892004-10-08 17:32:09 +0000444 NumElements = PTy->getNumElements();
445 else
446 assert(0 && "Unknown aggregate sequential type!");
447
Chris Lattner1f21ef12005-02-23 16:53:04 +0000448 if (NumElements > 16 && GV->hasNUsesOrMore(16))
Chris Lattnerd514d822005-02-01 01:23:31 +0000449 return 0; // It's not worth it.
Chris Lattner670c8892004-10-08 17:32:09 +0000450 NewGlobals.reserve(NumElements);
451 for (unsigned i = 0, e = NumElements; i != e; ++i) {
452 Constant *In = getAggregateConstantElement(Init,
Reid Spencerc5b206b2006-12-31 05:48:39 +0000453 ConstantInt::get(Type::Int32Ty, i));
Chris Lattner670c8892004-10-08 17:32:09 +0000454 assert(In && "Couldn't get element of initializer?");
455
456 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(), false,
457 GlobalVariable::InternalLinkage,
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +0000458 In, GV->getName()+"."+utostr(i),
459 (Module *)NULL,
460 GV->isThreadLocal());
Chris Lattner670c8892004-10-08 17:32:09 +0000461 Globals.insert(GV, NGV);
462 NewGlobals.push_back(NGV);
463 }
464 }
465
466 if (NewGlobals.empty())
467 return 0;
468
Bill Wendling0a81aac2006-11-26 10:02:32 +0000469 DOUT << "PERFORMING GLOBAL SRA ON: " << *GV;
Chris Lattner30ba5692004-10-11 05:54:41 +0000470
Reid Spencerc5b206b2006-12-31 05:48:39 +0000471 Constant *NullInt = Constant::getNullValue(Type::Int32Ty);
Chris Lattner670c8892004-10-08 17:32:09 +0000472
473 // Loop over all of the uses of the global, replacing the constantexpr geps,
474 // with smaller constantexpr geps or direct references.
475 while (!GV->use_empty()) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000476 User *GEP = GV->use_back();
477 assert(((isa<ConstantExpr>(GEP) &&
478 cast<ConstantExpr>(GEP)->getOpcode()==Instruction::GetElementPtr)||
479 isa<GetElementPtrInst>(GEP)) && "NonGEP CE's are not SRAable!");
Misha Brukmanfd939082005-04-21 23:48:37 +0000480
Chris Lattner670c8892004-10-08 17:32:09 +0000481 // Ignore the 1th operand, which has to be zero or else the program is quite
482 // broken (undefined). Get the 2nd operand, which is the structure or array
483 // index.
Reid Spencerb83eb642006-10-20 07:07:24 +0000484 unsigned Val = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
Chris Lattner670c8892004-10-08 17:32:09 +0000485 if (Val >= NewGlobals.size()) Val = 0; // Out of bound array access.
486
Chris Lattner30ba5692004-10-11 05:54:41 +0000487 Value *NewPtr = NewGlobals[Val];
Chris Lattner670c8892004-10-08 17:32:09 +0000488
489 // Form a shorter GEP if needed.
Chris Lattner30ba5692004-10-11 05:54:41 +0000490 if (GEP->getNumOperands() > 3)
491 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEP)) {
Chris Lattner55eb1c42007-01-31 04:40:53 +0000492 SmallVector<Constant*, 8> Idxs;
Chris Lattner30ba5692004-10-11 05:54:41 +0000493 Idxs.push_back(NullInt);
494 for (unsigned i = 3, e = CE->getNumOperands(); i != e; ++i)
495 Idxs.push_back(CE->getOperand(i));
Chris Lattner55eb1c42007-01-31 04:40:53 +0000496 NewPtr = ConstantExpr::getGetElementPtr(cast<Constant>(NewPtr),
497 &Idxs[0], Idxs.size());
Chris Lattner30ba5692004-10-11 05:54:41 +0000498 } else {
499 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(GEP);
Chris Lattner699d1442007-01-31 19:59:55 +0000500 SmallVector<Value*, 8> Idxs;
Chris Lattner30ba5692004-10-11 05:54:41 +0000501 Idxs.push_back(NullInt);
502 for (unsigned i = 3, e = GEPI->getNumOperands(); i != e; ++i)
503 Idxs.push_back(GEPI->getOperand(i));
David Greeneb8f74792007-09-04 15:46:09 +0000504 NewPtr = new GetElementPtrInst(NewPtr, Idxs.begin(), Idxs.end(),
Chris Lattner30ba5692004-10-11 05:54:41 +0000505 GEPI->getName()+"."+utostr(Val), GEPI);
506 }
507 GEP->replaceAllUsesWith(NewPtr);
508
509 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(GEP))
Chris Lattner7a7ed022004-10-16 18:09:00 +0000510 GEPI->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +0000511 else
512 cast<ConstantExpr>(GEP)->destroyConstant();
Chris Lattner670c8892004-10-08 17:32:09 +0000513 }
514
Chris Lattnere40e2d12004-10-08 20:25:55 +0000515 // Delete the old global, now that it is dead.
516 Globals.erase(GV);
Chris Lattner670c8892004-10-08 17:32:09 +0000517 ++NumSRA;
Chris Lattner30ba5692004-10-11 05:54:41 +0000518
519 // Loop over the new globals array deleting any globals that are obviously
520 // dead. This can arise due to scalarization of a structure or an array that
521 // has elements that are dead.
522 unsigned FirstGlobal = 0;
523 for (unsigned i = 0, e = NewGlobals.size(); i != e; ++i)
524 if (NewGlobals[i]->use_empty()) {
525 Globals.erase(NewGlobals[i]);
526 if (FirstGlobal == i) ++FirstGlobal;
527 }
528
529 return FirstGlobal != NewGlobals.size() ? NewGlobals[FirstGlobal] : 0;
Chris Lattner670c8892004-10-08 17:32:09 +0000530}
531
Chris Lattner9b34a612004-10-09 21:48:45 +0000532/// AllUsesOfValueWillTrapIfNull - Return true if all users of the specified
Chris Lattner81686182007-09-13 16:30:19 +0000533/// value will trap if the value is dynamically null. PHIs keeps track of any
534/// phi nodes we've seen to avoid reprocessing them.
535static bool AllUsesOfValueWillTrapIfNull(Value *V,
536 SmallPtrSet<PHINode*, 8> &PHIs) {
Chris Lattner9b34a612004-10-09 21:48:45 +0000537 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
538 if (isa<LoadInst>(*UI)) {
539 // Will trap.
540 } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
541 if (SI->getOperand(0) == V) {
Bill Wendlinge8156192006-12-07 01:30:32 +0000542 //cerr << "NONTRAPPING USE: " << **UI;
Chris Lattner9b34a612004-10-09 21:48:45 +0000543 return false; // Storing the value.
544 }
545 } else if (CallInst *CI = dyn_cast<CallInst>(*UI)) {
546 if (CI->getOperand(0) != V) {
Bill Wendlinge8156192006-12-07 01:30:32 +0000547 //cerr << "NONTRAPPING USE: " << **UI;
Chris Lattner9b34a612004-10-09 21:48:45 +0000548 return false; // Not calling the ptr
549 }
550 } else if (InvokeInst *II = dyn_cast<InvokeInst>(*UI)) {
551 if (II->getOperand(0) != V) {
Bill Wendlinge8156192006-12-07 01:30:32 +0000552 //cerr << "NONTRAPPING USE: " << **UI;
Chris Lattner9b34a612004-10-09 21:48:45 +0000553 return false; // Not calling the ptr
554 }
Chris Lattner81686182007-09-13 16:30:19 +0000555 } else if (BitCastInst *CI = dyn_cast<BitCastInst>(*UI)) {
556 if (!AllUsesOfValueWillTrapIfNull(CI, PHIs)) return false;
Chris Lattner9b34a612004-10-09 21:48:45 +0000557 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(*UI)) {
Chris Lattner81686182007-09-13 16:30:19 +0000558 if (!AllUsesOfValueWillTrapIfNull(GEPI, PHIs)) return false;
559 } else if (PHINode *PN = dyn_cast<PHINode>(*UI)) {
560 // If we've already seen this phi node, ignore it, it has already been
561 // checked.
562 if (PHIs.insert(PN))
563 return AllUsesOfValueWillTrapIfNull(PN, PHIs);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000564 } else if (isa<ICmpInst>(*UI) &&
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000565 isa<ConstantPointerNull>(UI->getOperand(1))) {
566 // Ignore setcc X, null
Chris Lattner9b34a612004-10-09 21:48:45 +0000567 } else {
Bill Wendlinge8156192006-12-07 01:30:32 +0000568 //cerr << "NONTRAPPING USE: " << **UI;
Chris Lattner9b34a612004-10-09 21:48:45 +0000569 return false;
570 }
571 return true;
572}
573
574/// AllUsesOfLoadedValueWillTrapIfNull - Return true if all uses of any loads
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000575/// from GV will trap if the loaded value is null. Note that this also permits
576/// comparisons of the loaded value against null, as a special case.
Chris Lattner9b34a612004-10-09 21:48:45 +0000577static bool AllUsesOfLoadedValueWillTrapIfNull(GlobalVariable *GV) {
578 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI!=E; ++UI)
579 if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
Chris Lattner81686182007-09-13 16:30:19 +0000580 SmallPtrSet<PHINode*, 8> PHIs;
581 if (!AllUsesOfValueWillTrapIfNull(LI, PHIs))
Chris Lattner9b34a612004-10-09 21:48:45 +0000582 return false;
583 } else if (isa<StoreInst>(*UI)) {
584 // Ignore stores to the global.
585 } else {
586 // We don't know or understand this user, bail out.
Bill Wendlinge8156192006-12-07 01:30:32 +0000587 //cerr << "UNKNOWN USER OF GLOBAL!: " << **UI;
Chris Lattner9b34a612004-10-09 21:48:45 +0000588 return false;
589 }
590
591 return true;
592}
593
Chris Lattner708148e2004-10-10 23:14:11 +0000594static bool OptimizeAwayTrappingUsesOfValue(Value *V, Constant *NewV) {
595 bool Changed = false;
596 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ) {
597 Instruction *I = cast<Instruction>(*UI++);
598 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
599 LI->setOperand(0, NewV);
600 Changed = true;
601 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
602 if (SI->getOperand(1) == V) {
603 SI->setOperand(1, NewV);
604 Changed = true;
605 }
606 } else if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
607 if (I->getOperand(0) == V) {
608 // Calling through the pointer! Turn into a direct call, but be careful
609 // that the pointer is not also being passed as an argument.
610 I->setOperand(0, NewV);
611 Changed = true;
612 bool PassedAsArg = false;
613 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i)
614 if (I->getOperand(i) == V) {
615 PassedAsArg = true;
616 I->setOperand(i, NewV);
617 }
618
619 if (PassedAsArg) {
620 // Being passed as an argument also. Be careful to not invalidate UI!
621 UI = V->use_begin();
622 }
623 }
624 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
625 Changed |= OptimizeAwayTrappingUsesOfValue(CI,
Chris Lattner6e8fbad2006-11-30 17:32:29 +0000626 ConstantExpr::getCast(CI->getOpcode(),
627 NewV, CI->getType()));
Chris Lattner708148e2004-10-10 23:14:11 +0000628 if (CI->use_empty()) {
629 Changed = true;
Chris Lattner7a7ed022004-10-16 18:09:00 +0000630 CI->eraseFromParent();
Chris Lattner708148e2004-10-10 23:14:11 +0000631 }
632 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
633 // Should handle GEP here.
Chris Lattner55eb1c42007-01-31 04:40:53 +0000634 SmallVector<Constant*, 8> Idxs;
635 Idxs.reserve(GEPI->getNumOperands()-1);
Chris Lattner708148e2004-10-10 23:14:11 +0000636 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
637 if (Constant *C = dyn_cast<Constant>(GEPI->getOperand(i)))
Chris Lattner55eb1c42007-01-31 04:40:53 +0000638 Idxs.push_back(C);
Chris Lattner708148e2004-10-10 23:14:11 +0000639 else
640 break;
Chris Lattner55eb1c42007-01-31 04:40:53 +0000641 if (Idxs.size() == GEPI->getNumOperands()-1)
Chris Lattner708148e2004-10-10 23:14:11 +0000642 Changed |= OptimizeAwayTrappingUsesOfValue(GEPI,
Chris Lattner55eb1c42007-01-31 04:40:53 +0000643 ConstantExpr::getGetElementPtr(NewV, &Idxs[0],
644 Idxs.size()));
Chris Lattner708148e2004-10-10 23:14:11 +0000645 if (GEPI->use_empty()) {
646 Changed = true;
Chris Lattner7a7ed022004-10-16 18:09:00 +0000647 GEPI->eraseFromParent();
Chris Lattner708148e2004-10-10 23:14:11 +0000648 }
649 }
650 }
651
652 return Changed;
653}
654
655
656/// OptimizeAwayTrappingUsesOfLoads - The specified global has only one non-null
657/// value stored into it. If there are uses of the loaded value that would trap
658/// if the loaded value is dynamically null, then we know that they cannot be
659/// reachable with a null optimize away the load.
660static bool OptimizeAwayTrappingUsesOfLoads(GlobalVariable *GV, Constant *LV) {
661 std::vector<LoadInst*> Loads;
662 bool Changed = false;
663
664 // Replace all uses of loads with uses of uses of the stored value.
665 for (Value::use_iterator GUI = GV->use_begin(), E = GV->use_end();
666 GUI != E; ++GUI)
667 if (LoadInst *LI = dyn_cast<LoadInst>(*GUI)) {
668 Loads.push_back(LI);
669 Changed |= OptimizeAwayTrappingUsesOfValue(LI, LV);
670 } else {
Chris Lattnerce3e2bf2007-05-15 06:42:04 +0000671 // If we get here we could have stores, selects, or phi nodes whose values
Chris Lattner79cfddf2007-05-13 21:28:07 +0000672 // are loaded.
Chris Lattnerce3e2bf2007-05-15 06:42:04 +0000673 assert((isa<StoreInst>(*GUI) || isa<PHINode>(*GUI) ||
Chris Lattner9027b3c2008-01-04 05:04:53 +0000674 isa<SelectInst>(*GUI) || isa<ConstantExpr>(*GUI)) &&
Chris Lattner79cfddf2007-05-13 21:28:07 +0000675 "Only expect load and stores!");
Chris Lattner708148e2004-10-10 23:14:11 +0000676 }
677
678 if (Changed) {
Bill Wendling0a81aac2006-11-26 10:02:32 +0000679 DOUT << "OPTIMIZED LOADS FROM STORED ONCE POINTER: " << *GV;
Chris Lattner708148e2004-10-10 23:14:11 +0000680 ++NumGlobUses;
681 }
682
683 // Delete all of the loads we can, keeping track of whether we nuked them all!
684 bool AllLoadsGone = true;
685 while (!Loads.empty()) {
686 LoadInst *L = Loads.back();
687 if (L->use_empty()) {
Chris Lattner7a7ed022004-10-16 18:09:00 +0000688 L->eraseFromParent();
Chris Lattner708148e2004-10-10 23:14:11 +0000689 Changed = true;
690 } else {
691 AllLoadsGone = false;
692 }
693 Loads.pop_back();
694 }
695
696 // If we nuked all of the loads, then none of the stores are needed either,
697 // nor is the global.
698 if (AllLoadsGone) {
Bill Wendling0a81aac2006-11-26 10:02:32 +0000699 DOUT << " *** GLOBAL NOW DEAD!\n";
Chris Lattner708148e2004-10-10 23:14:11 +0000700 CleanupConstantGlobalUsers(GV, 0);
701 if (GV->use_empty()) {
Chris Lattner7a7ed022004-10-16 18:09:00 +0000702 GV->eraseFromParent();
Chris Lattner708148e2004-10-10 23:14:11 +0000703 ++NumDeleted;
704 }
705 Changed = true;
706 }
707 return Changed;
708}
709
Chris Lattner30ba5692004-10-11 05:54:41 +0000710/// ConstantPropUsersOf - Walk the use list of V, constant folding all of the
711/// instructions that are foldable.
712static void ConstantPropUsersOf(Value *V) {
713 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; )
714 if (Instruction *I = dyn_cast<Instruction>(*UI++))
715 if (Constant *NewC = ConstantFoldInstruction(I)) {
716 I->replaceAllUsesWith(NewC);
717
Chris Lattnerd514d822005-02-01 01:23:31 +0000718 // Advance UI to the next non-I use to avoid invalidating it!
719 // Instructions could multiply use V.
720 while (UI != E && *UI == I)
Chris Lattner30ba5692004-10-11 05:54:41 +0000721 ++UI;
Chris Lattnerd514d822005-02-01 01:23:31 +0000722 I->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +0000723 }
724}
725
726/// OptimizeGlobalAddressOfMalloc - This function takes the specified global
727/// variable, and transforms the program as if it always contained the result of
728/// the specified malloc. Because it is always the result of the specified
729/// malloc, there is no reason to actually DO the malloc. Instead, turn the
Chris Lattner6e8fbad2006-11-30 17:32:29 +0000730/// malloc into a global, and any loads of GV as uses of the new global.
Chris Lattner30ba5692004-10-11 05:54:41 +0000731static GlobalVariable *OptimizeGlobalAddressOfMalloc(GlobalVariable *GV,
732 MallocInst *MI) {
Bill Wendling0a81aac2006-11-26 10:02:32 +0000733 DOUT << "PROMOTING MALLOC GLOBAL: " << *GV << " MALLOC = " << *MI;
Chris Lattner30ba5692004-10-11 05:54:41 +0000734 ConstantInt *NElements = cast<ConstantInt>(MI->getArraySize());
735
Reid Spencerb83eb642006-10-20 07:07:24 +0000736 if (NElements->getZExtValue() != 1) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000737 // If we have an array allocation, transform it to a single element
738 // allocation to make the code below simpler.
739 Type *NewTy = ArrayType::get(MI->getAllocatedType(),
Reid Spencerb83eb642006-10-20 07:07:24 +0000740 NElements->getZExtValue());
Chris Lattner30ba5692004-10-11 05:54:41 +0000741 MallocInst *NewMI =
Reid Spencerc5b206b2006-12-31 05:48:39 +0000742 new MallocInst(NewTy, Constant::getNullValue(Type::Int32Ty),
Nate Begeman14b05292005-11-05 09:21:28 +0000743 MI->getAlignment(), MI->getName(), MI);
Chris Lattner699d1442007-01-31 19:59:55 +0000744 Value* Indices[2];
745 Indices[0] = Indices[1] = Constant::getNullValue(Type::Int32Ty);
David Greeneb8f74792007-09-04 15:46:09 +0000746 Value *NewGEP = new GetElementPtrInst(NewMI, Indices, Indices + 2,
Chris Lattner30ba5692004-10-11 05:54:41 +0000747 NewMI->getName()+".el0", MI);
748 MI->replaceAllUsesWith(NewGEP);
Chris Lattner7a7ed022004-10-16 18:09:00 +0000749 MI->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +0000750 MI = NewMI;
751 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000752
Chris Lattner7a7ed022004-10-16 18:09:00 +0000753 // Create the new global variable. The contents of the malloc'd memory is
754 // undefined, so initialize with an undef value.
755 Constant *Init = UndefValue::get(MI->getAllocatedType());
Chris Lattner30ba5692004-10-11 05:54:41 +0000756 GlobalVariable *NewGV = new GlobalVariable(MI->getAllocatedType(), false,
757 GlobalValue::InternalLinkage, Init,
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +0000758 GV->getName()+".body",
759 (Module *)NULL,
760 GV->isThreadLocal());
Chris Lattner30ba5692004-10-11 05:54:41 +0000761 GV->getParent()->getGlobalList().insert(GV, NewGV);
Misha Brukmanfd939082005-04-21 23:48:37 +0000762
Chris Lattner30ba5692004-10-11 05:54:41 +0000763 // Anything that used the malloc now uses the global directly.
764 MI->replaceAllUsesWith(NewGV);
Chris Lattner30ba5692004-10-11 05:54:41 +0000765
766 Constant *RepValue = NewGV;
767 if (NewGV->getType() != GV->getType()->getElementType())
Reid Spencerd977d862006-12-12 23:36:14 +0000768 RepValue = ConstantExpr::getBitCast(RepValue,
769 GV->getType()->getElementType());
Chris Lattner30ba5692004-10-11 05:54:41 +0000770
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000771 // If there is a comparison against null, we will insert a global bool to
772 // keep track of whether the global was initialized yet or not.
Misha Brukmanfd939082005-04-21 23:48:37 +0000773 GlobalVariable *InitBool =
Reid Spencer4fe16d62007-01-11 18:21:29 +0000774 new GlobalVariable(Type::Int1Ty, false, GlobalValue::InternalLinkage,
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +0000775 ConstantInt::getFalse(), GV->getName()+".init",
776 (Module *)NULL, GV->isThreadLocal());
Chris Lattnerbc965b92004-12-02 06:25:58 +0000777 bool InitBoolUsed = false;
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000778
Chris Lattner30ba5692004-10-11 05:54:41 +0000779 // Loop over all uses of GV, processing them in turn.
Chris Lattnerbc965b92004-12-02 06:25:58 +0000780 std::vector<StoreInst*> Stores;
Chris Lattner30ba5692004-10-11 05:54:41 +0000781 while (!GV->use_empty())
782 if (LoadInst *LI = dyn_cast<LoadInst>(GV->use_back())) {
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000783 while (!LI->use_empty()) {
Chris Lattnerd514d822005-02-01 01:23:31 +0000784 Use &LoadUse = LI->use_begin().getUse();
Reid Spencere4d87aa2006-12-23 06:05:41 +0000785 if (!isa<ICmpInst>(LoadUse.getUser()))
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000786 LoadUse = RepValue;
787 else {
Reid Spencere4d87aa2006-12-23 06:05:41 +0000788 ICmpInst *CI = cast<ICmpInst>(LoadUse.getUser());
789 // Replace the cmp X, 0 with a use of the bool value.
790 Value *LV = new LoadInst(InitBool, InitBool->getName()+".val", CI);
Chris Lattnerbc965b92004-12-02 06:25:58 +0000791 InitBoolUsed = true;
Reid Spencere4d87aa2006-12-23 06:05:41 +0000792 switch (CI->getPredicate()) {
793 default: assert(0 && "Unknown ICmp Predicate!");
794 case ICmpInst::ICMP_ULT:
795 case ICmpInst::ICMP_SLT:
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000796 LV = ConstantInt::getFalse(); // X < null -> always false
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000797 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +0000798 case ICmpInst::ICMP_ULE:
799 case ICmpInst::ICMP_SLE:
800 case ICmpInst::ICMP_EQ:
801 LV = BinaryOperator::createNot(LV, "notinit", CI);
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000802 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +0000803 case ICmpInst::ICMP_NE:
804 case ICmpInst::ICMP_UGE:
805 case ICmpInst::ICMP_SGE:
806 case ICmpInst::ICMP_UGT:
807 case ICmpInst::ICMP_SGT:
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000808 break; // no change.
809 }
Reid Spencere4d87aa2006-12-23 06:05:41 +0000810 CI->replaceAllUsesWith(LV);
811 CI->eraseFromParent();
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000812 }
813 }
Chris Lattner7a7ed022004-10-16 18:09:00 +0000814 LI->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +0000815 } else {
816 StoreInst *SI = cast<StoreInst>(GV->use_back());
Chris Lattnerbc965b92004-12-02 06:25:58 +0000817 // The global is initialized when the store to it occurs.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000818 new StoreInst(ConstantInt::getTrue(), InitBool, SI);
Chris Lattner7a7ed022004-10-16 18:09:00 +0000819 SI->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +0000820 }
821
Chris Lattnerbc965b92004-12-02 06:25:58 +0000822 // If the initialization boolean was used, insert it, otherwise delete it.
823 if (!InitBoolUsed) {
824 while (!InitBool->use_empty()) // Delete initializations
825 cast<Instruction>(InitBool->use_back())->eraseFromParent();
826 delete InitBool;
827 } else
828 GV->getParent()->getGlobalList().insert(GV, InitBool);
829
830
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000831 // Now the GV is dead, nuke it and the malloc.
Chris Lattner7a7ed022004-10-16 18:09:00 +0000832 GV->eraseFromParent();
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000833 MI->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +0000834
835 // To further other optimizations, loop over all users of NewGV and try to
836 // constant prop them. This will promote GEP instructions with constant
837 // indices into GEP constant-exprs, which will allow global-opt to hack on it.
838 ConstantPropUsersOf(NewGV);
839 if (RepValue != NewGV)
840 ConstantPropUsersOf(RepValue);
841
842 return NewGV;
843}
Chris Lattner708148e2004-10-10 23:14:11 +0000844
Chris Lattnerfa07e4f2004-12-02 07:11:07 +0000845/// ValueIsOnlyUsedLocallyOrStoredToOneGlobal - Scan the use-list of V checking
846/// to make sure that there are no complex uses of V. We permit simple things
847/// like dereferencing the pointer, but not storing through the address, unless
848/// it is to the specified global.
849static bool ValueIsOnlyUsedLocallyOrStoredToOneGlobal(Instruction *V,
Chris Lattnerc451f9c2007-09-13 16:37:20 +0000850 GlobalVariable *GV,
851 SmallPtrSet<PHINode*, 8> &PHIs) {
Chris Lattner5e6e4942007-09-14 03:41:21 +0000852 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
Reid Spencere4d87aa2006-12-23 06:05:41 +0000853 if (isa<LoadInst>(*UI) || isa<CmpInst>(*UI)) {
Chris Lattnerfa07e4f2004-12-02 07:11:07 +0000854 // Fine, ignore.
855 } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
856 if (SI->getOperand(0) == V && SI->getOperand(1) != GV)
857 return false; // Storing the pointer itself... bad.
858 // Otherwise, storing through it, or storing into GV... fine.
Chris Lattner5e6e4942007-09-14 03:41:21 +0000859 } else if (isa<GetElementPtrInst>(*UI)) {
Chris Lattnerc451f9c2007-09-13 16:37:20 +0000860 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(cast<Instruction>(*UI),
861 GV, PHIs))
Chris Lattnerfa07e4f2004-12-02 07:11:07 +0000862 return false;
Chris Lattnerc451f9c2007-09-13 16:37:20 +0000863 } else if (PHINode *PN = dyn_cast<PHINode>(*UI)) {
864 // PHIs are ok if all uses are ok. Don't infinitely recurse through PHI
865 // cycles.
866 if (PHIs.insert(PN))
Chris Lattner5e6e4942007-09-14 03:41:21 +0000867 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(PN, GV, PHIs))
868 return false;
Chris Lattnerfa07e4f2004-12-02 07:11:07 +0000869 } else {
870 return false;
871 }
872 return true;
Chris Lattnerfa07e4f2004-12-02 07:11:07 +0000873}
874
Chris Lattner86395032006-09-30 23:32:09 +0000875/// ReplaceUsesOfMallocWithGlobal - The Alloc pointer is stored into GV
876/// somewhere. Transform all uses of the allocation into loads from the
877/// global and uses of the resultant pointer. Further, delete the store into
878/// GV. This assumes that these value pass the
879/// 'ValueIsOnlyUsedLocallyOrStoredToOneGlobal' predicate.
880static void ReplaceUsesOfMallocWithGlobal(Instruction *Alloc,
881 GlobalVariable *GV) {
882 while (!Alloc->use_empty()) {
Chris Lattnera637a8b2007-09-13 18:00:31 +0000883 Instruction *U = cast<Instruction>(*Alloc->use_begin());
884 Instruction *InsertPt = U;
Chris Lattner86395032006-09-30 23:32:09 +0000885 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
886 // If this is the store of the allocation into the global, remove it.
887 if (SI->getOperand(1) == GV) {
888 SI->eraseFromParent();
889 continue;
890 }
Chris Lattnera637a8b2007-09-13 18:00:31 +0000891 } else if (PHINode *PN = dyn_cast<PHINode>(U)) {
892 // Insert the load in the corresponding predecessor, not right before the
893 // PHI.
894 unsigned PredNo = Alloc->use_begin().getOperandNo()/2;
895 InsertPt = PN->getIncomingBlock(PredNo)->getTerminator();
Chris Lattner86395032006-09-30 23:32:09 +0000896 }
897
898 // Insert a load from the global, and use it instead of the malloc.
Chris Lattnera637a8b2007-09-13 18:00:31 +0000899 Value *NL = new LoadInst(GV, GV->getName()+".val", InsertPt);
Chris Lattner86395032006-09-30 23:32:09 +0000900 U->replaceUsesOfWith(Alloc, NL);
901 }
902}
903
904/// GlobalLoadUsesSimpleEnoughForHeapSRA - If all users of values loaded from
905/// GV are simple enough to perform HeapSRA, return true.
Chris Lattner309f20f2007-09-13 21:31:36 +0000906static bool GlobalLoadUsesSimpleEnoughForHeapSRA(GlobalVariable *GV,
907 MallocInst *MI) {
Chris Lattner86395032006-09-30 23:32:09 +0000908 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI != E;
909 ++UI)
910 if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
911 // We permit two users of the load: setcc comparing against the null
912 // pointer, and a getelementptr of a specific form.
913 for (Value::use_iterator UI = LI->use_begin(), E = LI->use_end(); UI != E;
914 ++UI) {
915 // Comparison against null is ok.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000916 if (ICmpInst *ICI = dyn_cast<ICmpInst>(*UI)) {
917 if (!isa<ConstantPointerNull>(ICI->getOperand(1)))
Chris Lattner86395032006-09-30 23:32:09 +0000918 return false;
919 continue;
920 }
921
922 // getelementptr is also ok, but only a simple form.
Chris Lattner309f20f2007-09-13 21:31:36 +0000923 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(*UI)) {
924 // Must index into the array and into the struct.
925 if (GEPI->getNumOperands() < 3)
926 return false;
927
928 // Otherwise the GEP is ok.
929 continue;
930 }
Chris Lattner86395032006-09-30 23:32:09 +0000931
Chris Lattner309f20f2007-09-13 21:31:36 +0000932 if (PHINode *PN = dyn_cast<PHINode>(*UI)) {
933 // We have a phi of a load from the global. We can only handle this
934 // if the other PHI'd values are actually the same. In this case,
935 // the rewriter will just drop the phi entirely.
936 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
937 Value *IV = PN->getIncomingValue(i);
938 if (IV == LI) continue; // Trivial the same.
939
940 // If the phi'd value is from the malloc that initializes the value,
941 // we can xform it.
942 if (IV == MI) continue;
943
944 // Otherwise, we don't know what it is.
945 return false;
946 }
947 return true;
948 }
Chris Lattner86395032006-09-30 23:32:09 +0000949
Chris Lattner309f20f2007-09-13 21:31:36 +0000950 // Otherwise we don't know what this is, not ok.
951 return false;
Chris Lattner86395032006-09-30 23:32:09 +0000952 }
953 }
954 return true;
955}
956
Chris Lattnera637a8b2007-09-13 18:00:31 +0000957/// GetHeapSROALoad - Return the load for the specified field of the HeapSROA'd
958/// value, lazily creating it on demand.
Chris Lattner309f20f2007-09-13 21:31:36 +0000959static Value *GetHeapSROALoad(Instruction *Load, unsigned FieldNo,
Chris Lattnera637a8b2007-09-13 18:00:31 +0000960 const std::vector<GlobalVariable*> &FieldGlobals,
961 std::vector<Value *> &InsertedLoadsForPtr) {
962 if (InsertedLoadsForPtr.size() <= FieldNo)
963 InsertedLoadsForPtr.resize(FieldNo+1);
964 if (InsertedLoadsForPtr[FieldNo] == 0)
965 InsertedLoadsForPtr[FieldNo] = new LoadInst(FieldGlobals[FieldNo],
966 Load->getName()+".f" +
967 utostr(FieldNo), Load);
968 return InsertedLoadsForPtr[FieldNo];
969}
970
Chris Lattner330245e2007-09-13 17:29:05 +0000971/// RewriteHeapSROALoadUser - Given a load instruction and a value derived from
972/// the load, rewrite the derived value to use the HeapSRoA'd load.
973static void RewriteHeapSROALoadUser(LoadInst *Load, Instruction *LoadUser,
974 const std::vector<GlobalVariable*> &FieldGlobals,
975 std::vector<Value *> &InsertedLoadsForPtr) {
976 // If this is a comparison against null, handle it.
977 if (ICmpInst *SCI = dyn_cast<ICmpInst>(LoadUser)) {
978 assert(isa<ConstantPointerNull>(SCI->getOperand(1)));
979 // If we have a setcc of the loaded pointer, we can use a setcc of any
980 // field.
981 Value *NPtr;
982 if (InsertedLoadsForPtr.empty()) {
Chris Lattnera637a8b2007-09-13 18:00:31 +0000983 NPtr = GetHeapSROALoad(Load, 0, FieldGlobals, InsertedLoadsForPtr);
Chris Lattner330245e2007-09-13 17:29:05 +0000984 } else {
985 NPtr = InsertedLoadsForPtr.back();
986 }
987
988 Value *New = new ICmpInst(SCI->getPredicate(), NPtr,
989 Constant::getNullValue(NPtr->getType()),
990 SCI->getName(), SCI);
991 SCI->replaceAllUsesWith(New);
992 SCI->eraseFromParent();
993 return;
994 }
995
Chris Lattnera637a8b2007-09-13 18:00:31 +0000996 // Handle 'getelementptr Ptr, Idx, uint FieldNo ...'
997 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(LoadUser)) {
998 assert(GEPI->getNumOperands() >= 3 && isa<ConstantInt>(GEPI->getOperand(2))
999 && "Unexpected GEPI!");
Chris Lattner330245e2007-09-13 17:29:05 +00001000
Chris Lattnera637a8b2007-09-13 18:00:31 +00001001 // Load the pointer for this field.
1002 unsigned FieldNo = cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue();
1003 Value *NewPtr = GetHeapSROALoad(Load, FieldNo,
1004 FieldGlobals, InsertedLoadsForPtr);
1005
1006 // Create the new GEP idx vector.
1007 SmallVector<Value*, 8> GEPIdx;
1008 GEPIdx.push_back(GEPI->getOperand(1));
1009 GEPIdx.append(GEPI->op_begin()+3, GEPI->op_end());
1010
1011 Value *NGEPI = new GetElementPtrInst(NewPtr, GEPIdx.begin(), GEPIdx.end(),
1012 GEPI->getName(), GEPI);
1013 GEPI->replaceAllUsesWith(NGEPI);
1014 GEPI->eraseFromParent();
1015 return;
1016 }
Chris Lattner330245e2007-09-13 17:29:05 +00001017
Chris Lattner309f20f2007-09-13 21:31:36 +00001018 // Handle PHI nodes. PHI nodes must be merging in the same values, plus
1019 // potentially the original malloc. Insert phi nodes for each field, then
1020 // process uses of the PHI.
Chris Lattnera637a8b2007-09-13 18:00:31 +00001021 PHINode *PN = cast<PHINode>(LoadUser);
Chris Lattner309f20f2007-09-13 21:31:36 +00001022 std::vector<Value *> PHIsForField;
1023 PHIsForField.resize(FieldGlobals.size());
1024 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
1025 Value *LoadV = GetHeapSROALoad(Load, i, FieldGlobals, InsertedLoadsForPtr);
1026
1027 PHINode *FieldPN = new PHINode(LoadV->getType(),
1028 PN->getName()+"."+utostr(i), PN);
1029 // Fill in the predecessor values.
1030 for (unsigned pred = 0, e = PN->getNumIncomingValues(); pred != e; ++pred) {
1031 // Each predecessor either uses the load or the original malloc.
1032 Value *InVal = PN->getIncomingValue(pred);
1033 BasicBlock *BB = PN->getIncomingBlock(pred);
1034 Value *NewVal;
1035 if (isa<MallocInst>(InVal)) {
1036 // Insert a reload from the global in the predecessor.
1037 NewVal = GetHeapSROALoad(BB->getTerminator(), i, FieldGlobals,
1038 PHIsForField);
1039 } else {
1040 NewVal = InsertedLoadsForPtr[i];
1041 }
1042 FieldPN->addIncoming(NewVal, BB);
1043 }
1044 PHIsForField[i] = FieldPN;
1045 }
1046
1047 // Since PHIsForField specifies a phi for every input value, the lazy inserter
1048 // will never insert a load.
Chris Lattnera637a8b2007-09-13 18:00:31 +00001049 while (!PN->use_empty())
Chris Lattner309f20f2007-09-13 21:31:36 +00001050 RewriteHeapSROALoadUser(Load, PN->use_back(), FieldGlobals, PHIsForField);
Chris Lattnera637a8b2007-09-13 18:00:31 +00001051 PN->eraseFromParent();
Chris Lattner330245e2007-09-13 17:29:05 +00001052}
1053
Chris Lattner86395032006-09-30 23:32:09 +00001054/// RewriteUsesOfLoadForHeapSRoA - We are performing Heap SRoA on a global. Ptr
1055/// is a value loaded from the global. Eliminate all uses of Ptr, making them
1056/// use FieldGlobals instead. All uses of loaded values satisfy
1057/// GlobalLoadUsesSimpleEnoughForHeapSRA.
Chris Lattner330245e2007-09-13 17:29:05 +00001058static void RewriteUsesOfLoadForHeapSRoA(LoadInst *Load,
Chris Lattner86395032006-09-30 23:32:09 +00001059 const std::vector<GlobalVariable*> &FieldGlobals) {
1060 std::vector<Value *> InsertedLoadsForPtr;
1061 //InsertedLoadsForPtr.resize(FieldGlobals.size());
Chris Lattner330245e2007-09-13 17:29:05 +00001062 while (!Load->use_empty())
1063 RewriteHeapSROALoadUser(Load, Load->use_back(),
1064 FieldGlobals, InsertedLoadsForPtr);
Chris Lattner86395032006-09-30 23:32:09 +00001065}
1066
1067/// PerformHeapAllocSRoA - MI is an allocation of an array of structures. Break
1068/// it up into multiple allocations of arrays of the fields.
1069static GlobalVariable *PerformHeapAllocSRoA(GlobalVariable *GV, MallocInst *MI){
Bill Wendling0a81aac2006-11-26 10:02:32 +00001070 DOUT << "SROA HEAP ALLOC: " << *GV << " MALLOC = " << *MI;
Chris Lattner86395032006-09-30 23:32:09 +00001071 const StructType *STy = cast<StructType>(MI->getAllocatedType());
1072
1073 // There is guaranteed to be at least one use of the malloc (storing
1074 // it into GV). If there are other uses, change them to be uses of
1075 // the global to simplify later code. This also deletes the store
1076 // into GV.
1077 ReplaceUsesOfMallocWithGlobal(MI, GV);
1078
1079 // Okay, at this point, there are no users of the malloc. Insert N
1080 // new mallocs at the same place as MI, and N globals.
1081 std::vector<GlobalVariable*> FieldGlobals;
1082 std::vector<MallocInst*> FieldMallocs;
1083
1084 for (unsigned FieldNo = 0, e = STy->getNumElements(); FieldNo != e;++FieldNo){
1085 const Type *FieldTy = STy->getElementType(FieldNo);
Christopher Lamb43ad6b32007-12-17 01:12:55 +00001086 const Type *PFieldTy = PointerType::getUnqual(FieldTy);
Chris Lattner86395032006-09-30 23:32:09 +00001087
1088 GlobalVariable *NGV =
1089 new GlobalVariable(PFieldTy, false, GlobalValue::InternalLinkage,
1090 Constant::getNullValue(PFieldTy),
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +00001091 GV->getName() + ".f" + utostr(FieldNo), GV,
1092 GV->isThreadLocal());
Chris Lattner86395032006-09-30 23:32:09 +00001093 FieldGlobals.push_back(NGV);
1094
1095 MallocInst *NMI = new MallocInst(FieldTy, MI->getArraySize(),
1096 MI->getName() + ".f" + utostr(FieldNo),MI);
1097 FieldMallocs.push_back(NMI);
1098 new StoreInst(NMI, NGV, MI);
1099 }
1100
1101 // The tricky aspect of this transformation is handling the case when malloc
1102 // fails. In the original code, malloc failing would set the result pointer
1103 // of malloc to null. In this case, some mallocs could succeed and others
1104 // could fail. As such, we emit code that looks like this:
1105 // F0 = malloc(field0)
1106 // F1 = malloc(field1)
1107 // F2 = malloc(field2)
1108 // if (F0 == 0 || F1 == 0 || F2 == 0) {
1109 // if (F0) { free(F0); F0 = 0; }
1110 // if (F1) { free(F1); F1 = 0; }
1111 // if (F2) { free(F2); F2 = 0; }
1112 // }
1113 Value *RunningOr = 0;
1114 for (unsigned i = 0, e = FieldMallocs.size(); i != e; ++i) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001115 Value *Cond = new ICmpInst(ICmpInst::ICMP_EQ, FieldMallocs[i],
Chris Lattner86395032006-09-30 23:32:09 +00001116 Constant::getNullValue(FieldMallocs[i]->getType()),
1117 "isnull", MI);
1118 if (!RunningOr)
1119 RunningOr = Cond; // First seteq
1120 else
1121 RunningOr = BinaryOperator::createOr(RunningOr, Cond, "tmp", MI);
1122 }
1123
1124 // Split the basic block at the old malloc.
1125 BasicBlock *OrigBB = MI->getParent();
1126 BasicBlock *ContBB = OrigBB->splitBasicBlock(MI, "malloc_cont");
1127
1128 // Create the block to check the first condition. Put all these blocks at the
1129 // end of the function as they are unlikely to be executed.
1130 BasicBlock *NullPtrBlock = new BasicBlock("malloc_ret_null",
1131 OrigBB->getParent());
1132
1133 // Remove the uncond branch from OrigBB to ContBB, turning it into a cond
1134 // branch on RunningOr.
1135 OrigBB->getTerminator()->eraseFromParent();
1136 new BranchInst(NullPtrBlock, ContBB, RunningOr, OrigBB);
1137
1138 // Within the NullPtrBlock, we need to emit a comparison and branch for each
1139 // pointer, because some may be null while others are not.
1140 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
1141 Value *GVVal = new LoadInst(FieldGlobals[i], "tmp", NullPtrBlock);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001142 Value *Cmp = new ICmpInst(ICmpInst::ICMP_NE, GVVal,
1143 Constant::getNullValue(GVVal->getType()),
1144 "tmp", NullPtrBlock);
Chris Lattner86395032006-09-30 23:32:09 +00001145 BasicBlock *FreeBlock = new BasicBlock("free_it", OrigBB->getParent());
1146 BasicBlock *NextBlock = new BasicBlock("next", OrigBB->getParent());
1147 new BranchInst(FreeBlock, NextBlock, Cmp, NullPtrBlock);
1148
1149 // Fill in FreeBlock.
1150 new FreeInst(GVVal, FreeBlock);
1151 new StoreInst(Constant::getNullValue(GVVal->getType()), FieldGlobals[i],
1152 FreeBlock);
1153 new BranchInst(NextBlock, FreeBlock);
1154
1155 NullPtrBlock = NextBlock;
1156 }
1157
1158 new BranchInst(ContBB, NullPtrBlock);
1159
1160
1161 // MI is no longer needed, remove it.
1162 MI->eraseFromParent();
1163
1164
1165 // Okay, the malloc site is completely handled. All of the uses of GV are now
1166 // loads, and all uses of those loads are simple. Rewrite them to use loads
1167 // of the per-field globals instead.
1168 while (!GV->use_empty()) {
Chris Lattner39ff1e22007-01-09 23:29:37 +00001169 if (LoadInst *LI = dyn_cast<LoadInst>(GV->use_back())) {
1170 RewriteUsesOfLoadForHeapSRoA(LI, FieldGlobals);
1171 LI->eraseFromParent();
1172 } else {
1173 // Must be a store of null.
1174 StoreInst *SI = cast<StoreInst>(GV->use_back());
1175 assert(isa<Constant>(SI->getOperand(0)) &&
1176 cast<Constant>(SI->getOperand(0))->isNullValue() &&
1177 "Unexpected heap-sra user!");
1178
1179 // Insert a store of null into each global.
1180 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
1181 Constant *Null =
1182 Constant::getNullValue(FieldGlobals[i]->getType()->getElementType());
1183 new StoreInst(Null, FieldGlobals[i], SI);
1184 }
1185 // Erase the original store.
1186 SI->eraseFromParent();
1187 }
Chris Lattner86395032006-09-30 23:32:09 +00001188 }
1189
1190 // The old global is now dead, remove it.
1191 GV->eraseFromParent();
1192
1193 ++NumHeapSRA;
1194 return FieldGlobals[0];
1195}
1196
1197
Chris Lattner9b34a612004-10-09 21:48:45 +00001198// OptimizeOnceStoredGlobal - Try to optimize globals based on the knowledge
1199// that only one value (besides its initializer) is ever stored to the global.
Chris Lattner30ba5692004-10-11 05:54:41 +00001200static bool OptimizeOnceStoredGlobal(GlobalVariable *GV, Value *StoredOnceVal,
Chris Lattner7f8897f2006-08-27 22:42:52 +00001201 Module::global_iterator &GVI,
1202 TargetData &TD) {
Chris Lattner9b34a612004-10-09 21:48:45 +00001203 if (CastInst *CI = dyn_cast<CastInst>(StoredOnceVal))
1204 StoredOnceVal = CI->getOperand(0);
1205 else if (GetElementPtrInst *GEPI =dyn_cast<GetElementPtrInst>(StoredOnceVal)){
Chris Lattner708148e2004-10-10 23:14:11 +00001206 // "getelementptr Ptr, 0, 0, 0" is really just a cast.
Chris Lattner9b34a612004-10-09 21:48:45 +00001207 bool IsJustACast = true;
1208 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
1209 if (!isa<Constant>(GEPI->getOperand(i)) ||
1210 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
1211 IsJustACast = false;
1212 break;
1213 }
1214 if (IsJustACast)
1215 StoredOnceVal = GEPI->getOperand(0);
1216 }
1217
Chris Lattner708148e2004-10-10 23:14:11 +00001218 // If we are dealing with a pointer global that is initialized to null and
1219 // only has one (non-null) value stored into it, then we can optimize any
1220 // users of the loaded value (often calls and loads) that would trap if the
1221 // value was null.
Chris Lattner9b34a612004-10-09 21:48:45 +00001222 if (isa<PointerType>(GV->getInitializer()->getType()) &&
1223 GV->getInitializer()->isNullValue()) {
Chris Lattner708148e2004-10-10 23:14:11 +00001224 if (Constant *SOVC = dyn_cast<Constant>(StoredOnceVal)) {
1225 if (GV->getInitializer()->getType() != SOVC->getType())
Reid Spencerd977d862006-12-12 23:36:14 +00001226 SOVC = ConstantExpr::getBitCast(SOVC, GV->getInitializer()->getType());
Misha Brukmanfd939082005-04-21 23:48:37 +00001227
Chris Lattner708148e2004-10-10 23:14:11 +00001228 // Optimize away any trapping uses of the loaded value.
1229 if (OptimizeAwayTrappingUsesOfLoads(GV, SOVC))
Chris Lattner8be80122004-10-10 17:07:12 +00001230 return true;
Chris Lattner30ba5692004-10-11 05:54:41 +00001231 } else if (MallocInst *MI = dyn_cast<MallocInst>(StoredOnceVal)) {
Chris Lattnercff16732006-09-30 19:40:30 +00001232 // If this is a malloc of an abstract type, don't touch it.
1233 if (!MI->getAllocatedType()->isSized())
1234 return false;
1235
Chris Lattner86395032006-09-30 23:32:09 +00001236 // We can't optimize this global unless all uses of it are *known* to be
1237 // of the malloc value, not of the null initializer value (consider a use
1238 // that compares the global's value against zero to see if the malloc has
1239 // been reached). To do this, we check to see if all uses of the global
1240 // would trap if the global were null: this proves that they must all
1241 // happen after the malloc.
1242 if (!AllUsesOfLoadedValueWillTrapIfNull(GV))
1243 return false;
1244
1245 // We can't optimize this if the malloc itself is used in a complex way,
1246 // for example, being stored into multiple globals. This allows the
1247 // malloc to be stored into the specified global, loaded setcc'd, and
1248 // GEP'd. These are all things we could transform to using the global
1249 // for.
Chris Lattnerc451f9c2007-09-13 16:37:20 +00001250 {
1251 SmallPtrSet<PHINode*, 8> PHIs;
1252 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(MI, GV, PHIs))
1253 return false;
1254 }
Chris Lattner86395032006-09-30 23:32:09 +00001255
1256
Chris Lattner30ba5692004-10-11 05:54:41 +00001257 // If we have a global that is only initialized with a fixed size malloc,
Chris Lattner86395032006-09-30 23:32:09 +00001258 // transform the program to use global memory instead of malloc'd memory.
1259 // This eliminates dynamic allocation, avoids an indirection accessing the
1260 // data, and exposes the resultant global to further GlobalOpt.
Chris Lattnercff16732006-09-30 19:40:30 +00001261 if (ConstantInt *NElements = dyn_cast<ConstantInt>(MI->getArraySize())) {
Chris Lattner86395032006-09-30 23:32:09 +00001262 // Restrict this transformation to only working on small allocations
1263 // (2048 bytes currently), as we don't want to introduce a 16M global or
1264 // something.
Reid Spencerb83eb642006-10-20 07:07:24 +00001265 if (NElements->getZExtValue()*
Duncan Sands514ab342007-11-01 20:53:16 +00001266 TD.getABITypeSize(MI->getAllocatedType()) < 2048) {
Chris Lattner30ba5692004-10-11 05:54:41 +00001267 GVI = OptimizeGlobalAddressOfMalloc(GV, MI);
1268 return true;
1269 }
Chris Lattnercff16732006-09-30 19:40:30 +00001270 }
Chris Lattner86395032006-09-30 23:32:09 +00001271
1272 // If the allocation is an array of structures, consider transforming this
1273 // into multiple malloc'd arrays, one for each field. This is basically
1274 // SRoA for malloc'd memory.
1275 if (const StructType *AllocTy =
1276 dyn_cast<StructType>(MI->getAllocatedType())) {
1277 // This the structure has an unreasonable number of fields, leave it
1278 // alone.
1279 if (AllocTy->getNumElements() <= 16 && AllocTy->getNumElements() > 0 &&
Chris Lattner309f20f2007-09-13 21:31:36 +00001280 GlobalLoadUsesSimpleEnoughForHeapSRA(GV, MI)) {
Chris Lattner86395032006-09-30 23:32:09 +00001281 GVI = PerformHeapAllocSRoA(GV, MI);
1282 return true;
1283 }
1284 }
Chris Lattner708148e2004-10-10 23:14:11 +00001285 }
Chris Lattner9b34a612004-10-09 21:48:45 +00001286 }
Chris Lattner30ba5692004-10-11 05:54:41 +00001287
Chris Lattner9b34a612004-10-09 21:48:45 +00001288 return false;
1289}
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001290
Chris Lattner58e44f42008-01-14 01:17:44 +00001291/// TryToShrinkGlobalToBoolean - At this point, we have learned that the only
1292/// two values ever stored into GV are its initializer and OtherVal. See if we
1293/// can shrink the global into a boolean and select between the two values
1294/// whenever it is used. This exposes the values to other scalar optimizations.
1295static bool TryToShrinkGlobalToBoolean(GlobalVariable *GV, Constant *OtherVal) {
1296 const Type *GVElType = GV->getType()->getElementType();
1297
1298 // If GVElType is already i1, it is already shrunk. If the type of the GV is
1299 // an FP value or vector, don't do this optimization because a select between
1300 // them is very expensive and unlikely to lead to later simplification.
1301 if (GVElType == Type::Int1Ty || GVElType->isFloatingPoint() ||
1302 isa<VectorType>(GVElType))
1303 return false;
1304
1305 // Walk the use list of the global seeing if all the uses are load or store.
1306 // If there is anything else, bail out.
1307 for (Value::use_iterator I = GV->use_begin(), E = GV->use_end(); I != E; ++I)
1308 if (!isa<LoadInst>(I) && !isa<StoreInst>(I))
1309 return false;
1310
1311 DOUT << " *** SHRINKING TO BOOL: " << *GV;
1312
Chris Lattner96a86b22004-12-12 05:53:50 +00001313 // Create the new global, initializing it to false.
Reid Spencer4fe16d62007-01-11 18:21:29 +00001314 GlobalVariable *NewGV = new GlobalVariable(Type::Int1Ty, false,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001315 GlobalValue::InternalLinkage, ConstantInt::getFalse(),
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +00001316 GV->getName()+".b",
1317 (Module *)NULL,
1318 GV->isThreadLocal());
Chris Lattner96a86b22004-12-12 05:53:50 +00001319 GV->getParent()->getGlobalList().insert(GV, NewGV);
1320
1321 Constant *InitVal = GV->getInitializer();
Reid Spencer4fe16d62007-01-11 18:21:29 +00001322 assert(InitVal->getType() != Type::Int1Ty && "No reason to shrink to bool!");
Chris Lattner96a86b22004-12-12 05:53:50 +00001323
1324 // If initialized to zero and storing one into the global, we can use a cast
1325 // instead of a select to synthesize the desired value.
1326 bool IsOneZero = false;
1327 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal))
Reid Spencercae57542007-03-02 00:28:52 +00001328 IsOneZero = InitVal->isNullValue() && CI->isOne();
Chris Lattner96a86b22004-12-12 05:53:50 +00001329
1330 while (!GV->use_empty()) {
1331 Instruction *UI = cast<Instruction>(GV->use_back());
1332 if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
1333 // Change the store into a boolean store.
1334 bool StoringOther = SI->getOperand(0) == OtherVal;
1335 // Only do this if we weren't storing a loaded value.
Chris Lattner38c25562004-12-12 19:34:41 +00001336 Value *StoreVal;
Chris Lattner96a86b22004-12-12 05:53:50 +00001337 if (StoringOther || SI->getOperand(0) == InitVal)
Reid Spencer579dca12007-01-12 04:24:46 +00001338 StoreVal = ConstantInt::get(Type::Int1Ty, StoringOther);
Chris Lattner38c25562004-12-12 19:34:41 +00001339 else {
1340 // Otherwise, we are storing a previously loaded copy. To do this,
1341 // change the copy from copying the original value to just copying the
1342 // bool.
1343 Instruction *StoredVal = cast<Instruction>(SI->getOperand(0));
1344
1345 // If we're already replaced the input, StoredVal will be a cast or
1346 // select instruction. If not, it will be a load of the original
1347 // global.
1348 if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
1349 assert(LI->getOperand(0) == GV && "Not a copy!");
1350 // Insert a new load, to preserve the saved value.
1351 StoreVal = new LoadInst(NewGV, LI->getName()+".b", LI);
1352 } else {
1353 assert((isa<CastInst>(StoredVal) || isa<SelectInst>(StoredVal)) &&
1354 "This is not a form that we understand!");
1355 StoreVal = StoredVal->getOperand(0);
1356 assert(isa<LoadInst>(StoreVal) && "Not a load of NewGV!");
1357 }
1358 }
1359 new StoreInst(StoreVal, NewGV, SI);
Chris Lattner58e44f42008-01-14 01:17:44 +00001360 } else {
Chris Lattner96a86b22004-12-12 05:53:50 +00001361 // Change the load into a load of bool then a select.
1362 LoadInst *LI = cast<LoadInst>(UI);
Chris Lattner046800a2007-02-11 01:08:35 +00001363 LoadInst *NLI = new LoadInst(NewGV, LI->getName()+".b", LI);
Chris Lattner96a86b22004-12-12 05:53:50 +00001364 Value *NSI;
1365 if (IsOneZero)
Chris Lattner046800a2007-02-11 01:08:35 +00001366 NSI = new ZExtInst(NLI, LI->getType(), "", LI);
Misha Brukmanfd939082005-04-21 23:48:37 +00001367 else
Chris Lattner046800a2007-02-11 01:08:35 +00001368 NSI = new SelectInst(NLI, OtherVal, InitVal, "", LI);
1369 NSI->takeName(LI);
Chris Lattner96a86b22004-12-12 05:53:50 +00001370 LI->replaceAllUsesWith(NSI);
1371 }
1372 UI->eraseFromParent();
1373 }
1374
1375 GV->eraseFromParent();
Chris Lattner58e44f42008-01-14 01:17:44 +00001376 return true;
Chris Lattner96a86b22004-12-12 05:53:50 +00001377}
1378
1379
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001380/// ProcessInternalGlobal - Analyze the specified global variable and optimize
1381/// it if possible. If we make a change, return true.
Chris Lattner30ba5692004-10-11 05:54:41 +00001382bool GlobalOpt::ProcessInternalGlobal(GlobalVariable *GV,
Chris Lattnere4d5c442005-03-15 04:54:21 +00001383 Module::global_iterator &GVI) {
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001384 std::set<PHINode*> PHIUsers;
1385 GlobalStatus GS;
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001386 GV->removeDeadConstantUsers();
1387
1388 if (GV->use_empty()) {
Bill Wendling0a81aac2006-11-26 10:02:32 +00001389 DOUT << "GLOBAL DEAD: " << *GV;
Chris Lattner7a7ed022004-10-16 18:09:00 +00001390 GV->eraseFromParent();
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001391 ++NumDeleted;
1392 return true;
1393 }
1394
1395 if (!AnalyzeGlobal(GV, GS, PHIUsers)) {
Chris Lattnercff16732006-09-30 19:40:30 +00001396#if 0
Bill Wendlinge8156192006-12-07 01:30:32 +00001397 cerr << "Global: " << *GV;
1398 cerr << " isLoaded = " << GS.isLoaded << "\n";
1399 cerr << " StoredType = ";
Chris Lattnercff16732006-09-30 19:40:30 +00001400 switch (GS.StoredType) {
Bill Wendlinge8156192006-12-07 01:30:32 +00001401 case GlobalStatus::NotStored: cerr << "NEVER STORED\n"; break;
1402 case GlobalStatus::isInitializerStored: cerr << "INIT STORED\n"; break;
1403 case GlobalStatus::isStoredOnce: cerr << "STORED ONCE\n"; break;
1404 case GlobalStatus::isStored: cerr << "stored\n"; break;
Chris Lattnercff16732006-09-30 19:40:30 +00001405 }
1406 if (GS.StoredType == GlobalStatus::isStoredOnce && GS.StoredOnceValue)
Bill Wendlinge8156192006-12-07 01:30:32 +00001407 cerr << " StoredOnceValue = " << *GS.StoredOnceValue << "\n";
Chris Lattnercff16732006-09-30 19:40:30 +00001408 if (GS.AccessingFunction && !GS.HasMultipleAccessingFunctions)
Bill Wendlinge8156192006-12-07 01:30:32 +00001409 cerr << " AccessingFunction = " << GS.AccessingFunction->getName()
Chris Lattnercff16732006-09-30 19:40:30 +00001410 << "\n";
Bill Wendlinge8156192006-12-07 01:30:32 +00001411 cerr << " HasMultipleAccessingFunctions = "
Chris Lattnercff16732006-09-30 19:40:30 +00001412 << GS.HasMultipleAccessingFunctions << "\n";
Bill Wendlinge8156192006-12-07 01:30:32 +00001413 cerr << " HasNonInstructionUser = " << GS.HasNonInstructionUser<<"\n";
Bill Wendlinge8156192006-12-07 01:30:32 +00001414 cerr << "\n";
Chris Lattnercff16732006-09-30 19:40:30 +00001415#endif
1416
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +00001417 // If this is a first class global and has only one accessing function
1418 // and this function is main (which we know is not recursive we can make
1419 // this global a local variable) we replace the global with a local alloca
1420 // in this function.
1421 //
1422 // NOTE: It doesn't make sense to promote non first class types since we
1423 // are just replacing static memory to stack memory.
1424 if (!GS.HasMultipleAccessingFunctions &&
Chris Lattner553ca522005-06-15 21:11:48 +00001425 GS.AccessingFunction && !GS.HasNonInstructionUser &&
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +00001426 GV->getType()->getElementType()->isFirstClassType() &&
1427 GS.AccessingFunction->getName() == "main" &&
1428 GS.AccessingFunction->hasExternalLinkage()) {
Bill Wendling0a81aac2006-11-26 10:02:32 +00001429 DOUT << "LOCALIZING GLOBAL: " << *GV;
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +00001430 Instruction* FirstI = GS.AccessingFunction->getEntryBlock().begin();
1431 const Type* ElemTy = GV->getType()->getElementType();
Nate Begeman14b05292005-11-05 09:21:28 +00001432 // FIXME: Pass Global's alignment when globals have alignment
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +00001433 AllocaInst* Alloca = new AllocaInst(ElemTy, NULL, GV->getName(), FirstI);
1434 if (!isa<UndefValue>(GV->getInitializer()))
1435 new StoreInst(GV->getInitializer(), Alloca, FirstI);
Misha Brukmanfd939082005-04-21 23:48:37 +00001436
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +00001437 GV->replaceAllUsesWith(Alloca);
1438 GV->eraseFromParent();
1439 ++NumLocalized;
1440 return true;
1441 }
Chris Lattnercff16732006-09-30 19:40:30 +00001442
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001443 // If the global is never loaded (but may be stored to), it is dead.
1444 // Delete it now.
1445 if (!GS.isLoaded) {
Bill Wendling0a81aac2006-11-26 10:02:32 +00001446 DOUT << "GLOBAL NEVER LOADED: " << *GV;
Chris Lattner930f4752004-10-09 03:32:52 +00001447
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001448 // Delete any stores we can find to the global. We may not be able to
1449 // make it completely dead though.
Chris Lattner031955d2004-10-10 16:43:46 +00001450 bool Changed = CleanupConstantGlobalUsers(GV, GV->getInitializer());
Chris Lattner930f4752004-10-09 03:32:52 +00001451
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001452 // If the global is dead now, delete it.
1453 if (GV->use_empty()) {
Chris Lattner7a7ed022004-10-16 18:09:00 +00001454 GV->eraseFromParent();
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001455 ++NumDeleted;
Chris Lattner930f4752004-10-09 03:32:52 +00001456 Changed = true;
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001457 }
Chris Lattner930f4752004-10-09 03:32:52 +00001458 return Changed;
Misha Brukmanfd939082005-04-21 23:48:37 +00001459
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001460 } else if (GS.StoredType <= GlobalStatus::isInitializerStored) {
Bill Wendling0a81aac2006-11-26 10:02:32 +00001461 DOUT << "MARKING CONSTANT: " << *GV;
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001462 GV->setConstant(true);
Misha Brukmanfd939082005-04-21 23:48:37 +00001463
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001464 // Clean up any obviously simplifiable users now.
1465 CleanupConstantGlobalUsers(GV, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +00001466
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001467 // If the global is dead now, just nuke it.
1468 if (GV->use_empty()) {
Bill Wendling0a81aac2006-11-26 10:02:32 +00001469 DOUT << " *** Marking constant allowed us to simplify "
1470 << "all users and delete global!\n";
Chris Lattner7a7ed022004-10-16 18:09:00 +00001471 GV->eraseFromParent();
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001472 ++NumDeleted;
1473 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001474
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001475 ++NumMarked;
1476 return true;
Chris Lattner727c2102008-01-14 01:31:05 +00001477 } else if (!GV->getInitializer()->getType()->isFirstClassType()) {
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001478 if (GlobalVariable *FirstNewGV = SRAGlobal(GV)) {
1479 GVI = FirstNewGV; // Don't skip the newly produced globals!
1480 return true;
1481 }
Chris Lattner9b34a612004-10-09 21:48:45 +00001482 } else if (GS.StoredType == GlobalStatus::isStoredOnce) {
Chris Lattner96a86b22004-12-12 05:53:50 +00001483 // If the initial value for the global was an undef value, and if only
1484 // one other value was stored into it, we can just change the
1485 // initializer to be an undef value, then delete all stores to the
1486 // global. This allows us to mark it constant.
1487 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
1488 if (isa<UndefValue>(GV->getInitializer())) {
1489 // Change the initial value here.
1490 GV->setInitializer(SOVConstant);
Misha Brukmanfd939082005-04-21 23:48:37 +00001491
Chris Lattner96a86b22004-12-12 05:53:50 +00001492 // Clean up any obviously simplifiable users now.
1493 CleanupConstantGlobalUsers(GV, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +00001494
Chris Lattner96a86b22004-12-12 05:53:50 +00001495 if (GV->use_empty()) {
Bill Wendling0a81aac2006-11-26 10:02:32 +00001496 DOUT << " *** Substituting initializer allowed us to "
1497 << "simplify all users and delete global!\n";
Chris Lattner96a86b22004-12-12 05:53:50 +00001498 GV->eraseFromParent();
1499 ++NumDeleted;
1500 } else {
1501 GVI = GV;
1502 }
1503 ++NumSubstitute;
1504 return true;
Chris Lattner7a7ed022004-10-16 18:09:00 +00001505 }
Chris Lattner7a7ed022004-10-16 18:09:00 +00001506
Chris Lattner9b34a612004-10-09 21:48:45 +00001507 // Try to optimize globals based on the knowledge that only one value
1508 // (besides its initializer) is ever stored to the global.
Chris Lattner30ba5692004-10-11 05:54:41 +00001509 if (OptimizeOnceStoredGlobal(GV, GS.StoredOnceValue, GVI,
1510 getAnalysis<TargetData>()))
Chris Lattner9b34a612004-10-09 21:48:45 +00001511 return true;
Chris Lattner96a86b22004-12-12 05:53:50 +00001512
1513 // Otherwise, if the global was not a boolean, we can shrink it to be a
1514 // boolean.
1515 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
Chris Lattner58e44f42008-01-14 01:17:44 +00001516 if (TryToShrinkGlobalToBoolean(GV, SOVConstant)) {
Chris Lattner96a86b22004-12-12 05:53:50 +00001517 ++NumShrunkToBool;
1518 return true;
1519 }
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001520 }
1521 }
1522 return false;
1523}
1524
Chris Lattnerfb217ad2005-05-08 22:18:06 +00001525/// OnlyCalledDirectly - Return true if the specified function is only called
1526/// directly. In other words, its address is never taken.
1527static bool OnlyCalledDirectly(Function *F) {
1528 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
1529 Instruction *User = dyn_cast<Instruction>(*UI);
1530 if (!User) return false;
1531 if (!isa<CallInst>(User) && !isa<InvokeInst>(User)) return false;
1532
1533 // See if the function address is passed as an argument.
1534 for (unsigned i = 1, e = User->getNumOperands(); i != e; ++i)
1535 if (User->getOperand(i) == F) return false;
1536 }
1537 return true;
1538}
1539
1540/// ChangeCalleesToFastCall - Walk all of the direct calls of the specified
1541/// function, changing them to FastCC.
1542static void ChangeCalleesToFastCall(Function *F) {
1543 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
1544 Instruction *User = cast<Instruction>(*UI);
1545 if (CallInst *CI = dyn_cast<CallInst>(User))
1546 CI->setCallingConv(CallingConv::Fast);
1547 else
1548 cast<InvokeInst>(User)->setCallingConv(CallingConv::Fast);
1549 }
1550}
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001551
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001552bool GlobalOpt::OptimizeFunctions(Module &M) {
1553 bool Changed = false;
1554 // Optimize functions.
1555 for (Module::iterator FI = M.begin(), E = M.end(); FI != E; ) {
1556 Function *F = FI++;
1557 F->removeDeadConstantUsers();
1558 if (F->use_empty() && (F->hasInternalLinkage() ||
1559 F->hasLinkOnceLinkage())) {
1560 M.getFunctionList().erase(F);
1561 Changed = true;
1562 ++NumFnDeleted;
1563 } else if (F->hasInternalLinkage() &&
1564 F->getCallingConv() == CallingConv::C && !F->isVarArg() &&
1565 OnlyCalledDirectly(F)) {
1566 // If this function has C calling conventions, is not a varargs
1567 // function, and is only called directly, promote it to use the Fast
1568 // calling convention.
1569 F->setCallingConv(CallingConv::Fast);
1570 ChangeCalleesToFastCall(F);
1571 ++NumFastCallFns;
1572 Changed = true;
1573 }
1574 }
1575 return Changed;
1576}
1577
1578bool GlobalOpt::OptimizeGlobalVars(Module &M) {
1579 bool Changed = false;
1580 for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
1581 GVI != E; ) {
1582 GlobalVariable *GV = GVI++;
1583 if (!GV->isConstant() && GV->hasInternalLinkage() &&
1584 GV->hasInitializer())
1585 Changed |= ProcessInternalGlobal(GV, GVI);
1586 }
1587 return Changed;
1588}
1589
1590/// FindGlobalCtors - Find the llvm.globalctors list, verifying that all
1591/// initializers have an init priority of 65535.
1592GlobalVariable *GlobalOpt::FindGlobalCtors(Module &M) {
Alkis Evlogimenose9c6d362005-10-25 11:18:06 +00001593 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1594 I != E; ++I)
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001595 if (I->getName() == "llvm.global_ctors") {
1596 // Found it, verify it's an array of { int, void()* }.
1597 const ArrayType *ATy =dyn_cast<ArrayType>(I->getType()->getElementType());
1598 if (!ATy) return 0;
1599 const StructType *STy = dyn_cast<StructType>(ATy->getElementType());
1600 if (!STy || STy->getNumElements() != 2 ||
Reid Spencerc5b206b2006-12-31 05:48:39 +00001601 STy->getElementType(0) != Type::Int32Ty) return 0;
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001602 const PointerType *PFTy = dyn_cast<PointerType>(STy->getElementType(1));
1603 if (!PFTy) return 0;
1604 const FunctionType *FTy = dyn_cast<FunctionType>(PFTy->getElementType());
1605 if (!FTy || FTy->getReturnType() != Type::VoidTy || FTy->isVarArg() ||
1606 FTy->getNumParams() != 0)
1607 return 0;
1608
1609 // Verify that the initializer is simple enough for us to handle.
1610 if (!I->hasInitializer()) return 0;
1611 ConstantArray *CA = dyn_cast<ConstantArray>(I->getInitializer());
1612 if (!CA) return 0;
1613 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1614 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(CA->getOperand(i))) {
Chris Lattner7d8e58f2005-09-26 02:19:27 +00001615 if (isa<ConstantPointerNull>(CS->getOperand(1)))
1616 continue;
1617
1618 // Must have a function or null ptr.
1619 if (!isa<Function>(CS->getOperand(1)))
1620 return 0;
1621
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001622 // Init priority must be standard.
1623 ConstantInt *CI = dyn_cast<ConstantInt>(CS->getOperand(0));
Reid Spencerb83eb642006-10-20 07:07:24 +00001624 if (!CI || CI->getZExtValue() != 65535)
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001625 return 0;
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001626 } else {
1627 return 0;
1628 }
1629
1630 return I;
1631 }
1632 return 0;
1633}
1634
Chris Lattnerdb973e62005-09-26 02:31:18 +00001635/// ParseGlobalCtors - Given a llvm.global_ctors list that we can understand,
1636/// return a list of the functions and null terminator as a vector.
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001637static std::vector<Function*> ParseGlobalCtors(GlobalVariable *GV) {
1638 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
1639 std::vector<Function*> Result;
1640 Result.reserve(CA->getNumOperands());
1641 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i) {
1642 ConstantStruct *CS = cast<ConstantStruct>(CA->getOperand(i));
1643 Result.push_back(dyn_cast<Function>(CS->getOperand(1)));
1644 }
1645 return Result;
1646}
1647
Chris Lattnerdb973e62005-09-26 02:31:18 +00001648/// InstallGlobalCtors - Given a specified llvm.global_ctors list, install the
1649/// specified array, returning the new global to use.
1650static GlobalVariable *InstallGlobalCtors(GlobalVariable *GCL,
1651 const std::vector<Function*> &Ctors) {
1652 // If we made a change, reassemble the initializer list.
1653 std::vector<Constant*> CSVals;
Reid Spencerc5b206b2006-12-31 05:48:39 +00001654 CSVals.push_back(ConstantInt::get(Type::Int32Ty, 65535));
Chris Lattnerdb973e62005-09-26 02:31:18 +00001655 CSVals.push_back(0);
1656
1657 // Create the new init list.
1658 std::vector<Constant*> CAList;
1659 for (unsigned i = 0, e = Ctors.size(); i != e; ++i) {
Chris Lattner79c11012005-09-26 04:44:35 +00001660 if (Ctors[i]) {
Chris Lattnerdb973e62005-09-26 02:31:18 +00001661 CSVals[1] = Ctors[i];
Chris Lattner79c11012005-09-26 04:44:35 +00001662 } else {
Chris Lattnerdb973e62005-09-26 02:31:18 +00001663 const Type *FTy = FunctionType::get(Type::VoidTy,
1664 std::vector<const Type*>(), false);
Christopher Lamb43ad6b32007-12-17 01:12:55 +00001665 const PointerType *PFTy = PointerType::getUnqual(FTy);
Chris Lattnerdb973e62005-09-26 02:31:18 +00001666 CSVals[1] = Constant::getNullValue(PFTy);
Reid Spencerc5b206b2006-12-31 05:48:39 +00001667 CSVals[0] = ConstantInt::get(Type::Int32Ty, 2147483647);
Chris Lattnerdb973e62005-09-26 02:31:18 +00001668 }
1669 CAList.push_back(ConstantStruct::get(CSVals));
1670 }
1671
1672 // Create the array initializer.
1673 const Type *StructTy =
1674 cast<ArrayType>(GCL->getType()->getElementType())->getElementType();
1675 Constant *CA = ConstantArray::get(ArrayType::get(StructTy, CAList.size()),
1676 CAList);
1677
1678 // If we didn't change the number of elements, don't create a new GV.
1679 if (CA->getType() == GCL->getInitializer()->getType()) {
1680 GCL->setInitializer(CA);
1681 return GCL;
1682 }
1683
1684 // Create the new global and insert it next to the existing list.
1685 GlobalVariable *NGV = new GlobalVariable(CA->getType(), GCL->isConstant(),
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +00001686 GCL->getLinkage(), CA, "",
1687 (Module *)NULL,
1688 GCL->isThreadLocal());
Chris Lattnerdb973e62005-09-26 02:31:18 +00001689 GCL->getParent()->getGlobalList().insert(GCL, NGV);
Chris Lattner046800a2007-02-11 01:08:35 +00001690 NGV->takeName(GCL);
Chris Lattnerdb973e62005-09-26 02:31:18 +00001691
1692 // Nuke the old list, replacing any uses with the new one.
1693 if (!GCL->use_empty()) {
1694 Constant *V = NGV;
1695 if (V->getType() != GCL->getType())
Reid Spencerd977d862006-12-12 23:36:14 +00001696 V = ConstantExpr::getBitCast(V, GCL->getType());
Chris Lattnerdb973e62005-09-26 02:31:18 +00001697 GCL->replaceAllUsesWith(V);
1698 }
1699 GCL->eraseFromParent();
1700
1701 if (Ctors.size())
1702 return NGV;
1703 else
1704 return 0;
1705}
Chris Lattner79c11012005-09-26 04:44:35 +00001706
1707
1708static Constant *getVal(std::map<Value*, Constant*> &ComputedValues,
1709 Value *V) {
1710 if (Constant *CV = dyn_cast<Constant>(V)) return CV;
1711 Constant *R = ComputedValues[V];
1712 assert(R && "Reference to an uncomputed value!");
1713 return R;
1714}
1715
1716/// isSimpleEnoughPointerToCommit - Return true if this constant is simple
1717/// enough for us to understand. In particular, if it is a cast of something,
1718/// we punt. We basically just support direct accesses to globals and GEP's of
1719/// globals. This should be kept up to date with CommitValueTo.
1720static bool isSimpleEnoughPointerToCommit(Constant *C) {
Chris Lattner231308c2005-09-27 04:50:03 +00001721 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
1722 if (!GV->hasExternalLinkage() && !GV->hasInternalLinkage())
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00001723 return false; // do not allow weak/linkonce/dllimport/dllexport linkage.
Reid Spencer5cbf9852007-01-30 20:08:39 +00001724 return !GV->isDeclaration(); // reject external globals.
Chris Lattner231308c2005-09-27 04:50:03 +00001725 }
Chris Lattner798b4d52005-09-26 06:52:44 +00001726 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
1727 // Handle a constantexpr gep.
1728 if (CE->getOpcode() == Instruction::GetElementPtr &&
1729 isa<GlobalVariable>(CE->getOperand(0))) {
1730 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
Chris Lattner231308c2005-09-27 04:50:03 +00001731 if (!GV->hasExternalLinkage() && !GV->hasInternalLinkage())
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00001732 return false; // do not allow weak/linkonce/dllimport/dllexport linkage.
Chris Lattner798b4d52005-09-26 06:52:44 +00001733 return GV->hasInitializer() &&
1734 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
1735 }
Chris Lattner79c11012005-09-26 04:44:35 +00001736 return false;
1737}
1738
Chris Lattner798b4d52005-09-26 06:52:44 +00001739/// EvaluateStoreInto - Evaluate a piece of a constantexpr store into a global
1740/// initializer. This returns 'Init' modified to reflect 'Val' stored into it.
1741/// At this point, the GEP operands of Addr [0, OpNo) have been stepped into.
1742static Constant *EvaluateStoreInto(Constant *Init, Constant *Val,
1743 ConstantExpr *Addr, unsigned OpNo) {
1744 // Base case of the recursion.
1745 if (OpNo == Addr->getNumOperands()) {
1746 assert(Val->getType() == Init->getType() && "Type mismatch!");
1747 return Val;
1748 }
1749
1750 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
1751 std::vector<Constant*> Elts;
1752
1753 // Break up the constant into its elements.
1754 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
1755 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i)
1756 Elts.push_back(CS->getOperand(i));
1757 } else if (isa<ConstantAggregateZero>(Init)) {
1758 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
1759 Elts.push_back(Constant::getNullValue(STy->getElementType(i)));
1760 } else if (isa<UndefValue>(Init)) {
1761 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
1762 Elts.push_back(UndefValue::get(STy->getElementType(i)));
1763 } else {
1764 assert(0 && "This code is out of sync with "
1765 " ConstantFoldLoadThroughGEPConstantExpr");
1766 }
1767
1768 // Replace the element that we are supposed to.
Reid Spencerb83eb642006-10-20 07:07:24 +00001769 ConstantInt *CU = cast<ConstantInt>(Addr->getOperand(OpNo));
1770 unsigned Idx = CU->getZExtValue();
1771 assert(Idx < STy->getNumElements() && "Struct index out of range!");
Chris Lattner798b4d52005-09-26 06:52:44 +00001772 Elts[Idx] = EvaluateStoreInto(Elts[Idx], Val, Addr, OpNo+1);
1773
1774 // Return the modified struct.
Chris Lattnerf0a9aab2007-06-04 22:23:42 +00001775 return ConstantStruct::get(&Elts[0], Elts.size(), STy->isPacked());
Chris Lattner798b4d52005-09-26 06:52:44 +00001776 } else {
1777 ConstantInt *CI = cast<ConstantInt>(Addr->getOperand(OpNo));
1778 const ArrayType *ATy = cast<ArrayType>(Init->getType());
1779
1780 // Break up the array into elements.
1781 std::vector<Constant*> Elts;
1782 if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
1783 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1784 Elts.push_back(CA->getOperand(i));
1785 } else if (isa<ConstantAggregateZero>(Init)) {
1786 Constant *Elt = Constant::getNullValue(ATy->getElementType());
1787 Elts.assign(ATy->getNumElements(), Elt);
1788 } else if (isa<UndefValue>(Init)) {
1789 Constant *Elt = UndefValue::get(ATy->getElementType());
1790 Elts.assign(ATy->getNumElements(), Elt);
1791 } else {
1792 assert(0 && "This code is out of sync with "
1793 " ConstantFoldLoadThroughGEPConstantExpr");
1794 }
1795
Reid Spencerb83eb642006-10-20 07:07:24 +00001796 assert(CI->getZExtValue() < ATy->getNumElements());
1797 Elts[CI->getZExtValue()] =
1798 EvaluateStoreInto(Elts[CI->getZExtValue()], Val, Addr, OpNo+1);
Chris Lattner798b4d52005-09-26 06:52:44 +00001799 return ConstantArray::get(ATy, Elts);
1800 }
1801}
1802
Chris Lattner79c11012005-09-26 04:44:35 +00001803/// CommitValueTo - We have decided that Addr (which satisfies the predicate
1804/// isSimpleEnoughPointerToCommit) should get Val as its value. Make it happen.
1805static void CommitValueTo(Constant *Val, Constant *Addr) {
Chris Lattner798b4d52005-09-26 06:52:44 +00001806 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Addr)) {
1807 assert(GV->hasInitializer());
1808 GV->setInitializer(Val);
1809 return;
1810 }
1811
1812 ConstantExpr *CE = cast<ConstantExpr>(Addr);
1813 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
1814
1815 Constant *Init = GV->getInitializer();
1816 Init = EvaluateStoreInto(Init, Val, CE, 2);
1817 GV->setInitializer(Init);
Chris Lattner79c11012005-09-26 04:44:35 +00001818}
1819
Chris Lattner562a0552005-09-26 05:16:34 +00001820/// ComputeLoadResult - Return the value that would be computed by a load from
1821/// P after the stores reflected by 'memory' have been performed. If we can't
1822/// decide, return null.
Chris Lattner04de1cf2005-09-26 05:15:37 +00001823static Constant *ComputeLoadResult(Constant *P,
1824 const std::map<Constant*, Constant*> &Memory) {
1825 // If this memory location has been recently stored, use the stored value: it
1826 // is the most up-to-date.
1827 std::map<Constant*, Constant*>::const_iterator I = Memory.find(P);
1828 if (I != Memory.end()) return I->second;
1829
1830 // Access it.
1831 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(P)) {
1832 if (GV->hasInitializer())
1833 return GV->getInitializer();
1834 return 0;
Chris Lattner04de1cf2005-09-26 05:15:37 +00001835 }
Chris Lattner798b4d52005-09-26 06:52:44 +00001836
1837 // Handle a constantexpr getelementptr.
1838 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(P))
1839 if (CE->getOpcode() == Instruction::GetElementPtr &&
1840 isa<GlobalVariable>(CE->getOperand(0))) {
1841 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
1842 if (GV->hasInitializer())
1843 return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
1844 }
1845
1846 return 0; // don't know how to evaluate.
Chris Lattner04de1cf2005-09-26 05:15:37 +00001847}
1848
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00001849/// EvaluateFunction - Evaluate a call to function F, returning true if
1850/// successful, false if we can't evaluate it. ActualArgs contains the formal
1851/// arguments for the function.
Chris Lattnercd271422005-09-27 04:45:34 +00001852static bool EvaluateFunction(Function *F, Constant *&RetVal,
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00001853 const std::vector<Constant*> &ActualArgs,
1854 std::vector<Function*> &CallStack,
1855 std::map<Constant*, Constant*> &MutatedMemory,
1856 std::vector<GlobalVariable*> &AllocaTmps) {
Chris Lattnercd271422005-09-27 04:45:34 +00001857 // Check to see if this function is already executing (recursion). If so,
1858 // bail out. TODO: we might want to accept limited recursion.
1859 if (std::find(CallStack.begin(), CallStack.end(), F) != CallStack.end())
1860 return false;
1861
1862 CallStack.push_back(F);
1863
Chris Lattner79c11012005-09-26 04:44:35 +00001864 /// Values - As we compute SSA register values, we store their contents here.
1865 std::map<Value*, Constant*> Values;
Chris Lattnercd271422005-09-27 04:45:34 +00001866
1867 // Initialize arguments to the incoming values specified.
1868 unsigned ArgNo = 0;
1869 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); AI != E;
1870 ++AI, ++ArgNo)
1871 Values[AI] = ActualArgs[ArgNo];
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00001872
Chris Lattnercdf98be2005-09-26 04:57:38 +00001873 /// ExecutedBlocks - We only handle non-looping, non-recursive code. As such,
1874 /// we can only evaluate any one basic block at most once. This set keeps
1875 /// track of what we have executed so we can detect recursive cases etc.
1876 std::set<BasicBlock*> ExecutedBlocks;
Chris Lattnera22fdb02005-09-26 17:07:09 +00001877
Chris Lattner79c11012005-09-26 04:44:35 +00001878 // CurInst - The current instruction we're evaluating.
1879 BasicBlock::iterator CurInst = F->begin()->begin();
1880
1881 // This is the main evaluation loop.
1882 while (1) {
1883 Constant *InstResult = 0;
1884
1885 if (StoreInst *SI = dyn_cast<StoreInst>(CurInst)) {
Chris Lattnercd271422005-09-27 04:45:34 +00001886 if (SI->isVolatile()) return false; // no volatile accesses.
Chris Lattner79c11012005-09-26 04:44:35 +00001887 Constant *Ptr = getVal(Values, SI->getOperand(1));
1888 if (!isSimpleEnoughPointerToCommit(Ptr))
1889 // If this is too complex for us to commit, reject it.
Chris Lattnercd271422005-09-27 04:45:34 +00001890 return false;
Chris Lattner79c11012005-09-26 04:44:35 +00001891 Constant *Val = getVal(Values, SI->getOperand(0));
1892 MutatedMemory[Ptr] = Val;
1893 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CurInst)) {
1894 InstResult = ConstantExpr::get(BO->getOpcode(),
1895 getVal(Values, BO->getOperand(0)),
1896 getVal(Values, BO->getOperand(1)));
Reid Spencere4d87aa2006-12-23 06:05:41 +00001897 } else if (CmpInst *CI = dyn_cast<CmpInst>(CurInst)) {
1898 InstResult = ConstantExpr::getCompare(CI->getPredicate(),
1899 getVal(Values, CI->getOperand(0)),
1900 getVal(Values, CI->getOperand(1)));
Chris Lattner79c11012005-09-26 04:44:35 +00001901 } else if (CastInst *CI = dyn_cast<CastInst>(CurInst)) {
Chris Lattner9a989f02006-11-30 17:26:08 +00001902 InstResult = ConstantExpr::getCast(CI->getOpcode(),
1903 getVal(Values, CI->getOperand(0)),
Chris Lattner79c11012005-09-26 04:44:35 +00001904 CI->getType());
1905 } else if (SelectInst *SI = dyn_cast<SelectInst>(CurInst)) {
1906 InstResult = ConstantExpr::getSelect(getVal(Values, SI->getOperand(0)),
1907 getVal(Values, SI->getOperand(1)),
1908 getVal(Values, SI->getOperand(2)));
Chris Lattner04de1cf2005-09-26 05:15:37 +00001909 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurInst)) {
1910 Constant *P = getVal(Values, GEP->getOperand(0));
Chris Lattner55eb1c42007-01-31 04:40:53 +00001911 SmallVector<Constant*, 8> GEPOps;
Chris Lattner04de1cf2005-09-26 05:15:37 +00001912 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
1913 GEPOps.push_back(getVal(Values, GEP->getOperand(i)));
Chris Lattner55eb1c42007-01-31 04:40:53 +00001914 InstResult = ConstantExpr::getGetElementPtr(P, &GEPOps[0], GEPOps.size());
Chris Lattner04de1cf2005-09-26 05:15:37 +00001915 } else if (LoadInst *LI = dyn_cast<LoadInst>(CurInst)) {
Chris Lattnercd271422005-09-27 04:45:34 +00001916 if (LI->isVolatile()) return false; // no volatile accesses.
Chris Lattner04de1cf2005-09-26 05:15:37 +00001917 InstResult = ComputeLoadResult(getVal(Values, LI->getOperand(0)),
1918 MutatedMemory);
Chris Lattnercd271422005-09-27 04:45:34 +00001919 if (InstResult == 0) return false; // Could not evaluate load.
Chris Lattnera22fdb02005-09-26 17:07:09 +00001920 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(CurInst)) {
Chris Lattnercd271422005-09-27 04:45:34 +00001921 if (AI->isArrayAllocation()) return false; // Cannot handle array allocs.
Chris Lattnera22fdb02005-09-26 17:07:09 +00001922 const Type *Ty = AI->getType()->getElementType();
1923 AllocaTmps.push_back(new GlobalVariable(Ty, false,
1924 GlobalValue::InternalLinkage,
1925 UndefValue::get(Ty),
1926 AI->getName()));
Chris Lattnercd271422005-09-27 04:45:34 +00001927 InstResult = AllocaTmps.back();
1928 } else if (CallInst *CI = dyn_cast<CallInst>(CurInst)) {
Chris Lattner7cd580f2006-07-07 21:37:01 +00001929 // Cannot handle inline asm.
1930 if (isa<InlineAsm>(CI->getOperand(0))) return false;
1931
Chris Lattnercd271422005-09-27 04:45:34 +00001932 // Resolve function pointers.
1933 Function *Callee = dyn_cast<Function>(getVal(Values, CI->getOperand(0)));
1934 if (!Callee) return false; // Cannot resolve.
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00001935
Chris Lattnercd271422005-09-27 04:45:34 +00001936 std::vector<Constant*> Formals;
1937 for (unsigned i = 1, e = CI->getNumOperands(); i != e; ++i)
1938 Formals.push_back(getVal(Values, CI->getOperand(i)));
Chris Lattnercd271422005-09-27 04:45:34 +00001939
Reid Spencer5cbf9852007-01-30 20:08:39 +00001940 if (Callee->isDeclaration()) {
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00001941 // If this is a function we can constant fold, do it.
Chris Lattner6c1f5652007-01-30 23:14:52 +00001942 if (Constant *C = ConstantFoldCall(Callee, &Formals[0],
1943 Formals.size())) {
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00001944 InstResult = C;
1945 } else {
1946 return false;
1947 }
1948 } else {
1949 if (Callee->getFunctionType()->isVarArg())
1950 return false;
1951
1952 Constant *RetVal;
1953
1954 // Execute the call, if successful, use the return value.
1955 if (!EvaluateFunction(Callee, RetVal, Formals, CallStack,
1956 MutatedMemory, AllocaTmps))
1957 return false;
1958 InstResult = RetVal;
1959 }
Reid Spencer3ed469c2006-11-02 20:25:50 +00001960 } else if (isa<TerminatorInst>(CurInst)) {
Chris Lattnercdf98be2005-09-26 04:57:38 +00001961 BasicBlock *NewBB = 0;
1962 if (BranchInst *BI = dyn_cast<BranchInst>(CurInst)) {
1963 if (BI->isUnconditional()) {
1964 NewBB = BI->getSuccessor(0);
1965 } else {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001966 ConstantInt *Cond =
1967 dyn_cast<ConstantInt>(getVal(Values, BI->getCondition()));
Chris Lattner97d1fad2007-01-12 18:30:11 +00001968 if (!Cond) return false; // Cannot determine.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001969
Reid Spencer579dca12007-01-12 04:24:46 +00001970 NewBB = BI->getSuccessor(!Cond->getZExtValue());
Chris Lattnercdf98be2005-09-26 04:57:38 +00001971 }
1972 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(CurInst)) {
1973 ConstantInt *Val =
1974 dyn_cast<ConstantInt>(getVal(Values, SI->getCondition()));
Chris Lattnercd271422005-09-27 04:45:34 +00001975 if (!Val) return false; // Cannot determine.
Chris Lattnercdf98be2005-09-26 04:57:38 +00001976 NewBB = SI->getSuccessor(SI->findCaseValue(Val));
1977 } else if (ReturnInst *RI = dyn_cast<ReturnInst>(CurInst)) {
Chris Lattnercd271422005-09-27 04:45:34 +00001978 if (RI->getNumOperands())
1979 RetVal = getVal(Values, RI->getOperand(0));
1980
1981 CallStack.pop_back(); // return from fn.
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00001982 return true; // We succeeded at evaluating this ctor!
Chris Lattnercdf98be2005-09-26 04:57:38 +00001983 } else {
Chris Lattnercd271422005-09-27 04:45:34 +00001984 // invoke, unwind, unreachable.
1985 return false; // Cannot handle this terminator.
Chris Lattnercdf98be2005-09-26 04:57:38 +00001986 }
1987
1988 // Okay, we succeeded in evaluating this control flow. See if we have
Chris Lattnercd271422005-09-27 04:45:34 +00001989 // executed the new block before. If so, we have a looping function,
1990 // which we cannot evaluate in reasonable time.
Chris Lattnercdf98be2005-09-26 04:57:38 +00001991 if (!ExecutedBlocks.insert(NewBB).second)
Chris Lattnercd271422005-09-27 04:45:34 +00001992 return false; // looped!
Chris Lattnercdf98be2005-09-26 04:57:38 +00001993
1994 // Okay, we have never been in this block before. Check to see if there
1995 // are any PHI nodes. If so, evaluate them with information about where
1996 // we came from.
1997 BasicBlock *OldBB = CurInst->getParent();
1998 CurInst = NewBB->begin();
1999 PHINode *PN;
2000 for (; (PN = dyn_cast<PHINode>(CurInst)); ++CurInst)
2001 Values[PN] = getVal(Values, PN->getIncomingValueForBlock(OldBB));
2002
2003 // Do NOT increment CurInst. We know that the terminator had no value.
2004 continue;
Chris Lattner79c11012005-09-26 04:44:35 +00002005 } else {
Chris Lattner79c11012005-09-26 04:44:35 +00002006 // Did not know how to evaluate this!
Chris Lattnercd271422005-09-27 04:45:34 +00002007 return false;
Chris Lattner79c11012005-09-26 04:44:35 +00002008 }
2009
2010 if (!CurInst->use_empty())
2011 Values[CurInst] = InstResult;
2012
2013 // Advance program counter.
2014 ++CurInst;
2015 }
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002016}
2017
2018/// EvaluateStaticConstructor - Evaluate static constructors in the function, if
2019/// we can. Return true if we can, false otherwise.
2020static bool EvaluateStaticConstructor(Function *F) {
2021 /// MutatedMemory - For each store we execute, we update this map. Loads
2022 /// check this to get the most up-to-date value. If evaluation is successful,
2023 /// this state is committed to the process.
2024 std::map<Constant*, Constant*> MutatedMemory;
2025
2026 /// AllocaTmps - To 'execute' an alloca, we create a temporary global variable
2027 /// to represent its body. This vector is needed so we can delete the
2028 /// temporary globals when we are done.
2029 std::vector<GlobalVariable*> AllocaTmps;
2030
2031 /// CallStack - This is used to detect recursion. In pathological situations
2032 /// we could hit exponential behavior, but at least there is nothing
2033 /// unbounded.
2034 std::vector<Function*> CallStack;
2035
2036 // Call the function.
Chris Lattnercd271422005-09-27 04:45:34 +00002037 Constant *RetValDummy;
2038 bool EvalSuccess = EvaluateFunction(F, RetValDummy, std::vector<Constant*>(),
2039 CallStack, MutatedMemory, AllocaTmps);
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002040 if (EvalSuccess) {
Chris Lattnera22fdb02005-09-26 17:07:09 +00002041 // We succeeded at evaluation: commit the result.
Bill Wendling0a81aac2006-11-26 10:02:32 +00002042 DOUT << "FULLY EVALUATED GLOBAL CTOR FUNCTION '"
2043 << F->getName() << "' to " << MutatedMemory.size()
2044 << " stores.\n";
Chris Lattnera22fdb02005-09-26 17:07:09 +00002045 for (std::map<Constant*, Constant*>::iterator I = MutatedMemory.begin(),
2046 E = MutatedMemory.end(); I != E; ++I)
2047 CommitValueTo(I->second, I->first);
2048 }
Chris Lattner79c11012005-09-26 04:44:35 +00002049
Chris Lattnera22fdb02005-09-26 17:07:09 +00002050 // At this point, we are done interpreting. If we created any 'alloca'
2051 // temporaries, release them now.
2052 while (!AllocaTmps.empty()) {
2053 GlobalVariable *Tmp = AllocaTmps.back();
2054 AllocaTmps.pop_back();
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002055
Chris Lattnera22fdb02005-09-26 17:07:09 +00002056 // If there are still users of the alloca, the program is doing something
2057 // silly, e.g. storing the address of the alloca somewhere and using it
2058 // later. Since this is undefined, we'll just make it be null.
2059 if (!Tmp->use_empty())
2060 Tmp->replaceAllUsesWith(Constant::getNullValue(Tmp->getType()));
2061 delete Tmp;
2062 }
Chris Lattneraae4a1c2005-09-26 07:34:35 +00002063
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002064 return EvalSuccess;
Chris Lattner79c11012005-09-26 04:44:35 +00002065}
2066
Chris Lattnerdb973e62005-09-26 02:31:18 +00002067
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002068
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002069/// OptimizeGlobalCtorsList - Simplify and evaluation global ctors if possible.
2070/// Return true if anything changed.
2071bool GlobalOpt::OptimizeGlobalCtorsList(GlobalVariable *&GCL) {
2072 std::vector<Function*> Ctors = ParseGlobalCtors(GCL);
2073 bool MadeChange = false;
2074 if (Ctors.empty()) return false;
2075
2076 // Loop over global ctors, optimizing them when we can.
2077 for (unsigned i = 0; i != Ctors.size(); ++i) {
2078 Function *F = Ctors[i];
2079 // Found a null terminator in the middle of the list, prune off the rest of
2080 // the list.
Chris Lattner7d8e58f2005-09-26 02:19:27 +00002081 if (F == 0) {
2082 if (i != Ctors.size()-1) {
2083 Ctors.resize(i+1);
2084 MadeChange = true;
2085 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002086 break;
2087 }
2088
Chris Lattner79c11012005-09-26 04:44:35 +00002089 // We cannot simplify external ctor functions.
2090 if (F->empty()) continue;
2091
2092 // If we can evaluate the ctor at compile time, do.
2093 if (EvaluateStaticConstructor(F)) {
2094 Ctors.erase(Ctors.begin()+i);
2095 MadeChange = true;
2096 --i;
2097 ++NumCtorsEvaluated;
2098 continue;
2099 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002100 }
2101
2102 if (!MadeChange) return false;
2103
Chris Lattnerdb973e62005-09-26 02:31:18 +00002104 GCL = InstallGlobalCtors(GCL, Ctors);
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002105 return true;
2106}
2107
2108
Chris Lattner7a90b682004-10-07 04:16:33 +00002109bool GlobalOpt::runOnModule(Module &M) {
Chris Lattner079236d2004-02-25 21:34:36 +00002110 bool Changed = false;
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002111
2112 // Try to find the llvm.globalctors list.
2113 GlobalVariable *GlobalCtors = FindGlobalCtors(M);
Chris Lattner7a90b682004-10-07 04:16:33 +00002114
Chris Lattner7a90b682004-10-07 04:16:33 +00002115 bool LocalChange = true;
2116 while (LocalChange) {
2117 LocalChange = false;
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002118
2119 // Delete functions that are trivially dead, ccc -> fastcc
2120 LocalChange |= OptimizeFunctions(M);
2121
2122 // Optimize global_ctors list.
2123 if (GlobalCtors)
2124 LocalChange |= OptimizeGlobalCtorsList(GlobalCtors);
2125
2126 // Optimize non-address-taken globals.
2127 LocalChange |= OptimizeGlobalVars(M);
Chris Lattner7a90b682004-10-07 04:16:33 +00002128 Changed |= LocalChange;
2129 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002130
2131 // TODO: Move all global ctors functions to the end of the module for code
2132 // layout.
2133
Chris Lattner079236d2004-02-25 21:34:36 +00002134 return Changed;
2135}