blob: 61e4316a61475e9e78bbd17ae3e9807abe38cebd [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"
Owen Anderson14ce9ef2009-07-06 01:34:54 +000023#include "llvm/LLVMContext.h"
Chris Lattner079236d2004-02-25 21:34:36 +000024#include "llvm/Module.h"
25#include "llvm/Pass.h"
Chris Lattner79066fa2007-01-30 23:46:24 +000026#include "llvm/Analysis/ConstantFolding.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"
Reid Spencer9133fe22007-02-05 23:32:05 +000029#include "llvm/Support/Compiler.h"
Chris Lattner79066fa2007-01-30 23:46:24 +000030#include "llvm/Support/Debug.h"
Torok Edwinc25e7582009-07-11 20:10:48 +000031#include "llvm/Support/ErrorHandling.h"
Chris Lattner941db492008-01-14 02:09:12 +000032#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner998182b2008-04-26 07:40:11 +000033#include "llvm/Support/MathExtras.h"
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000034#include "llvm/Support/raw_ostream.h"
Chris Lattner5a6bb6a2008-12-16 07:34:30 +000035#include "llvm/ADT/DenseMap.h"
Chris Lattner81686182007-09-13 16:30:19 +000036#include "llvm/ADT/SmallPtrSet.h"
Chris Lattner55eb1c42007-01-31 04:40:53 +000037#include "llvm/ADT/SmallVector.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000038#include "llvm/ADT/Statistic.h"
Chris Lattner670c8892004-10-08 17:32:09 +000039#include "llvm/ADT/StringExtras.h"
Chris Lattnerbce4afe2008-12-17 05:28:49 +000040#include "llvm/ADT/STLExtras.h"
Chris Lattnere47ba742004-10-06 20:57:02 +000041#include <algorithm>
Chris Lattner079236d2004-02-25 21:34:36 +000042using namespace llvm;
43
Chris Lattner86453c52006-12-19 22:09:18 +000044STATISTIC(NumMarked , "Number of globals marked constant");
45STATISTIC(NumSRA , "Number of aggregate globals broken into scalars");
46STATISTIC(NumHeapSRA , "Number of heap objects SRA'd");
47STATISTIC(NumSubstitute,"Number of globals with initializers stored into them");
48STATISTIC(NumDeleted , "Number of globals deleted");
49STATISTIC(NumFnDeleted , "Number of functions deleted");
50STATISTIC(NumGlobUses , "Number of global uses devirtualized");
51STATISTIC(NumLocalized , "Number of globals localized");
52STATISTIC(NumShrunkToBool , "Number of global vars shrunk to booleans");
53STATISTIC(NumFastCallFns , "Number of functions converted to fastcc");
54STATISTIC(NumCtorsEvaluated, "Number of static ctors evaluated");
Duncan Sands3d5378f2008-02-16 20:56:04 +000055STATISTIC(NumNestRemoved , "Number of nest attributes removed");
Duncan Sands4782b302009-02-15 09:56:08 +000056STATISTIC(NumAliasesResolved, "Number of global aliases resolved");
57STATISTIC(NumAliasesRemoved, "Number of global aliases eliminated");
Chris Lattner079236d2004-02-25 21:34:36 +000058
Chris Lattner86453c52006-12-19 22:09:18 +000059namespace {
Reid Spencer9133fe22007-02-05 23:32:05 +000060 struct VISIBILITY_HIDDEN GlobalOpt : public ModulePass {
Chris Lattner30ba5692004-10-11 05:54:41 +000061 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
62 AU.addRequired<TargetData>();
63 }
Nick Lewyckyecd94c82007-05-06 13:37:16 +000064 static char ID; // Pass identification, replacement for typeid
Dan Gohmanae73dc12008-09-04 17:05:41 +000065 GlobalOpt() : ModulePass(&ID) {}
Misha Brukmanfd939082005-04-21 23:48:37 +000066
Chris Lattnerb12914b2004-09-20 04:48:05 +000067 bool runOnModule(Module &M);
Chris Lattner30ba5692004-10-11 05:54:41 +000068
69 private:
Chris Lattnerb1ab4582005-09-26 01:43:45 +000070 GlobalVariable *FindGlobalCtors(Module &M);
71 bool OptimizeFunctions(Module &M);
72 bool OptimizeGlobalVars(Module &M);
Duncan Sandsfc5940d2009-03-06 10:21:56 +000073 bool OptimizeGlobalAliases(Module &M);
Chris Lattnerb1ab4582005-09-26 01:43:45 +000074 bool OptimizeGlobalCtorsList(GlobalVariable *&GCL);
Chris Lattner7f8897f2006-08-27 22:42:52 +000075 bool ProcessInternalGlobal(GlobalVariable *GV,Module::global_iterator &GVI);
Chris Lattner079236d2004-02-25 21:34:36 +000076 };
Chris Lattner079236d2004-02-25 21:34:36 +000077}
78
Dan Gohman844731a2008-05-13 00:00:25 +000079char GlobalOpt::ID = 0;
80static RegisterPass<GlobalOpt> X("globalopt", "Global Variable Optimizer");
81
Chris Lattner7a90b682004-10-07 04:16:33 +000082ModulePass *llvm::createGlobalOptimizerPass() { return new GlobalOpt(); }
Chris Lattner079236d2004-02-25 21:34:36 +000083
Dan Gohman844731a2008-05-13 00:00:25 +000084namespace {
85
Chris Lattner7a90b682004-10-07 04:16:33 +000086/// GlobalStatus - As we analyze each global, keep track of some information
87/// about it. If we find out that the address of the global is taken, none of
Chris Lattnercf4d2a52004-10-07 21:30:30 +000088/// this info will be accurate.
Reid Spencer9133fe22007-02-05 23:32:05 +000089struct VISIBILITY_HIDDEN GlobalStatus {
Chris Lattnercf4d2a52004-10-07 21:30:30 +000090 /// isLoaded - True if the global is ever loaded. If the global isn't ever
91 /// loaded it can be deleted.
Chris Lattner7a90b682004-10-07 04:16:33 +000092 bool isLoaded;
Chris Lattnercf4d2a52004-10-07 21:30:30 +000093
94 /// StoredType - Keep track of what stores to the global look like.
95 ///
Chris Lattner7a90b682004-10-07 04:16:33 +000096 enum StoredType {
Chris Lattnercf4d2a52004-10-07 21:30:30 +000097 /// NotStored - There is no store to this global. It can thus be marked
98 /// constant.
99 NotStored,
100
101 /// isInitializerStored - This global is stored to, but the only thing
102 /// stored is the constant it was initialized with. This is only tracked
103 /// for scalar globals.
104 isInitializerStored,
105
106 /// isStoredOnce - This global is stored to, but only its initializer and
107 /// one other value is ever stored to it. If this global isStoredOnce, we
108 /// track the value stored to it in StoredOnceValue below. This is only
109 /// tracked for scalar globals.
110 isStoredOnce,
111
112 /// isStored - This global is stored to by multiple values or something else
113 /// that we cannot track.
114 isStored
Chris Lattner7a90b682004-10-07 04:16:33 +0000115 } StoredType;
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000116
117 /// StoredOnceValue - If only one value (besides the initializer constant) is
118 /// ever stored to this global, keep track of what value it is.
119 Value *StoredOnceValue;
120
Chris Lattner25de4e52006-11-01 18:03:33 +0000121 /// AccessingFunction/HasMultipleAccessingFunctions - These start out
122 /// null/false. When the first accessing function is noticed, it is recorded.
123 /// When a second different accessing function is noticed,
124 /// HasMultipleAccessingFunctions is set to true.
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +0000125 Function *AccessingFunction;
126 bool HasMultipleAccessingFunctions;
127
Chris Lattner25de4e52006-11-01 18:03:33 +0000128 /// HasNonInstructionUser - Set to true if this global has a user that is not
129 /// an instruction (e.g. a constant expr or GV initializer).
Chris Lattner553ca522005-06-15 21:11:48 +0000130 bool HasNonInstructionUser;
131
Chris Lattner25de4e52006-11-01 18:03:33 +0000132 /// HasPHIUser - Set to true if this global has a user that is a PHI node.
133 bool HasPHIUser;
134
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000135 GlobalStatus() : isLoaded(false), StoredType(NotStored), StoredOnceValue(0),
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +0000136 AccessingFunction(0), HasMultipleAccessingFunctions(false),
Chris Lattner6a93fc02008-01-14 01:32:52 +0000137 HasNonInstructionUser(false), HasPHIUser(false) {}
Chris Lattner7a90b682004-10-07 04:16:33 +0000138};
Chris Lattnere47ba742004-10-06 20:57:02 +0000139
Dan Gohman844731a2008-05-13 00:00:25 +0000140}
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000141
Jay Foade3acf152009-06-09 21:37:11 +0000142// SafeToDestroyConstant - It is safe to destroy a constant iff it is only used
143// by constants itself. Note that constants cannot be cyclic, so this test is
144// pretty easy to implement recursively.
145//
146static bool SafeToDestroyConstant(Constant *C) {
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000147 if (isa<GlobalValue>(C)) return false;
148
Devang Patel743cdf82009-03-06 01:37:41 +0000149 for (Value::use_iterator UI = C->use_begin(), E = C->use_end(); UI != E; ++UI)
150 if (Constant *CU = dyn_cast<Constant>(*UI)) {
Jay Foade3acf152009-06-09 21:37:11 +0000151 if (!SafeToDestroyConstant(CU)) return false;
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000152 } else
153 return false;
154 return true;
155}
156
157
Chris Lattner7a90b682004-10-07 04:16:33 +0000158/// AnalyzeGlobal - Look at all uses of the global and fill in the GlobalStatus
159/// structure. If the global has its address taken, return true to indicate we
160/// can't do anything with it.
Chris Lattner079236d2004-02-25 21:34:36 +0000161///
Chris Lattner7a90b682004-10-07 04:16:33 +0000162static bool AnalyzeGlobal(Value *V, GlobalStatus &GS,
Chris Lattner5a6bb6a2008-12-16 07:34:30 +0000163 SmallPtrSet<PHINode*, 16> &PHIUsers) {
Chris Lattner079236d2004-02-25 21:34:36 +0000164 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
Chris Lattner96940cb2004-07-18 19:56:20 +0000165 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(*UI)) {
Chris Lattner553ca522005-06-15 21:11:48 +0000166 GS.HasNonInstructionUser = true;
167
Chris Lattner7a90b682004-10-07 04:16:33 +0000168 if (AnalyzeGlobal(CE, GS, PHIUsers)) return true;
Chris Lattner670c8892004-10-08 17:32:09 +0000169
Chris Lattner079236d2004-02-25 21:34:36 +0000170 } else if (Instruction *I = dyn_cast<Instruction>(*UI)) {
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +0000171 if (!GS.HasMultipleAccessingFunctions) {
172 Function *F = I->getParent()->getParent();
173 if (GS.AccessingFunction == 0)
174 GS.AccessingFunction = F;
175 else if (GS.AccessingFunction != F)
176 GS.HasMultipleAccessingFunctions = true;
177 }
Chris Lattnerc69d3c92008-01-29 19:01:37 +0000178 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattner7a90b682004-10-07 04:16:33 +0000179 GS.isLoaded = true;
Chris Lattnerc69d3c92008-01-29 19:01:37 +0000180 if (LI->isVolatile()) return true; // Don't hack on volatile loads.
Chris Lattner7a90b682004-10-07 04:16:33 +0000181 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Chris Lattner36025492004-10-07 06:01:25 +0000182 // Don't allow a store OF the address, only stores TO the address.
183 if (SI->getOperand(0) == V) return true;
184
Chris Lattnerc69d3c92008-01-29 19:01:37 +0000185 if (SI->isVolatile()) return true; // Don't hack on volatile stores.
186
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000187 // If this is a direct store to the global (i.e., the global is a scalar
188 // value, not an aggregate), keep more specific information about
189 // stores.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000190 if (GS.StoredType != GlobalStatus::isStored) {
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000191 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(SI->getOperand(1))){
Chris Lattnerbd38edf2004-11-14 20:50:30 +0000192 Value *StoredVal = SI->getOperand(0);
193 if (StoredVal == GV->getInitializer()) {
194 if (GS.StoredType < GlobalStatus::isInitializerStored)
195 GS.StoredType = GlobalStatus::isInitializerStored;
196 } else if (isa<LoadInst>(StoredVal) &&
197 cast<LoadInst>(StoredVal)->getOperand(0) == GV) {
198 // G = G
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000199 if (GS.StoredType < GlobalStatus::isInitializerStored)
200 GS.StoredType = GlobalStatus::isInitializerStored;
201 } else if (GS.StoredType < GlobalStatus::isStoredOnce) {
202 GS.StoredType = GlobalStatus::isStoredOnce;
Chris Lattnerbd38edf2004-11-14 20:50:30 +0000203 GS.StoredOnceValue = StoredVal;
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000204 } else if (GS.StoredType == GlobalStatus::isStoredOnce &&
Chris Lattnerbd38edf2004-11-14 20:50:30 +0000205 GS.StoredOnceValue == StoredVal) {
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000206 // noop.
207 } else {
208 GS.StoredType = GlobalStatus::isStored;
209 }
210 } else {
Chris Lattner7a90b682004-10-07 04:16:33 +0000211 GS.StoredType = GlobalStatus::isStored;
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000212 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000213 }
Chris Lattner35c81b02005-02-27 18:58:52 +0000214 } else if (isa<GetElementPtrInst>(I)) {
Chris Lattner7a90b682004-10-07 04:16:33 +0000215 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Chris Lattner35c81b02005-02-27 18:58:52 +0000216 } else if (isa<SelectInst>(I)) {
Chris Lattner7a90b682004-10-07 04:16:33 +0000217 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Chris Lattner7a90b682004-10-07 04:16:33 +0000218 } else if (PHINode *PN = dyn_cast<PHINode>(I)) {
219 // PHI nodes we can check just like select or GEP instructions, but we
220 // have to be careful about infinite recursion.
Chris Lattner5a6bb6a2008-12-16 07:34:30 +0000221 if (PHIUsers.insert(PN)) // Not already visited.
Chris Lattner7a90b682004-10-07 04:16:33 +0000222 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Chris Lattner25de4e52006-11-01 18:03:33 +0000223 GS.HasPHIUser = true;
Reid Spencere4d87aa2006-12-23 06:05:41 +0000224 } else if (isa<CmpInst>(I)) {
Chris Lattner8e108442009-03-08 03:37:35 +0000225 } else if (isa<MemTransferInst>(I)) {
Chris Lattner35c81b02005-02-27 18:58:52 +0000226 if (I->getOperand(1) == V)
227 GS.StoredType = GlobalStatus::isStored;
228 if (I->getOperand(2) == V)
229 GS.isLoaded = true;
Chris Lattner35c81b02005-02-27 18:58:52 +0000230 } else if (isa<MemSetInst>(I)) {
231 assert(I->getOperand(1) == V && "Memset only takes one pointer!");
232 GS.StoredType = GlobalStatus::isStored;
Chris Lattner7a90b682004-10-07 04:16:33 +0000233 } else {
234 return true; // Any other non-load instruction might take address!
Chris Lattner9ce30002004-07-20 03:58:07 +0000235 }
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000236 } else if (Constant *C = dyn_cast<Constant>(*UI)) {
Chris Lattner553ca522005-06-15 21:11:48 +0000237 GS.HasNonInstructionUser = true;
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000238 // We might have a dead and dangling constant hanging off of here.
Jay Foade3acf152009-06-09 21:37:11 +0000239 if (!SafeToDestroyConstant(C))
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000240 return true;
Chris Lattner079236d2004-02-25 21:34:36 +0000241 } else {
Chris Lattner553ca522005-06-15 21:11:48 +0000242 GS.HasNonInstructionUser = true;
243 // Otherwise must be some other user.
Chris Lattner079236d2004-02-25 21:34:36 +0000244 return true;
245 }
246
247 return false;
248}
249
Owen Anderson14ce9ef2009-07-06 01:34:54 +0000250static Constant *getAggregateConstantElement(Constant *Agg, Constant *Idx,
Owen Andersone922c022009-07-22 00:24:57 +0000251 LLVMContext &Context) {
Chris Lattner670c8892004-10-08 17:32:09 +0000252 ConstantInt *CI = dyn_cast<ConstantInt>(Idx);
253 if (!CI) return 0;
Reid Spencerb83eb642006-10-20 07:07:24 +0000254 unsigned IdxV = CI->getZExtValue();
Chris Lattner7a90b682004-10-07 04:16:33 +0000255
Chris Lattner670c8892004-10-08 17:32:09 +0000256 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Agg)) {
257 if (IdxV < CS->getNumOperands()) return CS->getOperand(IdxV);
258 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Agg)) {
259 if (IdxV < CA->getNumOperands()) return CA->getOperand(IdxV);
Reid Spencer9d6565a2007-02-15 02:26:10 +0000260 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Agg)) {
Chris Lattner670c8892004-10-08 17:32:09 +0000261 if (IdxV < CP->getNumOperands()) return CP->getOperand(IdxV);
Chris Lattner7a7ed022004-10-16 18:09:00 +0000262 } else if (isa<ConstantAggregateZero>(Agg)) {
Chris Lattner670c8892004-10-08 17:32:09 +0000263 if (const StructType *STy = dyn_cast<StructType>(Agg->getType())) {
264 if (IdxV < STy->getNumElements())
Owen Andersone922c022009-07-22 00:24:57 +0000265 return Context.getNullValue(STy->getElementType(IdxV));
Chris Lattner670c8892004-10-08 17:32:09 +0000266 } else if (const SequentialType *STy =
267 dyn_cast<SequentialType>(Agg->getType())) {
Owen Andersone922c022009-07-22 00:24:57 +0000268 return Context.getNullValue(STy->getElementType());
Chris Lattner670c8892004-10-08 17:32:09 +0000269 }
Chris Lattner7a7ed022004-10-16 18:09:00 +0000270 } else if (isa<UndefValue>(Agg)) {
271 if (const StructType *STy = dyn_cast<StructType>(Agg->getType())) {
272 if (IdxV < STy->getNumElements())
Owen Andersone922c022009-07-22 00:24:57 +0000273 return Context.getUndef(STy->getElementType(IdxV));
Chris Lattner7a7ed022004-10-16 18:09:00 +0000274 } else if (const SequentialType *STy =
275 dyn_cast<SequentialType>(Agg->getType())) {
Owen Andersone922c022009-07-22 00:24:57 +0000276 return Context.getUndef(STy->getElementType());
Chris Lattner7a7ed022004-10-16 18:09:00 +0000277 }
Chris Lattner670c8892004-10-08 17:32:09 +0000278 }
279 return 0;
280}
Chris Lattner7a90b682004-10-07 04:16:33 +0000281
Chris Lattner7a90b682004-10-07 04:16:33 +0000282
Chris Lattnere47ba742004-10-06 20:57:02 +0000283/// CleanupConstantGlobalUsers - We just marked GV constant. Loop over all
284/// users of the global, cleaning up the obvious ones. This is largely just a
Chris Lattner031955d2004-10-10 16:43:46 +0000285/// quick scan over the use list to clean up the easy and obvious cruft. This
286/// returns true if it made a change.
Owen Anderson50895512009-07-06 18:42:36 +0000287static bool CleanupConstantGlobalUsers(Value *V, Constant *Init,
Owen Andersone922c022009-07-22 00:24:57 +0000288 LLVMContext &Context) {
Chris Lattner031955d2004-10-10 16:43:46 +0000289 bool Changed = false;
Chris Lattner7a90b682004-10-07 04:16:33 +0000290 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;) {
291 User *U = *UI++;
Misha Brukmanfd939082005-04-21 23:48:37 +0000292
Chris Lattner7a90b682004-10-07 04:16:33 +0000293 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
Chris Lattner35c81b02005-02-27 18:58:52 +0000294 if (Init) {
295 // Replace the load with the initializer.
296 LI->replaceAllUsesWith(Init);
297 LI->eraseFromParent();
298 Changed = true;
299 }
Chris Lattner7a90b682004-10-07 04:16:33 +0000300 } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
Chris Lattnere47ba742004-10-06 20:57:02 +0000301 // Store must be unreachable or storing Init into the global.
Chris Lattner7a7ed022004-10-16 18:09:00 +0000302 SI->eraseFromParent();
Chris Lattner031955d2004-10-10 16:43:46 +0000303 Changed = true;
Chris Lattner7a90b682004-10-07 04:16:33 +0000304 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
305 if (CE->getOpcode() == Instruction::GetElementPtr) {
Chris Lattneraae4a1c2005-09-26 07:34:35 +0000306 Constant *SubInit = 0;
307 if (Init)
Owen Anderson50895512009-07-06 18:42:36 +0000308 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE, Context);
309 Changed |= CleanupConstantGlobalUsers(CE, SubInit, Context);
Reid Spencer3da59db2006-11-27 01:05:10 +0000310 } else if (CE->getOpcode() == Instruction::BitCast &&
Chris Lattner35c81b02005-02-27 18:58:52 +0000311 isa<PointerType>(CE->getType())) {
312 // Pointer cast, delete any stores and memsets to the global.
Owen Anderson50895512009-07-06 18:42:36 +0000313 Changed |= CleanupConstantGlobalUsers(CE, 0, Context);
Chris Lattner35c81b02005-02-27 18:58:52 +0000314 }
315
316 if (CE->use_empty()) {
317 CE->destroyConstant();
318 Changed = true;
Chris Lattner7a90b682004-10-07 04:16:33 +0000319 }
320 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
Chris Lattner7b52fe72007-11-09 17:33:02 +0000321 // Do not transform "gepinst (gep constexpr (GV))" here, because forming
322 // "gepconstexpr (gep constexpr (GV))" will cause the two gep's to fold
323 // and will invalidate our notion of what Init is.
Chris Lattner19450242007-11-13 21:46:23 +0000324 Constant *SubInit = 0;
Chris Lattner7b52fe72007-11-09 17:33:02 +0000325 if (!isa<ConstantExpr>(GEP->getOperand(0))) {
326 ConstantExpr *CE =
Owen Anderson50895512009-07-06 18:42:36 +0000327 dyn_cast_or_null<ConstantExpr>(ConstantFoldInstruction(GEP, Context));
Chris Lattner7b52fe72007-11-09 17:33:02 +0000328 if (Init && CE && CE->getOpcode() == Instruction::GetElementPtr)
Owen Anderson50895512009-07-06 18:42:36 +0000329 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE, Context);
Chris Lattner7b52fe72007-11-09 17:33:02 +0000330 }
Owen Anderson50895512009-07-06 18:42:36 +0000331 Changed |= CleanupConstantGlobalUsers(GEP, SubInit, Context);
Chris Lattnerc4d81b02004-10-10 16:47:33 +0000332
Chris Lattner031955d2004-10-10 16:43:46 +0000333 if (GEP->use_empty()) {
Chris Lattner7a7ed022004-10-16 18:09:00 +0000334 GEP->eraseFromParent();
Chris Lattner031955d2004-10-10 16:43:46 +0000335 Changed = true;
336 }
Chris Lattner35c81b02005-02-27 18:58:52 +0000337 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U)) { // memset/cpy/mv
338 if (MI->getRawDest() == V) {
339 MI->eraseFromParent();
340 Changed = true;
341 }
342
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000343 } else if (Constant *C = dyn_cast<Constant>(U)) {
344 // If we have a chain of dead constantexprs or other things dangling from
345 // us, and if they are all dead, nuke them without remorse.
Jay Foade3acf152009-06-09 21:37:11 +0000346 if (SafeToDestroyConstant(C)) {
Devang Patel743cdf82009-03-06 01:37:41 +0000347 C->destroyConstant();
Chris Lattner35c81b02005-02-27 18:58:52 +0000348 // This could have invalidated UI, start over from scratch.
Owen Anderson50895512009-07-06 18:42:36 +0000349 CleanupConstantGlobalUsers(V, Init, Context);
Chris Lattner031955d2004-10-10 16:43:46 +0000350 return true;
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000351 }
Chris Lattnere47ba742004-10-06 20:57:02 +0000352 }
353 }
Chris Lattner031955d2004-10-10 16:43:46 +0000354 return Changed;
Chris Lattnere47ba742004-10-06 20:57:02 +0000355}
356
Chris Lattner941db492008-01-14 02:09:12 +0000357/// isSafeSROAElementUse - Return true if the specified instruction is a safe
358/// user of a derived expression from a global that we want to SROA.
359static bool isSafeSROAElementUse(Value *V) {
360 // We might have a dead and dangling constant hanging off of here.
361 if (Constant *C = dyn_cast<Constant>(V))
Jay Foade3acf152009-06-09 21:37:11 +0000362 return SafeToDestroyConstant(C);
Chris Lattner727c2102008-01-14 01:31:05 +0000363
Chris Lattner941db492008-01-14 02:09:12 +0000364 Instruction *I = dyn_cast<Instruction>(V);
365 if (!I) return false;
366
367 // Loads are ok.
368 if (isa<LoadInst>(I)) return true;
369
370 // Stores *to* the pointer are ok.
371 if (StoreInst *SI = dyn_cast<StoreInst>(I))
372 return SI->getOperand(0) != V;
373
374 // Otherwise, it must be a GEP.
375 GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I);
376 if (GEPI == 0) return false;
377
378 if (GEPI->getNumOperands() < 3 || !isa<Constant>(GEPI->getOperand(1)) ||
379 !cast<Constant>(GEPI->getOperand(1))->isNullValue())
380 return false;
381
382 for (Value::use_iterator I = GEPI->use_begin(), E = GEPI->use_end();
383 I != E; ++I)
384 if (!isSafeSROAElementUse(*I))
385 return false;
Chris Lattner727c2102008-01-14 01:31:05 +0000386 return true;
387}
388
Chris Lattner941db492008-01-14 02:09:12 +0000389
390/// IsUserOfGlobalSafeForSRA - U is a direct user of the specified global value.
391/// Look at it and its uses and decide whether it is safe to SROA this global.
392///
393static bool IsUserOfGlobalSafeForSRA(User *U, GlobalValue *GV) {
394 // The user of the global must be a GEP Inst or a ConstantExpr GEP.
395 if (!isa<GetElementPtrInst>(U) &&
396 (!isa<ConstantExpr>(U) ||
397 cast<ConstantExpr>(U)->getOpcode() != Instruction::GetElementPtr))
398 return false;
399
400 // Check to see if this ConstantExpr GEP is SRA'able. In particular, we
401 // don't like < 3 operand CE's, and we don't like non-constant integer
402 // indices. This enforces that all uses are 'gep GV, 0, C, ...' for some
403 // value of C.
404 if (U->getNumOperands() < 3 || !isa<Constant>(U->getOperand(1)) ||
405 !cast<Constant>(U->getOperand(1))->isNullValue() ||
406 !isa<ConstantInt>(U->getOperand(2)))
407 return false;
408
409 gep_type_iterator GEPI = gep_type_begin(U), E = gep_type_end(U);
410 ++GEPI; // Skip over the pointer index.
411
412 // If this is a use of an array allocation, do a bit more checking for sanity.
413 if (const ArrayType *AT = dyn_cast<ArrayType>(*GEPI)) {
414 uint64_t NumElements = AT->getNumElements();
415 ConstantInt *Idx = cast<ConstantInt>(U->getOperand(2));
416
417 // Check to make sure that index falls within the array. If not,
418 // something funny is going on, so we won't do the optimization.
419 //
420 if (Idx->getZExtValue() >= NumElements)
421 return false;
422
423 // We cannot scalar repl this level of the array unless any array
424 // sub-indices are in-range constants. In particular, consider:
425 // A[0][i]. We cannot know that the user isn't doing invalid things like
426 // allowing i to index an out-of-range subscript that accesses A[1].
427 //
428 // Scalar replacing *just* the outer index of the array is probably not
429 // going to be a win anyway, so just give up.
430 for (++GEPI; // Skip array index.
431 GEPI != E && (isa<ArrayType>(*GEPI) || isa<VectorType>(*GEPI));
432 ++GEPI) {
433 uint64_t NumElements;
434 if (const ArrayType *SubArrayTy = dyn_cast<ArrayType>(*GEPI))
435 NumElements = SubArrayTy->getNumElements();
436 else
437 NumElements = cast<VectorType>(*GEPI)->getNumElements();
438
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.
Owen Anderson14ce9ef2009-07-06 01:34:54 +0000469static GlobalVariable *SRAGlobal(GlobalVariable *GV, const TargetData &TD,
Owen Andersone922c022009-07-22 00:24:57 +0000470 LLVMContext &Context) {
Chris Lattner727c2102008-01-14 01:31:05 +0000471 // Make sure this global only has simple uses that we can SRA.
Chris Lattner941db492008-01-14 02:09:12 +0000472 if (!GlobalUsersSafeToSRA(GV))
Chris Lattner727c2102008-01-14 01:31:05 +0000473 return 0;
474
Rafael Espindolabb46f522009-01-15 20:18:42 +0000475 assert(GV->hasLocalLinkage() && !GV->isConstant());
Chris Lattner670c8892004-10-08 17:32:09 +0000476 Constant *Init = GV->getInitializer();
477 const Type *Ty = Init->getType();
Misha Brukmanfd939082005-04-21 23:48:37 +0000478
Chris Lattner670c8892004-10-08 17:32:09 +0000479 std::vector<GlobalVariable*> NewGlobals;
480 Module::GlobalListType &Globals = GV->getParent()->getGlobalList();
481
Chris Lattner998182b2008-04-26 07:40:11 +0000482 // Get the alignment of the global, either explicit or target-specific.
483 unsigned StartAlignment = GV->getAlignment();
484 if (StartAlignment == 0)
485 StartAlignment = TD.getABITypeAlignment(GV->getType());
486
Chris Lattner670c8892004-10-08 17:32:09 +0000487 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
488 NewGlobals.reserve(STy->getNumElements());
Chris Lattner998182b2008-04-26 07:40:11 +0000489 const StructLayout &Layout = *TD.getStructLayout(STy);
Chris Lattner670c8892004-10-08 17:32:09 +0000490 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
491 Constant *In = getAggregateConstantElement(Init,
Owen Andersoneed707b2009-07-24 23:12:02 +0000492 ConstantInt::get(Type::Int32Ty, i),
Owen Anderson14ce9ef2009-07-06 01:34:54 +0000493 Context);
Chris Lattner670c8892004-10-08 17:32:09 +0000494 assert(In && "Couldn't get element of initializer?");
Owen Andersone922c022009-07-22 00:24:57 +0000495 GlobalVariable *NGV = new GlobalVariable(Context,
Owen Andersone9b11b42009-07-08 19:03:57 +0000496 STy->getElementType(i), false,
Chris Lattner670c8892004-10-08 17:32:09 +0000497 GlobalVariable::InternalLinkage,
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +0000498 In, GV->getName()+"."+utostr(i),
Matthijs Kooijmanbc1f9892008-07-17 11:59:53 +0000499 GV->isThreadLocal(),
Owen Anderson3d29df32009-07-08 01:26:06 +0000500 GV->getType()->getAddressSpace());
Chris Lattner670c8892004-10-08 17:32:09 +0000501 Globals.insert(GV, NGV);
502 NewGlobals.push_back(NGV);
Chris Lattner998182b2008-04-26 07:40:11 +0000503
504 // Calculate the known alignment of the field. If the original aggregate
505 // had 256 byte alignment for example, something might depend on that:
506 // propagate info to each field.
507 uint64_t FieldOffset = Layout.getElementOffset(i);
508 unsigned NewAlign = (unsigned)MinAlign(StartAlignment, FieldOffset);
509 if (NewAlign > TD.getABITypeAlignment(STy->getElementType(i)))
510 NGV->setAlignment(NewAlign);
Chris Lattner670c8892004-10-08 17:32:09 +0000511 }
512 } else if (const SequentialType *STy = dyn_cast<SequentialType>(Ty)) {
513 unsigned NumElements = 0;
514 if (const ArrayType *ATy = dyn_cast<ArrayType>(STy))
515 NumElements = ATy->getNumElements();
Chris Lattner670c8892004-10-08 17:32:09 +0000516 else
Chris Lattner998182b2008-04-26 07:40:11 +0000517 NumElements = cast<VectorType>(STy)->getNumElements();
Chris Lattner670c8892004-10-08 17:32:09 +0000518
Chris Lattner1f21ef12005-02-23 16:53:04 +0000519 if (NumElements > 16 && GV->hasNUsesOrMore(16))
Chris Lattnerd514d822005-02-01 01:23:31 +0000520 return 0; // It's not worth it.
Chris Lattner670c8892004-10-08 17:32:09 +0000521 NewGlobals.reserve(NumElements);
Chris Lattner998182b2008-04-26 07:40:11 +0000522
Duncan Sands777d2302009-05-09 07:06:46 +0000523 uint64_t EltSize = TD.getTypeAllocSize(STy->getElementType());
Chris Lattner998182b2008-04-26 07:40:11 +0000524 unsigned EltAlign = TD.getABITypeAlignment(STy->getElementType());
Chris Lattner670c8892004-10-08 17:32:09 +0000525 for (unsigned i = 0, e = NumElements; i != e; ++i) {
526 Constant *In = getAggregateConstantElement(Init,
Owen Andersoneed707b2009-07-24 23:12:02 +0000527 ConstantInt::get(Type::Int32Ty, i),
Owen Anderson14ce9ef2009-07-06 01:34:54 +0000528 Context);
Chris Lattner670c8892004-10-08 17:32:09 +0000529 assert(In && "Couldn't get element of initializer?");
530
Owen Andersone922c022009-07-22 00:24:57 +0000531 GlobalVariable *NGV = new GlobalVariable(Context,
Owen Andersone9b11b42009-07-08 19:03:57 +0000532 STy->getElementType(), false,
Chris Lattner670c8892004-10-08 17:32:09 +0000533 GlobalVariable::InternalLinkage,
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +0000534 In, GV->getName()+"."+utostr(i),
Matthijs Kooijmanbc1f9892008-07-17 11:59:53 +0000535 GV->isThreadLocal(),
Owen Andersone9b11b42009-07-08 19:03:57 +0000536 GV->getType()->getAddressSpace());
Chris Lattner670c8892004-10-08 17:32:09 +0000537 Globals.insert(GV, NGV);
538 NewGlobals.push_back(NGV);
Chris Lattner998182b2008-04-26 07:40:11 +0000539
540 // Calculate the known alignment of the field. If the original aggregate
541 // had 256 byte alignment for example, something might depend on that:
542 // propagate info to each field.
543 unsigned NewAlign = (unsigned)MinAlign(StartAlignment, EltSize*i);
544 if (NewAlign > EltAlign)
545 NGV->setAlignment(NewAlign);
Chris Lattner670c8892004-10-08 17:32:09 +0000546 }
547 }
548
549 if (NewGlobals.empty())
550 return 0;
551
Bill Wendling0a81aac2006-11-26 10:02:32 +0000552 DOUT << "PERFORMING GLOBAL SRA ON: " << *GV;
Chris Lattner30ba5692004-10-11 05:54:41 +0000553
Owen Andersone922c022009-07-22 00:24:57 +0000554 Constant *NullInt = Context.getNullValue(Type::Int32Ty);
Chris Lattner670c8892004-10-08 17:32:09 +0000555
556 // Loop over all of the uses of the global, replacing the constantexpr geps,
557 // with smaller constantexpr geps or direct references.
558 while (!GV->use_empty()) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000559 User *GEP = GV->use_back();
560 assert(((isa<ConstantExpr>(GEP) &&
561 cast<ConstantExpr>(GEP)->getOpcode()==Instruction::GetElementPtr)||
562 isa<GetElementPtrInst>(GEP)) && "NonGEP CE's are not SRAable!");
Misha Brukmanfd939082005-04-21 23:48:37 +0000563
Chris Lattner670c8892004-10-08 17:32:09 +0000564 // Ignore the 1th operand, which has to be zero or else the program is quite
565 // broken (undefined). Get the 2nd operand, which is the structure or array
566 // index.
Reid Spencerb83eb642006-10-20 07:07:24 +0000567 unsigned Val = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
Chris Lattner670c8892004-10-08 17:32:09 +0000568 if (Val >= NewGlobals.size()) Val = 0; // Out of bound array access.
569
Chris Lattner30ba5692004-10-11 05:54:41 +0000570 Value *NewPtr = NewGlobals[Val];
Chris Lattner670c8892004-10-08 17:32:09 +0000571
572 // Form a shorter GEP if needed.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000573 if (GEP->getNumOperands() > 3) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000574 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEP)) {
Chris Lattner55eb1c42007-01-31 04:40:53 +0000575 SmallVector<Constant*, 8> Idxs;
Chris Lattner30ba5692004-10-11 05:54:41 +0000576 Idxs.push_back(NullInt);
577 for (unsigned i = 3, e = CE->getNumOperands(); i != e; ++i)
578 Idxs.push_back(CE->getOperand(i));
Owen Andersonbaf3c402009-07-29 18:55:55 +0000579 NewPtr = ConstantExpr::getGetElementPtr(cast<Constant>(NewPtr),
Chris Lattner55eb1c42007-01-31 04:40:53 +0000580 &Idxs[0], Idxs.size());
Chris Lattner30ba5692004-10-11 05:54:41 +0000581 } else {
582 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(GEP);
Chris Lattner699d1442007-01-31 19:59:55 +0000583 SmallVector<Value*, 8> Idxs;
Chris Lattner30ba5692004-10-11 05:54:41 +0000584 Idxs.push_back(NullInt);
585 for (unsigned i = 3, e = GEPI->getNumOperands(); i != e; ++i)
586 Idxs.push_back(GEPI->getOperand(i));
Gabor Greif051a9502008-04-06 20:25:17 +0000587 NewPtr = GetElementPtrInst::Create(NewPtr, Idxs.begin(), Idxs.end(),
588 GEPI->getName()+"."+utostr(Val), GEPI);
Chris Lattner30ba5692004-10-11 05:54:41 +0000589 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000590 }
Chris Lattner30ba5692004-10-11 05:54:41 +0000591 GEP->replaceAllUsesWith(NewPtr);
592
593 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(GEP))
Chris Lattner7a7ed022004-10-16 18:09:00 +0000594 GEPI->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +0000595 else
596 cast<ConstantExpr>(GEP)->destroyConstant();
Chris Lattner670c8892004-10-08 17:32:09 +0000597 }
598
Chris Lattnere40e2d12004-10-08 20:25:55 +0000599 // Delete the old global, now that it is dead.
600 Globals.erase(GV);
Chris Lattner670c8892004-10-08 17:32:09 +0000601 ++NumSRA;
Chris Lattner30ba5692004-10-11 05:54:41 +0000602
603 // Loop over the new globals array deleting any globals that are obviously
604 // dead. This can arise due to scalarization of a structure or an array that
605 // has elements that are dead.
606 unsigned FirstGlobal = 0;
607 for (unsigned i = 0, e = NewGlobals.size(); i != e; ++i)
608 if (NewGlobals[i]->use_empty()) {
609 Globals.erase(NewGlobals[i]);
610 if (FirstGlobal == i) ++FirstGlobal;
611 }
612
613 return FirstGlobal != NewGlobals.size() ? NewGlobals[FirstGlobal] : 0;
Chris Lattner670c8892004-10-08 17:32:09 +0000614}
615
Chris Lattner9b34a612004-10-09 21:48:45 +0000616/// AllUsesOfValueWillTrapIfNull - Return true if all users of the specified
Chris Lattner81686182007-09-13 16:30:19 +0000617/// value will trap if the value is dynamically null. PHIs keeps track of any
618/// phi nodes we've seen to avoid reprocessing them.
619static bool AllUsesOfValueWillTrapIfNull(Value *V,
620 SmallPtrSet<PHINode*, 8> &PHIs) {
Chris Lattner9b34a612004-10-09 21:48:45 +0000621 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
622 if (isa<LoadInst>(*UI)) {
623 // Will trap.
624 } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
625 if (SI->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; // Storing the value.
628 }
629 } else if (CallInst *CI = dyn_cast<CallInst>(*UI)) {
630 if (CI->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 }
634 } else if (InvokeInst *II = dyn_cast<InvokeInst>(*UI)) {
635 if (II->getOperand(0) != V) {
Bill Wendlinge8156192006-12-07 01:30:32 +0000636 //cerr << "NONTRAPPING USE: " << **UI;
Chris Lattner9b34a612004-10-09 21:48:45 +0000637 return false; // Not calling the ptr
638 }
Chris Lattner81686182007-09-13 16:30:19 +0000639 } else if (BitCastInst *CI = dyn_cast<BitCastInst>(*UI)) {
640 if (!AllUsesOfValueWillTrapIfNull(CI, PHIs)) return false;
Chris Lattner9b34a612004-10-09 21:48:45 +0000641 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(*UI)) {
Chris Lattner81686182007-09-13 16:30:19 +0000642 if (!AllUsesOfValueWillTrapIfNull(GEPI, PHIs)) return false;
643 } else if (PHINode *PN = dyn_cast<PHINode>(*UI)) {
644 // If we've already seen this phi node, ignore it, it has already been
645 // checked.
646 if (PHIs.insert(PN))
647 return AllUsesOfValueWillTrapIfNull(PN, PHIs);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000648 } else if (isa<ICmpInst>(*UI) &&
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000649 isa<ConstantPointerNull>(UI->getOperand(1))) {
650 // Ignore setcc X, null
Chris Lattner9b34a612004-10-09 21:48:45 +0000651 } else {
Bill Wendlinge8156192006-12-07 01:30:32 +0000652 //cerr << "NONTRAPPING USE: " << **UI;
Chris Lattner9b34a612004-10-09 21:48:45 +0000653 return false;
654 }
655 return true;
656}
657
658/// AllUsesOfLoadedValueWillTrapIfNull - Return true if all uses of any loads
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000659/// from GV will trap if the loaded value is null. Note that this also permits
660/// comparisons of the loaded value against null, as a special case.
Chris Lattner9b34a612004-10-09 21:48:45 +0000661static bool AllUsesOfLoadedValueWillTrapIfNull(GlobalVariable *GV) {
662 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI!=E; ++UI)
663 if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
Chris Lattner81686182007-09-13 16:30:19 +0000664 SmallPtrSet<PHINode*, 8> PHIs;
665 if (!AllUsesOfValueWillTrapIfNull(LI, PHIs))
Chris Lattner9b34a612004-10-09 21:48:45 +0000666 return false;
667 } else if (isa<StoreInst>(*UI)) {
668 // Ignore stores to the global.
669 } else {
670 // We don't know or understand this user, bail out.
Bill Wendlinge8156192006-12-07 01:30:32 +0000671 //cerr << "UNKNOWN USER OF GLOBAL!: " << **UI;
Chris Lattner9b34a612004-10-09 21:48:45 +0000672 return false;
673 }
674
675 return true;
676}
677
Owen Anderson14ce9ef2009-07-06 01:34:54 +0000678static bool OptimizeAwayTrappingUsesOfValue(Value *V, Constant *NewV,
Owen Andersone922c022009-07-22 00:24:57 +0000679 LLVMContext &Context) {
Chris Lattner708148e2004-10-10 23:14:11 +0000680 bool Changed = false;
681 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ) {
682 Instruction *I = cast<Instruction>(*UI++);
683 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
684 LI->setOperand(0, NewV);
685 Changed = true;
686 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
687 if (SI->getOperand(1) == V) {
688 SI->setOperand(1, NewV);
689 Changed = true;
690 }
691 } else if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
692 if (I->getOperand(0) == V) {
693 // Calling through the pointer! Turn into a direct call, but be careful
694 // that the pointer is not also being passed as an argument.
695 I->setOperand(0, NewV);
696 Changed = true;
697 bool PassedAsArg = false;
698 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i)
699 if (I->getOperand(i) == V) {
700 PassedAsArg = true;
701 I->setOperand(i, NewV);
702 }
703
704 if (PassedAsArg) {
705 // Being passed as an argument also. Be careful to not invalidate UI!
706 UI = V->use_begin();
707 }
708 }
709 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
710 Changed |= OptimizeAwayTrappingUsesOfValue(CI,
Owen Andersonbaf3c402009-07-29 18:55:55 +0000711 ConstantExpr::getCast(CI->getOpcode(),
Owen Anderson14ce9ef2009-07-06 01:34:54 +0000712 NewV, CI->getType()), Context);
Chris Lattner708148e2004-10-10 23:14:11 +0000713 if (CI->use_empty()) {
714 Changed = true;
Chris Lattner7a7ed022004-10-16 18:09:00 +0000715 CI->eraseFromParent();
Chris Lattner708148e2004-10-10 23:14:11 +0000716 }
717 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
718 // Should handle GEP here.
Chris Lattner55eb1c42007-01-31 04:40:53 +0000719 SmallVector<Constant*, 8> Idxs;
720 Idxs.reserve(GEPI->getNumOperands()-1);
Gabor Greif5e463212008-05-29 01:59:18 +0000721 for (User::op_iterator i = GEPI->op_begin() + 1, e = GEPI->op_end();
722 i != e; ++i)
723 if (Constant *C = dyn_cast<Constant>(*i))
Chris Lattner55eb1c42007-01-31 04:40:53 +0000724 Idxs.push_back(C);
Chris Lattner708148e2004-10-10 23:14:11 +0000725 else
726 break;
Chris Lattner55eb1c42007-01-31 04:40:53 +0000727 if (Idxs.size() == GEPI->getNumOperands()-1)
Chris Lattner708148e2004-10-10 23:14:11 +0000728 Changed |= OptimizeAwayTrappingUsesOfValue(GEPI,
Owen Andersonbaf3c402009-07-29 18:55:55 +0000729 ConstantExpr::getGetElementPtr(NewV, &Idxs[0],
Owen Anderson14ce9ef2009-07-06 01:34:54 +0000730 Idxs.size()), Context);
Chris Lattner708148e2004-10-10 23:14:11 +0000731 if (GEPI->use_empty()) {
732 Changed = true;
Chris Lattner7a7ed022004-10-16 18:09:00 +0000733 GEPI->eraseFromParent();
Chris Lattner708148e2004-10-10 23:14:11 +0000734 }
735 }
736 }
737
738 return Changed;
739}
740
741
742/// OptimizeAwayTrappingUsesOfLoads - The specified global has only one non-null
743/// value stored into it. If there are uses of the loaded value that would trap
744/// if the loaded value is dynamically null, then we know that they cannot be
745/// reachable with a null optimize away the load.
Owen Anderson14ce9ef2009-07-06 01:34:54 +0000746static bool OptimizeAwayTrappingUsesOfLoads(GlobalVariable *GV, Constant *LV,
Owen Andersone922c022009-07-22 00:24:57 +0000747 LLVMContext &Context) {
Chris Lattner708148e2004-10-10 23:14:11 +0000748 bool Changed = false;
749
Chris Lattner92c6bd22009-01-14 00:12:58 +0000750 // Keep track of whether we are able to remove all the uses of the global
751 // other than the store that defines it.
752 bool AllNonStoreUsesGone = true;
753
Chris Lattner708148e2004-10-10 23:14:11 +0000754 // Replace all uses of loads with uses of uses of the stored value.
Chris Lattner92c6bd22009-01-14 00:12:58 +0000755 for (Value::use_iterator GUI = GV->use_begin(), E = GV->use_end(); GUI != E;){
756 User *GlobalUser = *GUI++;
757 if (LoadInst *LI = dyn_cast<LoadInst>(GlobalUser)) {
Owen Anderson14ce9ef2009-07-06 01:34:54 +0000758 Changed |= OptimizeAwayTrappingUsesOfValue(LI, LV, Context);
Chris Lattner92c6bd22009-01-14 00:12:58 +0000759 // If we were able to delete all uses of the loads
760 if (LI->use_empty()) {
761 LI->eraseFromParent();
762 Changed = true;
763 } else {
764 AllNonStoreUsesGone = false;
765 }
766 } else if (isa<StoreInst>(GlobalUser)) {
767 // Ignore the store that stores "LV" to the global.
768 assert(GlobalUser->getOperand(1) == GV &&
769 "Must be storing *to* the global");
Chris Lattner708148e2004-10-10 23:14:11 +0000770 } else {
Chris Lattner92c6bd22009-01-14 00:12:58 +0000771 AllNonStoreUsesGone = false;
772
773 // If we get here we could have other crazy uses that are transitively
774 // loaded.
775 assert((isa<PHINode>(GlobalUser) || isa<SelectInst>(GlobalUser) ||
776 isa<ConstantExpr>(GlobalUser)) && "Only expect load and stores!");
Chris Lattner708148e2004-10-10 23:14:11 +0000777 }
Chris Lattner92c6bd22009-01-14 00:12:58 +0000778 }
Chris Lattner708148e2004-10-10 23:14:11 +0000779
780 if (Changed) {
Bill Wendling0a81aac2006-11-26 10:02:32 +0000781 DOUT << "OPTIMIZED LOADS FROM STORED ONCE POINTER: " << *GV;
Chris Lattner708148e2004-10-10 23:14:11 +0000782 ++NumGlobUses;
783 }
784
Chris Lattner708148e2004-10-10 23:14:11 +0000785 // If we nuked all of the loads, then none of the stores are needed either,
786 // nor is the global.
Chris Lattner92c6bd22009-01-14 00:12:58 +0000787 if (AllNonStoreUsesGone) {
Bill Wendling0a81aac2006-11-26 10:02:32 +0000788 DOUT << " *** GLOBAL NOW DEAD!\n";
Owen Anderson50895512009-07-06 18:42:36 +0000789 CleanupConstantGlobalUsers(GV, 0, Context);
Chris Lattner708148e2004-10-10 23:14:11 +0000790 if (GV->use_empty()) {
Chris Lattner7a7ed022004-10-16 18:09:00 +0000791 GV->eraseFromParent();
Chris Lattner708148e2004-10-10 23:14:11 +0000792 ++NumDeleted;
793 }
794 Changed = true;
795 }
796 return Changed;
797}
798
Chris Lattner30ba5692004-10-11 05:54:41 +0000799/// ConstantPropUsersOf - Walk the use list of V, constant folding all of the
800/// instructions that are foldable.
Owen Andersone922c022009-07-22 00:24:57 +0000801static void ConstantPropUsersOf(Value *V, LLVMContext &Context) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000802 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; )
803 if (Instruction *I = dyn_cast<Instruction>(*UI++))
Owen Anderson50895512009-07-06 18:42:36 +0000804 if (Constant *NewC = ConstantFoldInstruction(I, Context)) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000805 I->replaceAllUsesWith(NewC);
806
Chris Lattnerd514d822005-02-01 01:23:31 +0000807 // Advance UI to the next non-I use to avoid invalidating it!
808 // Instructions could multiply use V.
809 while (UI != E && *UI == I)
Chris Lattner30ba5692004-10-11 05:54:41 +0000810 ++UI;
Chris Lattnerd514d822005-02-01 01:23:31 +0000811 I->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +0000812 }
813}
814
815/// OptimizeGlobalAddressOfMalloc - This function takes the specified global
816/// variable, and transforms the program as if it always contained the result of
817/// the specified malloc. Because it is always the result of the specified
818/// malloc, there is no reason to actually DO the malloc. Instead, turn the
Chris Lattner6e8fbad2006-11-30 17:32:29 +0000819/// malloc into a global, and any loads of GV as uses of the new global.
Chris Lattner30ba5692004-10-11 05:54:41 +0000820static GlobalVariable *OptimizeGlobalAddressOfMalloc(GlobalVariable *GV,
Owen Anderson14ce9ef2009-07-06 01:34:54 +0000821 MallocInst *MI,
Owen Andersone922c022009-07-22 00:24:57 +0000822 LLVMContext &Context) {
Bill Wendling0a81aac2006-11-26 10:02:32 +0000823 DOUT << "PROMOTING MALLOC GLOBAL: " << *GV << " MALLOC = " << *MI;
Chris Lattner30ba5692004-10-11 05:54:41 +0000824 ConstantInt *NElements = cast<ConstantInt>(MI->getArraySize());
825
Reid Spencerb83eb642006-10-20 07:07:24 +0000826 if (NElements->getZExtValue() != 1) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000827 // If we have an array allocation, transform it to a single element
828 // allocation to make the code below simpler.
Owen Andersondebcb012009-07-29 22:17:13 +0000829 Type *NewTy = ArrayType::get(MI->getAllocatedType(),
Reid Spencerb83eb642006-10-20 07:07:24 +0000830 NElements->getZExtValue());
Chris Lattner30ba5692004-10-11 05:54:41 +0000831 MallocInst *NewMI =
Owen Andersone922c022009-07-22 00:24:57 +0000832 new MallocInst(NewTy, Context.getNullValue(Type::Int32Ty),
Nate Begeman14b05292005-11-05 09:21:28 +0000833 MI->getAlignment(), MI->getName(), MI);
Chris Lattner699d1442007-01-31 19:59:55 +0000834 Value* Indices[2];
Owen Andersone922c022009-07-22 00:24:57 +0000835 Indices[0] = Indices[1] = Context.getNullValue(Type::Int32Ty);
Gabor Greif051a9502008-04-06 20:25:17 +0000836 Value *NewGEP = GetElementPtrInst::Create(NewMI, Indices, Indices + 2,
837 NewMI->getName()+".el0", MI);
Chris Lattner30ba5692004-10-11 05:54:41 +0000838 MI->replaceAllUsesWith(NewGEP);
Chris Lattner7a7ed022004-10-16 18:09:00 +0000839 MI->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +0000840 MI = NewMI;
841 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000842
Chris Lattner7a7ed022004-10-16 18:09:00 +0000843 // Create the new global variable. The contents of the malloc'd memory is
844 // undefined, so initialize with an undef value.
Chris Lattner998182b2008-04-26 07:40:11 +0000845 // FIXME: This new global should have the alignment returned by malloc. Code
846 // could depend on malloc returning large alignment (on the mac, 16 bytes) but
847 // this would only guarantee some lower alignment.
Owen Andersone922c022009-07-22 00:24:57 +0000848 Constant *Init = Context.getUndef(MI->getAllocatedType());
Owen Andersone9b11b42009-07-08 19:03:57 +0000849 GlobalVariable *NewGV = new GlobalVariable(*GV->getParent(),
850 MI->getAllocatedType(), false,
851 GlobalValue::InternalLinkage, Init,
852 GV->getName()+".body",
853 GV,
854 GV->isThreadLocal());
855
Chris Lattner30ba5692004-10-11 05:54:41 +0000856 // Anything that used the malloc now uses the global directly.
857 MI->replaceAllUsesWith(NewGV);
Chris Lattner30ba5692004-10-11 05:54:41 +0000858
859 Constant *RepValue = NewGV;
860 if (NewGV->getType() != GV->getType()->getElementType())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000861 RepValue = ConstantExpr::getBitCast(RepValue,
Reid Spencerd977d862006-12-12 23:36:14 +0000862 GV->getType()->getElementType());
Chris Lattner30ba5692004-10-11 05:54:41 +0000863
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000864 // If there is a comparison against null, we will insert a global bool to
865 // keep track of whether the global was initialized yet or not.
Misha Brukmanfd939082005-04-21 23:48:37 +0000866 GlobalVariable *InitBool =
Owen Andersone922c022009-07-22 00:24:57 +0000867 new GlobalVariable(Context, Type::Int1Ty, false,
Owen Anderson3d29df32009-07-08 01:26:06 +0000868 GlobalValue::InternalLinkage,
Owen Andersone922c022009-07-22 00:24:57 +0000869 Context.getFalse(), GV->getName()+".init",
Owen Andersone9b11b42009-07-08 19:03:57 +0000870 GV->isThreadLocal());
Chris Lattnerbc965b92004-12-02 06:25:58 +0000871 bool InitBoolUsed = false;
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000872
Chris Lattner30ba5692004-10-11 05:54:41 +0000873 // Loop over all uses of GV, processing them in turn.
Chris Lattnerbc965b92004-12-02 06:25:58 +0000874 std::vector<StoreInst*> Stores;
Chris Lattner30ba5692004-10-11 05:54:41 +0000875 while (!GV->use_empty())
876 if (LoadInst *LI = dyn_cast<LoadInst>(GV->use_back())) {
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000877 while (!LI->use_empty()) {
Chris Lattnerd514d822005-02-01 01:23:31 +0000878 Use &LoadUse = LI->use_begin().getUse();
Reid Spencere4d87aa2006-12-23 06:05:41 +0000879 if (!isa<ICmpInst>(LoadUse.getUser()))
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000880 LoadUse = RepValue;
881 else {
Reid Spencere4d87aa2006-12-23 06:05:41 +0000882 ICmpInst *CI = cast<ICmpInst>(LoadUse.getUser());
883 // Replace the cmp X, 0 with a use of the bool value.
884 Value *LV = new LoadInst(InitBool, InitBool->getName()+".val", CI);
Chris Lattnerbc965b92004-12-02 06:25:58 +0000885 InitBoolUsed = true;
Reid Spencere4d87aa2006-12-23 06:05:41 +0000886 switch (CI->getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000887 default: llvm_unreachable("Unknown ICmp Predicate!");
Reid Spencere4d87aa2006-12-23 06:05:41 +0000888 case ICmpInst::ICMP_ULT:
889 case ICmpInst::ICMP_SLT:
Owen Andersone922c022009-07-22 00:24:57 +0000890 LV = Context.getFalse(); // X < null -> always false
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000891 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +0000892 case ICmpInst::ICMP_ULE:
893 case ICmpInst::ICMP_SLE:
894 case ICmpInst::ICMP_EQ:
Owen Andersone922c022009-07-22 00:24:57 +0000895 LV = BinaryOperator::CreateNot(Context, LV, "notinit", CI);
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000896 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +0000897 case ICmpInst::ICMP_NE:
898 case ICmpInst::ICMP_UGE:
899 case ICmpInst::ICMP_SGE:
900 case ICmpInst::ICMP_UGT:
901 case ICmpInst::ICMP_SGT:
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000902 break; // no change.
903 }
Reid Spencere4d87aa2006-12-23 06:05:41 +0000904 CI->replaceAllUsesWith(LV);
905 CI->eraseFromParent();
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000906 }
907 }
Chris Lattner7a7ed022004-10-16 18:09:00 +0000908 LI->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +0000909 } else {
910 StoreInst *SI = cast<StoreInst>(GV->use_back());
Chris Lattnerbc965b92004-12-02 06:25:58 +0000911 // The global is initialized when the store to it occurs.
Owen Andersone922c022009-07-22 00:24:57 +0000912 new StoreInst(Context.getTrue(), InitBool, SI);
Chris Lattner7a7ed022004-10-16 18:09:00 +0000913 SI->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +0000914 }
915
Chris Lattnerbc965b92004-12-02 06:25:58 +0000916 // If the initialization boolean was used, insert it, otherwise delete it.
917 if (!InitBoolUsed) {
918 while (!InitBool->use_empty()) // Delete initializations
919 cast<Instruction>(InitBool->use_back())->eraseFromParent();
920 delete InitBool;
921 } else
922 GV->getParent()->getGlobalList().insert(GV, InitBool);
923
924
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000925 // Now the GV is dead, nuke it and the malloc.
Chris Lattner7a7ed022004-10-16 18:09:00 +0000926 GV->eraseFromParent();
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000927 MI->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +0000928
929 // To further other optimizations, loop over all users of NewGV and try to
930 // constant prop them. This will promote GEP instructions with constant
931 // indices into GEP constant-exprs, which will allow global-opt to hack on it.
Owen Anderson50895512009-07-06 18:42:36 +0000932 ConstantPropUsersOf(NewGV, Context);
Chris Lattner30ba5692004-10-11 05:54:41 +0000933 if (RepValue != NewGV)
Owen Anderson50895512009-07-06 18:42:36 +0000934 ConstantPropUsersOf(RepValue, Context);
Chris Lattner30ba5692004-10-11 05:54:41 +0000935
936 return NewGV;
937}
Chris Lattner708148e2004-10-10 23:14:11 +0000938
Chris Lattnerfa07e4f2004-12-02 07:11:07 +0000939/// ValueIsOnlyUsedLocallyOrStoredToOneGlobal - Scan the use-list of V checking
940/// to make sure that there are no complex uses of V. We permit simple things
941/// like dereferencing the pointer, but not storing through the address, unless
942/// it is to the specified global.
943static bool ValueIsOnlyUsedLocallyOrStoredToOneGlobal(Instruction *V,
Chris Lattnerc451f9c2007-09-13 16:37:20 +0000944 GlobalVariable *GV,
945 SmallPtrSet<PHINode*, 8> &PHIs) {
Chris Lattner49b6d4a2008-12-15 21:08:54 +0000946 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;++UI){
Jay Foad0906b1b2009-06-06 17:49:35 +0000947 Instruction *Inst = cast<Instruction>(*UI);
Chris Lattner49b6d4a2008-12-15 21:08:54 +0000948
949 if (isa<LoadInst>(Inst) || isa<CmpInst>(Inst)) {
950 continue; // Fine, ignore.
951 }
952
953 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
Chris Lattnerfa07e4f2004-12-02 07:11:07 +0000954 if (SI->getOperand(0) == V && SI->getOperand(1) != GV)
955 return false; // Storing the pointer itself... bad.
Chris Lattner49b6d4a2008-12-15 21:08:54 +0000956 continue; // Otherwise, storing through it, or storing into GV... fine.
957 }
958
959 if (isa<GetElementPtrInst>(Inst)) {
960 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(Inst, GV, PHIs))
Chris Lattnerfa07e4f2004-12-02 07:11:07 +0000961 return false;
Chris Lattner49b6d4a2008-12-15 21:08:54 +0000962 continue;
963 }
964
965 if (PHINode *PN = dyn_cast<PHINode>(Inst)) {
Chris Lattnerc451f9c2007-09-13 16:37:20 +0000966 // PHIs are ok if all uses are ok. Don't infinitely recurse through PHI
967 // cycles.
968 if (PHIs.insert(PN))
Chris Lattner5e6e4942007-09-14 03:41:21 +0000969 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(PN, GV, PHIs))
970 return false;
Chris Lattner49b6d4a2008-12-15 21:08:54 +0000971 continue;
Chris Lattnerfa07e4f2004-12-02 07:11:07 +0000972 }
Chris Lattner49b6d4a2008-12-15 21:08:54 +0000973
974 if (BitCastInst *BCI = dyn_cast<BitCastInst>(Inst)) {
975 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(BCI, GV, PHIs))
976 return false;
977 continue;
978 }
979
980 return false;
981 }
Chris Lattnerfa07e4f2004-12-02 07:11:07 +0000982 return true;
Chris Lattnerfa07e4f2004-12-02 07:11:07 +0000983}
984
Chris Lattner86395032006-09-30 23:32:09 +0000985/// ReplaceUsesOfMallocWithGlobal - The Alloc pointer is stored into GV
986/// somewhere. Transform all uses of the allocation into loads from the
987/// global and uses of the resultant pointer. Further, delete the store into
988/// GV. This assumes that these value pass the
989/// 'ValueIsOnlyUsedLocallyOrStoredToOneGlobal' predicate.
990static void ReplaceUsesOfMallocWithGlobal(Instruction *Alloc,
991 GlobalVariable *GV) {
992 while (!Alloc->use_empty()) {
Chris Lattnera637a8b2007-09-13 18:00:31 +0000993 Instruction *U = cast<Instruction>(*Alloc->use_begin());
994 Instruction *InsertPt = U;
Chris Lattner86395032006-09-30 23:32:09 +0000995 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
996 // If this is the store of the allocation into the global, remove it.
997 if (SI->getOperand(1) == GV) {
998 SI->eraseFromParent();
999 continue;
1000 }
Chris Lattnera637a8b2007-09-13 18:00:31 +00001001 } else if (PHINode *PN = dyn_cast<PHINode>(U)) {
1002 // Insert the load in the corresponding predecessor, not right before the
1003 // PHI.
Gabor Greifa36791d2009-01-23 19:40:15 +00001004 InsertPt = PN->getIncomingBlock(Alloc->use_begin())->getTerminator();
Chris Lattner101f44e2008-12-15 21:44:34 +00001005 } else if (isa<BitCastInst>(U)) {
1006 // Must be bitcast between the malloc and store to initialize the global.
1007 ReplaceUsesOfMallocWithGlobal(U, GV);
1008 U->eraseFromParent();
1009 continue;
1010 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
1011 // If this is a "GEP bitcast" and the user is a store to the global, then
1012 // just process it as a bitcast.
1013 if (GEPI->hasAllZeroIndices() && GEPI->hasOneUse())
1014 if (StoreInst *SI = dyn_cast<StoreInst>(GEPI->use_back()))
1015 if (SI->getOperand(1) == GV) {
1016 // Must be bitcast GEP between the malloc and store to initialize
1017 // the global.
1018 ReplaceUsesOfMallocWithGlobal(GEPI, GV);
1019 GEPI->eraseFromParent();
1020 continue;
1021 }
Chris Lattner86395032006-09-30 23:32:09 +00001022 }
Chris Lattner101f44e2008-12-15 21:44:34 +00001023
Chris Lattner86395032006-09-30 23:32:09 +00001024 // Insert a load from the global, and use it instead of the malloc.
Chris Lattnera637a8b2007-09-13 18:00:31 +00001025 Value *NL = new LoadInst(GV, GV->getName()+".val", InsertPt);
Chris Lattner86395032006-09-30 23:32:09 +00001026 U->replaceUsesOfWith(Alloc, NL);
1027 }
1028}
1029
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001030/// LoadUsesSimpleEnoughForHeapSRA - Verify that all uses of V (a load, or a phi
1031/// of a load) are simple enough to perform heap SRA on. This permits GEP's
1032/// that index through the array and struct field, icmps of null, and PHIs.
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001033static bool LoadUsesSimpleEnoughForHeapSRA(Value *V,
Evan Cheng5d163962009-06-02 00:56:07 +00001034 SmallPtrSet<PHINode*, 32> &LoadUsingPHIs,
1035 SmallPtrSet<PHINode*, 32> &LoadUsingPHIsPerLoad) {
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001036 // We permit two users of the load: setcc comparing against the null
1037 // pointer, and a getelementptr of a specific form.
1038 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;++UI){
1039 Instruction *User = cast<Instruction>(*UI);
1040
1041 // Comparison against null is ok.
1042 if (ICmpInst *ICI = dyn_cast<ICmpInst>(User)) {
1043 if (!isa<ConstantPointerNull>(ICI->getOperand(1)))
1044 return false;
1045 continue;
1046 }
1047
1048 // getelementptr is also ok, but only a simple form.
1049 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
1050 // Must index into the array and into the struct.
1051 if (GEPI->getNumOperands() < 3)
1052 return false;
1053
1054 // Otherwise the GEP is ok.
1055 continue;
1056 }
1057
1058 if (PHINode *PN = dyn_cast<PHINode>(User)) {
Evan Cheng5d163962009-06-02 00:56:07 +00001059 if (!LoadUsingPHIsPerLoad.insert(PN))
1060 // This means some phi nodes are dependent on each other.
1061 // Avoid infinite looping!
1062 return false;
1063 if (!LoadUsingPHIs.insert(PN))
1064 // If we have already analyzed this PHI, then it is safe.
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001065 continue;
1066
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001067 // Make sure all uses of the PHI are simple enough to transform.
Evan Cheng5d163962009-06-02 00:56:07 +00001068 if (!LoadUsesSimpleEnoughForHeapSRA(PN,
1069 LoadUsingPHIs, LoadUsingPHIsPerLoad))
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001070 return false;
1071
1072 continue;
Chris Lattner86395032006-09-30 23:32:09 +00001073 }
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001074
1075 // Otherwise we don't know what this is, not ok.
1076 return false;
1077 }
1078
1079 return true;
1080}
1081
1082
1083/// AllGlobalLoadUsesSimpleEnoughForHeapSRA - If all users of values loaded from
1084/// GV are simple enough to perform HeapSRA, return true.
1085static bool AllGlobalLoadUsesSimpleEnoughForHeapSRA(GlobalVariable *GV,
1086 MallocInst *MI) {
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001087 SmallPtrSet<PHINode*, 32> LoadUsingPHIs;
Evan Cheng5d163962009-06-02 00:56:07 +00001088 SmallPtrSet<PHINode*, 32> LoadUsingPHIsPerLoad;
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001089 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI != E;
1090 ++UI)
Evan Cheng5d163962009-06-02 00:56:07 +00001091 if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
1092 if (!LoadUsesSimpleEnoughForHeapSRA(LI, LoadUsingPHIs,
1093 LoadUsingPHIsPerLoad))
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001094 return false;
Evan Cheng5d163962009-06-02 00:56:07 +00001095 LoadUsingPHIsPerLoad.clear();
1096 }
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001097
1098 // If we reach here, we know that all uses of the loads and transitive uses
1099 // (through PHI nodes) are simple enough to transform. However, we don't know
1100 // that all inputs the to the PHI nodes are in the same equivalence sets.
1101 // Check to verify that all operands of the PHIs are either PHIS that can be
1102 // transformed, loads from GV, or MI itself.
1103 for (SmallPtrSet<PHINode*, 32>::iterator I = LoadUsingPHIs.begin(),
1104 E = LoadUsingPHIs.end(); I != E; ++I) {
1105 PHINode *PN = *I;
1106 for (unsigned op = 0, e = PN->getNumIncomingValues(); op != e; ++op) {
1107 Value *InVal = PN->getIncomingValue(op);
1108
1109 // PHI of the stored value itself is ok.
1110 if (InVal == MI) continue;
1111
1112 if (PHINode *InPN = dyn_cast<PHINode>(InVal)) {
1113 // One of the PHIs in our set is (optimistically) ok.
1114 if (LoadUsingPHIs.count(InPN))
1115 continue;
1116 return false;
1117 }
1118
1119 // Load from GV is ok.
1120 if (LoadInst *LI = dyn_cast<LoadInst>(InVal))
1121 if (LI->getOperand(0) == GV)
1122 continue;
1123
1124 // UNDEF? NULL?
1125
1126 // Anything else is rejected.
1127 return false;
1128 }
1129 }
1130
Chris Lattner86395032006-09-30 23:32:09 +00001131 return true;
1132}
1133
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001134static Value *GetHeapSROAValue(Value *V, unsigned FieldNo,
1135 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001136 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite,
Owen Andersone922c022009-07-22 00:24:57 +00001137 LLVMContext &Context) {
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001138 std::vector<Value*> &FieldVals = InsertedScalarizedValues[V];
1139
1140 if (FieldNo >= FieldVals.size())
1141 FieldVals.resize(FieldNo+1);
1142
1143 // If we already have this value, just reuse the previously scalarized
1144 // version.
1145 if (Value *FieldVal = FieldVals[FieldNo])
1146 return FieldVal;
1147
1148 // Depending on what instruction this is, we have several cases.
1149 Value *Result;
1150 if (LoadInst *LI = dyn_cast<LoadInst>(V)) {
1151 // This is a scalarized version of the load from the global. Just create
1152 // a new Load of the scalarized global.
1153 Result = new LoadInst(GetHeapSROAValue(LI->getOperand(0), FieldNo,
1154 InsertedScalarizedValues,
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001155 PHIsToRewrite, Context),
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001156 LI->getName()+".f" + utostr(FieldNo), LI);
1157 } else if (PHINode *PN = dyn_cast<PHINode>(V)) {
1158 // PN's type is pointer to struct. Make a new PHI of pointer to struct
1159 // field.
1160 const StructType *ST =
1161 cast<StructType>(cast<PointerType>(PN->getType())->getElementType());
1162
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001163 Result =
Owen Andersondebcb012009-07-29 22:17:13 +00001164 PHINode::Create(PointerType::getUnqual(ST->getElementType(FieldNo)),
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001165 PN->getName()+".f"+utostr(FieldNo), PN);
1166 PHIsToRewrite.push_back(std::make_pair(PN, FieldNo));
1167 } else {
Torok Edwinc23197a2009-07-14 16:55:14 +00001168 llvm_unreachable("Unknown usable value");
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001169 Result = 0;
1170 }
1171
1172 return FieldVals[FieldNo] = Result;
Chris Lattnera637a8b2007-09-13 18:00:31 +00001173}
1174
Chris Lattner330245e2007-09-13 17:29:05 +00001175/// RewriteHeapSROALoadUser - Given a load instruction and a value derived from
1176/// the load, rewrite the derived value to use the HeapSRoA'd load.
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001177static void RewriteHeapSROALoadUser(Instruction *LoadUser,
1178 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001179 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite,
Owen Andersone922c022009-07-22 00:24:57 +00001180 LLVMContext &Context) {
Chris Lattner330245e2007-09-13 17:29:05 +00001181 // If this is a comparison against null, handle it.
1182 if (ICmpInst *SCI = dyn_cast<ICmpInst>(LoadUser)) {
1183 assert(isa<ConstantPointerNull>(SCI->getOperand(1)));
1184 // If we have a setcc of the loaded pointer, we can use a setcc of any
1185 // field.
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001186 Value *NPtr = GetHeapSROAValue(SCI->getOperand(0), 0,
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001187 InsertedScalarizedValues, PHIsToRewrite,
1188 Context);
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 Andersone922c022009-07-22 00:24:57 +00001191 Context.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,
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001206 InsertedScalarizedValues, PHIsToRewrite,
1207 Context);
Chris Lattnera637a8b2007-09-13 18:00:31 +00001208
1209 // Create the new GEP idx vector.
1210 SmallVector<Value*, 8> GEPIdx;
1211 GEPIdx.push_back(GEPI->getOperand(1));
1212 GEPIdx.append(GEPI->op_begin()+3, GEPI->op_end());
1213
Gabor Greifb1dbcd82008-05-15 10:04:30 +00001214 Value *NGEPI = GetElementPtrInst::Create(NewPtr,
1215 GEPIdx.begin(), GEPIdx.end(),
Gabor Greif051a9502008-04-06 20:25:17 +00001216 GEPI->getName(), GEPI);
Chris Lattnera637a8b2007-09-13 18:00:31 +00001217 GEPI->replaceAllUsesWith(NGEPI);
1218 GEPI->eraseFromParent();
1219 return;
1220 }
Chris Lattner309f20f2007-09-13 21:31:36 +00001221
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001222 // Recursively transform the users of PHI nodes. This will lazily create the
1223 // PHIs that are needed for individual elements. Keep track of what PHIs we
1224 // see in InsertedScalarizedValues so that we don't get infinite loops (very
1225 // antisocial). If the PHI is already in InsertedScalarizedValues, it has
1226 // already been seen first by another load, so its uses have already been
1227 // processed.
1228 PHINode *PN = cast<PHINode>(LoadUser);
1229 bool Inserted;
1230 DenseMap<Value*, std::vector<Value*> >::iterator InsertPos;
1231 tie(InsertPos, Inserted) =
1232 InsertedScalarizedValues.insert(std::make_pair(PN, std::vector<Value*>()));
1233 if (!Inserted) return;
Chris Lattner309f20f2007-09-13 21:31:36 +00001234
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001235 // If this is the first time we've seen this PHI, recursively process all
1236 // users.
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001237 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end(); UI != E; ) {
1238 Instruction *User = cast<Instruction>(*UI++);
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001239 RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite,
1240 Context);
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001241 }
Chris Lattner330245e2007-09-13 17:29:05 +00001242}
1243
Chris Lattner86395032006-09-30 23:32:09 +00001244/// RewriteUsesOfLoadForHeapSRoA - We are performing Heap SRoA on a global. Ptr
1245/// is a value loaded from the global. Eliminate all uses of Ptr, making them
1246/// use FieldGlobals instead. All uses of loaded values satisfy
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001247/// AllGlobalLoadUsesSimpleEnoughForHeapSRA.
Chris Lattner330245e2007-09-13 17:29:05 +00001248static void RewriteUsesOfLoadForHeapSRoA(LoadInst *Load,
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001249 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001250 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite,
Owen Andersone922c022009-07-22 00:24:57 +00001251 LLVMContext &Context) {
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001252 for (Value::use_iterator UI = Load->use_begin(), E = Load->use_end();
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001253 UI != E; ) {
1254 Instruction *User = cast<Instruction>(*UI++);
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001255 RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite,
1256 Context);
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001257 }
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001258
1259 if (Load->use_empty()) {
1260 Load->eraseFromParent();
1261 InsertedScalarizedValues.erase(Load);
1262 }
Chris Lattner86395032006-09-30 23:32:09 +00001263}
1264
1265/// PerformHeapAllocSRoA - MI is an allocation of an array of structures. Break
1266/// it up into multiple allocations of arrays of the fields.
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001267static GlobalVariable *PerformHeapAllocSRoA(GlobalVariable *GV, MallocInst *MI,
Owen Andersone922c022009-07-22 00:24:57 +00001268 LLVMContext &Context){
Bill Wendling0a81aac2006-11-26 10:02:32 +00001269 DOUT << "SROA HEAP ALLOC: " << *GV << " MALLOC = " << *MI;
Chris Lattner86395032006-09-30 23:32:09 +00001270 const StructType *STy = cast<StructType>(MI->getAllocatedType());
1271
1272 // There is guaranteed to be at least one use of the malloc (storing
1273 // it into GV). If there are other uses, change them to be uses of
1274 // the global to simplify later code. This also deletes the store
1275 // into GV.
1276 ReplaceUsesOfMallocWithGlobal(MI, GV);
1277
1278 // Okay, at this point, there are no users of the malloc. Insert N
1279 // new mallocs at the same place as MI, and N globals.
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001280 std::vector<Value*> FieldGlobals;
Chris Lattner86395032006-09-30 23:32:09 +00001281 std::vector<MallocInst*> FieldMallocs;
1282
1283 for (unsigned FieldNo = 0, e = STy->getNumElements(); FieldNo != e;++FieldNo){
1284 const Type *FieldTy = STy->getElementType(FieldNo);
Owen Andersondebcb012009-07-29 22:17:13 +00001285 const Type *PFieldTy = PointerType::getUnqual(FieldTy);
Chris Lattner86395032006-09-30 23:32:09 +00001286
1287 GlobalVariable *NGV =
Owen Andersone9b11b42009-07-08 19:03:57 +00001288 new GlobalVariable(*GV->getParent(),
1289 PFieldTy, false, GlobalValue::InternalLinkage,
Owen Andersone922c022009-07-22 00:24:57 +00001290 Context.getNullValue(PFieldTy),
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +00001291 GV->getName() + ".f" + utostr(FieldNo), GV,
1292 GV->isThreadLocal());
Chris Lattner86395032006-09-30 23:32:09 +00001293 FieldGlobals.push_back(NGV);
1294
Owen Anderson50dead02009-07-15 23:53:25 +00001295 MallocInst *NMI = new MallocInst(FieldTy, MI->getArraySize(),
Chris Lattner86395032006-09-30 23:32:09 +00001296 MI->getName() + ".f" + utostr(FieldNo),MI);
1297 FieldMallocs.push_back(NMI);
1298 new StoreInst(NMI, NGV, MI);
1299 }
1300
1301 // The tricky aspect of this transformation is handling the case when malloc
1302 // fails. In the original code, malloc failing would set the result pointer
1303 // of malloc to null. In this case, some mallocs could succeed and others
1304 // could fail. As such, we emit code that looks like this:
1305 // F0 = malloc(field0)
1306 // F1 = malloc(field1)
1307 // F2 = malloc(field2)
1308 // if (F0 == 0 || F1 == 0 || F2 == 0) {
1309 // if (F0) { free(F0); F0 = 0; }
1310 // if (F1) { free(F1); F1 = 0; }
1311 // if (F2) { free(F2); F2 = 0; }
1312 // }
1313 Value *RunningOr = 0;
1314 for (unsigned i = 0, e = FieldMallocs.size(); i != e; ++i) {
Owen Anderson333c4002009-07-09 23:48:35 +00001315 Value *Cond = new ICmpInst(MI, ICmpInst::ICMP_EQ, FieldMallocs[i],
Owen Andersone922c022009-07-22 00:24:57 +00001316 Context.getNullValue(FieldMallocs[i]->getType()),
Owen Anderson333c4002009-07-09 23:48:35 +00001317 "isnull");
Chris Lattner86395032006-09-30 23:32:09 +00001318 if (!RunningOr)
1319 RunningOr = Cond; // First seteq
1320 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001321 RunningOr = BinaryOperator::CreateOr(RunningOr, Cond, "tmp", MI);
Chris Lattner86395032006-09-30 23:32:09 +00001322 }
1323
1324 // Split the basic block at the old malloc.
1325 BasicBlock *OrigBB = MI->getParent();
1326 BasicBlock *ContBB = OrigBB->splitBasicBlock(MI, "malloc_cont");
1327
1328 // Create the block to check the first condition. Put all these blocks at the
1329 // end of the function as they are unlikely to be executed.
Gabor Greif051a9502008-04-06 20:25:17 +00001330 BasicBlock *NullPtrBlock = BasicBlock::Create("malloc_ret_null",
1331 OrigBB->getParent());
Chris Lattner86395032006-09-30 23:32:09 +00001332
1333 // Remove the uncond branch from OrigBB to ContBB, turning it into a cond
1334 // branch on RunningOr.
1335 OrigBB->getTerminator()->eraseFromParent();
Gabor Greif051a9502008-04-06 20:25:17 +00001336 BranchInst::Create(NullPtrBlock, ContBB, RunningOr, OrigBB);
Chris Lattner86395032006-09-30 23:32:09 +00001337
1338 // Within the NullPtrBlock, we need to emit a comparison and branch for each
1339 // pointer, because some may be null while others are not.
1340 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
1341 Value *GVVal = new LoadInst(FieldGlobals[i], "tmp", NullPtrBlock);
Owen Anderson333c4002009-07-09 23:48:35 +00001342 Value *Cmp = new ICmpInst(*NullPtrBlock, ICmpInst::ICMP_NE, GVVal,
Owen Andersone922c022009-07-22 00:24:57 +00001343 Context.getNullValue(GVVal->getType()),
Owen Anderson333c4002009-07-09 23:48:35 +00001344 "tmp");
Gabor Greif051a9502008-04-06 20:25:17 +00001345 BasicBlock *FreeBlock = BasicBlock::Create("free_it", OrigBB->getParent());
1346 BasicBlock *NextBlock = BasicBlock::Create("next", OrigBB->getParent());
1347 BranchInst::Create(FreeBlock, NextBlock, Cmp, NullPtrBlock);
Chris Lattner86395032006-09-30 23:32:09 +00001348
1349 // Fill in FreeBlock.
1350 new FreeInst(GVVal, FreeBlock);
Owen Andersone922c022009-07-22 00:24:57 +00001351 new StoreInst(Context.getNullValue(GVVal->getType()), FieldGlobals[i],
Chris Lattner86395032006-09-30 23:32:09 +00001352 FreeBlock);
Gabor Greif051a9502008-04-06 20:25:17 +00001353 BranchInst::Create(NextBlock, FreeBlock);
Chris Lattner86395032006-09-30 23:32:09 +00001354
1355 NullPtrBlock = NextBlock;
1356 }
1357
Gabor Greif051a9502008-04-06 20:25:17 +00001358 BranchInst::Create(ContBB, NullPtrBlock);
Chris Lattner86395032006-09-30 23:32:09 +00001359
1360 // MI is no longer needed, remove it.
1361 MI->eraseFromParent();
1362
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001363 /// InsertedScalarizedLoads - As we process loads, if we can't immediately
1364 /// update all uses of the load, keep track of what scalarized loads are
1365 /// inserted for a given load.
1366 DenseMap<Value*, std::vector<Value*> > InsertedScalarizedValues;
1367 InsertedScalarizedValues[GV] = FieldGlobals;
1368
1369 std::vector<std::pair<PHINode*, unsigned> > PHIsToRewrite;
Chris Lattner86395032006-09-30 23:32:09 +00001370
1371 // Okay, the malloc site is completely handled. All of the uses of GV are now
1372 // loads, and all uses of those loads are simple. Rewrite them to use loads
1373 // of the per-field globals instead.
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001374 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI != E;) {
1375 Instruction *User = cast<Instruction>(*UI++);
1376
1377 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001378 RewriteUsesOfLoadForHeapSRoA(LI, InsertedScalarizedValues, PHIsToRewrite,
1379 Context);
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001380 continue;
Chris Lattner39ff1e22007-01-09 23:29:37 +00001381 }
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001382
1383 // Must be a store of null.
1384 StoreInst *SI = cast<StoreInst>(User);
1385 assert(isa<ConstantPointerNull>(SI->getOperand(0)) &&
1386 "Unexpected heap-sra user!");
1387
1388 // Insert a store of null into each global.
1389 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
1390 const PointerType *PT = cast<PointerType>(FieldGlobals[i]->getType());
Owen Andersone922c022009-07-22 00:24:57 +00001391 Constant *Null = Context.getNullValue(PT->getElementType());
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001392 new StoreInst(Null, FieldGlobals[i], SI);
1393 }
1394 // Erase the original store.
1395 SI->eraseFromParent();
Chris Lattner86395032006-09-30 23:32:09 +00001396 }
1397
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001398 // While we have PHIs that are interesting to rewrite, do it.
1399 while (!PHIsToRewrite.empty()) {
1400 PHINode *PN = PHIsToRewrite.back().first;
1401 unsigned FieldNo = PHIsToRewrite.back().second;
1402 PHIsToRewrite.pop_back();
1403 PHINode *FieldPN = cast<PHINode>(InsertedScalarizedValues[PN][FieldNo]);
1404 assert(FieldPN->getNumIncomingValues() == 0 &&"Already processed this phi");
1405
1406 // Add all the incoming values. This can materialize more phis.
1407 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1408 Value *InVal = PN->getIncomingValue(i);
1409 InVal = GetHeapSROAValue(InVal, FieldNo, InsertedScalarizedValues,
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001410 PHIsToRewrite, Context);
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001411 FieldPN->addIncoming(InVal, PN->getIncomingBlock(i));
1412 }
1413 }
1414
1415 // Drop all inter-phi links and any loads that made it this far.
1416 for (DenseMap<Value*, std::vector<Value*> >::iterator
1417 I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
1418 I != E; ++I) {
1419 if (PHINode *PN = dyn_cast<PHINode>(I->first))
1420 PN->dropAllReferences();
1421 else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
1422 LI->dropAllReferences();
1423 }
1424
1425 // Delete all the phis and loads now that inter-references are dead.
1426 for (DenseMap<Value*, std::vector<Value*> >::iterator
1427 I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
1428 I != E; ++I) {
1429 if (PHINode *PN = dyn_cast<PHINode>(I->first))
1430 PN->eraseFromParent();
1431 else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
1432 LI->eraseFromParent();
1433 }
1434
Chris Lattner86395032006-09-30 23:32:09 +00001435 // The old global is now dead, remove it.
1436 GV->eraseFromParent();
1437
1438 ++NumHeapSRA;
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001439 return cast<GlobalVariable>(FieldGlobals[0]);
Chris Lattner86395032006-09-30 23:32:09 +00001440}
1441
Chris Lattnere61d0a62008-12-15 21:02:25 +00001442/// TryToOptimizeStoreOfMallocToGlobal - This function is called when we see a
1443/// pointer global variable with a single value stored it that is a malloc or
1444/// cast of malloc.
1445static bool TryToOptimizeStoreOfMallocToGlobal(GlobalVariable *GV,
1446 MallocInst *MI,
1447 Module::global_iterator &GVI,
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001448 TargetData &TD,
Owen Andersone922c022009-07-22 00:24:57 +00001449 LLVMContext &Context) {
Chris Lattnere61d0a62008-12-15 21:02:25 +00001450 // If this is a malloc of an abstract type, don't touch it.
1451 if (!MI->getAllocatedType()->isSized())
1452 return false;
1453
1454 // We can't optimize this global unless all uses of it are *known* to be
1455 // of the malloc value, not of the null initializer value (consider a use
1456 // that compares the global's value against zero to see if the malloc has
1457 // been reached). To do this, we check to see if all uses of the global
1458 // would trap if the global were null: this proves that they must all
1459 // happen after the malloc.
1460 if (!AllUsesOfLoadedValueWillTrapIfNull(GV))
1461 return false;
1462
1463 // We can't optimize this if the malloc itself is used in a complex way,
1464 // for example, being stored into multiple globals. This allows the
1465 // malloc to be stored into the specified global, loaded setcc'd, and
1466 // GEP'd. These are all things we could transform to using the global
1467 // for.
1468 {
1469 SmallPtrSet<PHINode*, 8> PHIs;
1470 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(MI, GV, PHIs))
1471 return false;
1472 }
1473
1474
1475 // If we have a global that is only initialized with a fixed size malloc,
1476 // transform the program to use global memory instead of malloc'd memory.
1477 // This eliminates dynamic allocation, avoids an indirection accessing the
1478 // data, and exposes the resultant global to further GlobalOpt.
1479 if (ConstantInt *NElements = dyn_cast<ConstantInt>(MI->getArraySize())) {
1480 // Restrict this transformation to only working on small allocations
1481 // (2048 bytes currently), as we don't want to introduce a 16M global or
1482 // something.
1483 if (NElements->getZExtValue()*
Duncan Sands777d2302009-05-09 07:06:46 +00001484 TD.getTypeAllocSize(MI->getAllocatedType()) < 2048) {
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001485 GVI = OptimizeGlobalAddressOfMalloc(GV, MI, Context);
Chris Lattnere61d0a62008-12-15 21:02:25 +00001486 return true;
1487 }
1488 }
1489
1490 // If the allocation is an array of structures, consider transforming this
1491 // into multiple malloc'd arrays, one for each field. This is basically
1492 // SRoA for malloc'd memory.
Chris Lattner101f44e2008-12-15 21:44:34 +00001493 const Type *AllocTy = MI->getAllocatedType();
1494
1495 // If this is an allocation of a fixed size array of structs, analyze as a
1496 // variable size array. malloc [100 x struct],1 -> malloc struct, 100
1497 if (!MI->isArrayAllocation())
1498 if (const ArrayType *AT = dyn_cast<ArrayType>(AllocTy))
1499 AllocTy = AT->getElementType();
1500
1501 if (const StructType *AllocSTy = dyn_cast<StructType>(AllocTy)) {
Chris Lattnere61d0a62008-12-15 21:02:25 +00001502 // This the structure has an unreasonable number of fields, leave it
1503 // alone.
Chris Lattner101f44e2008-12-15 21:44:34 +00001504 if (AllocSTy->getNumElements() <= 16 && AllocSTy->getNumElements() != 0 &&
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001505 AllGlobalLoadUsesSimpleEnoughForHeapSRA(GV, MI)) {
Chris Lattner101f44e2008-12-15 21:44:34 +00001506
1507 // If this is a fixed size array, transform the Malloc to be an alloc of
1508 // structs. malloc [100 x struct],1 -> malloc struct, 100
1509 if (const ArrayType *AT = dyn_cast<ArrayType>(MI->getAllocatedType())) {
1510 MallocInst *NewMI =
Owen Anderson50dead02009-07-15 23:53:25 +00001511 new MallocInst(AllocSTy,
Owen Andersoneed707b2009-07-24 23:12:02 +00001512 ConstantInt::get(Type::Int32Ty, AT->getNumElements()),
Chris Lattner101f44e2008-12-15 21:44:34 +00001513 "", MI);
1514 NewMI->takeName(MI);
1515 Value *Cast = new BitCastInst(NewMI, MI->getType(), "tmp", MI);
1516 MI->replaceAllUsesWith(Cast);
1517 MI->eraseFromParent();
1518 MI = NewMI;
1519 }
1520
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001521 GVI = PerformHeapAllocSRoA(GV, MI, Context);
Chris Lattnere61d0a62008-12-15 21:02:25 +00001522 return true;
1523 }
1524 }
1525
1526 return false;
1527}
Chris Lattner86395032006-09-30 23:32:09 +00001528
Chris Lattner9b34a612004-10-09 21:48:45 +00001529// OptimizeOnceStoredGlobal - Try to optimize globals based on the knowledge
1530// that only one value (besides its initializer) is ever stored to the global.
Chris Lattner30ba5692004-10-11 05:54:41 +00001531static bool OptimizeOnceStoredGlobal(GlobalVariable *GV, Value *StoredOnceVal,
Chris Lattner7f8897f2006-08-27 22:42:52 +00001532 Module::global_iterator &GVI,
Owen Andersone922c022009-07-22 00:24:57 +00001533 TargetData &TD, LLVMContext &Context) {
Chris Lattner344b41c2008-12-15 21:20:32 +00001534 // Ignore no-op GEPs and bitcasts.
1535 StoredOnceVal = StoredOnceVal->stripPointerCasts();
Chris Lattner9b34a612004-10-09 21:48:45 +00001536
Chris Lattner708148e2004-10-10 23:14:11 +00001537 // If we are dealing with a pointer global that is initialized to null and
1538 // only has one (non-null) value stored into it, then we can optimize any
1539 // users of the loaded value (often calls and loads) that would trap if the
1540 // value was null.
Chris Lattner9b34a612004-10-09 21:48:45 +00001541 if (isa<PointerType>(GV->getInitializer()->getType()) &&
1542 GV->getInitializer()->isNullValue()) {
Chris Lattner708148e2004-10-10 23:14:11 +00001543 if (Constant *SOVC = dyn_cast<Constant>(StoredOnceVal)) {
1544 if (GV->getInitializer()->getType() != SOVC->getType())
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001545 SOVC =
Owen Andersonbaf3c402009-07-29 18:55:55 +00001546 ConstantExpr::getBitCast(SOVC, GV->getInitializer()->getType());
Misha Brukmanfd939082005-04-21 23:48:37 +00001547
Chris Lattner708148e2004-10-10 23:14:11 +00001548 // Optimize away any trapping uses of the loaded value.
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001549 if (OptimizeAwayTrappingUsesOfLoads(GV, SOVC, Context))
Chris Lattner8be80122004-10-10 17:07:12 +00001550 return true;
Chris Lattner30ba5692004-10-11 05:54:41 +00001551 } else if (MallocInst *MI = dyn_cast<MallocInst>(StoredOnceVal)) {
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001552 if (TryToOptimizeStoreOfMallocToGlobal(GV, MI, GVI, TD, Context))
Chris Lattnere61d0a62008-12-15 21:02:25 +00001553 return true;
Chris Lattner708148e2004-10-10 23:14:11 +00001554 }
Chris Lattner9b34a612004-10-09 21:48:45 +00001555 }
Chris Lattner30ba5692004-10-11 05:54:41 +00001556
Chris Lattner9b34a612004-10-09 21:48:45 +00001557 return false;
1558}
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001559
Chris Lattner58e44f42008-01-14 01:17:44 +00001560/// TryToShrinkGlobalToBoolean - At this point, we have learned that the only
1561/// two values ever stored into GV are its initializer and OtherVal. See if we
1562/// can shrink the global into a boolean and select between the two values
1563/// whenever it is used. This exposes the values to other scalar optimizations.
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001564static bool TryToShrinkGlobalToBoolean(GlobalVariable *GV, Constant *OtherVal,
Owen Andersone922c022009-07-22 00:24:57 +00001565 LLVMContext &Context) {
Chris Lattner58e44f42008-01-14 01:17:44 +00001566 const Type *GVElType = GV->getType()->getElementType();
1567
1568 // If GVElType is already i1, it is already shrunk. If the type of the GV is
Chris Lattner6f6923f2009-03-07 23:32:02 +00001569 // an FP value, pointer or vector, don't do this optimization because a select
1570 // between them is very expensive and unlikely to lead to later
1571 // simplification. In these cases, we typically end up with "cond ? v1 : v2"
1572 // where v1 and v2 both require constant pool loads, a big loss.
Chris Lattner58e44f42008-01-14 01:17:44 +00001573 if (GVElType == Type::Int1Ty || GVElType->isFloatingPoint() ||
Chris Lattner6f6923f2009-03-07 23:32:02 +00001574 isa<PointerType>(GVElType) || isa<VectorType>(GVElType))
Chris Lattner58e44f42008-01-14 01:17:44 +00001575 return false;
1576
1577 // Walk the use list of the global seeing if all the uses are load or store.
1578 // If there is anything else, bail out.
1579 for (Value::use_iterator I = GV->use_begin(), E = GV->use_end(); I != E; ++I)
Devang Patel771281f2009-03-06 01:39:36 +00001580 if (!isa<LoadInst>(I) && !isa<StoreInst>(I))
Chris Lattner58e44f42008-01-14 01:17:44 +00001581 return false;
1582
1583 DOUT << " *** SHRINKING TO BOOL: " << *GV;
1584
Chris Lattner96a86b22004-12-12 05:53:50 +00001585 // Create the new global, initializing it to false.
Owen Andersone922c022009-07-22 00:24:57 +00001586 GlobalVariable *NewGV = new GlobalVariable(Context, Type::Int1Ty, false,
1587 GlobalValue::InternalLinkage, Context.getFalse(),
Nick Lewycky0e670df2009-05-03 03:49:08 +00001588 GV->getName()+".b",
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +00001589 GV->isThreadLocal());
Chris Lattner96a86b22004-12-12 05:53:50 +00001590 GV->getParent()->getGlobalList().insert(GV, NewGV);
1591
1592 Constant *InitVal = GV->getInitializer();
Reid Spencer4fe16d62007-01-11 18:21:29 +00001593 assert(InitVal->getType() != Type::Int1Ty && "No reason to shrink to bool!");
Chris Lattner96a86b22004-12-12 05:53:50 +00001594
1595 // If initialized to zero and storing one into the global, we can use a cast
1596 // instead of a select to synthesize the desired value.
1597 bool IsOneZero = false;
1598 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal))
Reid Spencercae57542007-03-02 00:28:52 +00001599 IsOneZero = InitVal->isNullValue() && CI->isOne();
Chris Lattner96a86b22004-12-12 05:53:50 +00001600
1601 while (!GV->use_empty()) {
Devang Patel771281f2009-03-06 01:39:36 +00001602 Instruction *UI = cast<Instruction>(GV->use_back());
1603 if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
Chris Lattner96a86b22004-12-12 05:53:50 +00001604 // Change the store into a boolean store.
1605 bool StoringOther = SI->getOperand(0) == OtherVal;
1606 // Only do this if we weren't storing a loaded value.
Chris Lattner38c25562004-12-12 19:34:41 +00001607 Value *StoreVal;
Chris Lattner96a86b22004-12-12 05:53:50 +00001608 if (StoringOther || SI->getOperand(0) == InitVal)
Owen Andersoneed707b2009-07-24 23:12:02 +00001609 StoreVal = ConstantInt::get(Type::Int1Ty, StoringOther);
Chris Lattner38c25562004-12-12 19:34:41 +00001610 else {
1611 // Otherwise, we are storing a previously loaded copy. To do this,
1612 // change the copy from copying the original value to just copying the
1613 // bool.
1614 Instruction *StoredVal = cast<Instruction>(SI->getOperand(0));
1615
1616 // If we're already replaced the input, StoredVal will be a cast or
1617 // select instruction. If not, it will be a load of the original
1618 // global.
1619 if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
1620 assert(LI->getOperand(0) == GV && "Not a copy!");
1621 // Insert a new load, to preserve the saved value.
1622 StoreVal = new LoadInst(NewGV, LI->getName()+".b", LI);
1623 } else {
1624 assert((isa<CastInst>(StoredVal) || isa<SelectInst>(StoredVal)) &&
1625 "This is not a form that we understand!");
1626 StoreVal = StoredVal->getOperand(0);
1627 assert(isa<LoadInst>(StoreVal) && "Not a load of NewGV!");
1628 }
1629 }
1630 new StoreInst(StoreVal, NewGV, SI);
Devang Patel771281f2009-03-06 01:39:36 +00001631 } else {
Chris Lattner96a86b22004-12-12 05:53:50 +00001632 // Change the load into a load of bool then a select.
Devang Patel771281f2009-03-06 01:39:36 +00001633 LoadInst *LI = cast<LoadInst>(UI);
Chris Lattner046800a2007-02-11 01:08:35 +00001634 LoadInst *NLI = new LoadInst(NewGV, LI->getName()+".b", LI);
Chris Lattner96a86b22004-12-12 05:53:50 +00001635 Value *NSI;
1636 if (IsOneZero)
Chris Lattner046800a2007-02-11 01:08:35 +00001637 NSI = new ZExtInst(NLI, LI->getType(), "", LI);
Misha Brukmanfd939082005-04-21 23:48:37 +00001638 else
Gabor Greif051a9502008-04-06 20:25:17 +00001639 NSI = SelectInst::Create(NLI, OtherVal, InitVal, "", LI);
Chris Lattner046800a2007-02-11 01:08:35 +00001640 NSI->takeName(LI);
Chris Lattner96a86b22004-12-12 05:53:50 +00001641 LI->replaceAllUsesWith(NSI);
Devang Patel771281f2009-03-06 01:39:36 +00001642 }
1643 UI->eraseFromParent();
Chris Lattner96a86b22004-12-12 05:53:50 +00001644 }
1645
1646 GV->eraseFromParent();
Chris Lattner58e44f42008-01-14 01:17:44 +00001647 return true;
Chris Lattner96a86b22004-12-12 05:53:50 +00001648}
1649
1650
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001651/// ProcessInternalGlobal - Analyze the specified global variable and optimize
1652/// it if possible. If we make a change, return true.
Chris Lattner30ba5692004-10-11 05:54:41 +00001653bool GlobalOpt::ProcessInternalGlobal(GlobalVariable *GV,
Chris Lattnere4d5c442005-03-15 04:54:21 +00001654 Module::global_iterator &GVI) {
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00001655 SmallPtrSet<PHINode*, 16> PHIUsers;
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001656 GlobalStatus GS;
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001657 GV->removeDeadConstantUsers();
1658
1659 if (GV->use_empty()) {
Bill Wendling0a81aac2006-11-26 10:02:32 +00001660 DOUT << "GLOBAL DEAD: " << *GV;
Chris Lattner7a7ed022004-10-16 18:09:00 +00001661 GV->eraseFromParent();
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001662 ++NumDeleted;
1663 return true;
1664 }
1665
1666 if (!AnalyzeGlobal(GV, GS, PHIUsers)) {
Chris Lattnercff16732006-09-30 19:40:30 +00001667#if 0
Bill Wendlinge8156192006-12-07 01:30:32 +00001668 cerr << "Global: " << *GV;
1669 cerr << " isLoaded = " << GS.isLoaded << "\n";
1670 cerr << " StoredType = ";
Chris Lattnercff16732006-09-30 19:40:30 +00001671 switch (GS.StoredType) {
Bill Wendlinge8156192006-12-07 01:30:32 +00001672 case GlobalStatus::NotStored: cerr << "NEVER STORED\n"; break;
1673 case GlobalStatus::isInitializerStored: cerr << "INIT STORED\n"; break;
1674 case GlobalStatus::isStoredOnce: cerr << "STORED ONCE\n"; break;
1675 case GlobalStatus::isStored: cerr << "stored\n"; break;
Chris Lattnercff16732006-09-30 19:40:30 +00001676 }
1677 if (GS.StoredType == GlobalStatus::isStoredOnce && GS.StoredOnceValue)
Bill Wendlinge8156192006-12-07 01:30:32 +00001678 cerr << " StoredOnceValue = " << *GS.StoredOnceValue << "\n";
Chris Lattnercff16732006-09-30 19:40:30 +00001679 if (GS.AccessingFunction && !GS.HasMultipleAccessingFunctions)
Bill Wendlinge8156192006-12-07 01:30:32 +00001680 cerr << " AccessingFunction = " << GS.AccessingFunction->getName()
Chris Lattnercff16732006-09-30 19:40:30 +00001681 << "\n";
Bill Wendlinge8156192006-12-07 01:30:32 +00001682 cerr << " HasMultipleAccessingFunctions = "
Chris Lattnercff16732006-09-30 19:40:30 +00001683 << GS.HasMultipleAccessingFunctions << "\n";
Bill Wendlinge8156192006-12-07 01:30:32 +00001684 cerr << " HasNonInstructionUser = " << GS.HasNonInstructionUser<<"\n";
Bill Wendlinge8156192006-12-07 01:30:32 +00001685 cerr << "\n";
Chris Lattnercff16732006-09-30 19:40:30 +00001686#endif
1687
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +00001688 // If this is a first class global and has only one accessing function
1689 // and this function is main (which we know is not recursive we can make
1690 // this global a local variable) we replace the global with a local alloca
1691 // in this function.
1692 //
Dan Gohman399101a2008-05-23 00:17:26 +00001693 // NOTE: It doesn't make sense to promote non single-value types since we
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +00001694 // are just replacing static memory to stack memory.
Sanjiv Gupta059aa8c2009-06-17 06:47:15 +00001695 //
1696 // If the global is in different address space, don't bring it to stack.
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +00001697 if (!GS.HasMultipleAccessingFunctions &&
Chris Lattner553ca522005-06-15 21:11:48 +00001698 GS.AccessingFunction && !GS.HasNonInstructionUser &&
Dan Gohman399101a2008-05-23 00:17:26 +00001699 GV->getType()->getElementType()->isSingleValueType() &&
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +00001700 GS.AccessingFunction->getName() == "main" &&
Sanjiv Gupta059aa8c2009-06-17 06:47:15 +00001701 GS.AccessingFunction->hasExternalLinkage() &&
1702 GV->getType()->getAddressSpace() == 0) {
Bill Wendling0a81aac2006-11-26 10:02:32 +00001703 DOUT << "LOCALIZING GLOBAL: " << *GV;
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +00001704 Instruction* FirstI = GS.AccessingFunction->getEntryBlock().begin();
1705 const Type* ElemTy = GV->getType()->getElementType();
Nate Begeman14b05292005-11-05 09:21:28 +00001706 // FIXME: Pass Global's alignment when globals have alignment
Owen Anderson50dead02009-07-15 23:53:25 +00001707 AllocaInst* Alloca = new AllocaInst(ElemTy, NULL, GV->getName(), FirstI);
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +00001708 if (!isa<UndefValue>(GV->getInitializer()))
1709 new StoreInst(GV->getInitializer(), Alloca, FirstI);
Misha Brukmanfd939082005-04-21 23:48:37 +00001710
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +00001711 GV->replaceAllUsesWith(Alloca);
1712 GV->eraseFromParent();
1713 ++NumLocalized;
1714 return true;
1715 }
Chris Lattnercff16732006-09-30 19:40:30 +00001716
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001717 // If the global is never loaded (but may be stored to), it is dead.
1718 // Delete it now.
1719 if (!GS.isLoaded) {
Bill Wendling0a81aac2006-11-26 10:02:32 +00001720 DOUT << "GLOBAL NEVER LOADED: " << *GV;
Chris Lattner930f4752004-10-09 03:32:52 +00001721
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001722 // Delete any stores we can find to the global. We may not be able to
1723 // make it completely dead though.
Owen Anderson50895512009-07-06 18:42:36 +00001724 bool Changed = CleanupConstantGlobalUsers(GV, GV->getInitializer(),
Owen Andersone922c022009-07-22 00:24:57 +00001725 GV->getContext());
Chris Lattner930f4752004-10-09 03:32:52 +00001726
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001727 // If the global is dead now, delete it.
1728 if (GV->use_empty()) {
Chris Lattner7a7ed022004-10-16 18:09:00 +00001729 GV->eraseFromParent();
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001730 ++NumDeleted;
Chris Lattner930f4752004-10-09 03:32:52 +00001731 Changed = true;
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001732 }
Chris Lattner930f4752004-10-09 03:32:52 +00001733 return Changed;
Misha Brukmanfd939082005-04-21 23:48:37 +00001734
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001735 } else if (GS.StoredType <= GlobalStatus::isInitializerStored) {
Bill Wendling0a81aac2006-11-26 10:02:32 +00001736 DOUT << "MARKING CONSTANT: " << *GV;
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001737 GV->setConstant(true);
Misha Brukmanfd939082005-04-21 23:48:37 +00001738
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001739 // Clean up any obviously simplifiable users now.
Owen Andersone922c022009-07-22 00:24:57 +00001740 CleanupConstantGlobalUsers(GV, GV->getInitializer(), GV->getContext());
Misha Brukmanfd939082005-04-21 23:48:37 +00001741
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001742 // If the global is dead now, just nuke it.
1743 if (GV->use_empty()) {
Bill Wendling0a81aac2006-11-26 10:02:32 +00001744 DOUT << " *** Marking constant allowed us to simplify "
1745 << "all users and delete global!\n";
Chris Lattner7a7ed022004-10-16 18:09:00 +00001746 GV->eraseFromParent();
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001747 ++NumDeleted;
1748 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001749
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001750 ++NumMarked;
1751 return true;
Dan Gohman399101a2008-05-23 00:17:26 +00001752 } else if (!GV->getInitializer()->getType()->isSingleValueType()) {
Chris Lattner998182b2008-04-26 07:40:11 +00001753 if (GlobalVariable *FirstNewGV = SRAGlobal(GV,
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001754 getAnalysis<TargetData>(),
Owen Andersone922c022009-07-22 00:24:57 +00001755 GV->getContext())) {
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001756 GVI = FirstNewGV; // Don't skip the newly produced globals!
1757 return true;
1758 }
Chris Lattner9b34a612004-10-09 21:48:45 +00001759 } else if (GS.StoredType == GlobalStatus::isStoredOnce) {
Chris Lattner96a86b22004-12-12 05:53:50 +00001760 // If the initial value for the global was an undef value, and if only
1761 // one other value was stored into it, we can just change the
Duncan Sandsb5024402009-01-13 13:48:44 +00001762 // initializer to be the stored value, then delete all stores to the
Chris Lattner96a86b22004-12-12 05:53:50 +00001763 // global. This allows us to mark it constant.
1764 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
1765 if (isa<UndefValue>(GV->getInitializer())) {
1766 // Change the initial value here.
1767 GV->setInitializer(SOVConstant);
Misha Brukmanfd939082005-04-21 23:48:37 +00001768
Chris Lattner96a86b22004-12-12 05:53:50 +00001769 // Clean up any obviously simplifiable users now.
Owen Andersone922c022009-07-22 00:24:57 +00001770 CleanupConstantGlobalUsers(GV, GV->getInitializer(),
1771 GV->getContext());
Misha Brukmanfd939082005-04-21 23:48:37 +00001772
Chris Lattner96a86b22004-12-12 05:53:50 +00001773 if (GV->use_empty()) {
Bill Wendling0a81aac2006-11-26 10:02:32 +00001774 DOUT << " *** Substituting initializer allowed us to "
1775 << "simplify all users and delete global!\n";
Chris Lattner96a86b22004-12-12 05:53:50 +00001776 GV->eraseFromParent();
1777 ++NumDeleted;
1778 } else {
1779 GVI = GV;
1780 }
1781 ++NumSubstitute;
1782 return true;
Chris Lattner7a7ed022004-10-16 18:09:00 +00001783 }
Chris Lattner7a7ed022004-10-16 18:09:00 +00001784
Chris Lattner9b34a612004-10-09 21:48:45 +00001785 // Try to optimize globals based on the knowledge that only one value
1786 // (besides its initializer) is ever stored to the global.
Chris Lattner30ba5692004-10-11 05:54:41 +00001787 if (OptimizeOnceStoredGlobal(GV, GS.StoredOnceValue, GVI,
Owen Andersone922c022009-07-22 00:24:57 +00001788 getAnalysis<TargetData>(), GV->getContext()))
Chris Lattner9b34a612004-10-09 21:48:45 +00001789 return true;
Chris Lattner96a86b22004-12-12 05:53:50 +00001790
1791 // Otherwise, if the global was not a boolean, we can shrink it to be a
1792 // boolean.
1793 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
Owen Andersone922c022009-07-22 00:24:57 +00001794 if (TryToShrinkGlobalToBoolean(GV, SOVConstant, GV->getContext())) {
Chris Lattner96a86b22004-12-12 05:53:50 +00001795 ++NumShrunkToBool;
1796 return true;
1797 }
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001798 }
1799 }
1800 return false;
1801}
1802
Chris Lattnerfb217ad2005-05-08 22:18:06 +00001803/// ChangeCalleesToFastCall - Walk all of the direct calls of the specified
1804/// function, changing them to FastCC.
1805static void ChangeCalleesToFastCall(Function *F) {
1806 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
Duncan Sands548448a2008-02-18 17:32:13 +00001807 CallSite User(cast<Instruction>(*UI));
1808 User.setCallingConv(CallingConv::Fast);
Chris Lattnerfb217ad2005-05-08 22:18:06 +00001809 }
1810}
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001811
Devang Patel05988662008-09-25 21:00:45 +00001812static AttrListPtr StripNest(const AttrListPtr &Attrs) {
Chris Lattner58d74912008-03-12 17:45:29 +00001813 for (unsigned i = 0, e = Attrs.getNumSlots(); i != e; ++i) {
Devang Patel05988662008-09-25 21:00:45 +00001814 if ((Attrs.getSlot(i).Attrs & Attribute::Nest) == 0)
Duncan Sands548448a2008-02-18 17:32:13 +00001815 continue;
1816
Duncan Sands548448a2008-02-18 17:32:13 +00001817 // There can be only one.
Devang Patel05988662008-09-25 21:00:45 +00001818 return Attrs.removeAttr(Attrs.getSlot(i).Index, Attribute::Nest);
Duncan Sands3d5378f2008-02-16 20:56:04 +00001819 }
1820
1821 return Attrs;
1822}
1823
1824static void RemoveNestAttribute(Function *F) {
Devang Patel05988662008-09-25 21:00:45 +00001825 F->setAttributes(StripNest(F->getAttributes()));
Duncan Sands3d5378f2008-02-16 20:56:04 +00001826 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
Duncan Sands548448a2008-02-18 17:32:13 +00001827 CallSite User(cast<Instruction>(*UI));
Devang Patel05988662008-09-25 21:00:45 +00001828 User.setAttributes(StripNest(User.getAttributes()));
Duncan Sands3d5378f2008-02-16 20:56:04 +00001829 }
1830}
1831
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001832bool GlobalOpt::OptimizeFunctions(Module &M) {
1833 bool Changed = false;
1834 // Optimize functions.
1835 for (Module::iterator FI = M.begin(), E = M.end(); FI != E; ) {
1836 Function *F = FI++;
Duncan Sandsfc5940d2009-03-06 10:21:56 +00001837 // Functions without names cannot be referenced outside this module.
1838 if (!F->hasName() && !F->isDeclaration())
1839 F->setLinkage(GlobalValue::InternalLinkage);
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001840 F->removeDeadConstantUsers();
Rafael Espindolabb46f522009-01-15 20:18:42 +00001841 if (F->use_empty() && (F->hasLocalLinkage() ||
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001842 F->hasLinkOnceLinkage())) {
1843 M.getFunctionList().erase(F);
1844 Changed = true;
1845 ++NumFnDeleted;
Rafael Espindolabb46f522009-01-15 20:18:42 +00001846 } else if (F->hasLocalLinkage()) {
Duncan Sands3d5378f2008-02-16 20:56:04 +00001847 if (F->getCallingConv() == CallingConv::C && !F->isVarArg() &&
Jay Foad757068f2009-06-10 08:41:11 +00001848 !F->hasAddressTaken()) {
Duncan Sands3d5378f2008-02-16 20:56:04 +00001849 // If this function has C calling conventions, is not a varargs
1850 // function, and is only called directly, promote it to use the Fast
1851 // calling convention.
1852 F->setCallingConv(CallingConv::Fast);
1853 ChangeCalleesToFastCall(F);
1854 ++NumFastCallFns;
1855 Changed = true;
1856 }
1857
Devang Patel05988662008-09-25 21:00:45 +00001858 if (F->getAttributes().hasAttrSomewhere(Attribute::Nest) &&
Jay Foad757068f2009-06-10 08:41:11 +00001859 !F->hasAddressTaken()) {
Duncan Sands3d5378f2008-02-16 20:56:04 +00001860 // The function is not used by a trampoline intrinsic, so it is safe
1861 // to remove the 'nest' attribute.
1862 RemoveNestAttribute(F);
1863 ++NumNestRemoved;
1864 Changed = true;
1865 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001866 }
1867 }
1868 return Changed;
1869}
1870
1871bool GlobalOpt::OptimizeGlobalVars(Module &M) {
1872 bool Changed = false;
1873 for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
1874 GVI != E; ) {
1875 GlobalVariable *GV = GVI++;
Duncan Sandsfc5940d2009-03-06 10:21:56 +00001876 // Global variables without names cannot be referenced outside this module.
1877 if (!GV->hasName() && !GV->isDeclaration())
1878 GV->setLinkage(GlobalValue::InternalLinkage);
Rafael Espindolabb46f522009-01-15 20:18:42 +00001879 if (!GV->isConstant() && GV->hasLocalLinkage() &&
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001880 GV->hasInitializer())
1881 Changed |= ProcessInternalGlobal(GV, GVI);
1882 }
1883 return Changed;
1884}
1885
1886/// FindGlobalCtors - Find the llvm.globalctors list, verifying that all
1887/// initializers have an init priority of 65535.
1888GlobalVariable *GlobalOpt::FindGlobalCtors(Module &M) {
Alkis Evlogimenose9c6d362005-10-25 11:18:06 +00001889 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1890 I != E; ++I)
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001891 if (I->getName() == "llvm.global_ctors") {
1892 // Found it, verify it's an array of { int, void()* }.
1893 const ArrayType *ATy =dyn_cast<ArrayType>(I->getType()->getElementType());
1894 if (!ATy) return 0;
1895 const StructType *STy = dyn_cast<StructType>(ATy->getElementType());
1896 if (!STy || STy->getNumElements() != 2 ||
Reid Spencerc5b206b2006-12-31 05:48:39 +00001897 STy->getElementType(0) != Type::Int32Ty) return 0;
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001898 const PointerType *PFTy = dyn_cast<PointerType>(STy->getElementType(1));
1899 if (!PFTy) return 0;
1900 const FunctionType *FTy = dyn_cast<FunctionType>(PFTy->getElementType());
1901 if (!FTy || FTy->getReturnType() != Type::VoidTy || FTy->isVarArg() ||
1902 FTy->getNumParams() != 0)
1903 return 0;
1904
1905 // Verify that the initializer is simple enough for us to handle.
1906 if (!I->hasInitializer()) return 0;
1907 ConstantArray *CA = dyn_cast<ConstantArray>(I->getInitializer());
1908 if (!CA) return 0;
Gabor Greif5e463212008-05-29 01:59:18 +00001909 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i)
1910 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(*i)) {
Chris Lattner7d8e58f2005-09-26 02:19:27 +00001911 if (isa<ConstantPointerNull>(CS->getOperand(1)))
1912 continue;
1913
1914 // Must have a function or null ptr.
1915 if (!isa<Function>(CS->getOperand(1)))
1916 return 0;
1917
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001918 // Init priority must be standard.
1919 ConstantInt *CI = dyn_cast<ConstantInt>(CS->getOperand(0));
Reid Spencerb83eb642006-10-20 07:07:24 +00001920 if (!CI || CI->getZExtValue() != 65535)
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001921 return 0;
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001922 } else {
1923 return 0;
1924 }
1925
1926 return I;
1927 }
1928 return 0;
1929}
1930
Chris Lattnerdb973e62005-09-26 02:31:18 +00001931/// ParseGlobalCtors - Given a llvm.global_ctors list that we can understand,
1932/// return a list of the functions and null terminator as a vector.
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001933static std::vector<Function*> ParseGlobalCtors(GlobalVariable *GV) {
1934 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
1935 std::vector<Function*> Result;
1936 Result.reserve(CA->getNumOperands());
Gabor Greif5e463212008-05-29 01:59:18 +00001937 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i) {
1938 ConstantStruct *CS = cast<ConstantStruct>(*i);
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001939 Result.push_back(dyn_cast<Function>(CS->getOperand(1)));
1940 }
1941 return Result;
1942}
1943
Chris Lattnerdb973e62005-09-26 02:31:18 +00001944/// InstallGlobalCtors - Given a specified llvm.global_ctors list, install the
1945/// specified array, returning the new global to use.
1946static GlobalVariable *InstallGlobalCtors(GlobalVariable *GCL,
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001947 const std::vector<Function*> &Ctors,
Owen Andersone922c022009-07-22 00:24:57 +00001948 LLVMContext &Context) {
Chris Lattnerdb973e62005-09-26 02:31:18 +00001949 // If we made a change, reassemble the initializer list.
1950 std::vector<Constant*> CSVals;
Owen Andersoneed707b2009-07-24 23:12:02 +00001951 CSVals.push_back(ConstantInt::get(Type::Int32Ty, 65535));
Chris Lattnerdb973e62005-09-26 02:31:18 +00001952 CSVals.push_back(0);
1953
1954 // Create the new init list.
1955 std::vector<Constant*> CAList;
1956 for (unsigned i = 0, e = Ctors.size(); i != e; ++i) {
Chris Lattner79c11012005-09-26 04:44:35 +00001957 if (Ctors[i]) {
Chris Lattnerdb973e62005-09-26 02:31:18 +00001958 CSVals[1] = Ctors[i];
Chris Lattner79c11012005-09-26 04:44:35 +00001959 } else {
Owen Andersondebcb012009-07-29 22:17:13 +00001960 const Type *FTy = FunctionType::get(Type::VoidTy, false);
1961 const PointerType *PFTy = PointerType::getUnqual(FTy);
Owen Andersone922c022009-07-22 00:24:57 +00001962 CSVals[1] = Context.getNullValue(PFTy);
Owen Andersoneed707b2009-07-24 23:12:02 +00001963 CSVals[0] = ConstantInt::get(Type::Int32Ty, 2147483647);
Chris Lattnerdb973e62005-09-26 02:31:18 +00001964 }
Owen Anderson8fa33382009-07-27 22:29:26 +00001965 CAList.push_back(ConstantStruct::get(CSVals));
Chris Lattnerdb973e62005-09-26 02:31:18 +00001966 }
1967
1968 // Create the array initializer.
1969 const Type *StructTy =
1970 cast<ArrayType>(GCL->getType()->getElementType())->getElementType();
Owen Anderson1fd70962009-07-28 18:32:17 +00001971 Constant *CA = ConstantArray::get(ArrayType::get(StructTy,
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001972 CAList.size()), CAList);
Chris Lattnerdb973e62005-09-26 02:31:18 +00001973
1974 // If we didn't change the number of elements, don't create a new GV.
1975 if (CA->getType() == GCL->getInitializer()->getType()) {
1976 GCL->setInitializer(CA);
1977 return GCL;
1978 }
1979
1980 // Create the new global and insert it next to the existing list.
Owen Andersone922c022009-07-22 00:24:57 +00001981 GlobalVariable *NGV = new GlobalVariable(Context, CA->getType(),
Owen Anderson3d29df32009-07-08 01:26:06 +00001982 GCL->isConstant(),
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +00001983 GCL->getLinkage(), CA, "",
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +00001984 GCL->isThreadLocal());
Chris Lattnerdb973e62005-09-26 02:31:18 +00001985 GCL->getParent()->getGlobalList().insert(GCL, NGV);
Chris Lattner046800a2007-02-11 01:08:35 +00001986 NGV->takeName(GCL);
Chris Lattnerdb973e62005-09-26 02:31:18 +00001987
1988 // Nuke the old list, replacing any uses with the new one.
1989 if (!GCL->use_empty()) {
1990 Constant *V = NGV;
1991 if (V->getType() != GCL->getType())
Owen Andersonbaf3c402009-07-29 18:55:55 +00001992 V = ConstantExpr::getBitCast(V, GCL->getType());
Chris Lattnerdb973e62005-09-26 02:31:18 +00001993 GCL->replaceAllUsesWith(V);
1994 }
1995 GCL->eraseFromParent();
1996
1997 if (Ctors.size())
1998 return NGV;
1999 else
2000 return 0;
2001}
Chris Lattner79c11012005-09-26 04:44:35 +00002002
2003
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002004static Constant *getVal(DenseMap<Value*, Constant*> &ComputedValues,
Chris Lattner79c11012005-09-26 04:44:35 +00002005 Value *V) {
2006 if (Constant *CV = dyn_cast<Constant>(V)) return CV;
2007 Constant *R = ComputedValues[V];
2008 assert(R && "Reference to an uncomputed value!");
2009 return R;
2010}
2011
2012/// isSimpleEnoughPointerToCommit - Return true if this constant is simple
2013/// enough for us to understand. In particular, if it is a cast of something,
2014/// we punt. We basically just support direct accesses to globals and GEP's of
2015/// globals. This should be kept up to date with CommitValueTo.
Owen Andersone922c022009-07-22 00:24:57 +00002016static bool isSimpleEnoughPointerToCommit(Constant *C, LLVMContext &Context) {
Chris Lattner231308c2005-09-27 04:50:03 +00002017 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
Rafael Espindolabb46f522009-01-15 20:18:42 +00002018 if (!GV->hasExternalLinkage() && !GV->hasLocalLinkage())
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00002019 return false; // do not allow weak/linkonce/dllimport/dllexport linkage.
Reid Spencer5cbf9852007-01-30 20:08:39 +00002020 return !GV->isDeclaration(); // reject external globals.
Chris Lattner231308c2005-09-27 04:50:03 +00002021 }
Chris Lattner798b4d52005-09-26 06:52:44 +00002022 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
2023 // Handle a constantexpr gep.
2024 if (CE->getOpcode() == Instruction::GetElementPtr &&
2025 isa<GlobalVariable>(CE->getOperand(0))) {
2026 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
Rafael Espindolabb46f522009-01-15 20:18:42 +00002027 if (!GV->hasExternalLinkage() && !GV->hasLocalLinkage())
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00002028 return false; // do not allow weak/linkonce/dllimport/dllexport linkage.
Chris Lattner798b4d52005-09-26 06:52:44 +00002029 return GV->hasInitializer() &&
Owen Anderson50895512009-07-06 18:42:36 +00002030 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE,
2031 Context);
Chris Lattner798b4d52005-09-26 06:52:44 +00002032 }
Chris Lattner79c11012005-09-26 04:44:35 +00002033 return false;
2034}
2035
Chris Lattner798b4d52005-09-26 06:52:44 +00002036/// EvaluateStoreInto - Evaluate a piece of a constantexpr store into a global
2037/// initializer. This returns 'Init' modified to reflect 'Val' stored into it.
2038/// At this point, the GEP operands of Addr [0, OpNo) have been stepped into.
2039static Constant *EvaluateStoreInto(Constant *Init, Constant *Val,
Owen Anderson14ce9ef2009-07-06 01:34:54 +00002040 ConstantExpr *Addr, unsigned OpNo,
Owen Andersone922c022009-07-22 00:24:57 +00002041 LLVMContext &Context) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002042 // Base case of the recursion.
2043 if (OpNo == Addr->getNumOperands()) {
2044 assert(Val->getType() == Init->getType() && "Type mismatch!");
2045 return Val;
2046 }
2047
2048 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
2049 std::vector<Constant*> Elts;
2050
2051 // Break up the constant into its elements.
2052 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
Gabor Greif5e463212008-05-29 01:59:18 +00002053 for (User::op_iterator i = CS->op_begin(), e = CS->op_end(); i != e; ++i)
2054 Elts.push_back(cast<Constant>(*i));
Chris Lattner798b4d52005-09-26 06:52:44 +00002055 } else if (isa<ConstantAggregateZero>(Init)) {
2056 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
Owen Andersone922c022009-07-22 00:24:57 +00002057 Elts.push_back(Context.getNullValue(STy->getElementType(i)));
Chris Lattner798b4d52005-09-26 06:52:44 +00002058 } else if (isa<UndefValue>(Init)) {
2059 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
Owen Andersone922c022009-07-22 00:24:57 +00002060 Elts.push_back(Context.getUndef(STy->getElementType(i)));
Chris Lattner798b4d52005-09-26 06:52:44 +00002061 } else {
Torok Edwinc23197a2009-07-14 16:55:14 +00002062 llvm_unreachable("This code is out of sync with "
Chris Lattner798b4d52005-09-26 06:52:44 +00002063 " ConstantFoldLoadThroughGEPConstantExpr");
2064 }
2065
2066 // Replace the element that we are supposed to.
Reid Spencerb83eb642006-10-20 07:07:24 +00002067 ConstantInt *CU = cast<ConstantInt>(Addr->getOperand(OpNo));
2068 unsigned Idx = CU->getZExtValue();
2069 assert(Idx < STy->getNumElements() && "Struct index out of range!");
Owen Anderson14ce9ef2009-07-06 01:34:54 +00002070 Elts[Idx] = EvaluateStoreInto(Elts[Idx], Val, Addr, OpNo+1, Context);
Chris Lattner798b4d52005-09-26 06:52:44 +00002071
2072 // Return the modified struct.
Owen Anderson8fa33382009-07-27 22:29:26 +00002073 return ConstantStruct::get(&Elts[0], Elts.size(), STy->isPacked());
Chris Lattner798b4d52005-09-26 06:52:44 +00002074 } else {
2075 ConstantInt *CI = cast<ConstantInt>(Addr->getOperand(OpNo));
2076 const ArrayType *ATy = cast<ArrayType>(Init->getType());
2077
2078 // Break up the array into elements.
2079 std::vector<Constant*> Elts;
2080 if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
Gabor Greif5e463212008-05-29 01:59:18 +00002081 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i)
2082 Elts.push_back(cast<Constant>(*i));
Chris Lattner798b4d52005-09-26 06:52:44 +00002083 } else if (isa<ConstantAggregateZero>(Init)) {
Owen Andersone922c022009-07-22 00:24:57 +00002084 Constant *Elt = Context.getNullValue(ATy->getElementType());
Chris Lattner798b4d52005-09-26 06:52:44 +00002085 Elts.assign(ATy->getNumElements(), Elt);
2086 } else if (isa<UndefValue>(Init)) {
Owen Andersone922c022009-07-22 00:24:57 +00002087 Constant *Elt = Context.getUndef(ATy->getElementType());
Chris Lattner798b4d52005-09-26 06:52:44 +00002088 Elts.assign(ATy->getNumElements(), Elt);
2089 } else {
Torok Edwinc23197a2009-07-14 16:55:14 +00002090 llvm_unreachable("This code is out of sync with "
Chris Lattner798b4d52005-09-26 06:52:44 +00002091 " ConstantFoldLoadThroughGEPConstantExpr");
2092 }
2093
Reid Spencerb83eb642006-10-20 07:07:24 +00002094 assert(CI->getZExtValue() < ATy->getNumElements());
2095 Elts[CI->getZExtValue()] =
Owen Anderson14ce9ef2009-07-06 01:34:54 +00002096 EvaluateStoreInto(Elts[CI->getZExtValue()], Val, Addr, OpNo+1, Context);
Owen Anderson1fd70962009-07-28 18:32:17 +00002097 return ConstantArray::get(ATy, Elts);
Chris Lattner798b4d52005-09-26 06:52:44 +00002098 }
2099}
2100
Chris Lattner79c11012005-09-26 04:44:35 +00002101/// CommitValueTo - We have decided that Addr (which satisfies the predicate
2102/// isSimpleEnoughPointerToCommit) should get Val as its value. Make it happen.
Owen Anderson14ce9ef2009-07-06 01:34:54 +00002103static void CommitValueTo(Constant *Val, Constant *Addr,
Owen Andersone922c022009-07-22 00:24:57 +00002104 LLVMContext &Context) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002105 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Addr)) {
2106 assert(GV->hasInitializer());
2107 GV->setInitializer(Val);
2108 return;
2109 }
2110
2111 ConstantExpr *CE = cast<ConstantExpr>(Addr);
2112 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
2113
2114 Constant *Init = GV->getInitializer();
Owen Anderson14ce9ef2009-07-06 01:34:54 +00002115 Init = EvaluateStoreInto(Init, Val, CE, 2, Context);
Chris Lattner798b4d52005-09-26 06:52:44 +00002116 GV->setInitializer(Init);
Chris Lattner79c11012005-09-26 04:44:35 +00002117}
2118
Chris Lattner562a0552005-09-26 05:16:34 +00002119/// ComputeLoadResult - Return the value that would be computed by a load from
2120/// P after the stores reflected by 'memory' have been performed. If we can't
2121/// decide, return null.
Chris Lattner04de1cf2005-09-26 05:15:37 +00002122static Constant *ComputeLoadResult(Constant *P,
Owen Anderson50895512009-07-06 18:42:36 +00002123 const DenseMap<Constant*, Constant*> &Memory,
Owen Andersone922c022009-07-22 00:24:57 +00002124 LLVMContext &Context) {
Chris Lattner04de1cf2005-09-26 05:15:37 +00002125 // If this memory location has been recently stored, use the stored value: it
2126 // is the most up-to-date.
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002127 DenseMap<Constant*, Constant*>::const_iterator I = Memory.find(P);
Chris Lattner04de1cf2005-09-26 05:15:37 +00002128 if (I != Memory.end()) return I->second;
2129
2130 // Access it.
2131 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(P)) {
2132 if (GV->hasInitializer())
2133 return GV->getInitializer();
2134 return 0;
Chris Lattner04de1cf2005-09-26 05:15:37 +00002135 }
Chris Lattner798b4d52005-09-26 06:52:44 +00002136
2137 // Handle a constantexpr getelementptr.
2138 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(P))
2139 if (CE->getOpcode() == Instruction::GetElementPtr &&
2140 isa<GlobalVariable>(CE->getOperand(0))) {
2141 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
2142 if (GV->hasInitializer())
Owen Anderson50895512009-07-06 18:42:36 +00002143 return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE,
2144 Context);
Chris Lattner798b4d52005-09-26 06:52:44 +00002145 }
2146
2147 return 0; // don't know how to evaluate.
Chris Lattner04de1cf2005-09-26 05:15:37 +00002148}
2149
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002150/// EvaluateFunction - Evaluate a call to function F, returning true if
2151/// successful, false if we can't evaluate it. ActualArgs contains the formal
2152/// arguments for the function.
Chris Lattnercd271422005-09-27 04:45:34 +00002153static bool EvaluateFunction(Function *F, Constant *&RetVal,
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002154 const std::vector<Constant*> &ActualArgs,
2155 std::vector<Function*> &CallStack,
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002156 DenseMap<Constant*, Constant*> &MutatedMemory,
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002157 std::vector<GlobalVariable*> &AllocaTmps) {
Chris Lattnercd271422005-09-27 04:45:34 +00002158 // Check to see if this function is already executing (recursion). If so,
2159 // bail out. TODO: we might want to accept limited recursion.
2160 if (std::find(CallStack.begin(), CallStack.end(), F) != CallStack.end())
2161 return false;
2162
Owen Andersone922c022009-07-22 00:24:57 +00002163 LLVMContext &Context = F->getContext();
Owen Anderson14ce9ef2009-07-06 01:34:54 +00002164
Chris Lattnercd271422005-09-27 04:45:34 +00002165 CallStack.push_back(F);
2166
Chris Lattner79c11012005-09-26 04:44:35 +00002167 /// Values - As we compute SSA register values, we store their contents here.
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002168 DenseMap<Value*, Constant*> Values;
Chris Lattnercd271422005-09-27 04:45:34 +00002169
2170 // Initialize arguments to the incoming values specified.
2171 unsigned ArgNo = 0;
2172 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); AI != E;
2173 ++AI, ++ArgNo)
2174 Values[AI] = ActualArgs[ArgNo];
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002175
Chris Lattnercdf98be2005-09-26 04:57:38 +00002176 /// ExecutedBlocks - We only handle non-looping, non-recursive code. As such,
2177 /// we can only evaluate any one basic block at most once. This set keeps
2178 /// track of what we have executed so we can detect recursive cases etc.
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002179 SmallPtrSet<BasicBlock*, 32> ExecutedBlocks;
Chris Lattnera22fdb02005-09-26 17:07:09 +00002180
Chris Lattner79c11012005-09-26 04:44:35 +00002181 // CurInst - The current instruction we're evaluating.
2182 BasicBlock::iterator CurInst = F->begin()->begin();
2183
2184 // This is the main evaluation loop.
2185 while (1) {
2186 Constant *InstResult = 0;
2187
2188 if (StoreInst *SI = dyn_cast<StoreInst>(CurInst)) {
Chris Lattnercd271422005-09-27 04:45:34 +00002189 if (SI->isVolatile()) return false; // no volatile accesses.
Chris Lattner79c11012005-09-26 04:44:35 +00002190 Constant *Ptr = getVal(Values, SI->getOperand(1));
Owen Anderson50895512009-07-06 18:42:36 +00002191 if (!isSimpleEnoughPointerToCommit(Ptr, Context))
Chris Lattner79c11012005-09-26 04:44:35 +00002192 // If this is too complex for us to commit, reject it.
Chris Lattnercd271422005-09-27 04:45:34 +00002193 return false;
Chris Lattner79c11012005-09-26 04:44:35 +00002194 Constant *Val = getVal(Values, SI->getOperand(0));
2195 MutatedMemory[Ptr] = Val;
2196 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CurInst)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002197 InstResult = ConstantExpr::get(BO->getOpcode(),
Chris Lattner79c11012005-09-26 04:44:35 +00002198 getVal(Values, BO->getOperand(0)),
2199 getVal(Values, BO->getOperand(1)));
Reid Spencere4d87aa2006-12-23 06:05:41 +00002200 } else if (CmpInst *CI = dyn_cast<CmpInst>(CurInst)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002201 InstResult = ConstantExpr::getCompare(CI->getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00002202 getVal(Values, CI->getOperand(0)),
2203 getVal(Values, CI->getOperand(1)));
Chris Lattner79c11012005-09-26 04:44:35 +00002204 } else if (CastInst *CI = dyn_cast<CastInst>(CurInst)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002205 InstResult = ConstantExpr::getCast(CI->getOpcode(),
Chris Lattner9a989f02006-11-30 17:26:08 +00002206 getVal(Values, CI->getOperand(0)),
Chris Lattner79c11012005-09-26 04:44:35 +00002207 CI->getType());
2208 } else if (SelectInst *SI = dyn_cast<SelectInst>(CurInst)) {
Owen Anderson14ce9ef2009-07-06 01:34:54 +00002209 InstResult =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002210 ConstantExpr::getSelect(getVal(Values, SI->getOperand(0)),
Chris Lattner79c11012005-09-26 04:44:35 +00002211 getVal(Values, SI->getOperand(1)),
2212 getVal(Values, SI->getOperand(2)));
Chris Lattner04de1cf2005-09-26 05:15:37 +00002213 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurInst)) {
2214 Constant *P = getVal(Values, GEP->getOperand(0));
Chris Lattner55eb1c42007-01-31 04:40:53 +00002215 SmallVector<Constant*, 8> GEPOps;
Gabor Greif5e463212008-05-29 01:59:18 +00002216 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end();
2217 i != e; ++i)
2218 GEPOps.push_back(getVal(Values, *i));
Owen Anderson14ce9ef2009-07-06 01:34:54 +00002219 InstResult =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002220 ConstantExpr::getGetElementPtr(P, &GEPOps[0], GEPOps.size());
Chris Lattner04de1cf2005-09-26 05:15:37 +00002221 } else if (LoadInst *LI = dyn_cast<LoadInst>(CurInst)) {
Chris Lattnercd271422005-09-27 04:45:34 +00002222 if (LI->isVolatile()) return false; // no volatile accesses.
Chris Lattner04de1cf2005-09-26 05:15:37 +00002223 InstResult = ComputeLoadResult(getVal(Values, LI->getOperand(0)),
Owen Anderson50895512009-07-06 18:42:36 +00002224 MutatedMemory, Context);
Chris Lattnercd271422005-09-27 04:45:34 +00002225 if (InstResult == 0) return false; // Could not evaluate load.
Chris Lattnera22fdb02005-09-26 17:07:09 +00002226 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(CurInst)) {
Chris Lattnercd271422005-09-27 04:45:34 +00002227 if (AI->isArrayAllocation()) return false; // Cannot handle array allocs.
Chris Lattnera22fdb02005-09-26 17:07:09 +00002228 const Type *Ty = AI->getType()->getElementType();
Owen Andersone922c022009-07-22 00:24:57 +00002229 AllocaTmps.push_back(new GlobalVariable(Context, Ty, false,
Chris Lattnera22fdb02005-09-26 17:07:09 +00002230 GlobalValue::InternalLinkage,
Owen Andersone922c022009-07-22 00:24:57 +00002231 Context.getUndef(Ty),
Chris Lattnera22fdb02005-09-26 17:07:09 +00002232 AI->getName()));
Chris Lattnercd271422005-09-27 04:45:34 +00002233 InstResult = AllocaTmps.back();
2234 } else if (CallInst *CI = dyn_cast<CallInst>(CurInst)) {
Devang Patel412a4462009-03-09 23:04:12 +00002235
2236 // Debug info can safely be ignored here.
2237 if (isa<DbgInfoIntrinsic>(CI)) {
2238 ++CurInst;
2239 continue;
2240 }
2241
Chris Lattner7cd580f2006-07-07 21:37:01 +00002242 // Cannot handle inline asm.
2243 if (isa<InlineAsm>(CI->getOperand(0))) return false;
2244
Chris Lattnercd271422005-09-27 04:45:34 +00002245 // Resolve function pointers.
2246 Function *Callee = dyn_cast<Function>(getVal(Values, CI->getOperand(0)));
2247 if (!Callee) return false; // Cannot resolve.
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002248
Chris Lattnercd271422005-09-27 04:45:34 +00002249 std::vector<Constant*> Formals;
Gabor Greif5e463212008-05-29 01:59:18 +00002250 for (User::op_iterator i = CI->op_begin() + 1, e = CI->op_end();
2251 i != e; ++i)
2252 Formals.push_back(getVal(Values, *i));
Chris Lattnercd271422005-09-27 04:45:34 +00002253
Reid Spencer5cbf9852007-01-30 20:08:39 +00002254 if (Callee->isDeclaration()) {
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002255 // If this is a function we can constant fold, do it.
Chris Lattner6c1f5652007-01-30 23:14:52 +00002256 if (Constant *C = ConstantFoldCall(Callee, &Formals[0],
2257 Formals.size())) {
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002258 InstResult = C;
2259 } else {
2260 return false;
2261 }
2262 } else {
2263 if (Callee->getFunctionType()->isVarArg())
2264 return false;
2265
2266 Constant *RetVal;
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002267 // Execute the call, if successful, use the return value.
2268 if (!EvaluateFunction(Callee, RetVal, Formals, CallStack,
2269 MutatedMemory, AllocaTmps))
2270 return false;
2271 InstResult = RetVal;
2272 }
Reid Spencer3ed469c2006-11-02 20:25:50 +00002273 } else if (isa<TerminatorInst>(CurInst)) {
Chris Lattnercdf98be2005-09-26 04:57:38 +00002274 BasicBlock *NewBB = 0;
2275 if (BranchInst *BI = dyn_cast<BranchInst>(CurInst)) {
2276 if (BI->isUnconditional()) {
2277 NewBB = BI->getSuccessor(0);
2278 } else {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002279 ConstantInt *Cond =
2280 dyn_cast<ConstantInt>(getVal(Values, BI->getCondition()));
Chris Lattner97d1fad2007-01-12 18:30:11 +00002281 if (!Cond) return false; // Cannot determine.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002282
Reid Spencer579dca12007-01-12 04:24:46 +00002283 NewBB = BI->getSuccessor(!Cond->getZExtValue());
Chris Lattnercdf98be2005-09-26 04:57:38 +00002284 }
2285 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(CurInst)) {
2286 ConstantInt *Val =
2287 dyn_cast<ConstantInt>(getVal(Values, SI->getCondition()));
Chris Lattnercd271422005-09-27 04:45:34 +00002288 if (!Val) return false; // Cannot determine.
Chris Lattnercdf98be2005-09-26 04:57:38 +00002289 NewBB = SI->getSuccessor(SI->findCaseValue(Val));
2290 } else if (ReturnInst *RI = dyn_cast<ReturnInst>(CurInst)) {
Chris Lattnercd271422005-09-27 04:45:34 +00002291 if (RI->getNumOperands())
2292 RetVal = getVal(Values, RI->getOperand(0));
2293
2294 CallStack.pop_back(); // return from fn.
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002295 return true; // We succeeded at evaluating this ctor!
Chris Lattnercdf98be2005-09-26 04:57:38 +00002296 } else {
Chris Lattnercd271422005-09-27 04:45:34 +00002297 // invoke, unwind, unreachable.
2298 return false; // Cannot handle this terminator.
Chris Lattnercdf98be2005-09-26 04:57:38 +00002299 }
2300
2301 // Okay, we succeeded in evaluating this control flow. See if we have
Chris Lattnercd271422005-09-27 04:45:34 +00002302 // executed the new block before. If so, we have a looping function,
2303 // which we cannot evaluate in reasonable time.
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002304 if (!ExecutedBlocks.insert(NewBB))
Chris Lattnercd271422005-09-27 04:45:34 +00002305 return false; // looped!
Chris Lattnercdf98be2005-09-26 04:57:38 +00002306
2307 // Okay, we have never been in this block before. Check to see if there
2308 // are any PHI nodes. If so, evaluate them with information about where
2309 // we came from.
2310 BasicBlock *OldBB = CurInst->getParent();
2311 CurInst = NewBB->begin();
2312 PHINode *PN;
2313 for (; (PN = dyn_cast<PHINode>(CurInst)); ++CurInst)
2314 Values[PN] = getVal(Values, PN->getIncomingValueForBlock(OldBB));
2315
2316 // Do NOT increment CurInst. We know that the terminator had no value.
2317 continue;
Chris Lattner79c11012005-09-26 04:44:35 +00002318 } else {
Chris Lattner79c11012005-09-26 04:44:35 +00002319 // Did not know how to evaluate this!
Chris Lattnercd271422005-09-27 04:45:34 +00002320 return false;
Chris Lattner79c11012005-09-26 04:44:35 +00002321 }
2322
2323 if (!CurInst->use_empty())
2324 Values[CurInst] = InstResult;
2325
2326 // Advance program counter.
2327 ++CurInst;
2328 }
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002329}
2330
2331/// EvaluateStaticConstructor - Evaluate static constructors in the function, if
2332/// we can. Return true if we can, false otherwise.
2333static bool EvaluateStaticConstructor(Function *F) {
2334 /// MutatedMemory - For each store we execute, we update this map. Loads
2335 /// check this to get the most up-to-date value. If evaluation is successful,
2336 /// this state is committed to the process.
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002337 DenseMap<Constant*, Constant*> MutatedMemory;
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002338
2339 /// AllocaTmps - To 'execute' an alloca, we create a temporary global variable
2340 /// to represent its body. This vector is needed so we can delete the
2341 /// temporary globals when we are done.
2342 std::vector<GlobalVariable*> AllocaTmps;
2343
2344 /// CallStack - This is used to detect recursion. In pathological situations
2345 /// we could hit exponential behavior, but at least there is nothing
2346 /// unbounded.
2347 std::vector<Function*> CallStack;
2348
2349 // Call the function.
Chris Lattnercd271422005-09-27 04:45:34 +00002350 Constant *RetValDummy;
2351 bool EvalSuccess = EvaluateFunction(F, RetValDummy, std::vector<Constant*>(),
2352 CallStack, MutatedMemory, AllocaTmps);
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002353 if (EvalSuccess) {
Chris Lattnera22fdb02005-09-26 17:07:09 +00002354 // We succeeded at evaluation: commit the result.
Daniel Dunbarce63ffb2009-07-25 00:23:56 +00002355 DEBUG(errs() << "FULLY EVALUATED GLOBAL CTOR FUNCTION '"
2356 << F->getName() << "' to " << MutatedMemory.size()
2357 << " stores.\n");
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002358 for (DenseMap<Constant*, Constant*>::iterator I = MutatedMemory.begin(),
Chris Lattnera22fdb02005-09-26 17:07:09 +00002359 E = MutatedMemory.end(); I != E; ++I)
Owen Anderson14ce9ef2009-07-06 01:34:54 +00002360 CommitValueTo(I->second, I->first, F->getContext());
Chris Lattnera22fdb02005-09-26 17:07:09 +00002361 }
Chris Lattner79c11012005-09-26 04:44:35 +00002362
Chris Lattnera22fdb02005-09-26 17:07:09 +00002363 // At this point, we are done interpreting. If we created any 'alloca'
2364 // temporaries, release them now.
2365 while (!AllocaTmps.empty()) {
2366 GlobalVariable *Tmp = AllocaTmps.back();
2367 AllocaTmps.pop_back();
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002368
Chris Lattnera22fdb02005-09-26 17:07:09 +00002369 // If there are still users of the alloca, the program is doing something
2370 // silly, e.g. storing the address of the alloca somewhere and using it
2371 // later. Since this is undefined, we'll just make it be null.
2372 if (!Tmp->use_empty())
Owen Andersone922c022009-07-22 00:24:57 +00002373 Tmp->replaceAllUsesWith(F->getContext().getNullValue(Tmp->getType()));
Chris Lattnera22fdb02005-09-26 17:07:09 +00002374 delete Tmp;
2375 }
Chris Lattneraae4a1c2005-09-26 07:34:35 +00002376
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002377 return EvalSuccess;
Chris Lattner79c11012005-09-26 04:44:35 +00002378}
2379
Chris Lattnerdb973e62005-09-26 02:31:18 +00002380
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002381
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002382/// OptimizeGlobalCtorsList - Simplify and evaluation global ctors if possible.
2383/// Return true if anything changed.
2384bool GlobalOpt::OptimizeGlobalCtorsList(GlobalVariable *&GCL) {
2385 std::vector<Function*> Ctors = ParseGlobalCtors(GCL);
2386 bool MadeChange = false;
2387 if (Ctors.empty()) return false;
2388
2389 // Loop over global ctors, optimizing them when we can.
2390 for (unsigned i = 0; i != Ctors.size(); ++i) {
2391 Function *F = Ctors[i];
2392 // Found a null terminator in the middle of the list, prune off the rest of
2393 // the list.
Chris Lattner7d8e58f2005-09-26 02:19:27 +00002394 if (F == 0) {
2395 if (i != Ctors.size()-1) {
2396 Ctors.resize(i+1);
2397 MadeChange = true;
2398 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002399 break;
2400 }
2401
Chris Lattner79c11012005-09-26 04:44:35 +00002402 // We cannot simplify external ctor functions.
2403 if (F->empty()) continue;
2404
2405 // If we can evaluate the ctor at compile time, do.
2406 if (EvaluateStaticConstructor(F)) {
2407 Ctors.erase(Ctors.begin()+i);
2408 MadeChange = true;
2409 --i;
2410 ++NumCtorsEvaluated;
2411 continue;
2412 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002413 }
2414
2415 if (!MadeChange) return false;
2416
Owen Andersone922c022009-07-22 00:24:57 +00002417 GCL = InstallGlobalCtors(GCL, Ctors, GCL->getContext());
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002418 return true;
2419}
2420
Duncan Sandsfc5940d2009-03-06 10:21:56 +00002421bool GlobalOpt::OptimizeGlobalAliases(Module &M) {
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002422 bool Changed = false;
2423
Duncan Sands177d84e2009-01-07 20:01:06 +00002424 for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end();
Duncan Sands4782b302009-02-15 09:56:08 +00002425 I != E;) {
2426 Module::alias_iterator J = I++;
Duncan Sandsfc5940d2009-03-06 10:21:56 +00002427 // Aliases without names cannot be referenced outside this module.
2428 if (!J->hasName() && !J->isDeclaration())
2429 J->setLinkage(GlobalValue::InternalLinkage);
Duncan Sands4782b302009-02-15 09:56:08 +00002430 // If the aliasee may change at link time, nothing can be done - bail out.
2431 if (J->mayBeOverridden())
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002432 continue;
2433
Duncan Sands4782b302009-02-15 09:56:08 +00002434 Constant *Aliasee = J->getAliasee();
2435 GlobalValue *Target = cast<GlobalValue>(Aliasee->stripPointerCasts());
Duncan Sands95c5d0f2009-02-18 17:55:38 +00002436 Target->removeDeadConstantUsers();
Duncan Sands4782b302009-02-15 09:56:08 +00002437 bool hasOneUse = Target->hasOneUse() && Aliasee->hasOneUse();
2438
2439 // Make all users of the alias use the aliasee instead.
2440 if (!J->use_empty()) {
2441 J->replaceAllUsesWith(Aliasee);
2442 ++NumAliasesResolved;
2443 Changed = true;
2444 }
2445
2446 // If the aliasee has internal linkage, give it the name and linkage
2447 // of the alias, and delete the alias. This turns:
2448 // define internal ... @f(...)
2449 // @a = alias ... @f
2450 // into:
2451 // define ... @a(...)
Duncan Sands7ae5b9e2009-02-17 17:50:04 +00002452 if (!Target->hasLocalLinkage())
Duncan Sands4782b302009-02-15 09:56:08 +00002453 continue;
2454
2455 // The transform is only useful if the alias does not have internal linkage.
Duncan Sands7ae5b9e2009-02-17 17:50:04 +00002456 if (J->hasLocalLinkage())
Duncan Sands4782b302009-02-15 09:56:08 +00002457 continue;
2458
Duncan Sandsa37d1192009-02-15 11:54:49 +00002459 // Do not perform the transform if multiple aliases potentially target the
2460 // aliasee. This check also ensures that it is safe to replace the section
2461 // and other attributes of the aliasee with those of the alias.
Duncan Sands4782b302009-02-15 09:56:08 +00002462 if (!hasOneUse)
2463 continue;
2464
Duncan Sandsa37d1192009-02-15 11:54:49 +00002465 // Give the aliasee the name, linkage and other attributes of the alias.
Duncan Sands4782b302009-02-15 09:56:08 +00002466 Target->takeName(J);
2467 Target->setLinkage(J->getLinkage());
Duncan Sandsa37d1192009-02-15 11:54:49 +00002468 Target->GlobalValue::copyAttributesFrom(J);
Duncan Sands4782b302009-02-15 09:56:08 +00002469
2470 // Delete the alias.
2471 M.getAliasList().erase(J);
2472 ++NumAliasesRemoved;
2473 Changed = true;
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002474 }
2475
2476 return Changed;
2477}
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002478
Chris Lattner7a90b682004-10-07 04:16:33 +00002479bool GlobalOpt::runOnModule(Module &M) {
Chris Lattner079236d2004-02-25 21:34:36 +00002480 bool Changed = false;
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002481
2482 // Try to find the llvm.globalctors list.
2483 GlobalVariable *GlobalCtors = FindGlobalCtors(M);
Chris Lattner7a90b682004-10-07 04:16:33 +00002484
Chris Lattner7a90b682004-10-07 04:16:33 +00002485 bool LocalChange = true;
2486 while (LocalChange) {
2487 LocalChange = false;
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002488
2489 // Delete functions that are trivially dead, ccc -> fastcc
2490 LocalChange |= OptimizeFunctions(M);
2491
2492 // Optimize global_ctors list.
2493 if (GlobalCtors)
2494 LocalChange |= OptimizeGlobalCtorsList(GlobalCtors);
2495
2496 // Optimize non-address-taken globals.
2497 LocalChange |= OptimizeGlobalVars(M);
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002498
2499 // Resolve aliases, when possible.
Duncan Sandsfc5940d2009-03-06 10:21:56 +00002500 LocalChange |= OptimizeGlobalAliases(M);
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002501 Changed |= LocalChange;
Chris Lattner7a90b682004-10-07 04:16:33 +00002502 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002503
2504 // TODO: Move all global ctors functions to the end of the module for code
2505 // layout.
2506
Chris Lattner079236d2004-02-25 21:34:36 +00002507 return Changed;
2508}