blob: f881e089c2605064d15e4370dc6d279c587d92bb [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);
Duncan Sandsfc5940d2009-03-06 10:21:56 +000070 bool OptimizeGlobalAliases(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
Jay Foade3acf152009-06-09 21:37:11 +0000139// SafeToDestroyConstant - It is safe to destroy a constant iff it is only used
140// by constants itself. Note that constants cannot be cyclic, so this test is
141// pretty easy to implement recursively.
142//
143static bool SafeToDestroyConstant(Constant *C) {
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000144 if (isa<GlobalValue>(C)) return false;
145
Devang Patel743cdf82009-03-06 01:37:41 +0000146 for (Value::use_iterator UI = C->use_begin(), E = C->use_end(); UI != E; ++UI)
147 if (Constant *CU = dyn_cast<Constant>(*UI)) {
Jay Foade3acf152009-06-09 21:37:11 +0000148 if (!SafeToDestroyConstant(CU)) return false;
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000149 } else
150 return false;
151 return true;
152}
153
154
Chris Lattner7a90b682004-10-07 04:16:33 +0000155/// AnalyzeGlobal - Look at all uses of the global and fill in the GlobalStatus
156/// structure. If the global has its address taken, return true to indicate we
157/// can't do anything with it.
Chris Lattner079236d2004-02-25 21:34:36 +0000158///
Chris Lattner7a90b682004-10-07 04:16:33 +0000159static bool AnalyzeGlobal(Value *V, GlobalStatus &GS,
Chris Lattner5a6bb6a2008-12-16 07:34:30 +0000160 SmallPtrSet<PHINode*, 16> &PHIUsers) {
Chris Lattner079236d2004-02-25 21:34:36 +0000161 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
Chris Lattner96940cb2004-07-18 19:56:20 +0000162 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(*UI)) {
Chris Lattner553ca522005-06-15 21:11:48 +0000163 GS.HasNonInstructionUser = true;
164
Chris Lattner7a90b682004-10-07 04:16:33 +0000165 if (AnalyzeGlobal(CE, GS, PHIUsers)) return true;
Chris Lattner670c8892004-10-08 17:32:09 +0000166
Chris Lattner079236d2004-02-25 21:34:36 +0000167 } else if (Instruction *I = dyn_cast<Instruction>(*UI)) {
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +0000168 if (!GS.HasMultipleAccessingFunctions) {
169 Function *F = I->getParent()->getParent();
170 if (GS.AccessingFunction == 0)
171 GS.AccessingFunction = F;
172 else if (GS.AccessingFunction != F)
173 GS.HasMultipleAccessingFunctions = true;
174 }
Chris Lattnerc69d3c92008-01-29 19:01:37 +0000175 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattner7a90b682004-10-07 04:16:33 +0000176 GS.isLoaded = true;
Chris Lattnerc69d3c92008-01-29 19:01:37 +0000177 if (LI->isVolatile()) return true; // Don't hack on volatile loads.
Chris Lattner7a90b682004-10-07 04:16:33 +0000178 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Chris Lattner36025492004-10-07 06:01:25 +0000179 // Don't allow a store OF the address, only stores TO the address.
180 if (SI->getOperand(0) == V) return true;
181
Chris Lattnerc69d3c92008-01-29 19:01:37 +0000182 if (SI->isVolatile()) return true; // Don't hack on volatile stores.
183
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000184 // If this is a direct store to the global (i.e., the global is a scalar
185 // value, not an aggregate), keep more specific information about
186 // stores.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000187 if (GS.StoredType != GlobalStatus::isStored) {
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000188 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(SI->getOperand(1))){
Chris Lattnerbd38edf2004-11-14 20:50:30 +0000189 Value *StoredVal = SI->getOperand(0);
190 if (StoredVal == GV->getInitializer()) {
191 if (GS.StoredType < GlobalStatus::isInitializerStored)
192 GS.StoredType = GlobalStatus::isInitializerStored;
193 } else if (isa<LoadInst>(StoredVal) &&
194 cast<LoadInst>(StoredVal)->getOperand(0) == GV) {
195 // G = G
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000196 if (GS.StoredType < GlobalStatus::isInitializerStored)
197 GS.StoredType = GlobalStatus::isInitializerStored;
198 } else if (GS.StoredType < GlobalStatus::isStoredOnce) {
199 GS.StoredType = GlobalStatus::isStoredOnce;
Chris Lattnerbd38edf2004-11-14 20:50:30 +0000200 GS.StoredOnceValue = StoredVal;
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000201 } else if (GS.StoredType == GlobalStatus::isStoredOnce &&
Chris Lattnerbd38edf2004-11-14 20:50:30 +0000202 GS.StoredOnceValue == StoredVal) {
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000203 // noop.
204 } else {
205 GS.StoredType = GlobalStatus::isStored;
206 }
207 } else {
Chris Lattner7a90b682004-10-07 04:16:33 +0000208 GS.StoredType = GlobalStatus::isStored;
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000209 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000210 }
Chris Lattner35c81b02005-02-27 18:58:52 +0000211 } else if (isa<GetElementPtrInst>(I)) {
Chris Lattner7a90b682004-10-07 04:16:33 +0000212 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Chris Lattner35c81b02005-02-27 18:58:52 +0000213 } else if (isa<SelectInst>(I)) {
Chris Lattner7a90b682004-10-07 04:16:33 +0000214 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Chris Lattner7a90b682004-10-07 04:16:33 +0000215 } else if (PHINode *PN = dyn_cast<PHINode>(I)) {
216 // PHI nodes we can check just like select or GEP instructions, but we
217 // have to be careful about infinite recursion.
Chris Lattner5a6bb6a2008-12-16 07:34:30 +0000218 if (PHIUsers.insert(PN)) // Not already visited.
Chris Lattner7a90b682004-10-07 04:16:33 +0000219 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Chris Lattner25de4e52006-11-01 18:03:33 +0000220 GS.HasPHIUser = true;
Reid Spencere4d87aa2006-12-23 06:05:41 +0000221 } else if (isa<CmpInst>(I)) {
Chris Lattner8e108442009-03-08 03:37:35 +0000222 } else if (isa<MemTransferInst>(I)) {
Chris Lattner35c81b02005-02-27 18:58:52 +0000223 if (I->getOperand(1) == V)
224 GS.StoredType = GlobalStatus::isStored;
225 if (I->getOperand(2) == V)
226 GS.isLoaded = true;
Chris Lattner35c81b02005-02-27 18:58:52 +0000227 } else if (isa<MemSetInst>(I)) {
228 assert(I->getOperand(1) == V && "Memset only takes one pointer!");
229 GS.StoredType = GlobalStatus::isStored;
Chris Lattner7a90b682004-10-07 04:16:33 +0000230 } else {
231 return true; // Any other non-load instruction might take address!
Chris Lattner9ce30002004-07-20 03:58:07 +0000232 }
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000233 } else if (Constant *C = dyn_cast<Constant>(*UI)) {
Chris Lattner553ca522005-06-15 21:11:48 +0000234 GS.HasNonInstructionUser = true;
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000235 // We might have a dead and dangling constant hanging off of here.
Jay Foade3acf152009-06-09 21:37:11 +0000236 if (!SafeToDestroyConstant(C))
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000237 return true;
Chris Lattner079236d2004-02-25 21:34:36 +0000238 } else {
Chris Lattner553ca522005-06-15 21:11:48 +0000239 GS.HasNonInstructionUser = true;
240 // Otherwise must be some other user.
Chris Lattner079236d2004-02-25 21:34:36 +0000241 return true;
242 }
243
244 return false;
245}
246
Chris Lattner670c8892004-10-08 17:32:09 +0000247static Constant *getAggregateConstantElement(Constant *Agg, Constant *Idx) {
248 ConstantInt *CI = dyn_cast<ConstantInt>(Idx);
249 if (!CI) return 0;
Reid Spencerb83eb642006-10-20 07:07:24 +0000250 unsigned IdxV = CI->getZExtValue();
Chris Lattner7a90b682004-10-07 04:16:33 +0000251
Chris Lattner670c8892004-10-08 17:32:09 +0000252 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Agg)) {
253 if (IdxV < CS->getNumOperands()) return CS->getOperand(IdxV);
254 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Agg)) {
255 if (IdxV < CA->getNumOperands()) return CA->getOperand(IdxV);
Reid Spencer9d6565a2007-02-15 02:26:10 +0000256 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Agg)) {
Chris Lattner670c8892004-10-08 17:32:09 +0000257 if (IdxV < CP->getNumOperands()) return CP->getOperand(IdxV);
Chris Lattner7a7ed022004-10-16 18:09:00 +0000258 } else if (isa<ConstantAggregateZero>(Agg)) {
Chris Lattner670c8892004-10-08 17:32:09 +0000259 if (const StructType *STy = dyn_cast<StructType>(Agg->getType())) {
260 if (IdxV < STy->getNumElements())
261 return Constant::getNullValue(STy->getElementType(IdxV));
262 } else if (const SequentialType *STy =
263 dyn_cast<SequentialType>(Agg->getType())) {
264 return Constant::getNullValue(STy->getElementType());
265 }
Chris Lattner7a7ed022004-10-16 18:09:00 +0000266 } else if (isa<UndefValue>(Agg)) {
267 if (const StructType *STy = dyn_cast<StructType>(Agg->getType())) {
268 if (IdxV < STy->getNumElements())
269 return UndefValue::get(STy->getElementType(IdxV));
270 } else if (const SequentialType *STy =
271 dyn_cast<SequentialType>(Agg->getType())) {
272 return UndefValue::get(STy->getElementType());
273 }
Chris Lattner670c8892004-10-08 17:32:09 +0000274 }
275 return 0;
276}
Chris Lattner7a90b682004-10-07 04:16:33 +0000277
Chris Lattner7a90b682004-10-07 04:16:33 +0000278
Chris Lattnere47ba742004-10-06 20:57:02 +0000279/// CleanupConstantGlobalUsers - We just marked GV constant. Loop over all
280/// users of the global, cleaning up the obvious ones. This is largely just a
Chris Lattner031955d2004-10-10 16:43:46 +0000281/// quick scan over the use list to clean up the easy and obvious cruft. This
282/// returns true if it made a change.
283static bool CleanupConstantGlobalUsers(Value *V, Constant *Init) {
284 bool Changed = false;
Chris Lattner7a90b682004-10-07 04:16:33 +0000285 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;) {
286 User *U = *UI++;
Misha Brukmanfd939082005-04-21 23:48:37 +0000287
Chris Lattner7a90b682004-10-07 04:16:33 +0000288 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
Chris Lattner35c81b02005-02-27 18:58:52 +0000289 if (Init) {
290 // Replace the load with the initializer.
291 LI->replaceAllUsesWith(Init);
292 LI->eraseFromParent();
293 Changed = true;
294 }
Chris Lattner7a90b682004-10-07 04:16:33 +0000295 } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
Chris Lattnere47ba742004-10-06 20:57:02 +0000296 // Store must be unreachable or storing Init into the global.
Chris Lattner7a7ed022004-10-16 18:09:00 +0000297 SI->eraseFromParent();
Chris Lattner031955d2004-10-10 16:43:46 +0000298 Changed = true;
Chris Lattner7a90b682004-10-07 04:16:33 +0000299 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
300 if (CE->getOpcode() == Instruction::GetElementPtr) {
Chris Lattneraae4a1c2005-09-26 07:34:35 +0000301 Constant *SubInit = 0;
302 if (Init)
303 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
Chris Lattner35c81b02005-02-27 18:58:52 +0000304 Changed |= CleanupConstantGlobalUsers(CE, SubInit);
Reid Spencer3da59db2006-11-27 01:05:10 +0000305 } else if (CE->getOpcode() == Instruction::BitCast &&
Chris Lattner35c81b02005-02-27 18:58:52 +0000306 isa<PointerType>(CE->getType())) {
307 // Pointer cast, delete any stores and memsets to the global.
308 Changed |= CleanupConstantGlobalUsers(CE, 0);
309 }
310
311 if (CE->use_empty()) {
312 CE->destroyConstant();
313 Changed = true;
Chris Lattner7a90b682004-10-07 04:16:33 +0000314 }
315 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
Chris Lattner7b52fe72007-11-09 17:33:02 +0000316 // Do not transform "gepinst (gep constexpr (GV))" here, because forming
317 // "gepconstexpr (gep constexpr (GV))" will cause the two gep's to fold
318 // and will invalidate our notion of what Init is.
Chris Lattner19450242007-11-13 21:46:23 +0000319 Constant *SubInit = 0;
Chris Lattner7b52fe72007-11-09 17:33:02 +0000320 if (!isa<ConstantExpr>(GEP->getOperand(0))) {
321 ConstantExpr *CE =
322 dyn_cast_or_null<ConstantExpr>(ConstantFoldInstruction(GEP));
323 if (Init && CE && CE->getOpcode() == Instruction::GetElementPtr)
Chris Lattner19450242007-11-13 21:46:23 +0000324 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
Chris Lattner7b52fe72007-11-09 17:33:02 +0000325 }
Chris Lattner19450242007-11-13 21:46:23 +0000326 Changed |= CleanupConstantGlobalUsers(GEP, SubInit);
Chris Lattnerc4d81b02004-10-10 16:47:33 +0000327
Chris Lattner031955d2004-10-10 16:43:46 +0000328 if (GEP->use_empty()) {
Chris Lattner7a7ed022004-10-16 18:09:00 +0000329 GEP->eraseFromParent();
Chris Lattner031955d2004-10-10 16:43:46 +0000330 Changed = true;
331 }
Chris Lattner35c81b02005-02-27 18:58:52 +0000332 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U)) { // memset/cpy/mv
333 if (MI->getRawDest() == V) {
334 MI->eraseFromParent();
335 Changed = true;
336 }
337
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000338 } else if (Constant *C = dyn_cast<Constant>(U)) {
339 // If we have a chain of dead constantexprs or other things dangling from
340 // us, and if they are all dead, nuke them without remorse.
Jay Foade3acf152009-06-09 21:37:11 +0000341 if (SafeToDestroyConstant(C)) {
Devang Patel743cdf82009-03-06 01:37:41 +0000342 C->destroyConstant();
Chris Lattner35c81b02005-02-27 18:58:52 +0000343 // This could have invalidated UI, start over from scratch.
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000344 CleanupConstantGlobalUsers(V, Init);
Chris Lattner031955d2004-10-10 16:43:46 +0000345 return true;
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000346 }
Chris Lattnere47ba742004-10-06 20:57:02 +0000347 }
348 }
Chris Lattner031955d2004-10-10 16:43:46 +0000349 return Changed;
Chris Lattnere47ba742004-10-06 20:57:02 +0000350}
351
Chris Lattner941db492008-01-14 02:09:12 +0000352/// isSafeSROAElementUse - Return true if the specified instruction is a safe
353/// user of a derived expression from a global that we want to SROA.
354static bool isSafeSROAElementUse(Value *V) {
355 // We might have a dead and dangling constant hanging off of here.
356 if (Constant *C = dyn_cast<Constant>(V))
Jay Foade3acf152009-06-09 21:37:11 +0000357 return SafeToDestroyConstant(C);
Chris Lattner727c2102008-01-14 01:31:05 +0000358
Chris Lattner941db492008-01-14 02:09:12 +0000359 Instruction *I = dyn_cast<Instruction>(V);
360 if (!I) return false;
361
362 // Loads are ok.
363 if (isa<LoadInst>(I)) return true;
364
365 // Stores *to* the pointer are ok.
366 if (StoreInst *SI = dyn_cast<StoreInst>(I))
367 return SI->getOperand(0) != V;
368
369 // Otherwise, it must be a GEP.
370 GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I);
371 if (GEPI == 0) return false;
372
373 if (GEPI->getNumOperands() < 3 || !isa<Constant>(GEPI->getOperand(1)) ||
374 !cast<Constant>(GEPI->getOperand(1))->isNullValue())
375 return false;
376
377 for (Value::use_iterator I = GEPI->use_begin(), E = GEPI->use_end();
378 I != E; ++I)
379 if (!isSafeSROAElementUse(*I))
380 return false;
Chris Lattner727c2102008-01-14 01:31:05 +0000381 return true;
382}
383
Chris Lattner941db492008-01-14 02:09:12 +0000384
385/// IsUserOfGlobalSafeForSRA - U is a direct user of the specified global value.
386/// Look at it and its uses and decide whether it is safe to SROA this global.
387///
388static bool IsUserOfGlobalSafeForSRA(User *U, GlobalValue *GV) {
389 // The user of the global must be a GEP Inst or a ConstantExpr GEP.
390 if (!isa<GetElementPtrInst>(U) &&
391 (!isa<ConstantExpr>(U) ||
392 cast<ConstantExpr>(U)->getOpcode() != Instruction::GetElementPtr))
393 return false;
394
395 // Check to see if this ConstantExpr GEP is SRA'able. In particular, we
396 // don't like < 3 operand CE's, and we don't like non-constant integer
397 // indices. This enforces that all uses are 'gep GV, 0, C, ...' for some
398 // value of C.
399 if (U->getNumOperands() < 3 || !isa<Constant>(U->getOperand(1)) ||
400 !cast<Constant>(U->getOperand(1))->isNullValue() ||
401 !isa<ConstantInt>(U->getOperand(2)))
402 return false;
403
404 gep_type_iterator GEPI = gep_type_begin(U), E = gep_type_end(U);
405 ++GEPI; // Skip over the pointer index.
406
407 // If this is a use of an array allocation, do a bit more checking for sanity.
408 if (const ArrayType *AT = dyn_cast<ArrayType>(*GEPI)) {
409 uint64_t NumElements = AT->getNumElements();
410 ConstantInt *Idx = cast<ConstantInt>(U->getOperand(2));
411
412 // Check to make sure that index falls within the array. If not,
413 // something funny is going on, so we won't do the optimization.
414 //
415 if (Idx->getZExtValue() >= NumElements)
416 return false;
417
418 // We cannot scalar repl this level of the array unless any array
419 // sub-indices are in-range constants. In particular, consider:
420 // A[0][i]. We cannot know that the user isn't doing invalid things like
421 // allowing i to index an out-of-range subscript that accesses A[1].
422 //
423 // Scalar replacing *just* the outer index of the array is probably not
424 // going to be a win anyway, so just give up.
425 for (++GEPI; // Skip array index.
426 GEPI != E && (isa<ArrayType>(*GEPI) || isa<VectorType>(*GEPI));
427 ++GEPI) {
428 uint64_t NumElements;
429 if (const ArrayType *SubArrayTy = dyn_cast<ArrayType>(*GEPI))
430 NumElements = SubArrayTy->getNumElements();
431 else
432 NumElements = cast<VectorType>(*GEPI)->getNumElements();
433
434 ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPI.getOperand());
435 if (!IdxVal || IdxVal->getZExtValue() >= NumElements)
436 return false;
437 }
438 }
439
440 for (Value::use_iterator I = U->use_begin(), E = U->use_end(); I != E; ++I)
441 if (!isSafeSROAElementUse(*I))
442 return false;
443 return true;
444}
445
446/// GlobalUsersSafeToSRA - Look at all uses of the global and decide whether it
447/// is safe for us to perform this transformation.
448///
449static bool GlobalUsersSafeToSRA(GlobalValue *GV) {
450 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end();
451 UI != E; ++UI) {
452 if (!IsUserOfGlobalSafeForSRA(*UI, GV))
453 return false;
454 }
455 return true;
456}
457
458
Chris Lattner670c8892004-10-08 17:32:09 +0000459/// SRAGlobal - Perform scalar replacement of aggregates on the specified global
460/// variable. This opens the door for other optimizations by exposing the
461/// behavior of the program in a more fine-grained way. We have determined that
462/// this transformation is safe already. We return the first global variable we
463/// insert so that the caller can reprocess it.
Chris Lattner998182b2008-04-26 07:40:11 +0000464static GlobalVariable *SRAGlobal(GlobalVariable *GV, const TargetData &TD) {
Chris Lattner727c2102008-01-14 01:31:05 +0000465 // Make sure this global only has simple uses that we can SRA.
Chris Lattner941db492008-01-14 02:09:12 +0000466 if (!GlobalUsersSafeToSRA(GV))
Chris Lattner727c2102008-01-14 01:31:05 +0000467 return 0;
468
Rafael Espindolabb46f522009-01-15 20:18:42 +0000469 assert(GV->hasLocalLinkage() && !GV->isConstant());
Chris Lattner670c8892004-10-08 17:32:09 +0000470 Constant *Init = GV->getInitializer();
471 const Type *Ty = Init->getType();
Misha Brukmanfd939082005-04-21 23:48:37 +0000472
Chris Lattner670c8892004-10-08 17:32:09 +0000473 std::vector<GlobalVariable*> NewGlobals;
474 Module::GlobalListType &Globals = GV->getParent()->getGlobalList();
475
Chris Lattner998182b2008-04-26 07:40:11 +0000476 // Get the alignment of the global, either explicit or target-specific.
477 unsigned StartAlignment = GV->getAlignment();
478 if (StartAlignment == 0)
479 StartAlignment = TD.getABITypeAlignment(GV->getType());
480
Chris Lattner670c8892004-10-08 17:32:09 +0000481 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
482 NewGlobals.reserve(STy->getNumElements());
Chris Lattner998182b2008-04-26 07:40:11 +0000483 const StructLayout &Layout = *TD.getStructLayout(STy);
Chris Lattner670c8892004-10-08 17:32:09 +0000484 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
485 Constant *In = getAggregateConstantElement(Init,
Reid Spencerc5b206b2006-12-31 05:48:39 +0000486 ConstantInt::get(Type::Int32Ty, i));
Chris Lattner670c8892004-10-08 17:32:09 +0000487 assert(In && "Couldn't get element of initializer?");
488 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(i), false,
489 GlobalVariable::InternalLinkage,
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +0000490 In, GV->getName()+"."+utostr(i),
491 (Module *)NULL,
Matthijs Kooijmanbc1f9892008-07-17 11:59:53 +0000492 GV->isThreadLocal(),
493 GV->getType()->getAddressSpace());
Chris Lattner670c8892004-10-08 17:32:09 +0000494 Globals.insert(GV, NGV);
495 NewGlobals.push_back(NGV);
Chris Lattner998182b2008-04-26 07:40:11 +0000496
497 // Calculate the known alignment of the field. If the original aggregate
498 // had 256 byte alignment for example, something might depend on that:
499 // propagate info to each field.
500 uint64_t FieldOffset = Layout.getElementOffset(i);
501 unsigned NewAlign = (unsigned)MinAlign(StartAlignment, FieldOffset);
502 if (NewAlign > TD.getABITypeAlignment(STy->getElementType(i)))
503 NGV->setAlignment(NewAlign);
Chris Lattner670c8892004-10-08 17:32:09 +0000504 }
505 } else if (const SequentialType *STy = dyn_cast<SequentialType>(Ty)) {
506 unsigned NumElements = 0;
507 if (const ArrayType *ATy = dyn_cast<ArrayType>(STy))
508 NumElements = ATy->getNumElements();
Chris Lattner670c8892004-10-08 17:32:09 +0000509 else
Chris Lattner998182b2008-04-26 07:40:11 +0000510 NumElements = cast<VectorType>(STy)->getNumElements();
Chris Lattner670c8892004-10-08 17:32:09 +0000511
Chris Lattner1f21ef12005-02-23 16:53:04 +0000512 if (NumElements > 16 && GV->hasNUsesOrMore(16))
Chris Lattnerd514d822005-02-01 01:23:31 +0000513 return 0; // It's not worth it.
Chris Lattner670c8892004-10-08 17:32:09 +0000514 NewGlobals.reserve(NumElements);
Chris Lattner998182b2008-04-26 07:40:11 +0000515
Duncan Sands777d2302009-05-09 07:06:46 +0000516 uint64_t EltSize = TD.getTypeAllocSize(STy->getElementType());
Chris Lattner998182b2008-04-26 07:40:11 +0000517 unsigned EltAlign = TD.getABITypeAlignment(STy->getElementType());
Chris Lattner670c8892004-10-08 17:32:09 +0000518 for (unsigned i = 0, e = NumElements; i != e; ++i) {
519 Constant *In = getAggregateConstantElement(Init,
Reid Spencerc5b206b2006-12-31 05:48:39 +0000520 ConstantInt::get(Type::Int32Ty, i));
Chris Lattner670c8892004-10-08 17:32:09 +0000521 assert(In && "Couldn't get element of initializer?");
522
523 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(), false,
524 GlobalVariable::InternalLinkage,
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +0000525 In, GV->getName()+"."+utostr(i),
526 (Module *)NULL,
Matthijs Kooijmanbc1f9892008-07-17 11:59:53 +0000527 GV->isThreadLocal(),
528 GV->getType()->getAddressSpace());
Chris Lattner670c8892004-10-08 17:32:09 +0000529 Globals.insert(GV, NGV);
530 NewGlobals.push_back(NGV);
Chris Lattner998182b2008-04-26 07:40:11 +0000531
532 // Calculate the known alignment of the field. If the original aggregate
533 // had 256 byte alignment for example, something might depend on that:
534 // propagate info to each field.
535 unsigned NewAlign = (unsigned)MinAlign(StartAlignment, EltSize*i);
536 if (NewAlign > EltAlign)
537 NGV->setAlignment(NewAlign);
Chris Lattner670c8892004-10-08 17:32:09 +0000538 }
539 }
540
541 if (NewGlobals.empty())
542 return 0;
543
Bill Wendling0a81aac2006-11-26 10:02:32 +0000544 DOUT << "PERFORMING GLOBAL SRA ON: " << *GV;
Chris Lattner30ba5692004-10-11 05:54:41 +0000545
Reid Spencerc5b206b2006-12-31 05:48:39 +0000546 Constant *NullInt = Constant::getNullValue(Type::Int32Ty);
Chris Lattner670c8892004-10-08 17:32:09 +0000547
548 // Loop over all of the uses of the global, replacing the constantexpr geps,
549 // with smaller constantexpr geps or direct references.
550 while (!GV->use_empty()) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000551 User *GEP = GV->use_back();
552 assert(((isa<ConstantExpr>(GEP) &&
553 cast<ConstantExpr>(GEP)->getOpcode()==Instruction::GetElementPtr)||
554 isa<GetElementPtrInst>(GEP)) && "NonGEP CE's are not SRAable!");
Misha Brukmanfd939082005-04-21 23:48:37 +0000555
Chris Lattner670c8892004-10-08 17:32:09 +0000556 // Ignore the 1th operand, which has to be zero or else the program is quite
557 // broken (undefined). Get the 2nd operand, which is the structure or array
558 // index.
Reid Spencerb83eb642006-10-20 07:07:24 +0000559 unsigned Val = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
Chris Lattner670c8892004-10-08 17:32:09 +0000560 if (Val >= NewGlobals.size()) Val = 0; // Out of bound array access.
561
Chris Lattner30ba5692004-10-11 05:54:41 +0000562 Value *NewPtr = NewGlobals[Val];
Chris Lattner670c8892004-10-08 17:32:09 +0000563
564 // Form a shorter GEP if needed.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000565 if (GEP->getNumOperands() > 3) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000566 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEP)) {
Chris Lattner55eb1c42007-01-31 04:40:53 +0000567 SmallVector<Constant*, 8> Idxs;
Chris Lattner30ba5692004-10-11 05:54:41 +0000568 Idxs.push_back(NullInt);
569 for (unsigned i = 3, e = CE->getNumOperands(); i != e; ++i)
570 Idxs.push_back(CE->getOperand(i));
Chris Lattner55eb1c42007-01-31 04:40:53 +0000571 NewPtr = ConstantExpr::getGetElementPtr(cast<Constant>(NewPtr),
572 &Idxs[0], Idxs.size());
Chris Lattner30ba5692004-10-11 05:54:41 +0000573 } else {
574 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(GEP);
Chris Lattner699d1442007-01-31 19:59:55 +0000575 SmallVector<Value*, 8> Idxs;
Chris Lattner30ba5692004-10-11 05:54:41 +0000576 Idxs.push_back(NullInt);
577 for (unsigned i = 3, e = GEPI->getNumOperands(); i != e; ++i)
578 Idxs.push_back(GEPI->getOperand(i));
Gabor Greif051a9502008-04-06 20:25:17 +0000579 NewPtr = GetElementPtrInst::Create(NewPtr, Idxs.begin(), Idxs.end(),
580 GEPI->getName()+"."+utostr(Val), GEPI);
Chris Lattner30ba5692004-10-11 05:54:41 +0000581 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000582 }
Chris Lattner30ba5692004-10-11 05:54:41 +0000583 GEP->replaceAllUsesWith(NewPtr);
584
585 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(GEP))
Chris Lattner7a7ed022004-10-16 18:09:00 +0000586 GEPI->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +0000587 else
588 cast<ConstantExpr>(GEP)->destroyConstant();
Chris Lattner670c8892004-10-08 17:32:09 +0000589 }
590
Chris Lattnere40e2d12004-10-08 20:25:55 +0000591 // Delete the old global, now that it is dead.
592 Globals.erase(GV);
Chris Lattner670c8892004-10-08 17:32:09 +0000593 ++NumSRA;
Chris Lattner30ba5692004-10-11 05:54:41 +0000594
595 // Loop over the new globals array deleting any globals that are obviously
596 // dead. This can arise due to scalarization of a structure or an array that
597 // has elements that are dead.
598 unsigned FirstGlobal = 0;
599 for (unsigned i = 0, e = NewGlobals.size(); i != e; ++i)
600 if (NewGlobals[i]->use_empty()) {
601 Globals.erase(NewGlobals[i]);
602 if (FirstGlobal == i) ++FirstGlobal;
603 }
604
605 return FirstGlobal != NewGlobals.size() ? NewGlobals[FirstGlobal] : 0;
Chris Lattner670c8892004-10-08 17:32:09 +0000606}
607
Chris Lattner9b34a612004-10-09 21:48:45 +0000608/// AllUsesOfValueWillTrapIfNull - Return true if all users of the specified
Chris Lattner81686182007-09-13 16:30:19 +0000609/// value will trap if the value is dynamically null. PHIs keeps track of any
610/// phi nodes we've seen to avoid reprocessing them.
611static bool AllUsesOfValueWillTrapIfNull(Value *V,
612 SmallPtrSet<PHINode*, 8> &PHIs) {
Chris Lattner9b34a612004-10-09 21:48:45 +0000613 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
614 if (isa<LoadInst>(*UI)) {
615 // Will trap.
616 } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
617 if (SI->getOperand(0) == V) {
Bill Wendlinge8156192006-12-07 01:30:32 +0000618 //cerr << "NONTRAPPING USE: " << **UI;
Chris Lattner9b34a612004-10-09 21:48:45 +0000619 return false; // Storing the value.
620 }
621 } else if (CallInst *CI = dyn_cast<CallInst>(*UI)) {
622 if (CI->getOperand(0) != V) {
Bill Wendlinge8156192006-12-07 01:30:32 +0000623 //cerr << "NONTRAPPING USE: " << **UI;
Chris Lattner9b34a612004-10-09 21:48:45 +0000624 return false; // Not calling the ptr
625 }
626 } else if (InvokeInst *II = dyn_cast<InvokeInst>(*UI)) {
627 if (II->getOperand(0) != V) {
Bill Wendlinge8156192006-12-07 01:30:32 +0000628 //cerr << "NONTRAPPING USE: " << **UI;
Chris Lattner9b34a612004-10-09 21:48:45 +0000629 return false; // Not calling the ptr
630 }
Chris Lattner81686182007-09-13 16:30:19 +0000631 } else if (BitCastInst *CI = dyn_cast<BitCastInst>(*UI)) {
632 if (!AllUsesOfValueWillTrapIfNull(CI, PHIs)) return false;
Chris Lattner9b34a612004-10-09 21:48:45 +0000633 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(*UI)) {
Chris Lattner81686182007-09-13 16:30:19 +0000634 if (!AllUsesOfValueWillTrapIfNull(GEPI, PHIs)) return false;
635 } else if (PHINode *PN = dyn_cast<PHINode>(*UI)) {
636 // If we've already seen this phi node, ignore it, it has already been
637 // checked.
638 if (PHIs.insert(PN))
639 return AllUsesOfValueWillTrapIfNull(PN, PHIs);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000640 } else if (isa<ICmpInst>(*UI) &&
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000641 isa<ConstantPointerNull>(UI->getOperand(1))) {
642 // Ignore setcc X, null
Chris Lattner9b34a612004-10-09 21:48:45 +0000643 } else {
Bill Wendlinge8156192006-12-07 01:30:32 +0000644 //cerr << "NONTRAPPING USE: " << **UI;
Chris Lattner9b34a612004-10-09 21:48:45 +0000645 return false;
646 }
647 return true;
648}
649
650/// AllUsesOfLoadedValueWillTrapIfNull - Return true if all uses of any loads
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000651/// from GV will trap if the loaded value is null. Note that this also permits
652/// comparisons of the loaded value against null, as a special case.
Chris Lattner9b34a612004-10-09 21:48:45 +0000653static bool AllUsesOfLoadedValueWillTrapIfNull(GlobalVariable *GV) {
654 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI!=E; ++UI)
655 if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
Chris Lattner81686182007-09-13 16:30:19 +0000656 SmallPtrSet<PHINode*, 8> PHIs;
657 if (!AllUsesOfValueWillTrapIfNull(LI, PHIs))
Chris Lattner9b34a612004-10-09 21:48:45 +0000658 return false;
659 } else if (isa<StoreInst>(*UI)) {
660 // Ignore stores to the global.
661 } else {
662 // We don't know or understand this user, bail out.
Bill Wendlinge8156192006-12-07 01:30:32 +0000663 //cerr << "UNKNOWN USER OF GLOBAL!: " << **UI;
Chris Lattner9b34a612004-10-09 21:48:45 +0000664 return false;
665 }
666
667 return true;
668}
669
Chris Lattner708148e2004-10-10 23:14:11 +0000670static bool OptimizeAwayTrappingUsesOfValue(Value *V, Constant *NewV) {
671 bool Changed = false;
672 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ) {
673 Instruction *I = cast<Instruction>(*UI++);
674 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
675 LI->setOperand(0, NewV);
676 Changed = true;
677 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
678 if (SI->getOperand(1) == V) {
679 SI->setOperand(1, NewV);
680 Changed = true;
681 }
682 } else if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
683 if (I->getOperand(0) == V) {
684 // Calling through the pointer! Turn into a direct call, but be careful
685 // that the pointer is not also being passed as an argument.
686 I->setOperand(0, NewV);
687 Changed = true;
688 bool PassedAsArg = false;
689 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i)
690 if (I->getOperand(i) == V) {
691 PassedAsArg = true;
692 I->setOperand(i, NewV);
693 }
694
695 if (PassedAsArg) {
696 // Being passed as an argument also. Be careful to not invalidate UI!
697 UI = V->use_begin();
698 }
699 }
700 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
701 Changed |= OptimizeAwayTrappingUsesOfValue(CI,
Chris Lattner6e8fbad2006-11-30 17:32:29 +0000702 ConstantExpr::getCast(CI->getOpcode(),
703 NewV, CI->getType()));
Chris Lattner708148e2004-10-10 23:14:11 +0000704 if (CI->use_empty()) {
705 Changed = true;
Chris Lattner7a7ed022004-10-16 18:09:00 +0000706 CI->eraseFromParent();
Chris Lattner708148e2004-10-10 23:14:11 +0000707 }
708 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
709 // Should handle GEP here.
Chris Lattner55eb1c42007-01-31 04:40:53 +0000710 SmallVector<Constant*, 8> Idxs;
711 Idxs.reserve(GEPI->getNumOperands()-1);
Gabor Greif5e463212008-05-29 01:59:18 +0000712 for (User::op_iterator i = GEPI->op_begin() + 1, e = GEPI->op_end();
713 i != e; ++i)
714 if (Constant *C = dyn_cast<Constant>(*i))
Chris Lattner55eb1c42007-01-31 04:40:53 +0000715 Idxs.push_back(C);
Chris Lattner708148e2004-10-10 23:14:11 +0000716 else
717 break;
Chris Lattner55eb1c42007-01-31 04:40:53 +0000718 if (Idxs.size() == GEPI->getNumOperands()-1)
Chris Lattner708148e2004-10-10 23:14:11 +0000719 Changed |= OptimizeAwayTrappingUsesOfValue(GEPI,
Chris Lattner55eb1c42007-01-31 04:40:53 +0000720 ConstantExpr::getGetElementPtr(NewV, &Idxs[0],
721 Idxs.size()));
Chris Lattner708148e2004-10-10 23:14:11 +0000722 if (GEPI->use_empty()) {
723 Changed = true;
Chris Lattner7a7ed022004-10-16 18:09:00 +0000724 GEPI->eraseFromParent();
Chris Lattner708148e2004-10-10 23:14:11 +0000725 }
726 }
727 }
728
729 return Changed;
730}
731
732
733/// OptimizeAwayTrappingUsesOfLoads - The specified global has only one non-null
734/// value stored into it. If there are uses of the loaded value that would trap
735/// if the loaded value is dynamically null, then we know that they cannot be
736/// reachable with a null optimize away the load.
737static bool OptimizeAwayTrappingUsesOfLoads(GlobalVariable *GV, Constant *LV) {
Chris Lattner708148e2004-10-10 23:14:11 +0000738 bool Changed = false;
739
Chris Lattner92c6bd22009-01-14 00:12:58 +0000740 // Keep track of whether we are able to remove all the uses of the global
741 // other than the store that defines it.
742 bool AllNonStoreUsesGone = true;
743
Chris Lattner708148e2004-10-10 23:14:11 +0000744 // Replace all uses of loads with uses of uses of the stored value.
Chris Lattner92c6bd22009-01-14 00:12:58 +0000745 for (Value::use_iterator GUI = GV->use_begin(), E = GV->use_end(); GUI != E;){
746 User *GlobalUser = *GUI++;
747 if (LoadInst *LI = dyn_cast<LoadInst>(GlobalUser)) {
Chris Lattner708148e2004-10-10 23:14:11 +0000748 Changed |= OptimizeAwayTrappingUsesOfValue(LI, LV);
Chris Lattner92c6bd22009-01-14 00:12:58 +0000749 // If we were able to delete all uses of the loads
750 if (LI->use_empty()) {
751 LI->eraseFromParent();
752 Changed = true;
753 } else {
754 AllNonStoreUsesGone = false;
755 }
756 } else if (isa<StoreInst>(GlobalUser)) {
757 // Ignore the store that stores "LV" to the global.
758 assert(GlobalUser->getOperand(1) == GV &&
759 "Must be storing *to* the global");
Chris Lattner708148e2004-10-10 23:14:11 +0000760 } else {
Chris Lattner92c6bd22009-01-14 00:12:58 +0000761 AllNonStoreUsesGone = false;
762
763 // If we get here we could have other crazy uses that are transitively
764 // loaded.
765 assert((isa<PHINode>(GlobalUser) || isa<SelectInst>(GlobalUser) ||
766 isa<ConstantExpr>(GlobalUser)) && "Only expect load and stores!");
Chris Lattner708148e2004-10-10 23:14:11 +0000767 }
Chris Lattner92c6bd22009-01-14 00:12:58 +0000768 }
Chris Lattner708148e2004-10-10 23:14:11 +0000769
770 if (Changed) {
Bill Wendling0a81aac2006-11-26 10:02:32 +0000771 DOUT << "OPTIMIZED LOADS FROM STORED ONCE POINTER: " << *GV;
Chris Lattner708148e2004-10-10 23:14:11 +0000772 ++NumGlobUses;
773 }
774
Chris Lattner708148e2004-10-10 23:14:11 +0000775 // If we nuked all of the loads, then none of the stores are needed either,
776 // nor is the global.
Chris Lattner92c6bd22009-01-14 00:12:58 +0000777 if (AllNonStoreUsesGone) {
Bill Wendling0a81aac2006-11-26 10:02:32 +0000778 DOUT << " *** GLOBAL NOW DEAD!\n";
Chris Lattner708148e2004-10-10 23:14:11 +0000779 CleanupConstantGlobalUsers(GV, 0);
780 if (GV->use_empty()) {
Chris Lattner7a7ed022004-10-16 18:09:00 +0000781 GV->eraseFromParent();
Chris Lattner708148e2004-10-10 23:14:11 +0000782 ++NumDeleted;
783 }
784 Changed = true;
785 }
786 return Changed;
787}
788
Chris Lattner30ba5692004-10-11 05:54:41 +0000789/// ConstantPropUsersOf - Walk the use list of V, constant folding all of the
790/// instructions that are foldable.
791static void ConstantPropUsersOf(Value *V) {
792 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; )
793 if (Instruction *I = dyn_cast<Instruction>(*UI++))
794 if (Constant *NewC = ConstantFoldInstruction(I)) {
795 I->replaceAllUsesWith(NewC);
796
Chris Lattnerd514d822005-02-01 01:23:31 +0000797 // Advance UI to the next non-I use to avoid invalidating it!
798 // Instructions could multiply use V.
799 while (UI != E && *UI == I)
Chris Lattner30ba5692004-10-11 05:54:41 +0000800 ++UI;
Chris Lattnerd514d822005-02-01 01:23:31 +0000801 I->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +0000802 }
803}
804
805/// OptimizeGlobalAddressOfMalloc - This function takes the specified global
806/// variable, and transforms the program as if it always contained the result of
807/// the specified malloc. Because it is always the result of the specified
808/// malloc, there is no reason to actually DO the malloc. Instead, turn the
Chris Lattner6e8fbad2006-11-30 17:32:29 +0000809/// malloc into a global, and any loads of GV as uses of the new global.
Chris Lattner30ba5692004-10-11 05:54:41 +0000810static GlobalVariable *OptimizeGlobalAddressOfMalloc(GlobalVariable *GV,
811 MallocInst *MI) {
Bill Wendling0a81aac2006-11-26 10:02:32 +0000812 DOUT << "PROMOTING MALLOC GLOBAL: " << *GV << " MALLOC = " << *MI;
Chris Lattner30ba5692004-10-11 05:54:41 +0000813 ConstantInt *NElements = cast<ConstantInt>(MI->getArraySize());
814
Reid Spencerb83eb642006-10-20 07:07:24 +0000815 if (NElements->getZExtValue() != 1) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000816 // If we have an array allocation, transform it to a single element
817 // allocation to make the code below simpler.
818 Type *NewTy = ArrayType::get(MI->getAllocatedType(),
Reid Spencerb83eb642006-10-20 07:07:24 +0000819 NElements->getZExtValue());
Chris Lattner30ba5692004-10-11 05:54:41 +0000820 MallocInst *NewMI =
Reid Spencerc5b206b2006-12-31 05:48:39 +0000821 new MallocInst(NewTy, Constant::getNullValue(Type::Int32Ty),
Nate Begeman14b05292005-11-05 09:21:28 +0000822 MI->getAlignment(), MI->getName(), MI);
Chris Lattner699d1442007-01-31 19:59:55 +0000823 Value* Indices[2];
824 Indices[0] = Indices[1] = Constant::getNullValue(Type::Int32Ty);
Gabor Greif051a9502008-04-06 20:25:17 +0000825 Value *NewGEP = GetElementPtrInst::Create(NewMI, Indices, Indices + 2,
826 NewMI->getName()+".el0", MI);
Chris Lattner30ba5692004-10-11 05:54:41 +0000827 MI->replaceAllUsesWith(NewGEP);
Chris Lattner7a7ed022004-10-16 18:09:00 +0000828 MI->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +0000829 MI = NewMI;
830 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000831
Chris Lattner7a7ed022004-10-16 18:09:00 +0000832 // Create the new global variable. The contents of the malloc'd memory is
833 // undefined, so initialize with an undef value.
834 Constant *Init = UndefValue::get(MI->getAllocatedType());
Chris Lattner30ba5692004-10-11 05:54:41 +0000835 GlobalVariable *NewGV = new GlobalVariable(MI->getAllocatedType(), false,
836 GlobalValue::InternalLinkage, Init,
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +0000837 GV->getName()+".body",
838 (Module *)NULL,
839 GV->isThreadLocal());
Chris Lattner998182b2008-04-26 07:40:11 +0000840 // FIXME: This new global should have the alignment returned by malloc. Code
841 // could depend on malloc returning large alignment (on the mac, 16 bytes) but
842 // this would only guarantee some lower alignment.
Chris Lattner30ba5692004-10-11 05:54:41 +0000843 GV->getParent()->getGlobalList().insert(GV, NewGV);
Misha Brukmanfd939082005-04-21 23:48:37 +0000844
Chris Lattner30ba5692004-10-11 05:54:41 +0000845 // Anything that used the malloc now uses the global directly.
846 MI->replaceAllUsesWith(NewGV);
Chris Lattner30ba5692004-10-11 05:54:41 +0000847
848 Constant *RepValue = NewGV;
849 if (NewGV->getType() != GV->getType()->getElementType())
Reid Spencerd977d862006-12-12 23:36:14 +0000850 RepValue = ConstantExpr::getBitCast(RepValue,
851 GV->getType()->getElementType());
Chris Lattner30ba5692004-10-11 05:54:41 +0000852
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000853 // If there is a comparison against null, we will insert a global bool to
854 // keep track of whether the global was initialized yet or not.
Misha Brukmanfd939082005-04-21 23:48:37 +0000855 GlobalVariable *InitBool =
Reid Spencer4fe16d62007-01-11 18:21:29 +0000856 new GlobalVariable(Type::Int1Ty, false, GlobalValue::InternalLinkage,
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +0000857 ConstantInt::getFalse(), GV->getName()+".init",
858 (Module *)NULL, GV->isThreadLocal());
Chris Lattnerbc965b92004-12-02 06:25:58 +0000859 bool InitBoolUsed = false;
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000860
Chris Lattner30ba5692004-10-11 05:54:41 +0000861 // Loop over all uses of GV, processing them in turn.
Chris Lattnerbc965b92004-12-02 06:25:58 +0000862 std::vector<StoreInst*> Stores;
Chris Lattner30ba5692004-10-11 05:54:41 +0000863 while (!GV->use_empty())
864 if (LoadInst *LI = dyn_cast<LoadInst>(GV->use_back())) {
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000865 while (!LI->use_empty()) {
Chris Lattnerd514d822005-02-01 01:23:31 +0000866 Use &LoadUse = LI->use_begin().getUse();
Reid Spencere4d87aa2006-12-23 06:05:41 +0000867 if (!isa<ICmpInst>(LoadUse.getUser()))
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000868 LoadUse = RepValue;
869 else {
Reid Spencere4d87aa2006-12-23 06:05:41 +0000870 ICmpInst *CI = cast<ICmpInst>(LoadUse.getUser());
871 // Replace the cmp X, 0 with a use of the bool value.
872 Value *LV = new LoadInst(InitBool, InitBool->getName()+".val", CI);
Chris Lattnerbc965b92004-12-02 06:25:58 +0000873 InitBoolUsed = true;
Reid Spencere4d87aa2006-12-23 06:05:41 +0000874 switch (CI->getPredicate()) {
875 default: assert(0 && "Unknown ICmp Predicate!");
876 case ICmpInst::ICMP_ULT:
877 case ICmpInst::ICMP_SLT:
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000878 LV = ConstantInt::getFalse(); // X < null -> always false
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000879 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +0000880 case ICmpInst::ICMP_ULE:
881 case ICmpInst::ICMP_SLE:
882 case ICmpInst::ICMP_EQ:
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000883 LV = BinaryOperator::CreateNot(LV, "notinit", CI);
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000884 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +0000885 case ICmpInst::ICMP_NE:
886 case ICmpInst::ICMP_UGE:
887 case ICmpInst::ICMP_SGE:
888 case ICmpInst::ICMP_UGT:
889 case ICmpInst::ICMP_SGT:
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000890 break; // no change.
891 }
Reid Spencere4d87aa2006-12-23 06:05:41 +0000892 CI->replaceAllUsesWith(LV);
893 CI->eraseFromParent();
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000894 }
895 }
Chris Lattner7a7ed022004-10-16 18:09:00 +0000896 LI->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +0000897 } else {
898 StoreInst *SI = cast<StoreInst>(GV->use_back());
Chris Lattnerbc965b92004-12-02 06:25:58 +0000899 // The global is initialized when the store to it occurs.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000900 new StoreInst(ConstantInt::getTrue(), InitBool, SI);
Chris Lattner7a7ed022004-10-16 18:09:00 +0000901 SI->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +0000902 }
903
Chris Lattnerbc965b92004-12-02 06:25:58 +0000904 // If the initialization boolean was used, insert it, otherwise delete it.
905 if (!InitBoolUsed) {
906 while (!InitBool->use_empty()) // Delete initializations
907 cast<Instruction>(InitBool->use_back())->eraseFromParent();
908 delete InitBool;
909 } else
910 GV->getParent()->getGlobalList().insert(GV, InitBool);
911
912
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000913 // Now the GV is dead, nuke it and the malloc.
Chris Lattner7a7ed022004-10-16 18:09:00 +0000914 GV->eraseFromParent();
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000915 MI->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +0000916
917 // To further other optimizations, loop over all users of NewGV and try to
918 // constant prop them. This will promote GEP instructions with constant
919 // indices into GEP constant-exprs, which will allow global-opt to hack on it.
920 ConstantPropUsersOf(NewGV);
921 if (RepValue != NewGV)
922 ConstantPropUsersOf(RepValue);
923
924 return NewGV;
925}
Chris Lattner708148e2004-10-10 23:14:11 +0000926
Chris Lattnerfa07e4f2004-12-02 07:11:07 +0000927/// ValueIsOnlyUsedLocallyOrStoredToOneGlobal - Scan the use-list of V checking
928/// to make sure that there are no complex uses of V. We permit simple things
929/// like dereferencing the pointer, but not storing through the address, unless
930/// it is to the specified global.
931static bool ValueIsOnlyUsedLocallyOrStoredToOneGlobal(Instruction *V,
Chris Lattnerc451f9c2007-09-13 16:37:20 +0000932 GlobalVariable *GV,
933 SmallPtrSet<PHINode*, 8> &PHIs) {
Chris Lattner49b6d4a2008-12-15 21:08:54 +0000934 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;++UI){
Jay Foad0906b1b2009-06-06 17:49:35 +0000935 Instruction *Inst = cast<Instruction>(*UI);
Chris Lattner49b6d4a2008-12-15 21:08:54 +0000936
937 if (isa<LoadInst>(Inst) || isa<CmpInst>(Inst)) {
938 continue; // Fine, ignore.
939 }
940
941 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
Chris Lattnerfa07e4f2004-12-02 07:11:07 +0000942 if (SI->getOperand(0) == V && SI->getOperand(1) != GV)
943 return false; // Storing the pointer itself... bad.
Chris Lattner49b6d4a2008-12-15 21:08:54 +0000944 continue; // Otherwise, storing through it, or storing into GV... fine.
945 }
946
947 if (isa<GetElementPtrInst>(Inst)) {
948 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(Inst, GV, PHIs))
Chris Lattnerfa07e4f2004-12-02 07:11:07 +0000949 return false;
Chris Lattner49b6d4a2008-12-15 21:08:54 +0000950 continue;
951 }
952
953 if (PHINode *PN = dyn_cast<PHINode>(Inst)) {
Chris Lattnerc451f9c2007-09-13 16:37:20 +0000954 // PHIs are ok if all uses are ok. Don't infinitely recurse through PHI
955 // cycles.
956 if (PHIs.insert(PN))
Chris Lattner5e6e4942007-09-14 03:41:21 +0000957 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(PN, GV, PHIs))
958 return false;
Chris Lattner49b6d4a2008-12-15 21:08:54 +0000959 continue;
Chris Lattnerfa07e4f2004-12-02 07:11:07 +0000960 }
Chris Lattner49b6d4a2008-12-15 21:08:54 +0000961
962 if (BitCastInst *BCI = dyn_cast<BitCastInst>(Inst)) {
963 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(BCI, GV, PHIs))
964 return false;
965 continue;
966 }
967
968 return false;
969 }
Chris Lattnerfa07e4f2004-12-02 07:11:07 +0000970 return true;
Chris Lattnerfa07e4f2004-12-02 07:11:07 +0000971}
972
Chris Lattner86395032006-09-30 23:32:09 +0000973/// ReplaceUsesOfMallocWithGlobal - The Alloc pointer is stored into GV
974/// somewhere. Transform all uses of the allocation into loads from the
975/// global and uses of the resultant pointer. Further, delete the store into
976/// GV. This assumes that these value pass the
977/// 'ValueIsOnlyUsedLocallyOrStoredToOneGlobal' predicate.
978static void ReplaceUsesOfMallocWithGlobal(Instruction *Alloc,
979 GlobalVariable *GV) {
980 while (!Alloc->use_empty()) {
Chris Lattnera637a8b2007-09-13 18:00:31 +0000981 Instruction *U = cast<Instruction>(*Alloc->use_begin());
982 Instruction *InsertPt = U;
Chris Lattner86395032006-09-30 23:32:09 +0000983 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
984 // If this is the store of the allocation into the global, remove it.
985 if (SI->getOperand(1) == GV) {
986 SI->eraseFromParent();
987 continue;
988 }
Chris Lattnera637a8b2007-09-13 18:00:31 +0000989 } else if (PHINode *PN = dyn_cast<PHINode>(U)) {
990 // Insert the load in the corresponding predecessor, not right before the
991 // PHI.
Gabor Greifa36791d2009-01-23 19:40:15 +0000992 InsertPt = PN->getIncomingBlock(Alloc->use_begin())->getTerminator();
Chris Lattner101f44e2008-12-15 21:44:34 +0000993 } else if (isa<BitCastInst>(U)) {
994 // Must be bitcast between the malloc and store to initialize the global.
995 ReplaceUsesOfMallocWithGlobal(U, GV);
996 U->eraseFromParent();
997 continue;
998 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
999 // If this is a "GEP bitcast" and the user is a store to the global, then
1000 // just process it as a bitcast.
1001 if (GEPI->hasAllZeroIndices() && GEPI->hasOneUse())
1002 if (StoreInst *SI = dyn_cast<StoreInst>(GEPI->use_back()))
1003 if (SI->getOperand(1) == GV) {
1004 // Must be bitcast GEP between the malloc and store to initialize
1005 // the global.
1006 ReplaceUsesOfMallocWithGlobal(GEPI, GV);
1007 GEPI->eraseFromParent();
1008 continue;
1009 }
Chris Lattner86395032006-09-30 23:32:09 +00001010 }
Chris Lattner101f44e2008-12-15 21:44:34 +00001011
Chris Lattner86395032006-09-30 23:32:09 +00001012 // Insert a load from the global, and use it instead of the malloc.
Chris Lattnera637a8b2007-09-13 18:00:31 +00001013 Value *NL = new LoadInst(GV, GV->getName()+".val", InsertPt);
Chris Lattner86395032006-09-30 23:32:09 +00001014 U->replaceUsesOfWith(Alloc, NL);
1015 }
1016}
1017
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001018/// LoadUsesSimpleEnoughForHeapSRA - Verify that all uses of V (a load, or a phi
1019/// of a load) are simple enough to perform heap SRA on. This permits GEP's
1020/// that index through the array and struct field, icmps of null, and PHIs.
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001021static bool LoadUsesSimpleEnoughForHeapSRA(Value *V,
Evan Cheng5d163962009-06-02 00:56:07 +00001022 SmallPtrSet<PHINode*, 32> &LoadUsingPHIs,
1023 SmallPtrSet<PHINode*, 32> &LoadUsingPHIsPerLoad) {
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001024 // We permit two users of the load: setcc comparing against the null
1025 // pointer, and a getelementptr of a specific form.
1026 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;++UI){
1027 Instruction *User = cast<Instruction>(*UI);
1028
1029 // Comparison against null is ok.
1030 if (ICmpInst *ICI = dyn_cast<ICmpInst>(User)) {
1031 if (!isa<ConstantPointerNull>(ICI->getOperand(1)))
1032 return false;
1033 continue;
1034 }
1035
1036 // getelementptr is also ok, but only a simple form.
1037 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
1038 // Must index into the array and into the struct.
1039 if (GEPI->getNumOperands() < 3)
1040 return false;
1041
1042 // Otherwise the GEP is ok.
1043 continue;
1044 }
1045
1046 if (PHINode *PN = dyn_cast<PHINode>(User)) {
Evan Cheng5d163962009-06-02 00:56:07 +00001047 if (!LoadUsingPHIsPerLoad.insert(PN))
1048 // This means some phi nodes are dependent on each other.
1049 // Avoid infinite looping!
1050 return false;
1051 if (!LoadUsingPHIs.insert(PN))
1052 // If we have already analyzed this PHI, then it is safe.
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001053 continue;
1054
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001055 // Make sure all uses of the PHI are simple enough to transform.
Evan Cheng5d163962009-06-02 00:56:07 +00001056 if (!LoadUsesSimpleEnoughForHeapSRA(PN,
1057 LoadUsingPHIs, LoadUsingPHIsPerLoad))
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001058 return false;
1059
1060 continue;
Chris Lattner86395032006-09-30 23:32:09 +00001061 }
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001062
1063 // Otherwise we don't know what this is, not ok.
1064 return false;
1065 }
1066
1067 return true;
1068}
1069
1070
1071/// AllGlobalLoadUsesSimpleEnoughForHeapSRA - If all users of values loaded from
1072/// GV are simple enough to perform HeapSRA, return true.
1073static bool AllGlobalLoadUsesSimpleEnoughForHeapSRA(GlobalVariable *GV,
1074 MallocInst *MI) {
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001075 SmallPtrSet<PHINode*, 32> LoadUsingPHIs;
Evan Cheng5d163962009-06-02 00:56:07 +00001076 SmallPtrSet<PHINode*, 32> LoadUsingPHIsPerLoad;
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001077 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI != E;
1078 ++UI)
Evan Cheng5d163962009-06-02 00:56:07 +00001079 if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
1080 if (!LoadUsesSimpleEnoughForHeapSRA(LI, LoadUsingPHIs,
1081 LoadUsingPHIsPerLoad))
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001082 return false;
Evan Cheng5d163962009-06-02 00:56:07 +00001083 LoadUsingPHIsPerLoad.clear();
1084 }
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001085
1086 // If we reach here, we know that all uses of the loads and transitive uses
1087 // (through PHI nodes) are simple enough to transform. However, we don't know
1088 // that all inputs the to the PHI nodes are in the same equivalence sets.
1089 // Check to verify that all operands of the PHIs are either PHIS that can be
1090 // transformed, loads from GV, or MI itself.
1091 for (SmallPtrSet<PHINode*, 32>::iterator I = LoadUsingPHIs.begin(),
1092 E = LoadUsingPHIs.end(); I != E; ++I) {
1093 PHINode *PN = *I;
1094 for (unsigned op = 0, e = PN->getNumIncomingValues(); op != e; ++op) {
1095 Value *InVal = PN->getIncomingValue(op);
1096
1097 // PHI of the stored value itself is ok.
1098 if (InVal == MI) continue;
1099
1100 if (PHINode *InPN = dyn_cast<PHINode>(InVal)) {
1101 // One of the PHIs in our set is (optimistically) ok.
1102 if (LoadUsingPHIs.count(InPN))
1103 continue;
1104 return false;
1105 }
1106
1107 // Load from GV is ok.
1108 if (LoadInst *LI = dyn_cast<LoadInst>(InVal))
1109 if (LI->getOperand(0) == GV)
1110 continue;
1111
1112 // UNDEF? NULL?
1113
1114 // Anything else is rejected.
1115 return false;
1116 }
1117 }
1118
Chris Lattner86395032006-09-30 23:32:09 +00001119 return true;
1120}
1121
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001122static Value *GetHeapSROAValue(Value *V, unsigned FieldNo,
1123 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
1124 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
1125 std::vector<Value*> &FieldVals = InsertedScalarizedValues[V];
1126
1127 if (FieldNo >= FieldVals.size())
1128 FieldVals.resize(FieldNo+1);
1129
1130 // If we already have this value, just reuse the previously scalarized
1131 // version.
1132 if (Value *FieldVal = FieldVals[FieldNo])
1133 return FieldVal;
1134
1135 // Depending on what instruction this is, we have several cases.
1136 Value *Result;
1137 if (LoadInst *LI = dyn_cast<LoadInst>(V)) {
1138 // This is a scalarized version of the load from the global. Just create
1139 // a new Load of the scalarized global.
1140 Result = new LoadInst(GetHeapSROAValue(LI->getOperand(0), FieldNo,
1141 InsertedScalarizedValues,
1142 PHIsToRewrite),
1143 LI->getName()+".f" + utostr(FieldNo), LI);
1144 } else if (PHINode *PN = dyn_cast<PHINode>(V)) {
1145 // PN's type is pointer to struct. Make a new PHI of pointer to struct
1146 // field.
1147 const StructType *ST =
1148 cast<StructType>(cast<PointerType>(PN->getType())->getElementType());
1149
1150 Result =PHINode::Create(PointerType::getUnqual(ST->getElementType(FieldNo)),
1151 PN->getName()+".f"+utostr(FieldNo), PN);
1152 PHIsToRewrite.push_back(std::make_pair(PN, FieldNo));
1153 } else {
1154 assert(0 && "Unknown usable value");
1155 Result = 0;
1156 }
1157
1158 return FieldVals[FieldNo] = Result;
Chris Lattnera637a8b2007-09-13 18:00:31 +00001159}
1160
Chris Lattner330245e2007-09-13 17:29:05 +00001161/// RewriteHeapSROALoadUser - Given a load instruction and a value derived from
1162/// the load, rewrite the derived value to use the HeapSRoA'd load.
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001163static void RewriteHeapSROALoadUser(Instruction *LoadUser,
1164 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
1165 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
Chris Lattner330245e2007-09-13 17:29:05 +00001166 // If this is a comparison against null, handle it.
1167 if (ICmpInst *SCI = dyn_cast<ICmpInst>(LoadUser)) {
1168 assert(isa<ConstantPointerNull>(SCI->getOperand(1)));
1169 // If we have a setcc of the loaded pointer, we can use a setcc of any
1170 // field.
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001171 Value *NPtr = GetHeapSROAValue(SCI->getOperand(0), 0,
1172 InsertedScalarizedValues, PHIsToRewrite);
Chris Lattner330245e2007-09-13 17:29:05 +00001173
1174 Value *New = new ICmpInst(SCI->getPredicate(), NPtr,
1175 Constant::getNullValue(NPtr->getType()),
1176 SCI->getName(), SCI);
1177 SCI->replaceAllUsesWith(New);
1178 SCI->eraseFromParent();
1179 return;
1180 }
1181
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001182 // Handle 'getelementptr Ptr, Idx, i32 FieldNo ...'
Chris Lattnera637a8b2007-09-13 18:00:31 +00001183 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(LoadUser)) {
1184 assert(GEPI->getNumOperands() >= 3 && isa<ConstantInt>(GEPI->getOperand(2))
1185 && "Unexpected GEPI!");
Chris Lattner330245e2007-09-13 17:29:05 +00001186
Chris Lattnera637a8b2007-09-13 18:00:31 +00001187 // Load the pointer for this field.
1188 unsigned FieldNo = cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue();
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001189 Value *NewPtr = GetHeapSROAValue(GEPI->getOperand(0), FieldNo,
1190 InsertedScalarizedValues, PHIsToRewrite);
Chris Lattnera637a8b2007-09-13 18:00:31 +00001191
1192 // Create the new GEP idx vector.
1193 SmallVector<Value*, 8> GEPIdx;
1194 GEPIdx.push_back(GEPI->getOperand(1));
1195 GEPIdx.append(GEPI->op_begin()+3, GEPI->op_end());
1196
Gabor Greifb1dbcd82008-05-15 10:04:30 +00001197 Value *NGEPI = GetElementPtrInst::Create(NewPtr,
1198 GEPIdx.begin(), GEPIdx.end(),
Gabor Greif051a9502008-04-06 20:25:17 +00001199 GEPI->getName(), GEPI);
Chris Lattnera637a8b2007-09-13 18:00:31 +00001200 GEPI->replaceAllUsesWith(NGEPI);
1201 GEPI->eraseFromParent();
1202 return;
1203 }
Chris Lattner309f20f2007-09-13 21:31:36 +00001204
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001205 // Recursively transform the users of PHI nodes. This will lazily create the
1206 // PHIs that are needed for individual elements. Keep track of what PHIs we
1207 // see in InsertedScalarizedValues so that we don't get infinite loops (very
1208 // antisocial). If the PHI is already in InsertedScalarizedValues, it has
1209 // already been seen first by another load, so its uses have already been
1210 // processed.
1211 PHINode *PN = cast<PHINode>(LoadUser);
1212 bool Inserted;
1213 DenseMap<Value*, std::vector<Value*> >::iterator InsertPos;
1214 tie(InsertPos, Inserted) =
1215 InsertedScalarizedValues.insert(std::make_pair(PN, std::vector<Value*>()));
1216 if (!Inserted) return;
Chris Lattner309f20f2007-09-13 21:31:36 +00001217
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001218 // If this is the first time we've seen this PHI, recursively process all
1219 // users.
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001220 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end(); UI != E; ) {
1221 Instruction *User = cast<Instruction>(*UI++);
1222 RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite);
1223 }
Chris Lattner330245e2007-09-13 17:29:05 +00001224}
1225
Chris Lattner86395032006-09-30 23:32:09 +00001226/// RewriteUsesOfLoadForHeapSRoA - We are performing Heap SRoA on a global. Ptr
1227/// is a value loaded from the global. Eliminate all uses of Ptr, making them
1228/// use FieldGlobals instead. All uses of loaded values satisfy
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001229/// AllGlobalLoadUsesSimpleEnoughForHeapSRA.
Chris Lattner330245e2007-09-13 17:29:05 +00001230static void RewriteUsesOfLoadForHeapSRoA(LoadInst *Load,
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001231 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
1232 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
1233 for (Value::use_iterator UI = Load->use_begin(), E = Load->use_end();
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001234 UI != E; ) {
1235 Instruction *User = cast<Instruction>(*UI++);
1236 RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite);
1237 }
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001238
1239 if (Load->use_empty()) {
1240 Load->eraseFromParent();
1241 InsertedScalarizedValues.erase(Load);
1242 }
Chris Lattner86395032006-09-30 23:32:09 +00001243}
1244
1245/// PerformHeapAllocSRoA - MI is an allocation of an array of structures. Break
1246/// it up into multiple allocations of arrays of the fields.
1247static GlobalVariable *PerformHeapAllocSRoA(GlobalVariable *GV, MallocInst *MI){
Bill Wendling0a81aac2006-11-26 10:02:32 +00001248 DOUT << "SROA HEAP ALLOC: " << *GV << " MALLOC = " << *MI;
Chris Lattner86395032006-09-30 23:32:09 +00001249 const StructType *STy = cast<StructType>(MI->getAllocatedType());
1250
1251 // There is guaranteed to be at least one use of the malloc (storing
1252 // it into GV). If there are other uses, change them to be uses of
1253 // the global to simplify later code. This also deletes the store
1254 // into GV.
1255 ReplaceUsesOfMallocWithGlobal(MI, GV);
1256
1257 // Okay, at this point, there are no users of the malloc. Insert N
1258 // new mallocs at the same place as MI, and N globals.
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001259 std::vector<Value*> FieldGlobals;
Chris Lattner86395032006-09-30 23:32:09 +00001260 std::vector<MallocInst*> FieldMallocs;
1261
1262 for (unsigned FieldNo = 0, e = STy->getNumElements(); FieldNo != e;++FieldNo){
1263 const Type *FieldTy = STy->getElementType(FieldNo);
Christopher Lamb43ad6b32007-12-17 01:12:55 +00001264 const Type *PFieldTy = PointerType::getUnqual(FieldTy);
Chris Lattner86395032006-09-30 23:32:09 +00001265
1266 GlobalVariable *NGV =
1267 new GlobalVariable(PFieldTy, false, GlobalValue::InternalLinkage,
1268 Constant::getNullValue(PFieldTy),
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +00001269 GV->getName() + ".f" + utostr(FieldNo), GV,
1270 GV->isThreadLocal());
Chris Lattner86395032006-09-30 23:32:09 +00001271 FieldGlobals.push_back(NGV);
1272
1273 MallocInst *NMI = new MallocInst(FieldTy, MI->getArraySize(),
1274 MI->getName() + ".f" + utostr(FieldNo),MI);
1275 FieldMallocs.push_back(NMI);
1276 new StoreInst(NMI, NGV, MI);
1277 }
1278
1279 // The tricky aspect of this transformation is handling the case when malloc
1280 // fails. In the original code, malloc failing would set the result pointer
1281 // of malloc to null. In this case, some mallocs could succeed and others
1282 // could fail. As such, we emit code that looks like this:
1283 // F0 = malloc(field0)
1284 // F1 = malloc(field1)
1285 // F2 = malloc(field2)
1286 // if (F0 == 0 || F1 == 0 || F2 == 0) {
1287 // if (F0) { free(F0); F0 = 0; }
1288 // if (F1) { free(F1); F1 = 0; }
1289 // if (F2) { free(F2); F2 = 0; }
1290 // }
1291 Value *RunningOr = 0;
1292 for (unsigned i = 0, e = FieldMallocs.size(); i != e; ++i) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001293 Value *Cond = new ICmpInst(ICmpInst::ICMP_EQ, FieldMallocs[i],
Chris Lattner86395032006-09-30 23:32:09 +00001294 Constant::getNullValue(FieldMallocs[i]->getType()),
1295 "isnull", MI);
1296 if (!RunningOr)
1297 RunningOr = Cond; // First seteq
1298 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001299 RunningOr = BinaryOperator::CreateOr(RunningOr, Cond, "tmp", MI);
Chris Lattner86395032006-09-30 23:32:09 +00001300 }
1301
1302 // Split the basic block at the old malloc.
1303 BasicBlock *OrigBB = MI->getParent();
1304 BasicBlock *ContBB = OrigBB->splitBasicBlock(MI, "malloc_cont");
1305
1306 // Create the block to check the first condition. Put all these blocks at the
1307 // end of the function as they are unlikely to be executed.
Gabor Greif051a9502008-04-06 20:25:17 +00001308 BasicBlock *NullPtrBlock = BasicBlock::Create("malloc_ret_null",
1309 OrigBB->getParent());
Chris Lattner86395032006-09-30 23:32:09 +00001310
1311 // Remove the uncond branch from OrigBB to ContBB, turning it into a cond
1312 // branch on RunningOr.
1313 OrigBB->getTerminator()->eraseFromParent();
Gabor Greif051a9502008-04-06 20:25:17 +00001314 BranchInst::Create(NullPtrBlock, ContBB, RunningOr, OrigBB);
Chris Lattner86395032006-09-30 23:32:09 +00001315
1316 // Within the NullPtrBlock, we need to emit a comparison and branch for each
1317 // pointer, because some may be null while others are not.
1318 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
1319 Value *GVVal = new LoadInst(FieldGlobals[i], "tmp", NullPtrBlock);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001320 Value *Cmp = new ICmpInst(ICmpInst::ICMP_NE, GVVal,
1321 Constant::getNullValue(GVVal->getType()),
1322 "tmp", NullPtrBlock);
Gabor Greif051a9502008-04-06 20:25:17 +00001323 BasicBlock *FreeBlock = BasicBlock::Create("free_it", OrigBB->getParent());
1324 BasicBlock *NextBlock = BasicBlock::Create("next", OrigBB->getParent());
1325 BranchInst::Create(FreeBlock, NextBlock, Cmp, NullPtrBlock);
Chris Lattner86395032006-09-30 23:32:09 +00001326
1327 // Fill in FreeBlock.
1328 new FreeInst(GVVal, FreeBlock);
1329 new StoreInst(Constant::getNullValue(GVVal->getType()), FieldGlobals[i],
1330 FreeBlock);
Gabor Greif051a9502008-04-06 20:25:17 +00001331 BranchInst::Create(NextBlock, FreeBlock);
Chris Lattner86395032006-09-30 23:32:09 +00001332
1333 NullPtrBlock = NextBlock;
1334 }
1335
Gabor Greif051a9502008-04-06 20:25:17 +00001336 BranchInst::Create(ContBB, NullPtrBlock);
Chris Lattner86395032006-09-30 23:32:09 +00001337
1338 // MI is no longer needed, remove it.
1339 MI->eraseFromParent();
1340
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001341 /// InsertedScalarizedLoads - As we process loads, if we can't immediately
1342 /// update all uses of the load, keep track of what scalarized loads are
1343 /// inserted for a given load.
1344 DenseMap<Value*, std::vector<Value*> > InsertedScalarizedValues;
1345 InsertedScalarizedValues[GV] = FieldGlobals;
1346
1347 std::vector<std::pair<PHINode*, unsigned> > PHIsToRewrite;
Chris Lattner86395032006-09-30 23:32:09 +00001348
1349 // Okay, the malloc site is completely handled. All of the uses of GV are now
1350 // loads, and all uses of those loads are simple. Rewrite them to use loads
1351 // of the per-field globals instead.
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001352 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI != E;) {
1353 Instruction *User = cast<Instruction>(*UI++);
1354
1355 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
1356 RewriteUsesOfLoadForHeapSRoA(LI, InsertedScalarizedValues, PHIsToRewrite);
1357 continue;
Chris Lattner39ff1e22007-01-09 23:29:37 +00001358 }
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001359
1360 // Must be a store of null.
1361 StoreInst *SI = cast<StoreInst>(User);
1362 assert(isa<ConstantPointerNull>(SI->getOperand(0)) &&
1363 "Unexpected heap-sra user!");
1364
1365 // Insert a store of null into each global.
1366 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
1367 const PointerType *PT = cast<PointerType>(FieldGlobals[i]->getType());
1368 Constant *Null = Constant::getNullValue(PT->getElementType());
1369 new StoreInst(Null, FieldGlobals[i], SI);
1370 }
1371 // Erase the original store.
1372 SI->eraseFromParent();
Chris Lattner86395032006-09-30 23:32:09 +00001373 }
1374
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001375 // While we have PHIs that are interesting to rewrite, do it.
1376 while (!PHIsToRewrite.empty()) {
1377 PHINode *PN = PHIsToRewrite.back().first;
1378 unsigned FieldNo = PHIsToRewrite.back().second;
1379 PHIsToRewrite.pop_back();
1380 PHINode *FieldPN = cast<PHINode>(InsertedScalarizedValues[PN][FieldNo]);
1381 assert(FieldPN->getNumIncomingValues() == 0 &&"Already processed this phi");
1382
1383 // Add all the incoming values. This can materialize more phis.
1384 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1385 Value *InVal = PN->getIncomingValue(i);
1386 InVal = GetHeapSROAValue(InVal, FieldNo, InsertedScalarizedValues,
1387 PHIsToRewrite);
1388 FieldPN->addIncoming(InVal, PN->getIncomingBlock(i));
1389 }
1390 }
1391
1392 // Drop all inter-phi links and any loads that made it this far.
1393 for (DenseMap<Value*, std::vector<Value*> >::iterator
1394 I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
1395 I != E; ++I) {
1396 if (PHINode *PN = dyn_cast<PHINode>(I->first))
1397 PN->dropAllReferences();
1398 else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
1399 LI->dropAllReferences();
1400 }
1401
1402 // Delete all the phis and loads now that inter-references are dead.
1403 for (DenseMap<Value*, std::vector<Value*> >::iterator
1404 I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
1405 I != E; ++I) {
1406 if (PHINode *PN = dyn_cast<PHINode>(I->first))
1407 PN->eraseFromParent();
1408 else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
1409 LI->eraseFromParent();
1410 }
1411
Chris Lattner86395032006-09-30 23:32:09 +00001412 // The old global is now dead, remove it.
1413 GV->eraseFromParent();
1414
1415 ++NumHeapSRA;
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001416 return cast<GlobalVariable>(FieldGlobals[0]);
Chris Lattner86395032006-09-30 23:32:09 +00001417}
1418
Chris Lattnere61d0a62008-12-15 21:02:25 +00001419/// TryToOptimizeStoreOfMallocToGlobal - This function is called when we see a
1420/// pointer global variable with a single value stored it that is a malloc or
1421/// cast of malloc.
1422static bool TryToOptimizeStoreOfMallocToGlobal(GlobalVariable *GV,
1423 MallocInst *MI,
1424 Module::global_iterator &GVI,
1425 TargetData &TD) {
1426 // If this is a malloc of an abstract type, don't touch it.
1427 if (!MI->getAllocatedType()->isSized())
1428 return false;
1429
1430 // We can't optimize this global unless all uses of it are *known* to be
1431 // of the malloc value, not of the null initializer value (consider a use
1432 // that compares the global's value against zero to see if the malloc has
1433 // been reached). To do this, we check to see if all uses of the global
1434 // would trap if the global were null: this proves that they must all
1435 // happen after the malloc.
1436 if (!AllUsesOfLoadedValueWillTrapIfNull(GV))
1437 return false;
1438
1439 // We can't optimize this if the malloc itself is used in a complex way,
1440 // for example, being stored into multiple globals. This allows the
1441 // malloc to be stored into the specified global, loaded setcc'd, and
1442 // GEP'd. These are all things we could transform to using the global
1443 // for.
1444 {
1445 SmallPtrSet<PHINode*, 8> PHIs;
1446 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(MI, GV, PHIs))
1447 return false;
1448 }
1449
1450
1451 // If we have a global that is only initialized with a fixed size malloc,
1452 // transform the program to use global memory instead of malloc'd memory.
1453 // This eliminates dynamic allocation, avoids an indirection accessing the
1454 // data, and exposes the resultant global to further GlobalOpt.
1455 if (ConstantInt *NElements = dyn_cast<ConstantInt>(MI->getArraySize())) {
1456 // Restrict this transformation to only working on small allocations
1457 // (2048 bytes currently), as we don't want to introduce a 16M global or
1458 // something.
1459 if (NElements->getZExtValue()*
Duncan Sands777d2302009-05-09 07:06:46 +00001460 TD.getTypeAllocSize(MI->getAllocatedType()) < 2048) {
Chris Lattnere61d0a62008-12-15 21:02:25 +00001461 GVI = OptimizeGlobalAddressOfMalloc(GV, MI);
1462 return true;
1463 }
1464 }
1465
1466 // If the allocation is an array of structures, consider transforming this
1467 // into multiple malloc'd arrays, one for each field. This is basically
1468 // SRoA for malloc'd memory.
Chris Lattner101f44e2008-12-15 21:44:34 +00001469 const Type *AllocTy = MI->getAllocatedType();
1470
1471 // If this is an allocation of a fixed size array of structs, analyze as a
1472 // variable size array. malloc [100 x struct],1 -> malloc struct, 100
1473 if (!MI->isArrayAllocation())
1474 if (const ArrayType *AT = dyn_cast<ArrayType>(AllocTy))
1475 AllocTy = AT->getElementType();
1476
1477 if (const StructType *AllocSTy = dyn_cast<StructType>(AllocTy)) {
Chris Lattnere61d0a62008-12-15 21:02:25 +00001478 // This the structure has an unreasonable number of fields, leave it
1479 // alone.
Chris Lattner101f44e2008-12-15 21:44:34 +00001480 if (AllocSTy->getNumElements() <= 16 && AllocSTy->getNumElements() != 0 &&
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001481 AllGlobalLoadUsesSimpleEnoughForHeapSRA(GV, MI)) {
Chris Lattner101f44e2008-12-15 21:44:34 +00001482
1483 // If this is a fixed size array, transform the Malloc to be an alloc of
1484 // structs. malloc [100 x struct],1 -> malloc struct, 100
1485 if (const ArrayType *AT = dyn_cast<ArrayType>(MI->getAllocatedType())) {
1486 MallocInst *NewMI =
1487 new MallocInst(AllocSTy,
1488 ConstantInt::get(Type::Int32Ty, AT->getNumElements()),
1489 "", MI);
1490 NewMI->takeName(MI);
1491 Value *Cast = new BitCastInst(NewMI, MI->getType(), "tmp", MI);
1492 MI->replaceAllUsesWith(Cast);
1493 MI->eraseFromParent();
1494 MI = NewMI;
1495 }
1496
Chris Lattnere61d0a62008-12-15 21:02:25 +00001497 GVI = PerformHeapAllocSRoA(GV, MI);
1498 return true;
1499 }
1500 }
1501
1502 return false;
1503}
Chris Lattner86395032006-09-30 23:32:09 +00001504
Chris Lattner9b34a612004-10-09 21:48:45 +00001505// OptimizeOnceStoredGlobal - Try to optimize globals based on the knowledge
1506// that only one value (besides its initializer) is ever stored to the global.
Chris Lattner30ba5692004-10-11 05:54:41 +00001507static bool OptimizeOnceStoredGlobal(GlobalVariable *GV, Value *StoredOnceVal,
Chris Lattner7f8897f2006-08-27 22:42:52 +00001508 Module::global_iterator &GVI,
1509 TargetData &TD) {
Chris Lattner344b41c2008-12-15 21:20:32 +00001510 // Ignore no-op GEPs and bitcasts.
1511 StoredOnceVal = StoredOnceVal->stripPointerCasts();
Chris Lattner9b34a612004-10-09 21:48:45 +00001512
Chris Lattner708148e2004-10-10 23:14:11 +00001513 // If we are dealing with a pointer global that is initialized to null and
1514 // only has one (non-null) value stored into it, then we can optimize any
1515 // users of the loaded value (often calls and loads) that would trap if the
1516 // value was null.
Chris Lattner9b34a612004-10-09 21:48:45 +00001517 if (isa<PointerType>(GV->getInitializer()->getType()) &&
1518 GV->getInitializer()->isNullValue()) {
Chris Lattner708148e2004-10-10 23:14:11 +00001519 if (Constant *SOVC = dyn_cast<Constant>(StoredOnceVal)) {
1520 if (GV->getInitializer()->getType() != SOVC->getType())
Reid Spencerd977d862006-12-12 23:36:14 +00001521 SOVC = ConstantExpr::getBitCast(SOVC, GV->getInitializer()->getType());
Misha Brukmanfd939082005-04-21 23:48:37 +00001522
Chris Lattner708148e2004-10-10 23:14:11 +00001523 // Optimize away any trapping uses of the loaded value.
1524 if (OptimizeAwayTrappingUsesOfLoads(GV, SOVC))
Chris Lattner8be80122004-10-10 17:07:12 +00001525 return true;
Chris Lattner30ba5692004-10-11 05:54:41 +00001526 } else if (MallocInst *MI = dyn_cast<MallocInst>(StoredOnceVal)) {
Chris Lattnere61d0a62008-12-15 21:02:25 +00001527 if (TryToOptimizeStoreOfMallocToGlobal(GV, MI, GVI, TD))
1528 return true;
Chris Lattner708148e2004-10-10 23:14:11 +00001529 }
Chris Lattner9b34a612004-10-09 21:48:45 +00001530 }
Chris Lattner30ba5692004-10-11 05:54:41 +00001531
Chris Lattner9b34a612004-10-09 21:48:45 +00001532 return false;
1533}
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001534
Chris Lattner58e44f42008-01-14 01:17:44 +00001535/// TryToShrinkGlobalToBoolean - At this point, we have learned that the only
1536/// two values ever stored into GV are its initializer and OtherVal. See if we
1537/// can shrink the global into a boolean and select between the two values
1538/// whenever it is used. This exposes the values to other scalar optimizations.
1539static bool TryToShrinkGlobalToBoolean(GlobalVariable *GV, Constant *OtherVal) {
1540 const Type *GVElType = GV->getType()->getElementType();
1541
1542 // If GVElType is already i1, it is already shrunk. If the type of the GV is
Chris Lattner6f6923f2009-03-07 23:32:02 +00001543 // an FP value, pointer or vector, don't do this optimization because a select
1544 // between them is very expensive and unlikely to lead to later
1545 // simplification. In these cases, we typically end up with "cond ? v1 : v2"
1546 // where v1 and v2 both require constant pool loads, a big loss.
Chris Lattner58e44f42008-01-14 01:17:44 +00001547 if (GVElType == Type::Int1Ty || GVElType->isFloatingPoint() ||
Chris Lattner6f6923f2009-03-07 23:32:02 +00001548 isa<PointerType>(GVElType) || isa<VectorType>(GVElType))
Chris Lattner58e44f42008-01-14 01:17:44 +00001549 return false;
1550
1551 // Walk the use list of the global seeing if all the uses are load or store.
1552 // If there is anything else, bail out.
1553 for (Value::use_iterator I = GV->use_begin(), E = GV->use_end(); I != E; ++I)
Devang Patel771281f2009-03-06 01:39:36 +00001554 if (!isa<LoadInst>(I) && !isa<StoreInst>(I))
Chris Lattner58e44f42008-01-14 01:17:44 +00001555 return false;
1556
1557 DOUT << " *** SHRINKING TO BOOL: " << *GV;
1558
Chris Lattner96a86b22004-12-12 05:53:50 +00001559 // Create the new global, initializing it to false.
Reid Spencer4fe16d62007-01-11 18:21:29 +00001560 GlobalVariable *NewGV = new GlobalVariable(Type::Int1Ty, false,
Nick Lewycky0e670df2009-05-03 03:49:08 +00001561 GlobalValue::InternalLinkage, ConstantInt::getFalse(),
1562 GV->getName()+".b",
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +00001563 (Module *)NULL,
1564 GV->isThreadLocal());
Chris Lattner96a86b22004-12-12 05:53:50 +00001565 GV->getParent()->getGlobalList().insert(GV, NewGV);
1566
1567 Constant *InitVal = GV->getInitializer();
Reid Spencer4fe16d62007-01-11 18:21:29 +00001568 assert(InitVal->getType() != Type::Int1Ty && "No reason to shrink to bool!");
Chris Lattner96a86b22004-12-12 05:53:50 +00001569
1570 // If initialized to zero and storing one into the global, we can use a cast
1571 // instead of a select to synthesize the desired value.
1572 bool IsOneZero = false;
1573 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal))
Reid Spencercae57542007-03-02 00:28:52 +00001574 IsOneZero = InitVal->isNullValue() && CI->isOne();
Chris Lattner96a86b22004-12-12 05:53:50 +00001575
1576 while (!GV->use_empty()) {
Devang Patel771281f2009-03-06 01:39:36 +00001577 Instruction *UI = cast<Instruction>(GV->use_back());
1578 if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
Chris Lattner96a86b22004-12-12 05:53:50 +00001579 // Change the store into a boolean store.
1580 bool StoringOther = SI->getOperand(0) == OtherVal;
1581 // Only do this if we weren't storing a loaded value.
Chris Lattner38c25562004-12-12 19:34:41 +00001582 Value *StoreVal;
Chris Lattner96a86b22004-12-12 05:53:50 +00001583 if (StoringOther || SI->getOperand(0) == InitVal)
Reid Spencer579dca12007-01-12 04:24:46 +00001584 StoreVal = ConstantInt::get(Type::Int1Ty, StoringOther);
Chris Lattner38c25562004-12-12 19:34:41 +00001585 else {
1586 // Otherwise, we are storing a previously loaded copy. To do this,
1587 // change the copy from copying the original value to just copying the
1588 // bool.
1589 Instruction *StoredVal = cast<Instruction>(SI->getOperand(0));
1590
1591 // If we're already replaced the input, StoredVal will be a cast or
1592 // select instruction. If not, it will be a load of the original
1593 // global.
1594 if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
1595 assert(LI->getOperand(0) == GV && "Not a copy!");
1596 // Insert a new load, to preserve the saved value.
1597 StoreVal = new LoadInst(NewGV, LI->getName()+".b", LI);
1598 } else {
1599 assert((isa<CastInst>(StoredVal) || isa<SelectInst>(StoredVal)) &&
1600 "This is not a form that we understand!");
1601 StoreVal = StoredVal->getOperand(0);
1602 assert(isa<LoadInst>(StoreVal) && "Not a load of NewGV!");
1603 }
1604 }
1605 new StoreInst(StoreVal, NewGV, SI);
Devang Patel771281f2009-03-06 01:39:36 +00001606 } else {
Chris Lattner96a86b22004-12-12 05:53:50 +00001607 // Change the load into a load of bool then a select.
Devang Patel771281f2009-03-06 01:39:36 +00001608 LoadInst *LI = cast<LoadInst>(UI);
Chris Lattner046800a2007-02-11 01:08:35 +00001609 LoadInst *NLI = new LoadInst(NewGV, LI->getName()+".b", LI);
Chris Lattner96a86b22004-12-12 05:53:50 +00001610 Value *NSI;
1611 if (IsOneZero)
Chris Lattner046800a2007-02-11 01:08:35 +00001612 NSI = new ZExtInst(NLI, LI->getType(), "", LI);
Misha Brukmanfd939082005-04-21 23:48:37 +00001613 else
Gabor Greif051a9502008-04-06 20:25:17 +00001614 NSI = SelectInst::Create(NLI, OtherVal, InitVal, "", LI);
Chris Lattner046800a2007-02-11 01:08:35 +00001615 NSI->takeName(LI);
Chris Lattner96a86b22004-12-12 05:53:50 +00001616 LI->replaceAllUsesWith(NSI);
Devang Patel771281f2009-03-06 01:39:36 +00001617 }
1618 UI->eraseFromParent();
Chris Lattner96a86b22004-12-12 05:53:50 +00001619 }
1620
1621 GV->eraseFromParent();
Chris Lattner58e44f42008-01-14 01:17:44 +00001622 return true;
Chris Lattner96a86b22004-12-12 05:53:50 +00001623}
1624
1625
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001626/// ProcessInternalGlobal - Analyze the specified global variable and optimize
1627/// it if possible. If we make a change, return true.
Chris Lattner30ba5692004-10-11 05:54:41 +00001628bool GlobalOpt::ProcessInternalGlobal(GlobalVariable *GV,
Chris Lattnere4d5c442005-03-15 04:54:21 +00001629 Module::global_iterator &GVI) {
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00001630 SmallPtrSet<PHINode*, 16> PHIUsers;
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001631 GlobalStatus GS;
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001632 GV->removeDeadConstantUsers();
1633
1634 if (GV->use_empty()) {
Bill Wendling0a81aac2006-11-26 10:02:32 +00001635 DOUT << "GLOBAL DEAD: " << *GV;
Chris Lattner7a7ed022004-10-16 18:09:00 +00001636 GV->eraseFromParent();
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001637 ++NumDeleted;
1638 return true;
1639 }
1640
1641 if (!AnalyzeGlobal(GV, GS, PHIUsers)) {
Chris Lattnercff16732006-09-30 19:40:30 +00001642#if 0
Bill Wendlinge8156192006-12-07 01:30:32 +00001643 cerr << "Global: " << *GV;
1644 cerr << " isLoaded = " << GS.isLoaded << "\n";
1645 cerr << " StoredType = ";
Chris Lattnercff16732006-09-30 19:40:30 +00001646 switch (GS.StoredType) {
Bill Wendlinge8156192006-12-07 01:30:32 +00001647 case GlobalStatus::NotStored: cerr << "NEVER STORED\n"; break;
1648 case GlobalStatus::isInitializerStored: cerr << "INIT STORED\n"; break;
1649 case GlobalStatus::isStoredOnce: cerr << "STORED ONCE\n"; break;
1650 case GlobalStatus::isStored: cerr << "stored\n"; break;
Chris Lattnercff16732006-09-30 19:40:30 +00001651 }
1652 if (GS.StoredType == GlobalStatus::isStoredOnce && GS.StoredOnceValue)
Bill Wendlinge8156192006-12-07 01:30:32 +00001653 cerr << " StoredOnceValue = " << *GS.StoredOnceValue << "\n";
Chris Lattnercff16732006-09-30 19:40:30 +00001654 if (GS.AccessingFunction && !GS.HasMultipleAccessingFunctions)
Bill Wendlinge8156192006-12-07 01:30:32 +00001655 cerr << " AccessingFunction = " << GS.AccessingFunction->getName()
Chris Lattnercff16732006-09-30 19:40:30 +00001656 << "\n";
Bill Wendlinge8156192006-12-07 01:30:32 +00001657 cerr << " HasMultipleAccessingFunctions = "
Chris Lattnercff16732006-09-30 19:40:30 +00001658 << GS.HasMultipleAccessingFunctions << "\n";
Bill Wendlinge8156192006-12-07 01:30:32 +00001659 cerr << " HasNonInstructionUser = " << GS.HasNonInstructionUser<<"\n";
Bill Wendlinge8156192006-12-07 01:30:32 +00001660 cerr << "\n";
Chris Lattnercff16732006-09-30 19:40:30 +00001661#endif
1662
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +00001663 // If this is a first class global and has only one accessing function
1664 // and this function is main (which we know is not recursive we can make
1665 // this global a local variable) we replace the global with a local alloca
1666 // in this function.
1667 //
Dan Gohman399101a2008-05-23 00:17:26 +00001668 // NOTE: It doesn't make sense to promote non single-value types since we
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +00001669 // are just replacing static memory to stack memory.
1670 if (!GS.HasMultipleAccessingFunctions &&
Chris Lattner553ca522005-06-15 21:11:48 +00001671 GS.AccessingFunction && !GS.HasNonInstructionUser &&
Dan Gohman399101a2008-05-23 00:17:26 +00001672 GV->getType()->getElementType()->isSingleValueType() &&
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +00001673 GS.AccessingFunction->getName() == "main" &&
1674 GS.AccessingFunction->hasExternalLinkage()) {
Bill Wendling0a81aac2006-11-26 10:02:32 +00001675 DOUT << "LOCALIZING GLOBAL: " << *GV;
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +00001676 Instruction* FirstI = GS.AccessingFunction->getEntryBlock().begin();
1677 const Type* ElemTy = GV->getType()->getElementType();
Nate Begeman14b05292005-11-05 09:21:28 +00001678 // FIXME: Pass Global's alignment when globals have alignment
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +00001679 AllocaInst* Alloca = new AllocaInst(ElemTy, NULL, GV->getName(), FirstI);
1680 if (!isa<UndefValue>(GV->getInitializer()))
1681 new StoreInst(GV->getInitializer(), Alloca, FirstI);
Misha Brukmanfd939082005-04-21 23:48:37 +00001682
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +00001683 GV->replaceAllUsesWith(Alloca);
1684 GV->eraseFromParent();
1685 ++NumLocalized;
1686 return true;
1687 }
Chris Lattnercff16732006-09-30 19:40:30 +00001688
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001689 // If the global is never loaded (but may be stored to), it is dead.
1690 // Delete it now.
1691 if (!GS.isLoaded) {
Bill Wendling0a81aac2006-11-26 10:02:32 +00001692 DOUT << "GLOBAL NEVER LOADED: " << *GV;
Chris Lattner930f4752004-10-09 03:32:52 +00001693
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001694 // Delete any stores we can find to the global. We may not be able to
1695 // make it completely dead though.
Chris Lattner031955d2004-10-10 16:43:46 +00001696 bool Changed = CleanupConstantGlobalUsers(GV, GV->getInitializer());
Chris Lattner930f4752004-10-09 03:32:52 +00001697
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001698 // If the global is dead now, delete it.
1699 if (GV->use_empty()) {
Chris Lattner7a7ed022004-10-16 18:09:00 +00001700 GV->eraseFromParent();
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001701 ++NumDeleted;
Chris Lattner930f4752004-10-09 03:32:52 +00001702 Changed = true;
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001703 }
Chris Lattner930f4752004-10-09 03:32:52 +00001704 return Changed;
Misha Brukmanfd939082005-04-21 23:48:37 +00001705
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001706 } else if (GS.StoredType <= GlobalStatus::isInitializerStored) {
Bill Wendling0a81aac2006-11-26 10:02:32 +00001707 DOUT << "MARKING CONSTANT: " << *GV;
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001708 GV->setConstant(true);
Misha Brukmanfd939082005-04-21 23:48:37 +00001709
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001710 // Clean up any obviously simplifiable users now.
1711 CleanupConstantGlobalUsers(GV, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +00001712
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001713 // If the global is dead now, just nuke it.
1714 if (GV->use_empty()) {
Bill Wendling0a81aac2006-11-26 10:02:32 +00001715 DOUT << " *** Marking constant allowed us to simplify "
1716 << "all users and delete global!\n";
Chris Lattner7a7ed022004-10-16 18:09:00 +00001717 GV->eraseFromParent();
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001718 ++NumDeleted;
1719 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001720
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001721 ++NumMarked;
1722 return true;
Dan Gohman399101a2008-05-23 00:17:26 +00001723 } else if (!GV->getInitializer()->getType()->isSingleValueType()) {
Chris Lattner998182b2008-04-26 07:40:11 +00001724 if (GlobalVariable *FirstNewGV = SRAGlobal(GV,
1725 getAnalysis<TargetData>())) {
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001726 GVI = FirstNewGV; // Don't skip the newly produced globals!
1727 return true;
1728 }
Chris Lattner9b34a612004-10-09 21:48:45 +00001729 } else if (GS.StoredType == GlobalStatus::isStoredOnce) {
Chris Lattner96a86b22004-12-12 05:53:50 +00001730 // If the initial value for the global was an undef value, and if only
1731 // one other value was stored into it, we can just change the
Duncan Sandsb5024402009-01-13 13:48:44 +00001732 // initializer to be the stored value, then delete all stores to the
Chris Lattner96a86b22004-12-12 05:53:50 +00001733 // global. This allows us to mark it constant.
1734 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
1735 if (isa<UndefValue>(GV->getInitializer())) {
1736 // Change the initial value here.
1737 GV->setInitializer(SOVConstant);
Misha Brukmanfd939082005-04-21 23:48:37 +00001738
Chris Lattner96a86b22004-12-12 05:53:50 +00001739 // Clean up any obviously simplifiable users now.
1740 CleanupConstantGlobalUsers(GV, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +00001741
Chris Lattner96a86b22004-12-12 05:53:50 +00001742 if (GV->use_empty()) {
Bill Wendling0a81aac2006-11-26 10:02:32 +00001743 DOUT << " *** Substituting initializer allowed us to "
1744 << "simplify all users and delete global!\n";
Chris Lattner96a86b22004-12-12 05:53:50 +00001745 GV->eraseFromParent();
1746 ++NumDeleted;
1747 } else {
1748 GVI = GV;
1749 }
1750 ++NumSubstitute;
1751 return true;
Chris Lattner7a7ed022004-10-16 18:09:00 +00001752 }
Chris Lattner7a7ed022004-10-16 18:09:00 +00001753
Chris Lattner9b34a612004-10-09 21:48:45 +00001754 // Try to optimize globals based on the knowledge that only one value
1755 // (besides its initializer) is ever stored to the global.
Chris Lattner30ba5692004-10-11 05:54:41 +00001756 if (OptimizeOnceStoredGlobal(GV, GS.StoredOnceValue, GVI,
1757 getAnalysis<TargetData>()))
Chris Lattner9b34a612004-10-09 21:48:45 +00001758 return true;
Chris Lattner96a86b22004-12-12 05:53:50 +00001759
1760 // Otherwise, if the global was not a boolean, we can shrink it to be a
1761 // boolean.
1762 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
Chris Lattner58e44f42008-01-14 01:17:44 +00001763 if (TryToShrinkGlobalToBoolean(GV, SOVConstant)) {
Chris Lattner96a86b22004-12-12 05:53:50 +00001764 ++NumShrunkToBool;
1765 return true;
1766 }
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001767 }
1768 }
1769 return false;
1770}
1771
Chris Lattnerfb217ad2005-05-08 22:18:06 +00001772/// OnlyCalledDirectly - Return true if the specified function is only called
1773/// directly. In other words, its address is never taken.
1774static bool OnlyCalledDirectly(Function *F) {
1775 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
1776 Instruction *User = dyn_cast<Instruction>(*UI);
1777 if (!User) return false;
1778 if (!isa<CallInst>(User) && !isa<InvokeInst>(User)) return false;
1779
1780 // See if the function address is passed as an argument.
Gabor Greif5e463212008-05-29 01:59:18 +00001781 for (User::op_iterator i = User->op_begin() + 1, e = User->op_end();
Bill Wendlingf9e67ac2008-08-12 23:15:44 +00001782 i != e; ++i)
Gabor Greif5e463212008-05-29 01:59:18 +00001783 if (*i == F) return false;
Chris Lattnerfb217ad2005-05-08 22:18:06 +00001784 }
1785 return true;
1786}
1787
1788/// ChangeCalleesToFastCall - Walk all of the direct calls of the specified
1789/// function, changing them to FastCC.
1790static void ChangeCalleesToFastCall(Function *F) {
1791 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
Duncan Sands548448a2008-02-18 17:32:13 +00001792 CallSite User(cast<Instruction>(*UI));
1793 User.setCallingConv(CallingConv::Fast);
Chris Lattnerfb217ad2005-05-08 22:18:06 +00001794 }
1795}
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001796
Devang Patel05988662008-09-25 21:00:45 +00001797static AttrListPtr StripNest(const AttrListPtr &Attrs) {
Chris Lattner58d74912008-03-12 17:45:29 +00001798 for (unsigned i = 0, e = Attrs.getNumSlots(); i != e; ++i) {
Devang Patel05988662008-09-25 21:00:45 +00001799 if ((Attrs.getSlot(i).Attrs & Attribute::Nest) == 0)
Duncan Sands548448a2008-02-18 17:32:13 +00001800 continue;
1801
Duncan Sands548448a2008-02-18 17:32:13 +00001802 // There can be only one.
Devang Patel05988662008-09-25 21:00:45 +00001803 return Attrs.removeAttr(Attrs.getSlot(i).Index, Attribute::Nest);
Duncan Sands3d5378f2008-02-16 20:56:04 +00001804 }
1805
1806 return Attrs;
1807}
1808
1809static void RemoveNestAttribute(Function *F) {
Devang Patel05988662008-09-25 21:00:45 +00001810 F->setAttributes(StripNest(F->getAttributes()));
Duncan Sands3d5378f2008-02-16 20:56:04 +00001811 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
Duncan Sands548448a2008-02-18 17:32:13 +00001812 CallSite User(cast<Instruction>(*UI));
Devang Patel05988662008-09-25 21:00:45 +00001813 User.setAttributes(StripNest(User.getAttributes()));
Duncan Sands3d5378f2008-02-16 20:56:04 +00001814 }
1815}
1816
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001817bool GlobalOpt::OptimizeFunctions(Module &M) {
1818 bool Changed = false;
1819 // Optimize functions.
1820 for (Module::iterator FI = M.begin(), E = M.end(); FI != E; ) {
1821 Function *F = FI++;
Duncan Sandsfc5940d2009-03-06 10:21:56 +00001822 // Functions without names cannot be referenced outside this module.
1823 if (!F->hasName() && !F->isDeclaration())
1824 F->setLinkage(GlobalValue::InternalLinkage);
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001825 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++;
Duncan Sandsfc5940d2009-03-06 10:21:56 +00001861 // Global variables without names cannot be referenced outside this module.
1862 if (!GV->hasName() && !GV->isDeclaration())
1863 GV->setLinkage(GlobalValue::InternalLinkage);
Rafael Espindolabb46f522009-01-15 20:18:42 +00001864 if (!GV->isConstant() && GV->hasLocalLinkage() &&
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001865 GV->hasInitializer())
1866 Changed |= ProcessInternalGlobal(GV, GVI);
1867 }
1868 return Changed;
1869}
1870
1871/// FindGlobalCtors - Find the llvm.globalctors list, verifying that all
1872/// initializers have an init priority of 65535.
1873GlobalVariable *GlobalOpt::FindGlobalCtors(Module &M) {
Alkis Evlogimenose9c6d362005-10-25 11:18:06 +00001874 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1875 I != E; ++I)
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001876 if (I->getName() == "llvm.global_ctors") {
1877 // Found it, verify it's an array of { int, void()* }.
1878 const ArrayType *ATy =dyn_cast<ArrayType>(I->getType()->getElementType());
1879 if (!ATy) return 0;
1880 const StructType *STy = dyn_cast<StructType>(ATy->getElementType());
1881 if (!STy || STy->getNumElements() != 2 ||
Reid Spencerc5b206b2006-12-31 05:48:39 +00001882 STy->getElementType(0) != Type::Int32Ty) return 0;
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001883 const PointerType *PFTy = dyn_cast<PointerType>(STy->getElementType(1));
1884 if (!PFTy) return 0;
1885 const FunctionType *FTy = dyn_cast<FunctionType>(PFTy->getElementType());
1886 if (!FTy || FTy->getReturnType() != Type::VoidTy || FTy->isVarArg() ||
1887 FTy->getNumParams() != 0)
1888 return 0;
1889
1890 // Verify that the initializer is simple enough for us to handle.
1891 if (!I->hasInitializer()) return 0;
1892 ConstantArray *CA = dyn_cast<ConstantArray>(I->getInitializer());
1893 if (!CA) return 0;
Gabor Greif5e463212008-05-29 01:59:18 +00001894 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i)
1895 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(*i)) {
Chris Lattner7d8e58f2005-09-26 02:19:27 +00001896 if (isa<ConstantPointerNull>(CS->getOperand(1)))
1897 continue;
1898
1899 // Must have a function or null ptr.
1900 if (!isa<Function>(CS->getOperand(1)))
1901 return 0;
1902
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001903 // Init priority must be standard.
1904 ConstantInt *CI = dyn_cast<ConstantInt>(CS->getOperand(0));
Reid Spencerb83eb642006-10-20 07:07:24 +00001905 if (!CI || CI->getZExtValue() != 65535)
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001906 return 0;
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001907 } else {
1908 return 0;
1909 }
1910
1911 return I;
1912 }
1913 return 0;
1914}
1915
Chris Lattnerdb973e62005-09-26 02:31:18 +00001916/// ParseGlobalCtors - Given a llvm.global_ctors list that we can understand,
1917/// return a list of the functions and null terminator as a vector.
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001918static std::vector<Function*> ParseGlobalCtors(GlobalVariable *GV) {
1919 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
1920 std::vector<Function*> Result;
1921 Result.reserve(CA->getNumOperands());
Gabor Greif5e463212008-05-29 01:59:18 +00001922 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i) {
1923 ConstantStruct *CS = cast<ConstantStruct>(*i);
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001924 Result.push_back(dyn_cast<Function>(CS->getOperand(1)));
1925 }
1926 return Result;
1927}
1928
Chris Lattnerdb973e62005-09-26 02:31:18 +00001929/// InstallGlobalCtors - Given a specified llvm.global_ctors list, install the
1930/// specified array, returning the new global to use.
1931static GlobalVariable *InstallGlobalCtors(GlobalVariable *GCL,
1932 const std::vector<Function*> &Ctors) {
1933 // If we made a change, reassemble the initializer list.
1934 std::vector<Constant*> CSVals;
Reid Spencerc5b206b2006-12-31 05:48:39 +00001935 CSVals.push_back(ConstantInt::get(Type::Int32Ty, 65535));
Chris Lattnerdb973e62005-09-26 02:31:18 +00001936 CSVals.push_back(0);
1937
1938 // Create the new init list.
1939 std::vector<Constant*> CAList;
1940 for (unsigned i = 0, e = Ctors.size(); i != e; ++i) {
Chris Lattner79c11012005-09-26 04:44:35 +00001941 if (Ctors[i]) {
Chris Lattnerdb973e62005-09-26 02:31:18 +00001942 CSVals[1] = Ctors[i];
Chris Lattner79c11012005-09-26 04:44:35 +00001943 } else {
Chris Lattnerdb973e62005-09-26 02:31:18 +00001944 const Type *FTy = FunctionType::get(Type::VoidTy,
1945 std::vector<const Type*>(), false);
Christopher Lamb43ad6b32007-12-17 01:12:55 +00001946 const PointerType *PFTy = PointerType::getUnqual(FTy);
Chris Lattnerdb973e62005-09-26 02:31:18 +00001947 CSVals[1] = Constant::getNullValue(PFTy);
Reid Spencerc5b206b2006-12-31 05:48:39 +00001948 CSVals[0] = ConstantInt::get(Type::Int32Ty, 2147483647);
Chris Lattnerdb973e62005-09-26 02:31:18 +00001949 }
1950 CAList.push_back(ConstantStruct::get(CSVals));
1951 }
1952
1953 // Create the array initializer.
1954 const Type *StructTy =
1955 cast<ArrayType>(GCL->getType()->getElementType())->getElementType();
1956 Constant *CA = ConstantArray::get(ArrayType::get(StructTy, CAList.size()),
1957 CAList);
1958
1959 // If we didn't change the number of elements, don't create a new GV.
1960 if (CA->getType() == GCL->getInitializer()->getType()) {
1961 GCL->setInitializer(CA);
1962 return GCL;
1963 }
1964
1965 // Create the new global and insert it next to the existing list.
1966 GlobalVariable *NGV = new GlobalVariable(CA->getType(), GCL->isConstant(),
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +00001967 GCL->getLinkage(), CA, "",
1968 (Module *)NULL,
1969 GCL->isThreadLocal());
Chris Lattnerdb973e62005-09-26 02:31:18 +00001970 GCL->getParent()->getGlobalList().insert(GCL, NGV);
Chris Lattner046800a2007-02-11 01:08:35 +00001971 NGV->takeName(GCL);
Chris Lattnerdb973e62005-09-26 02:31:18 +00001972
1973 // Nuke the old list, replacing any uses with the new one.
1974 if (!GCL->use_empty()) {
1975 Constant *V = NGV;
1976 if (V->getType() != GCL->getType())
Reid Spencerd977d862006-12-12 23:36:14 +00001977 V = ConstantExpr::getBitCast(V, GCL->getType());
Chris Lattnerdb973e62005-09-26 02:31:18 +00001978 GCL->replaceAllUsesWith(V);
1979 }
1980 GCL->eraseFromParent();
1981
1982 if (Ctors.size())
1983 return NGV;
1984 else
1985 return 0;
1986}
Chris Lattner79c11012005-09-26 04:44:35 +00001987
1988
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00001989static Constant *getVal(DenseMap<Value*, Constant*> &ComputedValues,
Chris Lattner79c11012005-09-26 04:44:35 +00001990 Value *V) {
1991 if (Constant *CV = dyn_cast<Constant>(V)) return CV;
1992 Constant *R = ComputedValues[V];
1993 assert(R && "Reference to an uncomputed value!");
1994 return R;
1995}
1996
1997/// isSimpleEnoughPointerToCommit - Return true if this constant is simple
1998/// enough for us to understand. In particular, if it is a cast of something,
1999/// we punt. We basically just support direct accesses to globals and GEP's of
2000/// globals. This should be kept up to date with CommitValueTo.
2001static bool isSimpleEnoughPointerToCommit(Constant *C) {
Chris Lattner231308c2005-09-27 04:50:03 +00002002 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
Rafael Espindolabb46f522009-01-15 20:18:42 +00002003 if (!GV->hasExternalLinkage() && !GV->hasLocalLinkage())
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00002004 return false; // do not allow weak/linkonce/dllimport/dllexport linkage.
Reid Spencer5cbf9852007-01-30 20:08:39 +00002005 return !GV->isDeclaration(); // reject external globals.
Chris Lattner231308c2005-09-27 04:50:03 +00002006 }
Chris Lattner798b4d52005-09-26 06:52:44 +00002007 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
2008 // Handle a constantexpr gep.
2009 if (CE->getOpcode() == Instruction::GetElementPtr &&
2010 isa<GlobalVariable>(CE->getOperand(0))) {
2011 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
Rafael Espindolabb46f522009-01-15 20:18:42 +00002012 if (!GV->hasExternalLinkage() && !GV->hasLocalLinkage())
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00002013 return false; // do not allow weak/linkonce/dllimport/dllexport linkage.
Chris Lattner798b4d52005-09-26 06:52:44 +00002014 return GV->hasInitializer() &&
2015 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
2016 }
Chris Lattner79c11012005-09-26 04:44:35 +00002017 return false;
2018}
2019
Chris Lattner798b4d52005-09-26 06:52:44 +00002020/// EvaluateStoreInto - Evaluate a piece of a constantexpr store into a global
2021/// initializer. This returns 'Init' modified to reflect 'Val' stored into it.
2022/// At this point, the GEP operands of Addr [0, OpNo) have been stepped into.
2023static Constant *EvaluateStoreInto(Constant *Init, Constant *Val,
2024 ConstantExpr *Addr, unsigned OpNo) {
2025 // Base case of the recursion.
2026 if (OpNo == Addr->getNumOperands()) {
2027 assert(Val->getType() == Init->getType() && "Type mismatch!");
2028 return Val;
2029 }
2030
2031 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
2032 std::vector<Constant*> Elts;
2033
2034 // Break up the constant into its elements.
2035 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
Gabor Greif5e463212008-05-29 01:59:18 +00002036 for (User::op_iterator i = CS->op_begin(), e = CS->op_end(); i != e; ++i)
2037 Elts.push_back(cast<Constant>(*i));
Chris Lattner798b4d52005-09-26 06:52:44 +00002038 } else if (isa<ConstantAggregateZero>(Init)) {
2039 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
2040 Elts.push_back(Constant::getNullValue(STy->getElementType(i)));
2041 } else if (isa<UndefValue>(Init)) {
2042 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
2043 Elts.push_back(UndefValue::get(STy->getElementType(i)));
2044 } else {
2045 assert(0 && "This code is out of sync with "
2046 " ConstantFoldLoadThroughGEPConstantExpr");
2047 }
2048
2049 // Replace the element that we are supposed to.
Reid Spencerb83eb642006-10-20 07:07:24 +00002050 ConstantInt *CU = cast<ConstantInt>(Addr->getOperand(OpNo));
2051 unsigned Idx = CU->getZExtValue();
2052 assert(Idx < STy->getNumElements() && "Struct index out of range!");
Chris Lattner798b4d52005-09-26 06:52:44 +00002053 Elts[Idx] = EvaluateStoreInto(Elts[Idx], Val, Addr, OpNo+1);
2054
2055 // Return the modified struct.
Chris Lattnerf0a9aab2007-06-04 22:23:42 +00002056 return ConstantStruct::get(&Elts[0], Elts.size(), STy->isPacked());
Chris Lattner798b4d52005-09-26 06:52:44 +00002057 } else {
2058 ConstantInt *CI = cast<ConstantInt>(Addr->getOperand(OpNo));
2059 const ArrayType *ATy = cast<ArrayType>(Init->getType());
2060
2061 // Break up the array into elements.
2062 std::vector<Constant*> Elts;
2063 if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
Gabor Greif5e463212008-05-29 01:59:18 +00002064 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i)
2065 Elts.push_back(cast<Constant>(*i));
Chris Lattner798b4d52005-09-26 06:52:44 +00002066 } else if (isa<ConstantAggregateZero>(Init)) {
2067 Constant *Elt = Constant::getNullValue(ATy->getElementType());
2068 Elts.assign(ATy->getNumElements(), Elt);
2069 } else if (isa<UndefValue>(Init)) {
2070 Constant *Elt = UndefValue::get(ATy->getElementType());
2071 Elts.assign(ATy->getNumElements(), Elt);
2072 } else {
2073 assert(0 && "This code is out of sync with "
2074 " ConstantFoldLoadThroughGEPConstantExpr");
2075 }
2076
Reid Spencerb83eb642006-10-20 07:07:24 +00002077 assert(CI->getZExtValue() < ATy->getNumElements());
2078 Elts[CI->getZExtValue()] =
2079 EvaluateStoreInto(Elts[CI->getZExtValue()], Val, Addr, OpNo+1);
Chris Lattner798b4d52005-09-26 06:52:44 +00002080 return ConstantArray::get(ATy, Elts);
2081 }
2082}
2083
Chris Lattner79c11012005-09-26 04:44:35 +00002084/// CommitValueTo - We have decided that Addr (which satisfies the predicate
2085/// isSimpleEnoughPointerToCommit) should get Val as its value. Make it happen.
2086static void CommitValueTo(Constant *Val, Constant *Addr) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002087 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Addr)) {
2088 assert(GV->hasInitializer());
2089 GV->setInitializer(Val);
2090 return;
2091 }
2092
2093 ConstantExpr *CE = cast<ConstantExpr>(Addr);
2094 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
2095
2096 Constant *Init = GV->getInitializer();
2097 Init = EvaluateStoreInto(Init, Val, CE, 2);
2098 GV->setInitializer(Init);
Chris Lattner79c11012005-09-26 04:44:35 +00002099}
2100
Chris Lattner562a0552005-09-26 05:16:34 +00002101/// ComputeLoadResult - Return the value that would be computed by a load from
2102/// P after the stores reflected by 'memory' have been performed. If we can't
2103/// decide, return null.
Chris Lattner04de1cf2005-09-26 05:15:37 +00002104static Constant *ComputeLoadResult(Constant *P,
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002105 const DenseMap<Constant*, Constant*> &Memory) {
Chris Lattner04de1cf2005-09-26 05:15:37 +00002106 // If this memory location has been recently stored, use the stored value: it
2107 // is the most up-to-date.
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002108 DenseMap<Constant*, Constant*>::const_iterator I = Memory.find(P);
Chris Lattner04de1cf2005-09-26 05:15:37 +00002109 if (I != Memory.end()) return I->second;
2110
2111 // Access it.
2112 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(P)) {
2113 if (GV->hasInitializer())
2114 return GV->getInitializer();
2115 return 0;
Chris Lattner04de1cf2005-09-26 05:15:37 +00002116 }
Chris Lattner798b4d52005-09-26 06:52:44 +00002117
2118 // Handle a constantexpr getelementptr.
2119 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(P))
2120 if (CE->getOpcode() == Instruction::GetElementPtr &&
2121 isa<GlobalVariable>(CE->getOperand(0))) {
2122 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
2123 if (GV->hasInitializer())
2124 return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
2125 }
2126
2127 return 0; // don't know how to evaluate.
Chris Lattner04de1cf2005-09-26 05:15:37 +00002128}
2129
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002130/// EvaluateFunction - Evaluate a call to function F, returning true if
2131/// successful, false if we can't evaluate it. ActualArgs contains the formal
2132/// arguments for the function.
Chris Lattnercd271422005-09-27 04:45:34 +00002133static bool EvaluateFunction(Function *F, Constant *&RetVal,
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002134 const std::vector<Constant*> &ActualArgs,
2135 std::vector<Function*> &CallStack,
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002136 DenseMap<Constant*, Constant*> &MutatedMemory,
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002137 std::vector<GlobalVariable*> &AllocaTmps) {
Chris Lattnercd271422005-09-27 04:45:34 +00002138 // Check to see if this function is already executing (recursion). If so,
2139 // bail out. TODO: we might want to accept limited recursion.
2140 if (std::find(CallStack.begin(), CallStack.end(), F) != CallStack.end())
2141 return false;
2142
2143 CallStack.push_back(F);
2144
Chris Lattner79c11012005-09-26 04:44:35 +00002145 /// Values - As we compute SSA register values, we store their contents here.
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002146 DenseMap<Value*, Constant*> Values;
Chris Lattnercd271422005-09-27 04:45:34 +00002147
2148 // Initialize arguments to the incoming values specified.
2149 unsigned ArgNo = 0;
2150 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); AI != E;
2151 ++AI, ++ArgNo)
2152 Values[AI] = ActualArgs[ArgNo];
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002153
Chris Lattnercdf98be2005-09-26 04:57:38 +00002154 /// ExecutedBlocks - We only handle non-looping, non-recursive code. As such,
2155 /// we can only evaluate any one basic block at most once. This set keeps
2156 /// track of what we have executed so we can detect recursive cases etc.
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002157 SmallPtrSet<BasicBlock*, 32> ExecutedBlocks;
Chris Lattnera22fdb02005-09-26 17:07:09 +00002158
Chris Lattner79c11012005-09-26 04:44:35 +00002159 // CurInst - The current instruction we're evaluating.
2160 BasicBlock::iterator CurInst = F->begin()->begin();
2161
2162 // This is the main evaluation loop.
2163 while (1) {
2164 Constant *InstResult = 0;
2165
2166 if (StoreInst *SI = dyn_cast<StoreInst>(CurInst)) {
Chris Lattnercd271422005-09-27 04:45:34 +00002167 if (SI->isVolatile()) return false; // no volatile accesses.
Chris Lattner79c11012005-09-26 04:44:35 +00002168 Constant *Ptr = getVal(Values, SI->getOperand(1));
2169 if (!isSimpleEnoughPointerToCommit(Ptr))
2170 // If this is too complex for us to commit, reject it.
Chris Lattnercd271422005-09-27 04:45:34 +00002171 return false;
Chris Lattner79c11012005-09-26 04:44:35 +00002172 Constant *Val = getVal(Values, SI->getOperand(0));
2173 MutatedMemory[Ptr] = Val;
2174 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CurInst)) {
2175 InstResult = ConstantExpr::get(BO->getOpcode(),
2176 getVal(Values, BO->getOperand(0)),
2177 getVal(Values, BO->getOperand(1)));
Reid Spencere4d87aa2006-12-23 06:05:41 +00002178 } else if (CmpInst *CI = dyn_cast<CmpInst>(CurInst)) {
2179 InstResult = ConstantExpr::getCompare(CI->getPredicate(),
2180 getVal(Values, CI->getOperand(0)),
2181 getVal(Values, CI->getOperand(1)));
Chris Lattner79c11012005-09-26 04:44:35 +00002182 } else if (CastInst *CI = dyn_cast<CastInst>(CurInst)) {
Chris Lattner9a989f02006-11-30 17:26:08 +00002183 InstResult = ConstantExpr::getCast(CI->getOpcode(),
2184 getVal(Values, CI->getOperand(0)),
Chris Lattner79c11012005-09-26 04:44:35 +00002185 CI->getType());
2186 } else if (SelectInst *SI = dyn_cast<SelectInst>(CurInst)) {
2187 InstResult = ConstantExpr::getSelect(getVal(Values, SI->getOperand(0)),
2188 getVal(Values, SI->getOperand(1)),
2189 getVal(Values, SI->getOperand(2)));
Chris Lattner04de1cf2005-09-26 05:15:37 +00002190 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurInst)) {
2191 Constant *P = getVal(Values, GEP->getOperand(0));
Chris Lattner55eb1c42007-01-31 04:40:53 +00002192 SmallVector<Constant*, 8> GEPOps;
Gabor Greif5e463212008-05-29 01:59:18 +00002193 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end();
2194 i != e; ++i)
2195 GEPOps.push_back(getVal(Values, *i));
Chris Lattner55eb1c42007-01-31 04:40:53 +00002196 InstResult = ConstantExpr::getGetElementPtr(P, &GEPOps[0], GEPOps.size());
Chris Lattner04de1cf2005-09-26 05:15:37 +00002197 } else if (LoadInst *LI = dyn_cast<LoadInst>(CurInst)) {
Chris Lattnercd271422005-09-27 04:45:34 +00002198 if (LI->isVolatile()) return false; // no volatile accesses.
Chris Lattner04de1cf2005-09-26 05:15:37 +00002199 InstResult = ComputeLoadResult(getVal(Values, LI->getOperand(0)),
2200 MutatedMemory);
Chris Lattnercd271422005-09-27 04:45:34 +00002201 if (InstResult == 0) return false; // Could not evaluate load.
Chris Lattnera22fdb02005-09-26 17:07:09 +00002202 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(CurInst)) {
Chris Lattnercd271422005-09-27 04:45:34 +00002203 if (AI->isArrayAllocation()) return false; // Cannot handle array allocs.
Chris Lattnera22fdb02005-09-26 17:07:09 +00002204 const Type *Ty = AI->getType()->getElementType();
2205 AllocaTmps.push_back(new GlobalVariable(Ty, false,
2206 GlobalValue::InternalLinkage,
2207 UndefValue::get(Ty),
2208 AI->getName()));
Chris Lattnercd271422005-09-27 04:45:34 +00002209 InstResult = AllocaTmps.back();
2210 } else if (CallInst *CI = dyn_cast<CallInst>(CurInst)) {
Devang Patel412a4462009-03-09 23:04:12 +00002211
2212 // Debug info can safely be ignored here.
2213 if (isa<DbgInfoIntrinsic>(CI)) {
2214 ++CurInst;
2215 continue;
2216 }
2217
Chris Lattner7cd580f2006-07-07 21:37:01 +00002218 // Cannot handle inline asm.
2219 if (isa<InlineAsm>(CI->getOperand(0))) return false;
2220
Chris Lattnercd271422005-09-27 04:45:34 +00002221 // Resolve function pointers.
2222 Function *Callee = dyn_cast<Function>(getVal(Values, CI->getOperand(0)));
2223 if (!Callee) return false; // Cannot resolve.
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002224
Chris Lattnercd271422005-09-27 04:45:34 +00002225 std::vector<Constant*> Formals;
Gabor Greif5e463212008-05-29 01:59:18 +00002226 for (User::op_iterator i = CI->op_begin() + 1, e = CI->op_end();
2227 i != e; ++i)
2228 Formals.push_back(getVal(Values, *i));
Chris Lattnercd271422005-09-27 04:45:34 +00002229
Reid Spencer5cbf9852007-01-30 20:08:39 +00002230 if (Callee->isDeclaration()) {
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002231 // If this is a function we can constant fold, do it.
Chris Lattner6c1f5652007-01-30 23:14:52 +00002232 if (Constant *C = ConstantFoldCall(Callee, &Formals[0],
2233 Formals.size())) {
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002234 InstResult = C;
2235 } else {
2236 return false;
2237 }
2238 } else {
2239 if (Callee->getFunctionType()->isVarArg())
2240 return false;
2241
2242 Constant *RetVal;
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002243 // Execute the call, if successful, use the return value.
2244 if (!EvaluateFunction(Callee, RetVal, Formals, CallStack,
2245 MutatedMemory, AllocaTmps))
2246 return false;
2247 InstResult = RetVal;
2248 }
Reid Spencer3ed469c2006-11-02 20:25:50 +00002249 } else if (isa<TerminatorInst>(CurInst)) {
Chris Lattnercdf98be2005-09-26 04:57:38 +00002250 BasicBlock *NewBB = 0;
2251 if (BranchInst *BI = dyn_cast<BranchInst>(CurInst)) {
2252 if (BI->isUnconditional()) {
2253 NewBB = BI->getSuccessor(0);
2254 } else {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002255 ConstantInt *Cond =
2256 dyn_cast<ConstantInt>(getVal(Values, BI->getCondition()));
Chris Lattner97d1fad2007-01-12 18:30:11 +00002257 if (!Cond) return false; // Cannot determine.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002258
Reid Spencer579dca12007-01-12 04:24:46 +00002259 NewBB = BI->getSuccessor(!Cond->getZExtValue());
Chris Lattnercdf98be2005-09-26 04:57:38 +00002260 }
2261 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(CurInst)) {
2262 ConstantInt *Val =
2263 dyn_cast<ConstantInt>(getVal(Values, SI->getCondition()));
Chris Lattnercd271422005-09-27 04:45:34 +00002264 if (!Val) return false; // Cannot determine.
Chris Lattnercdf98be2005-09-26 04:57:38 +00002265 NewBB = SI->getSuccessor(SI->findCaseValue(Val));
2266 } else if (ReturnInst *RI = dyn_cast<ReturnInst>(CurInst)) {
Chris Lattnercd271422005-09-27 04:45:34 +00002267 if (RI->getNumOperands())
2268 RetVal = getVal(Values, RI->getOperand(0));
2269
2270 CallStack.pop_back(); // return from fn.
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002271 return true; // We succeeded at evaluating this ctor!
Chris Lattnercdf98be2005-09-26 04:57:38 +00002272 } else {
Chris Lattnercd271422005-09-27 04:45:34 +00002273 // invoke, unwind, unreachable.
2274 return false; // Cannot handle this terminator.
Chris Lattnercdf98be2005-09-26 04:57:38 +00002275 }
2276
2277 // Okay, we succeeded in evaluating this control flow. See if we have
Chris Lattnercd271422005-09-27 04:45:34 +00002278 // executed the new block before. If so, we have a looping function,
2279 // which we cannot evaluate in reasonable time.
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002280 if (!ExecutedBlocks.insert(NewBB))
Chris Lattnercd271422005-09-27 04:45:34 +00002281 return false; // looped!
Chris Lattnercdf98be2005-09-26 04:57:38 +00002282
2283 // Okay, we have never been in this block before. Check to see if there
2284 // are any PHI nodes. If so, evaluate them with information about where
2285 // we came from.
2286 BasicBlock *OldBB = CurInst->getParent();
2287 CurInst = NewBB->begin();
2288 PHINode *PN;
2289 for (; (PN = dyn_cast<PHINode>(CurInst)); ++CurInst)
2290 Values[PN] = getVal(Values, PN->getIncomingValueForBlock(OldBB));
2291
2292 // Do NOT increment CurInst. We know that the terminator had no value.
2293 continue;
Chris Lattner79c11012005-09-26 04:44:35 +00002294 } else {
Chris Lattner79c11012005-09-26 04:44:35 +00002295 // Did not know how to evaluate this!
Chris Lattnercd271422005-09-27 04:45:34 +00002296 return false;
Chris Lattner79c11012005-09-26 04:44:35 +00002297 }
2298
2299 if (!CurInst->use_empty())
2300 Values[CurInst] = InstResult;
2301
2302 // Advance program counter.
2303 ++CurInst;
2304 }
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002305}
2306
2307/// EvaluateStaticConstructor - Evaluate static constructors in the function, if
2308/// we can. Return true if we can, false otherwise.
2309static bool EvaluateStaticConstructor(Function *F) {
2310 /// MutatedMemory - For each store we execute, we update this map. Loads
2311 /// check this to get the most up-to-date value. If evaluation is successful,
2312 /// this state is committed to the process.
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002313 DenseMap<Constant*, Constant*> MutatedMemory;
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002314
2315 /// AllocaTmps - To 'execute' an alloca, we create a temporary global variable
2316 /// to represent its body. This vector is needed so we can delete the
2317 /// temporary globals when we are done.
2318 std::vector<GlobalVariable*> AllocaTmps;
2319
2320 /// CallStack - This is used to detect recursion. In pathological situations
2321 /// we could hit exponential behavior, but at least there is nothing
2322 /// unbounded.
2323 std::vector<Function*> CallStack;
2324
2325 // Call the function.
Chris Lattnercd271422005-09-27 04:45:34 +00002326 Constant *RetValDummy;
2327 bool EvalSuccess = EvaluateFunction(F, RetValDummy, std::vector<Constant*>(),
2328 CallStack, MutatedMemory, AllocaTmps);
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002329 if (EvalSuccess) {
Chris Lattnera22fdb02005-09-26 17:07:09 +00002330 // We succeeded at evaluation: commit the result.
Bill Wendling0a81aac2006-11-26 10:02:32 +00002331 DOUT << "FULLY EVALUATED GLOBAL CTOR FUNCTION '"
2332 << F->getName() << "' to " << MutatedMemory.size()
2333 << " stores.\n";
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002334 for (DenseMap<Constant*, Constant*>::iterator I = MutatedMemory.begin(),
Chris Lattnera22fdb02005-09-26 17:07:09 +00002335 E = MutatedMemory.end(); I != E; ++I)
2336 CommitValueTo(I->second, I->first);
2337 }
Chris Lattner79c11012005-09-26 04:44:35 +00002338
Chris Lattnera22fdb02005-09-26 17:07:09 +00002339 // At this point, we are done interpreting. If we created any 'alloca'
2340 // temporaries, release them now.
2341 while (!AllocaTmps.empty()) {
2342 GlobalVariable *Tmp = AllocaTmps.back();
2343 AllocaTmps.pop_back();
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002344
Chris Lattnera22fdb02005-09-26 17:07:09 +00002345 // If there are still users of the alloca, the program is doing something
2346 // silly, e.g. storing the address of the alloca somewhere and using it
2347 // later. Since this is undefined, we'll just make it be null.
2348 if (!Tmp->use_empty())
2349 Tmp->replaceAllUsesWith(Constant::getNullValue(Tmp->getType()));
2350 delete Tmp;
2351 }
Chris Lattneraae4a1c2005-09-26 07:34:35 +00002352
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002353 return EvalSuccess;
Chris Lattner79c11012005-09-26 04:44:35 +00002354}
2355
Chris Lattnerdb973e62005-09-26 02:31:18 +00002356
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002357
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002358/// OptimizeGlobalCtorsList - Simplify and evaluation global ctors if possible.
2359/// Return true if anything changed.
2360bool GlobalOpt::OptimizeGlobalCtorsList(GlobalVariable *&GCL) {
2361 std::vector<Function*> Ctors = ParseGlobalCtors(GCL);
2362 bool MadeChange = false;
2363 if (Ctors.empty()) return false;
2364
2365 // Loop over global ctors, optimizing them when we can.
2366 for (unsigned i = 0; i != Ctors.size(); ++i) {
2367 Function *F = Ctors[i];
2368 // Found a null terminator in the middle of the list, prune off the rest of
2369 // the list.
Chris Lattner7d8e58f2005-09-26 02:19:27 +00002370 if (F == 0) {
2371 if (i != Ctors.size()-1) {
2372 Ctors.resize(i+1);
2373 MadeChange = true;
2374 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002375 break;
2376 }
2377
Chris Lattner79c11012005-09-26 04:44:35 +00002378 // We cannot simplify external ctor functions.
2379 if (F->empty()) continue;
2380
2381 // If we can evaluate the ctor at compile time, do.
2382 if (EvaluateStaticConstructor(F)) {
2383 Ctors.erase(Ctors.begin()+i);
2384 MadeChange = true;
2385 --i;
2386 ++NumCtorsEvaluated;
2387 continue;
2388 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002389 }
2390
2391 if (!MadeChange) return false;
2392
Chris Lattnerdb973e62005-09-26 02:31:18 +00002393 GCL = InstallGlobalCtors(GCL, Ctors);
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002394 return true;
2395}
2396
Duncan Sandsfc5940d2009-03-06 10:21:56 +00002397bool GlobalOpt::OptimizeGlobalAliases(Module &M) {
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002398 bool Changed = false;
2399
Duncan Sands177d84e2009-01-07 20:01:06 +00002400 for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end();
Duncan Sands4782b302009-02-15 09:56:08 +00002401 I != E;) {
2402 Module::alias_iterator J = I++;
Duncan Sandsfc5940d2009-03-06 10:21:56 +00002403 // Aliases without names cannot be referenced outside this module.
2404 if (!J->hasName() && !J->isDeclaration())
2405 J->setLinkage(GlobalValue::InternalLinkage);
Duncan Sands4782b302009-02-15 09:56:08 +00002406 // If the aliasee may change at link time, nothing can be done - bail out.
2407 if (J->mayBeOverridden())
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002408 continue;
2409
Duncan Sands4782b302009-02-15 09:56:08 +00002410 Constant *Aliasee = J->getAliasee();
2411 GlobalValue *Target = cast<GlobalValue>(Aliasee->stripPointerCasts());
Duncan Sands95c5d0f2009-02-18 17:55:38 +00002412 Target->removeDeadConstantUsers();
Duncan Sands4782b302009-02-15 09:56:08 +00002413 bool hasOneUse = Target->hasOneUse() && Aliasee->hasOneUse();
2414
2415 // Make all users of the alias use the aliasee instead.
2416 if (!J->use_empty()) {
2417 J->replaceAllUsesWith(Aliasee);
2418 ++NumAliasesResolved;
2419 Changed = true;
2420 }
2421
2422 // If the aliasee has internal linkage, give it the name and linkage
2423 // of the alias, and delete the alias. This turns:
2424 // define internal ... @f(...)
2425 // @a = alias ... @f
2426 // into:
2427 // define ... @a(...)
Duncan Sands7ae5b9e2009-02-17 17:50:04 +00002428 if (!Target->hasLocalLinkage())
Duncan Sands4782b302009-02-15 09:56:08 +00002429 continue;
2430
2431 // The transform is only useful if the alias does not have internal linkage.
Duncan Sands7ae5b9e2009-02-17 17:50:04 +00002432 if (J->hasLocalLinkage())
Duncan Sands4782b302009-02-15 09:56:08 +00002433 continue;
2434
Duncan Sandsa37d1192009-02-15 11:54:49 +00002435 // Do not perform the transform if multiple aliases potentially target the
2436 // aliasee. This check also ensures that it is safe to replace the section
2437 // and other attributes of the aliasee with those of the alias.
Duncan Sands4782b302009-02-15 09:56:08 +00002438 if (!hasOneUse)
2439 continue;
2440
Duncan Sandsa37d1192009-02-15 11:54:49 +00002441 // Give the aliasee the name, linkage and other attributes of the alias.
Duncan Sands4782b302009-02-15 09:56:08 +00002442 Target->takeName(J);
2443 Target->setLinkage(J->getLinkage());
Duncan Sandsa37d1192009-02-15 11:54:49 +00002444 Target->GlobalValue::copyAttributesFrom(J);
Duncan Sands4782b302009-02-15 09:56:08 +00002445
2446 // Delete the alias.
2447 M.getAliasList().erase(J);
2448 ++NumAliasesRemoved;
2449 Changed = true;
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002450 }
2451
2452 return Changed;
2453}
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002454
Chris Lattner7a90b682004-10-07 04:16:33 +00002455bool GlobalOpt::runOnModule(Module &M) {
Chris Lattner079236d2004-02-25 21:34:36 +00002456 bool Changed = false;
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002457
2458 // Try to find the llvm.globalctors list.
2459 GlobalVariable *GlobalCtors = FindGlobalCtors(M);
Chris Lattner7a90b682004-10-07 04:16:33 +00002460
Chris Lattner7a90b682004-10-07 04:16:33 +00002461 bool LocalChange = true;
2462 while (LocalChange) {
2463 LocalChange = false;
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002464
2465 // Delete functions that are trivially dead, ccc -> fastcc
2466 LocalChange |= OptimizeFunctions(M);
2467
2468 // Optimize global_ctors list.
2469 if (GlobalCtors)
2470 LocalChange |= OptimizeGlobalCtorsList(GlobalCtors);
2471
2472 // Optimize non-address-taken globals.
2473 LocalChange |= OptimizeGlobalVars(M);
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002474
2475 // Resolve aliases, when possible.
Duncan Sandsfc5940d2009-03-06 10:21:56 +00002476 LocalChange |= OptimizeGlobalAliases(M);
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002477 Changed |= LocalChange;
Chris Lattner7a90b682004-10-07 04:16:33 +00002478 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002479
2480 // TODO: Move all global ctors functions to the end of the module for code
2481 // layout.
2482
Chris Lattner079236d2004-02-25 21:34:36 +00002483 return Changed;
2484}