blob: 73a5504a31498d02b4c914efe16da3719efac6a6 [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"
Victor Hernandezf006b182009-10-27 20:05:49 +000026#include "llvm/Analysis/MemoryBuiltins.h"
Chris Lattner30ba5692004-10-11 05:54:41 +000027#include "llvm/Target/TargetData.h"
Duncan Sands548448a2008-02-18 17:32:13 +000028#include "llvm/Support/CallSite.h"
Chris Lattner79066fa2007-01-30 23:46:24 +000029#include "llvm/Support/Debug.h"
Torok Edwinc25e7582009-07-11 20:10:48 +000030#include "llvm/Support/ErrorHandling.h"
Chris Lattner941db492008-01-14 02:09:12 +000031#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner998182b2008-04-26 07:40:11 +000032#include "llvm/Support/MathExtras.h"
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000033#include "llvm/Support/raw_ostream.h"
Chris Lattner5a6bb6a2008-12-16 07:34:30 +000034#include "llvm/ADT/DenseMap.h"
Chris Lattner81686182007-09-13 16:30:19 +000035#include "llvm/ADT/SmallPtrSet.h"
Chris Lattner55eb1c42007-01-31 04:40:53 +000036#include "llvm/ADT/SmallVector.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000037#include "llvm/ADT/Statistic.h"
Chris Lattnerbce4afe2008-12-17 05:28:49 +000038#include "llvm/ADT/STLExtras.h"
Chris Lattnere47ba742004-10-06 20:57:02 +000039#include <algorithm>
Chris Lattner079236d2004-02-25 21:34:36 +000040using namespace llvm;
41
Chris Lattner86453c52006-12-19 22:09:18 +000042STATISTIC(NumMarked , "Number of globals marked constant");
43STATISTIC(NumSRA , "Number of aggregate globals broken into scalars");
44STATISTIC(NumHeapSRA , "Number of heap objects SRA'd");
45STATISTIC(NumSubstitute,"Number of globals with initializers stored into them");
46STATISTIC(NumDeleted , "Number of globals deleted");
47STATISTIC(NumFnDeleted , "Number of functions deleted");
48STATISTIC(NumGlobUses , "Number of global uses devirtualized");
49STATISTIC(NumLocalized , "Number of globals localized");
50STATISTIC(NumShrunkToBool , "Number of global vars shrunk to booleans");
51STATISTIC(NumFastCallFns , "Number of functions converted to fastcc");
52STATISTIC(NumCtorsEvaluated, "Number of static ctors evaluated");
Duncan Sands3d5378f2008-02-16 20:56:04 +000053STATISTIC(NumNestRemoved , "Number of nest attributes removed");
Duncan Sands4782b302009-02-15 09:56:08 +000054STATISTIC(NumAliasesResolved, "Number of global aliases resolved");
55STATISTIC(NumAliasesRemoved, "Number of global aliases eliminated");
Chris Lattner079236d2004-02-25 21:34:36 +000056
Chris Lattner86453c52006-12-19 22:09:18 +000057namespace {
Nick Lewycky6726b6d2009-10-25 06:33:48 +000058 struct GlobalOpt : public ModulePass {
Chris Lattner30ba5692004-10-11 05:54:41 +000059 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner30ba5692004-10-11 05:54:41 +000060 }
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.
Nick Lewycky6726b6d2009-10-25 06:33:48 +000086struct 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 Lattner7b550cc2009-11-06 04:27:31 +0000247static Constant *getAggregateConstantElement(Constant *Agg, Constant *Idx) {
Chris Lattner670c8892004-10-08 17:32:09 +0000248 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())
Owen Andersona7235ea2009-07-31 20:28:14 +0000261 return Constant::getNullValue(STy->getElementType(IdxV));
Chris Lattner670c8892004-10-08 17:32:09 +0000262 } else if (const SequentialType *STy =
263 dyn_cast<SequentialType>(Agg->getType())) {
Owen Andersona7235ea2009-07-31 20:28:14 +0000264 return Constant::getNullValue(STy->getElementType());
Chris Lattner670c8892004-10-08 17:32:09 +0000265 }
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())
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000269 return UndefValue::get(STy->getElementType(IdxV));
Chris Lattner7a7ed022004-10-16 18:09:00 +0000270 } else if (const SequentialType *STy =
271 dyn_cast<SequentialType>(Agg->getType())) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000272 return UndefValue::get(STy->getElementType());
Chris Lattner7a7ed022004-10-16 18:09:00 +0000273 }
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.
Chris Lattner7b550cc2009-11-06 04:27:31 +0000283static bool CleanupConstantGlobalUsers(Value *V, Constant *Init) {
Chris Lattner031955d2004-10-10 16:43:46 +0000284 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)
Dan Gohmanc6f69e92009-10-05 16:36:26 +0000303 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
Chris Lattner7b550cc2009-11-06 04:27:31 +0000304 Changed |= CleanupConstantGlobalUsers(CE, SubInit);
Reid Spencer3da59db2006-11-27 01:05:10 +0000305 } else if (CE->getOpcode() == Instruction::BitCast &&
Duncan Sands1df98592010-02-16 11:11:14 +0000306 CE->getType()->isPointerTy()) {
Chris Lattner35c81b02005-02-27 18:58:52 +0000307 // Pointer cast, delete any stores and memsets to the global.
Chris Lattner7b550cc2009-11-06 04:27:31 +0000308 Changed |= CleanupConstantGlobalUsers(CE, 0);
Chris Lattner35c81b02005-02-27 18:58:52 +0000309 }
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 =
Chris Lattner7b550cc2009-11-06 04:27:31 +0000322 dyn_cast_or_null<ConstantExpr>(ConstantFoldInstruction(GEP));
Chris Lattner7b52fe72007-11-09 17:33:02 +0000323 if (Init && CE && CE->getOpcode() == Instruction::GetElementPtr)
Dan Gohmanc6f69e92009-10-05 16:36:26 +0000324 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
Chris Lattner7b52fe72007-11-09 17:33:02 +0000325 }
Chris Lattner7b550cc2009-11-06 04:27:31 +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 Lattner7b550cc2009-11-06 04:27:31 +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.
Dan Gohman6874a2a2009-08-18 14:58:19 +0000426 GEPI != E;
Chris Lattner941db492008-01-14 02:09:12 +0000427 ++GEPI) {
428 uint64_t NumElements;
429 if (const ArrayType *SubArrayTy = dyn_cast<ArrayType>(*GEPI))
430 NumElements = SubArrayTy->getNumElements();
Dan Gohman6874a2a2009-08-18 14:58:19 +0000431 else if (const VectorType *SubVectorTy = dyn_cast<VectorType>(*GEPI))
432 NumElements = SubVectorTy->getNumElements();
433 else {
Duncan Sands1df98592010-02-16 11:11:14 +0000434 assert((*GEPI)->isStructTy() &&
Dan Gohman6874a2a2009-08-18 14:58:19 +0000435 "Indexed GEP type is not array, vector, or struct!");
436 continue;
437 }
Chris Lattner941db492008-01-14 02:09:12 +0000438
439 ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPI.getOperand());
440 if (!IdxVal || IdxVal->getZExtValue() >= NumElements)
441 return false;
442 }
443 }
444
445 for (Value::use_iterator I = U->use_begin(), E = U->use_end(); I != E; ++I)
446 if (!isSafeSROAElementUse(*I))
447 return false;
448 return true;
449}
450
451/// GlobalUsersSafeToSRA - Look at all uses of the global and decide whether it
452/// is safe for us to perform this transformation.
453///
454static bool GlobalUsersSafeToSRA(GlobalValue *GV) {
455 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end();
456 UI != E; ++UI) {
457 if (!IsUserOfGlobalSafeForSRA(*UI, GV))
458 return false;
459 }
460 return true;
461}
462
463
Chris Lattner670c8892004-10-08 17:32:09 +0000464/// SRAGlobal - Perform scalar replacement of aggregates on the specified global
465/// variable. This opens the door for other optimizations by exposing the
466/// behavior of the program in a more fine-grained way. We have determined that
467/// this transformation is safe already. We return the first global variable we
468/// insert so that the caller can reprocess it.
Chris Lattner7b550cc2009-11-06 04:27:31 +0000469static GlobalVariable *SRAGlobal(GlobalVariable *GV, const TargetData &TD) {
Chris Lattner727c2102008-01-14 01:31:05 +0000470 // Make sure this global only has simple uses that we can SRA.
Chris Lattner941db492008-01-14 02:09:12 +0000471 if (!GlobalUsersSafeToSRA(GV))
Chris Lattner727c2102008-01-14 01:31:05 +0000472 return 0;
473
Rafael Espindolabb46f522009-01-15 20:18:42 +0000474 assert(GV->hasLocalLinkage() && !GV->isConstant());
Chris Lattner670c8892004-10-08 17:32:09 +0000475 Constant *Init = GV->getInitializer();
476 const Type *Ty = Init->getType();
Misha Brukmanfd939082005-04-21 23:48:37 +0000477
Chris Lattner670c8892004-10-08 17:32:09 +0000478 std::vector<GlobalVariable*> NewGlobals;
479 Module::GlobalListType &Globals = GV->getParent()->getGlobalList();
480
Chris Lattner998182b2008-04-26 07:40:11 +0000481 // Get the alignment of the global, either explicit or target-specific.
482 unsigned StartAlignment = GV->getAlignment();
483 if (StartAlignment == 0)
484 StartAlignment = TD.getABITypeAlignment(GV->getType());
485
Chris Lattner670c8892004-10-08 17:32:09 +0000486 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
487 NewGlobals.reserve(STy->getNumElements());
Chris Lattner998182b2008-04-26 07:40:11 +0000488 const StructLayout &Layout = *TD.getStructLayout(STy);
Chris Lattner670c8892004-10-08 17:32:09 +0000489 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
490 Constant *In = getAggregateConstantElement(Init,
Chris Lattner7b550cc2009-11-06 04:27:31 +0000491 ConstantInt::get(Type::getInt32Ty(STy->getContext()), i));
Chris Lattner670c8892004-10-08 17:32:09 +0000492 assert(In && "Couldn't get element of initializer?");
Chris Lattner7b550cc2009-11-06 04:27:31 +0000493 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(i), false,
Chris Lattner670c8892004-10-08 17:32:09 +0000494 GlobalVariable::InternalLinkage,
Daniel Dunbarfe09b202009-07-30 17:37:43 +0000495 In, GV->getName()+"."+Twine(i),
Matthijs Kooijmanbc1f9892008-07-17 11:59:53 +0000496 GV->isThreadLocal(),
Owen Anderson3d29df32009-07-08 01:26:06 +0000497 GV->getType()->getAddressSpace());
Chris Lattner670c8892004-10-08 17:32:09 +0000498 Globals.insert(GV, NGV);
499 NewGlobals.push_back(NGV);
Chris Lattner998182b2008-04-26 07:40:11 +0000500
501 // Calculate the known alignment of the field. If the original aggregate
502 // had 256 byte alignment for example, something might depend on that:
503 // propagate info to each field.
504 uint64_t FieldOffset = Layout.getElementOffset(i);
505 unsigned NewAlign = (unsigned)MinAlign(StartAlignment, FieldOffset);
506 if (NewAlign > TD.getABITypeAlignment(STy->getElementType(i)))
507 NGV->setAlignment(NewAlign);
Chris Lattner670c8892004-10-08 17:32:09 +0000508 }
509 } else if (const SequentialType *STy = dyn_cast<SequentialType>(Ty)) {
510 unsigned NumElements = 0;
511 if (const ArrayType *ATy = dyn_cast<ArrayType>(STy))
512 NumElements = ATy->getNumElements();
Chris Lattner670c8892004-10-08 17:32:09 +0000513 else
Chris Lattner998182b2008-04-26 07:40:11 +0000514 NumElements = cast<VectorType>(STy)->getNumElements();
Chris Lattner670c8892004-10-08 17:32:09 +0000515
Chris Lattner1f21ef12005-02-23 16:53:04 +0000516 if (NumElements > 16 && GV->hasNUsesOrMore(16))
Chris Lattnerd514d822005-02-01 01:23:31 +0000517 return 0; // It's not worth it.
Chris Lattner670c8892004-10-08 17:32:09 +0000518 NewGlobals.reserve(NumElements);
Chris Lattner998182b2008-04-26 07:40:11 +0000519
Duncan Sands777d2302009-05-09 07:06:46 +0000520 uint64_t EltSize = TD.getTypeAllocSize(STy->getElementType());
Chris Lattner998182b2008-04-26 07:40:11 +0000521 unsigned EltAlign = TD.getABITypeAlignment(STy->getElementType());
Chris Lattner670c8892004-10-08 17:32:09 +0000522 for (unsigned i = 0, e = NumElements; i != e; ++i) {
523 Constant *In = getAggregateConstantElement(Init,
Chris Lattner7b550cc2009-11-06 04:27:31 +0000524 ConstantInt::get(Type::getInt32Ty(Init->getContext()), i));
Chris Lattner670c8892004-10-08 17:32:09 +0000525 assert(In && "Couldn't get element of initializer?");
526
Chris Lattner7b550cc2009-11-06 04:27:31 +0000527 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(), false,
Chris Lattner670c8892004-10-08 17:32:09 +0000528 GlobalVariable::InternalLinkage,
Daniel Dunbarfe09b202009-07-30 17:37:43 +0000529 In, GV->getName()+"."+Twine(i),
Matthijs Kooijmanbc1f9892008-07-17 11:59:53 +0000530 GV->isThreadLocal(),
Owen Andersone9b11b42009-07-08 19:03:57 +0000531 GV->getType()->getAddressSpace());
Chris Lattner670c8892004-10-08 17:32:09 +0000532 Globals.insert(GV, NGV);
533 NewGlobals.push_back(NGV);
Chris Lattner998182b2008-04-26 07:40:11 +0000534
535 // Calculate the known alignment of the field. If the original aggregate
536 // had 256 byte alignment for example, something might depend on that:
537 // propagate info to each field.
538 unsigned NewAlign = (unsigned)MinAlign(StartAlignment, EltSize*i);
539 if (NewAlign > EltAlign)
540 NGV->setAlignment(NewAlign);
Chris Lattner670c8892004-10-08 17:32:09 +0000541 }
542 }
543
544 if (NewGlobals.empty())
545 return 0;
546
David Greene3215b0e2010-01-05 01:28:05 +0000547 DEBUG(dbgs() << "PERFORMING GLOBAL SRA ON: " << *GV);
Chris Lattner30ba5692004-10-11 05:54:41 +0000548
Chris Lattner7b550cc2009-11-06 04:27:31 +0000549 Constant *NullInt =Constant::getNullValue(Type::getInt32Ty(GV->getContext()));
Chris Lattner670c8892004-10-08 17:32:09 +0000550
551 // Loop over all of the uses of the global, replacing the constantexpr geps,
552 // with smaller constantexpr geps or direct references.
553 while (!GV->use_empty()) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000554 User *GEP = GV->use_back();
555 assert(((isa<ConstantExpr>(GEP) &&
556 cast<ConstantExpr>(GEP)->getOpcode()==Instruction::GetElementPtr)||
557 isa<GetElementPtrInst>(GEP)) && "NonGEP CE's are not SRAable!");
Misha Brukmanfd939082005-04-21 23:48:37 +0000558
Chris Lattner670c8892004-10-08 17:32:09 +0000559 // Ignore the 1th operand, which has to be zero or else the program is quite
560 // broken (undefined). Get the 2nd operand, which is the structure or array
561 // index.
Reid Spencerb83eb642006-10-20 07:07:24 +0000562 unsigned Val = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
Chris Lattner670c8892004-10-08 17:32:09 +0000563 if (Val >= NewGlobals.size()) Val = 0; // Out of bound array access.
564
Chris Lattner30ba5692004-10-11 05:54:41 +0000565 Value *NewPtr = NewGlobals[Val];
Chris Lattner670c8892004-10-08 17:32:09 +0000566
567 // Form a shorter GEP if needed.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000568 if (GEP->getNumOperands() > 3) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000569 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEP)) {
Chris Lattner55eb1c42007-01-31 04:40:53 +0000570 SmallVector<Constant*, 8> Idxs;
Chris Lattner30ba5692004-10-11 05:54:41 +0000571 Idxs.push_back(NullInt);
572 for (unsigned i = 3, e = CE->getNumOperands(); i != e; ++i)
573 Idxs.push_back(CE->getOperand(i));
Owen Andersonbaf3c402009-07-29 18:55:55 +0000574 NewPtr = ConstantExpr::getGetElementPtr(cast<Constant>(NewPtr),
Chris Lattner55eb1c42007-01-31 04:40:53 +0000575 &Idxs[0], Idxs.size());
Chris Lattner30ba5692004-10-11 05:54:41 +0000576 } else {
577 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(GEP);
Chris Lattner699d1442007-01-31 19:59:55 +0000578 SmallVector<Value*, 8> Idxs;
Chris Lattner30ba5692004-10-11 05:54:41 +0000579 Idxs.push_back(NullInt);
580 for (unsigned i = 3, e = GEPI->getNumOperands(); i != e; ++i)
581 Idxs.push_back(GEPI->getOperand(i));
Gabor Greif051a9502008-04-06 20:25:17 +0000582 NewPtr = GetElementPtrInst::Create(NewPtr, Idxs.begin(), Idxs.end(),
Daniel Dunbarfe09b202009-07-30 17:37:43 +0000583 GEPI->getName()+"."+Twine(Val),GEPI);
Chris Lattner30ba5692004-10-11 05:54:41 +0000584 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000585 }
Chris Lattner30ba5692004-10-11 05:54:41 +0000586 GEP->replaceAllUsesWith(NewPtr);
587
588 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(GEP))
Chris Lattner7a7ed022004-10-16 18:09:00 +0000589 GEPI->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +0000590 else
591 cast<ConstantExpr>(GEP)->destroyConstant();
Chris Lattner670c8892004-10-08 17:32:09 +0000592 }
593
Chris Lattnere40e2d12004-10-08 20:25:55 +0000594 // Delete the old global, now that it is dead.
595 Globals.erase(GV);
Chris Lattner670c8892004-10-08 17:32:09 +0000596 ++NumSRA;
Chris Lattner30ba5692004-10-11 05:54:41 +0000597
598 // Loop over the new globals array deleting any globals that are obviously
599 // dead. This can arise due to scalarization of a structure or an array that
600 // has elements that are dead.
601 unsigned FirstGlobal = 0;
602 for (unsigned i = 0, e = NewGlobals.size(); i != e; ++i)
603 if (NewGlobals[i]->use_empty()) {
604 Globals.erase(NewGlobals[i]);
605 if (FirstGlobal == i) ++FirstGlobal;
606 }
607
608 return FirstGlobal != NewGlobals.size() ? NewGlobals[FirstGlobal] : 0;
Chris Lattner670c8892004-10-08 17:32:09 +0000609}
610
Chris Lattner9b34a612004-10-09 21:48:45 +0000611/// AllUsesOfValueWillTrapIfNull - Return true if all users of the specified
Chris Lattner81686182007-09-13 16:30:19 +0000612/// value will trap if the value is dynamically null. PHIs keeps track of any
613/// phi nodes we've seen to avoid reprocessing them.
614static bool AllUsesOfValueWillTrapIfNull(Value *V,
615 SmallPtrSet<PHINode*, 8> &PHIs) {
Chris Lattner9b34a612004-10-09 21:48:45 +0000616 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
617 if (isa<LoadInst>(*UI)) {
618 // Will trap.
619 } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
620 if (SI->getOperand(0) == V) {
Bill Wendlinge8156192006-12-07 01:30:32 +0000621 //cerr << "NONTRAPPING USE: " << **UI;
Chris Lattner9b34a612004-10-09 21:48:45 +0000622 return false; // Storing the value.
623 }
624 } else if (CallInst *CI = dyn_cast<CallInst>(*UI)) {
625 if (CI->getOperand(0) != V) {
Bill Wendlinge8156192006-12-07 01:30:32 +0000626 //cerr << "NONTRAPPING USE: " << **UI;
Chris Lattner9b34a612004-10-09 21:48:45 +0000627 return false; // Not calling the ptr
628 }
629 } else if (InvokeInst *II = dyn_cast<InvokeInst>(*UI)) {
630 if (II->getOperand(0) != V) {
Bill Wendlinge8156192006-12-07 01:30:32 +0000631 //cerr << "NONTRAPPING USE: " << **UI;
Chris Lattner9b34a612004-10-09 21:48:45 +0000632 return false; // Not calling the ptr
633 }
Chris Lattner81686182007-09-13 16:30:19 +0000634 } else if (BitCastInst *CI = dyn_cast<BitCastInst>(*UI)) {
635 if (!AllUsesOfValueWillTrapIfNull(CI, PHIs)) return false;
Chris Lattner9b34a612004-10-09 21:48:45 +0000636 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(*UI)) {
Chris Lattner81686182007-09-13 16:30:19 +0000637 if (!AllUsesOfValueWillTrapIfNull(GEPI, PHIs)) return false;
638 } else if (PHINode *PN = dyn_cast<PHINode>(*UI)) {
639 // If we've already seen this phi node, ignore it, it has already been
640 // checked.
Jakob Stoklund Olesenb489d0f2010-01-29 23:54:14 +0000641 if (PHIs.insert(PN) && !AllUsesOfValueWillTrapIfNull(PN, PHIs))
642 return false;
Reid Spencere4d87aa2006-12-23 06:05:41 +0000643 } else if (isa<ICmpInst>(*UI) &&
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000644 isa<ConstantPointerNull>(UI->getOperand(1))) {
Nick Lewyckye7ee59b2010-02-25 06:39:10 +0000645 // Ignore icmp X, null
Chris Lattner9b34a612004-10-09 21:48:45 +0000646 } else {
Bill Wendlinge8156192006-12-07 01:30:32 +0000647 //cerr << "NONTRAPPING USE: " << **UI;
Chris Lattner9b34a612004-10-09 21:48:45 +0000648 return false;
649 }
650 return true;
651}
652
653/// AllUsesOfLoadedValueWillTrapIfNull - Return true if all uses of any loads
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000654/// from GV will trap if the loaded value is null. Note that this also permits
655/// comparisons of the loaded value against null, as a special case.
Chris Lattner9b34a612004-10-09 21:48:45 +0000656static bool AllUsesOfLoadedValueWillTrapIfNull(GlobalVariable *GV) {
657 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI!=E; ++UI)
658 if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
Chris Lattner81686182007-09-13 16:30:19 +0000659 SmallPtrSet<PHINode*, 8> PHIs;
660 if (!AllUsesOfValueWillTrapIfNull(LI, PHIs))
Chris Lattner9b34a612004-10-09 21:48:45 +0000661 return false;
662 } else if (isa<StoreInst>(*UI)) {
663 // Ignore stores to the global.
664 } else {
665 // We don't know or understand this user, bail out.
Bill Wendlinge8156192006-12-07 01:30:32 +0000666 //cerr << "UNKNOWN USER OF GLOBAL!: " << **UI;
Chris Lattner9b34a612004-10-09 21:48:45 +0000667 return false;
668 }
669
670 return true;
671}
672
Chris Lattner7b550cc2009-11-06 04:27:31 +0000673static bool OptimizeAwayTrappingUsesOfValue(Value *V, Constant *NewV) {
Chris Lattner708148e2004-10-10 23:14:11 +0000674 bool Changed = false;
675 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ) {
676 Instruction *I = cast<Instruction>(*UI++);
677 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
678 LI->setOperand(0, NewV);
679 Changed = true;
680 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
681 if (SI->getOperand(1) == V) {
682 SI->setOperand(1, NewV);
683 Changed = true;
684 }
685 } else if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
686 if (I->getOperand(0) == V) {
687 // Calling through the pointer! Turn into a direct call, but be careful
688 // that the pointer is not also being passed as an argument.
689 I->setOperand(0, NewV);
690 Changed = true;
691 bool PassedAsArg = false;
692 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i)
693 if (I->getOperand(i) == V) {
694 PassedAsArg = true;
695 I->setOperand(i, NewV);
696 }
697
698 if (PassedAsArg) {
699 // Being passed as an argument also. Be careful to not invalidate UI!
700 UI = V->use_begin();
701 }
702 }
703 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
704 Changed |= OptimizeAwayTrappingUsesOfValue(CI,
Owen Andersonbaf3c402009-07-29 18:55:55 +0000705 ConstantExpr::getCast(CI->getOpcode(),
Chris Lattner7b550cc2009-11-06 04:27:31 +0000706 NewV, CI->getType()));
Chris Lattner708148e2004-10-10 23:14:11 +0000707 if (CI->use_empty()) {
708 Changed = true;
Chris Lattner7a7ed022004-10-16 18:09:00 +0000709 CI->eraseFromParent();
Chris Lattner708148e2004-10-10 23:14:11 +0000710 }
711 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
712 // Should handle GEP here.
Chris Lattner55eb1c42007-01-31 04:40:53 +0000713 SmallVector<Constant*, 8> Idxs;
714 Idxs.reserve(GEPI->getNumOperands()-1);
Gabor Greif5e463212008-05-29 01:59:18 +0000715 for (User::op_iterator i = GEPI->op_begin() + 1, e = GEPI->op_end();
716 i != e; ++i)
717 if (Constant *C = dyn_cast<Constant>(*i))
Chris Lattner55eb1c42007-01-31 04:40:53 +0000718 Idxs.push_back(C);
Chris Lattner708148e2004-10-10 23:14:11 +0000719 else
720 break;
Chris Lattner55eb1c42007-01-31 04:40:53 +0000721 if (Idxs.size() == GEPI->getNumOperands()-1)
Chris Lattner708148e2004-10-10 23:14:11 +0000722 Changed |= OptimizeAwayTrappingUsesOfValue(GEPI,
Owen Andersonbaf3c402009-07-29 18:55:55 +0000723 ConstantExpr::getGetElementPtr(NewV, &Idxs[0],
Chris Lattner7b550cc2009-11-06 04:27:31 +0000724 Idxs.size()));
Chris Lattner708148e2004-10-10 23:14:11 +0000725 if (GEPI->use_empty()) {
726 Changed = true;
Chris Lattner7a7ed022004-10-16 18:09:00 +0000727 GEPI->eraseFromParent();
Chris Lattner708148e2004-10-10 23:14:11 +0000728 }
729 }
730 }
731
732 return Changed;
733}
734
735
736/// OptimizeAwayTrappingUsesOfLoads - The specified global has only one non-null
737/// value stored into it. If there are uses of the loaded value that would trap
738/// if the loaded value is dynamically null, then we know that they cannot be
739/// reachable with a null optimize away the load.
Chris Lattner7b550cc2009-11-06 04:27:31 +0000740static bool OptimizeAwayTrappingUsesOfLoads(GlobalVariable *GV, Constant *LV) {
Chris Lattner708148e2004-10-10 23:14:11 +0000741 bool Changed = false;
742
Chris Lattner92c6bd22009-01-14 00:12:58 +0000743 // Keep track of whether we are able to remove all the uses of the global
744 // other than the store that defines it.
745 bool AllNonStoreUsesGone = true;
746
Chris Lattner708148e2004-10-10 23:14:11 +0000747 // Replace all uses of loads with uses of uses of the stored value.
Chris Lattner92c6bd22009-01-14 00:12:58 +0000748 for (Value::use_iterator GUI = GV->use_begin(), E = GV->use_end(); GUI != E;){
749 User *GlobalUser = *GUI++;
750 if (LoadInst *LI = dyn_cast<LoadInst>(GlobalUser)) {
Chris Lattner7b550cc2009-11-06 04:27:31 +0000751 Changed |= OptimizeAwayTrappingUsesOfValue(LI, LV);
Chris Lattner92c6bd22009-01-14 00:12:58 +0000752 // If we were able to delete all uses of the loads
753 if (LI->use_empty()) {
754 LI->eraseFromParent();
755 Changed = true;
756 } else {
757 AllNonStoreUsesGone = false;
758 }
759 } else if (isa<StoreInst>(GlobalUser)) {
760 // Ignore the store that stores "LV" to the global.
761 assert(GlobalUser->getOperand(1) == GV &&
762 "Must be storing *to* the global");
Chris Lattner708148e2004-10-10 23:14:11 +0000763 } else {
Chris Lattner92c6bd22009-01-14 00:12:58 +0000764 AllNonStoreUsesGone = false;
765
766 // If we get here we could have other crazy uses that are transitively
767 // loaded.
768 assert((isa<PHINode>(GlobalUser) || isa<SelectInst>(GlobalUser) ||
769 isa<ConstantExpr>(GlobalUser)) && "Only expect load and stores!");
Chris Lattner708148e2004-10-10 23:14:11 +0000770 }
Chris Lattner92c6bd22009-01-14 00:12:58 +0000771 }
Chris Lattner708148e2004-10-10 23:14:11 +0000772
773 if (Changed) {
David Greene3215b0e2010-01-05 01:28:05 +0000774 DEBUG(dbgs() << "OPTIMIZED LOADS FROM STORED ONCE POINTER: " << *GV);
Chris Lattner708148e2004-10-10 23:14:11 +0000775 ++NumGlobUses;
776 }
777
Chris Lattner708148e2004-10-10 23:14:11 +0000778 // If we nuked all of the loads, then none of the stores are needed either,
779 // nor is the global.
Chris Lattner92c6bd22009-01-14 00:12:58 +0000780 if (AllNonStoreUsesGone) {
David Greene3215b0e2010-01-05 01:28:05 +0000781 DEBUG(dbgs() << " *** GLOBAL NOW DEAD!\n");
Chris Lattner7b550cc2009-11-06 04:27:31 +0000782 CleanupConstantGlobalUsers(GV, 0);
Chris Lattner708148e2004-10-10 23:14:11 +0000783 if (GV->use_empty()) {
Chris Lattner7a7ed022004-10-16 18:09:00 +0000784 GV->eraseFromParent();
Chris Lattner708148e2004-10-10 23:14:11 +0000785 ++NumDeleted;
786 }
787 Changed = true;
788 }
789 return Changed;
790}
791
Chris Lattner30ba5692004-10-11 05:54:41 +0000792/// ConstantPropUsersOf - Walk the use list of V, constant folding all of the
793/// instructions that are foldable.
Chris Lattner7b550cc2009-11-06 04:27:31 +0000794static void ConstantPropUsersOf(Value *V) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000795 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; )
796 if (Instruction *I = dyn_cast<Instruction>(*UI++))
Chris Lattner7b550cc2009-11-06 04:27:31 +0000797 if (Constant *NewC = ConstantFoldInstruction(I)) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000798 I->replaceAllUsesWith(NewC);
799
Chris Lattnerd514d822005-02-01 01:23:31 +0000800 // Advance UI to the next non-I use to avoid invalidating it!
801 // Instructions could multiply use V.
802 while (UI != E && *UI == I)
Chris Lattner30ba5692004-10-11 05:54:41 +0000803 ++UI;
Chris Lattnerd514d822005-02-01 01:23:31 +0000804 I->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +0000805 }
806}
807
808/// OptimizeGlobalAddressOfMalloc - This function takes the specified global
809/// variable, and transforms the program as if it always contained the result of
810/// the specified malloc. Because it is always the result of the specified
811/// malloc, there is no reason to actually DO the malloc. Instead, turn the
Chris Lattner6e8fbad2006-11-30 17:32:29 +0000812/// malloc into a global, and any loads of GV as uses of the new global.
Chris Lattner30ba5692004-10-11 05:54:41 +0000813static GlobalVariable *OptimizeGlobalAddressOfMalloc(GlobalVariable *GV,
Victor Hernandez83d63912009-09-18 22:35:49 +0000814 CallInst *CI,
Victor Hernandez9d0b7042009-11-07 00:16:28 +0000815 const Type *AllocTy,
Chris Lattnera6874652010-02-25 22:33:52 +0000816 ConstantInt *NElements,
Victor Hernandez83d63912009-09-18 22:35:49 +0000817 TargetData* TD) {
Chris Lattnera6874652010-02-25 22:33:52 +0000818 DEBUG(errs() << "PROMOTING GLOBAL: " << *GV << " CALL = " << *CI << '\n');
Victor Hernandez83d63912009-09-18 22:35:49 +0000819
Chris Lattnera6874652010-02-25 22:33:52 +0000820 const Type *GlobalType;
821 if (NElements->getZExtValue() == 1)
822 GlobalType = AllocTy;
823 else
824 // If we have an array allocation, the global variable is of an array.
825 GlobalType = ArrayType::get(AllocTy, NElements->getZExtValue());
Victor Hernandez83d63912009-09-18 22:35:49 +0000826
827 // Create the new global variable. The contents of the malloc'd memory is
828 // undefined, so initialize with an undef value.
Victor Hernandez83d63912009-09-18 22:35:49 +0000829 const Type *MAT = getMallocAllocatedType(CI);
Victor Hernandez83d63912009-09-18 22:35:49 +0000830 GlobalVariable *NewGV = new GlobalVariable(*GV->getParent(),
831 MAT, false,
Chris Lattnera6874652010-02-25 22:33:52 +0000832 GlobalValue::InternalLinkage,
833 UndefValue::get(MAT),
Victor Hernandez83d63912009-09-18 22:35:49 +0000834 GV->getName()+".body",
835 GV,
836 GV->isThreadLocal());
837
Chris Lattnera6874652010-02-25 22:33:52 +0000838 // If there are bitcast users of the malloc (which is typical, usually we have
839 // a malloc + bitcast) then replace them with uses of the new global. Update
840 // other users to use the global as well.
841 BitCastInst *TheBC = 0;
842 while (!CI->use_empty()) {
843 Instruction *User = cast<Instruction>(CI->use_back());
844 if (BitCastInst *BCI = dyn_cast<BitCastInst>(User)) {
845 if (BCI->getType() == NewGV->getType()) {
846 BCI->replaceAllUsesWith(NewGV);
847 BCI->eraseFromParent();
848 } else {
849 BCI->setOperand(0, NewGV);
850 }
851 } else {
852 if (TheBC == 0)
853 TheBC = new BitCastInst(NewGV, CI->getType(), "newgv", CI);
854 User->replaceUsesOfWith(CI, TheBC);
855 }
856 }
857
858 // Update Anything else that used the malloc or its bitcast now uses the global directly.
Victor Hernandez9d0b7042009-11-07 00:16:28 +0000859 CI->replaceAllUsesWith(new BitCastInst(NewGV, CI->getType(), "newgv", CI));
Victor Hernandez83d63912009-09-18 22:35:49 +0000860
861 Constant *RepValue = NewGV;
862 if (NewGV->getType() != GV->getType()->getElementType())
863 RepValue = ConstantExpr::getBitCast(RepValue,
864 GV->getType()->getElementType());
865
866 // If there is a comparison against null, we will insert a global bool to
867 // keep track of whether the global was initialized yet or not.
868 GlobalVariable *InitBool =
Chris Lattner7b550cc2009-11-06 04:27:31 +0000869 new GlobalVariable(Type::getInt1Ty(GV->getContext()), false,
Victor Hernandez83d63912009-09-18 22:35:49 +0000870 GlobalValue::InternalLinkage,
Chris Lattner7b550cc2009-11-06 04:27:31 +0000871 ConstantInt::getFalse(GV->getContext()),
872 GV->getName()+".init", GV->isThreadLocal());
Victor Hernandez83d63912009-09-18 22:35:49 +0000873 bool InitBoolUsed = false;
874
875 // Loop over all uses of GV, processing them in turn.
Chris Lattnera6874652010-02-25 22:33:52 +0000876 while (!GV->use_empty()) {
877 if (StoreInst *SI = dyn_cast<StoreInst>(GV->use_back())) {
Victor Hernandez83d63912009-09-18 22:35:49 +0000878 // The global is initialized when the store to it occurs.
Chris Lattner7b550cc2009-11-06 04:27:31 +0000879 new StoreInst(ConstantInt::getTrue(GV->getContext()), InitBool, SI);
Victor Hernandez83d63912009-09-18 22:35:49 +0000880 SI->eraseFromParent();
Chris Lattnera6874652010-02-25 22:33:52 +0000881 continue;
Victor Hernandez83d63912009-09-18 22:35:49 +0000882 }
Chris Lattnera6874652010-02-25 22:33:52 +0000883
884 LoadInst *LI = cast<LoadInst>(GV->use_back());
885 while (!LI->use_empty()) {
886 Use &LoadUse = LI->use_begin().getUse();
887 if (!isa<ICmpInst>(LoadUse.getUser())) {
888 LoadUse = RepValue;
889 continue;
890 }
891
892 ICmpInst *ICI = cast<ICmpInst>(LoadUse.getUser());
893 // Replace the cmp X, 0 with a use of the bool value.
894 Value *LV = new LoadInst(InitBool, InitBool->getName()+".val", ICI);
895 InitBoolUsed = true;
896 switch (ICI->getPredicate()) {
897 default: llvm_unreachable("Unknown ICmp Predicate!");
898 case ICmpInst::ICMP_ULT:
899 case ICmpInst::ICMP_SLT: // X < null -> always false
900 LV = ConstantInt::getFalse(GV->getContext());
901 break;
902 case ICmpInst::ICMP_ULE:
903 case ICmpInst::ICMP_SLE:
904 case ICmpInst::ICMP_EQ:
905 LV = BinaryOperator::CreateNot(LV, "notinit", ICI);
906 break;
907 case ICmpInst::ICMP_NE:
908 case ICmpInst::ICMP_UGE:
909 case ICmpInst::ICMP_SGE:
910 case ICmpInst::ICMP_UGT:
911 case ICmpInst::ICMP_SGT:
912 break; // no change.
913 }
914 ICI->replaceAllUsesWith(LV);
915 ICI->eraseFromParent();
916 }
917 LI->eraseFromParent();
918 }
Victor Hernandez83d63912009-09-18 22:35:49 +0000919
920 // If the initialization boolean was used, insert it, otherwise delete it.
921 if (!InitBoolUsed) {
922 while (!InitBool->use_empty()) // Delete initializations
Chris Lattnera6874652010-02-25 22:33:52 +0000923 cast<StoreInst>(InitBool->use_back())->eraseFromParent();
Victor Hernandez83d63912009-09-18 22:35:49 +0000924 delete InitBool;
925 } else
926 GV->getParent()->getGlobalList().insert(GV, InitBool);
927
Chris Lattnera6874652010-02-25 22:33:52 +0000928 // Now the GV is dead, nuke it and the malloc..
Victor Hernandez83d63912009-09-18 22:35:49 +0000929 GV->eraseFromParent();
Victor Hernandez83d63912009-09-18 22:35:49 +0000930 CI->eraseFromParent();
931
932 // To further other optimizations, loop over all users of NewGV and try to
933 // constant prop them. This will promote GEP instructions with constant
934 // indices into GEP constant-exprs, which will allow global-opt to hack on it.
Chris Lattner7b550cc2009-11-06 04:27:31 +0000935 ConstantPropUsersOf(NewGV);
Victor Hernandez83d63912009-09-18 22:35:49 +0000936 if (RepValue != NewGV)
Chris Lattner7b550cc2009-11-06 04:27:31 +0000937 ConstantPropUsersOf(RepValue);
Victor Hernandez83d63912009-09-18 22:35:49 +0000938
939 return NewGV;
940}
941
Chris Lattnerfa07e4f2004-12-02 07:11:07 +0000942/// ValueIsOnlyUsedLocallyOrStoredToOneGlobal - Scan the use-list of V checking
943/// to make sure that there are no complex uses of V. We permit simple things
944/// like dereferencing the pointer, but not storing through the address, unless
945/// it is to the specified global.
946static bool ValueIsOnlyUsedLocallyOrStoredToOneGlobal(Instruction *V,
Chris Lattnerc451f9c2007-09-13 16:37:20 +0000947 GlobalVariable *GV,
948 SmallPtrSet<PHINode*, 8> &PHIs) {
Chris Lattner49b6d4a2008-12-15 21:08:54 +0000949 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;++UI){
Jay Foad0906b1b2009-06-06 17:49:35 +0000950 Instruction *Inst = cast<Instruction>(*UI);
Chris Lattner49b6d4a2008-12-15 21:08:54 +0000951
952 if (isa<LoadInst>(Inst) || isa<CmpInst>(Inst)) {
953 continue; // Fine, ignore.
954 }
955
956 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
Chris Lattnerfa07e4f2004-12-02 07:11:07 +0000957 if (SI->getOperand(0) == V && SI->getOperand(1) != GV)
958 return false; // Storing the pointer itself... bad.
Chris Lattner49b6d4a2008-12-15 21:08:54 +0000959 continue; // Otherwise, storing through it, or storing into GV... fine.
960 }
961
962 if (isa<GetElementPtrInst>(Inst)) {
963 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(Inst, GV, PHIs))
Chris Lattnerfa07e4f2004-12-02 07:11:07 +0000964 return false;
Chris Lattner49b6d4a2008-12-15 21:08:54 +0000965 continue;
966 }
967
968 if (PHINode *PN = dyn_cast<PHINode>(Inst)) {
Chris Lattnerc451f9c2007-09-13 16:37:20 +0000969 // PHIs are ok if all uses are ok. Don't infinitely recurse through PHI
970 // cycles.
971 if (PHIs.insert(PN))
Chris Lattner5e6e4942007-09-14 03:41:21 +0000972 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(PN, GV, PHIs))
973 return false;
Chris Lattner49b6d4a2008-12-15 21:08:54 +0000974 continue;
Chris Lattnerfa07e4f2004-12-02 07:11:07 +0000975 }
Chris Lattner49b6d4a2008-12-15 21:08:54 +0000976
977 if (BitCastInst *BCI = dyn_cast<BitCastInst>(Inst)) {
978 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(BCI, GV, PHIs))
979 return false;
980 continue;
981 }
982
983 return false;
984 }
Chris Lattnerfa07e4f2004-12-02 07:11:07 +0000985 return true;
Chris Lattnerfa07e4f2004-12-02 07:11:07 +0000986}
987
Chris Lattner86395032006-09-30 23:32:09 +0000988/// ReplaceUsesOfMallocWithGlobal - The Alloc pointer is stored into GV
989/// somewhere. Transform all uses of the allocation into loads from the
990/// global and uses of the resultant pointer. Further, delete the store into
991/// GV. This assumes that these value pass the
992/// 'ValueIsOnlyUsedLocallyOrStoredToOneGlobal' predicate.
993static void ReplaceUsesOfMallocWithGlobal(Instruction *Alloc,
994 GlobalVariable *GV) {
995 while (!Alloc->use_empty()) {
Chris Lattnera637a8b2007-09-13 18:00:31 +0000996 Instruction *U = cast<Instruction>(*Alloc->use_begin());
997 Instruction *InsertPt = U;
Chris Lattner86395032006-09-30 23:32:09 +0000998 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
999 // If this is the store of the allocation into the global, remove it.
1000 if (SI->getOperand(1) == GV) {
1001 SI->eraseFromParent();
1002 continue;
1003 }
Chris Lattnera637a8b2007-09-13 18:00:31 +00001004 } else if (PHINode *PN = dyn_cast<PHINode>(U)) {
1005 // Insert the load in the corresponding predecessor, not right before the
1006 // PHI.
Gabor Greifa36791d2009-01-23 19:40:15 +00001007 InsertPt = PN->getIncomingBlock(Alloc->use_begin())->getTerminator();
Chris Lattner101f44e2008-12-15 21:44:34 +00001008 } else if (isa<BitCastInst>(U)) {
1009 // Must be bitcast between the malloc and store to initialize the global.
1010 ReplaceUsesOfMallocWithGlobal(U, GV);
1011 U->eraseFromParent();
1012 continue;
1013 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
1014 // If this is a "GEP bitcast" and the user is a store to the global, then
1015 // just process it as a bitcast.
1016 if (GEPI->hasAllZeroIndices() && GEPI->hasOneUse())
1017 if (StoreInst *SI = dyn_cast<StoreInst>(GEPI->use_back()))
1018 if (SI->getOperand(1) == GV) {
1019 // Must be bitcast GEP between the malloc and store to initialize
1020 // the global.
1021 ReplaceUsesOfMallocWithGlobal(GEPI, GV);
1022 GEPI->eraseFromParent();
1023 continue;
1024 }
Chris Lattner86395032006-09-30 23:32:09 +00001025 }
Chris Lattner101f44e2008-12-15 21:44:34 +00001026
Chris Lattner86395032006-09-30 23:32:09 +00001027 // Insert a load from the global, and use it instead of the malloc.
Chris Lattnera637a8b2007-09-13 18:00:31 +00001028 Value *NL = new LoadInst(GV, GV->getName()+".val", InsertPt);
Chris Lattner86395032006-09-30 23:32:09 +00001029 U->replaceUsesOfWith(Alloc, NL);
1030 }
1031}
1032
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001033/// LoadUsesSimpleEnoughForHeapSRA - Verify that all uses of V (a load, or a phi
1034/// of a load) are simple enough to perform heap SRA on. This permits GEP's
1035/// that index through the array and struct field, icmps of null, and PHIs.
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001036static bool LoadUsesSimpleEnoughForHeapSRA(Value *V,
Evan Cheng5d163962009-06-02 00:56:07 +00001037 SmallPtrSet<PHINode*, 32> &LoadUsingPHIs,
1038 SmallPtrSet<PHINode*, 32> &LoadUsingPHIsPerLoad) {
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001039 // We permit two users of the load: setcc comparing against the null
1040 // pointer, and a getelementptr of a specific form.
1041 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;++UI){
1042 Instruction *User = cast<Instruction>(*UI);
1043
1044 // Comparison against null is ok.
1045 if (ICmpInst *ICI = dyn_cast<ICmpInst>(User)) {
1046 if (!isa<ConstantPointerNull>(ICI->getOperand(1)))
1047 return false;
1048 continue;
1049 }
1050
1051 // getelementptr is also ok, but only a simple form.
1052 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
1053 // Must index into the array and into the struct.
1054 if (GEPI->getNumOperands() < 3)
1055 return false;
1056
1057 // Otherwise the GEP is ok.
1058 continue;
1059 }
1060
1061 if (PHINode *PN = dyn_cast<PHINode>(User)) {
Evan Cheng5d163962009-06-02 00:56:07 +00001062 if (!LoadUsingPHIsPerLoad.insert(PN))
1063 // This means some phi nodes are dependent on each other.
1064 // Avoid infinite looping!
1065 return false;
1066 if (!LoadUsingPHIs.insert(PN))
1067 // If we have already analyzed this PHI, then it is safe.
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001068 continue;
1069
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001070 // Make sure all uses of the PHI are simple enough to transform.
Evan Cheng5d163962009-06-02 00:56:07 +00001071 if (!LoadUsesSimpleEnoughForHeapSRA(PN,
1072 LoadUsingPHIs, LoadUsingPHIsPerLoad))
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001073 return false;
1074
1075 continue;
Chris Lattner86395032006-09-30 23:32:09 +00001076 }
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001077
1078 // Otherwise we don't know what this is, not ok.
1079 return false;
1080 }
1081
1082 return true;
1083}
1084
1085
1086/// AllGlobalLoadUsesSimpleEnoughForHeapSRA - If all users of values loaded from
1087/// GV are simple enough to perform HeapSRA, return true.
1088static bool AllGlobalLoadUsesSimpleEnoughForHeapSRA(GlobalVariable *GV,
Victor Hernandez83d63912009-09-18 22:35:49 +00001089 Instruction *StoredVal) {
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001090 SmallPtrSet<PHINode*, 32> LoadUsingPHIs;
Evan Cheng5d163962009-06-02 00:56:07 +00001091 SmallPtrSet<PHINode*, 32> LoadUsingPHIsPerLoad;
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001092 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI != E;
1093 ++UI)
Evan Cheng5d163962009-06-02 00:56:07 +00001094 if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
1095 if (!LoadUsesSimpleEnoughForHeapSRA(LI, LoadUsingPHIs,
1096 LoadUsingPHIsPerLoad))
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001097 return false;
Evan Cheng5d163962009-06-02 00:56:07 +00001098 LoadUsingPHIsPerLoad.clear();
1099 }
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001100
1101 // If we reach here, we know that all uses of the loads and transitive uses
1102 // (through PHI nodes) are simple enough to transform. However, we don't know
1103 // that all inputs the to the PHI nodes are in the same equivalence sets.
1104 // Check to verify that all operands of the PHIs are either PHIS that can be
1105 // transformed, loads from GV, or MI itself.
1106 for (SmallPtrSet<PHINode*, 32>::iterator I = LoadUsingPHIs.begin(),
1107 E = LoadUsingPHIs.end(); I != E; ++I) {
1108 PHINode *PN = *I;
1109 for (unsigned op = 0, e = PN->getNumIncomingValues(); op != e; ++op) {
1110 Value *InVal = PN->getIncomingValue(op);
1111
1112 // PHI of the stored value itself is ok.
Victor Hernandez83d63912009-09-18 22:35:49 +00001113 if (InVal == StoredVal) continue;
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001114
1115 if (PHINode *InPN = dyn_cast<PHINode>(InVal)) {
1116 // One of the PHIs in our set is (optimistically) ok.
1117 if (LoadUsingPHIs.count(InPN))
1118 continue;
1119 return false;
1120 }
1121
1122 // Load from GV is ok.
1123 if (LoadInst *LI = dyn_cast<LoadInst>(InVal))
1124 if (LI->getOperand(0) == GV)
1125 continue;
1126
1127 // UNDEF? NULL?
1128
1129 // Anything else is rejected.
1130 return false;
1131 }
1132 }
1133
Chris Lattner86395032006-09-30 23:32:09 +00001134 return true;
1135}
1136
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001137static Value *GetHeapSROAValue(Value *V, unsigned FieldNo,
1138 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001139 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001140 std::vector<Value*> &FieldVals = InsertedScalarizedValues[V];
1141
1142 if (FieldNo >= FieldVals.size())
1143 FieldVals.resize(FieldNo+1);
1144
1145 // If we already have this value, just reuse the previously scalarized
1146 // version.
1147 if (Value *FieldVal = FieldVals[FieldNo])
1148 return FieldVal;
1149
1150 // Depending on what instruction this is, we have several cases.
1151 Value *Result;
1152 if (LoadInst *LI = dyn_cast<LoadInst>(V)) {
1153 // This is a scalarized version of the load from the global. Just create
1154 // a new Load of the scalarized global.
1155 Result = new LoadInst(GetHeapSROAValue(LI->getOperand(0), FieldNo,
1156 InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001157 PHIsToRewrite),
Daniel Dunbarfe09b202009-07-30 17:37:43 +00001158 LI->getName()+".f"+Twine(FieldNo), LI);
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001159 } else if (PHINode *PN = dyn_cast<PHINode>(V)) {
1160 // PN's type is pointer to struct. Make a new PHI of pointer to struct
1161 // field.
1162 const StructType *ST =
1163 cast<StructType>(cast<PointerType>(PN->getType())->getElementType());
1164
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001165 Result =
Owen Andersondebcb012009-07-29 22:17:13 +00001166 PHINode::Create(PointerType::getUnqual(ST->getElementType(FieldNo)),
Daniel Dunbarfe09b202009-07-30 17:37:43 +00001167 PN->getName()+".f"+Twine(FieldNo), PN);
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001168 PHIsToRewrite.push_back(std::make_pair(PN, FieldNo));
1169 } else {
Torok Edwinc23197a2009-07-14 16:55:14 +00001170 llvm_unreachable("Unknown usable value");
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001171 Result = 0;
1172 }
1173
1174 return FieldVals[FieldNo] = Result;
Chris Lattnera637a8b2007-09-13 18:00:31 +00001175}
1176
Chris Lattner330245e2007-09-13 17:29:05 +00001177/// RewriteHeapSROALoadUser - Given a load instruction and a value derived from
1178/// the load, rewrite the derived value to use the HeapSRoA'd load.
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001179static void RewriteHeapSROALoadUser(Instruction *LoadUser,
1180 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001181 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
Chris Lattner330245e2007-09-13 17:29:05 +00001182 // If this is a comparison against null, handle it.
1183 if (ICmpInst *SCI = dyn_cast<ICmpInst>(LoadUser)) {
1184 assert(isa<ConstantPointerNull>(SCI->getOperand(1)));
1185 // If we have a setcc of the loaded pointer, we can use a setcc of any
1186 // field.
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001187 Value *NPtr = GetHeapSROAValue(SCI->getOperand(0), 0,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001188 InsertedScalarizedValues, PHIsToRewrite);
Chris Lattner330245e2007-09-13 17:29:05 +00001189
Owen Anderson333c4002009-07-09 23:48:35 +00001190 Value *New = new ICmpInst(SCI, SCI->getPredicate(), NPtr,
Owen Andersona7235ea2009-07-31 20:28:14 +00001191 Constant::getNullValue(NPtr->getType()),
Owen Anderson333c4002009-07-09 23:48:35 +00001192 SCI->getName());
Chris Lattner330245e2007-09-13 17:29:05 +00001193 SCI->replaceAllUsesWith(New);
1194 SCI->eraseFromParent();
1195 return;
1196 }
1197
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001198 // Handle 'getelementptr Ptr, Idx, i32 FieldNo ...'
Chris Lattnera637a8b2007-09-13 18:00:31 +00001199 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(LoadUser)) {
1200 assert(GEPI->getNumOperands() >= 3 && isa<ConstantInt>(GEPI->getOperand(2))
1201 && "Unexpected GEPI!");
Chris Lattner330245e2007-09-13 17:29:05 +00001202
Chris Lattnera637a8b2007-09-13 18:00:31 +00001203 // Load the pointer for this field.
1204 unsigned FieldNo = cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue();
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001205 Value *NewPtr = GetHeapSROAValue(GEPI->getOperand(0), FieldNo,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001206 InsertedScalarizedValues, PHIsToRewrite);
Chris Lattnera637a8b2007-09-13 18:00:31 +00001207
1208 // Create the new GEP idx vector.
1209 SmallVector<Value*, 8> GEPIdx;
1210 GEPIdx.push_back(GEPI->getOperand(1));
1211 GEPIdx.append(GEPI->op_begin()+3, GEPI->op_end());
1212
Gabor Greifb1dbcd82008-05-15 10:04:30 +00001213 Value *NGEPI = GetElementPtrInst::Create(NewPtr,
1214 GEPIdx.begin(), GEPIdx.end(),
Gabor Greif051a9502008-04-06 20:25:17 +00001215 GEPI->getName(), GEPI);
Chris Lattnera637a8b2007-09-13 18:00:31 +00001216 GEPI->replaceAllUsesWith(NGEPI);
1217 GEPI->eraseFromParent();
1218 return;
1219 }
Chris Lattner309f20f2007-09-13 21:31:36 +00001220
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001221 // Recursively transform the users of PHI nodes. This will lazily create the
1222 // PHIs that are needed for individual elements. Keep track of what PHIs we
1223 // see in InsertedScalarizedValues so that we don't get infinite loops (very
1224 // antisocial). If the PHI is already in InsertedScalarizedValues, it has
1225 // already been seen first by another load, so its uses have already been
1226 // processed.
1227 PHINode *PN = cast<PHINode>(LoadUser);
1228 bool Inserted;
1229 DenseMap<Value*, std::vector<Value*> >::iterator InsertPos;
1230 tie(InsertPos, Inserted) =
1231 InsertedScalarizedValues.insert(std::make_pair(PN, std::vector<Value*>()));
1232 if (!Inserted) return;
Chris Lattner309f20f2007-09-13 21:31:36 +00001233
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001234 // If this is the first time we've seen this PHI, recursively process all
1235 // users.
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001236 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end(); UI != E; ) {
1237 Instruction *User = cast<Instruction>(*UI++);
Chris Lattner7b550cc2009-11-06 04:27:31 +00001238 RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite);
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001239 }
Chris Lattner330245e2007-09-13 17:29:05 +00001240}
1241
Chris Lattner86395032006-09-30 23:32:09 +00001242/// RewriteUsesOfLoadForHeapSRoA - We are performing Heap SRoA on a global. Ptr
1243/// is a value loaded from the global. Eliminate all uses of Ptr, making them
1244/// use FieldGlobals instead. All uses of loaded values satisfy
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001245/// AllGlobalLoadUsesSimpleEnoughForHeapSRA.
Chris Lattner330245e2007-09-13 17:29:05 +00001246static void RewriteUsesOfLoadForHeapSRoA(LoadInst *Load,
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001247 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001248 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001249 for (Value::use_iterator UI = Load->use_begin(), E = Load->use_end();
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001250 UI != E; ) {
1251 Instruction *User = cast<Instruction>(*UI++);
Chris Lattner7b550cc2009-11-06 04:27:31 +00001252 RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite);
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001253 }
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001254
1255 if (Load->use_empty()) {
1256 Load->eraseFromParent();
1257 InsertedScalarizedValues.erase(Load);
1258 }
Chris Lattner86395032006-09-30 23:32:09 +00001259}
1260
Victor Hernandez83d63912009-09-18 22:35:49 +00001261/// PerformHeapAllocSRoA - CI is an allocation of an array of structures. Break
1262/// it up into multiple allocations of arrays of the fields.
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001263static GlobalVariable *PerformHeapAllocSRoA(GlobalVariable *GV, CallInst *CI,
1264 Value* NElems, TargetData *TD) {
David Greene3215b0e2010-01-05 01:28:05 +00001265 DEBUG(dbgs() << "SROA HEAP ALLOC: " << *GV << " MALLOC = " << *CI << '\n');
Victor Hernandez83d63912009-09-18 22:35:49 +00001266 const Type* MAT = getMallocAllocatedType(CI);
1267 const StructType *STy = cast<StructType>(MAT);
1268
1269 // There is guaranteed to be at least one use of the malloc (storing
1270 // it into GV). If there are other uses, change them to be uses of
1271 // the global to simplify later code. This also deletes the store
1272 // into GV.
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001273 ReplaceUsesOfMallocWithGlobal(CI, GV);
1274
Victor Hernandez83d63912009-09-18 22:35:49 +00001275 // Okay, at this point, there are no users of the malloc. Insert N
1276 // new mallocs at the same place as CI, and N globals.
1277 std::vector<Value*> FieldGlobals;
1278 std::vector<Value*> FieldMallocs;
1279
1280 for (unsigned FieldNo = 0, e = STy->getNumElements(); FieldNo != e;++FieldNo){
1281 const Type *FieldTy = STy->getElementType(FieldNo);
1282 const PointerType *PFieldTy = PointerType::getUnqual(FieldTy);
1283
1284 GlobalVariable *NGV =
1285 new GlobalVariable(*GV->getParent(),
1286 PFieldTy, false, GlobalValue::InternalLinkage,
1287 Constant::getNullValue(PFieldTy),
1288 GV->getName() + ".f" + Twine(FieldNo), GV,
1289 GV->isThreadLocal());
1290 FieldGlobals.push_back(NGV);
1291
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001292 unsigned TypeSize = TD->getTypeAllocSize(FieldTy);
Victor Hernandez631f3c02009-11-07 00:41:19 +00001293 if (const StructType *ST = dyn_cast<StructType>(FieldTy))
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001294 TypeSize = TD->getStructLayout(ST)->getSizeInBytes();
Victor Hernandez631f3c02009-11-07 00:41:19 +00001295 const Type *IntPtrTy = TD->getIntPtrType(CI->getContext());
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001296 Value *NMI = CallInst::CreateMalloc(CI, IntPtrTy, FieldTy,
1297 ConstantInt::get(IntPtrTy, TypeSize),
1298 NElems,
1299 CI->getName() + ".f" + Twine(FieldNo));
Chris Lattner3f5e0b82010-02-26 18:23:13 +00001300 FieldMallocs.push_back(NMI);
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001301 new StoreInst(NMI, NGV, CI);
Victor Hernandez83d63912009-09-18 22:35:49 +00001302 }
1303
1304 // The tricky aspect of this transformation is handling the case when malloc
1305 // fails. In the original code, malloc failing would set the result pointer
1306 // of malloc to null. In this case, some mallocs could succeed and others
1307 // could fail. As such, we emit code that looks like this:
1308 // F0 = malloc(field0)
1309 // F1 = malloc(field1)
1310 // F2 = malloc(field2)
1311 // if (F0 == 0 || F1 == 0 || F2 == 0) {
1312 // if (F0) { free(F0); F0 = 0; }
1313 // if (F1) { free(F1); F1 = 0; }
1314 // if (F2) { free(F2); F2 = 0; }
1315 // }
Victor Hernandez8e345a12009-11-10 08:32:25 +00001316 // The malloc can also fail if its argument is too large.
1317 Constant *ConstantZero = ConstantInt::get(CI->getOperand(1)->getType(), 0);
1318 Value *RunningOr = new ICmpInst(CI, ICmpInst::ICMP_SLT, CI->getOperand(1),
1319 ConstantZero, "isneg");
Victor Hernandez83d63912009-09-18 22:35:49 +00001320 for (unsigned i = 0, e = FieldMallocs.size(); i != e; ++i) {
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001321 Value *Cond = new ICmpInst(CI, ICmpInst::ICMP_EQ, FieldMallocs[i],
1322 Constant::getNullValue(FieldMallocs[i]->getType()),
1323 "isnull");
Victor Hernandez8e345a12009-11-10 08:32:25 +00001324 RunningOr = BinaryOperator::CreateOr(RunningOr, Cond, "tmp", CI);
Victor Hernandez83d63912009-09-18 22:35:49 +00001325 }
1326
1327 // Split the basic block at the old malloc.
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001328 BasicBlock *OrigBB = CI->getParent();
1329 BasicBlock *ContBB = OrigBB->splitBasicBlock(CI, "malloc_cont");
Victor Hernandez83d63912009-09-18 22:35:49 +00001330
1331 // Create the block to check the first condition. Put all these blocks at the
1332 // end of the function as they are unlikely to be executed.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001333 BasicBlock *NullPtrBlock = BasicBlock::Create(OrigBB->getContext(),
1334 "malloc_ret_null",
Victor Hernandez83d63912009-09-18 22:35:49 +00001335 OrigBB->getParent());
1336
1337 // Remove the uncond branch from OrigBB to ContBB, turning it into a cond
1338 // branch on RunningOr.
1339 OrigBB->getTerminator()->eraseFromParent();
1340 BranchInst::Create(NullPtrBlock, ContBB, RunningOr, OrigBB);
1341
1342 // Within the NullPtrBlock, we need to emit a comparison and branch for each
1343 // pointer, because some may be null while others are not.
1344 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
1345 Value *GVVal = new LoadInst(FieldGlobals[i], "tmp", NullPtrBlock);
1346 Value *Cmp = new ICmpInst(*NullPtrBlock, ICmpInst::ICMP_NE, GVVal,
1347 Constant::getNullValue(GVVal->getType()),
1348 "tmp");
Chris Lattner7b550cc2009-11-06 04:27:31 +00001349 BasicBlock *FreeBlock = BasicBlock::Create(Cmp->getContext(), "free_it",
Victor Hernandez83d63912009-09-18 22:35:49 +00001350 OrigBB->getParent());
Chris Lattner7b550cc2009-11-06 04:27:31 +00001351 BasicBlock *NextBlock = BasicBlock::Create(Cmp->getContext(), "next",
Victor Hernandez83d63912009-09-18 22:35:49 +00001352 OrigBB->getParent());
Victor Hernandez66284e02009-10-24 04:23:03 +00001353 Instruction *BI = BranchInst::Create(FreeBlock, NextBlock,
1354 Cmp, NullPtrBlock);
Victor Hernandez83d63912009-09-18 22:35:49 +00001355
1356 // Fill in FreeBlock.
Victor Hernandez66284e02009-10-24 04:23:03 +00001357 CallInst::CreateFree(GVVal, BI);
Victor Hernandez83d63912009-09-18 22:35:49 +00001358 new StoreInst(Constant::getNullValue(GVVal->getType()), FieldGlobals[i],
1359 FreeBlock);
1360 BranchInst::Create(NextBlock, FreeBlock);
1361
1362 NullPtrBlock = NextBlock;
1363 }
1364
1365 BranchInst::Create(ContBB, NullPtrBlock);
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001366
1367 // CI is no longer needed, remove it.
Victor Hernandez83d63912009-09-18 22:35:49 +00001368 CI->eraseFromParent();
1369
1370 /// InsertedScalarizedLoads - As we process loads, if we can't immediately
1371 /// update all uses of the load, keep track of what scalarized loads are
1372 /// inserted for a given load.
1373 DenseMap<Value*, std::vector<Value*> > InsertedScalarizedValues;
1374 InsertedScalarizedValues[GV] = FieldGlobals;
1375
1376 std::vector<std::pair<PHINode*, unsigned> > PHIsToRewrite;
1377
1378 // Okay, the malloc site is completely handled. All of the uses of GV are now
1379 // loads, and all uses of those loads are simple. Rewrite them to use loads
1380 // of the per-field globals instead.
1381 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI != E;) {
1382 Instruction *User = cast<Instruction>(*UI++);
1383
1384 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Chris Lattner7b550cc2009-11-06 04:27:31 +00001385 RewriteUsesOfLoadForHeapSRoA(LI, InsertedScalarizedValues, PHIsToRewrite);
Victor Hernandez83d63912009-09-18 22:35:49 +00001386 continue;
1387 }
1388
1389 // Must be a store of null.
1390 StoreInst *SI = cast<StoreInst>(User);
1391 assert(isa<ConstantPointerNull>(SI->getOperand(0)) &&
1392 "Unexpected heap-sra user!");
1393
1394 // Insert a store of null into each global.
1395 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
1396 const PointerType *PT = cast<PointerType>(FieldGlobals[i]->getType());
1397 Constant *Null = Constant::getNullValue(PT->getElementType());
1398 new StoreInst(Null, FieldGlobals[i], SI);
1399 }
1400 // Erase the original store.
1401 SI->eraseFromParent();
1402 }
1403
1404 // While we have PHIs that are interesting to rewrite, do it.
1405 while (!PHIsToRewrite.empty()) {
1406 PHINode *PN = PHIsToRewrite.back().first;
1407 unsigned FieldNo = PHIsToRewrite.back().second;
1408 PHIsToRewrite.pop_back();
1409 PHINode *FieldPN = cast<PHINode>(InsertedScalarizedValues[PN][FieldNo]);
1410 assert(FieldPN->getNumIncomingValues() == 0 &&"Already processed this phi");
1411
1412 // Add all the incoming values. This can materialize more phis.
1413 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1414 Value *InVal = PN->getIncomingValue(i);
1415 InVal = GetHeapSROAValue(InVal, FieldNo, InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001416 PHIsToRewrite);
Victor Hernandez83d63912009-09-18 22:35:49 +00001417 FieldPN->addIncoming(InVal, PN->getIncomingBlock(i));
1418 }
1419 }
1420
1421 // Drop all inter-phi links and any loads that made it this far.
1422 for (DenseMap<Value*, std::vector<Value*> >::iterator
1423 I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
1424 I != E; ++I) {
1425 if (PHINode *PN = dyn_cast<PHINode>(I->first))
1426 PN->dropAllReferences();
1427 else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
1428 LI->dropAllReferences();
1429 }
1430
1431 // Delete all the phis and loads now that inter-references are dead.
1432 for (DenseMap<Value*, std::vector<Value*> >::iterator
1433 I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
1434 I != E; ++I) {
1435 if (PHINode *PN = dyn_cast<PHINode>(I->first))
1436 PN->eraseFromParent();
1437 else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
1438 LI->eraseFromParent();
1439 }
1440
1441 // The old global is now dead, remove it.
1442 GV->eraseFromParent();
1443
1444 ++NumHeapSRA;
1445 return cast<GlobalVariable>(FieldGlobals[0]);
1446}
1447
Chris Lattnere61d0a62008-12-15 21:02:25 +00001448/// TryToOptimizeStoreOfMallocToGlobal - This function is called when we see a
1449/// pointer global variable with a single value stored it that is a malloc or
1450/// cast of malloc.
1451static bool TryToOptimizeStoreOfMallocToGlobal(GlobalVariable *GV,
Victor Hernandez83d63912009-09-18 22:35:49 +00001452 CallInst *CI,
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001453 const Type *AllocTy,
Victor Hernandez83d63912009-09-18 22:35:49 +00001454 Module::global_iterator &GVI,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001455 TargetData *TD) {
Victor Hernandez83d63912009-09-18 22:35:49 +00001456 // If this is a malloc of an abstract type, don't touch it.
1457 if (!AllocTy->isSized())
1458 return false;
1459
1460 // We can't optimize this global unless all uses of it are *known* to be
1461 // of the malloc value, not of the null initializer value (consider a use
1462 // that compares the global's value against zero to see if the malloc has
1463 // been reached). To do this, we check to see if all uses of the global
1464 // would trap if the global were null: this proves that they must all
1465 // happen after the malloc.
1466 if (!AllUsesOfLoadedValueWillTrapIfNull(GV))
1467 return false;
1468
1469 // We can't optimize this if the malloc itself is used in a complex way,
1470 // for example, being stored into multiple globals. This allows the
1471 // malloc to be stored into the specified global, loaded setcc'd, and
1472 // GEP'd. These are all things we could transform to using the global
1473 // for.
1474 {
1475 SmallPtrSet<PHINode*, 8> PHIs;
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001476 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(CI, GV, PHIs))
Victor Hernandez83d63912009-09-18 22:35:49 +00001477 return false;
1478 }
1479
1480 // If we have a global that is only initialized with a fixed size malloc,
1481 // transform the program to use global memory instead of malloc'd memory.
1482 // This eliminates dynamic allocation, avoids an indirection accessing the
1483 // data, and exposes the resultant global to further GlobalOpt.
Victor Hernandez8db42d22009-10-16 23:12:25 +00001484 // We cannot optimize the malloc if we cannot determine malloc array size.
Victor Hernandez8e345a12009-11-10 08:32:25 +00001485 if (Value *NElems = getMallocArraySize(CI, TD, true)) {
Victor Hernandez2491ce02009-10-15 20:14:52 +00001486 if (ConstantInt *NElements = dyn_cast<ConstantInt>(NElems))
1487 // Restrict this transformation to only working on small allocations
1488 // (2048 bytes currently), as we don't want to introduce a 16M global or
1489 // something.
1490 if (TD &&
1491 NElements->getZExtValue() * TD->getTypeAllocSize(AllocTy) < 2048) {
Chris Lattnera6874652010-02-25 22:33:52 +00001492 GVI = OptimizeGlobalAddressOfMalloc(GV, CI, AllocTy, NElements, TD);
Victor Hernandez2491ce02009-10-15 20:14:52 +00001493 return true;
1494 }
Victor Hernandez83d63912009-09-18 22:35:49 +00001495
Victor Hernandez8db42d22009-10-16 23:12:25 +00001496 // If the allocation is an array of structures, consider transforming this
1497 // into multiple malloc'd arrays, one for each field. This is basically
1498 // SRoA for malloc'd memory.
Victor Hernandez83d63912009-09-18 22:35:49 +00001499
Victor Hernandez8db42d22009-10-16 23:12:25 +00001500 // If this is an allocation of a fixed size array of structs, analyze as a
1501 // variable size array. malloc [100 x struct],1 -> malloc struct, 100
Victor Hernandez90f48e72009-10-28 20:18:55 +00001502 if (NElems == ConstantInt::get(CI->getOperand(1)->getType(), 1))
Victor Hernandez8db42d22009-10-16 23:12:25 +00001503 if (const ArrayType *AT = dyn_cast<ArrayType>(AllocTy))
1504 AllocTy = AT->getElementType();
Victor Hernandez83d63912009-09-18 22:35:49 +00001505
Victor Hernandez8db42d22009-10-16 23:12:25 +00001506 if (const StructType *AllocSTy = dyn_cast<StructType>(AllocTy)) {
1507 // This the structure has an unreasonable number of fields, leave it
1508 // alone.
1509 if (AllocSTy->getNumElements() <= 16 && AllocSTy->getNumElements() != 0 &&
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001510 AllGlobalLoadUsesSimpleEnoughForHeapSRA(GV, CI)) {
Victor Hernandez83d63912009-09-18 22:35:49 +00001511
Victor Hernandez8db42d22009-10-16 23:12:25 +00001512 // If this is a fixed size array, transform the Malloc to be an alloc of
1513 // structs. malloc [100 x struct],1 -> malloc struct, 100
1514 if (const ArrayType *AT =
1515 dyn_cast<ArrayType>(getMallocAllocatedType(CI))) {
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001516 const Type *IntPtrTy = TD->getIntPtrType(CI->getContext());
1517 unsigned TypeSize = TD->getStructLayout(AllocSTy)->getSizeInBytes();
1518 Value *AllocSize = ConstantInt::get(IntPtrTy, TypeSize);
1519 Value *NumElements = ConstantInt::get(IntPtrTy, AT->getNumElements());
1520 Instruction *Malloc = CallInst::CreateMalloc(CI, IntPtrTy, AllocSTy,
1521 AllocSize, NumElements,
1522 CI->getName());
1523 Instruction *Cast = new BitCastInst(Malloc, CI->getType(), "tmp", CI);
1524 CI->replaceAllUsesWith(Cast);
Victor Hernandez8db42d22009-10-16 23:12:25 +00001525 CI->eraseFromParent();
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001526 CI = dyn_cast<BitCastInst>(Malloc) ?
Victor Hernandez631f3c02009-11-07 00:41:19 +00001527 extractMallocCallFromBitCast(Malloc) : cast<CallInst>(Malloc);
Victor Hernandez8db42d22009-10-16 23:12:25 +00001528 }
Victor Hernandez83d63912009-09-18 22:35:49 +00001529
Victor Hernandez8e345a12009-11-10 08:32:25 +00001530 GVI = PerformHeapAllocSRoA(GV, CI, getMallocArraySize(CI, TD, true),TD);
Victor Hernandez8db42d22009-10-16 23:12:25 +00001531 return true;
1532 }
Victor Hernandez83d63912009-09-18 22:35:49 +00001533 }
1534 }
1535
1536 return false;
1537}
1538
Chris Lattner9b34a612004-10-09 21:48:45 +00001539// OptimizeOnceStoredGlobal - Try to optimize globals based on the knowledge
1540// that only one value (besides its initializer) is ever stored to the global.
Chris Lattner30ba5692004-10-11 05:54:41 +00001541static bool OptimizeOnceStoredGlobal(GlobalVariable *GV, Value *StoredOnceVal,
Chris Lattner7f8897f2006-08-27 22:42:52 +00001542 Module::global_iterator &GVI,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001543 TargetData *TD) {
Chris Lattner344b41c2008-12-15 21:20:32 +00001544 // Ignore no-op GEPs and bitcasts.
1545 StoredOnceVal = StoredOnceVal->stripPointerCasts();
Chris Lattner9b34a612004-10-09 21:48:45 +00001546
Chris Lattner708148e2004-10-10 23:14:11 +00001547 // If we are dealing with a pointer global that is initialized to null and
1548 // only has one (non-null) value stored into it, then we can optimize any
1549 // users of the loaded value (often calls and loads) that would trap if the
1550 // value was null.
Duncan Sands1df98592010-02-16 11:11:14 +00001551 if (GV->getInitializer()->getType()->isPointerTy() &&
Chris Lattner9b34a612004-10-09 21:48:45 +00001552 GV->getInitializer()->isNullValue()) {
Chris Lattner708148e2004-10-10 23:14:11 +00001553 if (Constant *SOVC = dyn_cast<Constant>(StoredOnceVal)) {
1554 if (GV->getInitializer()->getType() != SOVC->getType())
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001555 SOVC =
Owen Andersonbaf3c402009-07-29 18:55:55 +00001556 ConstantExpr::getBitCast(SOVC, GV->getInitializer()->getType());
Misha Brukmanfd939082005-04-21 23:48:37 +00001557
Chris Lattner708148e2004-10-10 23:14:11 +00001558 // Optimize away any trapping uses of the loaded value.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001559 if (OptimizeAwayTrappingUsesOfLoads(GV, SOVC))
Chris Lattner8be80122004-10-10 17:07:12 +00001560 return true;
Victor Hernandez83d63912009-09-18 22:35:49 +00001561 } else if (CallInst *CI = extractMallocCall(StoredOnceVal)) {
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001562 const Type* MallocType = getMallocAllocatedType(CI);
1563 if (MallocType && TryToOptimizeStoreOfMallocToGlobal(GV, CI, MallocType,
1564 GVI, TD))
1565 return true;
Chris Lattner708148e2004-10-10 23:14:11 +00001566 }
Chris Lattner9b34a612004-10-09 21:48:45 +00001567 }
Chris Lattner30ba5692004-10-11 05:54:41 +00001568
Chris Lattner9b34a612004-10-09 21:48:45 +00001569 return false;
1570}
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001571
Chris Lattner58e44f42008-01-14 01:17:44 +00001572/// TryToShrinkGlobalToBoolean - At this point, we have learned that the only
1573/// two values ever stored into GV are its initializer and OtherVal. See if we
1574/// can shrink the global into a boolean and select between the two values
1575/// whenever it is used. This exposes the values to other scalar optimizations.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001576static bool TryToShrinkGlobalToBoolean(GlobalVariable *GV, Constant *OtherVal) {
Chris Lattner58e44f42008-01-14 01:17:44 +00001577 const Type *GVElType = GV->getType()->getElementType();
1578
1579 // If GVElType is already i1, it is already shrunk. If the type of the GV is
Chris Lattner6f6923f2009-03-07 23:32:02 +00001580 // an FP value, pointer or vector, don't do this optimization because a select
1581 // between them is very expensive and unlikely to lead to later
1582 // simplification. In these cases, we typically end up with "cond ? v1 : v2"
1583 // where v1 and v2 both require constant pool loads, a big loss.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001584 if (GVElType == Type::getInt1Ty(GV->getContext()) ||
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001585 GVElType->isFloatingPointTy() ||
Duncan Sands1df98592010-02-16 11:11:14 +00001586 GVElType->isPointerTy() || GVElType->isVectorTy())
Chris Lattner58e44f42008-01-14 01:17:44 +00001587 return false;
1588
1589 // Walk the use list of the global seeing if all the uses are load or store.
1590 // If there is anything else, bail out.
1591 for (Value::use_iterator I = GV->use_begin(), E = GV->use_end(); I != E; ++I)
Devang Patel771281f2009-03-06 01:39:36 +00001592 if (!isa<LoadInst>(I) && !isa<StoreInst>(I))
Chris Lattner58e44f42008-01-14 01:17:44 +00001593 return false;
1594
David Greene3215b0e2010-01-05 01:28:05 +00001595 DEBUG(dbgs() << " *** SHRINKING TO BOOL: " << *GV);
Chris Lattner58e44f42008-01-14 01:17:44 +00001596
Chris Lattner96a86b22004-12-12 05:53:50 +00001597 // Create the new global, initializing it to false.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001598 GlobalVariable *NewGV = new GlobalVariable(Type::getInt1Ty(GV->getContext()),
1599 false,
1600 GlobalValue::InternalLinkage,
1601 ConstantInt::getFalse(GV->getContext()),
Nick Lewycky0e670df2009-05-03 03:49:08 +00001602 GV->getName()+".b",
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +00001603 GV->isThreadLocal());
Chris Lattner96a86b22004-12-12 05:53:50 +00001604 GV->getParent()->getGlobalList().insert(GV, NewGV);
1605
1606 Constant *InitVal = GV->getInitializer();
Chris Lattner7b550cc2009-11-06 04:27:31 +00001607 assert(InitVal->getType() != Type::getInt1Ty(GV->getContext()) &&
Owen Anderson1d0be152009-08-13 21:58:54 +00001608 "No reason to shrink to bool!");
Chris Lattner96a86b22004-12-12 05:53:50 +00001609
1610 // If initialized to zero and storing one into the global, we can use a cast
1611 // instead of a select to synthesize the desired value.
1612 bool IsOneZero = false;
1613 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal))
Reid Spencercae57542007-03-02 00:28:52 +00001614 IsOneZero = InitVal->isNullValue() && CI->isOne();
Chris Lattner96a86b22004-12-12 05:53:50 +00001615
1616 while (!GV->use_empty()) {
Devang Patel771281f2009-03-06 01:39:36 +00001617 Instruction *UI = cast<Instruction>(GV->use_back());
1618 if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
Chris Lattner96a86b22004-12-12 05:53:50 +00001619 // Change the store into a boolean store.
1620 bool StoringOther = SI->getOperand(0) == OtherVal;
1621 // Only do this if we weren't storing a loaded value.
Chris Lattner38c25562004-12-12 19:34:41 +00001622 Value *StoreVal;
Chris Lattner96a86b22004-12-12 05:53:50 +00001623 if (StoringOther || SI->getOperand(0) == InitVal)
Chris Lattner7b550cc2009-11-06 04:27:31 +00001624 StoreVal = ConstantInt::get(Type::getInt1Ty(GV->getContext()),
1625 StoringOther);
Chris Lattner38c25562004-12-12 19:34:41 +00001626 else {
1627 // Otherwise, we are storing a previously loaded copy. To do this,
1628 // change the copy from copying the original value to just copying the
1629 // bool.
1630 Instruction *StoredVal = cast<Instruction>(SI->getOperand(0));
1631
1632 // If we're already replaced the input, StoredVal will be a cast or
1633 // select instruction. If not, it will be a load of the original
1634 // global.
1635 if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
1636 assert(LI->getOperand(0) == GV && "Not a copy!");
1637 // Insert a new load, to preserve the saved value.
1638 StoreVal = new LoadInst(NewGV, LI->getName()+".b", LI);
1639 } else {
1640 assert((isa<CastInst>(StoredVal) || isa<SelectInst>(StoredVal)) &&
1641 "This is not a form that we understand!");
1642 StoreVal = StoredVal->getOperand(0);
1643 assert(isa<LoadInst>(StoreVal) && "Not a load of NewGV!");
1644 }
1645 }
1646 new StoreInst(StoreVal, NewGV, SI);
Devang Patel771281f2009-03-06 01:39:36 +00001647 } else {
Chris Lattner96a86b22004-12-12 05:53:50 +00001648 // Change the load into a load of bool then a select.
Devang Patel771281f2009-03-06 01:39:36 +00001649 LoadInst *LI = cast<LoadInst>(UI);
Chris Lattner046800a2007-02-11 01:08:35 +00001650 LoadInst *NLI = new LoadInst(NewGV, LI->getName()+".b", LI);
Chris Lattner96a86b22004-12-12 05:53:50 +00001651 Value *NSI;
1652 if (IsOneZero)
Chris Lattner046800a2007-02-11 01:08:35 +00001653 NSI = new ZExtInst(NLI, LI->getType(), "", LI);
Misha Brukmanfd939082005-04-21 23:48:37 +00001654 else
Gabor Greif051a9502008-04-06 20:25:17 +00001655 NSI = SelectInst::Create(NLI, OtherVal, InitVal, "", LI);
Chris Lattner046800a2007-02-11 01:08:35 +00001656 NSI->takeName(LI);
Chris Lattner96a86b22004-12-12 05:53:50 +00001657 LI->replaceAllUsesWith(NSI);
Devang Patel771281f2009-03-06 01:39:36 +00001658 }
1659 UI->eraseFromParent();
Chris Lattner96a86b22004-12-12 05:53:50 +00001660 }
1661
1662 GV->eraseFromParent();
Chris Lattner58e44f42008-01-14 01:17:44 +00001663 return true;
Chris Lattner96a86b22004-12-12 05:53:50 +00001664}
1665
1666
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001667/// ProcessInternalGlobal - Analyze the specified global variable and optimize
1668/// it if possible. If we make a change, return true.
Chris Lattner30ba5692004-10-11 05:54:41 +00001669bool GlobalOpt::ProcessInternalGlobal(GlobalVariable *GV,
Chris Lattnere4d5c442005-03-15 04:54:21 +00001670 Module::global_iterator &GVI) {
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00001671 SmallPtrSet<PHINode*, 16> PHIUsers;
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001672 GlobalStatus GS;
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001673 GV->removeDeadConstantUsers();
1674
1675 if (GV->use_empty()) {
David Greene3215b0e2010-01-05 01:28:05 +00001676 DEBUG(dbgs() << "GLOBAL DEAD: " << *GV);
Chris Lattner7a7ed022004-10-16 18:09:00 +00001677 GV->eraseFromParent();
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001678 ++NumDeleted;
1679 return true;
1680 }
1681
1682 if (!AnalyzeGlobal(GV, GS, PHIUsers)) {
Chris Lattnercff16732006-09-30 19:40:30 +00001683#if 0
David Greene3215b0e2010-01-05 01:28:05 +00001684 DEBUG(dbgs() << "Global: " << *GV);
1685 DEBUG(dbgs() << " isLoaded = " << GS.isLoaded << "\n");
1686 DEBUG(dbgs() << " StoredType = ");
Chris Lattnercff16732006-09-30 19:40:30 +00001687 switch (GS.StoredType) {
David Greene3215b0e2010-01-05 01:28:05 +00001688 case GlobalStatus::NotStored: DEBUG(dbgs() << "NEVER STORED\n"); break;
1689 case GlobalStatus::isInitializerStored: DEBUG(dbgs() << "INIT STORED\n");
Victor Hernandez631f3c02009-11-07 00:41:19 +00001690 break;
David Greene3215b0e2010-01-05 01:28:05 +00001691 case GlobalStatus::isStoredOnce: DEBUG(dbgs() << "STORED ONCE\n"); break;
1692 case GlobalStatus::isStored: DEBUG(dbgs() << "stored\n"); break;
Chris Lattnercff16732006-09-30 19:40:30 +00001693 }
1694 if (GS.StoredType == GlobalStatus::isStoredOnce && GS.StoredOnceValue)
David Greene3215b0e2010-01-05 01:28:05 +00001695 DEBUG(dbgs() << " StoredOnceValue = " << *GS.StoredOnceValue << "\n");
Chris Lattnercff16732006-09-30 19:40:30 +00001696 if (GS.AccessingFunction && !GS.HasMultipleAccessingFunctions)
David Greene3215b0e2010-01-05 01:28:05 +00001697 DEBUG(dbgs() << " AccessingFunction = " << GS.AccessingFunction->getName()
Victor Hernandez631f3c02009-11-07 00:41:19 +00001698 << "\n");
David Greene3215b0e2010-01-05 01:28:05 +00001699 DEBUG(dbgs() << " HasMultipleAccessingFunctions = "
Victor Hernandez631f3c02009-11-07 00:41:19 +00001700 << GS.HasMultipleAccessingFunctions << "\n");
David Greene3215b0e2010-01-05 01:28:05 +00001701 DEBUG(dbgs() << " HasNonInstructionUser = "
Victor Hernandez631f3c02009-11-07 00:41:19 +00001702 << GS.HasNonInstructionUser<<"\n");
David Greene3215b0e2010-01-05 01:28:05 +00001703 DEBUG(dbgs() << "\n");
Chris Lattnercff16732006-09-30 19:40:30 +00001704#endif
1705
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +00001706 // If this is a first class global and has only one accessing function
1707 // and this function is main (which we know is not recursive we can make
1708 // this global a local variable) we replace the global with a local alloca
1709 // in this function.
1710 //
Dan Gohman399101a2008-05-23 00:17:26 +00001711 // NOTE: It doesn't make sense to promote non single-value types since we
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +00001712 // are just replacing static memory to stack memory.
Sanjiv Gupta059aa8c2009-06-17 06:47:15 +00001713 //
1714 // If the global is in different address space, don't bring it to stack.
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +00001715 if (!GS.HasMultipleAccessingFunctions &&
Chris Lattner553ca522005-06-15 21:11:48 +00001716 GS.AccessingFunction && !GS.HasNonInstructionUser &&
Dan Gohman399101a2008-05-23 00:17:26 +00001717 GV->getType()->getElementType()->isSingleValueType() &&
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +00001718 GS.AccessingFunction->getName() == "main" &&
Sanjiv Gupta059aa8c2009-06-17 06:47:15 +00001719 GS.AccessingFunction->hasExternalLinkage() &&
1720 GV->getType()->getAddressSpace() == 0) {
David Greene3215b0e2010-01-05 01:28:05 +00001721 DEBUG(dbgs() << "LOCALIZING GLOBAL: " << *GV);
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +00001722 Instruction* FirstI = GS.AccessingFunction->getEntryBlock().begin();
1723 const Type* ElemTy = GV->getType()->getElementType();
Nate Begeman14b05292005-11-05 09:21:28 +00001724 // FIXME: Pass Global's alignment when globals have alignment
Owen Anderson50dead02009-07-15 23:53:25 +00001725 AllocaInst* Alloca = new AllocaInst(ElemTy, NULL, GV->getName(), FirstI);
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +00001726 if (!isa<UndefValue>(GV->getInitializer()))
1727 new StoreInst(GV->getInitializer(), Alloca, FirstI);
Misha Brukmanfd939082005-04-21 23:48:37 +00001728
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +00001729 GV->replaceAllUsesWith(Alloca);
1730 GV->eraseFromParent();
1731 ++NumLocalized;
1732 return true;
1733 }
Chris Lattnercff16732006-09-30 19:40:30 +00001734
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001735 // If the global is never loaded (but may be stored to), it is dead.
1736 // Delete it now.
1737 if (!GS.isLoaded) {
David Greene3215b0e2010-01-05 01:28:05 +00001738 DEBUG(dbgs() << "GLOBAL NEVER LOADED: " << *GV);
Chris Lattner930f4752004-10-09 03:32:52 +00001739
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001740 // Delete any stores we can find to the global. We may not be able to
1741 // make it completely dead though.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001742 bool Changed = CleanupConstantGlobalUsers(GV, GV->getInitializer());
Chris Lattner930f4752004-10-09 03:32:52 +00001743
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001744 // If the global is dead now, delete it.
1745 if (GV->use_empty()) {
Chris Lattner7a7ed022004-10-16 18:09:00 +00001746 GV->eraseFromParent();
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001747 ++NumDeleted;
Chris Lattner930f4752004-10-09 03:32:52 +00001748 Changed = true;
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001749 }
Chris Lattner930f4752004-10-09 03:32:52 +00001750 return Changed;
Misha Brukmanfd939082005-04-21 23:48:37 +00001751
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001752 } else if (GS.StoredType <= GlobalStatus::isInitializerStored) {
David Greene3215b0e2010-01-05 01:28:05 +00001753 DEBUG(dbgs() << "MARKING CONSTANT: " << *GV);
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001754 GV->setConstant(true);
Misha Brukmanfd939082005-04-21 23:48:37 +00001755
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001756 // Clean up any obviously simplifiable users now.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001757 CleanupConstantGlobalUsers(GV, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +00001758
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001759 // If the global is dead now, just nuke it.
1760 if (GV->use_empty()) {
David Greene3215b0e2010-01-05 01:28:05 +00001761 DEBUG(dbgs() << " *** Marking constant allowed us to simplify "
Chris Lattnerbdff5482009-08-23 04:37:46 +00001762 << "all users and delete global!\n");
Chris Lattner7a7ed022004-10-16 18:09:00 +00001763 GV->eraseFromParent();
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001764 ++NumDeleted;
1765 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001766
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001767 ++NumMarked;
1768 return true;
Dan Gohman399101a2008-05-23 00:17:26 +00001769 } else if (!GV->getInitializer()->getType()->isSingleValueType()) {
Dan Gohman7eb28f32009-08-14 00:11:03 +00001770 if (TargetData *TD = getAnalysisIfAvailable<TargetData>())
Chris Lattner7b550cc2009-11-06 04:27:31 +00001771 if (GlobalVariable *FirstNewGV = SRAGlobal(GV, *TD)) {
Dan Gohman7eb28f32009-08-14 00:11:03 +00001772 GVI = FirstNewGV; // Don't skip the newly produced globals!
1773 return true;
1774 }
Chris Lattner9b34a612004-10-09 21:48:45 +00001775 } else if (GS.StoredType == GlobalStatus::isStoredOnce) {
Chris Lattner96a86b22004-12-12 05:53:50 +00001776 // If the initial value for the global was an undef value, and if only
1777 // one other value was stored into it, we can just change the
Duncan Sandsb5024402009-01-13 13:48:44 +00001778 // initializer to be the stored value, then delete all stores to the
Chris Lattner96a86b22004-12-12 05:53:50 +00001779 // global. This allows us to mark it constant.
1780 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
1781 if (isa<UndefValue>(GV->getInitializer())) {
1782 // Change the initial value here.
1783 GV->setInitializer(SOVConstant);
Misha Brukmanfd939082005-04-21 23:48:37 +00001784
Chris Lattner96a86b22004-12-12 05:53:50 +00001785 // Clean up any obviously simplifiable users now.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001786 CleanupConstantGlobalUsers(GV, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +00001787
Chris Lattner96a86b22004-12-12 05:53:50 +00001788 if (GV->use_empty()) {
David Greene3215b0e2010-01-05 01:28:05 +00001789 DEBUG(dbgs() << " *** Substituting initializer allowed us to "
Chris Lattnerbdff5482009-08-23 04:37:46 +00001790 << "simplify all users and delete global!\n");
Chris Lattner96a86b22004-12-12 05:53:50 +00001791 GV->eraseFromParent();
1792 ++NumDeleted;
1793 } else {
1794 GVI = GV;
1795 }
1796 ++NumSubstitute;
1797 return true;
Chris Lattner7a7ed022004-10-16 18:09:00 +00001798 }
Chris Lattner7a7ed022004-10-16 18:09:00 +00001799
Chris Lattner9b34a612004-10-09 21:48:45 +00001800 // Try to optimize globals based on the knowledge that only one value
1801 // (besides its initializer) is ever stored to the global.
Chris Lattner30ba5692004-10-11 05:54:41 +00001802 if (OptimizeOnceStoredGlobal(GV, GS.StoredOnceValue, GVI,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001803 getAnalysisIfAvailable<TargetData>()))
Chris Lattner9b34a612004-10-09 21:48:45 +00001804 return true;
Chris Lattner96a86b22004-12-12 05:53:50 +00001805
1806 // Otherwise, if the global was not a boolean, we can shrink it to be a
1807 // boolean.
1808 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
Chris Lattner7b550cc2009-11-06 04:27:31 +00001809 if (TryToShrinkGlobalToBoolean(GV, SOVConstant)) {
Chris Lattner96a86b22004-12-12 05:53:50 +00001810 ++NumShrunkToBool;
1811 return true;
1812 }
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001813 }
1814 }
1815 return false;
1816}
1817
Chris Lattnerfb217ad2005-05-08 22:18:06 +00001818/// ChangeCalleesToFastCall - Walk all of the direct calls of the specified
1819/// function, changing them to FastCC.
1820static void ChangeCalleesToFastCall(Function *F) {
1821 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
Duncan Sands548448a2008-02-18 17:32:13 +00001822 CallSite User(cast<Instruction>(*UI));
1823 User.setCallingConv(CallingConv::Fast);
Chris Lattnerfb217ad2005-05-08 22:18:06 +00001824 }
1825}
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001826
Devang Patel05988662008-09-25 21:00:45 +00001827static AttrListPtr StripNest(const AttrListPtr &Attrs) {
Chris Lattner58d74912008-03-12 17:45:29 +00001828 for (unsigned i = 0, e = Attrs.getNumSlots(); i != e; ++i) {
Devang Patel05988662008-09-25 21:00:45 +00001829 if ((Attrs.getSlot(i).Attrs & Attribute::Nest) == 0)
Duncan Sands548448a2008-02-18 17:32:13 +00001830 continue;
1831
Duncan Sands548448a2008-02-18 17:32:13 +00001832 // There can be only one.
Devang Patel05988662008-09-25 21:00:45 +00001833 return Attrs.removeAttr(Attrs.getSlot(i).Index, Attribute::Nest);
Duncan Sands3d5378f2008-02-16 20:56:04 +00001834 }
1835
1836 return Attrs;
1837}
1838
1839static void RemoveNestAttribute(Function *F) {
Devang Patel05988662008-09-25 21:00:45 +00001840 F->setAttributes(StripNest(F->getAttributes()));
Duncan Sands3d5378f2008-02-16 20:56:04 +00001841 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
Duncan Sands548448a2008-02-18 17:32:13 +00001842 CallSite User(cast<Instruction>(*UI));
Devang Patel05988662008-09-25 21:00:45 +00001843 User.setAttributes(StripNest(User.getAttributes()));
Duncan Sands3d5378f2008-02-16 20:56:04 +00001844 }
1845}
1846
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001847bool GlobalOpt::OptimizeFunctions(Module &M) {
1848 bool Changed = false;
1849 // Optimize functions.
1850 for (Module::iterator FI = M.begin(), E = M.end(); FI != E; ) {
1851 Function *F = FI++;
Duncan Sandsfc5940d2009-03-06 10:21:56 +00001852 // Functions without names cannot be referenced outside this module.
1853 if (!F->hasName() && !F->isDeclaration())
1854 F->setLinkage(GlobalValue::InternalLinkage);
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001855 F->removeDeadConstantUsers();
Chris Lattnerec4c7b92009-11-01 19:03:42 +00001856 if (F->use_empty() && (F->hasLocalLinkage() || F->hasLinkOnceLinkage())) {
1857 F->eraseFromParent();
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001858 Changed = true;
1859 ++NumFnDeleted;
Rafael Espindolabb46f522009-01-15 20:18:42 +00001860 } else if (F->hasLocalLinkage()) {
Duncan Sands3d5378f2008-02-16 20:56:04 +00001861 if (F->getCallingConv() == CallingConv::C && !F->isVarArg() &&
Jay Foad757068f2009-06-10 08:41:11 +00001862 !F->hasAddressTaken()) {
Duncan Sands3d5378f2008-02-16 20:56:04 +00001863 // If this function has C calling conventions, is not a varargs
1864 // function, and is only called directly, promote it to use the Fast
1865 // calling convention.
1866 F->setCallingConv(CallingConv::Fast);
1867 ChangeCalleesToFastCall(F);
1868 ++NumFastCallFns;
1869 Changed = true;
1870 }
1871
Devang Patel05988662008-09-25 21:00:45 +00001872 if (F->getAttributes().hasAttrSomewhere(Attribute::Nest) &&
Jay Foad757068f2009-06-10 08:41:11 +00001873 !F->hasAddressTaken()) {
Duncan Sands3d5378f2008-02-16 20:56:04 +00001874 // The function is not used by a trampoline intrinsic, so it is safe
1875 // to remove the 'nest' attribute.
1876 RemoveNestAttribute(F);
1877 ++NumNestRemoved;
1878 Changed = true;
1879 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001880 }
1881 }
1882 return Changed;
1883}
1884
1885bool GlobalOpt::OptimizeGlobalVars(Module &M) {
1886 bool Changed = false;
1887 for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
1888 GVI != E; ) {
1889 GlobalVariable *GV = GVI++;
Duncan Sandsfc5940d2009-03-06 10:21:56 +00001890 // Global variables without names cannot be referenced outside this module.
1891 if (!GV->hasName() && !GV->isDeclaration())
1892 GV->setLinkage(GlobalValue::InternalLinkage);
Dan Gohman01b97dd2009-11-23 16:22:21 +00001893 // Simplify the initializer.
1894 if (GV->hasInitializer())
1895 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GV->getInitializer())) {
1896 TargetData *TD = getAnalysisIfAvailable<TargetData>();
1897 Constant *New = ConstantFoldConstantExpression(CE, TD);
1898 if (New && New != CE)
1899 GV->setInitializer(New);
1900 }
1901 // Do more involved optimizations if the global is internal.
Rafael Espindolabb46f522009-01-15 20:18:42 +00001902 if (!GV->isConstant() && GV->hasLocalLinkage() &&
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001903 GV->hasInitializer())
1904 Changed |= ProcessInternalGlobal(GV, GVI);
1905 }
1906 return Changed;
1907}
1908
1909/// FindGlobalCtors - Find the llvm.globalctors list, verifying that all
1910/// initializers have an init priority of 65535.
1911GlobalVariable *GlobalOpt::FindGlobalCtors(Module &M) {
Alkis Evlogimenose9c6d362005-10-25 11:18:06 +00001912 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1913 I != E; ++I)
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001914 if (I->getName() == "llvm.global_ctors") {
1915 // Found it, verify it's an array of { int, void()* }.
1916 const ArrayType *ATy =dyn_cast<ArrayType>(I->getType()->getElementType());
1917 if (!ATy) return 0;
1918 const StructType *STy = dyn_cast<StructType>(ATy->getElementType());
1919 if (!STy || STy->getNumElements() != 2 ||
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001920 !STy->getElementType(0)->isIntegerTy(32)) return 0;
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001921 const PointerType *PFTy = dyn_cast<PointerType>(STy->getElementType(1));
1922 if (!PFTy) return 0;
1923 const FunctionType *FTy = dyn_cast<FunctionType>(PFTy->getElementType());
Benjamin Kramerf0127052010-01-05 13:12:22 +00001924 if (!FTy || !FTy->getReturnType()->isVoidTy() ||
Owen Anderson1d0be152009-08-13 21:58:54 +00001925 FTy->isVarArg() || FTy->getNumParams() != 0)
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001926 return 0;
1927
1928 // Verify that the initializer is simple enough for us to handle.
Dan Gohman82555732009-08-19 18:20:44 +00001929 if (!I->hasDefinitiveInitializer()) return 0;
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001930 ConstantArray *CA = dyn_cast<ConstantArray>(I->getInitializer());
1931 if (!CA) return 0;
Gabor Greif5e463212008-05-29 01:59:18 +00001932 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i)
1933 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(*i)) {
Chris Lattner7d8e58f2005-09-26 02:19:27 +00001934 if (isa<ConstantPointerNull>(CS->getOperand(1)))
1935 continue;
1936
1937 // Must have a function or null ptr.
1938 if (!isa<Function>(CS->getOperand(1)))
1939 return 0;
1940
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001941 // Init priority must be standard.
1942 ConstantInt *CI = dyn_cast<ConstantInt>(CS->getOperand(0));
Reid Spencerb83eb642006-10-20 07:07:24 +00001943 if (!CI || CI->getZExtValue() != 65535)
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001944 return 0;
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001945 } else {
1946 return 0;
1947 }
1948
1949 return I;
1950 }
1951 return 0;
1952}
1953
Chris Lattnerdb973e62005-09-26 02:31:18 +00001954/// ParseGlobalCtors - Given a llvm.global_ctors list that we can understand,
1955/// return a list of the functions and null terminator as a vector.
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001956static std::vector<Function*> ParseGlobalCtors(GlobalVariable *GV) {
1957 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
1958 std::vector<Function*> Result;
1959 Result.reserve(CA->getNumOperands());
Gabor Greif5e463212008-05-29 01:59:18 +00001960 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i) {
1961 ConstantStruct *CS = cast<ConstantStruct>(*i);
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001962 Result.push_back(dyn_cast<Function>(CS->getOperand(1)));
1963 }
1964 return Result;
1965}
1966
Chris Lattnerdb973e62005-09-26 02:31:18 +00001967/// InstallGlobalCtors - Given a specified llvm.global_ctors list, install the
1968/// specified array, returning the new global to use.
1969static GlobalVariable *InstallGlobalCtors(GlobalVariable *GCL,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001970 const std::vector<Function*> &Ctors) {
Chris Lattnerdb973e62005-09-26 02:31:18 +00001971 // If we made a change, reassemble the initializer list.
1972 std::vector<Constant*> CSVals;
Chris Lattner7b550cc2009-11-06 04:27:31 +00001973 CSVals.push_back(ConstantInt::get(Type::getInt32Ty(GCL->getContext()),65535));
Chris Lattnerdb973e62005-09-26 02:31:18 +00001974 CSVals.push_back(0);
1975
1976 // Create the new init list.
1977 std::vector<Constant*> CAList;
1978 for (unsigned i = 0, e = Ctors.size(); i != e; ++i) {
Chris Lattner79c11012005-09-26 04:44:35 +00001979 if (Ctors[i]) {
Chris Lattnerdb973e62005-09-26 02:31:18 +00001980 CSVals[1] = Ctors[i];
Chris Lattner79c11012005-09-26 04:44:35 +00001981 } else {
Chris Lattner7b550cc2009-11-06 04:27:31 +00001982 const Type *FTy = FunctionType::get(Type::getVoidTy(GCL->getContext()),
1983 false);
Owen Andersondebcb012009-07-29 22:17:13 +00001984 const PointerType *PFTy = PointerType::getUnqual(FTy);
Owen Andersona7235ea2009-07-31 20:28:14 +00001985 CSVals[1] = Constant::getNullValue(PFTy);
Chris Lattner7b550cc2009-11-06 04:27:31 +00001986 CSVals[0] = ConstantInt::get(Type::getInt32Ty(GCL->getContext()),
1987 2147483647);
Chris Lattnerdb973e62005-09-26 02:31:18 +00001988 }
Chris Lattner7b550cc2009-11-06 04:27:31 +00001989 CAList.push_back(ConstantStruct::get(GCL->getContext(), CSVals, false));
Chris Lattnerdb973e62005-09-26 02:31:18 +00001990 }
1991
1992 // Create the array initializer.
1993 const Type *StructTy =
Nick Lewyckyc332fba2009-09-19 20:30:26 +00001994 cast<ArrayType>(GCL->getType()->getElementType())->getElementType();
Owen Anderson1fd70962009-07-28 18:32:17 +00001995 Constant *CA = ConstantArray::get(ArrayType::get(StructTy,
Nick Lewyckyc332fba2009-09-19 20:30:26 +00001996 CAList.size()), CAList);
Chris Lattnerdb973e62005-09-26 02:31:18 +00001997
1998 // If we didn't change the number of elements, don't create a new GV.
1999 if (CA->getType() == GCL->getInitializer()->getType()) {
2000 GCL->setInitializer(CA);
2001 return GCL;
2002 }
2003
2004 // Create the new global and insert it next to the existing list.
Chris Lattner7b550cc2009-11-06 04:27:31 +00002005 GlobalVariable *NGV = new GlobalVariable(CA->getType(), GCL->isConstant(),
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +00002006 GCL->getLinkage(), CA, "",
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +00002007 GCL->isThreadLocal());
Chris Lattnerdb973e62005-09-26 02:31:18 +00002008 GCL->getParent()->getGlobalList().insert(GCL, NGV);
Chris Lattner046800a2007-02-11 01:08:35 +00002009 NGV->takeName(GCL);
Chris Lattnerdb973e62005-09-26 02:31:18 +00002010
2011 // Nuke the old list, replacing any uses with the new one.
2012 if (!GCL->use_empty()) {
2013 Constant *V = NGV;
2014 if (V->getType() != GCL->getType())
Owen Andersonbaf3c402009-07-29 18:55:55 +00002015 V = ConstantExpr::getBitCast(V, GCL->getType());
Chris Lattnerdb973e62005-09-26 02:31:18 +00002016 GCL->replaceAllUsesWith(V);
2017 }
2018 GCL->eraseFromParent();
2019
2020 if (Ctors.size())
2021 return NGV;
2022 else
2023 return 0;
2024}
Chris Lattner79c11012005-09-26 04:44:35 +00002025
2026
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002027static Constant *getVal(DenseMap<Value*, Constant*> &ComputedValues,
Chris Lattner79c11012005-09-26 04:44:35 +00002028 Value *V) {
2029 if (Constant *CV = dyn_cast<Constant>(V)) return CV;
2030 Constant *R = ComputedValues[V];
2031 assert(R && "Reference to an uncomputed value!");
2032 return R;
2033}
2034
2035/// isSimpleEnoughPointerToCommit - Return true if this constant is simple
2036/// enough for us to understand. In particular, if it is a cast of something,
2037/// we punt. We basically just support direct accesses to globals and GEP's of
2038/// globals. This should be kept up to date with CommitValueTo.
Chris Lattner7b550cc2009-11-06 04:27:31 +00002039static bool isSimpleEnoughPointerToCommit(Constant *C) {
Dan Gohmance5de5b2009-09-07 22:42:05 +00002040 // Conservatively, avoid aggregate types. This is because we don't
2041 // want to worry about them partially overlapping other stores.
2042 if (!cast<PointerType>(C->getType())->getElementType()->isSingleValueType())
2043 return false;
2044
Dan Gohmanfd54a892009-09-07 22:31:26 +00002045 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
2046 // Do not allow weak/linkonce/dllimport/dllexport linkage or
2047 // external globals.
2048 return GV->hasDefinitiveInitializer();
2049
Chris Lattner798b4d52005-09-26 06:52:44 +00002050 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
2051 // Handle a constantexpr gep.
2052 if (CE->getOpcode() == Instruction::GetElementPtr &&
Dan Gohmanc62482d2009-09-07 22:40:13 +00002053 isa<GlobalVariable>(CE->getOperand(0)) &&
2054 cast<GEPOperator>(CE)->isInBounds()) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002055 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
Dan Gohmanfd54a892009-09-07 22:31:26 +00002056 // Do not allow weak/linkonce/dllimport/dllexport linkage or
2057 // external globals.
2058 if (!GV->hasDefinitiveInitializer())
2059 return false;
Dan Gohman80bdc962009-09-07 22:44:55 +00002060
Dan Gohman80bdc962009-09-07 22:44:55 +00002061 // The first index must be zero.
Dan Gohmane6992f72009-09-10 23:37:55 +00002062 ConstantInt *CI = dyn_cast<ConstantInt>(*next(CE->op_begin()));
Dan Gohman80bdc962009-09-07 22:44:55 +00002063 if (!CI || !CI->isZero()) return false;
Dan Gohman80bdc962009-09-07 22:44:55 +00002064
2065 // The remaining indices must be compile-time known integers within the
Dan Gohmane6992f72009-09-10 23:37:55 +00002066 // notional bounds of the corresponding static array types.
2067 if (!CE->isGEPWithNoNotionalOverIndexing())
2068 return false;
Dan Gohman80bdc962009-09-07 22:44:55 +00002069
Dan Gohmanc6f69e92009-10-05 16:36:26 +00002070 return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
Chris Lattner798b4d52005-09-26 06:52:44 +00002071 }
Chris Lattner79c11012005-09-26 04:44:35 +00002072 return false;
2073}
2074
Chris Lattner798b4d52005-09-26 06:52:44 +00002075/// EvaluateStoreInto - Evaluate a piece of a constantexpr store into a global
2076/// initializer. This returns 'Init' modified to reflect 'Val' stored into it.
2077/// At this point, the GEP operands of Addr [0, OpNo) have been stepped into.
2078static Constant *EvaluateStoreInto(Constant *Init, Constant *Val,
Chris Lattner7b550cc2009-11-06 04:27:31 +00002079 ConstantExpr *Addr, unsigned OpNo) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002080 // Base case of the recursion.
2081 if (OpNo == Addr->getNumOperands()) {
2082 assert(Val->getType() == Init->getType() && "Type mismatch!");
2083 return Val;
2084 }
2085
Chris Lattnera0e9a242010-01-07 01:16:21 +00002086 std::vector<Constant*> Elts;
Chris Lattner798b4d52005-09-26 06:52:44 +00002087 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002088
2089 // Break up the constant into its elements.
2090 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
Gabor Greif5e463212008-05-29 01:59:18 +00002091 for (User::op_iterator i = CS->op_begin(), e = CS->op_end(); i != e; ++i)
2092 Elts.push_back(cast<Constant>(*i));
Chris Lattner798b4d52005-09-26 06:52:44 +00002093 } else if (isa<ConstantAggregateZero>(Init)) {
2094 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
Owen Andersona7235ea2009-07-31 20:28:14 +00002095 Elts.push_back(Constant::getNullValue(STy->getElementType(i)));
Chris Lattner798b4d52005-09-26 06:52:44 +00002096 } else if (isa<UndefValue>(Init)) {
2097 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002098 Elts.push_back(UndefValue::get(STy->getElementType(i)));
Chris Lattner798b4d52005-09-26 06:52:44 +00002099 } else {
Torok Edwinc23197a2009-07-14 16:55:14 +00002100 llvm_unreachable("This code is out of sync with "
Chris Lattner798b4d52005-09-26 06:52:44 +00002101 " ConstantFoldLoadThroughGEPConstantExpr");
2102 }
2103
2104 // Replace the element that we are supposed to.
Reid Spencerb83eb642006-10-20 07:07:24 +00002105 ConstantInt *CU = cast<ConstantInt>(Addr->getOperand(OpNo));
2106 unsigned Idx = CU->getZExtValue();
2107 assert(Idx < STy->getNumElements() && "Struct index out of range!");
Chris Lattner7b550cc2009-11-06 04:27:31 +00002108 Elts[Idx] = EvaluateStoreInto(Elts[Idx], Val, Addr, OpNo+1);
Chris Lattner798b4d52005-09-26 06:52:44 +00002109
2110 // Return the modified struct.
Chris Lattner7b550cc2009-11-06 04:27:31 +00002111 return ConstantStruct::get(Init->getContext(), &Elts[0], Elts.size(),
2112 STy->isPacked());
Chris Lattner798b4d52005-09-26 06:52:44 +00002113 } else {
2114 ConstantInt *CI = cast<ConstantInt>(Addr->getOperand(OpNo));
Chris Lattnera0e9a242010-01-07 01:16:21 +00002115 const SequentialType *InitTy = cast<SequentialType>(Init->getType());
Chris Lattner798b4d52005-09-26 06:52:44 +00002116
Chris Lattnera0e9a242010-01-07 01:16:21 +00002117 uint64_t NumElts;
2118 if (const ArrayType *ATy = dyn_cast<ArrayType>(InitTy))
2119 NumElts = ATy->getNumElements();
2120 else
2121 NumElts = cast<VectorType>(InitTy)->getNumElements();
2122
2123
Chris Lattner798b4d52005-09-26 06:52:44 +00002124 // Break up the array into elements.
Chris Lattner798b4d52005-09-26 06:52:44 +00002125 if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
Gabor Greif5e463212008-05-29 01:59:18 +00002126 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i)
2127 Elts.push_back(cast<Constant>(*i));
Chris Lattner4039bd02010-01-07 01:20:20 +00002128 } else if (ConstantVector *CV = dyn_cast<ConstantVector>(Init)) {
2129 for (User::op_iterator i = CV->op_begin(), e = CV->op_end(); i != e; ++i)
2130 Elts.push_back(cast<Constant>(*i));
Chris Lattner798b4d52005-09-26 06:52:44 +00002131 } else if (isa<ConstantAggregateZero>(Init)) {
Chris Lattnera0e9a242010-01-07 01:16:21 +00002132 Elts.assign(NumElts, Constant::getNullValue(InitTy->getElementType()));
Chris Lattner798b4d52005-09-26 06:52:44 +00002133 } else {
Chris Lattnera0e9a242010-01-07 01:16:21 +00002134 assert(isa<UndefValue>(Init) && "This code is out of sync with "
Chris Lattner798b4d52005-09-26 06:52:44 +00002135 " ConstantFoldLoadThroughGEPConstantExpr");
Chris Lattnera0e9a242010-01-07 01:16:21 +00002136 Elts.assign(NumElts, UndefValue::get(InitTy->getElementType()));
Chris Lattner798b4d52005-09-26 06:52:44 +00002137 }
2138
Chris Lattnera0e9a242010-01-07 01:16:21 +00002139 assert(CI->getZExtValue() < NumElts);
Reid Spencerb83eb642006-10-20 07:07:24 +00002140 Elts[CI->getZExtValue()] =
Chris Lattner7b550cc2009-11-06 04:27:31 +00002141 EvaluateStoreInto(Elts[CI->getZExtValue()], Val, Addr, OpNo+1);
Chris Lattnera0e9a242010-01-07 01:16:21 +00002142
Duncan Sands1df98592010-02-16 11:11:14 +00002143 if (Init->getType()->isArrayTy())
Chris Lattnera0e9a242010-01-07 01:16:21 +00002144 return ConstantArray::get(cast<ArrayType>(InitTy), Elts);
2145 else
2146 return ConstantVector::get(&Elts[0], Elts.size());
Chris Lattner798b4d52005-09-26 06:52:44 +00002147 }
2148}
2149
Chris Lattner79c11012005-09-26 04:44:35 +00002150/// CommitValueTo - We have decided that Addr (which satisfies the predicate
2151/// isSimpleEnoughPointerToCommit) should get Val as its value. Make it happen.
Chris Lattner7b550cc2009-11-06 04:27:31 +00002152static void CommitValueTo(Constant *Val, Constant *Addr) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002153 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Addr)) {
2154 assert(GV->hasInitializer());
2155 GV->setInitializer(Val);
2156 return;
2157 }
Chris Lattnera0e9a242010-01-07 01:16:21 +00002158
Chris Lattner798b4d52005-09-26 06:52:44 +00002159 ConstantExpr *CE = cast<ConstantExpr>(Addr);
2160 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
Chris Lattnera0e9a242010-01-07 01:16:21 +00002161 GV->setInitializer(EvaluateStoreInto(GV->getInitializer(), Val, CE, 2));
Chris Lattner79c11012005-09-26 04:44:35 +00002162}
2163
Chris Lattner562a0552005-09-26 05:16:34 +00002164/// ComputeLoadResult - Return the value that would be computed by a load from
2165/// P after the stores reflected by 'memory' have been performed. If we can't
2166/// decide, return null.
Chris Lattner04de1cf2005-09-26 05:15:37 +00002167static Constant *ComputeLoadResult(Constant *P,
Chris Lattner7b550cc2009-11-06 04:27:31 +00002168 const DenseMap<Constant*, Constant*> &Memory) {
Chris Lattner04de1cf2005-09-26 05:15:37 +00002169 // If this memory location has been recently stored, use the stored value: it
2170 // is the most up-to-date.
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002171 DenseMap<Constant*, Constant*>::const_iterator I = Memory.find(P);
Chris Lattner04de1cf2005-09-26 05:15:37 +00002172 if (I != Memory.end()) return I->second;
2173
2174 // Access it.
2175 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(P)) {
Dan Gohman82555732009-08-19 18:20:44 +00002176 if (GV->hasDefinitiveInitializer())
Chris Lattner04de1cf2005-09-26 05:15:37 +00002177 return GV->getInitializer();
2178 return 0;
Chris Lattner04de1cf2005-09-26 05:15:37 +00002179 }
Chris Lattner798b4d52005-09-26 06:52:44 +00002180
2181 // Handle a constantexpr getelementptr.
2182 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(P))
2183 if (CE->getOpcode() == Instruction::GetElementPtr &&
2184 isa<GlobalVariable>(CE->getOperand(0))) {
2185 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
Dan Gohman82555732009-08-19 18:20:44 +00002186 if (GV->hasDefinitiveInitializer())
Dan Gohmanc6f69e92009-10-05 16:36:26 +00002187 return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
Chris Lattner798b4d52005-09-26 06:52:44 +00002188 }
2189
2190 return 0; // don't know how to evaluate.
Chris Lattner04de1cf2005-09-26 05:15:37 +00002191}
2192
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002193/// EvaluateFunction - Evaluate a call to function F, returning true if
2194/// successful, false if we can't evaluate it. ActualArgs contains the formal
2195/// arguments for the function.
Chris Lattnercd271422005-09-27 04:45:34 +00002196static bool EvaluateFunction(Function *F, Constant *&RetVal,
Duncan Sandsfa6a1cf2009-08-17 14:33:27 +00002197 const SmallVectorImpl<Constant*> &ActualArgs,
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002198 std::vector<Function*> &CallStack,
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002199 DenseMap<Constant*, Constant*> &MutatedMemory,
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002200 std::vector<GlobalVariable*> &AllocaTmps) {
Chris Lattnercd271422005-09-27 04:45:34 +00002201 // Check to see if this function is already executing (recursion). If so,
2202 // bail out. TODO: we might want to accept limited recursion.
2203 if (std::find(CallStack.begin(), CallStack.end(), F) != CallStack.end())
2204 return false;
2205
2206 CallStack.push_back(F);
2207
Chris Lattner79c11012005-09-26 04:44:35 +00002208 /// Values - As we compute SSA register values, we store their contents here.
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002209 DenseMap<Value*, Constant*> Values;
Chris Lattnercd271422005-09-27 04:45:34 +00002210
2211 // Initialize arguments to the incoming values specified.
2212 unsigned ArgNo = 0;
2213 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); AI != E;
2214 ++AI, ++ArgNo)
2215 Values[AI] = ActualArgs[ArgNo];
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002216
Chris Lattnercdf98be2005-09-26 04:57:38 +00002217 /// ExecutedBlocks - We only handle non-looping, non-recursive code. As such,
2218 /// we can only evaluate any one basic block at most once. This set keeps
2219 /// track of what we have executed so we can detect recursive cases etc.
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002220 SmallPtrSet<BasicBlock*, 32> ExecutedBlocks;
Chris Lattnera22fdb02005-09-26 17:07:09 +00002221
Chris Lattner79c11012005-09-26 04:44:35 +00002222 // CurInst - The current instruction we're evaluating.
2223 BasicBlock::iterator CurInst = F->begin()->begin();
2224
2225 // This is the main evaluation loop.
2226 while (1) {
2227 Constant *InstResult = 0;
2228
2229 if (StoreInst *SI = dyn_cast<StoreInst>(CurInst)) {
Chris Lattnercd271422005-09-27 04:45:34 +00002230 if (SI->isVolatile()) return false; // no volatile accesses.
Chris Lattner79c11012005-09-26 04:44:35 +00002231 Constant *Ptr = getVal(Values, SI->getOperand(1));
Chris Lattner7b550cc2009-11-06 04:27:31 +00002232 if (!isSimpleEnoughPointerToCommit(Ptr))
Chris Lattner79c11012005-09-26 04:44:35 +00002233 // If this is too complex for us to commit, reject it.
Chris Lattnercd271422005-09-27 04:45:34 +00002234 return false;
Chris Lattner79c11012005-09-26 04:44:35 +00002235 Constant *Val = getVal(Values, SI->getOperand(0));
2236 MutatedMemory[Ptr] = Val;
2237 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CurInst)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002238 InstResult = ConstantExpr::get(BO->getOpcode(),
Chris Lattner79c11012005-09-26 04:44:35 +00002239 getVal(Values, BO->getOperand(0)),
2240 getVal(Values, BO->getOperand(1)));
Reid Spencere4d87aa2006-12-23 06:05:41 +00002241 } else if (CmpInst *CI = dyn_cast<CmpInst>(CurInst)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002242 InstResult = ConstantExpr::getCompare(CI->getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00002243 getVal(Values, CI->getOperand(0)),
2244 getVal(Values, CI->getOperand(1)));
Chris Lattner79c11012005-09-26 04:44:35 +00002245 } else if (CastInst *CI = dyn_cast<CastInst>(CurInst)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002246 InstResult = ConstantExpr::getCast(CI->getOpcode(),
Chris Lattner9a989f02006-11-30 17:26:08 +00002247 getVal(Values, CI->getOperand(0)),
Chris Lattner79c11012005-09-26 04:44:35 +00002248 CI->getType());
2249 } else if (SelectInst *SI = dyn_cast<SelectInst>(CurInst)) {
Owen Anderson14ce9ef2009-07-06 01:34:54 +00002250 InstResult =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002251 ConstantExpr::getSelect(getVal(Values, SI->getOperand(0)),
Chris Lattner79c11012005-09-26 04:44:35 +00002252 getVal(Values, SI->getOperand(1)),
2253 getVal(Values, SI->getOperand(2)));
Chris Lattner04de1cf2005-09-26 05:15:37 +00002254 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurInst)) {
2255 Constant *P = getVal(Values, GEP->getOperand(0));
Chris Lattner55eb1c42007-01-31 04:40:53 +00002256 SmallVector<Constant*, 8> GEPOps;
Gabor Greif5e463212008-05-29 01:59:18 +00002257 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end();
2258 i != e; ++i)
2259 GEPOps.push_back(getVal(Values, *i));
Dan Gohman4a7e6b72009-09-07 22:34:43 +00002260 InstResult = cast<GEPOperator>(GEP)->isInBounds() ?
2261 ConstantExpr::getInBoundsGetElementPtr(P, &GEPOps[0], GEPOps.size()) :
2262 ConstantExpr::getGetElementPtr(P, &GEPOps[0], GEPOps.size());
Chris Lattner04de1cf2005-09-26 05:15:37 +00002263 } else if (LoadInst *LI = dyn_cast<LoadInst>(CurInst)) {
Chris Lattnercd271422005-09-27 04:45:34 +00002264 if (LI->isVolatile()) return false; // no volatile accesses.
Chris Lattner04de1cf2005-09-26 05:15:37 +00002265 InstResult = ComputeLoadResult(getVal(Values, LI->getOperand(0)),
Chris Lattner7b550cc2009-11-06 04:27:31 +00002266 MutatedMemory);
Chris Lattnercd271422005-09-27 04:45:34 +00002267 if (InstResult == 0) return false; // Could not evaluate load.
Chris Lattnera22fdb02005-09-26 17:07:09 +00002268 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(CurInst)) {
Chris Lattnercd271422005-09-27 04:45:34 +00002269 if (AI->isArrayAllocation()) return false; // Cannot handle array allocs.
Chris Lattnera22fdb02005-09-26 17:07:09 +00002270 const Type *Ty = AI->getType()->getElementType();
Chris Lattner7b550cc2009-11-06 04:27:31 +00002271 AllocaTmps.push_back(new GlobalVariable(Ty, false,
Chris Lattnera22fdb02005-09-26 17:07:09 +00002272 GlobalValue::InternalLinkage,
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002273 UndefValue::get(Ty),
Chris Lattnera22fdb02005-09-26 17:07:09 +00002274 AI->getName()));
Chris Lattnercd271422005-09-27 04:45:34 +00002275 InstResult = AllocaTmps.back();
2276 } else if (CallInst *CI = dyn_cast<CallInst>(CurInst)) {
Devang Patel412a4462009-03-09 23:04:12 +00002277
2278 // Debug info can safely be ignored here.
2279 if (isa<DbgInfoIntrinsic>(CI)) {
2280 ++CurInst;
2281 continue;
2282 }
2283
Chris Lattner7cd580f2006-07-07 21:37:01 +00002284 // Cannot handle inline asm.
2285 if (isa<InlineAsm>(CI->getOperand(0))) return false;
2286
Chris Lattnercd271422005-09-27 04:45:34 +00002287 // Resolve function pointers.
2288 Function *Callee = dyn_cast<Function>(getVal(Values, CI->getOperand(0)));
2289 if (!Callee) return false; // Cannot resolve.
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002290
Duncan Sandsfa6a1cf2009-08-17 14:33:27 +00002291 SmallVector<Constant*, 8> Formals;
Gabor Greif5e463212008-05-29 01:59:18 +00002292 for (User::op_iterator i = CI->op_begin() + 1, e = CI->op_end();
2293 i != e; ++i)
2294 Formals.push_back(getVal(Values, *i));
Duncan Sandsfa6a1cf2009-08-17 14:33:27 +00002295
Reid Spencer5cbf9852007-01-30 20:08:39 +00002296 if (Callee->isDeclaration()) {
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002297 // If this is a function we can constant fold, do it.
Duncan Sandsfa6a1cf2009-08-17 14:33:27 +00002298 if (Constant *C = ConstantFoldCall(Callee, Formals.data(),
Chris Lattner6c1f5652007-01-30 23:14:52 +00002299 Formals.size())) {
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002300 InstResult = C;
2301 } else {
2302 return false;
2303 }
2304 } else {
2305 if (Callee->getFunctionType()->isVarArg())
2306 return false;
2307
2308 Constant *RetVal;
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002309 // Execute the call, if successful, use the return value.
2310 if (!EvaluateFunction(Callee, RetVal, Formals, CallStack,
2311 MutatedMemory, AllocaTmps))
2312 return false;
2313 InstResult = RetVal;
2314 }
Reid Spencer3ed469c2006-11-02 20:25:50 +00002315 } else if (isa<TerminatorInst>(CurInst)) {
Chris Lattnercdf98be2005-09-26 04:57:38 +00002316 BasicBlock *NewBB = 0;
2317 if (BranchInst *BI = dyn_cast<BranchInst>(CurInst)) {
2318 if (BI->isUnconditional()) {
2319 NewBB = BI->getSuccessor(0);
2320 } else {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002321 ConstantInt *Cond =
2322 dyn_cast<ConstantInt>(getVal(Values, BI->getCondition()));
Chris Lattner97d1fad2007-01-12 18:30:11 +00002323 if (!Cond) return false; // Cannot determine.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002324
Reid Spencer579dca12007-01-12 04:24:46 +00002325 NewBB = BI->getSuccessor(!Cond->getZExtValue());
Chris Lattnercdf98be2005-09-26 04:57:38 +00002326 }
2327 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(CurInst)) {
2328 ConstantInt *Val =
2329 dyn_cast<ConstantInt>(getVal(Values, SI->getCondition()));
Chris Lattnercd271422005-09-27 04:45:34 +00002330 if (!Val) return false; // Cannot determine.
Chris Lattnercdf98be2005-09-26 04:57:38 +00002331 NewBB = SI->getSuccessor(SI->findCaseValue(Val));
Chris Lattnerb3d5a652009-10-29 05:51:50 +00002332 } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(CurInst)) {
2333 Value *Val = getVal(Values, IBI->getAddress())->stripPointerCasts();
2334 if (BlockAddress *BA = dyn_cast<BlockAddress>(Val))
2335 NewBB = BA->getBasicBlock();
Chris Lattnercdfc9402009-11-01 01:27:45 +00002336 else
2337 return false; // Cannot determine.
Chris Lattnercdf98be2005-09-26 04:57:38 +00002338 } else if (ReturnInst *RI = dyn_cast<ReturnInst>(CurInst)) {
Chris Lattnercd271422005-09-27 04:45:34 +00002339 if (RI->getNumOperands())
2340 RetVal = getVal(Values, RI->getOperand(0));
2341
2342 CallStack.pop_back(); // return from fn.
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002343 return true; // We succeeded at evaluating this ctor!
Chris Lattnercdf98be2005-09-26 04:57:38 +00002344 } else {
Chris Lattnercd271422005-09-27 04:45:34 +00002345 // invoke, unwind, unreachable.
2346 return false; // Cannot handle this terminator.
Chris Lattnercdf98be2005-09-26 04:57:38 +00002347 }
2348
2349 // Okay, we succeeded in evaluating this control flow. See if we have
Chris Lattnercd271422005-09-27 04:45:34 +00002350 // executed the new block before. If so, we have a looping function,
2351 // which we cannot evaluate in reasonable time.
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002352 if (!ExecutedBlocks.insert(NewBB))
Chris Lattnercd271422005-09-27 04:45:34 +00002353 return false; // looped!
Chris Lattnercdf98be2005-09-26 04:57:38 +00002354
2355 // Okay, we have never been in this block before. Check to see if there
2356 // are any PHI nodes. If so, evaluate them with information about where
2357 // we came from.
2358 BasicBlock *OldBB = CurInst->getParent();
2359 CurInst = NewBB->begin();
2360 PHINode *PN;
2361 for (; (PN = dyn_cast<PHINode>(CurInst)); ++CurInst)
2362 Values[PN] = getVal(Values, PN->getIncomingValueForBlock(OldBB));
2363
2364 // Do NOT increment CurInst. We know that the terminator had no value.
2365 continue;
Chris Lattner79c11012005-09-26 04:44:35 +00002366 } else {
Chris Lattner79c11012005-09-26 04:44:35 +00002367 // Did not know how to evaluate this!
Chris Lattnercd271422005-09-27 04:45:34 +00002368 return false;
Chris Lattner79c11012005-09-26 04:44:35 +00002369 }
2370
2371 if (!CurInst->use_empty())
2372 Values[CurInst] = InstResult;
2373
2374 // Advance program counter.
2375 ++CurInst;
2376 }
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002377}
2378
2379/// EvaluateStaticConstructor - Evaluate static constructors in the function, if
2380/// we can. Return true if we can, false otherwise.
2381static bool EvaluateStaticConstructor(Function *F) {
2382 /// MutatedMemory - For each store we execute, we update this map. Loads
2383 /// check this to get the most up-to-date value. If evaluation is successful,
2384 /// this state is committed to the process.
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002385 DenseMap<Constant*, Constant*> MutatedMemory;
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002386
2387 /// AllocaTmps - To 'execute' an alloca, we create a temporary global variable
2388 /// to represent its body. This vector is needed so we can delete the
2389 /// temporary globals when we are done.
2390 std::vector<GlobalVariable*> AllocaTmps;
2391
2392 /// CallStack - This is used to detect recursion. In pathological situations
2393 /// we could hit exponential behavior, but at least there is nothing
2394 /// unbounded.
2395 std::vector<Function*> CallStack;
2396
2397 // Call the function.
Chris Lattnercd271422005-09-27 04:45:34 +00002398 Constant *RetValDummy;
Duncan Sandsfa6a1cf2009-08-17 14:33:27 +00002399 bool EvalSuccess = EvaluateFunction(F, RetValDummy,
2400 SmallVector<Constant*, 0>(), CallStack,
2401 MutatedMemory, AllocaTmps);
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002402 if (EvalSuccess) {
Chris Lattnera22fdb02005-09-26 17:07:09 +00002403 // We succeeded at evaluation: commit the result.
David Greene3215b0e2010-01-05 01:28:05 +00002404 DEBUG(dbgs() << "FULLY EVALUATED GLOBAL CTOR FUNCTION '"
Daniel Dunbarce63ffb2009-07-25 00:23:56 +00002405 << F->getName() << "' to " << MutatedMemory.size()
2406 << " stores.\n");
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002407 for (DenseMap<Constant*, Constant*>::iterator I = MutatedMemory.begin(),
Chris Lattnera22fdb02005-09-26 17:07:09 +00002408 E = MutatedMemory.end(); I != E; ++I)
Chris Lattner7b550cc2009-11-06 04:27:31 +00002409 CommitValueTo(I->second, I->first);
Chris Lattnera22fdb02005-09-26 17:07:09 +00002410 }
Chris Lattner79c11012005-09-26 04:44:35 +00002411
Chris Lattnera22fdb02005-09-26 17:07:09 +00002412 // At this point, we are done interpreting. If we created any 'alloca'
2413 // temporaries, release them now.
2414 while (!AllocaTmps.empty()) {
2415 GlobalVariable *Tmp = AllocaTmps.back();
2416 AllocaTmps.pop_back();
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002417
Chris Lattnera22fdb02005-09-26 17:07:09 +00002418 // If there are still users of the alloca, the program is doing something
2419 // silly, e.g. storing the address of the alloca somewhere and using it
2420 // later. Since this is undefined, we'll just make it be null.
2421 if (!Tmp->use_empty())
Owen Andersona7235ea2009-07-31 20:28:14 +00002422 Tmp->replaceAllUsesWith(Constant::getNullValue(Tmp->getType()));
Chris Lattnera22fdb02005-09-26 17:07:09 +00002423 delete Tmp;
2424 }
Chris Lattneraae4a1c2005-09-26 07:34:35 +00002425
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002426 return EvalSuccess;
Chris Lattner79c11012005-09-26 04:44:35 +00002427}
2428
Chris Lattnerdb973e62005-09-26 02:31:18 +00002429
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002430
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002431/// OptimizeGlobalCtorsList - Simplify and evaluation global ctors if possible.
2432/// Return true if anything changed.
2433bool GlobalOpt::OptimizeGlobalCtorsList(GlobalVariable *&GCL) {
2434 std::vector<Function*> Ctors = ParseGlobalCtors(GCL);
2435 bool MadeChange = false;
2436 if (Ctors.empty()) return false;
2437
2438 // Loop over global ctors, optimizing them when we can.
2439 for (unsigned i = 0; i != Ctors.size(); ++i) {
2440 Function *F = Ctors[i];
2441 // Found a null terminator in the middle of the list, prune off the rest of
2442 // the list.
Chris Lattner7d8e58f2005-09-26 02:19:27 +00002443 if (F == 0) {
2444 if (i != Ctors.size()-1) {
2445 Ctors.resize(i+1);
2446 MadeChange = true;
2447 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002448 break;
2449 }
2450
Chris Lattner79c11012005-09-26 04:44:35 +00002451 // We cannot simplify external ctor functions.
2452 if (F->empty()) continue;
2453
2454 // If we can evaluate the ctor at compile time, do.
2455 if (EvaluateStaticConstructor(F)) {
2456 Ctors.erase(Ctors.begin()+i);
2457 MadeChange = true;
2458 --i;
2459 ++NumCtorsEvaluated;
2460 continue;
2461 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002462 }
2463
2464 if (!MadeChange) return false;
2465
Chris Lattner7b550cc2009-11-06 04:27:31 +00002466 GCL = InstallGlobalCtors(GCL, Ctors);
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002467 return true;
2468}
2469
Duncan Sandsfc5940d2009-03-06 10:21:56 +00002470bool GlobalOpt::OptimizeGlobalAliases(Module &M) {
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002471 bool Changed = false;
2472
Duncan Sands177d84e2009-01-07 20:01:06 +00002473 for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end();
Duncan Sands4782b302009-02-15 09:56:08 +00002474 I != E;) {
2475 Module::alias_iterator J = I++;
Duncan Sandsfc5940d2009-03-06 10:21:56 +00002476 // Aliases without names cannot be referenced outside this module.
2477 if (!J->hasName() && !J->isDeclaration())
2478 J->setLinkage(GlobalValue::InternalLinkage);
Duncan Sands4782b302009-02-15 09:56:08 +00002479 // If the aliasee may change at link time, nothing can be done - bail out.
2480 if (J->mayBeOverridden())
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002481 continue;
2482
Duncan Sands4782b302009-02-15 09:56:08 +00002483 Constant *Aliasee = J->getAliasee();
2484 GlobalValue *Target = cast<GlobalValue>(Aliasee->stripPointerCasts());
Duncan Sands95c5d0f2009-02-18 17:55:38 +00002485 Target->removeDeadConstantUsers();
Duncan Sands4782b302009-02-15 09:56:08 +00002486 bool hasOneUse = Target->hasOneUse() && Aliasee->hasOneUse();
2487
2488 // Make all users of the alias use the aliasee instead.
2489 if (!J->use_empty()) {
2490 J->replaceAllUsesWith(Aliasee);
2491 ++NumAliasesResolved;
2492 Changed = true;
2493 }
2494
Duncan Sands7a154cf2009-12-08 10:10:20 +00002495 // If the alias is externally visible, we may still be able to simplify it.
2496 if (!J->hasLocalLinkage()) {
2497 // If the aliasee has internal linkage, give it the name and linkage
2498 // of the alias, and delete the alias. This turns:
2499 // define internal ... @f(...)
2500 // @a = alias ... @f
2501 // into:
2502 // define ... @a(...)
2503 if (!Target->hasLocalLinkage())
2504 continue;
Duncan Sands4782b302009-02-15 09:56:08 +00002505
Duncan Sands7a154cf2009-12-08 10:10:20 +00002506 // Do not perform the transform if multiple aliases potentially target the
2507 // aliasee. This check also ensures that it is safe to replace the section
2508 // and other attributes of the aliasee with those of the alias.
2509 if (!hasOneUse)
2510 continue;
Duncan Sands4782b302009-02-15 09:56:08 +00002511
Duncan Sands7a154cf2009-12-08 10:10:20 +00002512 // Give the aliasee the name, linkage and other attributes of the alias.
2513 Target->takeName(J);
2514 Target->setLinkage(J->getLinkage());
2515 Target->GlobalValue::copyAttributesFrom(J);
2516 }
Duncan Sands4782b302009-02-15 09:56:08 +00002517
2518 // Delete the alias.
2519 M.getAliasList().erase(J);
2520 ++NumAliasesRemoved;
2521 Changed = true;
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002522 }
2523
2524 return Changed;
2525}
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002526
Chris Lattner7a90b682004-10-07 04:16:33 +00002527bool GlobalOpt::runOnModule(Module &M) {
Chris Lattner079236d2004-02-25 21:34:36 +00002528 bool Changed = false;
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002529
2530 // Try to find the llvm.globalctors list.
2531 GlobalVariable *GlobalCtors = FindGlobalCtors(M);
Chris Lattner7a90b682004-10-07 04:16:33 +00002532
Chris Lattner7a90b682004-10-07 04:16:33 +00002533 bool LocalChange = true;
2534 while (LocalChange) {
2535 LocalChange = false;
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002536
2537 // Delete functions that are trivially dead, ccc -> fastcc
2538 LocalChange |= OptimizeFunctions(M);
2539
2540 // Optimize global_ctors list.
2541 if (GlobalCtors)
2542 LocalChange |= OptimizeGlobalCtorsList(GlobalCtors);
2543
2544 // Optimize non-address-taken globals.
2545 LocalChange |= OptimizeGlobalVars(M);
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002546
2547 // Resolve aliases, when possible.
Duncan Sandsfc5940d2009-03-06 10:21:56 +00002548 LocalChange |= OptimizeGlobalAliases(M);
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002549 Changed |= LocalChange;
Chris Lattner7a90b682004-10-07 04:16:33 +00002550 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002551
2552 // TODO: Move all global ctors functions to the end of the module for code
2553 // layout.
2554
Chris Lattner079236d2004-02-25 21:34:36 +00002555 return Changed;
2556}