blob: 28cd902472dcf3f70ffdbee3d5eea038cc01fabe [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 Patel7f6179d2009-03-04 01:22:23 +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) {
146 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
147 if (GV->hasLocalLinkage() && GV->use_empty()) {
148 if (DeadGVs)
149 DeadGVs->insert(GV);
150 return true;
151 }
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000152 if (isa<GlobalValue>(C)) return false;
153
154 for (Value::use_iterator UI = C->use_begin(), E = C->use_end(); UI != E; ++UI)
155 if (Constant *CU = dyn_cast<Constant>(*UI)) {
Devang Patel7f6179d2009-03-04 01:22:23 +0000156 if (!ConstantIsDead(CU, DeadGVs)) return false;
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000157 } else
158 return false;
159 return true;
160}
161
162
Chris Lattner7a90b682004-10-07 04:16:33 +0000163/// AnalyzeGlobal - Look at all uses of the global and fill in the GlobalStatus
164/// structure. If the global has its address taken, return true to indicate we
165/// can't do anything with it.
Chris Lattner079236d2004-02-25 21:34:36 +0000166///
Chris Lattner7a90b682004-10-07 04:16:33 +0000167static bool AnalyzeGlobal(Value *V, GlobalStatus &GS,
Chris Lattner5a6bb6a2008-12-16 07:34:30 +0000168 SmallPtrSet<PHINode*, 16> &PHIUsers) {
Chris Lattner079236d2004-02-25 21:34:36 +0000169 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
Chris Lattner96940cb2004-07-18 19:56:20 +0000170 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(*UI)) {
Chris Lattner553ca522005-06-15 21:11:48 +0000171 GS.HasNonInstructionUser = true;
172
Chris Lattner7a90b682004-10-07 04:16:33 +0000173 if (AnalyzeGlobal(CE, GS, PHIUsers)) return true;
Chris Lattner670c8892004-10-08 17:32:09 +0000174
Chris Lattner079236d2004-02-25 21:34:36 +0000175 } else if (Instruction *I = dyn_cast<Instruction>(*UI)) {
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +0000176 if (!GS.HasMultipleAccessingFunctions) {
177 Function *F = I->getParent()->getParent();
178 if (GS.AccessingFunction == 0)
179 GS.AccessingFunction = F;
180 else if (GS.AccessingFunction != F)
181 GS.HasMultipleAccessingFunctions = true;
182 }
Chris Lattnerc69d3c92008-01-29 19:01:37 +0000183 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattner7a90b682004-10-07 04:16:33 +0000184 GS.isLoaded = true;
Chris Lattnerc69d3c92008-01-29 19:01:37 +0000185 if (LI->isVolatile()) return true; // Don't hack on volatile loads.
Chris Lattner7a90b682004-10-07 04:16:33 +0000186 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Chris Lattner36025492004-10-07 06:01:25 +0000187 // Don't allow a store OF the address, only stores TO the address.
188 if (SI->getOperand(0) == V) return true;
189
Chris Lattnerc69d3c92008-01-29 19:01:37 +0000190 if (SI->isVolatile()) return true; // Don't hack on volatile stores.
191
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000192 // If this is a direct store to the global (i.e., the global is a scalar
193 // value, not an aggregate), keep more specific information about
194 // stores.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000195 if (GS.StoredType != GlobalStatus::isStored) {
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000196 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(SI->getOperand(1))){
Chris Lattnerbd38edf2004-11-14 20:50:30 +0000197 Value *StoredVal = SI->getOperand(0);
198 if (StoredVal == GV->getInitializer()) {
199 if (GS.StoredType < GlobalStatus::isInitializerStored)
200 GS.StoredType = GlobalStatus::isInitializerStored;
201 } else if (isa<LoadInst>(StoredVal) &&
202 cast<LoadInst>(StoredVal)->getOperand(0) == GV) {
203 // G = G
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000204 if (GS.StoredType < GlobalStatus::isInitializerStored)
205 GS.StoredType = GlobalStatus::isInitializerStored;
206 } else if (GS.StoredType < GlobalStatus::isStoredOnce) {
207 GS.StoredType = GlobalStatus::isStoredOnce;
Chris Lattnerbd38edf2004-11-14 20:50:30 +0000208 GS.StoredOnceValue = StoredVal;
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000209 } else if (GS.StoredType == GlobalStatus::isStoredOnce &&
Chris Lattnerbd38edf2004-11-14 20:50:30 +0000210 GS.StoredOnceValue == StoredVal) {
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000211 // noop.
212 } else {
213 GS.StoredType = GlobalStatus::isStored;
214 }
215 } else {
Chris Lattner7a90b682004-10-07 04:16:33 +0000216 GS.StoredType = GlobalStatus::isStored;
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000217 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000218 }
Chris Lattner35c81b02005-02-27 18:58:52 +0000219 } else if (isa<GetElementPtrInst>(I)) {
Chris Lattner7a90b682004-10-07 04:16:33 +0000220 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Chris Lattner35c81b02005-02-27 18:58:52 +0000221 } else if (isa<SelectInst>(I)) {
Chris Lattner7a90b682004-10-07 04:16:33 +0000222 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Chris Lattner7a90b682004-10-07 04:16:33 +0000223 } else if (PHINode *PN = dyn_cast<PHINode>(I)) {
224 // PHI nodes we can check just like select or GEP instructions, but we
225 // have to be careful about infinite recursion.
Chris Lattner5a6bb6a2008-12-16 07:34:30 +0000226 if (PHIUsers.insert(PN)) // Not already visited.
Chris Lattner7a90b682004-10-07 04:16:33 +0000227 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Chris Lattner25de4e52006-11-01 18:03:33 +0000228 GS.HasPHIUser = true;
Reid Spencere4d87aa2006-12-23 06:05:41 +0000229 } else if (isa<CmpInst>(I)) {
Chris Lattner35c81b02005-02-27 18:58:52 +0000230 } else if (isa<MemCpyInst>(I) || isa<MemMoveInst>(I)) {
231 if (I->getOperand(1) == V)
232 GS.StoredType = GlobalStatus::isStored;
233 if (I->getOperand(2) == V)
234 GS.isLoaded = true;
Chris Lattner35c81b02005-02-27 18:58:52 +0000235 } else if (isa<MemSetInst>(I)) {
236 assert(I->getOperand(1) == V && "Memset only takes one pointer!");
237 GS.StoredType = GlobalStatus::isStored;
Chris Lattner7a90b682004-10-07 04:16:33 +0000238 } else {
239 return true; // Any other non-load instruction might take address!
Chris Lattner9ce30002004-07-20 03:58:07 +0000240 }
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000241 } else if (Constant *C = dyn_cast<Constant>(*UI)) {
Chris Lattner553ca522005-06-15 21:11:48 +0000242 GS.HasNonInstructionUser = true;
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000243 // We might have a dead and dangling constant hanging off of here.
244 if (!ConstantIsDead(C))
245 return true;
Chris Lattner079236d2004-02-25 21:34:36 +0000246 } else {
Chris Lattner553ca522005-06-15 21:11:48 +0000247 GS.HasNonInstructionUser = true;
248 // Otherwise must be some other user.
Chris Lattner079236d2004-02-25 21:34:36 +0000249 return true;
250 }
251
252 return false;
253}
254
Chris Lattner670c8892004-10-08 17:32:09 +0000255static Constant *getAggregateConstantElement(Constant *Agg, Constant *Idx) {
256 ConstantInt *CI = dyn_cast<ConstantInt>(Idx);
257 if (!CI) return 0;
Reid Spencerb83eb642006-10-20 07:07:24 +0000258 unsigned IdxV = CI->getZExtValue();
Chris Lattner7a90b682004-10-07 04:16:33 +0000259
Chris Lattner670c8892004-10-08 17:32:09 +0000260 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Agg)) {
261 if (IdxV < CS->getNumOperands()) return CS->getOperand(IdxV);
262 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Agg)) {
263 if (IdxV < CA->getNumOperands()) return CA->getOperand(IdxV);
Reid Spencer9d6565a2007-02-15 02:26:10 +0000264 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Agg)) {
Chris Lattner670c8892004-10-08 17:32:09 +0000265 if (IdxV < CP->getNumOperands()) return CP->getOperand(IdxV);
Chris Lattner7a7ed022004-10-16 18:09:00 +0000266 } else if (isa<ConstantAggregateZero>(Agg)) {
Chris Lattner670c8892004-10-08 17:32:09 +0000267 if (const StructType *STy = dyn_cast<StructType>(Agg->getType())) {
268 if (IdxV < STy->getNumElements())
269 return Constant::getNullValue(STy->getElementType(IdxV));
270 } else if (const SequentialType *STy =
271 dyn_cast<SequentialType>(Agg->getType())) {
272 return Constant::getNullValue(STy->getElementType());
273 }
Chris Lattner7a7ed022004-10-16 18:09:00 +0000274 } else if (isa<UndefValue>(Agg)) {
275 if (const StructType *STy = dyn_cast<StructType>(Agg->getType())) {
276 if (IdxV < STy->getNumElements())
277 return UndefValue::get(STy->getElementType(IdxV));
278 } else if (const SequentialType *STy =
279 dyn_cast<SequentialType>(Agg->getType())) {
280 return UndefValue::get(STy->getElementType());
281 }
Chris Lattner670c8892004-10-08 17:32:09 +0000282 }
283 return 0;
284}
Chris Lattner7a90b682004-10-07 04:16:33 +0000285
Chris Lattner7a90b682004-10-07 04:16:33 +0000286
Chris Lattnere47ba742004-10-06 20:57:02 +0000287/// CleanupConstantGlobalUsers - We just marked GV constant. Loop over all
288/// users of the global, cleaning up the obvious ones. This is largely just a
Chris Lattner031955d2004-10-10 16:43:46 +0000289/// quick scan over the use list to clean up the easy and obvious cruft. This
290/// returns true if it made a change.
291static bool CleanupConstantGlobalUsers(Value *V, Constant *Init) {
292 bool Changed = false;
Chris Lattner7a90b682004-10-07 04:16:33 +0000293 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;) {
294 User *U = *UI++;
Misha Brukmanfd939082005-04-21 23:48:37 +0000295
Chris Lattner7a90b682004-10-07 04:16:33 +0000296 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
Chris Lattner35c81b02005-02-27 18:58:52 +0000297 if (Init) {
298 // Replace the load with the initializer.
299 LI->replaceAllUsesWith(Init);
300 LI->eraseFromParent();
301 Changed = true;
302 }
Chris Lattner7a90b682004-10-07 04:16:33 +0000303 } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
Chris Lattnere47ba742004-10-06 20:57:02 +0000304 // Store must be unreachable or storing Init into the global.
Chris Lattner7a7ed022004-10-16 18:09:00 +0000305 SI->eraseFromParent();
Chris Lattner031955d2004-10-10 16:43:46 +0000306 Changed = true;
Chris Lattner7a90b682004-10-07 04:16:33 +0000307 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
308 if (CE->getOpcode() == Instruction::GetElementPtr) {
Chris Lattneraae4a1c2005-09-26 07:34:35 +0000309 Constant *SubInit = 0;
310 if (Init)
311 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
Chris Lattner35c81b02005-02-27 18:58:52 +0000312 Changed |= CleanupConstantGlobalUsers(CE, SubInit);
Reid Spencer3da59db2006-11-27 01:05:10 +0000313 } else if (CE->getOpcode() == Instruction::BitCast &&
Chris Lattner35c81b02005-02-27 18:58:52 +0000314 isa<PointerType>(CE->getType())) {
315 // Pointer cast, delete any stores and memsets to the global.
316 Changed |= CleanupConstantGlobalUsers(CE, 0);
317 }
318
319 if (CE->use_empty()) {
320 CE->destroyConstant();
321 Changed = true;
Chris Lattner7a90b682004-10-07 04:16:33 +0000322 }
323 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
Chris Lattner7b52fe72007-11-09 17:33:02 +0000324 // Do not transform "gepinst (gep constexpr (GV))" here, because forming
325 // "gepconstexpr (gep constexpr (GV))" will cause the two gep's to fold
326 // and will invalidate our notion of what Init is.
Chris Lattner19450242007-11-13 21:46:23 +0000327 Constant *SubInit = 0;
Chris Lattner7b52fe72007-11-09 17:33:02 +0000328 if (!isa<ConstantExpr>(GEP->getOperand(0))) {
329 ConstantExpr *CE =
330 dyn_cast_or_null<ConstantExpr>(ConstantFoldInstruction(GEP));
331 if (Init && CE && CE->getOpcode() == Instruction::GetElementPtr)
Chris Lattner19450242007-11-13 21:46:23 +0000332 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
Chris Lattner7b52fe72007-11-09 17:33:02 +0000333 }
Chris Lattner19450242007-11-13 21:46:23 +0000334 Changed |= CleanupConstantGlobalUsers(GEP, SubInit);
Chris Lattnerc4d81b02004-10-10 16:47:33 +0000335
Chris Lattner031955d2004-10-10 16:43:46 +0000336 if (GEP->use_empty()) {
Chris Lattner7a7ed022004-10-16 18:09:00 +0000337 GEP->eraseFromParent();
Chris Lattner031955d2004-10-10 16:43:46 +0000338 Changed = true;
339 }
Chris Lattner35c81b02005-02-27 18:58:52 +0000340 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U)) { // memset/cpy/mv
341 if (MI->getRawDest() == V) {
342 MI->eraseFromParent();
343 Changed = true;
344 }
345
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000346 } else if (Constant *C = dyn_cast<Constant>(U)) {
347 // If we have a chain of dead constantexprs or other things dangling from
348 // us, and if they are all dead, nuke them without remorse.
Devang Patel7f6179d2009-03-04 01:22:23 +0000349 SmallPtrSet<GlobalVariable *, 4> DeadGVs;
350 if (ConstantIsDead(C, &DeadGVs)) {
351 for (SmallPtrSet<GlobalVariable *, 4>::iterator TI = DeadGVs.begin(),
352 TE = DeadGVs.end(); TI != TE; ) {
353 GlobalVariable *TGV = *TI; ++TI;
354 TGV->eraseFromParent();
355 }
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000356 C->destroyConstant();
Chris Lattner35c81b02005-02-27 18:58:52 +0000357 // This could have invalidated UI, start over from scratch.
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000358 CleanupConstantGlobalUsers(V, Init);
Chris Lattner031955d2004-10-10 16:43:46 +0000359 return true;
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000360 }
Chris Lattnere47ba742004-10-06 20:57:02 +0000361 }
362 }
Chris Lattner031955d2004-10-10 16:43:46 +0000363 return Changed;
Chris Lattnere47ba742004-10-06 20:57:02 +0000364}
365
Chris Lattner941db492008-01-14 02:09:12 +0000366/// isSafeSROAElementUse - Return true if the specified instruction is a safe
367/// user of a derived expression from a global that we want to SROA.
368static bool isSafeSROAElementUse(Value *V) {
369 // We might have a dead and dangling constant hanging off of here.
370 if (Constant *C = dyn_cast<Constant>(V))
371 return ConstantIsDead(C);
Chris Lattner727c2102008-01-14 01:31:05 +0000372
Chris Lattner941db492008-01-14 02:09:12 +0000373 Instruction *I = dyn_cast<Instruction>(V);
374 if (!I) return false;
375
376 // Loads are ok.
377 if (isa<LoadInst>(I)) return true;
378
379 // Stores *to* the pointer are ok.
380 if (StoreInst *SI = dyn_cast<StoreInst>(I))
381 return SI->getOperand(0) != V;
382
383 // Otherwise, it must be a GEP.
384 GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I);
385 if (GEPI == 0) return false;
386
387 if (GEPI->getNumOperands() < 3 || !isa<Constant>(GEPI->getOperand(1)) ||
388 !cast<Constant>(GEPI->getOperand(1))->isNullValue())
389 return false;
390
391 for (Value::use_iterator I = GEPI->use_begin(), E = GEPI->use_end();
392 I != E; ++I)
393 if (!isSafeSROAElementUse(*I))
394 return false;
Chris Lattner727c2102008-01-14 01:31:05 +0000395 return true;
396}
397
Chris Lattner941db492008-01-14 02:09:12 +0000398
399/// IsUserOfGlobalSafeForSRA - U is a direct user of the specified global value.
400/// Look at it and its uses and decide whether it is safe to SROA this global.
401///
402static bool IsUserOfGlobalSafeForSRA(User *U, GlobalValue *GV) {
403 // The user of the global must be a GEP Inst or a ConstantExpr GEP.
404 if (!isa<GetElementPtrInst>(U) &&
405 (!isa<ConstantExpr>(U) ||
406 cast<ConstantExpr>(U)->getOpcode() != Instruction::GetElementPtr))
407 return false;
408
409 // Check to see if this ConstantExpr GEP is SRA'able. In particular, we
410 // don't like < 3 operand CE's, and we don't like non-constant integer
411 // indices. This enforces that all uses are 'gep GV, 0, C, ...' for some
412 // value of C.
413 if (U->getNumOperands() < 3 || !isa<Constant>(U->getOperand(1)) ||
414 !cast<Constant>(U->getOperand(1))->isNullValue() ||
415 !isa<ConstantInt>(U->getOperand(2)))
416 return false;
417
418 gep_type_iterator GEPI = gep_type_begin(U), E = gep_type_end(U);
419 ++GEPI; // Skip over the pointer index.
420
421 // If this is a use of an array allocation, do a bit more checking for sanity.
422 if (const ArrayType *AT = dyn_cast<ArrayType>(*GEPI)) {
423 uint64_t NumElements = AT->getNumElements();
424 ConstantInt *Idx = cast<ConstantInt>(U->getOperand(2));
425
426 // Check to make sure that index falls within the array. If not,
427 // something funny is going on, so we won't do the optimization.
428 //
429 if (Idx->getZExtValue() >= NumElements)
430 return false;
431
432 // We cannot scalar repl this level of the array unless any array
433 // sub-indices are in-range constants. In particular, consider:
434 // A[0][i]. We cannot know that the user isn't doing invalid things like
435 // allowing i to index an out-of-range subscript that accesses A[1].
436 //
437 // Scalar replacing *just* the outer index of the array is probably not
438 // going to be a win anyway, so just give up.
439 for (++GEPI; // Skip array index.
440 GEPI != E && (isa<ArrayType>(*GEPI) || isa<VectorType>(*GEPI));
441 ++GEPI) {
442 uint64_t NumElements;
443 if (const ArrayType *SubArrayTy = dyn_cast<ArrayType>(*GEPI))
444 NumElements = SubArrayTy->getNumElements();
445 else
446 NumElements = cast<VectorType>(*GEPI)->getNumElements();
447
448 ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPI.getOperand());
449 if (!IdxVal || IdxVal->getZExtValue() >= NumElements)
450 return false;
451 }
452 }
453
454 for (Value::use_iterator I = U->use_begin(), E = U->use_end(); I != E; ++I)
455 if (!isSafeSROAElementUse(*I))
456 return false;
457 return true;
458}
459
460/// GlobalUsersSafeToSRA - Look at all uses of the global and decide whether it
461/// is safe for us to perform this transformation.
462///
463static bool GlobalUsersSafeToSRA(GlobalValue *GV) {
464 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end();
465 UI != E; ++UI) {
466 if (!IsUserOfGlobalSafeForSRA(*UI, GV))
467 return false;
468 }
469 return true;
470}
471
472
Chris Lattner670c8892004-10-08 17:32:09 +0000473/// SRAGlobal - Perform scalar replacement of aggregates on the specified global
474/// variable. This opens the door for other optimizations by exposing the
475/// behavior of the program in a more fine-grained way. We have determined that
476/// this transformation is safe already. We return the first global variable we
477/// insert so that the caller can reprocess it.
Chris Lattner998182b2008-04-26 07:40:11 +0000478static GlobalVariable *SRAGlobal(GlobalVariable *GV, const TargetData &TD) {
Chris Lattner727c2102008-01-14 01:31:05 +0000479 // Make sure this global only has simple uses that we can SRA.
Chris Lattner941db492008-01-14 02:09:12 +0000480 if (!GlobalUsersSafeToSRA(GV))
Chris Lattner727c2102008-01-14 01:31:05 +0000481 return 0;
482
Rafael Espindolabb46f522009-01-15 20:18:42 +0000483 assert(GV->hasLocalLinkage() && !GV->isConstant());
Chris Lattner670c8892004-10-08 17:32:09 +0000484 Constant *Init = GV->getInitializer();
485 const Type *Ty = Init->getType();
Misha Brukmanfd939082005-04-21 23:48:37 +0000486
Chris Lattner670c8892004-10-08 17:32:09 +0000487 std::vector<GlobalVariable*> NewGlobals;
488 Module::GlobalListType &Globals = GV->getParent()->getGlobalList();
489
Chris Lattner998182b2008-04-26 07:40:11 +0000490 // Get the alignment of the global, either explicit or target-specific.
491 unsigned StartAlignment = GV->getAlignment();
492 if (StartAlignment == 0)
493 StartAlignment = TD.getABITypeAlignment(GV->getType());
494
Chris Lattner670c8892004-10-08 17:32:09 +0000495 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
496 NewGlobals.reserve(STy->getNumElements());
Chris Lattner998182b2008-04-26 07:40:11 +0000497 const StructLayout &Layout = *TD.getStructLayout(STy);
Chris Lattner670c8892004-10-08 17:32:09 +0000498 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
499 Constant *In = getAggregateConstantElement(Init,
Reid Spencerc5b206b2006-12-31 05:48:39 +0000500 ConstantInt::get(Type::Int32Ty, i));
Chris Lattner670c8892004-10-08 17:32:09 +0000501 assert(In && "Couldn't get element of initializer?");
502 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(i), false,
503 GlobalVariable::InternalLinkage,
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +0000504 In, GV->getName()+"."+utostr(i),
505 (Module *)NULL,
Matthijs Kooijmanbc1f9892008-07-17 11:59:53 +0000506 GV->isThreadLocal(),
507 GV->getType()->getAddressSpace());
Chris Lattner670c8892004-10-08 17:32:09 +0000508 Globals.insert(GV, NGV);
509 NewGlobals.push_back(NGV);
Chris Lattner998182b2008-04-26 07:40:11 +0000510
511 // Calculate the known alignment of the field. If the original aggregate
512 // had 256 byte alignment for example, something might depend on that:
513 // propagate info to each field.
514 uint64_t FieldOffset = Layout.getElementOffset(i);
515 unsigned NewAlign = (unsigned)MinAlign(StartAlignment, FieldOffset);
516 if (NewAlign > TD.getABITypeAlignment(STy->getElementType(i)))
517 NGV->setAlignment(NewAlign);
Chris Lattner670c8892004-10-08 17:32:09 +0000518 }
519 } else if (const SequentialType *STy = dyn_cast<SequentialType>(Ty)) {
520 unsigned NumElements = 0;
521 if (const ArrayType *ATy = dyn_cast<ArrayType>(STy))
522 NumElements = ATy->getNumElements();
Chris Lattner670c8892004-10-08 17:32:09 +0000523 else
Chris Lattner998182b2008-04-26 07:40:11 +0000524 NumElements = cast<VectorType>(STy)->getNumElements();
Chris Lattner670c8892004-10-08 17:32:09 +0000525
Chris Lattner1f21ef12005-02-23 16:53:04 +0000526 if (NumElements > 16 && GV->hasNUsesOrMore(16))
Chris Lattnerd514d822005-02-01 01:23:31 +0000527 return 0; // It's not worth it.
Chris Lattner670c8892004-10-08 17:32:09 +0000528 NewGlobals.reserve(NumElements);
Chris Lattner998182b2008-04-26 07:40:11 +0000529
Duncan Sandsceb4d1a2009-01-12 20:38:59 +0000530 uint64_t EltSize = TD.getTypePaddedSize(STy->getElementType());
Chris Lattner998182b2008-04-26 07:40:11 +0000531 unsigned EltAlign = TD.getABITypeAlignment(STy->getElementType());
Chris Lattner670c8892004-10-08 17:32:09 +0000532 for (unsigned i = 0, e = NumElements; i != e; ++i) {
533 Constant *In = getAggregateConstantElement(Init,
Reid Spencerc5b206b2006-12-31 05:48:39 +0000534 ConstantInt::get(Type::Int32Ty, i));
Chris Lattner670c8892004-10-08 17:32:09 +0000535 assert(In && "Couldn't get element of initializer?");
536
537 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(), false,
538 GlobalVariable::InternalLinkage,
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +0000539 In, GV->getName()+"."+utostr(i),
540 (Module *)NULL,
Matthijs Kooijmanbc1f9892008-07-17 11:59:53 +0000541 GV->isThreadLocal(),
542 GV->getType()->getAddressSpace());
Chris Lattner670c8892004-10-08 17:32:09 +0000543 Globals.insert(GV, NGV);
544 NewGlobals.push_back(NGV);
Chris Lattner998182b2008-04-26 07:40:11 +0000545
546 // Calculate the known alignment of the field. If the original aggregate
547 // had 256 byte alignment for example, something might depend on that:
548 // propagate info to each field.
549 unsigned NewAlign = (unsigned)MinAlign(StartAlignment, EltSize*i);
550 if (NewAlign > EltAlign)
551 NGV->setAlignment(NewAlign);
Chris Lattner670c8892004-10-08 17:32:09 +0000552 }
553 }
554
555 if (NewGlobals.empty())
556 return 0;
557
Bill Wendling0a81aac2006-11-26 10:02:32 +0000558 DOUT << "PERFORMING GLOBAL SRA ON: " << *GV;
Chris Lattner30ba5692004-10-11 05:54:41 +0000559
Reid Spencerc5b206b2006-12-31 05:48:39 +0000560 Constant *NullInt = Constant::getNullValue(Type::Int32Ty);
Chris Lattner670c8892004-10-08 17:32:09 +0000561
562 // Loop over all of the uses of the global, replacing the constantexpr geps,
563 // with smaller constantexpr geps or direct references.
564 while (!GV->use_empty()) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000565 User *GEP = GV->use_back();
566 assert(((isa<ConstantExpr>(GEP) &&
567 cast<ConstantExpr>(GEP)->getOpcode()==Instruction::GetElementPtr)||
568 isa<GetElementPtrInst>(GEP)) && "NonGEP CE's are not SRAable!");
Misha Brukmanfd939082005-04-21 23:48:37 +0000569
Chris Lattner670c8892004-10-08 17:32:09 +0000570 // Ignore the 1th operand, which has to be zero or else the program is quite
571 // broken (undefined). Get the 2nd operand, which is the structure or array
572 // index.
Reid Spencerb83eb642006-10-20 07:07:24 +0000573 unsigned Val = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
Chris Lattner670c8892004-10-08 17:32:09 +0000574 if (Val >= NewGlobals.size()) Val = 0; // Out of bound array access.
575
Chris Lattner30ba5692004-10-11 05:54:41 +0000576 Value *NewPtr = NewGlobals[Val];
Chris Lattner670c8892004-10-08 17:32:09 +0000577
578 // Form a shorter GEP if needed.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000579 if (GEP->getNumOperands() > 3) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000580 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEP)) {
Chris Lattner55eb1c42007-01-31 04:40:53 +0000581 SmallVector<Constant*, 8> Idxs;
Chris Lattner30ba5692004-10-11 05:54:41 +0000582 Idxs.push_back(NullInt);
583 for (unsigned i = 3, e = CE->getNumOperands(); i != e; ++i)
584 Idxs.push_back(CE->getOperand(i));
Chris Lattner55eb1c42007-01-31 04:40:53 +0000585 NewPtr = ConstantExpr::getGetElementPtr(cast<Constant>(NewPtr),
586 &Idxs[0], Idxs.size());
Chris Lattner30ba5692004-10-11 05:54:41 +0000587 } else {
588 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(GEP);
Chris Lattner699d1442007-01-31 19:59:55 +0000589 SmallVector<Value*, 8> Idxs;
Chris Lattner30ba5692004-10-11 05:54:41 +0000590 Idxs.push_back(NullInt);
591 for (unsigned i = 3, e = GEPI->getNumOperands(); i != e; ++i)
592 Idxs.push_back(GEPI->getOperand(i));
Gabor Greif051a9502008-04-06 20:25:17 +0000593 NewPtr = GetElementPtrInst::Create(NewPtr, Idxs.begin(), Idxs.end(),
594 GEPI->getName()+"."+utostr(Val), GEPI);
Chris Lattner30ba5692004-10-11 05:54:41 +0000595 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000596 }
Chris Lattner30ba5692004-10-11 05:54:41 +0000597 GEP->replaceAllUsesWith(NewPtr);
598
599 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(GEP))
Chris Lattner7a7ed022004-10-16 18:09:00 +0000600 GEPI->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +0000601 else
602 cast<ConstantExpr>(GEP)->destroyConstant();
Chris Lattner670c8892004-10-08 17:32:09 +0000603 }
604
Chris Lattnere40e2d12004-10-08 20:25:55 +0000605 // Delete the old global, now that it is dead.
606 Globals.erase(GV);
Chris Lattner670c8892004-10-08 17:32:09 +0000607 ++NumSRA;
Chris Lattner30ba5692004-10-11 05:54:41 +0000608
609 // Loop over the new globals array deleting any globals that are obviously
610 // dead. This can arise due to scalarization of a structure or an array that
611 // has elements that are dead.
612 unsigned FirstGlobal = 0;
613 for (unsigned i = 0, e = NewGlobals.size(); i != e; ++i)
614 if (NewGlobals[i]->use_empty()) {
615 Globals.erase(NewGlobals[i]);
616 if (FirstGlobal == i) ++FirstGlobal;
617 }
618
619 return FirstGlobal != NewGlobals.size() ? NewGlobals[FirstGlobal] : 0;
Chris Lattner670c8892004-10-08 17:32:09 +0000620}
621
Chris Lattner9b34a612004-10-09 21:48:45 +0000622/// AllUsesOfValueWillTrapIfNull - Return true if all users of the specified
Chris Lattner81686182007-09-13 16:30:19 +0000623/// value will trap if the value is dynamically null. PHIs keeps track of any
624/// phi nodes we've seen to avoid reprocessing them.
625static bool AllUsesOfValueWillTrapIfNull(Value *V,
626 SmallPtrSet<PHINode*, 8> &PHIs) {
Chris Lattner9b34a612004-10-09 21:48:45 +0000627 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
628 if (isa<LoadInst>(*UI)) {
629 // Will trap.
630 } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
631 if (SI->getOperand(0) == V) {
Bill Wendlinge8156192006-12-07 01:30:32 +0000632 //cerr << "NONTRAPPING USE: " << **UI;
Chris Lattner9b34a612004-10-09 21:48:45 +0000633 return false; // Storing the value.
634 }
635 } else if (CallInst *CI = dyn_cast<CallInst>(*UI)) {
636 if (CI->getOperand(0) != V) {
Bill Wendlinge8156192006-12-07 01:30:32 +0000637 //cerr << "NONTRAPPING USE: " << **UI;
Chris Lattner9b34a612004-10-09 21:48:45 +0000638 return false; // Not calling the ptr
639 }
640 } else if (InvokeInst *II = dyn_cast<InvokeInst>(*UI)) {
641 if (II->getOperand(0) != V) {
Bill Wendlinge8156192006-12-07 01:30:32 +0000642 //cerr << "NONTRAPPING USE: " << **UI;
Chris Lattner9b34a612004-10-09 21:48:45 +0000643 return false; // Not calling the ptr
644 }
Chris Lattner81686182007-09-13 16:30:19 +0000645 } else if (BitCastInst *CI = dyn_cast<BitCastInst>(*UI)) {
646 if (!AllUsesOfValueWillTrapIfNull(CI, PHIs)) return false;
Chris Lattner9b34a612004-10-09 21:48:45 +0000647 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(*UI)) {
Chris Lattner81686182007-09-13 16:30:19 +0000648 if (!AllUsesOfValueWillTrapIfNull(GEPI, PHIs)) return false;
649 } else if (PHINode *PN = dyn_cast<PHINode>(*UI)) {
650 // If we've already seen this phi node, ignore it, it has already been
651 // checked.
652 if (PHIs.insert(PN))
653 return AllUsesOfValueWillTrapIfNull(PN, PHIs);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000654 } else if (isa<ICmpInst>(*UI) &&
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000655 isa<ConstantPointerNull>(UI->getOperand(1))) {
656 // Ignore setcc X, null
Chris Lattner9b34a612004-10-09 21:48:45 +0000657 } else {
Bill Wendlinge8156192006-12-07 01:30:32 +0000658 //cerr << "NONTRAPPING USE: " << **UI;
Chris Lattner9b34a612004-10-09 21:48:45 +0000659 return false;
660 }
661 return true;
662}
663
664/// AllUsesOfLoadedValueWillTrapIfNull - Return true if all uses of any loads
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000665/// from GV will trap if the loaded value is null. Note that this also permits
666/// comparisons of the loaded value against null, as a special case.
Chris Lattner9b34a612004-10-09 21:48:45 +0000667static bool AllUsesOfLoadedValueWillTrapIfNull(GlobalVariable *GV) {
668 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI!=E; ++UI)
669 if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
Chris Lattner81686182007-09-13 16:30:19 +0000670 SmallPtrSet<PHINode*, 8> PHIs;
671 if (!AllUsesOfValueWillTrapIfNull(LI, PHIs))
Chris Lattner9b34a612004-10-09 21:48:45 +0000672 return false;
673 } else if (isa<StoreInst>(*UI)) {
674 // Ignore stores to the global.
675 } else {
676 // We don't know or understand this user, bail out.
Bill Wendlinge8156192006-12-07 01:30:32 +0000677 //cerr << "UNKNOWN USER OF GLOBAL!: " << **UI;
Chris Lattner9b34a612004-10-09 21:48:45 +0000678 return false;
679 }
680
681 return true;
682}
683
Chris Lattner708148e2004-10-10 23:14:11 +0000684static bool OptimizeAwayTrappingUsesOfValue(Value *V, Constant *NewV) {
685 bool Changed = false;
686 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ) {
687 Instruction *I = cast<Instruction>(*UI++);
688 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
689 LI->setOperand(0, NewV);
690 Changed = true;
691 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
692 if (SI->getOperand(1) == V) {
693 SI->setOperand(1, NewV);
694 Changed = true;
695 }
696 } else if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
697 if (I->getOperand(0) == V) {
698 // Calling through the pointer! Turn into a direct call, but be careful
699 // that the pointer is not also being passed as an argument.
700 I->setOperand(0, NewV);
701 Changed = true;
702 bool PassedAsArg = false;
703 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i)
704 if (I->getOperand(i) == V) {
705 PassedAsArg = true;
706 I->setOperand(i, NewV);
707 }
708
709 if (PassedAsArg) {
710 // Being passed as an argument also. Be careful to not invalidate UI!
711 UI = V->use_begin();
712 }
713 }
714 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
715 Changed |= OptimizeAwayTrappingUsesOfValue(CI,
Chris Lattner6e8fbad2006-11-30 17:32:29 +0000716 ConstantExpr::getCast(CI->getOpcode(),
717 NewV, CI->getType()));
Chris Lattner708148e2004-10-10 23:14:11 +0000718 if (CI->use_empty()) {
719 Changed = true;
Chris Lattner7a7ed022004-10-16 18:09:00 +0000720 CI->eraseFromParent();
Chris Lattner708148e2004-10-10 23:14:11 +0000721 }
722 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
723 // Should handle GEP here.
Chris Lattner55eb1c42007-01-31 04:40:53 +0000724 SmallVector<Constant*, 8> Idxs;
725 Idxs.reserve(GEPI->getNumOperands()-1);
Gabor Greif5e463212008-05-29 01:59:18 +0000726 for (User::op_iterator i = GEPI->op_begin() + 1, e = GEPI->op_end();
727 i != e; ++i)
728 if (Constant *C = dyn_cast<Constant>(*i))
Chris Lattner55eb1c42007-01-31 04:40:53 +0000729 Idxs.push_back(C);
Chris Lattner708148e2004-10-10 23:14:11 +0000730 else
731 break;
Chris Lattner55eb1c42007-01-31 04:40:53 +0000732 if (Idxs.size() == GEPI->getNumOperands()-1)
Chris Lattner708148e2004-10-10 23:14:11 +0000733 Changed |= OptimizeAwayTrappingUsesOfValue(GEPI,
Chris Lattner55eb1c42007-01-31 04:40:53 +0000734 ConstantExpr::getGetElementPtr(NewV, &Idxs[0],
735 Idxs.size()));
Chris Lattner708148e2004-10-10 23:14:11 +0000736 if (GEPI->use_empty()) {
737 Changed = true;
Chris Lattner7a7ed022004-10-16 18:09:00 +0000738 GEPI->eraseFromParent();
Chris Lattner708148e2004-10-10 23:14:11 +0000739 }
740 }
741 }
742
743 return Changed;
744}
745
746
747/// OptimizeAwayTrappingUsesOfLoads - The specified global has only one non-null
748/// value stored into it. If there are uses of the loaded value that would trap
749/// if the loaded value is dynamically null, then we know that they cannot be
750/// reachable with a null optimize away the load.
751static bool OptimizeAwayTrappingUsesOfLoads(GlobalVariable *GV, Constant *LV) {
Chris Lattner708148e2004-10-10 23:14:11 +0000752 bool Changed = false;
753
Chris Lattner92c6bd22009-01-14 00:12:58 +0000754 // Keep track of whether we are able to remove all the uses of the global
755 // other than the store that defines it.
756 bool AllNonStoreUsesGone = true;
757
Chris Lattner708148e2004-10-10 23:14:11 +0000758 // Replace all uses of loads with uses of uses of the stored value.
Chris Lattner92c6bd22009-01-14 00:12:58 +0000759 for (Value::use_iterator GUI = GV->use_begin(), E = GV->use_end(); GUI != E;){
760 User *GlobalUser = *GUI++;
761 if (LoadInst *LI = dyn_cast<LoadInst>(GlobalUser)) {
Chris Lattner708148e2004-10-10 23:14:11 +0000762 Changed |= OptimizeAwayTrappingUsesOfValue(LI, LV);
Chris Lattner92c6bd22009-01-14 00:12:58 +0000763 // If we were able to delete all uses of the loads
764 if (LI->use_empty()) {
765 LI->eraseFromParent();
766 Changed = true;
767 } else {
768 AllNonStoreUsesGone = false;
769 }
770 } else if (isa<StoreInst>(GlobalUser)) {
771 // Ignore the store that stores "LV" to the global.
772 assert(GlobalUser->getOperand(1) == GV &&
773 "Must be storing *to* the global");
Chris Lattner708148e2004-10-10 23:14:11 +0000774 } else {
Chris Lattner92c6bd22009-01-14 00:12:58 +0000775 AllNonStoreUsesGone = false;
776
777 // If we get here we could have other crazy uses that are transitively
778 // loaded.
779 assert((isa<PHINode>(GlobalUser) || isa<SelectInst>(GlobalUser) ||
780 isa<ConstantExpr>(GlobalUser)) && "Only expect load and stores!");
Chris Lattner708148e2004-10-10 23:14:11 +0000781 }
Chris Lattner92c6bd22009-01-14 00:12:58 +0000782 }
Chris Lattner708148e2004-10-10 23:14:11 +0000783
784 if (Changed) {
Bill Wendling0a81aac2006-11-26 10:02:32 +0000785 DOUT << "OPTIMIZED LOADS FROM STORED ONCE POINTER: " << *GV;
Chris Lattner708148e2004-10-10 23:14:11 +0000786 ++NumGlobUses;
787 }
788
Chris Lattner708148e2004-10-10 23:14:11 +0000789 // If we nuked all of the loads, then none of the stores are needed either,
790 // nor is the global.
Chris Lattner92c6bd22009-01-14 00:12:58 +0000791 if (AllNonStoreUsesGone) {
Bill Wendling0a81aac2006-11-26 10:02:32 +0000792 DOUT << " *** GLOBAL NOW DEAD!\n";
Chris Lattner708148e2004-10-10 23:14:11 +0000793 CleanupConstantGlobalUsers(GV, 0);
794 if (GV->use_empty()) {
Chris Lattner7a7ed022004-10-16 18:09:00 +0000795 GV->eraseFromParent();
Chris Lattner708148e2004-10-10 23:14:11 +0000796 ++NumDeleted;
797 }
798 Changed = true;
799 }
800 return Changed;
801}
802
Chris Lattner30ba5692004-10-11 05:54:41 +0000803/// ConstantPropUsersOf - Walk the use list of V, constant folding all of the
804/// instructions that are foldable.
805static void ConstantPropUsersOf(Value *V) {
806 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; )
807 if (Instruction *I = dyn_cast<Instruction>(*UI++))
808 if (Constant *NewC = ConstantFoldInstruction(I)) {
809 I->replaceAllUsesWith(NewC);
810
Chris Lattnerd514d822005-02-01 01:23:31 +0000811 // Advance UI to the next non-I use to avoid invalidating it!
812 // Instructions could multiply use V.
813 while (UI != E && *UI == I)
Chris Lattner30ba5692004-10-11 05:54:41 +0000814 ++UI;
Chris Lattnerd514d822005-02-01 01:23:31 +0000815 I->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +0000816 }
817}
818
819/// OptimizeGlobalAddressOfMalloc - This function takes the specified global
820/// variable, and transforms the program as if it always contained the result of
821/// the specified malloc. Because it is always the result of the specified
822/// malloc, there is no reason to actually DO the malloc. Instead, turn the
Chris Lattner6e8fbad2006-11-30 17:32:29 +0000823/// malloc into a global, and any loads of GV as uses of the new global.
Chris Lattner30ba5692004-10-11 05:54:41 +0000824static GlobalVariable *OptimizeGlobalAddressOfMalloc(GlobalVariable *GV,
825 MallocInst *MI) {
Bill Wendling0a81aac2006-11-26 10:02:32 +0000826 DOUT << "PROMOTING MALLOC GLOBAL: " << *GV << " MALLOC = " << *MI;
Chris Lattner30ba5692004-10-11 05:54:41 +0000827 ConstantInt *NElements = cast<ConstantInt>(MI->getArraySize());
828
Reid Spencerb83eb642006-10-20 07:07:24 +0000829 if (NElements->getZExtValue() != 1) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000830 // If we have an array allocation, transform it to a single element
831 // allocation to make the code below simpler.
832 Type *NewTy = ArrayType::get(MI->getAllocatedType(),
Reid Spencerb83eb642006-10-20 07:07:24 +0000833 NElements->getZExtValue());
Chris Lattner30ba5692004-10-11 05:54:41 +0000834 MallocInst *NewMI =
Reid Spencerc5b206b2006-12-31 05:48:39 +0000835 new MallocInst(NewTy, Constant::getNullValue(Type::Int32Ty),
Nate Begeman14b05292005-11-05 09:21:28 +0000836 MI->getAlignment(), MI->getName(), MI);
Chris Lattner699d1442007-01-31 19:59:55 +0000837 Value* Indices[2];
838 Indices[0] = Indices[1] = Constant::getNullValue(Type::Int32Ty);
Gabor Greif051a9502008-04-06 20:25:17 +0000839 Value *NewGEP = GetElementPtrInst::Create(NewMI, Indices, Indices + 2,
840 NewMI->getName()+".el0", MI);
Chris Lattner30ba5692004-10-11 05:54:41 +0000841 MI->replaceAllUsesWith(NewGEP);
Chris Lattner7a7ed022004-10-16 18:09:00 +0000842 MI->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +0000843 MI = NewMI;
844 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000845
Chris Lattner7a7ed022004-10-16 18:09:00 +0000846 // Create the new global variable. The contents of the malloc'd memory is
847 // undefined, so initialize with an undef value.
848 Constant *Init = UndefValue::get(MI->getAllocatedType());
Chris Lattner30ba5692004-10-11 05:54:41 +0000849 GlobalVariable *NewGV = new GlobalVariable(MI->getAllocatedType(), false,
850 GlobalValue::InternalLinkage, Init,
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +0000851 GV->getName()+".body",
852 (Module *)NULL,
853 GV->isThreadLocal());
Chris Lattner998182b2008-04-26 07:40:11 +0000854 // FIXME: This new global should have the alignment returned by malloc. Code
855 // could depend on malloc returning large alignment (on the mac, 16 bytes) but
856 // this would only guarantee some lower alignment.
Chris Lattner30ba5692004-10-11 05:54:41 +0000857 GV->getParent()->getGlobalList().insert(GV, NewGV);
Misha Brukmanfd939082005-04-21 23:48:37 +0000858
Chris Lattner30ba5692004-10-11 05:54:41 +0000859 // Anything that used the malloc now uses the global directly.
860 MI->replaceAllUsesWith(NewGV);
Chris Lattner30ba5692004-10-11 05:54:41 +0000861
862 Constant *RepValue = NewGV;
863 if (NewGV->getType() != GV->getType()->getElementType())
Reid Spencerd977d862006-12-12 23:36:14 +0000864 RepValue = ConstantExpr::getBitCast(RepValue,
865 GV->getType()->getElementType());
Chris Lattner30ba5692004-10-11 05:54:41 +0000866
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000867 // If there is a comparison against null, we will insert a global bool to
868 // keep track of whether the global was initialized yet or not.
Misha Brukmanfd939082005-04-21 23:48:37 +0000869 GlobalVariable *InitBool =
Reid Spencer4fe16d62007-01-11 18:21:29 +0000870 new GlobalVariable(Type::Int1Ty, false, GlobalValue::InternalLinkage,
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +0000871 ConstantInt::getFalse(), GV->getName()+".init",
872 (Module *)NULL, GV->isThreadLocal());
Chris Lattnerbc965b92004-12-02 06:25:58 +0000873 bool InitBoolUsed = false;
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000874
Chris Lattner30ba5692004-10-11 05:54:41 +0000875 // Loop over all uses of GV, processing them in turn.
Chris Lattnerbc965b92004-12-02 06:25:58 +0000876 std::vector<StoreInst*> Stores;
Chris Lattner30ba5692004-10-11 05:54:41 +0000877 while (!GV->use_empty())
878 if (LoadInst *LI = dyn_cast<LoadInst>(GV->use_back())) {
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000879 while (!LI->use_empty()) {
Chris Lattnerd514d822005-02-01 01:23:31 +0000880 Use &LoadUse = LI->use_begin().getUse();
Reid Spencere4d87aa2006-12-23 06:05:41 +0000881 if (!isa<ICmpInst>(LoadUse.getUser()))
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000882 LoadUse = RepValue;
883 else {
Reid Spencere4d87aa2006-12-23 06:05:41 +0000884 ICmpInst *CI = cast<ICmpInst>(LoadUse.getUser());
885 // Replace the cmp X, 0 with a use of the bool value.
886 Value *LV = new LoadInst(InitBool, InitBool->getName()+".val", CI);
Chris Lattnerbc965b92004-12-02 06:25:58 +0000887 InitBoolUsed = true;
Reid Spencere4d87aa2006-12-23 06:05:41 +0000888 switch (CI->getPredicate()) {
889 default: assert(0 && "Unknown ICmp Predicate!");
890 case ICmpInst::ICMP_ULT:
891 case ICmpInst::ICMP_SLT:
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000892 LV = ConstantInt::getFalse(); // X < null -> always false
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000893 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +0000894 case ICmpInst::ICMP_ULE:
895 case ICmpInst::ICMP_SLE:
896 case ICmpInst::ICMP_EQ:
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000897 LV = BinaryOperator::CreateNot(LV, "notinit", CI);
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000898 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +0000899 case ICmpInst::ICMP_NE:
900 case ICmpInst::ICMP_UGE:
901 case ICmpInst::ICMP_SGE:
902 case ICmpInst::ICMP_UGT:
903 case ICmpInst::ICMP_SGT:
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000904 break; // no change.
905 }
Reid Spencere4d87aa2006-12-23 06:05:41 +0000906 CI->replaceAllUsesWith(LV);
907 CI->eraseFromParent();
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000908 }
909 }
Chris Lattner7a7ed022004-10-16 18:09:00 +0000910 LI->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +0000911 } else {
912 StoreInst *SI = cast<StoreInst>(GV->use_back());
Chris Lattnerbc965b92004-12-02 06:25:58 +0000913 // The global is initialized when the store to it occurs.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000914 new StoreInst(ConstantInt::getTrue(), InitBool, SI);
Chris Lattner7a7ed022004-10-16 18:09:00 +0000915 SI->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +0000916 }
917
Chris Lattnerbc965b92004-12-02 06:25:58 +0000918 // If the initialization boolean was used, insert it, otherwise delete it.
919 if (!InitBoolUsed) {
920 while (!InitBool->use_empty()) // Delete initializations
921 cast<Instruction>(InitBool->use_back())->eraseFromParent();
922 delete InitBool;
923 } else
924 GV->getParent()->getGlobalList().insert(GV, InitBool);
925
926
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000927 // Now the GV is dead, nuke it and the malloc.
Chris Lattner7a7ed022004-10-16 18:09:00 +0000928 GV->eraseFromParent();
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000929 MI->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +0000930
931 // To further other optimizations, loop over all users of NewGV and try to
932 // constant prop them. This will promote GEP instructions with constant
933 // indices into GEP constant-exprs, which will allow global-opt to hack on it.
934 ConstantPropUsersOf(NewGV);
935 if (RepValue != NewGV)
936 ConstantPropUsersOf(RepValue);
937
938 return NewGV;
939}
Chris Lattner708148e2004-10-10 23:14:11 +0000940
Chris Lattnerfa07e4f2004-12-02 07:11:07 +0000941/// ValueIsOnlyUsedLocallyOrStoredToOneGlobal - Scan the use-list of V checking
942/// to make sure that there are no complex uses of V. We permit simple things
943/// like dereferencing the pointer, but not storing through the address, unless
944/// it is to the specified global.
945static bool ValueIsOnlyUsedLocallyOrStoredToOneGlobal(Instruction *V,
Chris Lattnerc451f9c2007-09-13 16:37:20 +0000946 GlobalVariable *GV,
947 SmallPtrSet<PHINode*, 8> &PHIs) {
Chris Lattner49b6d4a2008-12-15 21:08:54 +0000948 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;++UI){
949 Instruction *Inst = dyn_cast<Instruction>(*UI);
950 if (Inst == 0) return false;
951
952 if (isa<LoadInst>(Inst) || isa<CmpInst>(Inst)) {
953 continue; // Fine, ignore.
954 }
955
956 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
Chris Lattnerfa07e4f2004-12-02 07:11:07 +0000957 if (SI->getOperand(0) == V && SI->getOperand(1) != GV)
958 return false; // Storing the pointer itself... bad.
Chris Lattner49b6d4a2008-12-15 21:08:54 +0000959 continue; // Otherwise, storing through it, or storing into GV... fine.
960 }
961
962 if (isa<GetElementPtrInst>(Inst)) {
963 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(Inst, GV, PHIs))
Chris Lattnerfa07e4f2004-12-02 07:11:07 +0000964 return false;
Chris Lattner49b6d4a2008-12-15 21:08:54 +0000965 continue;
966 }
967
968 if (PHINode *PN = dyn_cast<PHINode>(Inst)) {
Chris Lattnerc451f9c2007-09-13 16:37:20 +0000969 // PHIs are ok if all uses are ok. Don't infinitely recurse through PHI
970 // cycles.
971 if (PHIs.insert(PN))
Chris Lattner5e6e4942007-09-14 03:41:21 +0000972 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(PN, GV, PHIs))
973 return false;
Chris Lattner49b6d4a2008-12-15 21:08:54 +0000974 continue;
Chris Lattnerfa07e4f2004-12-02 07:11:07 +0000975 }
Chris Lattner49b6d4a2008-12-15 21:08:54 +0000976
977 if (BitCastInst *BCI = dyn_cast<BitCastInst>(Inst)) {
978 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(BCI, GV, PHIs))
979 return false;
980 continue;
981 }
982
983 return false;
984 }
Chris Lattnerfa07e4f2004-12-02 07:11:07 +0000985 return true;
Chris Lattnerfa07e4f2004-12-02 07:11:07 +0000986}
987
Chris Lattner86395032006-09-30 23:32:09 +0000988/// ReplaceUsesOfMallocWithGlobal - The Alloc pointer is stored into GV
989/// somewhere. Transform all uses of the allocation into loads from the
990/// global and uses of the resultant pointer. Further, delete the store into
991/// GV. This assumes that these value pass the
992/// 'ValueIsOnlyUsedLocallyOrStoredToOneGlobal' predicate.
993static void ReplaceUsesOfMallocWithGlobal(Instruction *Alloc,
994 GlobalVariable *GV) {
995 while (!Alloc->use_empty()) {
Chris Lattnera637a8b2007-09-13 18:00:31 +0000996 Instruction *U = cast<Instruction>(*Alloc->use_begin());
997 Instruction *InsertPt = U;
Chris Lattner86395032006-09-30 23:32:09 +0000998 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
999 // If this is the store of the allocation into the global, remove it.
1000 if (SI->getOperand(1) == GV) {
1001 SI->eraseFromParent();
1002 continue;
1003 }
Chris Lattnera637a8b2007-09-13 18:00:31 +00001004 } else if (PHINode *PN = dyn_cast<PHINode>(U)) {
1005 // Insert the load in the corresponding predecessor, not right before the
1006 // PHI.
Gabor Greifa36791d2009-01-23 19:40:15 +00001007 InsertPt = PN->getIncomingBlock(Alloc->use_begin())->getTerminator();
Chris Lattner101f44e2008-12-15 21:44:34 +00001008 } else if (isa<BitCastInst>(U)) {
1009 // Must be bitcast between the malloc and store to initialize the global.
1010 ReplaceUsesOfMallocWithGlobal(U, GV);
1011 U->eraseFromParent();
1012 continue;
1013 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
1014 // If this is a "GEP bitcast" and the user is a store to the global, then
1015 // just process it as a bitcast.
1016 if (GEPI->hasAllZeroIndices() && GEPI->hasOneUse())
1017 if (StoreInst *SI = dyn_cast<StoreInst>(GEPI->use_back()))
1018 if (SI->getOperand(1) == GV) {
1019 // Must be bitcast GEP between the malloc and store to initialize
1020 // the global.
1021 ReplaceUsesOfMallocWithGlobal(GEPI, GV);
1022 GEPI->eraseFromParent();
1023 continue;
1024 }
Chris Lattner86395032006-09-30 23:32:09 +00001025 }
Chris Lattner101f44e2008-12-15 21:44:34 +00001026
Chris Lattner86395032006-09-30 23:32:09 +00001027 // Insert a load from the global, and use it instead of the malloc.
Chris Lattnera637a8b2007-09-13 18:00:31 +00001028 Value *NL = new LoadInst(GV, GV->getName()+".val", InsertPt);
Chris Lattner86395032006-09-30 23:32:09 +00001029 U->replaceUsesOfWith(Alloc, NL);
1030 }
1031}
1032
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001033/// LoadUsesSimpleEnoughForHeapSRA - Verify that all uses of V (a load, or a phi
1034/// of a load) are simple enough to perform heap SRA on. This permits GEP's
1035/// that index through the array and struct field, icmps of null, and PHIs.
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001036static bool LoadUsesSimpleEnoughForHeapSRA(Value *V,
1037 SmallPtrSet<PHINode*, 32> &LoadUsingPHIs) {
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001038 // We permit two users of the load: setcc comparing against the null
1039 // pointer, and a getelementptr of a specific form.
1040 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;++UI){
1041 Instruction *User = cast<Instruction>(*UI);
1042
1043 // Comparison against null is ok.
1044 if (ICmpInst *ICI = dyn_cast<ICmpInst>(User)) {
1045 if (!isa<ConstantPointerNull>(ICI->getOperand(1)))
1046 return false;
1047 continue;
1048 }
1049
1050 // getelementptr is also ok, but only a simple form.
1051 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
1052 // Must index into the array and into the struct.
1053 if (GEPI->getNumOperands() < 3)
1054 return false;
1055
1056 // Otherwise the GEP is ok.
1057 continue;
1058 }
1059
1060 if (PHINode *PN = dyn_cast<PHINode>(User)) {
1061 // If we have already recursively analyzed this PHI, then it is safe.
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001062 if (LoadUsingPHIs.insert(PN))
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001063 continue;
1064
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001065 // Make sure all uses of the PHI are simple enough to transform.
1066 if (!LoadUsesSimpleEnoughForHeapSRA(PN, LoadUsingPHIs))
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001067 return false;
1068
1069 continue;
Chris Lattner86395032006-09-30 23:32:09 +00001070 }
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001071
1072 // Otherwise we don't know what this is, not ok.
1073 return false;
1074 }
1075
1076 return true;
1077}
1078
1079
1080/// AllGlobalLoadUsesSimpleEnoughForHeapSRA - If all users of values loaded from
1081/// GV are simple enough to perform HeapSRA, return true.
1082static bool AllGlobalLoadUsesSimpleEnoughForHeapSRA(GlobalVariable *GV,
1083 MallocInst *MI) {
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001084 SmallPtrSet<PHINode*, 32> LoadUsingPHIs;
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001085 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI != E;
1086 ++UI)
1087 if (LoadInst *LI = dyn_cast<LoadInst>(*UI))
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001088 if (!LoadUsesSimpleEnoughForHeapSRA(LI, LoadUsingPHIs))
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001089 return false;
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001090
1091 // If we reach here, we know that all uses of the loads and transitive uses
1092 // (through PHI nodes) are simple enough to transform. However, we don't know
1093 // that all inputs the to the PHI nodes are in the same equivalence sets.
1094 // Check to verify that all operands of the PHIs are either PHIS that can be
1095 // transformed, loads from GV, or MI itself.
1096 for (SmallPtrSet<PHINode*, 32>::iterator I = LoadUsingPHIs.begin(),
1097 E = LoadUsingPHIs.end(); I != E; ++I) {
1098 PHINode *PN = *I;
1099 for (unsigned op = 0, e = PN->getNumIncomingValues(); op != e; ++op) {
1100 Value *InVal = PN->getIncomingValue(op);
1101
1102 // PHI of the stored value itself is ok.
1103 if (InVal == MI) continue;
1104
1105 if (PHINode *InPN = dyn_cast<PHINode>(InVal)) {
1106 // One of the PHIs in our set is (optimistically) ok.
1107 if (LoadUsingPHIs.count(InPN))
1108 continue;
1109 return false;
1110 }
1111
1112 // Load from GV is ok.
1113 if (LoadInst *LI = dyn_cast<LoadInst>(InVal))
1114 if (LI->getOperand(0) == GV)
1115 continue;
1116
1117 // UNDEF? NULL?
1118
1119 // Anything else is rejected.
1120 return false;
1121 }
1122 }
1123
Chris Lattner86395032006-09-30 23:32:09 +00001124 return true;
1125}
1126
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001127static Value *GetHeapSROAValue(Value *V, unsigned FieldNo,
1128 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
1129 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
1130 std::vector<Value*> &FieldVals = InsertedScalarizedValues[V];
1131
1132 if (FieldNo >= FieldVals.size())
1133 FieldVals.resize(FieldNo+1);
1134
1135 // If we already have this value, just reuse the previously scalarized
1136 // version.
1137 if (Value *FieldVal = FieldVals[FieldNo])
1138 return FieldVal;
1139
1140 // Depending on what instruction this is, we have several cases.
1141 Value *Result;
1142 if (LoadInst *LI = dyn_cast<LoadInst>(V)) {
1143 // This is a scalarized version of the load from the global. Just create
1144 // a new Load of the scalarized global.
1145 Result = new LoadInst(GetHeapSROAValue(LI->getOperand(0), FieldNo,
1146 InsertedScalarizedValues,
1147 PHIsToRewrite),
1148 LI->getName()+".f" + utostr(FieldNo), LI);
1149 } else if (PHINode *PN = dyn_cast<PHINode>(V)) {
1150 // PN's type is pointer to struct. Make a new PHI of pointer to struct
1151 // field.
1152 const StructType *ST =
1153 cast<StructType>(cast<PointerType>(PN->getType())->getElementType());
1154
1155 Result =PHINode::Create(PointerType::getUnqual(ST->getElementType(FieldNo)),
1156 PN->getName()+".f"+utostr(FieldNo), PN);
1157 PHIsToRewrite.push_back(std::make_pair(PN, FieldNo));
1158 } else {
1159 assert(0 && "Unknown usable value");
1160 Result = 0;
1161 }
1162
1163 return FieldVals[FieldNo] = Result;
Chris Lattnera637a8b2007-09-13 18:00:31 +00001164}
1165
Chris Lattner330245e2007-09-13 17:29:05 +00001166/// RewriteHeapSROALoadUser - Given a load instruction and a value derived from
1167/// the load, rewrite the derived value to use the HeapSRoA'd load.
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001168static void RewriteHeapSROALoadUser(Instruction *LoadUser,
1169 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
1170 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
Chris Lattner330245e2007-09-13 17:29:05 +00001171 // If this is a comparison against null, handle it.
1172 if (ICmpInst *SCI = dyn_cast<ICmpInst>(LoadUser)) {
1173 assert(isa<ConstantPointerNull>(SCI->getOperand(1)));
1174 // If we have a setcc of the loaded pointer, we can use a setcc of any
1175 // field.
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001176 Value *NPtr = GetHeapSROAValue(SCI->getOperand(0), 0,
1177 InsertedScalarizedValues, PHIsToRewrite);
Chris Lattner330245e2007-09-13 17:29:05 +00001178
1179 Value *New = new ICmpInst(SCI->getPredicate(), NPtr,
1180 Constant::getNullValue(NPtr->getType()),
1181 SCI->getName(), SCI);
1182 SCI->replaceAllUsesWith(New);
1183 SCI->eraseFromParent();
1184 return;
1185 }
1186
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001187 // Handle 'getelementptr Ptr, Idx, i32 FieldNo ...'
Chris Lattnera637a8b2007-09-13 18:00:31 +00001188 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(LoadUser)) {
1189 assert(GEPI->getNumOperands() >= 3 && isa<ConstantInt>(GEPI->getOperand(2))
1190 && "Unexpected GEPI!");
Chris Lattner330245e2007-09-13 17:29:05 +00001191
Chris Lattnera637a8b2007-09-13 18:00:31 +00001192 // Load the pointer for this field.
1193 unsigned FieldNo = cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue();
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001194 Value *NewPtr = GetHeapSROAValue(GEPI->getOperand(0), FieldNo,
1195 InsertedScalarizedValues, PHIsToRewrite);
Chris Lattnera637a8b2007-09-13 18:00:31 +00001196
1197 // Create the new GEP idx vector.
1198 SmallVector<Value*, 8> GEPIdx;
1199 GEPIdx.push_back(GEPI->getOperand(1));
1200 GEPIdx.append(GEPI->op_begin()+3, GEPI->op_end());
1201
Gabor Greifb1dbcd82008-05-15 10:04:30 +00001202 Value *NGEPI = GetElementPtrInst::Create(NewPtr,
1203 GEPIdx.begin(), GEPIdx.end(),
Gabor Greif051a9502008-04-06 20:25:17 +00001204 GEPI->getName(), GEPI);
Chris Lattnera637a8b2007-09-13 18:00:31 +00001205 GEPI->replaceAllUsesWith(NGEPI);
1206 GEPI->eraseFromParent();
1207 return;
1208 }
Chris Lattner309f20f2007-09-13 21:31:36 +00001209
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001210 // Recursively transform the users of PHI nodes. This will lazily create the
1211 // PHIs that are needed for individual elements. Keep track of what PHIs we
1212 // see in InsertedScalarizedValues so that we don't get infinite loops (very
1213 // antisocial). If the PHI is already in InsertedScalarizedValues, it has
1214 // already been seen first by another load, so its uses have already been
1215 // processed.
1216 PHINode *PN = cast<PHINode>(LoadUser);
1217 bool Inserted;
1218 DenseMap<Value*, std::vector<Value*> >::iterator InsertPos;
1219 tie(InsertPos, Inserted) =
1220 InsertedScalarizedValues.insert(std::make_pair(PN, std::vector<Value*>()));
1221 if (!Inserted) return;
Chris Lattner309f20f2007-09-13 21:31:36 +00001222
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001223 // If this is the first time we've seen this PHI, recursively process all
1224 // users.
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001225 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end(); UI != E; ) {
1226 Instruction *User = cast<Instruction>(*UI++);
1227 RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite);
1228 }
Chris Lattner330245e2007-09-13 17:29:05 +00001229}
1230
Chris Lattner86395032006-09-30 23:32:09 +00001231/// RewriteUsesOfLoadForHeapSRoA - We are performing Heap SRoA on a global. Ptr
1232/// is a value loaded from the global. Eliminate all uses of Ptr, making them
1233/// use FieldGlobals instead. All uses of loaded values satisfy
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001234/// AllGlobalLoadUsesSimpleEnoughForHeapSRA.
Chris Lattner330245e2007-09-13 17:29:05 +00001235static void RewriteUsesOfLoadForHeapSRoA(LoadInst *Load,
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001236 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
1237 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
1238 for (Value::use_iterator UI = Load->use_begin(), E = Load->use_end();
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001239 UI != E; ) {
1240 Instruction *User = cast<Instruction>(*UI++);
1241 RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite);
1242 }
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001243
1244 if (Load->use_empty()) {
1245 Load->eraseFromParent();
1246 InsertedScalarizedValues.erase(Load);
1247 }
Chris Lattner86395032006-09-30 23:32:09 +00001248}
1249
1250/// PerformHeapAllocSRoA - MI is an allocation of an array of structures. Break
1251/// it up into multiple allocations of arrays of the fields.
1252static GlobalVariable *PerformHeapAllocSRoA(GlobalVariable *GV, MallocInst *MI){
Bill Wendling0a81aac2006-11-26 10:02:32 +00001253 DOUT << "SROA HEAP ALLOC: " << *GV << " MALLOC = " << *MI;
Chris Lattner86395032006-09-30 23:32:09 +00001254 const StructType *STy = cast<StructType>(MI->getAllocatedType());
1255
1256 // There is guaranteed to be at least one use of the malloc (storing
1257 // it into GV). If there are other uses, change them to be uses of
1258 // the global to simplify later code. This also deletes the store
1259 // into GV.
1260 ReplaceUsesOfMallocWithGlobal(MI, GV);
1261
1262 // Okay, at this point, there are no users of the malloc. Insert N
1263 // new mallocs at the same place as MI, and N globals.
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001264 std::vector<Value*> FieldGlobals;
Chris Lattner86395032006-09-30 23:32:09 +00001265 std::vector<MallocInst*> FieldMallocs;
1266
1267 for (unsigned FieldNo = 0, e = STy->getNumElements(); FieldNo != e;++FieldNo){
1268 const Type *FieldTy = STy->getElementType(FieldNo);
Christopher Lamb43ad6b32007-12-17 01:12:55 +00001269 const Type *PFieldTy = PointerType::getUnqual(FieldTy);
Chris Lattner86395032006-09-30 23:32:09 +00001270
1271 GlobalVariable *NGV =
1272 new GlobalVariable(PFieldTy, false, GlobalValue::InternalLinkage,
1273 Constant::getNullValue(PFieldTy),
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +00001274 GV->getName() + ".f" + utostr(FieldNo), GV,
1275 GV->isThreadLocal());
Chris Lattner86395032006-09-30 23:32:09 +00001276 FieldGlobals.push_back(NGV);
1277
1278 MallocInst *NMI = new MallocInst(FieldTy, MI->getArraySize(),
1279 MI->getName() + ".f" + utostr(FieldNo),MI);
1280 FieldMallocs.push_back(NMI);
1281 new StoreInst(NMI, NGV, MI);
1282 }
1283
1284 // The tricky aspect of this transformation is handling the case when malloc
1285 // fails. In the original code, malloc failing would set the result pointer
1286 // of malloc to null. In this case, some mallocs could succeed and others
1287 // could fail. As such, we emit code that looks like this:
1288 // F0 = malloc(field0)
1289 // F1 = malloc(field1)
1290 // F2 = malloc(field2)
1291 // if (F0 == 0 || F1 == 0 || F2 == 0) {
1292 // if (F0) { free(F0); F0 = 0; }
1293 // if (F1) { free(F1); F1 = 0; }
1294 // if (F2) { free(F2); F2 = 0; }
1295 // }
1296 Value *RunningOr = 0;
1297 for (unsigned i = 0, e = FieldMallocs.size(); i != e; ++i) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001298 Value *Cond = new ICmpInst(ICmpInst::ICMP_EQ, FieldMallocs[i],
Chris Lattner86395032006-09-30 23:32:09 +00001299 Constant::getNullValue(FieldMallocs[i]->getType()),
1300 "isnull", MI);
1301 if (!RunningOr)
1302 RunningOr = Cond; // First seteq
1303 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001304 RunningOr = BinaryOperator::CreateOr(RunningOr, Cond, "tmp", MI);
Chris Lattner86395032006-09-30 23:32:09 +00001305 }
1306
1307 // Split the basic block at the old malloc.
1308 BasicBlock *OrigBB = MI->getParent();
1309 BasicBlock *ContBB = OrigBB->splitBasicBlock(MI, "malloc_cont");
1310
1311 // Create the block to check the first condition. Put all these blocks at the
1312 // end of the function as they are unlikely to be executed.
Gabor Greif051a9502008-04-06 20:25:17 +00001313 BasicBlock *NullPtrBlock = BasicBlock::Create("malloc_ret_null",
1314 OrigBB->getParent());
Chris Lattner86395032006-09-30 23:32:09 +00001315
1316 // Remove the uncond branch from OrigBB to ContBB, turning it into a cond
1317 // branch on RunningOr.
1318 OrigBB->getTerminator()->eraseFromParent();
Gabor Greif051a9502008-04-06 20:25:17 +00001319 BranchInst::Create(NullPtrBlock, ContBB, RunningOr, OrigBB);
Chris Lattner86395032006-09-30 23:32:09 +00001320
1321 // Within the NullPtrBlock, we need to emit a comparison and branch for each
1322 // pointer, because some may be null while others are not.
1323 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
1324 Value *GVVal = new LoadInst(FieldGlobals[i], "tmp", NullPtrBlock);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001325 Value *Cmp = new ICmpInst(ICmpInst::ICMP_NE, GVVal,
1326 Constant::getNullValue(GVVal->getType()),
1327 "tmp", NullPtrBlock);
Gabor Greif051a9502008-04-06 20:25:17 +00001328 BasicBlock *FreeBlock = BasicBlock::Create("free_it", OrigBB->getParent());
1329 BasicBlock *NextBlock = BasicBlock::Create("next", OrigBB->getParent());
1330 BranchInst::Create(FreeBlock, NextBlock, Cmp, NullPtrBlock);
Chris Lattner86395032006-09-30 23:32:09 +00001331
1332 // Fill in FreeBlock.
1333 new FreeInst(GVVal, FreeBlock);
1334 new StoreInst(Constant::getNullValue(GVVal->getType()), FieldGlobals[i],
1335 FreeBlock);
Gabor Greif051a9502008-04-06 20:25:17 +00001336 BranchInst::Create(NextBlock, FreeBlock);
Chris Lattner86395032006-09-30 23:32:09 +00001337
1338 NullPtrBlock = NextBlock;
1339 }
1340
Gabor Greif051a9502008-04-06 20:25:17 +00001341 BranchInst::Create(ContBB, NullPtrBlock);
Chris Lattner86395032006-09-30 23:32:09 +00001342
1343 // MI is no longer needed, remove it.
1344 MI->eraseFromParent();
1345
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001346 /// InsertedScalarizedLoads - As we process loads, if we can't immediately
1347 /// update all uses of the load, keep track of what scalarized loads are
1348 /// inserted for a given load.
1349 DenseMap<Value*, std::vector<Value*> > InsertedScalarizedValues;
1350 InsertedScalarizedValues[GV] = FieldGlobals;
1351
1352 std::vector<std::pair<PHINode*, unsigned> > PHIsToRewrite;
Chris Lattner86395032006-09-30 23:32:09 +00001353
1354 // Okay, the malloc site is completely handled. All of the uses of GV are now
1355 // loads, and all uses of those loads are simple. Rewrite them to use loads
1356 // of the per-field globals instead.
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001357 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI != E;) {
1358 Instruction *User = cast<Instruction>(*UI++);
1359
1360 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
1361 RewriteUsesOfLoadForHeapSRoA(LI, InsertedScalarizedValues, PHIsToRewrite);
1362 continue;
Chris Lattner39ff1e22007-01-09 23:29:37 +00001363 }
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001364
1365 // Must be a store of null.
1366 StoreInst *SI = cast<StoreInst>(User);
1367 assert(isa<ConstantPointerNull>(SI->getOperand(0)) &&
1368 "Unexpected heap-sra user!");
1369
1370 // Insert a store of null into each global.
1371 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
1372 const PointerType *PT = cast<PointerType>(FieldGlobals[i]->getType());
1373 Constant *Null = Constant::getNullValue(PT->getElementType());
1374 new StoreInst(Null, FieldGlobals[i], SI);
1375 }
1376 // Erase the original store.
1377 SI->eraseFromParent();
Chris Lattner86395032006-09-30 23:32:09 +00001378 }
1379
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001380 // While we have PHIs that are interesting to rewrite, do it.
1381 while (!PHIsToRewrite.empty()) {
1382 PHINode *PN = PHIsToRewrite.back().first;
1383 unsigned FieldNo = PHIsToRewrite.back().second;
1384 PHIsToRewrite.pop_back();
1385 PHINode *FieldPN = cast<PHINode>(InsertedScalarizedValues[PN][FieldNo]);
1386 assert(FieldPN->getNumIncomingValues() == 0 &&"Already processed this phi");
1387
1388 // Add all the incoming values. This can materialize more phis.
1389 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1390 Value *InVal = PN->getIncomingValue(i);
1391 InVal = GetHeapSROAValue(InVal, FieldNo, InsertedScalarizedValues,
1392 PHIsToRewrite);
1393 FieldPN->addIncoming(InVal, PN->getIncomingBlock(i));
1394 }
1395 }
1396
1397 // Drop all inter-phi links and any loads that made it this far.
1398 for (DenseMap<Value*, std::vector<Value*> >::iterator
1399 I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
1400 I != E; ++I) {
1401 if (PHINode *PN = dyn_cast<PHINode>(I->first))
1402 PN->dropAllReferences();
1403 else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
1404 LI->dropAllReferences();
1405 }
1406
1407 // Delete all the phis and loads now that inter-references are dead.
1408 for (DenseMap<Value*, std::vector<Value*> >::iterator
1409 I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
1410 I != E; ++I) {
1411 if (PHINode *PN = dyn_cast<PHINode>(I->first))
1412 PN->eraseFromParent();
1413 else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
1414 LI->eraseFromParent();
1415 }
1416
Chris Lattner86395032006-09-30 23:32:09 +00001417 // The old global is now dead, remove it.
1418 GV->eraseFromParent();
1419
1420 ++NumHeapSRA;
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001421 return cast<GlobalVariable>(FieldGlobals[0]);
Chris Lattner86395032006-09-30 23:32:09 +00001422}
1423
Chris Lattnere61d0a62008-12-15 21:02:25 +00001424/// TryToOptimizeStoreOfMallocToGlobal - This function is called when we see a
1425/// pointer global variable with a single value stored it that is a malloc or
1426/// cast of malloc.
1427static bool TryToOptimizeStoreOfMallocToGlobal(GlobalVariable *GV,
1428 MallocInst *MI,
1429 Module::global_iterator &GVI,
1430 TargetData &TD) {
1431 // If this is a malloc of an abstract type, don't touch it.
1432 if (!MI->getAllocatedType()->isSized())
1433 return false;
1434
1435 // We can't optimize this global unless all uses of it are *known* to be
1436 // of the malloc value, not of the null initializer value (consider a use
1437 // that compares the global's value against zero to see if the malloc has
1438 // been reached). To do this, we check to see if all uses of the global
1439 // would trap if the global were null: this proves that they must all
1440 // happen after the malloc.
1441 if (!AllUsesOfLoadedValueWillTrapIfNull(GV))
1442 return false;
1443
1444 // We can't optimize this if the malloc itself is used in a complex way,
1445 // for example, being stored into multiple globals. This allows the
1446 // malloc to be stored into the specified global, loaded setcc'd, and
1447 // GEP'd. These are all things we could transform to using the global
1448 // for.
1449 {
1450 SmallPtrSet<PHINode*, 8> PHIs;
1451 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(MI, GV, PHIs))
1452 return false;
1453 }
1454
1455
1456 // If we have a global that is only initialized with a fixed size malloc,
1457 // transform the program to use global memory instead of malloc'd memory.
1458 // This eliminates dynamic allocation, avoids an indirection accessing the
1459 // data, and exposes the resultant global to further GlobalOpt.
1460 if (ConstantInt *NElements = dyn_cast<ConstantInt>(MI->getArraySize())) {
1461 // Restrict this transformation to only working on small allocations
1462 // (2048 bytes currently), as we don't want to introduce a 16M global or
1463 // something.
1464 if (NElements->getZExtValue()*
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00001465 TD.getTypePaddedSize(MI->getAllocatedType()) < 2048) {
Chris Lattnere61d0a62008-12-15 21:02:25 +00001466 GVI = OptimizeGlobalAddressOfMalloc(GV, MI);
1467 return true;
1468 }
1469 }
1470
1471 // If the allocation is an array of structures, consider transforming this
1472 // into multiple malloc'd arrays, one for each field. This is basically
1473 // SRoA for malloc'd memory.
Chris Lattner101f44e2008-12-15 21:44:34 +00001474 const Type *AllocTy = MI->getAllocatedType();
1475
1476 // If this is an allocation of a fixed size array of structs, analyze as a
1477 // variable size array. malloc [100 x struct],1 -> malloc struct, 100
1478 if (!MI->isArrayAllocation())
1479 if (const ArrayType *AT = dyn_cast<ArrayType>(AllocTy))
1480 AllocTy = AT->getElementType();
1481
1482 if (const StructType *AllocSTy = dyn_cast<StructType>(AllocTy)) {
Chris Lattnere61d0a62008-12-15 21:02:25 +00001483 // This the structure has an unreasonable number of fields, leave it
1484 // alone.
Chris Lattner101f44e2008-12-15 21:44:34 +00001485 if (AllocSTy->getNumElements() <= 16 && AllocSTy->getNumElements() != 0 &&
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001486 AllGlobalLoadUsesSimpleEnoughForHeapSRA(GV, MI)) {
Chris Lattner101f44e2008-12-15 21:44:34 +00001487
1488 // If this is a fixed size array, transform the Malloc to be an alloc of
1489 // structs. malloc [100 x struct],1 -> malloc struct, 100
1490 if (const ArrayType *AT = dyn_cast<ArrayType>(MI->getAllocatedType())) {
1491 MallocInst *NewMI =
1492 new MallocInst(AllocSTy,
1493 ConstantInt::get(Type::Int32Ty, AT->getNumElements()),
1494 "", MI);
1495 NewMI->takeName(MI);
1496 Value *Cast = new BitCastInst(NewMI, MI->getType(), "tmp", MI);
1497 MI->replaceAllUsesWith(Cast);
1498 MI->eraseFromParent();
1499 MI = NewMI;
1500 }
1501
Chris Lattnere61d0a62008-12-15 21:02:25 +00001502 GVI = PerformHeapAllocSRoA(GV, MI);
1503 return true;
1504 }
1505 }
1506
1507 return false;
1508}
Chris Lattner86395032006-09-30 23:32:09 +00001509
Chris Lattner9b34a612004-10-09 21:48:45 +00001510// OptimizeOnceStoredGlobal - Try to optimize globals based on the knowledge
1511// that only one value (besides its initializer) is ever stored to the global.
Chris Lattner30ba5692004-10-11 05:54:41 +00001512static bool OptimizeOnceStoredGlobal(GlobalVariable *GV, Value *StoredOnceVal,
Chris Lattner7f8897f2006-08-27 22:42:52 +00001513 Module::global_iterator &GVI,
1514 TargetData &TD) {
Chris Lattner344b41c2008-12-15 21:20:32 +00001515 // Ignore no-op GEPs and bitcasts.
1516 StoredOnceVal = StoredOnceVal->stripPointerCasts();
Chris Lattner9b34a612004-10-09 21:48:45 +00001517
Chris Lattner708148e2004-10-10 23:14:11 +00001518 // If we are dealing with a pointer global that is initialized to null and
1519 // only has one (non-null) value stored into it, then we can optimize any
1520 // users of the loaded value (often calls and loads) that would trap if the
1521 // value was null.
Chris Lattner9b34a612004-10-09 21:48:45 +00001522 if (isa<PointerType>(GV->getInitializer()->getType()) &&
1523 GV->getInitializer()->isNullValue()) {
Chris Lattner708148e2004-10-10 23:14:11 +00001524 if (Constant *SOVC = dyn_cast<Constant>(StoredOnceVal)) {
1525 if (GV->getInitializer()->getType() != SOVC->getType())
Reid Spencerd977d862006-12-12 23:36:14 +00001526 SOVC = ConstantExpr::getBitCast(SOVC, GV->getInitializer()->getType());
Misha Brukmanfd939082005-04-21 23:48:37 +00001527
Chris Lattner708148e2004-10-10 23:14:11 +00001528 // Optimize away any trapping uses of the loaded value.
1529 if (OptimizeAwayTrappingUsesOfLoads(GV, SOVC))
Chris Lattner8be80122004-10-10 17:07:12 +00001530 return true;
Chris Lattner30ba5692004-10-11 05:54:41 +00001531 } else if (MallocInst *MI = dyn_cast<MallocInst>(StoredOnceVal)) {
Chris Lattnere61d0a62008-12-15 21:02:25 +00001532 if (TryToOptimizeStoreOfMallocToGlobal(GV, MI, GVI, TD))
1533 return true;
Chris Lattner708148e2004-10-10 23:14:11 +00001534 }
Chris Lattner9b34a612004-10-09 21:48:45 +00001535 }
Chris Lattner30ba5692004-10-11 05:54:41 +00001536
Chris Lattner9b34a612004-10-09 21:48:45 +00001537 return false;
1538}
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001539
Chris Lattner58e44f42008-01-14 01:17:44 +00001540/// TryToShrinkGlobalToBoolean - At this point, we have learned that the only
1541/// two values ever stored into GV are its initializer and OtherVal. See if we
1542/// can shrink the global into a boolean and select between the two values
1543/// whenever it is used. This exposes the values to other scalar optimizations.
1544static bool TryToShrinkGlobalToBoolean(GlobalVariable *GV, Constant *OtherVal) {
1545 const Type *GVElType = GV->getType()->getElementType();
1546
1547 // If GVElType is already i1, it is already shrunk. If the type of the GV is
1548 // an FP value or vector, don't do this optimization because a select between
1549 // them is very expensive and unlikely to lead to later simplification.
1550 if (GVElType == Type::Int1Ty || GVElType->isFloatingPoint() ||
1551 isa<VectorType>(GVElType))
1552 return false;
1553
1554 // Walk the use list of the global seeing if all the uses are load or store.
1555 // If there is anything else, bail out.
1556 for (Value::use_iterator I = GV->use_begin(), E = GV->use_end(); I != E; ++I)
1557 if (!isa<LoadInst>(I) && !isa<StoreInst>(I))
1558 return false;
1559
1560 DOUT << " *** SHRINKING TO BOOL: " << *GV;
1561
Chris Lattner96a86b22004-12-12 05:53:50 +00001562 // Create the new global, initializing it to false.
Reid Spencer4fe16d62007-01-11 18:21:29 +00001563 GlobalVariable *NewGV = new GlobalVariable(Type::Int1Ty, false,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001564 GlobalValue::InternalLinkage, ConstantInt::getFalse(),
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +00001565 GV->getName()+".b",
1566 (Module *)NULL,
1567 GV->isThreadLocal());
Chris Lattner96a86b22004-12-12 05:53:50 +00001568 GV->getParent()->getGlobalList().insert(GV, NewGV);
1569
1570 Constant *InitVal = GV->getInitializer();
Reid Spencer4fe16d62007-01-11 18:21:29 +00001571 assert(InitVal->getType() != Type::Int1Ty && "No reason to shrink to bool!");
Chris Lattner96a86b22004-12-12 05:53:50 +00001572
1573 // If initialized to zero and storing one into the global, we can use a cast
1574 // instead of a select to synthesize the desired value.
1575 bool IsOneZero = false;
1576 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal))
Reid Spencercae57542007-03-02 00:28:52 +00001577 IsOneZero = InitVal->isNullValue() && CI->isOne();
Chris Lattner96a86b22004-12-12 05:53:50 +00001578
1579 while (!GV->use_empty()) {
1580 Instruction *UI = cast<Instruction>(GV->use_back());
1581 if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
1582 // Change the store into a boolean store.
1583 bool StoringOther = SI->getOperand(0) == OtherVal;
1584 // Only do this if we weren't storing a loaded value.
Chris Lattner38c25562004-12-12 19:34:41 +00001585 Value *StoreVal;
Chris Lattner96a86b22004-12-12 05:53:50 +00001586 if (StoringOther || SI->getOperand(0) == InitVal)
Reid Spencer579dca12007-01-12 04:24:46 +00001587 StoreVal = ConstantInt::get(Type::Int1Ty, StoringOther);
Chris Lattner38c25562004-12-12 19:34:41 +00001588 else {
1589 // Otherwise, we are storing a previously loaded copy. To do this,
1590 // change the copy from copying the original value to just copying the
1591 // bool.
1592 Instruction *StoredVal = cast<Instruction>(SI->getOperand(0));
1593
1594 // If we're already replaced the input, StoredVal will be a cast or
1595 // select instruction. If not, it will be a load of the original
1596 // global.
1597 if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
1598 assert(LI->getOperand(0) == GV && "Not a copy!");
1599 // Insert a new load, to preserve the saved value.
1600 StoreVal = new LoadInst(NewGV, LI->getName()+".b", LI);
1601 } else {
1602 assert((isa<CastInst>(StoredVal) || isa<SelectInst>(StoredVal)) &&
1603 "This is not a form that we understand!");
1604 StoreVal = StoredVal->getOperand(0);
1605 assert(isa<LoadInst>(StoreVal) && "Not a load of NewGV!");
1606 }
1607 }
1608 new StoreInst(StoreVal, NewGV, SI);
Chris Lattner58e44f42008-01-14 01:17:44 +00001609 } else {
Chris Lattner96a86b22004-12-12 05:53:50 +00001610 // Change the load into a load of bool then a select.
1611 LoadInst *LI = cast<LoadInst>(UI);
Chris Lattner046800a2007-02-11 01:08:35 +00001612 LoadInst *NLI = new LoadInst(NewGV, LI->getName()+".b", LI);
Chris Lattner96a86b22004-12-12 05:53:50 +00001613 Value *NSI;
1614 if (IsOneZero)
Chris Lattner046800a2007-02-11 01:08:35 +00001615 NSI = new ZExtInst(NLI, LI->getType(), "", LI);
Misha Brukmanfd939082005-04-21 23:48:37 +00001616 else
Gabor Greif051a9502008-04-06 20:25:17 +00001617 NSI = SelectInst::Create(NLI, OtherVal, InitVal, "", LI);
Chris Lattner046800a2007-02-11 01:08:35 +00001618 NSI->takeName(LI);
Chris Lattner96a86b22004-12-12 05:53:50 +00001619 LI->replaceAllUsesWith(NSI);
1620 }
1621 UI->eraseFromParent();
1622 }
1623
1624 GV->eraseFromParent();
Chris Lattner58e44f42008-01-14 01:17:44 +00001625 return true;
Chris Lattner96a86b22004-12-12 05:53:50 +00001626}
1627
1628
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001629/// ProcessInternalGlobal - Analyze the specified global variable and optimize
1630/// it if possible. If we make a change, return true.
Chris Lattner30ba5692004-10-11 05:54:41 +00001631bool GlobalOpt::ProcessInternalGlobal(GlobalVariable *GV,
Chris Lattnere4d5c442005-03-15 04:54:21 +00001632 Module::global_iterator &GVI) {
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00001633 SmallPtrSet<PHINode*, 16> PHIUsers;
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001634 GlobalStatus GS;
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001635 GV->removeDeadConstantUsers();
1636
1637 if (GV->use_empty()) {
Bill Wendling0a81aac2006-11-26 10:02:32 +00001638 DOUT << "GLOBAL DEAD: " << *GV;
Chris Lattner7a7ed022004-10-16 18:09:00 +00001639 GV->eraseFromParent();
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001640 ++NumDeleted;
1641 return true;
1642 }
1643
1644 if (!AnalyzeGlobal(GV, GS, PHIUsers)) {
Chris Lattnercff16732006-09-30 19:40:30 +00001645#if 0
Bill Wendlinge8156192006-12-07 01:30:32 +00001646 cerr << "Global: " << *GV;
1647 cerr << " isLoaded = " << GS.isLoaded << "\n";
1648 cerr << " StoredType = ";
Chris Lattnercff16732006-09-30 19:40:30 +00001649 switch (GS.StoredType) {
Bill Wendlinge8156192006-12-07 01:30:32 +00001650 case GlobalStatus::NotStored: cerr << "NEVER STORED\n"; break;
1651 case GlobalStatus::isInitializerStored: cerr << "INIT STORED\n"; break;
1652 case GlobalStatus::isStoredOnce: cerr << "STORED ONCE\n"; break;
1653 case GlobalStatus::isStored: cerr << "stored\n"; break;
Chris Lattnercff16732006-09-30 19:40:30 +00001654 }
1655 if (GS.StoredType == GlobalStatus::isStoredOnce && GS.StoredOnceValue)
Bill Wendlinge8156192006-12-07 01:30:32 +00001656 cerr << " StoredOnceValue = " << *GS.StoredOnceValue << "\n";
Chris Lattnercff16732006-09-30 19:40:30 +00001657 if (GS.AccessingFunction && !GS.HasMultipleAccessingFunctions)
Bill Wendlinge8156192006-12-07 01:30:32 +00001658 cerr << " AccessingFunction = " << GS.AccessingFunction->getName()
Chris Lattnercff16732006-09-30 19:40:30 +00001659 << "\n";
Bill Wendlinge8156192006-12-07 01:30:32 +00001660 cerr << " HasMultipleAccessingFunctions = "
Chris Lattnercff16732006-09-30 19:40:30 +00001661 << GS.HasMultipleAccessingFunctions << "\n";
Bill Wendlinge8156192006-12-07 01:30:32 +00001662 cerr << " HasNonInstructionUser = " << GS.HasNonInstructionUser<<"\n";
Bill Wendlinge8156192006-12-07 01:30:32 +00001663 cerr << "\n";
Chris Lattnercff16732006-09-30 19:40:30 +00001664#endif
1665
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +00001666 // If this is a first class global and has only one accessing function
1667 // and this function is main (which we know is not recursive we can make
1668 // this global a local variable) we replace the global with a local alloca
1669 // in this function.
1670 //
Dan Gohman399101a2008-05-23 00:17:26 +00001671 // NOTE: It doesn't make sense to promote non single-value types since we
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +00001672 // are just replacing static memory to stack memory.
1673 if (!GS.HasMultipleAccessingFunctions &&
Chris Lattner553ca522005-06-15 21:11:48 +00001674 GS.AccessingFunction && !GS.HasNonInstructionUser &&
Dan Gohman399101a2008-05-23 00:17:26 +00001675 GV->getType()->getElementType()->isSingleValueType() &&
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +00001676 GS.AccessingFunction->getName() == "main" &&
1677 GS.AccessingFunction->hasExternalLinkage()) {
Bill Wendling0a81aac2006-11-26 10:02:32 +00001678 DOUT << "LOCALIZING GLOBAL: " << *GV;
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +00001679 Instruction* FirstI = GS.AccessingFunction->getEntryBlock().begin();
1680 const Type* ElemTy = GV->getType()->getElementType();
Nate Begeman14b05292005-11-05 09:21:28 +00001681 // FIXME: Pass Global's alignment when globals have alignment
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +00001682 AllocaInst* Alloca = new AllocaInst(ElemTy, NULL, GV->getName(), FirstI);
1683 if (!isa<UndefValue>(GV->getInitializer()))
1684 new StoreInst(GV->getInitializer(), Alloca, FirstI);
Misha Brukmanfd939082005-04-21 23:48:37 +00001685
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +00001686 GV->replaceAllUsesWith(Alloca);
1687 GV->eraseFromParent();
1688 ++NumLocalized;
1689 return true;
1690 }
Chris Lattnercff16732006-09-30 19:40:30 +00001691
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001692 // If the global is never loaded (but may be stored to), it is dead.
1693 // Delete it now.
1694 if (!GS.isLoaded) {
Bill Wendling0a81aac2006-11-26 10:02:32 +00001695 DOUT << "GLOBAL NEVER LOADED: " << *GV;
Chris Lattner930f4752004-10-09 03:32:52 +00001696
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001697 // Delete any stores we can find to the global. We may not be able to
1698 // make it completely dead though.
Chris Lattner031955d2004-10-10 16:43:46 +00001699 bool Changed = CleanupConstantGlobalUsers(GV, GV->getInitializer());
Chris Lattner930f4752004-10-09 03:32:52 +00001700
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001701 // If the global is dead now, delete it.
1702 if (GV->use_empty()) {
Chris Lattner7a7ed022004-10-16 18:09:00 +00001703 GV->eraseFromParent();
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001704 ++NumDeleted;
Chris Lattner930f4752004-10-09 03:32:52 +00001705 Changed = true;
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001706 }
Chris Lattner930f4752004-10-09 03:32:52 +00001707 return Changed;
Misha Brukmanfd939082005-04-21 23:48:37 +00001708
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001709 } else if (GS.StoredType <= GlobalStatus::isInitializerStored) {
Bill Wendling0a81aac2006-11-26 10:02:32 +00001710 DOUT << "MARKING CONSTANT: " << *GV;
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001711 GV->setConstant(true);
Misha Brukmanfd939082005-04-21 23:48:37 +00001712
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001713 // Clean up any obviously simplifiable users now.
1714 CleanupConstantGlobalUsers(GV, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +00001715
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001716 // If the global is dead now, just nuke it.
1717 if (GV->use_empty()) {
Bill Wendling0a81aac2006-11-26 10:02:32 +00001718 DOUT << " *** Marking constant allowed us to simplify "
1719 << "all users and delete global!\n";
Chris Lattner7a7ed022004-10-16 18:09:00 +00001720 GV->eraseFromParent();
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001721 ++NumDeleted;
1722 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001723
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001724 ++NumMarked;
1725 return true;
Dan Gohman399101a2008-05-23 00:17:26 +00001726 } else if (!GV->getInitializer()->getType()->isSingleValueType()) {
Chris Lattner998182b2008-04-26 07:40:11 +00001727 if (GlobalVariable *FirstNewGV = SRAGlobal(GV,
1728 getAnalysis<TargetData>())) {
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001729 GVI = FirstNewGV; // Don't skip the newly produced globals!
1730 return true;
1731 }
Chris Lattner9b34a612004-10-09 21:48:45 +00001732 } else if (GS.StoredType == GlobalStatus::isStoredOnce) {
Chris Lattner96a86b22004-12-12 05:53:50 +00001733 // If the initial value for the global was an undef value, and if only
1734 // one other value was stored into it, we can just change the
Duncan Sandsb5024402009-01-13 13:48:44 +00001735 // initializer to be the stored value, then delete all stores to the
Chris Lattner96a86b22004-12-12 05:53:50 +00001736 // global. This allows us to mark it constant.
1737 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
1738 if (isa<UndefValue>(GV->getInitializer())) {
1739 // Change the initial value here.
1740 GV->setInitializer(SOVConstant);
Misha Brukmanfd939082005-04-21 23:48:37 +00001741
Chris Lattner96a86b22004-12-12 05:53:50 +00001742 // Clean up any obviously simplifiable users now.
1743 CleanupConstantGlobalUsers(GV, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +00001744
Chris Lattner96a86b22004-12-12 05:53:50 +00001745 if (GV->use_empty()) {
Bill Wendling0a81aac2006-11-26 10:02:32 +00001746 DOUT << " *** Substituting initializer allowed us to "
1747 << "simplify all users and delete global!\n";
Chris Lattner96a86b22004-12-12 05:53:50 +00001748 GV->eraseFromParent();
1749 ++NumDeleted;
1750 } else {
1751 GVI = GV;
1752 }
1753 ++NumSubstitute;
1754 return true;
Chris Lattner7a7ed022004-10-16 18:09:00 +00001755 }
Chris Lattner7a7ed022004-10-16 18:09:00 +00001756
Chris Lattner9b34a612004-10-09 21:48:45 +00001757 // Try to optimize globals based on the knowledge that only one value
1758 // (besides its initializer) is ever stored to the global.
Chris Lattner30ba5692004-10-11 05:54:41 +00001759 if (OptimizeOnceStoredGlobal(GV, GS.StoredOnceValue, GVI,
1760 getAnalysis<TargetData>()))
Chris Lattner9b34a612004-10-09 21:48:45 +00001761 return true;
Chris Lattner96a86b22004-12-12 05:53:50 +00001762
1763 // Otherwise, if the global was not a boolean, we can shrink it to be a
1764 // boolean.
1765 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
Chris Lattner58e44f42008-01-14 01:17:44 +00001766 if (TryToShrinkGlobalToBoolean(GV, SOVConstant)) {
Chris Lattner96a86b22004-12-12 05:53:50 +00001767 ++NumShrunkToBool;
1768 return true;
1769 }
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001770 }
1771 }
1772 return false;
1773}
1774
Chris Lattnerfb217ad2005-05-08 22:18:06 +00001775/// OnlyCalledDirectly - Return true if the specified function is only called
1776/// directly. In other words, its address is never taken.
1777static bool OnlyCalledDirectly(Function *F) {
1778 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
1779 Instruction *User = dyn_cast<Instruction>(*UI);
1780 if (!User) return false;
1781 if (!isa<CallInst>(User) && !isa<InvokeInst>(User)) return false;
1782
1783 // See if the function address is passed as an argument.
Gabor Greif5e463212008-05-29 01:59:18 +00001784 for (User::op_iterator i = User->op_begin() + 1, e = User->op_end();
Bill Wendlingf9e67ac2008-08-12 23:15:44 +00001785 i != e; ++i)
Gabor Greif5e463212008-05-29 01:59:18 +00001786 if (*i == F) return false;
Chris Lattnerfb217ad2005-05-08 22:18:06 +00001787 }
1788 return true;
1789}
1790
1791/// ChangeCalleesToFastCall - Walk all of the direct calls of the specified
1792/// function, changing them to FastCC.
1793static void ChangeCalleesToFastCall(Function *F) {
1794 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
Duncan Sands548448a2008-02-18 17:32:13 +00001795 CallSite User(cast<Instruction>(*UI));
1796 User.setCallingConv(CallingConv::Fast);
Chris Lattnerfb217ad2005-05-08 22:18:06 +00001797 }
1798}
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001799
Devang Patel05988662008-09-25 21:00:45 +00001800static AttrListPtr StripNest(const AttrListPtr &Attrs) {
Chris Lattner58d74912008-03-12 17:45:29 +00001801 for (unsigned i = 0, e = Attrs.getNumSlots(); i != e; ++i) {
Devang Patel05988662008-09-25 21:00:45 +00001802 if ((Attrs.getSlot(i).Attrs & Attribute::Nest) == 0)
Duncan Sands548448a2008-02-18 17:32:13 +00001803 continue;
1804
Duncan Sands548448a2008-02-18 17:32:13 +00001805 // There can be only one.
Devang Patel05988662008-09-25 21:00:45 +00001806 return Attrs.removeAttr(Attrs.getSlot(i).Index, Attribute::Nest);
Duncan Sands3d5378f2008-02-16 20:56:04 +00001807 }
1808
1809 return Attrs;
1810}
1811
1812static void RemoveNestAttribute(Function *F) {
Devang Patel05988662008-09-25 21:00:45 +00001813 F->setAttributes(StripNest(F->getAttributes()));
Duncan Sands3d5378f2008-02-16 20:56:04 +00001814 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
Duncan Sands548448a2008-02-18 17:32:13 +00001815 CallSite User(cast<Instruction>(*UI));
Devang Patel05988662008-09-25 21:00:45 +00001816 User.setAttributes(StripNest(User.getAttributes()));
Duncan Sands3d5378f2008-02-16 20:56:04 +00001817 }
1818}
1819
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001820bool GlobalOpt::OptimizeFunctions(Module &M) {
1821 bool Changed = false;
1822 // Optimize functions.
1823 for (Module::iterator FI = M.begin(), E = M.end(); FI != E; ) {
1824 Function *F = FI++;
1825 F->removeDeadConstantUsers();
Rafael Espindolabb46f522009-01-15 20:18:42 +00001826 if (F->use_empty() && (F->hasLocalLinkage() ||
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001827 F->hasLinkOnceLinkage())) {
1828 M.getFunctionList().erase(F);
1829 Changed = true;
1830 ++NumFnDeleted;
Rafael Espindolabb46f522009-01-15 20:18:42 +00001831 } else if (F->hasLocalLinkage()) {
Duncan Sands3d5378f2008-02-16 20:56:04 +00001832 if (F->getCallingConv() == CallingConv::C && !F->isVarArg() &&
1833 OnlyCalledDirectly(F)) {
1834 // If this function has C calling conventions, is not a varargs
1835 // function, and is only called directly, promote it to use the Fast
1836 // calling convention.
1837 F->setCallingConv(CallingConv::Fast);
1838 ChangeCalleesToFastCall(F);
1839 ++NumFastCallFns;
1840 Changed = true;
1841 }
1842
Devang Patel05988662008-09-25 21:00:45 +00001843 if (F->getAttributes().hasAttrSomewhere(Attribute::Nest) &&
Duncan Sands3d5378f2008-02-16 20:56:04 +00001844 OnlyCalledDirectly(F)) {
1845 // The function is not used by a trampoline intrinsic, so it is safe
1846 // to remove the 'nest' attribute.
1847 RemoveNestAttribute(F);
1848 ++NumNestRemoved;
1849 Changed = true;
1850 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001851 }
1852 }
1853 return Changed;
1854}
1855
1856bool GlobalOpt::OptimizeGlobalVars(Module &M) {
1857 bool Changed = false;
1858 for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
1859 GVI != E; ) {
1860 GlobalVariable *GV = GVI++;
Rafael Espindolabb46f522009-01-15 20:18:42 +00001861 if (!GV->isConstant() && GV->hasLocalLinkage() &&
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001862 GV->hasInitializer())
1863 Changed |= ProcessInternalGlobal(GV, GVI);
1864 }
1865 return Changed;
1866}
1867
1868/// FindGlobalCtors - Find the llvm.globalctors list, verifying that all
1869/// initializers have an init priority of 65535.
1870GlobalVariable *GlobalOpt::FindGlobalCtors(Module &M) {
Alkis Evlogimenose9c6d362005-10-25 11:18:06 +00001871 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1872 I != E; ++I)
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001873 if (I->getName() == "llvm.global_ctors") {
1874 // Found it, verify it's an array of { int, void()* }.
1875 const ArrayType *ATy =dyn_cast<ArrayType>(I->getType()->getElementType());
1876 if (!ATy) return 0;
1877 const StructType *STy = dyn_cast<StructType>(ATy->getElementType());
1878 if (!STy || STy->getNumElements() != 2 ||
Reid Spencerc5b206b2006-12-31 05:48:39 +00001879 STy->getElementType(0) != Type::Int32Ty) return 0;
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001880 const PointerType *PFTy = dyn_cast<PointerType>(STy->getElementType(1));
1881 if (!PFTy) return 0;
1882 const FunctionType *FTy = dyn_cast<FunctionType>(PFTy->getElementType());
1883 if (!FTy || FTy->getReturnType() != Type::VoidTy || FTy->isVarArg() ||
1884 FTy->getNumParams() != 0)
1885 return 0;
1886
1887 // Verify that the initializer is simple enough for us to handle.
1888 if (!I->hasInitializer()) return 0;
1889 ConstantArray *CA = dyn_cast<ConstantArray>(I->getInitializer());
1890 if (!CA) return 0;
Gabor Greif5e463212008-05-29 01:59:18 +00001891 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i)
1892 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(*i)) {
Chris Lattner7d8e58f2005-09-26 02:19:27 +00001893 if (isa<ConstantPointerNull>(CS->getOperand(1)))
1894 continue;
1895
1896 // Must have a function or null ptr.
1897 if (!isa<Function>(CS->getOperand(1)))
1898 return 0;
1899
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001900 // Init priority must be standard.
1901 ConstantInt *CI = dyn_cast<ConstantInt>(CS->getOperand(0));
Reid Spencerb83eb642006-10-20 07:07:24 +00001902 if (!CI || CI->getZExtValue() != 65535)
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001903 return 0;
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001904 } else {
1905 return 0;
1906 }
1907
1908 return I;
1909 }
1910 return 0;
1911}
1912
Chris Lattnerdb973e62005-09-26 02:31:18 +00001913/// ParseGlobalCtors - Given a llvm.global_ctors list that we can understand,
1914/// return a list of the functions and null terminator as a vector.
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001915static std::vector<Function*> ParseGlobalCtors(GlobalVariable *GV) {
1916 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
1917 std::vector<Function*> Result;
1918 Result.reserve(CA->getNumOperands());
Gabor Greif5e463212008-05-29 01:59:18 +00001919 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i) {
1920 ConstantStruct *CS = cast<ConstantStruct>(*i);
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001921 Result.push_back(dyn_cast<Function>(CS->getOperand(1)));
1922 }
1923 return Result;
1924}
1925
Chris Lattnerdb973e62005-09-26 02:31:18 +00001926/// InstallGlobalCtors - Given a specified llvm.global_ctors list, install the
1927/// specified array, returning the new global to use.
1928static GlobalVariable *InstallGlobalCtors(GlobalVariable *GCL,
1929 const std::vector<Function*> &Ctors) {
1930 // If we made a change, reassemble the initializer list.
1931 std::vector<Constant*> CSVals;
Reid Spencerc5b206b2006-12-31 05:48:39 +00001932 CSVals.push_back(ConstantInt::get(Type::Int32Ty, 65535));
Chris Lattnerdb973e62005-09-26 02:31:18 +00001933 CSVals.push_back(0);
1934
1935 // Create the new init list.
1936 std::vector<Constant*> CAList;
1937 for (unsigned i = 0, e = Ctors.size(); i != e; ++i) {
Chris Lattner79c11012005-09-26 04:44:35 +00001938 if (Ctors[i]) {
Chris Lattnerdb973e62005-09-26 02:31:18 +00001939 CSVals[1] = Ctors[i];
Chris Lattner79c11012005-09-26 04:44:35 +00001940 } else {
Chris Lattnerdb973e62005-09-26 02:31:18 +00001941 const Type *FTy = FunctionType::get(Type::VoidTy,
1942 std::vector<const Type*>(), false);
Christopher Lamb43ad6b32007-12-17 01:12:55 +00001943 const PointerType *PFTy = PointerType::getUnqual(FTy);
Chris Lattnerdb973e62005-09-26 02:31:18 +00001944 CSVals[1] = Constant::getNullValue(PFTy);
Reid Spencerc5b206b2006-12-31 05:48:39 +00001945 CSVals[0] = ConstantInt::get(Type::Int32Ty, 2147483647);
Chris Lattnerdb973e62005-09-26 02:31:18 +00001946 }
1947 CAList.push_back(ConstantStruct::get(CSVals));
1948 }
1949
1950 // Create the array initializer.
1951 const Type *StructTy =
1952 cast<ArrayType>(GCL->getType()->getElementType())->getElementType();
1953 Constant *CA = ConstantArray::get(ArrayType::get(StructTy, CAList.size()),
1954 CAList);
1955
1956 // If we didn't change the number of elements, don't create a new GV.
1957 if (CA->getType() == GCL->getInitializer()->getType()) {
1958 GCL->setInitializer(CA);
1959 return GCL;
1960 }
1961
1962 // Create the new global and insert it next to the existing list.
1963 GlobalVariable *NGV = new GlobalVariable(CA->getType(), GCL->isConstant(),
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +00001964 GCL->getLinkage(), CA, "",
1965 (Module *)NULL,
1966 GCL->isThreadLocal());
Chris Lattnerdb973e62005-09-26 02:31:18 +00001967 GCL->getParent()->getGlobalList().insert(GCL, NGV);
Chris Lattner046800a2007-02-11 01:08:35 +00001968 NGV->takeName(GCL);
Chris Lattnerdb973e62005-09-26 02:31:18 +00001969
1970 // Nuke the old list, replacing any uses with the new one.
1971 if (!GCL->use_empty()) {
1972 Constant *V = NGV;
1973 if (V->getType() != GCL->getType())
Reid Spencerd977d862006-12-12 23:36:14 +00001974 V = ConstantExpr::getBitCast(V, GCL->getType());
Chris Lattnerdb973e62005-09-26 02:31:18 +00001975 GCL->replaceAllUsesWith(V);
1976 }
1977 GCL->eraseFromParent();
1978
1979 if (Ctors.size())
1980 return NGV;
1981 else
1982 return 0;
1983}
Chris Lattner79c11012005-09-26 04:44:35 +00001984
1985
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00001986static Constant *getVal(DenseMap<Value*, Constant*> &ComputedValues,
Chris Lattner79c11012005-09-26 04:44:35 +00001987 Value *V) {
1988 if (Constant *CV = dyn_cast<Constant>(V)) return CV;
1989 Constant *R = ComputedValues[V];
1990 assert(R && "Reference to an uncomputed value!");
1991 return R;
1992}
1993
1994/// isSimpleEnoughPointerToCommit - Return true if this constant is simple
1995/// enough for us to understand. In particular, if it is a cast of something,
1996/// we punt. We basically just support direct accesses to globals and GEP's of
1997/// globals. This should be kept up to date with CommitValueTo.
1998static bool isSimpleEnoughPointerToCommit(Constant *C) {
Chris Lattner231308c2005-09-27 04:50:03 +00001999 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
Rafael Espindolabb46f522009-01-15 20:18:42 +00002000 if (!GV->hasExternalLinkage() && !GV->hasLocalLinkage())
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00002001 return false; // do not allow weak/linkonce/dllimport/dllexport linkage.
Reid Spencer5cbf9852007-01-30 20:08:39 +00002002 return !GV->isDeclaration(); // reject external globals.
Chris Lattner231308c2005-09-27 04:50:03 +00002003 }
Chris Lattner798b4d52005-09-26 06:52:44 +00002004 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
2005 // Handle a constantexpr gep.
2006 if (CE->getOpcode() == Instruction::GetElementPtr &&
2007 isa<GlobalVariable>(CE->getOperand(0))) {
2008 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
Rafael Espindolabb46f522009-01-15 20:18:42 +00002009 if (!GV->hasExternalLinkage() && !GV->hasLocalLinkage())
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00002010 return false; // do not allow weak/linkonce/dllimport/dllexport linkage.
Chris Lattner798b4d52005-09-26 06:52:44 +00002011 return GV->hasInitializer() &&
2012 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
2013 }
Chris Lattner79c11012005-09-26 04:44:35 +00002014 return false;
2015}
2016
Chris Lattner798b4d52005-09-26 06:52:44 +00002017/// EvaluateStoreInto - Evaluate a piece of a constantexpr store into a global
2018/// initializer. This returns 'Init' modified to reflect 'Val' stored into it.
2019/// At this point, the GEP operands of Addr [0, OpNo) have been stepped into.
2020static Constant *EvaluateStoreInto(Constant *Init, Constant *Val,
2021 ConstantExpr *Addr, unsigned OpNo) {
2022 // Base case of the recursion.
2023 if (OpNo == Addr->getNumOperands()) {
2024 assert(Val->getType() == Init->getType() && "Type mismatch!");
2025 return Val;
2026 }
2027
2028 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
2029 std::vector<Constant*> Elts;
2030
2031 // Break up the constant into its elements.
2032 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
Gabor Greif5e463212008-05-29 01:59:18 +00002033 for (User::op_iterator i = CS->op_begin(), e = CS->op_end(); i != e; ++i)
2034 Elts.push_back(cast<Constant>(*i));
Chris Lattner798b4d52005-09-26 06:52:44 +00002035 } else if (isa<ConstantAggregateZero>(Init)) {
2036 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
2037 Elts.push_back(Constant::getNullValue(STy->getElementType(i)));
2038 } else if (isa<UndefValue>(Init)) {
2039 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
2040 Elts.push_back(UndefValue::get(STy->getElementType(i)));
2041 } else {
2042 assert(0 && "This code is out of sync with "
2043 " ConstantFoldLoadThroughGEPConstantExpr");
2044 }
2045
2046 // Replace the element that we are supposed to.
Reid Spencerb83eb642006-10-20 07:07:24 +00002047 ConstantInt *CU = cast<ConstantInt>(Addr->getOperand(OpNo));
2048 unsigned Idx = CU->getZExtValue();
2049 assert(Idx < STy->getNumElements() && "Struct index out of range!");
Chris Lattner798b4d52005-09-26 06:52:44 +00002050 Elts[Idx] = EvaluateStoreInto(Elts[Idx], Val, Addr, OpNo+1);
2051
2052 // Return the modified struct.
Chris Lattnerf0a9aab2007-06-04 22:23:42 +00002053 return ConstantStruct::get(&Elts[0], Elts.size(), STy->isPacked());
Chris Lattner798b4d52005-09-26 06:52:44 +00002054 } else {
2055 ConstantInt *CI = cast<ConstantInt>(Addr->getOperand(OpNo));
2056 const ArrayType *ATy = cast<ArrayType>(Init->getType());
2057
2058 // Break up the array into elements.
2059 std::vector<Constant*> Elts;
2060 if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
Gabor Greif5e463212008-05-29 01:59:18 +00002061 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i)
2062 Elts.push_back(cast<Constant>(*i));
Chris Lattner798b4d52005-09-26 06:52:44 +00002063 } else if (isa<ConstantAggregateZero>(Init)) {
2064 Constant *Elt = Constant::getNullValue(ATy->getElementType());
2065 Elts.assign(ATy->getNumElements(), Elt);
2066 } else if (isa<UndefValue>(Init)) {
2067 Constant *Elt = UndefValue::get(ATy->getElementType());
2068 Elts.assign(ATy->getNumElements(), Elt);
2069 } else {
2070 assert(0 && "This code is out of sync with "
2071 " ConstantFoldLoadThroughGEPConstantExpr");
2072 }
2073
Reid Spencerb83eb642006-10-20 07:07:24 +00002074 assert(CI->getZExtValue() < ATy->getNumElements());
2075 Elts[CI->getZExtValue()] =
2076 EvaluateStoreInto(Elts[CI->getZExtValue()], Val, Addr, OpNo+1);
Chris Lattner798b4d52005-09-26 06:52:44 +00002077 return ConstantArray::get(ATy, Elts);
2078 }
2079}
2080
Chris Lattner79c11012005-09-26 04:44:35 +00002081/// CommitValueTo - We have decided that Addr (which satisfies the predicate
2082/// isSimpleEnoughPointerToCommit) should get Val as its value. Make it happen.
2083static void CommitValueTo(Constant *Val, Constant *Addr) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002084 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Addr)) {
2085 assert(GV->hasInitializer());
2086 GV->setInitializer(Val);
2087 return;
2088 }
2089
2090 ConstantExpr *CE = cast<ConstantExpr>(Addr);
2091 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
2092
2093 Constant *Init = GV->getInitializer();
2094 Init = EvaluateStoreInto(Init, Val, CE, 2);
2095 GV->setInitializer(Init);
Chris Lattner79c11012005-09-26 04:44:35 +00002096}
2097
Chris Lattner562a0552005-09-26 05:16:34 +00002098/// ComputeLoadResult - Return the value that would be computed by a load from
2099/// P after the stores reflected by 'memory' have been performed. If we can't
2100/// decide, return null.
Chris Lattner04de1cf2005-09-26 05:15:37 +00002101static Constant *ComputeLoadResult(Constant *P,
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002102 const DenseMap<Constant*, Constant*> &Memory) {
Chris Lattner04de1cf2005-09-26 05:15:37 +00002103 // If this memory location has been recently stored, use the stored value: it
2104 // is the most up-to-date.
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002105 DenseMap<Constant*, Constant*>::const_iterator I = Memory.find(P);
Chris Lattner04de1cf2005-09-26 05:15:37 +00002106 if (I != Memory.end()) return I->second;
2107
2108 // Access it.
2109 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(P)) {
2110 if (GV->hasInitializer())
2111 return GV->getInitializer();
2112 return 0;
Chris Lattner04de1cf2005-09-26 05:15:37 +00002113 }
Chris Lattner798b4d52005-09-26 06:52:44 +00002114
2115 // Handle a constantexpr getelementptr.
2116 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(P))
2117 if (CE->getOpcode() == Instruction::GetElementPtr &&
2118 isa<GlobalVariable>(CE->getOperand(0))) {
2119 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
2120 if (GV->hasInitializer())
2121 return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
2122 }
2123
2124 return 0; // don't know how to evaluate.
Chris Lattner04de1cf2005-09-26 05:15:37 +00002125}
2126
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002127/// EvaluateFunction - Evaluate a call to function F, returning true if
2128/// successful, false if we can't evaluate it. ActualArgs contains the formal
2129/// arguments for the function.
Chris Lattnercd271422005-09-27 04:45:34 +00002130static bool EvaluateFunction(Function *F, Constant *&RetVal,
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002131 const std::vector<Constant*> &ActualArgs,
2132 std::vector<Function*> &CallStack,
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002133 DenseMap<Constant*, Constant*> &MutatedMemory,
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002134 std::vector<GlobalVariable*> &AllocaTmps) {
Chris Lattnercd271422005-09-27 04:45:34 +00002135 // Check to see if this function is already executing (recursion). If so,
2136 // bail out. TODO: we might want to accept limited recursion.
2137 if (std::find(CallStack.begin(), CallStack.end(), F) != CallStack.end())
2138 return false;
2139
2140 CallStack.push_back(F);
2141
Chris Lattner79c11012005-09-26 04:44:35 +00002142 /// Values - As we compute SSA register values, we store their contents here.
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002143 DenseMap<Value*, Constant*> Values;
Chris Lattnercd271422005-09-27 04:45:34 +00002144
2145 // Initialize arguments to the incoming values specified.
2146 unsigned ArgNo = 0;
2147 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); AI != E;
2148 ++AI, ++ArgNo)
2149 Values[AI] = ActualArgs[ArgNo];
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002150
Chris Lattnercdf98be2005-09-26 04:57:38 +00002151 /// ExecutedBlocks - We only handle non-looping, non-recursive code. As such,
2152 /// we can only evaluate any one basic block at most once. This set keeps
2153 /// track of what we have executed so we can detect recursive cases etc.
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002154 SmallPtrSet<BasicBlock*, 32> ExecutedBlocks;
Chris Lattnera22fdb02005-09-26 17:07:09 +00002155
Chris Lattner79c11012005-09-26 04:44:35 +00002156 // CurInst - The current instruction we're evaluating.
2157 BasicBlock::iterator CurInst = F->begin()->begin();
2158
2159 // This is the main evaluation loop.
2160 while (1) {
2161 Constant *InstResult = 0;
2162
2163 if (StoreInst *SI = dyn_cast<StoreInst>(CurInst)) {
Chris Lattnercd271422005-09-27 04:45:34 +00002164 if (SI->isVolatile()) return false; // no volatile accesses.
Chris Lattner79c11012005-09-26 04:44:35 +00002165 Constant *Ptr = getVal(Values, SI->getOperand(1));
2166 if (!isSimpleEnoughPointerToCommit(Ptr))
2167 // If this is too complex for us to commit, reject it.
Chris Lattnercd271422005-09-27 04:45:34 +00002168 return false;
Chris Lattner79c11012005-09-26 04:44:35 +00002169 Constant *Val = getVal(Values, SI->getOperand(0));
2170 MutatedMemory[Ptr] = Val;
2171 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CurInst)) {
2172 InstResult = ConstantExpr::get(BO->getOpcode(),
2173 getVal(Values, BO->getOperand(0)),
2174 getVal(Values, BO->getOperand(1)));
Reid Spencere4d87aa2006-12-23 06:05:41 +00002175 } else if (CmpInst *CI = dyn_cast<CmpInst>(CurInst)) {
2176 InstResult = ConstantExpr::getCompare(CI->getPredicate(),
2177 getVal(Values, CI->getOperand(0)),
2178 getVal(Values, CI->getOperand(1)));
Chris Lattner79c11012005-09-26 04:44:35 +00002179 } else if (CastInst *CI = dyn_cast<CastInst>(CurInst)) {
Chris Lattner9a989f02006-11-30 17:26:08 +00002180 InstResult = ConstantExpr::getCast(CI->getOpcode(),
2181 getVal(Values, CI->getOperand(0)),
Chris Lattner79c11012005-09-26 04:44:35 +00002182 CI->getType());
2183 } else if (SelectInst *SI = dyn_cast<SelectInst>(CurInst)) {
2184 InstResult = ConstantExpr::getSelect(getVal(Values, SI->getOperand(0)),
2185 getVal(Values, SI->getOperand(1)),
2186 getVal(Values, SI->getOperand(2)));
Chris Lattner04de1cf2005-09-26 05:15:37 +00002187 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurInst)) {
2188 Constant *P = getVal(Values, GEP->getOperand(0));
Chris Lattner55eb1c42007-01-31 04:40:53 +00002189 SmallVector<Constant*, 8> GEPOps;
Gabor Greif5e463212008-05-29 01:59:18 +00002190 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end();
2191 i != e; ++i)
2192 GEPOps.push_back(getVal(Values, *i));
Chris Lattner55eb1c42007-01-31 04:40:53 +00002193 InstResult = ConstantExpr::getGetElementPtr(P, &GEPOps[0], GEPOps.size());
Chris Lattner04de1cf2005-09-26 05:15:37 +00002194 } else if (LoadInst *LI = dyn_cast<LoadInst>(CurInst)) {
Chris Lattnercd271422005-09-27 04:45:34 +00002195 if (LI->isVolatile()) return false; // no volatile accesses.
Chris Lattner04de1cf2005-09-26 05:15:37 +00002196 InstResult = ComputeLoadResult(getVal(Values, LI->getOperand(0)),
2197 MutatedMemory);
Chris Lattnercd271422005-09-27 04:45:34 +00002198 if (InstResult == 0) return false; // Could not evaluate load.
Chris Lattnera22fdb02005-09-26 17:07:09 +00002199 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(CurInst)) {
Chris Lattnercd271422005-09-27 04:45:34 +00002200 if (AI->isArrayAllocation()) return false; // Cannot handle array allocs.
Chris Lattnera22fdb02005-09-26 17:07:09 +00002201 const Type *Ty = AI->getType()->getElementType();
2202 AllocaTmps.push_back(new GlobalVariable(Ty, false,
2203 GlobalValue::InternalLinkage,
2204 UndefValue::get(Ty),
2205 AI->getName()));
Chris Lattnercd271422005-09-27 04:45:34 +00002206 InstResult = AllocaTmps.back();
2207 } else if (CallInst *CI = dyn_cast<CallInst>(CurInst)) {
Chris Lattner7cd580f2006-07-07 21:37:01 +00002208 // Cannot handle inline asm.
2209 if (isa<InlineAsm>(CI->getOperand(0))) return false;
2210
Chris Lattnercd271422005-09-27 04:45:34 +00002211 // Resolve function pointers.
2212 Function *Callee = dyn_cast<Function>(getVal(Values, CI->getOperand(0)));
2213 if (!Callee) return false; // Cannot resolve.
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002214
Chris Lattnercd271422005-09-27 04:45:34 +00002215 std::vector<Constant*> Formals;
Gabor Greif5e463212008-05-29 01:59:18 +00002216 for (User::op_iterator i = CI->op_begin() + 1, e = CI->op_end();
2217 i != e; ++i)
2218 Formals.push_back(getVal(Values, *i));
Chris Lattnercd271422005-09-27 04:45:34 +00002219
Reid Spencer5cbf9852007-01-30 20:08:39 +00002220 if (Callee->isDeclaration()) {
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002221 // If this is a function we can constant fold, do it.
Chris Lattner6c1f5652007-01-30 23:14:52 +00002222 if (Constant *C = ConstantFoldCall(Callee, &Formals[0],
2223 Formals.size())) {
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002224 InstResult = C;
2225 } else {
2226 return false;
2227 }
2228 } else {
2229 if (Callee->getFunctionType()->isVarArg())
2230 return false;
2231
2232 Constant *RetVal;
2233
2234 // Execute the call, if successful, use the return value.
2235 if (!EvaluateFunction(Callee, RetVal, Formals, CallStack,
2236 MutatedMemory, AllocaTmps))
2237 return false;
2238 InstResult = RetVal;
2239 }
Reid Spencer3ed469c2006-11-02 20:25:50 +00002240 } else if (isa<TerminatorInst>(CurInst)) {
Chris Lattnercdf98be2005-09-26 04:57:38 +00002241 BasicBlock *NewBB = 0;
2242 if (BranchInst *BI = dyn_cast<BranchInst>(CurInst)) {
2243 if (BI->isUnconditional()) {
2244 NewBB = BI->getSuccessor(0);
2245 } else {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002246 ConstantInt *Cond =
2247 dyn_cast<ConstantInt>(getVal(Values, BI->getCondition()));
Chris Lattner97d1fad2007-01-12 18:30:11 +00002248 if (!Cond) return false; // Cannot determine.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002249
Reid Spencer579dca12007-01-12 04:24:46 +00002250 NewBB = BI->getSuccessor(!Cond->getZExtValue());
Chris Lattnercdf98be2005-09-26 04:57:38 +00002251 }
2252 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(CurInst)) {
2253 ConstantInt *Val =
2254 dyn_cast<ConstantInt>(getVal(Values, SI->getCondition()));
Chris Lattnercd271422005-09-27 04:45:34 +00002255 if (!Val) return false; // Cannot determine.
Chris Lattnercdf98be2005-09-26 04:57:38 +00002256 NewBB = SI->getSuccessor(SI->findCaseValue(Val));
2257 } else if (ReturnInst *RI = dyn_cast<ReturnInst>(CurInst)) {
Chris Lattnercd271422005-09-27 04:45:34 +00002258 if (RI->getNumOperands())
2259 RetVal = getVal(Values, RI->getOperand(0));
2260
2261 CallStack.pop_back(); // return from fn.
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002262 return true; // We succeeded at evaluating this ctor!
Chris Lattnercdf98be2005-09-26 04:57:38 +00002263 } else {
Chris Lattnercd271422005-09-27 04:45:34 +00002264 // invoke, unwind, unreachable.
2265 return false; // Cannot handle this terminator.
Chris Lattnercdf98be2005-09-26 04:57:38 +00002266 }
2267
2268 // Okay, we succeeded in evaluating this control flow. See if we have
Chris Lattnercd271422005-09-27 04:45:34 +00002269 // executed the new block before. If so, we have a looping function,
2270 // which we cannot evaluate in reasonable time.
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002271 if (!ExecutedBlocks.insert(NewBB))
Chris Lattnercd271422005-09-27 04:45:34 +00002272 return false; // looped!
Chris Lattnercdf98be2005-09-26 04:57:38 +00002273
2274 // Okay, we have never been in this block before. Check to see if there
2275 // are any PHI nodes. If so, evaluate them with information about where
2276 // we came from.
2277 BasicBlock *OldBB = CurInst->getParent();
2278 CurInst = NewBB->begin();
2279 PHINode *PN;
2280 for (; (PN = dyn_cast<PHINode>(CurInst)); ++CurInst)
2281 Values[PN] = getVal(Values, PN->getIncomingValueForBlock(OldBB));
2282
2283 // Do NOT increment CurInst. We know that the terminator had no value.
2284 continue;
Chris Lattner79c11012005-09-26 04:44:35 +00002285 } else {
Chris Lattner79c11012005-09-26 04:44:35 +00002286 // Did not know how to evaluate this!
Chris Lattnercd271422005-09-27 04:45:34 +00002287 return false;
Chris Lattner79c11012005-09-26 04:44:35 +00002288 }
2289
2290 if (!CurInst->use_empty())
2291 Values[CurInst] = InstResult;
2292
2293 // Advance program counter.
2294 ++CurInst;
2295 }
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002296}
2297
2298/// EvaluateStaticConstructor - Evaluate static constructors in the function, if
2299/// we can. Return true if we can, false otherwise.
2300static bool EvaluateStaticConstructor(Function *F) {
2301 /// MutatedMemory - For each store we execute, we update this map. Loads
2302 /// check this to get the most up-to-date value. If evaluation is successful,
2303 /// this state is committed to the process.
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002304 DenseMap<Constant*, Constant*> MutatedMemory;
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002305
2306 /// AllocaTmps - To 'execute' an alloca, we create a temporary global variable
2307 /// to represent its body. This vector is needed so we can delete the
2308 /// temporary globals when we are done.
2309 std::vector<GlobalVariable*> AllocaTmps;
2310
2311 /// CallStack - This is used to detect recursion. In pathological situations
2312 /// we could hit exponential behavior, but at least there is nothing
2313 /// unbounded.
2314 std::vector<Function*> CallStack;
2315
2316 // Call the function.
Chris Lattnercd271422005-09-27 04:45:34 +00002317 Constant *RetValDummy;
2318 bool EvalSuccess = EvaluateFunction(F, RetValDummy, std::vector<Constant*>(),
2319 CallStack, MutatedMemory, AllocaTmps);
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002320 if (EvalSuccess) {
Chris Lattnera22fdb02005-09-26 17:07:09 +00002321 // We succeeded at evaluation: commit the result.
Bill Wendling0a81aac2006-11-26 10:02:32 +00002322 DOUT << "FULLY EVALUATED GLOBAL CTOR FUNCTION '"
2323 << F->getName() << "' to " << MutatedMemory.size()
2324 << " stores.\n";
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002325 for (DenseMap<Constant*, Constant*>::iterator I = MutatedMemory.begin(),
Chris Lattnera22fdb02005-09-26 17:07:09 +00002326 E = MutatedMemory.end(); I != E; ++I)
2327 CommitValueTo(I->second, I->first);
2328 }
Chris Lattner79c11012005-09-26 04:44:35 +00002329
Chris Lattnera22fdb02005-09-26 17:07:09 +00002330 // At this point, we are done interpreting. If we created any 'alloca'
2331 // temporaries, release them now.
2332 while (!AllocaTmps.empty()) {
2333 GlobalVariable *Tmp = AllocaTmps.back();
2334 AllocaTmps.pop_back();
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002335
Chris Lattnera22fdb02005-09-26 17:07:09 +00002336 // If there are still users of the alloca, the program is doing something
2337 // silly, e.g. storing the address of the alloca somewhere and using it
2338 // later. Since this is undefined, we'll just make it be null.
2339 if (!Tmp->use_empty())
2340 Tmp->replaceAllUsesWith(Constant::getNullValue(Tmp->getType()));
2341 delete Tmp;
2342 }
Chris Lattneraae4a1c2005-09-26 07:34:35 +00002343
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002344 return EvalSuccess;
Chris Lattner79c11012005-09-26 04:44:35 +00002345}
2346
Chris Lattnerdb973e62005-09-26 02:31:18 +00002347
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002348
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002349/// OptimizeGlobalCtorsList - Simplify and evaluation global ctors if possible.
2350/// Return true if anything changed.
2351bool GlobalOpt::OptimizeGlobalCtorsList(GlobalVariable *&GCL) {
2352 std::vector<Function*> Ctors = ParseGlobalCtors(GCL);
2353 bool MadeChange = false;
2354 if (Ctors.empty()) return false;
2355
2356 // Loop over global ctors, optimizing them when we can.
2357 for (unsigned i = 0; i != Ctors.size(); ++i) {
2358 Function *F = Ctors[i];
2359 // Found a null terminator in the middle of the list, prune off the rest of
2360 // the list.
Chris Lattner7d8e58f2005-09-26 02:19:27 +00002361 if (F == 0) {
2362 if (i != Ctors.size()-1) {
2363 Ctors.resize(i+1);
2364 MadeChange = true;
2365 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002366 break;
2367 }
2368
Chris Lattner79c11012005-09-26 04:44:35 +00002369 // We cannot simplify external ctor functions.
2370 if (F->empty()) continue;
2371
2372 // If we can evaluate the ctor at compile time, do.
2373 if (EvaluateStaticConstructor(F)) {
2374 Ctors.erase(Ctors.begin()+i);
2375 MadeChange = true;
2376 --i;
2377 ++NumCtorsEvaluated;
2378 continue;
2379 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002380 }
2381
2382 if (!MadeChange) return false;
2383
Chris Lattnerdb973e62005-09-26 02:31:18 +00002384 GCL = InstallGlobalCtors(GCL, Ctors);
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002385 return true;
2386}
2387
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002388bool GlobalOpt::ResolveAliases(Module &M) {
2389 bool Changed = false;
2390
Duncan Sands177d84e2009-01-07 20:01:06 +00002391 for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end();
Duncan Sands4782b302009-02-15 09:56:08 +00002392 I != E;) {
2393 Module::alias_iterator J = I++;
2394 // If the aliasee may change at link time, nothing can be done - bail out.
2395 if (J->mayBeOverridden())
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002396 continue;
2397
Duncan Sands4782b302009-02-15 09:56:08 +00002398 Constant *Aliasee = J->getAliasee();
2399 GlobalValue *Target = cast<GlobalValue>(Aliasee->stripPointerCasts());
Duncan Sands95c5d0f2009-02-18 17:55:38 +00002400 Target->removeDeadConstantUsers();
Duncan Sands4782b302009-02-15 09:56:08 +00002401 bool hasOneUse = Target->hasOneUse() && Aliasee->hasOneUse();
2402
2403 // Make all users of the alias use the aliasee instead.
2404 if (!J->use_empty()) {
2405 J->replaceAllUsesWith(Aliasee);
2406 ++NumAliasesResolved;
2407 Changed = true;
2408 }
2409
2410 // If the aliasee has internal linkage, give it the name and linkage
2411 // of the alias, and delete the alias. This turns:
2412 // define internal ... @f(...)
2413 // @a = alias ... @f
2414 // into:
2415 // define ... @a(...)
Duncan Sands7ae5b9e2009-02-17 17:50:04 +00002416 if (!Target->hasLocalLinkage())
Duncan Sands4782b302009-02-15 09:56:08 +00002417 continue;
2418
2419 // The transform is only useful if the alias does not have internal linkage.
Duncan Sands7ae5b9e2009-02-17 17:50:04 +00002420 if (J->hasLocalLinkage())
Duncan Sands4782b302009-02-15 09:56:08 +00002421 continue;
2422
Duncan Sandsa37d1192009-02-15 11:54:49 +00002423 // Do not perform the transform if multiple aliases potentially target the
2424 // aliasee. This check also ensures that it is safe to replace the section
2425 // and other attributes of the aliasee with those of the alias.
Duncan Sands4782b302009-02-15 09:56:08 +00002426 if (!hasOneUse)
2427 continue;
2428
Duncan Sandsa37d1192009-02-15 11:54:49 +00002429 // Give the aliasee the name, linkage and other attributes of the alias.
Duncan Sands4782b302009-02-15 09:56:08 +00002430 Target->takeName(J);
2431 Target->setLinkage(J->getLinkage());
Duncan Sandsa37d1192009-02-15 11:54:49 +00002432 Target->GlobalValue::copyAttributesFrom(J);
Duncan Sands4782b302009-02-15 09:56:08 +00002433
2434 // Delete the alias.
2435 M.getAliasList().erase(J);
2436 ++NumAliasesRemoved;
2437 Changed = true;
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002438 }
2439
2440 return Changed;
2441}
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002442
Chris Lattner7a90b682004-10-07 04:16:33 +00002443bool GlobalOpt::runOnModule(Module &M) {
Chris Lattner079236d2004-02-25 21:34:36 +00002444 bool Changed = false;
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002445
2446 // Try to find the llvm.globalctors list.
2447 GlobalVariable *GlobalCtors = FindGlobalCtors(M);
Chris Lattner7a90b682004-10-07 04:16:33 +00002448
Chris Lattner7a90b682004-10-07 04:16:33 +00002449 bool LocalChange = true;
2450 while (LocalChange) {
2451 LocalChange = false;
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002452
2453 // Delete functions that are trivially dead, ccc -> fastcc
2454 LocalChange |= OptimizeFunctions(M);
2455
2456 // Optimize global_ctors list.
2457 if (GlobalCtors)
2458 LocalChange |= OptimizeGlobalCtorsList(GlobalCtors);
2459
2460 // Optimize non-address-taken globals.
2461 LocalChange |= OptimizeGlobalVars(M);
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002462
2463 // Resolve aliases, when possible.
2464 LocalChange |= ResolveAliases(M);
2465 Changed |= LocalChange;
Chris Lattner7a90b682004-10-07 04:16:33 +00002466 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002467
2468 // TODO: Move all global ctors functions to the end of the module for code
2469 // layout.
2470
Chris Lattner079236d2004-02-25 21:34:36 +00002471 return Changed;
2472}