blob: 9284500a8651c7075a9b93fa52d58928b1c7e972 [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"
Duncan Sands548448a2008-02-18 17:32:13 +000027#include "llvm/Support/CallSite.h"
Reid Spencer9133fe22007-02-05 23:32:05 +000028#include "llvm/Support/Compiler.h"
Chris Lattner79066fa2007-01-30 23:46:24 +000029#include "llvm/Support/Debug.h"
Chris Lattner941db492008-01-14 02:09:12 +000030#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner998182b2008-04-26 07:40:11 +000031#include "llvm/Support/MathExtras.h"
Chris Lattner5a6bb6a2008-12-16 07:34:30 +000032#include "llvm/ADT/DenseMap.h"
Chris Lattner81686182007-09-13 16:30:19 +000033#include "llvm/ADT/SmallPtrSet.h"
Chris Lattner55eb1c42007-01-31 04:40:53 +000034#include "llvm/ADT/SmallVector.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000035#include "llvm/ADT/Statistic.h"
Chris Lattner670c8892004-10-08 17:32:09 +000036#include "llvm/ADT/StringExtras.h"
Chris Lattnerbce4afe2008-12-17 05:28:49 +000037#include "llvm/ADT/STLExtras.h"
Chris Lattnere47ba742004-10-06 20:57:02 +000038#include <algorithm>
Chris Lattner079236d2004-02-25 21:34:36 +000039using namespace llvm;
40
Chris Lattner86453c52006-12-19 22:09:18 +000041STATISTIC(NumMarked , "Number of globals marked constant");
42STATISTIC(NumSRA , "Number of aggregate globals broken into scalars");
43STATISTIC(NumHeapSRA , "Number of heap objects SRA'd");
44STATISTIC(NumSubstitute,"Number of globals with initializers stored into them");
45STATISTIC(NumDeleted , "Number of globals deleted");
46STATISTIC(NumFnDeleted , "Number of functions deleted");
47STATISTIC(NumGlobUses , "Number of global uses devirtualized");
48STATISTIC(NumLocalized , "Number of globals localized");
49STATISTIC(NumShrunkToBool , "Number of global vars shrunk to booleans");
50STATISTIC(NumFastCallFns , "Number of functions converted to fastcc");
51STATISTIC(NumCtorsEvaluated, "Number of static ctors evaluated");
Duncan Sands3d5378f2008-02-16 20:56:04 +000052STATISTIC(NumNestRemoved , "Number of nest attributes removed");
Duncan Sands4782b302009-02-15 09:56:08 +000053STATISTIC(NumAliasesResolved, "Number of global aliases resolved");
54STATISTIC(NumAliasesRemoved, "Number of global aliases eliminated");
Chris Lattner079236d2004-02-25 21:34:36 +000055
Chris Lattner86453c52006-12-19 22:09:18 +000056namespace {
Reid Spencer9133fe22007-02-05 23:32:05 +000057 struct VISIBILITY_HIDDEN GlobalOpt : public ModulePass {
Chris Lattner30ba5692004-10-11 05:54:41 +000058 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
59 AU.addRequired<TargetData>();
60 }
Nick Lewyckyecd94c82007-05-06 13:37:16 +000061 static char ID; // Pass identification, replacement for typeid
Dan Gohmanae73dc12008-09-04 17:05:41 +000062 GlobalOpt() : ModulePass(&ID) {}
Misha Brukmanfd939082005-04-21 23:48:37 +000063
Chris Lattnerb12914b2004-09-20 04:48:05 +000064 bool runOnModule(Module &M);
Chris Lattner30ba5692004-10-11 05:54:41 +000065
66 private:
Chris Lattnerb1ab4582005-09-26 01:43:45 +000067 GlobalVariable *FindGlobalCtors(Module &M);
68 bool OptimizeFunctions(Module &M);
69 bool OptimizeGlobalVars(Module &M);
Anton Korobeynikove4c6b612008-09-09 19:04:59 +000070 bool ResolveAliases(Module &M);
Chris Lattnerb1ab4582005-09-26 01:43:45 +000071 bool OptimizeGlobalCtorsList(GlobalVariable *&GCL);
Chris Lattner7f8897f2006-08-27 22:42:52 +000072 bool ProcessInternalGlobal(GlobalVariable *GV,Module::global_iterator &GVI);
Chris Lattner079236d2004-02-25 21:34:36 +000073 };
Chris Lattner079236d2004-02-25 21:34:36 +000074}
75
Dan Gohman844731a2008-05-13 00:00:25 +000076char GlobalOpt::ID = 0;
77static RegisterPass<GlobalOpt> X("globalopt", "Global Variable Optimizer");
78
Chris Lattner7a90b682004-10-07 04:16:33 +000079ModulePass *llvm::createGlobalOptimizerPass() { return new GlobalOpt(); }
Chris Lattner079236d2004-02-25 21:34:36 +000080
Dan Gohman844731a2008-05-13 00:00:25 +000081namespace {
82
Chris Lattner7a90b682004-10-07 04:16:33 +000083/// GlobalStatus - As we analyze each global, keep track of some information
84/// about it. If we find out that the address of the global is taken, none of
Chris Lattnercf4d2a52004-10-07 21:30:30 +000085/// this info will be accurate.
Reid Spencer9133fe22007-02-05 23:32:05 +000086struct VISIBILITY_HIDDEN GlobalStatus {
Chris Lattnercf4d2a52004-10-07 21:30:30 +000087 /// isLoaded - True if the global is ever loaded. If the global isn't ever
88 /// loaded it can be deleted.
Chris Lattner7a90b682004-10-07 04:16:33 +000089 bool isLoaded;
Chris Lattnercf4d2a52004-10-07 21:30:30 +000090
91 /// StoredType - Keep track of what stores to the global look like.
92 ///
Chris Lattner7a90b682004-10-07 04:16:33 +000093 enum StoredType {
Chris Lattnercf4d2a52004-10-07 21:30:30 +000094 /// NotStored - There is no store to this global. It can thus be marked
95 /// constant.
96 NotStored,
97
98 /// isInitializerStored - This global is stored to, but the only thing
99 /// stored is the constant it was initialized with. This is only tracked
100 /// for scalar globals.
101 isInitializerStored,
102
103 /// isStoredOnce - This global is stored to, but only its initializer and
104 /// one other value is ever stored to it. If this global isStoredOnce, we
105 /// track the value stored to it in StoredOnceValue below. This is only
106 /// tracked for scalar globals.
107 isStoredOnce,
108
109 /// isStored - This global is stored to by multiple values or something else
110 /// that we cannot track.
111 isStored
Chris Lattner7a90b682004-10-07 04:16:33 +0000112 } StoredType;
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000113
114 /// StoredOnceValue - If only one value (besides the initializer constant) is
115 /// ever stored to this global, keep track of what value it is.
116 Value *StoredOnceValue;
117
Chris Lattner25de4e52006-11-01 18:03:33 +0000118 /// AccessingFunction/HasMultipleAccessingFunctions - These start out
119 /// null/false. When the first accessing function is noticed, it is recorded.
120 /// When a second different accessing function is noticed,
121 /// HasMultipleAccessingFunctions is set to true.
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +0000122 Function *AccessingFunction;
123 bool HasMultipleAccessingFunctions;
124
Chris Lattner25de4e52006-11-01 18:03:33 +0000125 /// HasNonInstructionUser - Set to true if this global has a user that is not
126 /// an instruction (e.g. a constant expr or GV initializer).
Chris Lattner553ca522005-06-15 21:11:48 +0000127 bool HasNonInstructionUser;
128
Chris Lattner25de4e52006-11-01 18:03:33 +0000129 /// HasPHIUser - Set to true if this global has a user that is a PHI node.
130 bool HasPHIUser;
131
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000132 GlobalStatus() : isLoaded(false), StoredType(NotStored), StoredOnceValue(0),
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +0000133 AccessingFunction(0), HasMultipleAccessingFunctions(false),
Chris Lattner6a93fc02008-01-14 01:32:52 +0000134 HasNonInstructionUser(false), HasPHIUser(false) {}
Chris Lattner7a90b682004-10-07 04:16:33 +0000135};
Chris Lattnere47ba742004-10-06 20:57:02 +0000136
Dan Gohman844731a2008-05-13 00:00:25 +0000137}
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000138
139/// ConstantIsDead - Return true if the specified constant is (transitively)
Devang Patel50496002009-03-05 18:12:02 +0000140/// dead. The constant may be used by other constants (e.g. constant arrays,
141/// constant exprs, constant global variables) as long as they are dead,
142/// but it cannot be used by anything else. If DeadGVs is not null then
143/// record dead constant GV users.
144static bool ConstantIsDead(Constant *C,
145 SmallPtrSet<GlobalVariable *, 4> *DeadGVs = false) {
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000146 if (isa<GlobalValue>(C)) return false;
147
Devang Patel50496002009-03-05 18:12:02 +0000148 for (Value::use_iterator UI = C->use_begin(), E = C->use_end(); UI != E; ++UI) {
149 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(*UI)) {
150 if (!GV->isConstant() || !GV->hasLocalLinkage() || !GV->use_empty())
151 return false;
152 else {
153 if (DeadGVs)
154 DeadGVs->insert(GV);
155 }
156 }
157 else if (Constant *CU = dyn_cast<Constant>(*UI)) {
158 if (!ConstantIsDead(CU, DeadGVs)) return false;
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000159 } else
160 return false;
Devang Patel50496002009-03-05 18:12:02 +0000161 }
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000162 return true;
163}
164
165
Chris Lattner7a90b682004-10-07 04:16:33 +0000166/// AnalyzeGlobal - Look at all uses of the global and fill in the GlobalStatus
167/// structure. If the global has its address taken, return true to indicate we
168/// can't do anything with it.
Chris Lattner079236d2004-02-25 21:34:36 +0000169///
Chris Lattner7a90b682004-10-07 04:16:33 +0000170static bool AnalyzeGlobal(Value *V, GlobalStatus &GS,
Chris Lattner5a6bb6a2008-12-16 07:34:30 +0000171 SmallPtrSet<PHINode*, 16> &PHIUsers) {
Chris Lattner079236d2004-02-25 21:34:36 +0000172 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
Chris Lattner96940cb2004-07-18 19:56:20 +0000173 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(*UI)) {
Chris Lattner553ca522005-06-15 21:11:48 +0000174 GS.HasNonInstructionUser = true;
175
Chris Lattner7a90b682004-10-07 04:16:33 +0000176 if (AnalyzeGlobal(CE, GS, PHIUsers)) return true;
Chris Lattner670c8892004-10-08 17:32:09 +0000177
Chris Lattner079236d2004-02-25 21:34:36 +0000178 } else if (Instruction *I = dyn_cast<Instruction>(*UI)) {
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +0000179 if (!GS.HasMultipleAccessingFunctions) {
180 Function *F = I->getParent()->getParent();
181 if (GS.AccessingFunction == 0)
182 GS.AccessingFunction = F;
183 else if (GS.AccessingFunction != F)
184 GS.HasMultipleAccessingFunctions = true;
185 }
Chris Lattnerc69d3c92008-01-29 19:01:37 +0000186 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattner7a90b682004-10-07 04:16:33 +0000187 GS.isLoaded = true;
Chris Lattnerc69d3c92008-01-29 19:01:37 +0000188 if (LI->isVolatile()) return true; // Don't hack on volatile loads.
Chris Lattner7a90b682004-10-07 04:16:33 +0000189 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Chris Lattner36025492004-10-07 06:01:25 +0000190 // Don't allow a store OF the address, only stores TO the address.
191 if (SI->getOperand(0) == V) return true;
192
Chris Lattnerc69d3c92008-01-29 19:01:37 +0000193 if (SI->isVolatile()) return true; // Don't hack on volatile stores.
194
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000195 // If this is a direct store to the global (i.e., the global is a scalar
196 // value, not an aggregate), keep more specific information about
197 // stores.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000198 if (GS.StoredType != GlobalStatus::isStored) {
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000199 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(SI->getOperand(1))){
Chris Lattnerbd38edf2004-11-14 20:50:30 +0000200 Value *StoredVal = SI->getOperand(0);
201 if (StoredVal == GV->getInitializer()) {
202 if (GS.StoredType < GlobalStatus::isInitializerStored)
203 GS.StoredType = GlobalStatus::isInitializerStored;
204 } else if (isa<LoadInst>(StoredVal) &&
205 cast<LoadInst>(StoredVal)->getOperand(0) == GV) {
206 // G = G
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000207 if (GS.StoredType < GlobalStatus::isInitializerStored)
208 GS.StoredType = GlobalStatus::isInitializerStored;
209 } else if (GS.StoredType < GlobalStatus::isStoredOnce) {
210 GS.StoredType = GlobalStatus::isStoredOnce;
Chris Lattnerbd38edf2004-11-14 20:50:30 +0000211 GS.StoredOnceValue = StoredVal;
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000212 } else if (GS.StoredType == GlobalStatus::isStoredOnce &&
Chris Lattnerbd38edf2004-11-14 20:50:30 +0000213 GS.StoredOnceValue == StoredVal) {
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000214 // noop.
215 } else {
216 GS.StoredType = GlobalStatus::isStored;
217 }
218 } else {
Chris Lattner7a90b682004-10-07 04:16:33 +0000219 GS.StoredType = GlobalStatus::isStored;
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000220 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000221 }
Chris Lattner35c81b02005-02-27 18:58:52 +0000222 } else if (isa<GetElementPtrInst>(I)) {
Chris Lattner7a90b682004-10-07 04:16:33 +0000223 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Chris Lattner35c81b02005-02-27 18:58:52 +0000224 } else if (isa<SelectInst>(I)) {
Chris Lattner7a90b682004-10-07 04:16:33 +0000225 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Chris Lattner7a90b682004-10-07 04:16:33 +0000226 } else if (PHINode *PN = dyn_cast<PHINode>(I)) {
227 // PHI nodes we can check just like select or GEP instructions, but we
228 // have to be careful about infinite recursion.
Chris Lattner5a6bb6a2008-12-16 07:34:30 +0000229 if (PHIUsers.insert(PN)) // Not already visited.
Chris Lattner7a90b682004-10-07 04:16:33 +0000230 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Chris Lattner25de4e52006-11-01 18:03:33 +0000231 GS.HasPHIUser = true;
Reid Spencere4d87aa2006-12-23 06:05:41 +0000232 } else if (isa<CmpInst>(I)) {
Chris Lattner35c81b02005-02-27 18:58:52 +0000233 } else if (isa<MemCpyInst>(I) || isa<MemMoveInst>(I)) {
234 if (I->getOperand(1) == V)
235 GS.StoredType = GlobalStatus::isStored;
236 if (I->getOperand(2) == V)
237 GS.isLoaded = true;
Chris Lattner35c81b02005-02-27 18:58:52 +0000238 } else if (isa<MemSetInst>(I)) {
239 assert(I->getOperand(1) == V && "Memset only takes one pointer!");
240 GS.StoredType = GlobalStatus::isStored;
Chris Lattner7a90b682004-10-07 04:16:33 +0000241 } else {
242 return true; // Any other non-load instruction might take address!
Chris Lattner9ce30002004-07-20 03:58:07 +0000243 }
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000244 } else if (Constant *C = dyn_cast<Constant>(*UI)) {
Chris Lattner553ca522005-06-15 21:11:48 +0000245 GS.HasNonInstructionUser = true;
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000246 // We might have a dead and dangling constant hanging off of here.
247 if (!ConstantIsDead(C))
248 return true;
Chris Lattner079236d2004-02-25 21:34:36 +0000249 } else {
Chris Lattner553ca522005-06-15 21:11:48 +0000250 GS.HasNonInstructionUser = true;
251 // Otherwise must be some other user.
Chris Lattner079236d2004-02-25 21:34:36 +0000252 return true;
253 }
254
255 return false;
256}
257
Chris Lattner670c8892004-10-08 17:32:09 +0000258static Constant *getAggregateConstantElement(Constant *Agg, Constant *Idx) {
259 ConstantInt *CI = dyn_cast<ConstantInt>(Idx);
260 if (!CI) return 0;
Reid Spencerb83eb642006-10-20 07:07:24 +0000261 unsigned IdxV = CI->getZExtValue();
Chris Lattner7a90b682004-10-07 04:16:33 +0000262
Chris Lattner670c8892004-10-08 17:32:09 +0000263 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Agg)) {
264 if (IdxV < CS->getNumOperands()) return CS->getOperand(IdxV);
265 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Agg)) {
266 if (IdxV < CA->getNumOperands()) return CA->getOperand(IdxV);
Reid Spencer9d6565a2007-02-15 02:26:10 +0000267 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Agg)) {
Chris Lattner670c8892004-10-08 17:32:09 +0000268 if (IdxV < CP->getNumOperands()) return CP->getOperand(IdxV);
Chris Lattner7a7ed022004-10-16 18:09:00 +0000269 } else if (isa<ConstantAggregateZero>(Agg)) {
Chris Lattner670c8892004-10-08 17:32:09 +0000270 if (const StructType *STy = dyn_cast<StructType>(Agg->getType())) {
271 if (IdxV < STy->getNumElements())
272 return Constant::getNullValue(STy->getElementType(IdxV));
273 } else if (const SequentialType *STy =
274 dyn_cast<SequentialType>(Agg->getType())) {
275 return Constant::getNullValue(STy->getElementType());
276 }
Chris Lattner7a7ed022004-10-16 18:09:00 +0000277 } else if (isa<UndefValue>(Agg)) {
278 if (const StructType *STy = dyn_cast<StructType>(Agg->getType())) {
279 if (IdxV < STy->getNumElements())
280 return UndefValue::get(STy->getElementType(IdxV));
281 } else if (const SequentialType *STy =
282 dyn_cast<SequentialType>(Agg->getType())) {
283 return UndefValue::get(STy->getElementType());
284 }
Chris Lattner670c8892004-10-08 17:32:09 +0000285 }
286 return 0;
287}
Chris Lattner7a90b682004-10-07 04:16:33 +0000288
Chris Lattner7a90b682004-10-07 04:16:33 +0000289
Chris Lattnere47ba742004-10-06 20:57:02 +0000290/// CleanupConstantGlobalUsers - We just marked GV constant. Loop over all
291/// users of the global, cleaning up the obvious ones. This is largely just a
Chris Lattner031955d2004-10-10 16:43:46 +0000292/// quick scan over the use list to clean up the easy and obvious cruft. This
293/// returns true if it made a change.
294static bool CleanupConstantGlobalUsers(Value *V, Constant *Init) {
295 bool Changed = false;
Chris Lattner7a90b682004-10-07 04:16:33 +0000296 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;) {
297 User *U = *UI++;
Misha Brukmanfd939082005-04-21 23:48:37 +0000298
Chris Lattner7a90b682004-10-07 04:16:33 +0000299 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
Chris Lattner35c81b02005-02-27 18:58:52 +0000300 if (Init) {
301 // Replace the load with the initializer.
302 LI->replaceAllUsesWith(Init);
303 LI->eraseFromParent();
304 Changed = true;
305 }
Chris Lattner7a90b682004-10-07 04:16:33 +0000306 } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
Chris Lattnere47ba742004-10-06 20:57:02 +0000307 // Store must be unreachable or storing Init into the global.
Chris Lattner7a7ed022004-10-16 18:09:00 +0000308 SI->eraseFromParent();
Chris Lattner031955d2004-10-10 16:43:46 +0000309 Changed = true;
Chris Lattner7a90b682004-10-07 04:16:33 +0000310 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
311 if (CE->getOpcode() == Instruction::GetElementPtr) {
Chris Lattneraae4a1c2005-09-26 07:34:35 +0000312 Constant *SubInit = 0;
313 if (Init)
314 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
Chris Lattner35c81b02005-02-27 18:58:52 +0000315 Changed |= CleanupConstantGlobalUsers(CE, SubInit);
Reid Spencer3da59db2006-11-27 01:05:10 +0000316 } else if (CE->getOpcode() == Instruction::BitCast &&
Chris Lattner35c81b02005-02-27 18:58:52 +0000317 isa<PointerType>(CE->getType())) {
318 // Pointer cast, delete any stores and memsets to the global.
319 Changed |= CleanupConstantGlobalUsers(CE, 0);
320 }
321
322 if (CE->use_empty()) {
323 CE->destroyConstant();
324 Changed = true;
Chris Lattner7a90b682004-10-07 04:16:33 +0000325 }
326 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
Chris Lattner7b52fe72007-11-09 17:33:02 +0000327 // Do not transform "gepinst (gep constexpr (GV))" here, because forming
328 // "gepconstexpr (gep constexpr (GV))" will cause the two gep's to fold
329 // and will invalidate our notion of what Init is.
Chris Lattner19450242007-11-13 21:46:23 +0000330 Constant *SubInit = 0;
Chris Lattner7b52fe72007-11-09 17:33:02 +0000331 if (!isa<ConstantExpr>(GEP->getOperand(0))) {
332 ConstantExpr *CE =
333 dyn_cast_or_null<ConstantExpr>(ConstantFoldInstruction(GEP));
334 if (Init && CE && CE->getOpcode() == Instruction::GetElementPtr)
Chris Lattner19450242007-11-13 21:46:23 +0000335 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
Chris Lattner7b52fe72007-11-09 17:33:02 +0000336 }
Chris Lattner19450242007-11-13 21:46:23 +0000337 Changed |= CleanupConstantGlobalUsers(GEP, SubInit);
Chris Lattnerc4d81b02004-10-10 16:47:33 +0000338
Chris Lattner031955d2004-10-10 16:43:46 +0000339 if (GEP->use_empty()) {
Chris Lattner7a7ed022004-10-16 18:09:00 +0000340 GEP->eraseFromParent();
Chris Lattner031955d2004-10-10 16:43:46 +0000341 Changed = true;
342 }
Chris Lattner35c81b02005-02-27 18:58:52 +0000343 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U)) { // memset/cpy/mv
344 if (MI->getRawDest() == V) {
345 MI->eraseFromParent();
346 Changed = true;
347 }
348
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000349 } else if (Constant *C = dyn_cast<Constant>(U)) {
350 // If we have a chain of dead constantexprs or other things dangling from
351 // us, and if they are all dead, nuke them without remorse.
Devang Patel50496002009-03-05 18:12:02 +0000352 SmallPtrSet<GlobalVariable *, 4> DeadGVs;
353 if (ConstantIsDead(C, &DeadGVs)) {
354 for (SmallPtrSet<GlobalVariable *, 4>::iterator TI = DeadGVs.begin(),
355 TE = DeadGVs.end(); TI != TE; ) {
356 GlobalVariable *TGV = *TI; ++TI;
357 if (TGV == C)
358 C = NULL;
359 TGV->eraseFromParent();
360 }
361 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
362 GV->eraseFromParent();
363 else if (C)
364 C->destroyConstant();
Chris Lattner35c81b02005-02-27 18:58:52 +0000365 // This could have invalidated UI, start over from scratch.
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000366 CleanupConstantGlobalUsers(V, Init);
Chris Lattner031955d2004-10-10 16:43:46 +0000367 return true;
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000368 }
Chris Lattnere47ba742004-10-06 20:57:02 +0000369 }
370 }
Chris Lattner031955d2004-10-10 16:43:46 +0000371 return Changed;
Chris Lattnere47ba742004-10-06 20:57:02 +0000372}
373
Chris Lattner941db492008-01-14 02:09:12 +0000374/// isSafeSROAElementUse - Return true if the specified instruction is a safe
375/// user of a derived expression from a global that we want to SROA.
376static bool isSafeSROAElementUse(Value *V) {
377 // We might have a dead and dangling constant hanging off of here.
378 if (Constant *C = dyn_cast<Constant>(V))
379 return ConstantIsDead(C);
Chris Lattner727c2102008-01-14 01:31:05 +0000380
Chris Lattner941db492008-01-14 02:09:12 +0000381 Instruction *I = dyn_cast<Instruction>(V);
382 if (!I) return false;
383
384 // Loads are ok.
385 if (isa<LoadInst>(I)) return true;
386
387 // Stores *to* the pointer are ok.
388 if (StoreInst *SI = dyn_cast<StoreInst>(I))
389 return SI->getOperand(0) != V;
390
391 // Otherwise, it must be a GEP.
392 GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I);
393 if (GEPI == 0) return false;
394
395 if (GEPI->getNumOperands() < 3 || !isa<Constant>(GEPI->getOperand(1)) ||
396 !cast<Constant>(GEPI->getOperand(1))->isNullValue())
397 return false;
398
399 for (Value::use_iterator I = GEPI->use_begin(), E = GEPI->use_end();
400 I != E; ++I)
401 if (!isSafeSROAElementUse(*I))
402 return false;
Chris Lattner727c2102008-01-14 01:31:05 +0000403 return true;
404}
405
Chris Lattner941db492008-01-14 02:09:12 +0000406
407/// IsUserOfGlobalSafeForSRA - U is a direct user of the specified global value.
408/// Look at it and its uses and decide whether it is safe to SROA this global.
409///
410static bool IsUserOfGlobalSafeForSRA(User *U, GlobalValue *GV) {
411 // The user of the global must be a GEP Inst or a ConstantExpr GEP.
412 if (!isa<GetElementPtrInst>(U) &&
413 (!isa<ConstantExpr>(U) ||
414 cast<ConstantExpr>(U)->getOpcode() != Instruction::GetElementPtr))
415 return false;
416
417 // Check to see if this ConstantExpr GEP is SRA'able. In particular, we
418 // don't like < 3 operand CE's, and we don't like non-constant integer
419 // indices. This enforces that all uses are 'gep GV, 0, C, ...' for some
420 // value of C.
421 if (U->getNumOperands() < 3 || !isa<Constant>(U->getOperand(1)) ||
422 !cast<Constant>(U->getOperand(1))->isNullValue() ||
423 !isa<ConstantInt>(U->getOperand(2)))
424 return false;
425
426 gep_type_iterator GEPI = gep_type_begin(U), E = gep_type_end(U);
427 ++GEPI; // Skip over the pointer index.
428
429 // If this is a use of an array allocation, do a bit more checking for sanity.
430 if (const ArrayType *AT = dyn_cast<ArrayType>(*GEPI)) {
431 uint64_t NumElements = AT->getNumElements();
432 ConstantInt *Idx = cast<ConstantInt>(U->getOperand(2));
433
434 // Check to make sure that index falls within the array. If not,
435 // something funny is going on, so we won't do the optimization.
436 //
437 if (Idx->getZExtValue() >= NumElements)
438 return false;
439
440 // We cannot scalar repl this level of the array unless any array
441 // sub-indices are in-range constants. In particular, consider:
442 // A[0][i]. We cannot know that the user isn't doing invalid things like
443 // allowing i to index an out-of-range subscript that accesses A[1].
444 //
445 // Scalar replacing *just* the outer index of the array is probably not
446 // going to be a win anyway, so just give up.
447 for (++GEPI; // Skip array index.
448 GEPI != E && (isa<ArrayType>(*GEPI) || isa<VectorType>(*GEPI));
449 ++GEPI) {
450 uint64_t NumElements;
451 if (const ArrayType *SubArrayTy = dyn_cast<ArrayType>(*GEPI))
452 NumElements = SubArrayTy->getNumElements();
453 else
454 NumElements = cast<VectorType>(*GEPI)->getNumElements();
455
456 ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPI.getOperand());
457 if (!IdxVal || IdxVal->getZExtValue() >= NumElements)
458 return false;
459 }
460 }
461
462 for (Value::use_iterator I = U->use_begin(), E = U->use_end(); I != E; ++I)
463 if (!isSafeSROAElementUse(*I))
464 return false;
465 return true;
466}
467
468/// GlobalUsersSafeToSRA - Look at all uses of the global and decide whether it
469/// is safe for us to perform this transformation.
470///
471static bool GlobalUsersSafeToSRA(GlobalValue *GV) {
472 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end();
473 UI != E; ++UI) {
474 if (!IsUserOfGlobalSafeForSRA(*UI, GV))
475 return false;
476 }
477 return true;
478}
479
480
Chris Lattner670c8892004-10-08 17:32:09 +0000481/// SRAGlobal - Perform scalar replacement of aggregates on the specified global
482/// variable. This opens the door for other optimizations by exposing the
483/// behavior of the program in a more fine-grained way. We have determined that
484/// this transformation is safe already. We return the first global variable we
485/// insert so that the caller can reprocess it.
Chris Lattner998182b2008-04-26 07:40:11 +0000486static GlobalVariable *SRAGlobal(GlobalVariable *GV, const TargetData &TD) {
Chris Lattner727c2102008-01-14 01:31:05 +0000487 // Make sure this global only has simple uses that we can SRA.
Chris Lattner941db492008-01-14 02:09:12 +0000488 if (!GlobalUsersSafeToSRA(GV))
Chris Lattner727c2102008-01-14 01:31:05 +0000489 return 0;
490
Rafael Espindolabb46f522009-01-15 20:18:42 +0000491 assert(GV->hasLocalLinkage() && !GV->isConstant());
Chris Lattner670c8892004-10-08 17:32:09 +0000492 Constant *Init = GV->getInitializer();
493 const Type *Ty = Init->getType();
Misha Brukmanfd939082005-04-21 23:48:37 +0000494
Chris Lattner670c8892004-10-08 17:32:09 +0000495 std::vector<GlobalVariable*> NewGlobals;
496 Module::GlobalListType &Globals = GV->getParent()->getGlobalList();
497
Chris Lattner998182b2008-04-26 07:40:11 +0000498 // Get the alignment of the global, either explicit or target-specific.
499 unsigned StartAlignment = GV->getAlignment();
500 if (StartAlignment == 0)
501 StartAlignment = TD.getABITypeAlignment(GV->getType());
502
Chris Lattner670c8892004-10-08 17:32:09 +0000503 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
504 NewGlobals.reserve(STy->getNumElements());
Chris Lattner998182b2008-04-26 07:40:11 +0000505 const StructLayout &Layout = *TD.getStructLayout(STy);
Chris Lattner670c8892004-10-08 17:32:09 +0000506 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
507 Constant *In = getAggregateConstantElement(Init,
Reid Spencerc5b206b2006-12-31 05:48:39 +0000508 ConstantInt::get(Type::Int32Ty, i));
Chris Lattner670c8892004-10-08 17:32:09 +0000509 assert(In && "Couldn't get element of initializer?");
510 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(i), false,
511 GlobalVariable::InternalLinkage,
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +0000512 In, GV->getName()+"."+utostr(i),
513 (Module *)NULL,
Matthijs Kooijmanbc1f9892008-07-17 11:59:53 +0000514 GV->isThreadLocal(),
515 GV->getType()->getAddressSpace());
Chris Lattner670c8892004-10-08 17:32:09 +0000516 Globals.insert(GV, NGV);
517 NewGlobals.push_back(NGV);
Chris Lattner998182b2008-04-26 07:40:11 +0000518
519 // Calculate the known alignment of the field. If the original aggregate
520 // had 256 byte alignment for example, something might depend on that:
521 // propagate info to each field.
522 uint64_t FieldOffset = Layout.getElementOffset(i);
523 unsigned NewAlign = (unsigned)MinAlign(StartAlignment, FieldOffset);
524 if (NewAlign > TD.getABITypeAlignment(STy->getElementType(i)))
525 NGV->setAlignment(NewAlign);
Chris Lattner670c8892004-10-08 17:32:09 +0000526 }
527 } else if (const SequentialType *STy = dyn_cast<SequentialType>(Ty)) {
528 unsigned NumElements = 0;
529 if (const ArrayType *ATy = dyn_cast<ArrayType>(STy))
530 NumElements = ATy->getNumElements();
Chris Lattner670c8892004-10-08 17:32:09 +0000531 else
Chris Lattner998182b2008-04-26 07:40:11 +0000532 NumElements = cast<VectorType>(STy)->getNumElements();
Chris Lattner670c8892004-10-08 17:32:09 +0000533
Chris Lattner1f21ef12005-02-23 16:53:04 +0000534 if (NumElements > 16 && GV->hasNUsesOrMore(16))
Chris Lattnerd514d822005-02-01 01:23:31 +0000535 return 0; // It's not worth it.
Chris Lattner670c8892004-10-08 17:32:09 +0000536 NewGlobals.reserve(NumElements);
Chris Lattner998182b2008-04-26 07:40:11 +0000537
Duncan Sandsceb4d1a2009-01-12 20:38:59 +0000538 uint64_t EltSize = TD.getTypePaddedSize(STy->getElementType());
Chris Lattner998182b2008-04-26 07:40:11 +0000539 unsigned EltAlign = TD.getABITypeAlignment(STy->getElementType());
Chris Lattner670c8892004-10-08 17:32:09 +0000540 for (unsigned i = 0, e = NumElements; i != e; ++i) {
541 Constant *In = getAggregateConstantElement(Init,
Reid Spencerc5b206b2006-12-31 05:48:39 +0000542 ConstantInt::get(Type::Int32Ty, i));
Chris Lattner670c8892004-10-08 17:32:09 +0000543 assert(In && "Couldn't get element of initializer?");
544
545 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(), false,
546 GlobalVariable::InternalLinkage,
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +0000547 In, GV->getName()+"."+utostr(i),
548 (Module *)NULL,
Matthijs Kooijmanbc1f9892008-07-17 11:59:53 +0000549 GV->isThreadLocal(),
550 GV->getType()->getAddressSpace());
Chris Lattner670c8892004-10-08 17:32:09 +0000551 Globals.insert(GV, NGV);
552 NewGlobals.push_back(NGV);
Chris Lattner998182b2008-04-26 07:40:11 +0000553
554 // Calculate the known alignment of the field. If the original aggregate
555 // had 256 byte alignment for example, something might depend on that:
556 // propagate info to each field.
557 unsigned NewAlign = (unsigned)MinAlign(StartAlignment, EltSize*i);
558 if (NewAlign > EltAlign)
559 NGV->setAlignment(NewAlign);
Chris Lattner670c8892004-10-08 17:32:09 +0000560 }
561 }
562
563 if (NewGlobals.empty())
564 return 0;
565
Bill Wendling0a81aac2006-11-26 10:02:32 +0000566 DOUT << "PERFORMING GLOBAL SRA ON: " << *GV;
Chris Lattner30ba5692004-10-11 05:54:41 +0000567
Reid Spencerc5b206b2006-12-31 05:48:39 +0000568 Constant *NullInt = Constant::getNullValue(Type::Int32Ty);
Chris Lattner670c8892004-10-08 17:32:09 +0000569
570 // Loop over all of the uses of the global, replacing the constantexpr geps,
571 // with smaller constantexpr geps or direct references.
572 while (!GV->use_empty()) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000573 User *GEP = GV->use_back();
574 assert(((isa<ConstantExpr>(GEP) &&
575 cast<ConstantExpr>(GEP)->getOpcode()==Instruction::GetElementPtr)||
576 isa<GetElementPtrInst>(GEP)) && "NonGEP CE's are not SRAable!");
Misha Brukmanfd939082005-04-21 23:48:37 +0000577
Chris Lattner670c8892004-10-08 17:32:09 +0000578 // Ignore the 1th operand, which has to be zero or else the program is quite
579 // broken (undefined). Get the 2nd operand, which is the structure or array
580 // index.
Reid Spencerb83eb642006-10-20 07:07:24 +0000581 unsigned Val = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
Chris Lattner670c8892004-10-08 17:32:09 +0000582 if (Val >= NewGlobals.size()) Val = 0; // Out of bound array access.
583
Chris Lattner30ba5692004-10-11 05:54:41 +0000584 Value *NewPtr = NewGlobals[Val];
Chris Lattner670c8892004-10-08 17:32:09 +0000585
586 // Form a shorter GEP if needed.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000587 if (GEP->getNumOperands() > 3) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000588 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEP)) {
Chris Lattner55eb1c42007-01-31 04:40:53 +0000589 SmallVector<Constant*, 8> Idxs;
Chris Lattner30ba5692004-10-11 05:54:41 +0000590 Idxs.push_back(NullInt);
591 for (unsigned i = 3, e = CE->getNumOperands(); i != e; ++i)
592 Idxs.push_back(CE->getOperand(i));
Chris Lattner55eb1c42007-01-31 04:40:53 +0000593 NewPtr = ConstantExpr::getGetElementPtr(cast<Constant>(NewPtr),
594 &Idxs[0], Idxs.size());
Chris Lattner30ba5692004-10-11 05:54:41 +0000595 } else {
596 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(GEP);
Chris Lattner699d1442007-01-31 19:59:55 +0000597 SmallVector<Value*, 8> Idxs;
Chris Lattner30ba5692004-10-11 05:54:41 +0000598 Idxs.push_back(NullInt);
599 for (unsigned i = 3, e = GEPI->getNumOperands(); i != e; ++i)
600 Idxs.push_back(GEPI->getOperand(i));
Gabor Greif051a9502008-04-06 20:25:17 +0000601 NewPtr = GetElementPtrInst::Create(NewPtr, Idxs.begin(), Idxs.end(),
602 GEPI->getName()+"."+utostr(Val), GEPI);
Chris Lattner30ba5692004-10-11 05:54:41 +0000603 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000604 }
Chris Lattner30ba5692004-10-11 05:54:41 +0000605 GEP->replaceAllUsesWith(NewPtr);
606
607 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(GEP))
Chris Lattner7a7ed022004-10-16 18:09:00 +0000608 GEPI->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +0000609 else
610 cast<ConstantExpr>(GEP)->destroyConstant();
Chris Lattner670c8892004-10-08 17:32:09 +0000611 }
612
Chris Lattnere40e2d12004-10-08 20:25:55 +0000613 // Delete the old global, now that it is dead.
614 Globals.erase(GV);
Chris Lattner670c8892004-10-08 17:32:09 +0000615 ++NumSRA;
Chris Lattner30ba5692004-10-11 05:54:41 +0000616
617 // Loop over the new globals array deleting any globals that are obviously
618 // dead. This can arise due to scalarization of a structure or an array that
619 // has elements that are dead.
620 unsigned FirstGlobal = 0;
621 for (unsigned i = 0, e = NewGlobals.size(); i != e; ++i)
622 if (NewGlobals[i]->use_empty()) {
623 Globals.erase(NewGlobals[i]);
624 if (FirstGlobal == i) ++FirstGlobal;
625 }
626
627 return FirstGlobal != NewGlobals.size() ? NewGlobals[FirstGlobal] : 0;
Chris Lattner670c8892004-10-08 17:32:09 +0000628}
629
Chris Lattner9b34a612004-10-09 21:48:45 +0000630/// AllUsesOfValueWillTrapIfNull - Return true if all users of the specified
Chris Lattner81686182007-09-13 16:30:19 +0000631/// value will trap if the value is dynamically null. PHIs keeps track of any
632/// phi nodes we've seen to avoid reprocessing them.
633static bool AllUsesOfValueWillTrapIfNull(Value *V,
634 SmallPtrSet<PHINode*, 8> &PHIs) {
Chris Lattner9b34a612004-10-09 21:48:45 +0000635 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
636 if (isa<LoadInst>(*UI)) {
637 // Will trap.
638 } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
639 if (SI->getOperand(0) == V) {
Bill Wendlinge8156192006-12-07 01:30:32 +0000640 //cerr << "NONTRAPPING USE: " << **UI;
Chris Lattner9b34a612004-10-09 21:48:45 +0000641 return false; // Storing the value.
642 }
643 } else if (CallInst *CI = dyn_cast<CallInst>(*UI)) {
644 if (CI->getOperand(0) != V) {
Bill Wendlinge8156192006-12-07 01:30:32 +0000645 //cerr << "NONTRAPPING USE: " << **UI;
Chris Lattner9b34a612004-10-09 21:48:45 +0000646 return false; // Not calling the ptr
647 }
648 } else if (InvokeInst *II = dyn_cast<InvokeInst>(*UI)) {
649 if (II->getOperand(0) != V) {
Bill Wendlinge8156192006-12-07 01:30:32 +0000650 //cerr << "NONTRAPPING USE: " << **UI;
Chris Lattner9b34a612004-10-09 21:48:45 +0000651 return false; // Not calling the ptr
652 }
Chris Lattner81686182007-09-13 16:30:19 +0000653 } else if (BitCastInst *CI = dyn_cast<BitCastInst>(*UI)) {
654 if (!AllUsesOfValueWillTrapIfNull(CI, PHIs)) return false;
Chris Lattner9b34a612004-10-09 21:48:45 +0000655 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(*UI)) {
Chris Lattner81686182007-09-13 16:30:19 +0000656 if (!AllUsesOfValueWillTrapIfNull(GEPI, PHIs)) return false;
657 } else if (PHINode *PN = dyn_cast<PHINode>(*UI)) {
658 // If we've already seen this phi node, ignore it, it has already been
659 // checked.
660 if (PHIs.insert(PN))
661 return AllUsesOfValueWillTrapIfNull(PN, PHIs);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000662 } else if (isa<ICmpInst>(*UI) &&
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000663 isa<ConstantPointerNull>(UI->getOperand(1))) {
664 // Ignore setcc X, null
Chris Lattner9b34a612004-10-09 21:48:45 +0000665 } else {
Bill Wendlinge8156192006-12-07 01:30:32 +0000666 //cerr << "NONTRAPPING USE: " << **UI;
Chris Lattner9b34a612004-10-09 21:48:45 +0000667 return false;
668 }
669 return true;
670}
671
672/// AllUsesOfLoadedValueWillTrapIfNull - Return true if all uses of any loads
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000673/// from GV will trap if the loaded value is null. Note that this also permits
674/// comparisons of the loaded value against null, as a special case.
Chris Lattner9b34a612004-10-09 21:48:45 +0000675static bool AllUsesOfLoadedValueWillTrapIfNull(GlobalVariable *GV) {
676 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI!=E; ++UI)
677 if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
Chris Lattner81686182007-09-13 16:30:19 +0000678 SmallPtrSet<PHINode*, 8> PHIs;
679 if (!AllUsesOfValueWillTrapIfNull(LI, PHIs))
Chris Lattner9b34a612004-10-09 21:48:45 +0000680 return false;
681 } else if (isa<StoreInst>(*UI)) {
682 // Ignore stores to the global.
683 } else {
684 // We don't know or understand this user, bail out.
Bill Wendlinge8156192006-12-07 01:30:32 +0000685 //cerr << "UNKNOWN USER OF GLOBAL!: " << **UI;
Chris Lattner9b34a612004-10-09 21:48:45 +0000686 return false;
687 }
688
689 return true;
690}
691
Chris Lattner708148e2004-10-10 23:14:11 +0000692static bool OptimizeAwayTrappingUsesOfValue(Value *V, Constant *NewV) {
693 bool Changed = false;
694 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ) {
695 Instruction *I = cast<Instruction>(*UI++);
696 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
697 LI->setOperand(0, NewV);
698 Changed = true;
699 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
700 if (SI->getOperand(1) == V) {
701 SI->setOperand(1, NewV);
702 Changed = true;
703 }
704 } else if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
705 if (I->getOperand(0) == V) {
706 // Calling through the pointer! Turn into a direct call, but be careful
707 // that the pointer is not also being passed as an argument.
708 I->setOperand(0, NewV);
709 Changed = true;
710 bool PassedAsArg = false;
711 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i)
712 if (I->getOperand(i) == V) {
713 PassedAsArg = true;
714 I->setOperand(i, NewV);
715 }
716
717 if (PassedAsArg) {
718 // Being passed as an argument also. Be careful to not invalidate UI!
719 UI = V->use_begin();
720 }
721 }
722 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
723 Changed |= OptimizeAwayTrappingUsesOfValue(CI,
Chris Lattner6e8fbad2006-11-30 17:32:29 +0000724 ConstantExpr::getCast(CI->getOpcode(),
725 NewV, CI->getType()));
Chris Lattner708148e2004-10-10 23:14:11 +0000726 if (CI->use_empty()) {
727 Changed = true;
Chris Lattner7a7ed022004-10-16 18:09:00 +0000728 CI->eraseFromParent();
Chris Lattner708148e2004-10-10 23:14:11 +0000729 }
730 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
731 // Should handle GEP here.
Chris Lattner55eb1c42007-01-31 04:40:53 +0000732 SmallVector<Constant*, 8> Idxs;
733 Idxs.reserve(GEPI->getNumOperands()-1);
Gabor Greif5e463212008-05-29 01:59:18 +0000734 for (User::op_iterator i = GEPI->op_begin() + 1, e = GEPI->op_end();
735 i != e; ++i)
736 if (Constant *C = dyn_cast<Constant>(*i))
Chris Lattner55eb1c42007-01-31 04:40:53 +0000737 Idxs.push_back(C);
Chris Lattner708148e2004-10-10 23:14:11 +0000738 else
739 break;
Chris Lattner55eb1c42007-01-31 04:40:53 +0000740 if (Idxs.size() == GEPI->getNumOperands()-1)
Chris Lattner708148e2004-10-10 23:14:11 +0000741 Changed |= OptimizeAwayTrappingUsesOfValue(GEPI,
Chris Lattner55eb1c42007-01-31 04:40:53 +0000742 ConstantExpr::getGetElementPtr(NewV, &Idxs[0],
743 Idxs.size()));
Chris Lattner708148e2004-10-10 23:14:11 +0000744 if (GEPI->use_empty()) {
745 Changed = true;
Chris Lattner7a7ed022004-10-16 18:09:00 +0000746 GEPI->eraseFromParent();
Chris Lattner708148e2004-10-10 23:14:11 +0000747 }
748 }
749 }
750
751 return Changed;
752}
753
754
755/// OptimizeAwayTrappingUsesOfLoads - The specified global has only one non-null
756/// value stored into it. If there are uses of the loaded value that would trap
757/// if the loaded value is dynamically null, then we know that they cannot be
758/// reachable with a null optimize away the load.
759static bool OptimizeAwayTrappingUsesOfLoads(GlobalVariable *GV, Constant *LV) {
Chris Lattner708148e2004-10-10 23:14:11 +0000760 bool Changed = false;
761
Chris Lattner92c6bd22009-01-14 00:12:58 +0000762 // Keep track of whether we are able to remove all the uses of the global
763 // other than the store that defines it.
764 bool AllNonStoreUsesGone = true;
765
Chris Lattner708148e2004-10-10 23:14:11 +0000766 // Replace all uses of loads with uses of uses of the stored value.
Chris Lattner92c6bd22009-01-14 00:12:58 +0000767 for (Value::use_iterator GUI = GV->use_begin(), E = GV->use_end(); GUI != E;){
768 User *GlobalUser = *GUI++;
769 if (LoadInst *LI = dyn_cast<LoadInst>(GlobalUser)) {
Chris Lattner708148e2004-10-10 23:14:11 +0000770 Changed |= OptimizeAwayTrappingUsesOfValue(LI, LV);
Chris Lattner92c6bd22009-01-14 00:12:58 +0000771 // If we were able to delete all uses of the loads
772 if (LI->use_empty()) {
773 LI->eraseFromParent();
774 Changed = true;
775 } else {
776 AllNonStoreUsesGone = false;
777 }
778 } else if (isa<StoreInst>(GlobalUser)) {
779 // Ignore the store that stores "LV" to the global.
780 assert(GlobalUser->getOperand(1) == GV &&
781 "Must be storing *to* the global");
Chris Lattner708148e2004-10-10 23:14:11 +0000782 } else {
Chris Lattner92c6bd22009-01-14 00:12:58 +0000783 AllNonStoreUsesGone = false;
784
785 // If we get here we could have other crazy uses that are transitively
786 // loaded.
787 assert((isa<PHINode>(GlobalUser) || isa<SelectInst>(GlobalUser) ||
788 isa<ConstantExpr>(GlobalUser)) && "Only expect load and stores!");
Chris Lattner708148e2004-10-10 23:14:11 +0000789 }
Chris Lattner92c6bd22009-01-14 00:12:58 +0000790 }
Chris Lattner708148e2004-10-10 23:14:11 +0000791
792 if (Changed) {
Bill Wendling0a81aac2006-11-26 10:02:32 +0000793 DOUT << "OPTIMIZED LOADS FROM STORED ONCE POINTER: " << *GV;
Chris Lattner708148e2004-10-10 23:14:11 +0000794 ++NumGlobUses;
795 }
796
Chris Lattner708148e2004-10-10 23:14:11 +0000797 // If we nuked all of the loads, then none of the stores are needed either,
798 // nor is the global.
Chris Lattner92c6bd22009-01-14 00:12:58 +0000799 if (AllNonStoreUsesGone) {
Bill Wendling0a81aac2006-11-26 10:02:32 +0000800 DOUT << " *** GLOBAL NOW DEAD!\n";
Chris Lattner708148e2004-10-10 23:14:11 +0000801 CleanupConstantGlobalUsers(GV, 0);
802 if (GV->use_empty()) {
Chris Lattner7a7ed022004-10-16 18:09:00 +0000803 GV->eraseFromParent();
Chris Lattner708148e2004-10-10 23:14:11 +0000804 ++NumDeleted;
805 }
806 Changed = true;
807 }
808 return Changed;
809}
810
Chris Lattner30ba5692004-10-11 05:54:41 +0000811/// ConstantPropUsersOf - Walk the use list of V, constant folding all of the
812/// instructions that are foldable.
813static void ConstantPropUsersOf(Value *V) {
814 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; )
815 if (Instruction *I = dyn_cast<Instruction>(*UI++))
816 if (Constant *NewC = ConstantFoldInstruction(I)) {
817 I->replaceAllUsesWith(NewC);
818
Chris Lattnerd514d822005-02-01 01:23:31 +0000819 // Advance UI to the next non-I use to avoid invalidating it!
820 // Instructions could multiply use V.
821 while (UI != E && *UI == I)
Chris Lattner30ba5692004-10-11 05:54:41 +0000822 ++UI;
Chris Lattnerd514d822005-02-01 01:23:31 +0000823 I->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +0000824 }
825}
826
827/// OptimizeGlobalAddressOfMalloc - This function takes the specified global
828/// variable, and transforms the program as if it always contained the result of
829/// the specified malloc. Because it is always the result of the specified
830/// malloc, there is no reason to actually DO the malloc. Instead, turn the
Chris Lattner6e8fbad2006-11-30 17:32:29 +0000831/// malloc into a global, and any loads of GV as uses of the new global.
Chris Lattner30ba5692004-10-11 05:54:41 +0000832static GlobalVariable *OptimizeGlobalAddressOfMalloc(GlobalVariable *GV,
833 MallocInst *MI) {
Bill Wendling0a81aac2006-11-26 10:02:32 +0000834 DOUT << "PROMOTING MALLOC GLOBAL: " << *GV << " MALLOC = " << *MI;
Chris Lattner30ba5692004-10-11 05:54:41 +0000835 ConstantInt *NElements = cast<ConstantInt>(MI->getArraySize());
836
Reid Spencerb83eb642006-10-20 07:07:24 +0000837 if (NElements->getZExtValue() != 1) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000838 // If we have an array allocation, transform it to a single element
839 // allocation to make the code below simpler.
840 Type *NewTy = ArrayType::get(MI->getAllocatedType(),
Reid Spencerb83eb642006-10-20 07:07:24 +0000841 NElements->getZExtValue());
Chris Lattner30ba5692004-10-11 05:54:41 +0000842 MallocInst *NewMI =
Reid Spencerc5b206b2006-12-31 05:48:39 +0000843 new MallocInst(NewTy, Constant::getNullValue(Type::Int32Ty),
Nate Begeman14b05292005-11-05 09:21:28 +0000844 MI->getAlignment(), MI->getName(), MI);
Chris Lattner699d1442007-01-31 19:59:55 +0000845 Value* Indices[2];
846 Indices[0] = Indices[1] = Constant::getNullValue(Type::Int32Ty);
Gabor Greif051a9502008-04-06 20:25:17 +0000847 Value *NewGEP = GetElementPtrInst::Create(NewMI, Indices, Indices + 2,
848 NewMI->getName()+".el0", MI);
Chris Lattner30ba5692004-10-11 05:54:41 +0000849 MI->replaceAllUsesWith(NewGEP);
Chris Lattner7a7ed022004-10-16 18:09:00 +0000850 MI->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +0000851 MI = NewMI;
852 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000853
Chris Lattner7a7ed022004-10-16 18:09:00 +0000854 // Create the new global variable. The contents of the malloc'd memory is
855 // undefined, so initialize with an undef value.
856 Constant *Init = UndefValue::get(MI->getAllocatedType());
Chris Lattner30ba5692004-10-11 05:54:41 +0000857 GlobalVariable *NewGV = new GlobalVariable(MI->getAllocatedType(), false,
858 GlobalValue::InternalLinkage, Init,
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +0000859 GV->getName()+".body",
860 (Module *)NULL,
861 GV->isThreadLocal());
Chris Lattner998182b2008-04-26 07:40:11 +0000862 // FIXME: This new global should have the alignment returned by malloc. Code
863 // could depend on malloc returning large alignment (on the mac, 16 bytes) but
864 // this would only guarantee some lower alignment.
Chris Lattner30ba5692004-10-11 05:54:41 +0000865 GV->getParent()->getGlobalList().insert(GV, NewGV);
Misha Brukmanfd939082005-04-21 23:48:37 +0000866
Chris Lattner30ba5692004-10-11 05:54:41 +0000867 // Anything that used the malloc now uses the global directly.
868 MI->replaceAllUsesWith(NewGV);
Chris Lattner30ba5692004-10-11 05:54:41 +0000869
870 Constant *RepValue = NewGV;
871 if (NewGV->getType() != GV->getType()->getElementType())
Reid Spencerd977d862006-12-12 23:36:14 +0000872 RepValue = ConstantExpr::getBitCast(RepValue,
873 GV->getType()->getElementType());
Chris Lattner30ba5692004-10-11 05:54:41 +0000874
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000875 // If there is a comparison against null, we will insert a global bool to
876 // keep track of whether the global was initialized yet or not.
Misha Brukmanfd939082005-04-21 23:48:37 +0000877 GlobalVariable *InitBool =
Reid Spencer4fe16d62007-01-11 18:21:29 +0000878 new GlobalVariable(Type::Int1Ty, false, GlobalValue::InternalLinkage,
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +0000879 ConstantInt::getFalse(), GV->getName()+".init",
880 (Module *)NULL, GV->isThreadLocal());
Chris Lattnerbc965b92004-12-02 06:25:58 +0000881 bool InitBoolUsed = false;
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000882
Chris Lattner30ba5692004-10-11 05:54:41 +0000883 // Loop over all uses of GV, processing them in turn.
Chris Lattnerbc965b92004-12-02 06:25:58 +0000884 std::vector<StoreInst*> Stores;
Chris Lattner30ba5692004-10-11 05:54:41 +0000885 while (!GV->use_empty())
886 if (LoadInst *LI = dyn_cast<LoadInst>(GV->use_back())) {
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000887 while (!LI->use_empty()) {
Chris Lattnerd514d822005-02-01 01:23:31 +0000888 Use &LoadUse = LI->use_begin().getUse();
Reid Spencere4d87aa2006-12-23 06:05:41 +0000889 if (!isa<ICmpInst>(LoadUse.getUser()))
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000890 LoadUse = RepValue;
891 else {
Reid Spencere4d87aa2006-12-23 06:05:41 +0000892 ICmpInst *CI = cast<ICmpInst>(LoadUse.getUser());
893 // Replace the cmp X, 0 with a use of the bool value.
894 Value *LV = new LoadInst(InitBool, InitBool->getName()+".val", CI);
Chris Lattnerbc965b92004-12-02 06:25:58 +0000895 InitBoolUsed = true;
Reid Spencere4d87aa2006-12-23 06:05:41 +0000896 switch (CI->getPredicate()) {
897 default: assert(0 && "Unknown ICmp Predicate!");
898 case ICmpInst::ICMP_ULT:
899 case ICmpInst::ICMP_SLT:
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000900 LV = ConstantInt::getFalse(); // X < null -> always false
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000901 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +0000902 case ICmpInst::ICMP_ULE:
903 case ICmpInst::ICMP_SLE:
904 case ICmpInst::ICMP_EQ:
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000905 LV = BinaryOperator::CreateNot(LV, "notinit", CI);
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000906 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +0000907 case ICmpInst::ICMP_NE:
908 case ICmpInst::ICMP_UGE:
909 case ICmpInst::ICMP_SGE:
910 case ICmpInst::ICMP_UGT:
911 case ICmpInst::ICMP_SGT:
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000912 break; // no change.
913 }
Reid Spencere4d87aa2006-12-23 06:05:41 +0000914 CI->replaceAllUsesWith(LV);
915 CI->eraseFromParent();
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000916 }
917 }
Chris Lattner7a7ed022004-10-16 18:09:00 +0000918 LI->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +0000919 } else {
920 StoreInst *SI = cast<StoreInst>(GV->use_back());
Chris Lattnerbc965b92004-12-02 06:25:58 +0000921 // The global is initialized when the store to it occurs.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000922 new StoreInst(ConstantInt::getTrue(), InitBool, SI);
Chris Lattner7a7ed022004-10-16 18:09:00 +0000923 SI->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +0000924 }
925
Chris Lattnerbc965b92004-12-02 06:25:58 +0000926 // If the initialization boolean was used, insert it, otherwise delete it.
927 if (!InitBoolUsed) {
928 while (!InitBool->use_empty()) // Delete initializations
929 cast<Instruction>(InitBool->use_back())->eraseFromParent();
930 delete InitBool;
931 } else
932 GV->getParent()->getGlobalList().insert(GV, InitBool);
933
934
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000935 // Now the GV is dead, nuke it and the malloc.
Chris Lattner7a7ed022004-10-16 18:09:00 +0000936 GV->eraseFromParent();
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000937 MI->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +0000938
939 // To further other optimizations, loop over all users of NewGV and try to
940 // constant prop them. This will promote GEP instructions with constant
941 // indices into GEP constant-exprs, which will allow global-opt to hack on it.
942 ConstantPropUsersOf(NewGV);
943 if (RepValue != NewGV)
944 ConstantPropUsersOf(RepValue);
945
946 return NewGV;
947}
Chris Lattner708148e2004-10-10 23:14:11 +0000948
Chris Lattnerfa07e4f2004-12-02 07:11:07 +0000949/// ValueIsOnlyUsedLocallyOrStoredToOneGlobal - Scan the use-list of V checking
950/// to make sure that there are no complex uses of V. We permit simple things
951/// like dereferencing the pointer, but not storing through the address, unless
952/// it is to the specified global.
953static bool ValueIsOnlyUsedLocallyOrStoredToOneGlobal(Instruction *V,
Chris Lattnerc451f9c2007-09-13 16:37:20 +0000954 GlobalVariable *GV,
955 SmallPtrSet<PHINode*, 8> &PHIs) {
Chris Lattner49b6d4a2008-12-15 21:08:54 +0000956 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;++UI){
957 Instruction *Inst = dyn_cast<Instruction>(*UI);
958 if (Inst == 0) return false;
959
960 if (isa<LoadInst>(Inst) || isa<CmpInst>(Inst)) {
961 continue; // Fine, ignore.
962 }
963
964 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
Chris Lattnerfa07e4f2004-12-02 07:11:07 +0000965 if (SI->getOperand(0) == V && SI->getOperand(1) != GV)
966 return false; // Storing the pointer itself... bad.
Chris Lattner49b6d4a2008-12-15 21:08:54 +0000967 continue; // Otherwise, storing through it, or storing into GV... fine.
968 }
969
970 if (isa<GetElementPtrInst>(Inst)) {
971 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(Inst, GV, PHIs))
Chris Lattnerfa07e4f2004-12-02 07:11:07 +0000972 return false;
Chris Lattner49b6d4a2008-12-15 21:08:54 +0000973 continue;
974 }
975
976 if (PHINode *PN = dyn_cast<PHINode>(Inst)) {
Chris Lattnerc451f9c2007-09-13 16:37:20 +0000977 // PHIs are ok if all uses are ok. Don't infinitely recurse through PHI
978 // cycles.
979 if (PHIs.insert(PN))
Chris Lattner5e6e4942007-09-14 03:41:21 +0000980 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(PN, GV, PHIs))
981 return false;
Chris Lattner49b6d4a2008-12-15 21:08:54 +0000982 continue;
Chris Lattnerfa07e4f2004-12-02 07:11:07 +0000983 }
Chris Lattner49b6d4a2008-12-15 21:08:54 +0000984
985 if (BitCastInst *BCI = dyn_cast<BitCastInst>(Inst)) {
986 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(BCI, GV, PHIs))
987 return false;
988 continue;
989 }
990
991 return false;
992 }
Chris Lattnerfa07e4f2004-12-02 07:11:07 +0000993 return true;
Chris Lattnerfa07e4f2004-12-02 07:11:07 +0000994}
995
Chris Lattner86395032006-09-30 23:32:09 +0000996/// ReplaceUsesOfMallocWithGlobal - The Alloc pointer is stored into GV
997/// somewhere. Transform all uses of the allocation into loads from the
998/// global and uses of the resultant pointer. Further, delete the store into
999/// GV. This assumes that these value pass the
1000/// 'ValueIsOnlyUsedLocallyOrStoredToOneGlobal' predicate.
1001static void ReplaceUsesOfMallocWithGlobal(Instruction *Alloc,
1002 GlobalVariable *GV) {
1003 while (!Alloc->use_empty()) {
Chris Lattnera637a8b2007-09-13 18:00:31 +00001004 Instruction *U = cast<Instruction>(*Alloc->use_begin());
1005 Instruction *InsertPt = U;
Chris Lattner86395032006-09-30 23:32:09 +00001006 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
1007 // If this is the store of the allocation into the global, remove it.
1008 if (SI->getOperand(1) == GV) {
1009 SI->eraseFromParent();
1010 continue;
1011 }
Chris Lattnera637a8b2007-09-13 18:00:31 +00001012 } else if (PHINode *PN = dyn_cast<PHINode>(U)) {
1013 // Insert the load in the corresponding predecessor, not right before the
1014 // PHI.
Gabor Greifa36791d2009-01-23 19:40:15 +00001015 InsertPt = PN->getIncomingBlock(Alloc->use_begin())->getTerminator();
Chris Lattner101f44e2008-12-15 21:44:34 +00001016 } else if (isa<BitCastInst>(U)) {
1017 // Must be bitcast between the malloc and store to initialize the global.
1018 ReplaceUsesOfMallocWithGlobal(U, GV);
1019 U->eraseFromParent();
1020 continue;
1021 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
1022 // If this is a "GEP bitcast" and the user is a store to the global, then
1023 // just process it as a bitcast.
1024 if (GEPI->hasAllZeroIndices() && GEPI->hasOneUse())
1025 if (StoreInst *SI = dyn_cast<StoreInst>(GEPI->use_back()))
1026 if (SI->getOperand(1) == GV) {
1027 // Must be bitcast GEP between the malloc and store to initialize
1028 // the global.
1029 ReplaceUsesOfMallocWithGlobal(GEPI, GV);
1030 GEPI->eraseFromParent();
1031 continue;
1032 }
Chris Lattner86395032006-09-30 23:32:09 +00001033 }
Chris Lattner101f44e2008-12-15 21:44:34 +00001034
Chris Lattner86395032006-09-30 23:32:09 +00001035 // Insert a load from the global, and use it instead of the malloc.
Chris Lattnera637a8b2007-09-13 18:00:31 +00001036 Value *NL = new LoadInst(GV, GV->getName()+".val", InsertPt);
Chris Lattner86395032006-09-30 23:32:09 +00001037 U->replaceUsesOfWith(Alloc, NL);
1038 }
1039}
1040
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001041/// LoadUsesSimpleEnoughForHeapSRA - Verify that all uses of V (a load, or a phi
1042/// of a load) are simple enough to perform heap SRA on. This permits GEP's
1043/// that index through the array and struct field, icmps of null, and PHIs.
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001044static bool LoadUsesSimpleEnoughForHeapSRA(Value *V,
1045 SmallPtrSet<PHINode*, 32> &LoadUsingPHIs) {
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001046 // We permit two users of the load: setcc comparing against the null
1047 // pointer, and a getelementptr of a specific form.
1048 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;++UI){
1049 Instruction *User = cast<Instruction>(*UI);
1050
1051 // Comparison against null is ok.
1052 if (ICmpInst *ICI = dyn_cast<ICmpInst>(User)) {
1053 if (!isa<ConstantPointerNull>(ICI->getOperand(1)))
1054 return false;
1055 continue;
1056 }
1057
1058 // getelementptr is also ok, but only a simple form.
1059 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
1060 // Must index into the array and into the struct.
1061 if (GEPI->getNumOperands() < 3)
1062 return false;
1063
1064 // Otherwise the GEP is ok.
1065 continue;
1066 }
1067
1068 if (PHINode *PN = dyn_cast<PHINode>(User)) {
1069 // If we have already recursively analyzed this PHI, then it is safe.
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001070 if (LoadUsingPHIs.insert(PN))
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001071 continue;
1072
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001073 // Make sure all uses of the PHI are simple enough to transform.
1074 if (!LoadUsesSimpleEnoughForHeapSRA(PN, LoadUsingPHIs))
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001075 return false;
1076
1077 continue;
Chris Lattner86395032006-09-30 23:32:09 +00001078 }
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001079
1080 // Otherwise we don't know what this is, not ok.
1081 return false;
1082 }
1083
1084 return true;
1085}
1086
1087
1088/// AllGlobalLoadUsesSimpleEnoughForHeapSRA - If all users of values loaded from
1089/// GV are simple enough to perform HeapSRA, return true.
1090static bool AllGlobalLoadUsesSimpleEnoughForHeapSRA(GlobalVariable *GV,
1091 MallocInst *MI) {
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001092 SmallPtrSet<PHINode*, 32> LoadUsingPHIs;
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001093 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI != E;
1094 ++UI)
1095 if (LoadInst *LI = dyn_cast<LoadInst>(*UI))
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001096 if (!LoadUsesSimpleEnoughForHeapSRA(LI, LoadUsingPHIs))
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001097 return false;
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001098
1099 // If we reach here, we know that all uses of the loads and transitive uses
1100 // (through PHI nodes) are simple enough to transform. However, we don't know
1101 // that all inputs the to the PHI nodes are in the same equivalence sets.
1102 // Check to verify that all operands of the PHIs are either PHIS that can be
1103 // transformed, loads from GV, or MI itself.
1104 for (SmallPtrSet<PHINode*, 32>::iterator I = LoadUsingPHIs.begin(),
1105 E = LoadUsingPHIs.end(); I != E; ++I) {
1106 PHINode *PN = *I;
1107 for (unsigned op = 0, e = PN->getNumIncomingValues(); op != e; ++op) {
1108 Value *InVal = PN->getIncomingValue(op);
1109
1110 // PHI of the stored value itself is ok.
1111 if (InVal == MI) continue;
1112
1113 if (PHINode *InPN = dyn_cast<PHINode>(InVal)) {
1114 // One of the PHIs in our set is (optimistically) ok.
1115 if (LoadUsingPHIs.count(InPN))
1116 continue;
1117 return false;
1118 }
1119
1120 // Load from GV is ok.
1121 if (LoadInst *LI = dyn_cast<LoadInst>(InVal))
1122 if (LI->getOperand(0) == GV)
1123 continue;
1124
1125 // UNDEF? NULL?
1126
1127 // Anything else is rejected.
1128 return false;
1129 }
1130 }
1131
Chris Lattner86395032006-09-30 23:32:09 +00001132 return true;
1133}
1134
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001135static Value *GetHeapSROAValue(Value *V, unsigned FieldNo,
1136 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
1137 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
1138 std::vector<Value*> &FieldVals = InsertedScalarizedValues[V];
1139
1140 if (FieldNo >= FieldVals.size())
1141 FieldVals.resize(FieldNo+1);
1142
1143 // If we already have this value, just reuse the previously scalarized
1144 // version.
1145 if (Value *FieldVal = FieldVals[FieldNo])
1146 return FieldVal;
1147
1148 // Depending on what instruction this is, we have several cases.
1149 Value *Result;
1150 if (LoadInst *LI = dyn_cast<LoadInst>(V)) {
1151 // This is a scalarized version of the load from the global. Just create
1152 // a new Load of the scalarized global.
1153 Result = new LoadInst(GetHeapSROAValue(LI->getOperand(0), FieldNo,
1154 InsertedScalarizedValues,
1155 PHIsToRewrite),
1156 LI->getName()+".f" + utostr(FieldNo), LI);
1157 } else if (PHINode *PN = dyn_cast<PHINode>(V)) {
1158 // PN's type is pointer to struct. Make a new PHI of pointer to struct
1159 // field.
1160 const StructType *ST =
1161 cast<StructType>(cast<PointerType>(PN->getType())->getElementType());
1162
1163 Result =PHINode::Create(PointerType::getUnqual(ST->getElementType(FieldNo)),
1164 PN->getName()+".f"+utostr(FieldNo), PN);
1165 PHIsToRewrite.push_back(std::make_pair(PN, FieldNo));
1166 } else {
1167 assert(0 && "Unknown usable value");
1168 Result = 0;
1169 }
1170
1171 return FieldVals[FieldNo] = Result;
Chris Lattnera637a8b2007-09-13 18:00:31 +00001172}
1173
Chris Lattner330245e2007-09-13 17:29:05 +00001174/// RewriteHeapSROALoadUser - Given a load instruction and a value derived from
1175/// the load, rewrite the derived value to use the HeapSRoA'd load.
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001176static void RewriteHeapSROALoadUser(Instruction *LoadUser,
1177 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
1178 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
Chris Lattner330245e2007-09-13 17:29:05 +00001179 // If this is a comparison against null, handle it.
1180 if (ICmpInst *SCI = dyn_cast<ICmpInst>(LoadUser)) {
1181 assert(isa<ConstantPointerNull>(SCI->getOperand(1)));
1182 // If we have a setcc of the loaded pointer, we can use a setcc of any
1183 // field.
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001184 Value *NPtr = GetHeapSROAValue(SCI->getOperand(0), 0,
1185 InsertedScalarizedValues, PHIsToRewrite);
Chris Lattner330245e2007-09-13 17:29:05 +00001186
1187 Value *New = new ICmpInst(SCI->getPredicate(), NPtr,
1188 Constant::getNullValue(NPtr->getType()),
1189 SCI->getName(), SCI);
1190 SCI->replaceAllUsesWith(New);
1191 SCI->eraseFromParent();
1192 return;
1193 }
1194
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001195 // Handle 'getelementptr Ptr, Idx, i32 FieldNo ...'
Chris Lattnera637a8b2007-09-13 18:00:31 +00001196 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(LoadUser)) {
1197 assert(GEPI->getNumOperands() >= 3 && isa<ConstantInt>(GEPI->getOperand(2))
1198 && "Unexpected GEPI!");
Chris Lattner330245e2007-09-13 17:29:05 +00001199
Chris Lattnera637a8b2007-09-13 18:00:31 +00001200 // Load the pointer for this field.
1201 unsigned FieldNo = cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue();
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001202 Value *NewPtr = GetHeapSROAValue(GEPI->getOperand(0), FieldNo,
1203 InsertedScalarizedValues, PHIsToRewrite);
Chris Lattnera637a8b2007-09-13 18:00:31 +00001204
1205 // Create the new GEP idx vector.
1206 SmallVector<Value*, 8> GEPIdx;
1207 GEPIdx.push_back(GEPI->getOperand(1));
1208 GEPIdx.append(GEPI->op_begin()+3, GEPI->op_end());
1209
Gabor Greifb1dbcd82008-05-15 10:04:30 +00001210 Value *NGEPI = GetElementPtrInst::Create(NewPtr,
1211 GEPIdx.begin(), GEPIdx.end(),
Gabor Greif051a9502008-04-06 20:25:17 +00001212 GEPI->getName(), GEPI);
Chris Lattnera637a8b2007-09-13 18:00:31 +00001213 GEPI->replaceAllUsesWith(NGEPI);
1214 GEPI->eraseFromParent();
1215 return;
1216 }
Chris Lattner309f20f2007-09-13 21:31:36 +00001217
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001218 // Recursively transform the users of PHI nodes. This will lazily create the
1219 // PHIs that are needed for individual elements. Keep track of what PHIs we
1220 // see in InsertedScalarizedValues so that we don't get infinite loops (very
1221 // antisocial). If the PHI is already in InsertedScalarizedValues, it has
1222 // already been seen first by another load, so its uses have already been
1223 // processed.
1224 PHINode *PN = cast<PHINode>(LoadUser);
1225 bool Inserted;
1226 DenseMap<Value*, std::vector<Value*> >::iterator InsertPos;
1227 tie(InsertPos, Inserted) =
1228 InsertedScalarizedValues.insert(std::make_pair(PN, std::vector<Value*>()));
1229 if (!Inserted) return;
Chris Lattner309f20f2007-09-13 21:31:36 +00001230
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001231 // If this is the first time we've seen this PHI, recursively process all
1232 // users.
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001233 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end(); UI != E; ) {
1234 Instruction *User = cast<Instruction>(*UI++);
1235 RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite);
1236 }
Chris Lattner330245e2007-09-13 17:29:05 +00001237}
1238
Chris Lattner86395032006-09-30 23:32:09 +00001239/// RewriteUsesOfLoadForHeapSRoA - We are performing Heap SRoA on a global. Ptr
1240/// is a value loaded from the global. Eliminate all uses of Ptr, making them
1241/// use FieldGlobals instead. All uses of loaded values satisfy
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001242/// AllGlobalLoadUsesSimpleEnoughForHeapSRA.
Chris Lattner330245e2007-09-13 17:29:05 +00001243static void RewriteUsesOfLoadForHeapSRoA(LoadInst *Load,
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001244 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
1245 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
1246 for (Value::use_iterator UI = Load->use_begin(), E = Load->use_end();
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001247 UI != E; ) {
1248 Instruction *User = cast<Instruction>(*UI++);
1249 RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite);
1250 }
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001251
1252 if (Load->use_empty()) {
1253 Load->eraseFromParent();
1254 InsertedScalarizedValues.erase(Load);
1255 }
Chris Lattner86395032006-09-30 23:32:09 +00001256}
1257
1258/// PerformHeapAllocSRoA - MI is an allocation of an array of structures. Break
1259/// it up into multiple allocations of arrays of the fields.
1260static GlobalVariable *PerformHeapAllocSRoA(GlobalVariable *GV, MallocInst *MI){
Bill Wendling0a81aac2006-11-26 10:02:32 +00001261 DOUT << "SROA HEAP ALLOC: " << *GV << " MALLOC = " << *MI;
Chris Lattner86395032006-09-30 23:32:09 +00001262 const StructType *STy = cast<StructType>(MI->getAllocatedType());
1263
1264 // There is guaranteed to be at least one use of the malloc (storing
1265 // it into GV). If there are other uses, change them to be uses of
1266 // the global to simplify later code. This also deletes the store
1267 // into GV.
1268 ReplaceUsesOfMallocWithGlobal(MI, GV);
1269
1270 // Okay, at this point, there are no users of the malloc. Insert N
1271 // new mallocs at the same place as MI, and N globals.
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001272 std::vector<Value*> FieldGlobals;
Chris Lattner86395032006-09-30 23:32:09 +00001273 std::vector<MallocInst*> FieldMallocs;
1274
1275 for (unsigned FieldNo = 0, e = STy->getNumElements(); FieldNo != e;++FieldNo){
1276 const Type *FieldTy = STy->getElementType(FieldNo);
Christopher Lamb43ad6b32007-12-17 01:12:55 +00001277 const Type *PFieldTy = PointerType::getUnqual(FieldTy);
Chris Lattner86395032006-09-30 23:32:09 +00001278
1279 GlobalVariable *NGV =
1280 new GlobalVariable(PFieldTy, false, GlobalValue::InternalLinkage,
1281 Constant::getNullValue(PFieldTy),
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +00001282 GV->getName() + ".f" + utostr(FieldNo), GV,
1283 GV->isThreadLocal());
Chris Lattner86395032006-09-30 23:32:09 +00001284 FieldGlobals.push_back(NGV);
1285
1286 MallocInst *NMI = new MallocInst(FieldTy, MI->getArraySize(),
1287 MI->getName() + ".f" + utostr(FieldNo),MI);
1288 FieldMallocs.push_back(NMI);
1289 new StoreInst(NMI, NGV, MI);
1290 }
1291
1292 // The tricky aspect of this transformation is handling the case when malloc
1293 // fails. In the original code, malloc failing would set the result pointer
1294 // of malloc to null. In this case, some mallocs could succeed and others
1295 // could fail. As such, we emit code that looks like this:
1296 // F0 = malloc(field0)
1297 // F1 = malloc(field1)
1298 // F2 = malloc(field2)
1299 // if (F0 == 0 || F1 == 0 || F2 == 0) {
1300 // if (F0) { free(F0); F0 = 0; }
1301 // if (F1) { free(F1); F1 = 0; }
1302 // if (F2) { free(F2); F2 = 0; }
1303 // }
1304 Value *RunningOr = 0;
1305 for (unsigned i = 0, e = FieldMallocs.size(); i != e; ++i) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001306 Value *Cond = new ICmpInst(ICmpInst::ICMP_EQ, FieldMallocs[i],
Chris Lattner86395032006-09-30 23:32:09 +00001307 Constant::getNullValue(FieldMallocs[i]->getType()),
1308 "isnull", MI);
1309 if (!RunningOr)
1310 RunningOr = Cond; // First seteq
1311 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001312 RunningOr = BinaryOperator::CreateOr(RunningOr, Cond, "tmp", MI);
Chris Lattner86395032006-09-30 23:32:09 +00001313 }
1314
1315 // Split the basic block at the old malloc.
1316 BasicBlock *OrigBB = MI->getParent();
1317 BasicBlock *ContBB = OrigBB->splitBasicBlock(MI, "malloc_cont");
1318
1319 // Create the block to check the first condition. Put all these blocks at the
1320 // end of the function as they are unlikely to be executed.
Gabor Greif051a9502008-04-06 20:25:17 +00001321 BasicBlock *NullPtrBlock = BasicBlock::Create("malloc_ret_null",
1322 OrigBB->getParent());
Chris Lattner86395032006-09-30 23:32:09 +00001323
1324 // Remove the uncond branch from OrigBB to ContBB, turning it into a cond
1325 // branch on RunningOr.
1326 OrigBB->getTerminator()->eraseFromParent();
Gabor Greif051a9502008-04-06 20:25:17 +00001327 BranchInst::Create(NullPtrBlock, ContBB, RunningOr, OrigBB);
Chris Lattner86395032006-09-30 23:32:09 +00001328
1329 // Within the NullPtrBlock, we need to emit a comparison and branch for each
1330 // pointer, because some may be null while others are not.
1331 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
1332 Value *GVVal = new LoadInst(FieldGlobals[i], "tmp", NullPtrBlock);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001333 Value *Cmp = new ICmpInst(ICmpInst::ICMP_NE, GVVal,
1334 Constant::getNullValue(GVVal->getType()),
1335 "tmp", NullPtrBlock);
Gabor Greif051a9502008-04-06 20:25:17 +00001336 BasicBlock *FreeBlock = BasicBlock::Create("free_it", OrigBB->getParent());
1337 BasicBlock *NextBlock = BasicBlock::Create("next", OrigBB->getParent());
1338 BranchInst::Create(FreeBlock, NextBlock, Cmp, NullPtrBlock);
Chris Lattner86395032006-09-30 23:32:09 +00001339
1340 // Fill in FreeBlock.
1341 new FreeInst(GVVal, FreeBlock);
1342 new StoreInst(Constant::getNullValue(GVVal->getType()), FieldGlobals[i],
1343 FreeBlock);
Gabor Greif051a9502008-04-06 20:25:17 +00001344 BranchInst::Create(NextBlock, FreeBlock);
Chris Lattner86395032006-09-30 23:32:09 +00001345
1346 NullPtrBlock = NextBlock;
1347 }
1348
Gabor Greif051a9502008-04-06 20:25:17 +00001349 BranchInst::Create(ContBB, NullPtrBlock);
Chris Lattner86395032006-09-30 23:32:09 +00001350
1351 // MI is no longer needed, remove it.
1352 MI->eraseFromParent();
1353
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001354 /// InsertedScalarizedLoads - As we process loads, if we can't immediately
1355 /// update all uses of the load, keep track of what scalarized loads are
1356 /// inserted for a given load.
1357 DenseMap<Value*, std::vector<Value*> > InsertedScalarizedValues;
1358 InsertedScalarizedValues[GV] = FieldGlobals;
1359
1360 std::vector<std::pair<PHINode*, unsigned> > PHIsToRewrite;
Chris Lattner86395032006-09-30 23:32:09 +00001361
1362 // Okay, the malloc site is completely handled. All of the uses of GV are now
1363 // loads, and all uses of those loads are simple. Rewrite them to use loads
1364 // of the per-field globals instead.
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001365 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI != E;) {
1366 Instruction *User = cast<Instruction>(*UI++);
1367
1368 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
1369 RewriteUsesOfLoadForHeapSRoA(LI, InsertedScalarizedValues, PHIsToRewrite);
1370 continue;
Chris Lattner39ff1e22007-01-09 23:29:37 +00001371 }
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001372
1373 // Must be a store of null.
1374 StoreInst *SI = cast<StoreInst>(User);
1375 assert(isa<ConstantPointerNull>(SI->getOperand(0)) &&
1376 "Unexpected heap-sra user!");
1377
1378 // Insert a store of null into each global.
1379 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
1380 const PointerType *PT = cast<PointerType>(FieldGlobals[i]->getType());
1381 Constant *Null = Constant::getNullValue(PT->getElementType());
1382 new StoreInst(Null, FieldGlobals[i], SI);
1383 }
1384 // Erase the original store.
1385 SI->eraseFromParent();
Chris Lattner86395032006-09-30 23:32:09 +00001386 }
1387
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001388 // While we have PHIs that are interesting to rewrite, do it.
1389 while (!PHIsToRewrite.empty()) {
1390 PHINode *PN = PHIsToRewrite.back().first;
1391 unsigned FieldNo = PHIsToRewrite.back().second;
1392 PHIsToRewrite.pop_back();
1393 PHINode *FieldPN = cast<PHINode>(InsertedScalarizedValues[PN][FieldNo]);
1394 assert(FieldPN->getNumIncomingValues() == 0 &&"Already processed this phi");
1395
1396 // Add all the incoming values. This can materialize more phis.
1397 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1398 Value *InVal = PN->getIncomingValue(i);
1399 InVal = GetHeapSROAValue(InVal, FieldNo, InsertedScalarizedValues,
1400 PHIsToRewrite);
1401 FieldPN->addIncoming(InVal, PN->getIncomingBlock(i));
1402 }
1403 }
1404
1405 // Drop all inter-phi links and any loads that made it this far.
1406 for (DenseMap<Value*, std::vector<Value*> >::iterator
1407 I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
1408 I != E; ++I) {
1409 if (PHINode *PN = dyn_cast<PHINode>(I->first))
1410 PN->dropAllReferences();
1411 else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
1412 LI->dropAllReferences();
1413 }
1414
1415 // Delete all the phis and loads now that inter-references are dead.
1416 for (DenseMap<Value*, std::vector<Value*> >::iterator
1417 I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
1418 I != E; ++I) {
1419 if (PHINode *PN = dyn_cast<PHINode>(I->first))
1420 PN->eraseFromParent();
1421 else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
1422 LI->eraseFromParent();
1423 }
1424
Chris Lattner86395032006-09-30 23:32:09 +00001425 // The old global is now dead, remove it.
1426 GV->eraseFromParent();
1427
1428 ++NumHeapSRA;
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001429 return cast<GlobalVariable>(FieldGlobals[0]);
Chris Lattner86395032006-09-30 23:32:09 +00001430}
1431
Chris Lattnere61d0a62008-12-15 21:02:25 +00001432/// TryToOptimizeStoreOfMallocToGlobal - This function is called when we see a
1433/// pointer global variable with a single value stored it that is a malloc or
1434/// cast of malloc.
1435static bool TryToOptimizeStoreOfMallocToGlobal(GlobalVariable *GV,
1436 MallocInst *MI,
1437 Module::global_iterator &GVI,
1438 TargetData &TD) {
1439 // If this is a malloc of an abstract type, don't touch it.
1440 if (!MI->getAllocatedType()->isSized())
1441 return false;
1442
1443 // We can't optimize this global unless all uses of it are *known* to be
1444 // of the malloc value, not of the null initializer value (consider a use
1445 // that compares the global's value against zero to see if the malloc has
1446 // been reached). To do this, we check to see if all uses of the global
1447 // would trap if the global were null: this proves that they must all
1448 // happen after the malloc.
1449 if (!AllUsesOfLoadedValueWillTrapIfNull(GV))
1450 return false;
1451
1452 // We can't optimize this if the malloc itself is used in a complex way,
1453 // for example, being stored into multiple globals. This allows the
1454 // malloc to be stored into the specified global, loaded setcc'd, and
1455 // GEP'd. These are all things we could transform to using the global
1456 // for.
1457 {
1458 SmallPtrSet<PHINode*, 8> PHIs;
1459 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(MI, GV, PHIs))
1460 return false;
1461 }
1462
1463
1464 // If we have a global that is only initialized with a fixed size malloc,
1465 // transform the program to use global memory instead of malloc'd memory.
1466 // This eliminates dynamic allocation, avoids an indirection accessing the
1467 // data, and exposes the resultant global to further GlobalOpt.
1468 if (ConstantInt *NElements = dyn_cast<ConstantInt>(MI->getArraySize())) {
1469 // Restrict this transformation to only working on small allocations
1470 // (2048 bytes currently), as we don't want to introduce a 16M global or
1471 // something.
1472 if (NElements->getZExtValue()*
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00001473 TD.getTypePaddedSize(MI->getAllocatedType()) < 2048) {
Chris Lattnere61d0a62008-12-15 21:02:25 +00001474 GVI = OptimizeGlobalAddressOfMalloc(GV, MI);
1475 return true;
1476 }
1477 }
1478
1479 // If the allocation is an array of structures, consider transforming this
1480 // into multiple malloc'd arrays, one for each field. This is basically
1481 // SRoA for malloc'd memory.
Chris Lattner101f44e2008-12-15 21:44:34 +00001482 const Type *AllocTy = MI->getAllocatedType();
1483
1484 // If this is an allocation of a fixed size array of structs, analyze as a
1485 // variable size array. malloc [100 x struct],1 -> malloc struct, 100
1486 if (!MI->isArrayAllocation())
1487 if (const ArrayType *AT = dyn_cast<ArrayType>(AllocTy))
1488 AllocTy = AT->getElementType();
1489
1490 if (const StructType *AllocSTy = dyn_cast<StructType>(AllocTy)) {
Chris Lattnere61d0a62008-12-15 21:02:25 +00001491 // This the structure has an unreasonable number of fields, leave it
1492 // alone.
Chris Lattner101f44e2008-12-15 21:44:34 +00001493 if (AllocSTy->getNumElements() <= 16 && AllocSTy->getNumElements() != 0 &&
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001494 AllGlobalLoadUsesSimpleEnoughForHeapSRA(GV, MI)) {
Chris Lattner101f44e2008-12-15 21:44:34 +00001495
1496 // If this is a fixed size array, transform the Malloc to be an alloc of
1497 // structs. malloc [100 x struct],1 -> malloc struct, 100
1498 if (const ArrayType *AT = dyn_cast<ArrayType>(MI->getAllocatedType())) {
1499 MallocInst *NewMI =
1500 new MallocInst(AllocSTy,
1501 ConstantInt::get(Type::Int32Ty, AT->getNumElements()),
1502 "", MI);
1503 NewMI->takeName(MI);
1504 Value *Cast = new BitCastInst(NewMI, MI->getType(), "tmp", MI);
1505 MI->replaceAllUsesWith(Cast);
1506 MI->eraseFromParent();
1507 MI = NewMI;
1508 }
1509
Chris Lattnere61d0a62008-12-15 21:02:25 +00001510 GVI = PerformHeapAllocSRoA(GV, MI);
1511 return true;
1512 }
1513 }
1514
1515 return false;
1516}
Chris Lattner86395032006-09-30 23:32:09 +00001517
Chris Lattner9b34a612004-10-09 21:48:45 +00001518// OptimizeOnceStoredGlobal - Try to optimize globals based on the knowledge
1519// that only one value (besides its initializer) is ever stored to the global.
Chris Lattner30ba5692004-10-11 05:54:41 +00001520static bool OptimizeOnceStoredGlobal(GlobalVariable *GV, Value *StoredOnceVal,
Chris Lattner7f8897f2006-08-27 22:42:52 +00001521 Module::global_iterator &GVI,
1522 TargetData &TD) {
Chris Lattner344b41c2008-12-15 21:20:32 +00001523 // Ignore no-op GEPs and bitcasts.
1524 StoredOnceVal = StoredOnceVal->stripPointerCasts();
Chris Lattner9b34a612004-10-09 21:48:45 +00001525
Chris Lattner708148e2004-10-10 23:14:11 +00001526 // If we are dealing with a pointer global that is initialized to null and
1527 // only has one (non-null) value stored into it, then we can optimize any
1528 // users of the loaded value (often calls and loads) that would trap if the
1529 // value was null.
Chris Lattner9b34a612004-10-09 21:48:45 +00001530 if (isa<PointerType>(GV->getInitializer()->getType()) &&
1531 GV->getInitializer()->isNullValue()) {
Chris Lattner708148e2004-10-10 23:14:11 +00001532 if (Constant *SOVC = dyn_cast<Constant>(StoredOnceVal)) {
1533 if (GV->getInitializer()->getType() != SOVC->getType())
Reid Spencerd977d862006-12-12 23:36:14 +00001534 SOVC = ConstantExpr::getBitCast(SOVC, GV->getInitializer()->getType());
Misha Brukmanfd939082005-04-21 23:48:37 +00001535
Chris Lattner708148e2004-10-10 23:14:11 +00001536 // Optimize away any trapping uses of the loaded value.
1537 if (OptimizeAwayTrappingUsesOfLoads(GV, SOVC))
Chris Lattner8be80122004-10-10 17:07:12 +00001538 return true;
Chris Lattner30ba5692004-10-11 05:54:41 +00001539 } else if (MallocInst *MI = dyn_cast<MallocInst>(StoredOnceVal)) {
Chris Lattnere61d0a62008-12-15 21:02:25 +00001540 if (TryToOptimizeStoreOfMallocToGlobal(GV, MI, GVI, TD))
1541 return true;
Chris Lattner708148e2004-10-10 23:14:11 +00001542 }
Chris Lattner9b34a612004-10-09 21:48:45 +00001543 }
Chris Lattner30ba5692004-10-11 05:54:41 +00001544
Chris Lattner9b34a612004-10-09 21:48:45 +00001545 return false;
1546}
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001547
Chris Lattner58e44f42008-01-14 01:17:44 +00001548/// TryToShrinkGlobalToBoolean - At this point, we have learned that the only
1549/// two values ever stored into GV are its initializer and OtherVal. See if we
1550/// can shrink the global into a boolean and select between the two values
1551/// whenever it is used. This exposes the values to other scalar optimizations.
1552static bool TryToShrinkGlobalToBoolean(GlobalVariable *GV, Constant *OtherVal) {
1553 const Type *GVElType = GV->getType()->getElementType();
1554
1555 // If GVElType is already i1, it is already shrunk. If the type of the GV is
1556 // an FP value or vector, don't do this optimization because a select between
1557 // them is very expensive and unlikely to lead to later simplification.
1558 if (GVElType == Type::Int1Ty || GVElType->isFloatingPoint() ||
1559 isa<VectorType>(GVElType))
1560 return false;
1561
1562 // Walk the use list of the global seeing if all the uses are load or store.
1563 // If there is anything else, bail out.
1564 for (Value::use_iterator I = GV->use_begin(), E = GV->use_end(); I != E; ++I)
1565 if (!isa<LoadInst>(I) && !isa<StoreInst>(I))
1566 return false;
1567
1568 DOUT << " *** SHRINKING TO BOOL: " << *GV;
1569
Chris Lattner96a86b22004-12-12 05:53:50 +00001570 // Create the new global, initializing it to false.
Reid Spencer4fe16d62007-01-11 18:21:29 +00001571 GlobalVariable *NewGV = new GlobalVariable(Type::Int1Ty, false,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001572 GlobalValue::InternalLinkage, ConstantInt::getFalse(),
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +00001573 GV->getName()+".b",
1574 (Module *)NULL,
1575 GV->isThreadLocal());
Chris Lattner96a86b22004-12-12 05:53:50 +00001576 GV->getParent()->getGlobalList().insert(GV, NewGV);
1577
1578 Constant *InitVal = GV->getInitializer();
Reid Spencer4fe16d62007-01-11 18:21:29 +00001579 assert(InitVal->getType() != Type::Int1Ty && "No reason to shrink to bool!");
Chris Lattner96a86b22004-12-12 05:53:50 +00001580
1581 // If initialized to zero and storing one into the global, we can use a cast
1582 // instead of a select to synthesize the desired value.
1583 bool IsOneZero = false;
1584 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal))
Reid Spencercae57542007-03-02 00:28:52 +00001585 IsOneZero = InitVal->isNullValue() && CI->isOne();
Chris Lattner96a86b22004-12-12 05:53:50 +00001586
1587 while (!GV->use_empty()) {
1588 Instruction *UI = cast<Instruction>(GV->use_back());
1589 if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
1590 // Change the store into a boolean store.
1591 bool StoringOther = SI->getOperand(0) == OtherVal;
1592 // Only do this if we weren't storing a loaded value.
Chris Lattner38c25562004-12-12 19:34:41 +00001593 Value *StoreVal;
Chris Lattner96a86b22004-12-12 05:53:50 +00001594 if (StoringOther || SI->getOperand(0) == InitVal)
Reid Spencer579dca12007-01-12 04:24:46 +00001595 StoreVal = ConstantInt::get(Type::Int1Ty, StoringOther);
Chris Lattner38c25562004-12-12 19:34:41 +00001596 else {
1597 // Otherwise, we are storing a previously loaded copy. To do this,
1598 // change the copy from copying the original value to just copying the
1599 // bool.
1600 Instruction *StoredVal = cast<Instruction>(SI->getOperand(0));
1601
1602 // If we're already replaced the input, StoredVal will be a cast or
1603 // select instruction. If not, it will be a load of the original
1604 // global.
1605 if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
1606 assert(LI->getOperand(0) == GV && "Not a copy!");
1607 // Insert a new load, to preserve the saved value.
1608 StoreVal = new LoadInst(NewGV, LI->getName()+".b", LI);
1609 } else {
1610 assert((isa<CastInst>(StoredVal) || isa<SelectInst>(StoredVal)) &&
1611 "This is not a form that we understand!");
1612 StoreVal = StoredVal->getOperand(0);
1613 assert(isa<LoadInst>(StoreVal) && "Not a load of NewGV!");
1614 }
1615 }
1616 new StoreInst(StoreVal, NewGV, SI);
Chris Lattner58e44f42008-01-14 01:17:44 +00001617 } else {
Chris Lattner96a86b22004-12-12 05:53:50 +00001618 // Change the load into a load of bool then a select.
1619 LoadInst *LI = cast<LoadInst>(UI);
Chris Lattner046800a2007-02-11 01:08:35 +00001620 LoadInst *NLI = new LoadInst(NewGV, LI->getName()+".b", LI);
Chris Lattner96a86b22004-12-12 05:53:50 +00001621 Value *NSI;
1622 if (IsOneZero)
Chris Lattner046800a2007-02-11 01:08:35 +00001623 NSI = new ZExtInst(NLI, LI->getType(), "", LI);
Misha Brukmanfd939082005-04-21 23:48:37 +00001624 else
Gabor Greif051a9502008-04-06 20:25:17 +00001625 NSI = SelectInst::Create(NLI, OtherVal, InitVal, "", LI);
Chris Lattner046800a2007-02-11 01:08:35 +00001626 NSI->takeName(LI);
Chris Lattner96a86b22004-12-12 05:53:50 +00001627 LI->replaceAllUsesWith(NSI);
1628 }
1629 UI->eraseFromParent();
1630 }
1631
1632 GV->eraseFromParent();
Chris Lattner58e44f42008-01-14 01:17:44 +00001633 return true;
Chris Lattner96a86b22004-12-12 05:53:50 +00001634}
1635
1636
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001637/// ProcessInternalGlobal - Analyze the specified global variable and optimize
1638/// it if possible. If we make a change, return true.
Chris Lattner30ba5692004-10-11 05:54:41 +00001639bool GlobalOpt::ProcessInternalGlobal(GlobalVariable *GV,
Chris Lattnere4d5c442005-03-15 04:54:21 +00001640 Module::global_iterator &GVI) {
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00001641 SmallPtrSet<PHINode*, 16> PHIUsers;
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001642 GlobalStatus GS;
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001643 GV->removeDeadConstantUsers();
1644
1645 if (GV->use_empty()) {
Bill Wendling0a81aac2006-11-26 10:02:32 +00001646 DOUT << "GLOBAL DEAD: " << *GV;
Chris Lattner7a7ed022004-10-16 18:09:00 +00001647 GV->eraseFromParent();
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001648 ++NumDeleted;
1649 return true;
1650 }
1651
1652 if (!AnalyzeGlobal(GV, GS, PHIUsers)) {
Chris Lattnercff16732006-09-30 19:40:30 +00001653#if 0
Bill Wendlinge8156192006-12-07 01:30:32 +00001654 cerr << "Global: " << *GV;
1655 cerr << " isLoaded = " << GS.isLoaded << "\n";
1656 cerr << " StoredType = ";
Chris Lattnercff16732006-09-30 19:40:30 +00001657 switch (GS.StoredType) {
Bill Wendlinge8156192006-12-07 01:30:32 +00001658 case GlobalStatus::NotStored: cerr << "NEVER STORED\n"; break;
1659 case GlobalStatus::isInitializerStored: cerr << "INIT STORED\n"; break;
1660 case GlobalStatus::isStoredOnce: cerr << "STORED ONCE\n"; break;
1661 case GlobalStatus::isStored: cerr << "stored\n"; break;
Chris Lattnercff16732006-09-30 19:40:30 +00001662 }
1663 if (GS.StoredType == GlobalStatus::isStoredOnce && GS.StoredOnceValue)
Bill Wendlinge8156192006-12-07 01:30:32 +00001664 cerr << " StoredOnceValue = " << *GS.StoredOnceValue << "\n";
Chris Lattnercff16732006-09-30 19:40:30 +00001665 if (GS.AccessingFunction && !GS.HasMultipleAccessingFunctions)
Bill Wendlinge8156192006-12-07 01:30:32 +00001666 cerr << " AccessingFunction = " << GS.AccessingFunction->getName()
Chris Lattnercff16732006-09-30 19:40:30 +00001667 << "\n";
Bill Wendlinge8156192006-12-07 01:30:32 +00001668 cerr << " HasMultipleAccessingFunctions = "
Chris Lattnercff16732006-09-30 19:40:30 +00001669 << GS.HasMultipleAccessingFunctions << "\n";
Bill Wendlinge8156192006-12-07 01:30:32 +00001670 cerr << " HasNonInstructionUser = " << GS.HasNonInstructionUser<<"\n";
Bill Wendlinge8156192006-12-07 01:30:32 +00001671 cerr << "\n";
Chris Lattnercff16732006-09-30 19:40:30 +00001672#endif
1673
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +00001674 // If this is a first class global and has only one accessing function
1675 // and this function is main (which we know is not recursive we can make
1676 // this global a local variable) we replace the global with a local alloca
1677 // in this function.
1678 //
Dan Gohman399101a2008-05-23 00:17:26 +00001679 // NOTE: It doesn't make sense to promote non single-value types since we
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +00001680 // are just replacing static memory to stack memory.
1681 if (!GS.HasMultipleAccessingFunctions &&
Chris Lattner553ca522005-06-15 21:11:48 +00001682 GS.AccessingFunction && !GS.HasNonInstructionUser &&
Dan Gohman399101a2008-05-23 00:17:26 +00001683 GV->getType()->getElementType()->isSingleValueType() &&
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +00001684 GS.AccessingFunction->getName() == "main" &&
1685 GS.AccessingFunction->hasExternalLinkage()) {
Bill Wendling0a81aac2006-11-26 10:02:32 +00001686 DOUT << "LOCALIZING GLOBAL: " << *GV;
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +00001687 Instruction* FirstI = GS.AccessingFunction->getEntryBlock().begin();
1688 const Type* ElemTy = GV->getType()->getElementType();
Nate Begeman14b05292005-11-05 09:21:28 +00001689 // FIXME: Pass Global's alignment when globals have alignment
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +00001690 AllocaInst* Alloca = new AllocaInst(ElemTy, NULL, GV->getName(), FirstI);
1691 if (!isa<UndefValue>(GV->getInitializer()))
1692 new StoreInst(GV->getInitializer(), Alloca, FirstI);
Misha Brukmanfd939082005-04-21 23:48:37 +00001693
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +00001694 GV->replaceAllUsesWith(Alloca);
1695 GV->eraseFromParent();
1696 ++NumLocalized;
1697 return true;
1698 }
Chris Lattnercff16732006-09-30 19:40:30 +00001699
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001700 // If the global is never loaded (but may be stored to), it is dead.
1701 // Delete it now.
1702 if (!GS.isLoaded) {
Bill Wendling0a81aac2006-11-26 10:02:32 +00001703 DOUT << "GLOBAL NEVER LOADED: " << *GV;
Chris Lattner930f4752004-10-09 03:32:52 +00001704
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001705 // Delete any stores we can find to the global. We may not be able to
1706 // make it completely dead though.
Chris Lattner031955d2004-10-10 16:43:46 +00001707 bool Changed = CleanupConstantGlobalUsers(GV, GV->getInitializer());
Chris Lattner930f4752004-10-09 03:32:52 +00001708
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001709 // If the global is dead now, delete it.
1710 if (GV->use_empty()) {
Chris Lattner7a7ed022004-10-16 18:09:00 +00001711 GV->eraseFromParent();
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001712 ++NumDeleted;
Chris Lattner930f4752004-10-09 03:32:52 +00001713 Changed = true;
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001714 }
Chris Lattner930f4752004-10-09 03:32:52 +00001715 return Changed;
Misha Brukmanfd939082005-04-21 23:48:37 +00001716
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001717 } else if (GS.StoredType <= GlobalStatus::isInitializerStored) {
Bill Wendling0a81aac2006-11-26 10:02:32 +00001718 DOUT << "MARKING CONSTANT: " << *GV;
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001719 GV->setConstant(true);
Misha Brukmanfd939082005-04-21 23:48:37 +00001720
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001721 // Clean up any obviously simplifiable users now.
1722 CleanupConstantGlobalUsers(GV, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +00001723
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001724 // If the global is dead now, just nuke it.
1725 if (GV->use_empty()) {
Bill Wendling0a81aac2006-11-26 10:02:32 +00001726 DOUT << " *** Marking constant allowed us to simplify "
1727 << "all users and delete global!\n";
Chris Lattner7a7ed022004-10-16 18:09:00 +00001728 GV->eraseFromParent();
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001729 ++NumDeleted;
1730 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001731
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001732 ++NumMarked;
1733 return true;
Dan Gohman399101a2008-05-23 00:17:26 +00001734 } else if (!GV->getInitializer()->getType()->isSingleValueType()) {
Chris Lattner998182b2008-04-26 07:40:11 +00001735 if (GlobalVariable *FirstNewGV = SRAGlobal(GV,
1736 getAnalysis<TargetData>())) {
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001737 GVI = FirstNewGV; // Don't skip the newly produced globals!
1738 return true;
1739 }
Chris Lattner9b34a612004-10-09 21:48:45 +00001740 } else if (GS.StoredType == GlobalStatus::isStoredOnce) {
Chris Lattner96a86b22004-12-12 05:53:50 +00001741 // If the initial value for the global was an undef value, and if only
1742 // one other value was stored into it, we can just change the
Duncan Sandsb5024402009-01-13 13:48:44 +00001743 // initializer to be the stored value, then delete all stores to the
Chris Lattner96a86b22004-12-12 05:53:50 +00001744 // global. This allows us to mark it constant.
1745 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
1746 if (isa<UndefValue>(GV->getInitializer())) {
1747 // Change the initial value here.
1748 GV->setInitializer(SOVConstant);
Misha Brukmanfd939082005-04-21 23:48:37 +00001749
Chris Lattner96a86b22004-12-12 05:53:50 +00001750 // Clean up any obviously simplifiable users now.
1751 CleanupConstantGlobalUsers(GV, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +00001752
Chris Lattner96a86b22004-12-12 05:53:50 +00001753 if (GV->use_empty()) {
Bill Wendling0a81aac2006-11-26 10:02:32 +00001754 DOUT << " *** Substituting initializer allowed us to "
1755 << "simplify all users and delete global!\n";
Chris Lattner96a86b22004-12-12 05:53:50 +00001756 GV->eraseFromParent();
1757 ++NumDeleted;
1758 } else {
1759 GVI = GV;
1760 }
1761 ++NumSubstitute;
1762 return true;
Chris Lattner7a7ed022004-10-16 18:09:00 +00001763 }
Chris Lattner7a7ed022004-10-16 18:09:00 +00001764
Chris Lattner9b34a612004-10-09 21:48:45 +00001765 // Try to optimize globals based on the knowledge that only one value
1766 // (besides its initializer) is ever stored to the global.
Chris Lattner30ba5692004-10-11 05:54:41 +00001767 if (OptimizeOnceStoredGlobal(GV, GS.StoredOnceValue, GVI,
1768 getAnalysis<TargetData>()))
Chris Lattner9b34a612004-10-09 21:48:45 +00001769 return true;
Chris Lattner96a86b22004-12-12 05:53:50 +00001770
1771 // Otherwise, if the global was not a boolean, we can shrink it to be a
1772 // boolean.
1773 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
Chris Lattner58e44f42008-01-14 01:17:44 +00001774 if (TryToShrinkGlobalToBoolean(GV, SOVConstant)) {
Chris Lattner96a86b22004-12-12 05:53:50 +00001775 ++NumShrunkToBool;
1776 return true;
1777 }
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001778 }
1779 }
1780 return false;
1781}
1782
Chris Lattnerfb217ad2005-05-08 22:18:06 +00001783/// OnlyCalledDirectly - Return true if the specified function is only called
1784/// directly. In other words, its address is never taken.
1785static bool OnlyCalledDirectly(Function *F) {
1786 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
1787 Instruction *User = dyn_cast<Instruction>(*UI);
1788 if (!User) return false;
1789 if (!isa<CallInst>(User) && !isa<InvokeInst>(User)) return false;
1790
1791 // See if the function address is passed as an argument.
Gabor Greif5e463212008-05-29 01:59:18 +00001792 for (User::op_iterator i = User->op_begin() + 1, e = User->op_end();
Bill Wendlingf9e67ac2008-08-12 23:15:44 +00001793 i != e; ++i)
Gabor Greif5e463212008-05-29 01:59:18 +00001794 if (*i == F) return false;
Chris Lattnerfb217ad2005-05-08 22:18:06 +00001795 }
1796 return true;
1797}
1798
1799/// ChangeCalleesToFastCall - Walk all of the direct calls of the specified
1800/// function, changing them to FastCC.
1801static void ChangeCalleesToFastCall(Function *F) {
1802 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
Duncan Sands548448a2008-02-18 17:32:13 +00001803 CallSite User(cast<Instruction>(*UI));
1804 User.setCallingConv(CallingConv::Fast);
Chris Lattnerfb217ad2005-05-08 22:18:06 +00001805 }
1806}
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001807
Devang Patel05988662008-09-25 21:00:45 +00001808static AttrListPtr StripNest(const AttrListPtr &Attrs) {
Chris Lattner58d74912008-03-12 17:45:29 +00001809 for (unsigned i = 0, e = Attrs.getNumSlots(); i != e; ++i) {
Devang Patel05988662008-09-25 21:00:45 +00001810 if ((Attrs.getSlot(i).Attrs & Attribute::Nest) == 0)
Duncan Sands548448a2008-02-18 17:32:13 +00001811 continue;
1812
Duncan Sands548448a2008-02-18 17:32:13 +00001813 // There can be only one.
Devang Patel05988662008-09-25 21:00:45 +00001814 return Attrs.removeAttr(Attrs.getSlot(i).Index, Attribute::Nest);
Duncan Sands3d5378f2008-02-16 20:56:04 +00001815 }
1816
1817 return Attrs;
1818}
1819
1820static void RemoveNestAttribute(Function *F) {
Devang Patel05988662008-09-25 21:00:45 +00001821 F->setAttributes(StripNest(F->getAttributes()));
Duncan Sands3d5378f2008-02-16 20:56:04 +00001822 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
Duncan Sands548448a2008-02-18 17:32:13 +00001823 CallSite User(cast<Instruction>(*UI));
Devang Patel05988662008-09-25 21:00:45 +00001824 User.setAttributes(StripNest(User.getAttributes()));
Duncan Sands3d5378f2008-02-16 20:56:04 +00001825 }
1826}
1827
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001828bool GlobalOpt::OptimizeFunctions(Module &M) {
1829 bool Changed = false;
1830 // Optimize functions.
1831 for (Module::iterator FI = M.begin(), E = M.end(); FI != E; ) {
1832 Function *F = FI++;
1833 F->removeDeadConstantUsers();
Rafael Espindolabb46f522009-01-15 20:18:42 +00001834 if (F->use_empty() && (F->hasLocalLinkage() ||
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001835 F->hasLinkOnceLinkage())) {
1836 M.getFunctionList().erase(F);
1837 Changed = true;
1838 ++NumFnDeleted;
Rafael Espindolabb46f522009-01-15 20:18:42 +00001839 } else if (F->hasLocalLinkage()) {
Duncan Sands3d5378f2008-02-16 20:56:04 +00001840 if (F->getCallingConv() == CallingConv::C && !F->isVarArg() &&
1841 OnlyCalledDirectly(F)) {
1842 // If this function has C calling conventions, is not a varargs
1843 // function, and is only called directly, promote it to use the Fast
1844 // calling convention.
1845 F->setCallingConv(CallingConv::Fast);
1846 ChangeCalleesToFastCall(F);
1847 ++NumFastCallFns;
1848 Changed = true;
1849 }
1850
Devang Patel05988662008-09-25 21:00:45 +00001851 if (F->getAttributes().hasAttrSomewhere(Attribute::Nest) &&
Duncan Sands3d5378f2008-02-16 20:56:04 +00001852 OnlyCalledDirectly(F)) {
1853 // The function is not used by a trampoline intrinsic, so it is safe
1854 // to remove the 'nest' attribute.
1855 RemoveNestAttribute(F);
1856 ++NumNestRemoved;
1857 Changed = true;
1858 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001859 }
1860 }
1861 return Changed;
1862}
1863
1864bool GlobalOpt::OptimizeGlobalVars(Module &M) {
1865 bool Changed = false;
1866 for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
1867 GVI != E; ) {
1868 GlobalVariable *GV = GVI++;
Rafael Espindolabb46f522009-01-15 20:18:42 +00001869 if (!GV->isConstant() && GV->hasLocalLinkage() &&
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001870 GV->hasInitializer())
1871 Changed |= ProcessInternalGlobal(GV, GVI);
1872 }
1873 return Changed;
1874}
1875
1876/// FindGlobalCtors - Find the llvm.globalctors list, verifying that all
1877/// initializers have an init priority of 65535.
1878GlobalVariable *GlobalOpt::FindGlobalCtors(Module &M) {
Alkis Evlogimenose9c6d362005-10-25 11:18:06 +00001879 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1880 I != E; ++I)
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001881 if (I->getName() == "llvm.global_ctors") {
1882 // Found it, verify it's an array of { int, void()* }.
1883 const ArrayType *ATy =dyn_cast<ArrayType>(I->getType()->getElementType());
1884 if (!ATy) return 0;
1885 const StructType *STy = dyn_cast<StructType>(ATy->getElementType());
1886 if (!STy || STy->getNumElements() != 2 ||
Reid Spencerc5b206b2006-12-31 05:48:39 +00001887 STy->getElementType(0) != Type::Int32Ty) return 0;
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001888 const PointerType *PFTy = dyn_cast<PointerType>(STy->getElementType(1));
1889 if (!PFTy) return 0;
1890 const FunctionType *FTy = dyn_cast<FunctionType>(PFTy->getElementType());
1891 if (!FTy || FTy->getReturnType() != Type::VoidTy || FTy->isVarArg() ||
1892 FTy->getNumParams() != 0)
1893 return 0;
1894
1895 // Verify that the initializer is simple enough for us to handle.
1896 if (!I->hasInitializer()) return 0;
1897 ConstantArray *CA = dyn_cast<ConstantArray>(I->getInitializer());
1898 if (!CA) return 0;
Gabor Greif5e463212008-05-29 01:59:18 +00001899 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i)
1900 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(*i)) {
Chris Lattner7d8e58f2005-09-26 02:19:27 +00001901 if (isa<ConstantPointerNull>(CS->getOperand(1)))
1902 continue;
1903
1904 // Must have a function or null ptr.
1905 if (!isa<Function>(CS->getOperand(1)))
1906 return 0;
1907
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001908 // Init priority must be standard.
1909 ConstantInt *CI = dyn_cast<ConstantInt>(CS->getOperand(0));
Reid Spencerb83eb642006-10-20 07:07:24 +00001910 if (!CI || CI->getZExtValue() != 65535)
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001911 return 0;
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001912 } else {
1913 return 0;
1914 }
1915
1916 return I;
1917 }
1918 return 0;
1919}
1920
Chris Lattnerdb973e62005-09-26 02:31:18 +00001921/// ParseGlobalCtors - Given a llvm.global_ctors list that we can understand,
1922/// return a list of the functions and null terminator as a vector.
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001923static std::vector<Function*> ParseGlobalCtors(GlobalVariable *GV) {
1924 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
1925 std::vector<Function*> Result;
1926 Result.reserve(CA->getNumOperands());
Gabor Greif5e463212008-05-29 01:59:18 +00001927 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i) {
1928 ConstantStruct *CS = cast<ConstantStruct>(*i);
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001929 Result.push_back(dyn_cast<Function>(CS->getOperand(1)));
1930 }
1931 return Result;
1932}
1933
Chris Lattnerdb973e62005-09-26 02:31:18 +00001934/// InstallGlobalCtors - Given a specified llvm.global_ctors list, install the
1935/// specified array, returning the new global to use.
1936static GlobalVariable *InstallGlobalCtors(GlobalVariable *GCL,
1937 const std::vector<Function*> &Ctors) {
1938 // If we made a change, reassemble the initializer list.
1939 std::vector<Constant*> CSVals;
Reid Spencerc5b206b2006-12-31 05:48:39 +00001940 CSVals.push_back(ConstantInt::get(Type::Int32Ty, 65535));
Chris Lattnerdb973e62005-09-26 02:31:18 +00001941 CSVals.push_back(0);
1942
1943 // Create the new init list.
1944 std::vector<Constant*> CAList;
1945 for (unsigned i = 0, e = Ctors.size(); i != e; ++i) {
Chris Lattner79c11012005-09-26 04:44:35 +00001946 if (Ctors[i]) {
Chris Lattnerdb973e62005-09-26 02:31:18 +00001947 CSVals[1] = Ctors[i];
Chris Lattner79c11012005-09-26 04:44:35 +00001948 } else {
Chris Lattnerdb973e62005-09-26 02:31:18 +00001949 const Type *FTy = FunctionType::get(Type::VoidTy,
1950 std::vector<const Type*>(), false);
Christopher Lamb43ad6b32007-12-17 01:12:55 +00001951 const PointerType *PFTy = PointerType::getUnqual(FTy);
Chris Lattnerdb973e62005-09-26 02:31:18 +00001952 CSVals[1] = Constant::getNullValue(PFTy);
Reid Spencerc5b206b2006-12-31 05:48:39 +00001953 CSVals[0] = ConstantInt::get(Type::Int32Ty, 2147483647);
Chris Lattnerdb973e62005-09-26 02:31:18 +00001954 }
1955 CAList.push_back(ConstantStruct::get(CSVals));
1956 }
1957
1958 // Create the array initializer.
1959 const Type *StructTy =
1960 cast<ArrayType>(GCL->getType()->getElementType())->getElementType();
1961 Constant *CA = ConstantArray::get(ArrayType::get(StructTy, CAList.size()),
1962 CAList);
1963
1964 // If we didn't change the number of elements, don't create a new GV.
1965 if (CA->getType() == GCL->getInitializer()->getType()) {
1966 GCL->setInitializer(CA);
1967 return GCL;
1968 }
1969
1970 // Create the new global and insert it next to the existing list.
1971 GlobalVariable *NGV = new GlobalVariable(CA->getType(), GCL->isConstant(),
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +00001972 GCL->getLinkage(), CA, "",
1973 (Module *)NULL,
1974 GCL->isThreadLocal());
Chris Lattnerdb973e62005-09-26 02:31:18 +00001975 GCL->getParent()->getGlobalList().insert(GCL, NGV);
Chris Lattner046800a2007-02-11 01:08:35 +00001976 NGV->takeName(GCL);
Chris Lattnerdb973e62005-09-26 02:31:18 +00001977
1978 // Nuke the old list, replacing any uses with the new one.
1979 if (!GCL->use_empty()) {
1980 Constant *V = NGV;
1981 if (V->getType() != GCL->getType())
Reid Spencerd977d862006-12-12 23:36:14 +00001982 V = ConstantExpr::getBitCast(V, GCL->getType());
Chris Lattnerdb973e62005-09-26 02:31:18 +00001983 GCL->replaceAllUsesWith(V);
1984 }
1985 GCL->eraseFromParent();
1986
1987 if (Ctors.size())
1988 return NGV;
1989 else
1990 return 0;
1991}
Chris Lattner79c11012005-09-26 04:44:35 +00001992
1993
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00001994static Constant *getVal(DenseMap<Value*, Constant*> &ComputedValues,
Chris Lattner79c11012005-09-26 04:44:35 +00001995 Value *V) {
1996 if (Constant *CV = dyn_cast<Constant>(V)) return CV;
1997 Constant *R = ComputedValues[V];
1998 assert(R && "Reference to an uncomputed value!");
1999 return R;
2000}
2001
2002/// isSimpleEnoughPointerToCommit - Return true if this constant is simple
2003/// enough for us to understand. In particular, if it is a cast of something,
2004/// we punt. We basically just support direct accesses to globals and GEP's of
2005/// globals. This should be kept up to date with CommitValueTo.
2006static bool isSimpleEnoughPointerToCommit(Constant *C) {
Chris Lattner231308c2005-09-27 04:50:03 +00002007 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
Rafael Espindolabb46f522009-01-15 20:18:42 +00002008 if (!GV->hasExternalLinkage() && !GV->hasLocalLinkage())
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00002009 return false; // do not allow weak/linkonce/dllimport/dllexport linkage.
Reid Spencer5cbf9852007-01-30 20:08:39 +00002010 return !GV->isDeclaration(); // reject external globals.
Chris Lattner231308c2005-09-27 04:50:03 +00002011 }
Chris Lattner798b4d52005-09-26 06:52:44 +00002012 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
2013 // Handle a constantexpr gep.
2014 if (CE->getOpcode() == Instruction::GetElementPtr &&
2015 isa<GlobalVariable>(CE->getOperand(0))) {
2016 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
Rafael Espindolabb46f522009-01-15 20:18:42 +00002017 if (!GV->hasExternalLinkage() && !GV->hasLocalLinkage())
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00002018 return false; // do not allow weak/linkonce/dllimport/dllexport linkage.
Chris Lattner798b4d52005-09-26 06:52:44 +00002019 return GV->hasInitializer() &&
2020 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
2021 }
Chris Lattner79c11012005-09-26 04:44:35 +00002022 return false;
2023}
2024
Chris Lattner798b4d52005-09-26 06:52:44 +00002025/// EvaluateStoreInto - Evaluate a piece of a constantexpr store into a global
2026/// initializer. This returns 'Init' modified to reflect 'Val' stored into it.
2027/// At this point, the GEP operands of Addr [0, OpNo) have been stepped into.
2028static Constant *EvaluateStoreInto(Constant *Init, Constant *Val,
2029 ConstantExpr *Addr, unsigned OpNo) {
2030 // Base case of the recursion.
2031 if (OpNo == Addr->getNumOperands()) {
2032 assert(Val->getType() == Init->getType() && "Type mismatch!");
2033 return Val;
2034 }
2035
2036 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
2037 std::vector<Constant*> Elts;
2038
2039 // Break up the constant into its elements.
2040 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
Gabor Greif5e463212008-05-29 01:59:18 +00002041 for (User::op_iterator i = CS->op_begin(), e = CS->op_end(); i != e; ++i)
2042 Elts.push_back(cast<Constant>(*i));
Chris Lattner798b4d52005-09-26 06:52:44 +00002043 } else if (isa<ConstantAggregateZero>(Init)) {
2044 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
2045 Elts.push_back(Constant::getNullValue(STy->getElementType(i)));
2046 } else if (isa<UndefValue>(Init)) {
2047 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
2048 Elts.push_back(UndefValue::get(STy->getElementType(i)));
2049 } else {
2050 assert(0 && "This code is out of sync with "
2051 " ConstantFoldLoadThroughGEPConstantExpr");
2052 }
2053
2054 // Replace the element that we are supposed to.
Reid Spencerb83eb642006-10-20 07:07:24 +00002055 ConstantInt *CU = cast<ConstantInt>(Addr->getOperand(OpNo));
2056 unsigned Idx = CU->getZExtValue();
2057 assert(Idx < STy->getNumElements() && "Struct index out of range!");
Chris Lattner798b4d52005-09-26 06:52:44 +00002058 Elts[Idx] = EvaluateStoreInto(Elts[Idx], Val, Addr, OpNo+1);
2059
2060 // Return the modified struct.
Chris Lattnerf0a9aab2007-06-04 22:23:42 +00002061 return ConstantStruct::get(&Elts[0], Elts.size(), STy->isPacked());
Chris Lattner798b4d52005-09-26 06:52:44 +00002062 } else {
2063 ConstantInt *CI = cast<ConstantInt>(Addr->getOperand(OpNo));
2064 const ArrayType *ATy = cast<ArrayType>(Init->getType());
2065
2066 // Break up the array into elements.
2067 std::vector<Constant*> Elts;
2068 if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
Gabor Greif5e463212008-05-29 01:59:18 +00002069 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i)
2070 Elts.push_back(cast<Constant>(*i));
Chris Lattner798b4d52005-09-26 06:52:44 +00002071 } else if (isa<ConstantAggregateZero>(Init)) {
2072 Constant *Elt = Constant::getNullValue(ATy->getElementType());
2073 Elts.assign(ATy->getNumElements(), Elt);
2074 } else if (isa<UndefValue>(Init)) {
2075 Constant *Elt = UndefValue::get(ATy->getElementType());
2076 Elts.assign(ATy->getNumElements(), Elt);
2077 } else {
2078 assert(0 && "This code is out of sync with "
2079 " ConstantFoldLoadThroughGEPConstantExpr");
2080 }
2081
Reid Spencerb83eb642006-10-20 07:07:24 +00002082 assert(CI->getZExtValue() < ATy->getNumElements());
2083 Elts[CI->getZExtValue()] =
2084 EvaluateStoreInto(Elts[CI->getZExtValue()], Val, Addr, OpNo+1);
Chris Lattner798b4d52005-09-26 06:52:44 +00002085 return ConstantArray::get(ATy, Elts);
2086 }
2087}
2088
Chris Lattner79c11012005-09-26 04:44:35 +00002089/// CommitValueTo - We have decided that Addr (which satisfies the predicate
2090/// isSimpleEnoughPointerToCommit) should get Val as its value. Make it happen.
2091static void CommitValueTo(Constant *Val, Constant *Addr) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002092 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Addr)) {
2093 assert(GV->hasInitializer());
2094 GV->setInitializer(Val);
2095 return;
2096 }
2097
2098 ConstantExpr *CE = cast<ConstantExpr>(Addr);
2099 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
2100
2101 Constant *Init = GV->getInitializer();
2102 Init = EvaluateStoreInto(Init, Val, CE, 2);
2103 GV->setInitializer(Init);
Chris Lattner79c11012005-09-26 04:44:35 +00002104}
2105
Chris Lattner562a0552005-09-26 05:16:34 +00002106/// ComputeLoadResult - Return the value that would be computed by a load from
2107/// P after the stores reflected by 'memory' have been performed. If we can't
2108/// decide, return null.
Chris Lattner04de1cf2005-09-26 05:15:37 +00002109static Constant *ComputeLoadResult(Constant *P,
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002110 const DenseMap<Constant*, Constant*> &Memory) {
Chris Lattner04de1cf2005-09-26 05:15:37 +00002111 // If this memory location has been recently stored, use the stored value: it
2112 // is the most up-to-date.
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002113 DenseMap<Constant*, Constant*>::const_iterator I = Memory.find(P);
Chris Lattner04de1cf2005-09-26 05:15:37 +00002114 if (I != Memory.end()) return I->second;
2115
2116 // Access it.
2117 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(P)) {
2118 if (GV->hasInitializer())
2119 return GV->getInitializer();
2120 return 0;
Chris Lattner04de1cf2005-09-26 05:15:37 +00002121 }
Chris Lattner798b4d52005-09-26 06:52:44 +00002122
2123 // Handle a constantexpr getelementptr.
2124 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(P))
2125 if (CE->getOpcode() == Instruction::GetElementPtr &&
2126 isa<GlobalVariable>(CE->getOperand(0))) {
2127 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
2128 if (GV->hasInitializer())
2129 return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
2130 }
2131
2132 return 0; // don't know how to evaluate.
Chris Lattner04de1cf2005-09-26 05:15:37 +00002133}
2134
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002135/// EvaluateFunction - Evaluate a call to function F, returning true if
2136/// successful, false if we can't evaluate it. ActualArgs contains the formal
2137/// arguments for the function.
Chris Lattnercd271422005-09-27 04:45:34 +00002138static bool EvaluateFunction(Function *F, Constant *&RetVal,
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002139 const std::vector<Constant*> &ActualArgs,
2140 std::vector<Function*> &CallStack,
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002141 DenseMap<Constant*, Constant*> &MutatedMemory,
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002142 std::vector<GlobalVariable*> &AllocaTmps) {
Chris Lattnercd271422005-09-27 04:45:34 +00002143 // Check to see if this function is already executing (recursion). If so,
2144 // bail out. TODO: we might want to accept limited recursion.
2145 if (std::find(CallStack.begin(), CallStack.end(), F) != CallStack.end())
2146 return false;
2147
2148 CallStack.push_back(F);
2149
Chris Lattner79c11012005-09-26 04:44:35 +00002150 /// Values - As we compute SSA register values, we store their contents here.
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002151 DenseMap<Value*, Constant*> Values;
Chris Lattnercd271422005-09-27 04:45:34 +00002152
2153 // Initialize arguments to the incoming values specified.
2154 unsigned ArgNo = 0;
2155 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); AI != E;
2156 ++AI, ++ArgNo)
2157 Values[AI] = ActualArgs[ArgNo];
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002158
Chris Lattnercdf98be2005-09-26 04:57:38 +00002159 /// ExecutedBlocks - We only handle non-looping, non-recursive code. As such,
2160 /// we can only evaluate any one basic block at most once. This set keeps
2161 /// track of what we have executed so we can detect recursive cases etc.
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002162 SmallPtrSet<BasicBlock*, 32> ExecutedBlocks;
Chris Lattnera22fdb02005-09-26 17:07:09 +00002163
Chris Lattner79c11012005-09-26 04:44:35 +00002164 // CurInst - The current instruction we're evaluating.
2165 BasicBlock::iterator CurInst = F->begin()->begin();
2166
2167 // This is the main evaluation loop.
2168 while (1) {
2169 Constant *InstResult = 0;
2170
2171 if (StoreInst *SI = dyn_cast<StoreInst>(CurInst)) {
Chris Lattnercd271422005-09-27 04:45:34 +00002172 if (SI->isVolatile()) return false; // no volatile accesses.
Chris Lattner79c11012005-09-26 04:44:35 +00002173 Constant *Ptr = getVal(Values, SI->getOperand(1));
2174 if (!isSimpleEnoughPointerToCommit(Ptr))
2175 // If this is too complex for us to commit, reject it.
Chris Lattnercd271422005-09-27 04:45:34 +00002176 return false;
Chris Lattner79c11012005-09-26 04:44:35 +00002177 Constant *Val = getVal(Values, SI->getOperand(0));
2178 MutatedMemory[Ptr] = Val;
2179 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CurInst)) {
2180 InstResult = ConstantExpr::get(BO->getOpcode(),
2181 getVal(Values, BO->getOperand(0)),
2182 getVal(Values, BO->getOperand(1)));
Reid Spencere4d87aa2006-12-23 06:05:41 +00002183 } else if (CmpInst *CI = dyn_cast<CmpInst>(CurInst)) {
2184 InstResult = ConstantExpr::getCompare(CI->getPredicate(),
2185 getVal(Values, CI->getOperand(0)),
2186 getVal(Values, CI->getOperand(1)));
Chris Lattner79c11012005-09-26 04:44:35 +00002187 } else if (CastInst *CI = dyn_cast<CastInst>(CurInst)) {
Chris Lattner9a989f02006-11-30 17:26:08 +00002188 InstResult = ConstantExpr::getCast(CI->getOpcode(),
2189 getVal(Values, CI->getOperand(0)),
Chris Lattner79c11012005-09-26 04:44:35 +00002190 CI->getType());
2191 } else if (SelectInst *SI = dyn_cast<SelectInst>(CurInst)) {
2192 InstResult = ConstantExpr::getSelect(getVal(Values, SI->getOperand(0)),
2193 getVal(Values, SI->getOperand(1)),
2194 getVal(Values, SI->getOperand(2)));
Chris Lattner04de1cf2005-09-26 05:15:37 +00002195 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurInst)) {
2196 Constant *P = getVal(Values, GEP->getOperand(0));
Chris Lattner55eb1c42007-01-31 04:40:53 +00002197 SmallVector<Constant*, 8> GEPOps;
Gabor Greif5e463212008-05-29 01:59:18 +00002198 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end();
2199 i != e; ++i)
2200 GEPOps.push_back(getVal(Values, *i));
Chris Lattner55eb1c42007-01-31 04:40:53 +00002201 InstResult = ConstantExpr::getGetElementPtr(P, &GEPOps[0], GEPOps.size());
Chris Lattner04de1cf2005-09-26 05:15:37 +00002202 } else if (LoadInst *LI = dyn_cast<LoadInst>(CurInst)) {
Chris Lattnercd271422005-09-27 04:45:34 +00002203 if (LI->isVolatile()) return false; // no volatile accesses.
Chris Lattner04de1cf2005-09-26 05:15:37 +00002204 InstResult = ComputeLoadResult(getVal(Values, LI->getOperand(0)),
2205 MutatedMemory);
Chris Lattnercd271422005-09-27 04:45:34 +00002206 if (InstResult == 0) return false; // Could not evaluate load.
Chris Lattnera22fdb02005-09-26 17:07:09 +00002207 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(CurInst)) {
Chris Lattnercd271422005-09-27 04:45:34 +00002208 if (AI->isArrayAllocation()) return false; // Cannot handle array allocs.
Chris Lattnera22fdb02005-09-26 17:07:09 +00002209 const Type *Ty = AI->getType()->getElementType();
2210 AllocaTmps.push_back(new GlobalVariable(Ty, false,
2211 GlobalValue::InternalLinkage,
2212 UndefValue::get(Ty),
2213 AI->getName()));
Chris Lattnercd271422005-09-27 04:45:34 +00002214 InstResult = AllocaTmps.back();
2215 } else if (CallInst *CI = dyn_cast<CallInst>(CurInst)) {
Chris Lattner7cd580f2006-07-07 21:37:01 +00002216 // Cannot handle inline asm.
2217 if (isa<InlineAsm>(CI->getOperand(0))) return false;
2218
Chris Lattnercd271422005-09-27 04:45:34 +00002219 // Resolve function pointers.
2220 Function *Callee = dyn_cast<Function>(getVal(Values, CI->getOperand(0)));
2221 if (!Callee) return false; // Cannot resolve.
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002222
Chris Lattnercd271422005-09-27 04:45:34 +00002223 std::vector<Constant*> Formals;
Gabor Greif5e463212008-05-29 01:59:18 +00002224 for (User::op_iterator i = CI->op_begin() + 1, e = CI->op_end();
2225 i != e; ++i)
2226 Formals.push_back(getVal(Values, *i));
Chris Lattnercd271422005-09-27 04:45:34 +00002227
Reid Spencer5cbf9852007-01-30 20:08:39 +00002228 if (Callee->isDeclaration()) {
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002229 // If this is a function we can constant fold, do it.
Chris Lattner6c1f5652007-01-30 23:14:52 +00002230 if (Constant *C = ConstantFoldCall(Callee, &Formals[0],
2231 Formals.size())) {
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002232 InstResult = C;
2233 } else {
2234 return false;
2235 }
2236 } else {
2237 if (Callee->getFunctionType()->isVarArg())
2238 return false;
2239
2240 Constant *RetVal;
2241
2242 // Execute the call, if successful, use the return value.
2243 if (!EvaluateFunction(Callee, RetVal, Formals, CallStack,
2244 MutatedMemory, AllocaTmps))
2245 return false;
2246 InstResult = RetVal;
2247 }
Reid Spencer3ed469c2006-11-02 20:25:50 +00002248 } else if (isa<TerminatorInst>(CurInst)) {
Chris Lattnercdf98be2005-09-26 04:57:38 +00002249 BasicBlock *NewBB = 0;
2250 if (BranchInst *BI = dyn_cast<BranchInst>(CurInst)) {
2251 if (BI->isUnconditional()) {
2252 NewBB = BI->getSuccessor(0);
2253 } else {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002254 ConstantInt *Cond =
2255 dyn_cast<ConstantInt>(getVal(Values, BI->getCondition()));
Chris Lattner97d1fad2007-01-12 18:30:11 +00002256 if (!Cond) return false; // Cannot determine.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002257
Reid Spencer579dca12007-01-12 04:24:46 +00002258 NewBB = BI->getSuccessor(!Cond->getZExtValue());
Chris Lattnercdf98be2005-09-26 04:57:38 +00002259 }
2260 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(CurInst)) {
2261 ConstantInt *Val =
2262 dyn_cast<ConstantInt>(getVal(Values, SI->getCondition()));
Chris Lattnercd271422005-09-27 04:45:34 +00002263 if (!Val) return false; // Cannot determine.
Chris Lattnercdf98be2005-09-26 04:57:38 +00002264 NewBB = SI->getSuccessor(SI->findCaseValue(Val));
2265 } else if (ReturnInst *RI = dyn_cast<ReturnInst>(CurInst)) {
Chris Lattnercd271422005-09-27 04:45:34 +00002266 if (RI->getNumOperands())
2267 RetVal = getVal(Values, RI->getOperand(0));
2268
2269 CallStack.pop_back(); // return from fn.
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002270 return true; // We succeeded at evaluating this ctor!
Chris Lattnercdf98be2005-09-26 04:57:38 +00002271 } else {
Chris Lattnercd271422005-09-27 04:45:34 +00002272 // invoke, unwind, unreachable.
2273 return false; // Cannot handle this terminator.
Chris Lattnercdf98be2005-09-26 04:57:38 +00002274 }
2275
2276 // Okay, we succeeded in evaluating this control flow. See if we have
Chris Lattnercd271422005-09-27 04:45:34 +00002277 // executed the new block before. If so, we have a looping function,
2278 // which we cannot evaluate in reasonable time.
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002279 if (!ExecutedBlocks.insert(NewBB))
Chris Lattnercd271422005-09-27 04:45:34 +00002280 return false; // looped!
Chris Lattnercdf98be2005-09-26 04:57:38 +00002281
2282 // Okay, we have never been in this block before. Check to see if there
2283 // are any PHI nodes. If so, evaluate them with information about where
2284 // we came from.
2285 BasicBlock *OldBB = CurInst->getParent();
2286 CurInst = NewBB->begin();
2287 PHINode *PN;
2288 for (; (PN = dyn_cast<PHINode>(CurInst)); ++CurInst)
2289 Values[PN] = getVal(Values, PN->getIncomingValueForBlock(OldBB));
2290
2291 // Do NOT increment CurInst. We know that the terminator had no value.
2292 continue;
Chris Lattner79c11012005-09-26 04:44:35 +00002293 } else {
Chris Lattner79c11012005-09-26 04:44:35 +00002294 // Did not know how to evaluate this!
Chris Lattnercd271422005-09-27 04:45:34 +00002295 return false;
Chris Lattner79c11012005-09-26 04:44:35 +00002296 }
2297
2298 if (!CurInst->use_empty())
2299 Values[CurInst] = InstResult;
2300
2301 // Advance program counter.
2302 ++CurInst;
2303 }
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002304}
2305
2306/// EvaluateStaticConstructor - Evaluate static constructors in the function, if
2307/// we can. Return true if we can, false otherwise.
2308static bool EvaluateStaticConstructor(Function *F) {
2309 /// MutatedMemory - For each store we execute, we update this map. Loads
2310 /// check this to get the most up-to-date value. If evaluation is successful,
2311 /// this state is committed to the process.
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002312 DenseMap<Constant*, Constant*> MutatedMemory;
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002313
2314 /// AllocaTmps - To 'execute' an alloca, we create a temporary global variable
2315 /// to represent its body. This vector is needed so we can delete the
2316 /// temporary globals when we are done.
2317 std::vector<GlobalVariable*> AllocaTmps;
2318
2319 /// CallStack - This is used to detect recursion. In pathological situations
2320 /// we could hit exponential behavior, but at least there is nothing
2321 /// unbounded.
2322 std::vector<Function*> CallStack;
2323
2324 // Call the function.
Chris Lattnercd271422005-09-27 04:45:34 +00002325 Constant *RetValDummy;
2326 bool EvalSuccess = EvaluateFunction(F, RetValDummy, std::vector<Constant*>(),
2327 CallStack, MutatedMemory, AllocaTmps);
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002328 if (EvalSuccess) {
Chris Lattnera22fdb02005-09-26 17:07:09 +00002329 // We succeeded at evaluation: commit the result.
Bill Wendling0a81aac2006-11-26 10:02:32 +00002330 DOUT << "FULLY EVALUATED GLOBAL CTOR FUNCTION '"
2331 << F->getName() << "' to " << MutatedMemory.size()
2332 << " stores.\n";
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002333 for (DenseMap<Constant*, Constant*>::iterator I = MutatedMemory.begin(),
Chris Lattnera22fdb02005-09-26 17:07:09 +00002334 E = MutatedMemory.end(); I != E; ++I)
2335 CommitValueTo(I->second, I->first);
2336 }
Chris Lattner79c11012005-09-26 04:44:35 +00002337
Chris Lattnera22fdb02005-09-26 17:07:09 +00002338 // At this point, we are done interpreting. If we created any 'alloca'
2339 // temporaries, release them now.
2340 while (!AllocaTmps.empty()) {
2341 GlobalVariable *Tmp = AllocaTmps.back();
2342 AllocaTmps.pop_back();
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002343
Chris Lattnera22fdb02005-09-26 17:07:09 +00002344 // If there are still users of the alloca, the program is doing something
2345 // silly, e.g. storing the address of the alloca somewhere and using it
2346 // later. Since this is undefined, we'll just make it be null.
2347 if (!Tmp->use_empty())
2348 Tmp->replaceAllUsesWith(Constant::getNullValue(Tmp->getType()));
2349 delete Tmp;
2350 }
Chris Lattneraae4a1c2005-09-26 07:34:35 +00002351
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002352 return EvalSuccess;
Chris Lattner79c11012005-09-26 04:44:35 +00002353}
2354
Chris Lattnerdb973e62005-09-26 02:31:18 +00002355
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002356
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002357/// OptimizeGlobalCtorsList - Simplify and evaluation global ctors if possible.
2358/// Return true if anything changed.
2359bool GlobalOpt::OptimizeGlobalCtorsList(GlobalVariable *&GCL) {
2360 std::vector<Function*> Ctors = ParseGlobalCtors(GCL);
2361 bool MadeChange = false;
2362 if (Ctors.empty()) return false;
2363
2364 // Loop over global ctors, optimizing them when we can.
2365 for (unsigned i = 0; i != Ctors.size(); ++i) {
2366 Function *F = Ctors[i];
2367 // Found a null terminator in the middle of the list, prune off the rest of
2368 // the list.
Chris Lattner7d8e58f2005-09-26 02:19:27 +00002369 if (F == 0) {
2370 if (i != Ctors.size()-1) {
2371 Ctors.resize(i+1);
2372 MadeChange = true;
2373 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002374 break;
2375 }
2376
Chris Lattner79c11012005-09-26 04:44:35 +00002377 // We cannot simplify external ctor functions.
2378 if (F->empty()) continue;
2379
2380 // If we can evaluate the ctor at compile time, do.
2381 if (EvaluateStaticConstructor(F)) {
2382 Ctors.erase(Ctors.begin()+i);
2383 MadeChange = true;
2384 --i;
2385 ++NumCtorsEvaluated;
2386 continue;
2387 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002388 }
2389
2390 if (!MadeChange) return false;
2391
Chris Lattnerdb973e62005-09-26 02:31:18 +00002392 GCL = InstallGlobalCtors(GCL, Ctors);
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002393 return true;
2394}
2395
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002396bool GlobalOpt::ResolveAliases(Module &M) {
2397 bool Changed = false;
2398
Duncan Sands177d84e2009-01-07 20:01:06 +00002399 for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end();
Duncan Sands4782b302009-02-15 09:56:08 +00002400 I != E;) {
2401 Module::alias_iterator J = I++;
2402 // If the aliasee may change at link time, nothing can be done - bail out.
2403 if (J->mayBeOverridden())
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002404 continue;
2405
Duncan Sands4782b302009-02-15 09:56:08 +00002406 Constant *Aliasee = J->getAliasee();
2407 GlobalValue *Target = cast<GlobalValue>(Aliasee->stripPointerCasts());
Duncan Sands95c5d0f2009-02-18 17:55:38 +00002408 Target->removeDeadConstantUsers();
Duncan Sands4782b302009-02-15 09:56:08 +00002409 bool hasOneUse = Target->hasOneUse() && Aliasee->hasOneUse();
2410
2411 // Make all users of the alias use the aliasee instead.
2412 if (!J->use_empty()) {
2413 J->replaceAllUsesWith(Aliasee);
2414 ++NumAliasesResolved;
2415 Changed = true;
2416 }
2417
2418 // If the aliasee has internal linkage, give it the name and linkage
2419 // of the alias, and delete the alias. This turns:
2420 // define internal ... @f(...)
2421 // @a = alias ... @f
2422 // into:
2423 // define ... @a(...)
Duncan Sands7ae5b9e2009-02-17 17:50:04 +00002424 if (!Target->hasLocalLinkage())
Duncan Sands4782b302009-02-15 09:56:08 +00002425 continue;
2426
2427 // The transform is only useful if the alias does not have internal linkage.
Duncan Sands7ae5b9e2009-02-17 17:50:04 +00002428 if (J->hasLocalLinkage())
Duncan Sands4782b302009-02-15 09:56:08 +00002429 continue;
2430
Duncan Sandsa37d1192009-02-15 11:54:49 +00002431 // Do not perform the transform if multiple aliases potentially target the
2432 // aliasee. This check also ensures that it is safe to replace the section
2433 // and other attributes of the aliasee with those of the alias.
Duncan Sands4782b302009-02-15 09:56:08 +00002434 if (!hasOneUse)
2435 continue;
2436
Duncan Sandsa37d1192009-02-15 11:54:49 +00002437 // Give the aliasee the name, linkage and other attributes of the alias.
Duncan Sands4782b302009-02-15 09:56:08 +00002438 Target->takeName(J);
2439 Target->setLinkage(J->getLinkage());
Duncan Sandsa37d1192009-02-15 11:54:49 +00002440 Target->GlobalValue::copyAttributesFrom(J);
Duncan Sands4782b302009-02-15 09:56:08 +00002441
2442 // Delete the alias.
2443 M.getAliasList().erase(J);
2444 ++NumAliasesRemoved;
2445 Changed = true;
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002446 }
2447
2448 return Changed;
2449}
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002450
Chris Lattner7a90b682004-10-07 04:16:33 +00002451bool GlobalOpt::runOnModule(Module &M) {
Chris Lattner079236d2004-02-25 21:34:36 +00002452 bool Changed = false;
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002453
2454 // Try to find the llvm.globalctors list.
2455 GlobalVariable *GlobalCtors = FindGlobalCtors(M);
Chris Lattner7a90b682004-10-07 04:16:33 +00002456
Chris Lattner7a90b682004-10-07 04:16:33 +00002457 bool LocalChange = true;
2458 while (LocalChange) {
2459 LocalChange = false;
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002460
2461 // Delete functions that are trivially dead, ccc -> fastcc
2462 LocalChange |= OptimizeFunctions(M);
2463
2464 // Optimize global_ctors list.
2465 if (GlobalCtors)
2466 LocalChange |= OptimizeGlobalCtorsList(GlobalCtors);
2467
2468 // Optimize non-address-taken globals.
2469 LocalChange |= OptimizeGlobalVars(M);
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002470
2471 // Resolve aliases, when possible.
2472 LocalChange |= ResolveAliases(M);
2473 Changed |= LocalChange;
Chris Lattner7a90b682004-10-07 04:16:33 +00002474 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002475
2476 // TODO: Move all global ctors functions to the end of the module for code
2477 // layout.
2478
Chris Lattner079236d2004-02-25 21:34:36 +00002479 return Changed;
2480}