blob: 9d0b96b7a36c6b97f45f5d588b15d2dc69161fcd [file] [log] [blame]
Chris Lattner7a90b682004-10-07 04:16:33 +00001//===- GlobalOpt.cpp - Optimize Global Variables --------------------------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
Chris Lattner079236d2004-02-25 21:34:36 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
Chris Lattner079236d2004-02-25 21:34:36 +00008//===----------------------------------------------------------------------===//
9//
Chris Lattner7a90b682004-10-07 04:16:33 +000010// This pass transforms simple global variables that never have their address
11// taken. If obviously true, it marks read/write globals as constant, deletes
12// variables only stored to, etc.
Chris Lattner079236d2004-02-25 21:34:36 +000013//
14//===----------------------------------------------------------------------===//
15
Chris Lattner7a90b682004-10-07 04:16:33 +000016#define DEBUG_TYPE "globalopt"
Chris Lattner079236d2004-02-25 21:34:36 +000017#include "llvm/Transforms/IPO.h"
Chris Lattnerfb217ad2005-05-08 22:18:06 +000018#include "llvm/CallingConv.h"
Chris Lattner079236d2004-02-25 21:34:36 +000019#include "llvm/Constants.h"
Chris Lattner7a90b682004-10-07 04:16:33 +000020#include "llvm/DerivedTypes.h"
Chris Lattner7d90a272004-02-27 18:09:25 +000021#include "llvm/Instructions.h"
Chris Lattner35c81b02005-02-27 18:58:52 +000022#include "llvm/IntrinsicInst.h"
Chris Lattner079236d2004-02-25 21:34:36 +000023#include "llvm/Module.h"
Jay Foad562b84b2011-04-11 09:35:34 +000024#include "llvm/Operator.h"
Chris Lattner079236d2004-02-25 21:34:36 +000025#include "llvm/Pass.h"
Chris Lattner79066fa2007-01-30 23:46:24 +000026#include "llvm/Analysis/ConstantFolding.h"
Victor Hernandezf006b182009-10-27 20:05:49 +000027#include "llvm/Analysis/MemoryBuiltins.h"
Chris Lattner30ba5692004-10-11 05:54:41 +000028#include "llvm/Target/TargetData.h"
Chad Rosier00737bd2011-12-01 21:29:16 +000029#include "llvm/Target/TargetLibraryInfo.h"
Duncan Sands548448a2008-02-18 17:32:13 +000030#include "llvm/Support/CallSite.h"
Chris Lattner79066fa2007-01-30 23:46:24 +000031#include "llvm/Support/Debug.h"
Torok Edwinc25e7582009-07-11 20:10:48 +000032#include "llvm/Support/ErrorHandling.h"
Chris Lattner941db492008-01-14 02:09:12 +000033#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner998182b2008-04-26 07:40:11 +000034#include "llvm/Support/MathExtras.h"
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000035#include "llvm/Support/raw_ostream.h"
Chris Lattner5a6bb6a2008-12-16 07:34:30 +000036#include "llvm/ADT/DenseMap.h"
Chris Lattner81686182007-09-13 16:30:19 +000037#include "llvm/ADT/SmallPtrSet.h"
Chris Lattner55eb1c42007-01-31 04:40:53 +000038#include "llvm/ADT/SmallVector.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000039#include "llvm/ADT/Statistic.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");
Rafael Espindolac4440e32011-01-19 16:32:21 +000045STATISTIC(NumUnnamed , "Number of globals marked unnamed_addr");
Chris Lattner86453c52006-12-19 22:09:18 +000046STATISTIC(NumSRA , "Number of aggregate globals broken into scalars");
47STATISTIC(NumHeapSRA , "Number of heap objects SRA'd");
48STATISTIC(NumSubstitute,"Number of globals with initializers stored into them");
49STATISTIC(NumDeleted , "Number of globals deleted");
50STATISTIC(NumFnDeleted , "Number of functions deleted");
51STATISTIC(NumGlobUses , "Number of global uses devirtualized");
52STATISTIC(NumLocalized , "Number of globals localized");
53STATISTIC(NumShrunkToBool , "Number of global vars shrunk to booleans");
54STATISTIC(NumFastCallFns , "Number of functions converted to fastcc");
55STATISTIC(NumCtorsEvaluated, "Number of static ctors evaluated");
Duncan Sands3d5378f2008-02-16 20:56:04 +000056STATISTIC(NumNestRemoved , "Number of nest attributes removed");
Duncan Sands4782b302009-02-15 09:56:08 +000057STATISTIC(NumAliasesResolved, "Number of global aliases resolved");
58STATISTIC(NumAliasesRemoved, "Number of global aliases eliminated");
Anders Carlssona201c4c2011-03-20 17:59:11 +000059STATISTIC(NumCXXDtorsRemoved, "Number of global C++ destructors removed");
Chris Lattner079236d2004-02-25 21:34:36 +000060
Chris Lattner86453c52006-12-19 22:09:18 +000061namespace {
Rafael Espindolac4440e32011-01-19 16:32:21 +000062 struct GlobalStatus;
Nick Lewycky6726b6d2009-10-25 06:33:48 +000063 struct GlobalOpt : public ModulePass {
Chris Lattner30ba5692004-10-11 05:54:41 +000064 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chad Rosier00737bd2011-12-01 21:29:16 +000065 AU.addRequired<TargetLibraryInfo>();
Chris Lattner30ba5692004-10-11 05:54:41 +000066 }
Nick Lewyckyecd94c82007-05-06 13:37:16 +000067 static char ID; // Pass identification, replacement for typeid
Owen Anderson081c34b2010-10-19 17:21:58 +000068 GlobalOpt() : ModulePass(ID) {
69 initializeGlobalOptPass(*PassRegistry::getPassRegistry());
70 }
Misha Brukmanfd939082005-04-21 23:48:37 +000071
Chris Lattnerb12914b2004-09-20 04:48:05 +000072 bool runOnModule(Module &M);
Chris Lattner30ba5692004-10-11 05:54:41 +000073
74 private:
Chris Lattnerb1ab4582005-09-26 01:43:45 +000075 GlobalVariable *FindGlobalCtors(Module &M);
76 bool OptimizeFunctions(Module &M);
77 bool OptimizeGlobalVars(Module &M);
Duncan Sandsfc5940d2009-03-06 10:21:56 +000078 bool OptimizeGlobalAliases(Module &M);
Chris Lattnerb1ab4582005-09-26 01:43:45 +000079 bool OptimizeGlobalCtorsList(GlobalVariable *&GCL);
Rafael Espindolac4440e32011-01-19 16:32:21 +000080 bool ProcessGlobal(GlobalVariable *GV,Module::global_iterator &GVI);
81 bool ProcessInternalGlobal(GlobalVariable *GV,Module::global_iterator &GVI,
82 const SmallPtrSet<const PHINode*, 16> &PHIUsers,
83 const GlobalStatus &GS);
Anders Carlssona201c4c2011-03-20 17:59:11 +000084 bool OptimizeEmptyGlobalCXXDtors(Function *CXAAtExitFn);
Chris Lattner079236d2004-02-25 21:34:36 +000085 };
Chris Lattner079236d2004-02-25 21:34:36 +000086}
87
Dan Gohman844731a2008-05-13 00:00:25 +000088char GlobalOpt::ID = 0;
Chad Rosier00737bd2011-12-01 21:29:16 +000089INITIALIZE_PASS_BEGIN(GlobalOpt, "globalopt",
90 "Global Variable Optimizer", false, false)
91INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
92INITIALIZE_PASS_END(GlobalOpt, "globalopt",
Owen Andersonce665bd2010-10-07 22:25:06 +000093 "Global Variable Optimizer", false, false)
Dan Gohman844731a2008-05-13 00:00:25 +000094
Chris Lattner7a90b682004-10-07 04:16:33 +000095ModulePass *llvm::createGlobalOptimizerPass() { return new GlobalOpt(); }
Chris Lattner079236d2004-02-25 21:34:36 +000096
Dan Gohman844731a2008-05-13 00:00:25 +000097namespace {
98
Chris Lattner7a90b682004-10-07 04:16:33 +000099/// GlobalStatus - As we analyze each global, keep track of some information
100/// about it. If we find out that the address of the global is taken, none of
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000101/// this info will be accurate.
Nick Lewycky6726b6d2009-10-25 06:33:48 +0000102struct GlobalStatus {
Rafael Espindolac4440e32011-01-19 16:32:21 +0000103 /// isCompared - True if the global's address is used in a comparison.
104 bool isCompared;
105
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000106 /// isLoaded - True if the global is ever loaded. If the global isn't ever
107 /// loaded it can be deleted.
Chris Lattner7a90b682004-10-07 04:16:33 +0000108 bool isLoaded;
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000109
110 /// StoredType - Keep track of what stores to the global look like.
111 ///
Chris Lattner7a90b682004-10-07 04:16:33 +0000112 enum StoredType {
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000113 /// NotStored - There is no store to this global. It can thus be marked
114 /// constant.
115 NotStored,
116
117 /// isInitializerStored - This global is stored to, but the only thing
118 /// stored is the constant it was initialized with. This is only tracked
119 /// for scalar globals.
120 isInitializerStored,
121
122 /// isStoredOnce - This global is stored to, but only its initializer and
123 /// one other value is ever stored to it. If this global isStoredOnce, we
124 /// track the value stored to it in StoredOnceValue below. This is only
125 /// tracked for scalar globals.
126 isStoredOnce,
127
128 /// isStored - This global is stored to by multiple values or something else
129 /// that we cannot track.
130 isStored
Chris Lattner7a90b682004-10-07 04:16:33 +0000131 } StoredType;
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000132
133 /// StoredOnceValue - If only one value (besides the initializer constant) is
134 /// ever stored to this global, keep track of what value it is.
135 Value *StoredOnceValue;
136
Chris Lattner25de4e52006-11-01 18:03:33 +0000137 /// AccessingFunction/HasMultipleAccessingFunctions - These start out
138 /// null/false. When the first accessing function is noticed, it is recorded.
139 /// When a second different accessing function is noticed,
140 /// HasMultipleAccessingFunctions is set to true.
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000141 const Function *AccessingFunction;
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +0000142 bool HasMultipleAccessingFunctions;
143
Chris Lattner25de4e52006-11-01 18:03:33 +0000144 /// HasNonInstructionUser - Set to true if this global has a user that is not
145 /// an instruction (e.g. a constant expr or GV initializer).
Chris Lattner553ca522005-06-15 21:11:48 +0000146 bool HasNonInstructionUser;
147
Chris Lattner25de4e52006-11-01 18:03:33 +0000148 /// HasPHIUser - Set to true if this global has a user that is a PHI node.
149 bool HasPHIUser;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000150
Rafael Espindolac4440e32011-01-19 16:32:21 +0000151 GlobalStatus() : isCompared(false), isLoaded(false), StoredType(NotStored),
152 StoredOnceValue(0), AccessingFunction(0),
153 HasMultipleAccessingFunctions(false), HasNonInstructionUser(false),
154 HasPHIUser(false) {}
Chris Lattner7a90b682004-10-07 04:16:33 +0000155};
Chris Lattnere47ba742004-10-06 20:57:02 +0000156
Dan Gohman844731a2008-05-13 00:00:25 +0000157}
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000158
Jay Foade3acf152009-06-09 21:37:11 +0000159// SafeToDestroyConstant - It is safe to destroy a constant iff it is only used
160// by constants itself. Note that constants cannot be cyclic, so this test is
161// pretty easy to implement recursively.
162//
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000163static bool SafeToDestroyConstant(const Constant *C) {
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000164 if (isa<GlobalValue>(C)) return false;
165
Gabor Greif27236912010-04-07 18:59:26 +0000166 for (Value::const_use_iterator UI = C->use_begin(), E = C->use_end(); UI != E;
167 ++UI)
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000168 if (const Constant *CU = dyn_cast<Constant>(*UI)) {
Jay Foade3acf152009-06-09 21:37:11 +0000169 if (!SafeToDestroyConstant(CU)) return false;
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000170 } else
171 return false;
172 return true;
173}
174
175
Chris Lattner7a90b682004-10-07 04:16:33 +0000176/// AnalyzeGlobal - Look at all uses of the global and fill in the GlobalStatus
177/// structure. If the global has its address taken, return true to indicate we
178/// can't do anything with it.
Chris Lattner079236d2004-02-25 21:34:36 +0000179///
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000180static bool AnalyzeGlobal(const Value *V, GlobalStatus &GS,
181 SmallPtrSet<const PHINode*, 16> &PHIUsers) {
Gabor Greif27236912010-04-07 18:59:26 +0000182 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;
Gabor Greife6642672010-07-09 16:51:20 +0000183 ++UI) {
184 const User *U = *UI;
185 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
Chris Lattner553ca522005-06-15 21:11:48 +0000186 GS.HasNonInstructionUser = true;
Chris Lattnerd91ed102011-01-01 22:31:46 +0000187
188 // If the result of the constantexpr isn't pointer type, then we won't
189 // know to expect it in various places. Just reject early.
190 if (!isa<PointerType>(CE->getType())) return true;
191
Chris Lattner7a90b682004-10-07 04:16:33 +0000192 if (AnalyzeGlobal(CE, GS, PHIUsers)) return true;
Gabor Greife6642672010-07-09 16:51:20 +0000193 } else if (const Instruction *I = dyn_cast<Instruction>(U)) {
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +0000194 if (!GS.HasMultipleAccessingFunctions) {
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000195 const Function *F = I->getParent()->getParent();
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +0000196 if (GS.AccessingFunction == 0)
197 GS.AccessingFunction = F;
198 else if (GS.AccessingFunction != F)
199 GS.HasMultipleAccessingFunctions = true;
200 }
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000201 if (const LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattner7a90b682004-10-07 04:16:33 +0000202 GS.isLoaded = true;
Eli Friedman33cb4452011-08-16 00:20:11 +0000203 // Don't hack on volatile/atomic loads.
204 if (!LI->isSimple()) return true;
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000205 } else if (const StoreInst *SI = dyn_cast<StoreInst>(I)) {
Chris Lattner36025492004-10-07 06:01:25 +0000206 // Don't allow a store OF the address, only stores TO the address.
207 if (SI->getOperand(0) == V) return true;
208
Eli Friedman33cb4452011-08-16 00:20:11 +0000209 // Don't hack on volatile/atomic stores.
210 if (!SI->isSimple()) return true;
Chris Lattnerc69d3c92008-01-29 19:01:37 +0000211
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000212 // If this is a direct store to the global (i.e., the global is a scalar
213 // value, not an aggregate), keep more specific information about
214 // stores.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000215 if (GS.StoredType != GlobalStatus::isStored) {
Gabor Greif27236912010-04-07 18:59:26 +0000216 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(
217 SI->getOperand(1))) {
Chris Lattnerbd38edf2004-11-14 20:50:30 +0000218 Value *StoredVal = SI->getOperand(0);
219 if (StoredVal == GV->getInitializer()) {
220 if (GS.StoredType < GlobalStatus::isInitializerStored)
221 GS.StoredType = GlobalStatus::isInitializerStored;
222 } else if (isa<LoadInst>(StoredVal) &&
223 cast<LoadInst>(StoredVal)->getOperand(0) == GV) {
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000224 if (GS.StoredType < GlobalStatus::isInitializerStored)
225 GS.StoredType = GlobalStatus::isInitializerStored;
226 } else if (GS.StoredType < GlobalStatus::isStoredOnce) {
227 GS.StoredType = GlobalStatus::isStoredOnce;
Chris Lattnerbd38edf2004-11-14 20:50:30 +0000228 GS.StoredOnceValue = StoredVal;
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000229 } else if (GS.StoredType == GlobalStatus::isStoredOnce &&
Chris Lattnerbd38edf2004-11-14 20:50:30 +0000230 GS.StoredOnceValue == StoredVal) {
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000231 // noop.
232 } else {
233 GS.StoredType = GlobalStatus::isStored;
234 }
235 } else {
Chris Lattner7a90b682004-10-07 04:16:33 +0000236 GS.StoredType = GlobalStatus::isStored;
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000237 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000238 }
Chris Lattner35c81b02005-02-27 18:58:52 +0000239 } else if (isa<GetElementPtrInst>(I)) {
Chris Lattner7a90b682004-10-07 04:16:33 +0000240 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Chris Lattner35c81b02005-02-27 18:58:52 +0000241 } else if (isa<SelectInst>(I)) {
Chris Lattner7a90b682004-10-07 04:16:33 +0000242 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000243 } else if (const PHINode *PN = dyn_cast<PHINode>(I)) {
Chris Lattner7a90b682004-10-07 04:16:33 +0000244 // PHI nodes we can check just like select or GEP instructions, but we
245 // have to be careful about infinite recursion.
Chris Lattner5a6bb6a2008-12-16 07:34:30 +0000246 if (PHIUsers.insert(PN)) // Not already visited.
Chris Lattner7a90b682004-10-07 04:16:33 +0000247 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Chris Lattner25de4e52006-11-01 18:03:33 +0000248 GS.HasPHIUser = true;
Reid Spencere4d87aa2006-12-23 06:05:41 +0000249 } else if (isa<CmpInst>(I)) {
Rafael Espindolac4440e32011-01-19 16:32:21 +0000250 GS.isCompared = true;
Nick Lewycky1f237b02011-05-29 18:41:56 +0000251 } else if (const MemTransferInst *MTI = dyn_cast<MemTransferInst>(I)) {
252 if (MTI->isVolatile()) return true;
Gabor Greif9e4f2432010-06-24 14:42:01 +0000253 if (MTI->getArgOperand(0) == V)
Eric Christopher551754c2010-04-16 23:37:20 +0000254 GS.StoredType = GlobalStatus::isStored;
Gabor Greif9e4f2432010-06-24 14:42:01 +0000255 if (MTI->getArgOperand(1) == V)
Chris Lattner35c81b02005-02-27 18:58:52 +0000256 GS.isLoaded = true;
Nick Lewycky1f237b02011-05-29 18:41:56 +0000257 } else if (const MemSetInst *MSI = dyn_cast<MemSetInst>(I)) {
258 assert(MSI->getArgOperand(0) == V && "Memset only takes one pointer!");
259 if (MSI->isVolatile()) return true;
Chris Lattner35c81b02005-02-27 18:58:52 +0000260 GS.StoredType = GlobalStatus::isStored;
Chris Lattner7a90b682004-10-07 04:16:33 +0000261 } else {
262 return true; // Any other non-load instruction might take address!
Chris Lattner9ce30002004-07-20 03:58:07 +0000263 }
Gabor Greife6642672010-07-09 16:51:20 +0000264 } else if (const Constant *C = dyn_cast<Constant>(U)) {
Chris Lattner553ca522005-06-15 21:11:48 +0000265 GS.HasNonInstructionUser = true;
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000266 // We might have a dead and dangling constant hanging off of here.
Jay Foade3acf152009-06-09 21:37:11 +0000267 if (!SafeToDestroyConstant(C))
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000268 return true;
Chris Lattner079236d2004-02-25 21:34:36 +0000269 } else {
Chris Lattner553ca522005-06-15 21:11:48 +0000270 GS.HasNonInstructionUser = true;
271 // Otherwise must be some other user.
Chris Lattner079236d2004-02-25 21:34:36 +0000272 return true;
273 }
Gabor Greife6642672010-07-09 16:51:20 +0000274 }
Chris Lattner079236d2004-02-25 21:34:36 +0000275
276 return false;
277}
278
Chris Lattner7b550cc2009-11-06 04:27:31 +0000279static Constant *getAggregateConstantElement(Constant *Agg, Constant *Idx) {
Chris Lattner670c8892004-10-08 17:32:09 +0000280 ConstantInt *CI = dyn_cast<ConstantInt>(Idx);
281 if (!CI) return 0;
Reid Spencerb83eb642006-10-20 07:07:24 +0000282 unsigned IdxV = CI->getZExtValue();
Chris Lattner7a90b682004-10-07 04:16:33 +0000283
Chris Lattner670c8892004-10-08 17:32:09 +0000284 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Agg)) {
285 if (IdxV < CS->getNumOperands()) return CS->getOperand(IdxV);
286 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Agg)) {
287 if (IdxV < CA->getNumOperands()) return CA->getOperand(IdxV);
Reid Spencer9d6565a2007-02-15 02:26:10 +0000288 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Agg)) {
Chris Lattner670c8892004-10-08 17:32:09 +0000289 if (IdxV < CP->getNumOperands()) return CP->getOperand(IdxV);
Chris Lattner7a7ed022004-10-16 18:09:00 +0000290 } else if (isa<ConstantAggregateZero>(Agg)) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000291 if (StructType *STy = dyn_cast<StructType>(Agg->getType())) {
Chris Lattner670c8892004-10-08 17:32:09 +0000292 if (IdxV < STy->getNumElements())
Owen Andersona7235ea2009-07-31 20:28:14 +0000293 return Constant::getNullValue(STy->getElementType(IdxV));
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000294 } else if (SequentialType *STy =
Chris Lattner670c8892004-10-08 17:32:09 +0000295 dyn_cast<SequentialType>(Agg->getType())) {
Owen Andersona7235ea2009-07-31 20:28:14 +0000296 return Constant::getNullValue(STy->getElementType());
Chris Lattner670c8892004-10-08 17:32:09 +0000297 }
Chris Lattner7a7ed022004-10-16 18:09:00 +0000298 } else if (isa<UndefValue>(Agg)) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000299 if (StructType *STy = dyn_cast<StructType>(Agg->getType())) {
Chris Lattner7a7ed022004-10-16 18:09:00 +0000300 if (IdxV < STy->getNumElements())
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000301 return UndefValue::get(STy->getElementType(IdxV));
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000302 } else if (SequentialType *STy =
Chris Lattner7a7ed022004-10-16 18:09:00 +0000303 dyn_cast<SequentialType>(Agg->getType())) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000304 return UndefValue::get(STy->getElementType());
Chris Lattner7a7ed022004-10-16 18:09:00 +0000305 }
Chris Lattner670c8892004-10-08 17:32:09 +0000306 }
307 return 0;
308}
Chris Lattner7a90b682004-10-07 04:16:33 +0000309
Chris Lattner7a90b682004-10-07 04:16:33 +0000310
Chris Lattnere47ba742004-10-06 20:57:02 +0000311/// CleanupConstantGlobalUsers - We just marked GV constant. Loop over all
312/// users of the global, cleaning up the obvious ones. This is largely just a
Chris Lattner031955d2004-10-10 16:43:46 +0000313/// quick scan over the use list to clean up the easy and obvious cruft. This
314/// returns true if it made a change.
Chris Lattner7b550cc2009-11-06 04:27:31 +0000315static bool CleanupConstantGlobalUsers(Value *V, Constant *Init) {
Chris Lattner031955d2004-10-10 16:43:46 +0000316 bool Changed = false;
Chris Lattner7a90b682004-10-07 04:16:33 +0000317 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;) {
318 User *U = *UI++;
Misha Brukmanfd939082005-04-21 23:48:37 +0000319
Chris Lattner7a90b682004-10-07 04:16:33 +0000320 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
Chris Lattner35c81b02005-02-27 18:58:52 +0000321 if (Init) {
322 // Replace the load with the initializer.
323 LI->replaceAllUsesWith(Init);
324 LI->eraseFromParent();
325 Changed = true;
326 }
Chris Lattner7a90b682004-10-07 04:16:33 +0000327 } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
Chris Lattnere47ba742004-10-06 20:57:02 +0000328 // Store must be unreachable or storing Init into the global.
Chris Lattner7a7ed022004-10-16 18:09:00 +0000329 SI->eraseFromParent();
Chris Lattner031955d2004-10-10 16:43:46 +0000330 Changed = true;
Chris Lattner7a90b682004-10-07 04:16:33 +0000331 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
332 if (CE->getOpcode() == Instruction::GetElementPtr) {
Chris Lattneraae4a1c2005-09-26 07:34:35 +0000333 Constant *SubInit = 0;
334 if (Init)
Dan Gohmanc6f69e92009-10-05 16:36:26 +0000335 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
Chris Lattner7b550cc2009-11-06 04:27:31 +0000336 Changed |= CleanupConstantGlobalUsers(CE, SubInit);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000337 } else if (CE->getOpcode() == Instruction::BitCast &&
Duncan Sands1df98592010-02-16 11:11:14 +0000338 CE->getType()->isPointerTy()) {
Chris Lattner35c81b02005-02-27 18:58:52 +0000339 // Pointer cast, delete any stores and memsets to the global.
Chris Lattner7b550cc2009-11-06 04:27:31 +0000340 Changed |= CleanupConstantGlobalUsers(CE, 0);
Chris Lattner35c81b02005-02-27 18:58:52 +0000341 }
342
343 if (CE->use_empty()) {
344 CE->destroyConstant();
345 Changed = true;
Chris Lattner7a90b682004-10-07 04:16:33 +0000346 }
347 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
Chris Lattner7b52fe72007-11-09 17:33:02 +0000348 // Do not transform "gepinst (gep constexpr (GV))" here, because forming
349 // "gepconstexpr (gep constexpr (GV))" will cause the two gep's to fold
350 // and will invalidate our notion of what Init is.
Chris Lattner19450242007-11-13 21:46:23 +0000351 Constant *SubInit = 0;
Chris Lattner7b52fe72007-11-09 17:33:02 +0000352 if (!isa<ConstantExpr>(GEP->getOperand(0))) {
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000353 ConstantExpr *CE =
Chris Lattner7b550cc2009-11-06 04:27:31 +0000354 dyn_cast_or_null<ConstantExpr>(ConstantFoldInstruction(GEP));
Chris Lattner7b52fe72007-11-09 17:33:02 +0000355 if (Init && CE && CE->getOpcode() == Instruction::GetElementPtr)
Dan Gohmanc6f69e92009-10-05 16:36:26 +0000356 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
Chris Lattner7b52fe72007-11-09 17:33:02 +0000357 }
Chris Lattner7b550cc2009-11-06 04:27:31 +0000358 Changed |= CleanupConstantGlobalUsers(GEP, SubInit);
Chris Lattnerc4d81b02004-10-10 16:47:33 +0000359
Chris Lattner031955d2004-10-10 16:43:46 +0000360 if (GEP->use_empty()) {
Chris Lattner7a7ed022004-10-16 18:09:00 +0000361 GEP->eraseFromParent();
Chris Lattner031955d2004-10-10 16:43:46 +0000362 Changed = true;
363 }
Chris Lattner35c81b02005-02-27 18:58:52 +0000364 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U)) { // memset/cpy/mv
365 if (MI->getRawDest() == V) {
366 MI->eraseFromParent();
367 Changed = true;
368 }
369
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000370 } else if (Constant *C = dyn_cast<Constant>(U)) {
371 // If we have a chain of dead constantexprs or other things dangling from
372 // us, and if they are all dead, nuke them without remorse.
Jay Foade3acf152009-06-09 21:37:11 +0000373 if (SafeToDestroyConstant(C)) {
Devang Patel743cdf82009-03-06 01:37:41 +0000374 C->destroyConstant();
Chris Lattner35c81b02005-02-27 18:58:52 +0000375 // This could have invalidated UI, start over from scratch.
Chris Lattner7b550cc2009-11-06 04:27:31 +0000376 CleanupConstantGlobalUsers(V, Init);
Chris Lattner031955d2004-10-10 16:43:46 +0000377 return true;
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000378 }
Chris Lattnere47ba742004-10-06 20:57:02 +0000379 }
380 }
Chris Lattner031955d2004-10-10 16:43:46 +0000381 return Changed;
Chris Lattnere47ba742004-10-06 20:57:02 +0000382}
383
Chris Lattner941db492008-01-14 02:09:12 +0000384/// isSafeSROAElementUse - Return true if the specified instruction is a safe
385/// user of a derived expression from a global that we want to SROA.
386static bool isSafeSROAElementUse(Value *V) {
387 // We might have a dead and dangling constant hanging off of here.
388 if (Constant *C = dyn_cast<Constant>(V))
Jay Foade3acf152009-06-09 21:37:11 +0000389 return SafeToDestroyConstant(C);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000390
Chris Lattner941db492008-01-14 02:09:12 +0000391 Instruction *I = dyn_cast<Instruction>(V);
392 if (!I) return false;
393
394 // Loads are ok.
395 if (isa<LoadInst>(I)) return true;
396
397 // Stores *to* the pointer are ok.
398 if (StoreInst *SI = dyn_cast<StoreInst>(I))
399 return SI->getOperand(0) != V;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000400
Chris Lattner941db492008-01-14 02:09:12 +0000401 // Otherwise, it must be a GEP.
402 GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I);
403 if (GEPI == 0) return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000404
Chris Lattner941db492008-01-14 02:09:12 +0000405 if (GEPI->getNumOperands() < 3 || !isa<Constant>(GEPI->getOperand(1)) ||
406 !cast<Constant>(GEPI->getOperand(1))->isNullValue())
407 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000408
Chris Lattner941db492008-01-14 02:09:12 +0000409 for (Value::use_iterator I = GEPI->use_begin(), E = GEPI->use_end();
410 I != E; ++I)
411 if (!isSafeSROAElementUse(*I))
412 return false;
Chris Lattner727c2102008-01-14 01:31:05 +0000413 return true;
414}
415
Chris Lattner941db492008-01-14 02:09:12 +0000416
417/// IsUserOfGlobalSafeForSRA - U is a direct user of the specified global value.
418/// Look at it and its uses and decide whether it is safe to SROA this global.
419///
420static bool IsUserOfGlobalSafeForSRA(User *U, GlobalValue *GV) {
421 // The user of the global must be a GEP Inst or a ConstantExpr GEP.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000422 if (!isa<GetElementPtrInst>(U) &&
423 (!isa<ConstantExpr>(U) ||
Chris Lattner941db492008-01-14 02:09:12 +0000424 cast<ConstantExpr>(U)->getOpcode() != Instruction::GetElementPtr))
425 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000426
Chris Lattner941db492008-01-14 02:09:12 +0000427 // Check to see if this ConstantExpr GEP is SRA'able. In particular, we
428 // don't like < 3 operand CE's, and we don't like non-constant integer
429 // indices. This enforces that all uses are 'gep GV, 0, C, ...' for some
430 // value of C.
431 if (U->getNumOperands() < 3 || !isa<Constant>(U->getOperand(1)) ||
432 !cast<Constant>(U->getOperand(1))->isNullValue() ||
433 !isa<ConstantInt>(U->getOperand(2)))
434 return false;
435
436 gep_type_iterator GEPI = gep_type_begin(U), E = gep_type_end(U);
437 ++GEPI; // Skip over the pointer index.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000438
Chris Lattner941db492008-01-14 02:09:12 +0000439 // If this is a use of an array allocation, do a bit more checking for sanity.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000440 if (ArrayType *AT = dyn_cast<ArrayType>(*GEPI)) {
Chris Lattner941db492008-01-14 02:09:12 +0000441 uint64_t NumElements = AT->getNumElements();
442 ConstantInt *Idx = cast<ConstantInt>(U->getOperand(2));
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000443
Chris Lattner941db492008-01-14 02:09:12 +0000444 // Check to make sure that index falls within the array. If not,
445 // something funny is going on, so we won't do the optimization.
446 //
447 if (Idx->getZExtValue() >= NumElements)
448 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000449
Chris Lattner941db492008-01-14 02:09:12 +0000450 // We cannot scalar repl this level of the array unless any array
451 // sub-indices are in-range constants. In particular, consider:
452 // A[0][i]. We cannot know that the user isn't doing invalid things like
453 // allowing i to index an out-of-range subscript that accesses A[1].
454 //
455 // Scalar replacing *just* the outer index of the array is probably not
456 // going to be a win anyway, so just give up.
457 for (++GEPI; // Skip array index.
Dan Gohman6874a2a2009-08-18 14:58:19 +0000458 GEPI != E;
Chris Lattner941db492008-01-14 02:09:12 +0000459 ++GEPI) {
460 uint64_t NumElements;
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000461 if (ArrayType *SubArrayTy = dyn_cast<ArrayType>(*GEPI))
Chris Lattner941db492008-01-14 02:09:12 +0000462 NumElements = SubArrayTy->getNumElements();
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000463 else if (VectorType *SubVectorTy = dyn_cast<VectorType>(*GEPI))
Dan Gohman6874a2a2009-08-18 14:58:19 +0000464 NumElements = SubVectorTy->getNumElements();
465 else {
Duncan Sands1df98592010-02-16 11:11:14 +0000466 assert((*GEPI)->isStructTy() &&
Dan Gohman6874a2a2009-08-18 14:58:19 +0000467 "Indexed GEP type is not array, vector, or struct!");
468 continue;
469 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000470
Chris Lattner941db492008-01-14 02:09:12 +0000471 ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPI.getOperand());
472 if (!IdxVal || IdxVal->getZExtValue() >= NumElements)
473 return false;
474 }
475 }
476
477 for (Value::use_iterator I = U->use_begin(), E = U->use_end(); I != E; ++I)
478 if (!isSafeSROAElementUse(*I))
479 return false;
480 return true;
481}
482
483/// GlobalUsersSafeToSRA - Look at all uses of the global and decide whether it
484/// is safe for us to perform this transformation.
485///
486static bool GlobalUsersSafeToSRA(GlobalValue *GV) {
487 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end();
488 UI != E; ++UI) {
489 if (!IsUserOfGlobalSafeForSRA(*UI, GV))
490 return false;
491 }
492 return true;
493}
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000494
Chris Lattner941db492008-01-14 02:09:12 +0000495
Chris Lattner670c8892004-10-08 17:32:09 +0000496/// SRAGlobal - Perform scalar replacement of aggregates on the specified global
497/// variable. This opens the door for other optimizations by exposing the
498/// behavior of the program in a more fine-grained way. We have determined that
499/// this transformation is safe already. We return the first global variable we
500/// insert so that the caller can reprocess it.
Chris Lattner7b550cc2009-11-06 04:27:31 +0000501static GlobalVariable *SRAGlobal(GlobalVariable *GV, const TargetData &TD) {
Chris Lattner727c2102008-01-14 01:31:05 +0000502 // Make sure this global only has simple uses that we can SRA.
Chris Lattner941db492008-01-14 02:09:12 +0000503 if (!GlobalUsersSafeToSRA(GV))
Chris Lattner727c2102008-01-14 01:31:05 +0000504 return 0;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000505
Rafael Espindolabb46f522009-01-15 20:18:42 +0000506 assert(GV->hasLocalLinkage() && !GV->isConstant());
Chris Lattner670c8892004-10-08 17:32:09 +0000507 Constant *Init = GV->getInitializer();
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000508 Type *Ty = Init->getType();
Misha Brukmanfd939082005-04-21 23:48:37 +0000509
Chris Lattner670c8892004-10-08 17:32:09 +0000510 std::vector<GlobalVariable*> NewGlobals;
511 Module::GlobalListType &Globals = GV->getParent()->getGlobalList();
512
Chris Lattner998182b2008-04-26 07:40:11 +0000513 // Get the alignment of the global, either explicit or target-specific.
514 unsigned StartAlignment = GV->getAlignment();
515 if (StartAlignment == 0)
516 StartAlignment = TD.getABITypeAlignment(GV->getType());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000517
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000518 if (StructType *STy = dyn_cast<StructType>(Ty)) {
Chris Lattner670c8892004-10-08 17:32:09 +0000519 NewGlobals.reserve(STy->getNumElements());
Chris Lattner998182b2008-04-26 07:40:11 +0000520 const StructLayout &Layout = *TD.getStructLayout(STy);
Chris Lattner670c8892004-10-08 17:32:09 +0000521 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
522 Constant *In = getAggregateConstantElement(Init,
Chris Lattner7b550cc2009-11-06 04:27:31 +0000523 ConstantInt::get(Type::getInt32Ty(STy->getContext()), i));
Chris Lattner670c8892004-10-08 17:32:09 +0000524 assert(In && "Couldn't get element of initializer?");
Chris Lattner7b550cc2009-11-06 04:27:31 +0000525 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(i), false,
Chris Lattner670c8892004-10-08 17:32:09 +0000526 GlobalVariable::InternalLinkage,
Daniel Dunbarfe09b202009-07-30 17:37:43 +0000527 In, GV->getName()+"."+Twine(i),
Matthijs Kooijmanbc1f9892008-07-17 11:59:53 +0000528 GV->isThreadLocal(),
Owen Anderson3d29df32009-07-08 01:26:06 +0000529 GV->getType()->getAddressSpace());
Chris Lattner670c8892004-10-08 17:32:09 +0000530 Globals.insert(GV, NGV);
531 NewGlobals.push_back(NGV);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000532
Chris Lattner998182b2008-04-26 07:40:11 +0000533 // Calculate the known alignment of the field. If the original aggregate
534 // had 256 byte alignment for example, something might depend on that:
535 // propagate info to each field.
536 uint64_t FieldOffset = Layout.getElementOffset(i);
537 unsigned NewAlign = (unsigned)MinAlign(StartAlignment, FieldOffset);
538 if (NewAlign > TD.getABITypeAlignment(STy->getElementType(i)))
539 NGV->setAlignment(NewAlign);
Chris Lattner670c8892004-10-08 17:32:09 +0000540 }
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000541 } else if (SequentialType *STy = dyn_cast<SequentialType>(Ty)) {
Chris Lattner670c8892004-10-08 17:32:09 +0000542 unsigned NumElements = 0;
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000543 if (ArrayType *ATy = dyn_cast<ArrayType>(STy))
Chris Lattner670c8892004-10-08 17:32:09 +0000544 NumElements = ATy->getNumElements();
Chris Lattner670c8892004-10-08 17:32:09 +0000545 else
Chris Lattner998182b2008-04-26 07:40:11 +0000546 NumElements = cast<VectorType>(STy)->getNumElements();
Chris Lattner670c8892004-10-08 17:32:09 +0000547
Chris Lattner1f21ef12005-02-23 16:53:04 +0000548 if (NumElements > 16 && GV->hasNUsesOrMore(16))
Chris Lattnerd514d822005-02-01 01:23:31 +0000549 return 0; // It's not worth it.
Chris Lattner670c8892004-10-08 17:32:09 +0000550 NewGlobals.reserve(NumElements);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000551
Duncan Sands777d2302009-05-09 07:06:46 +0000552 uint64_t EltSize = TD.getTypeAllocSize(STy->getElementType());
Chris Lattner998182b2008-04-26 07:40:11 +0000553 unsigned EltAlign = TD.getABITypeAlignment(STy->getElementType());
Chris Lattner670c8892004-10-08 17:32:09 +0000554 for (unsigned i = 0, e = NumElements; i != e; ++i) {
555 Constant *In = getAggregateConstantElement(Init,
Chris Lattner7b550cc2009-11-06 04:27:31 +0000556 ConstantInt::get(Type::getInt32Ty(Init->getContext()), i));
Chris Lattner670c8892004-10-08 17:32:09 +0000557 assert(In && "Couldn't get element of initializer?");
558
Chris Lattner7b550cc2009-11-06 04:27:31 +0000559 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(), false,
Chris Lattner670c8892004-10-08 17:32:09 +0000560 GlobalVariable::InternalLinkage,
Daniel Dunbarfe09b202009-07-30 17:37:43 +0000561 In, GV->getName()+"."+Twine(i),
Matthijs Kooijmanbc1f9892008-07-17 11:59:53 +0000562 GV->isThreadLocal(),
Owen Andersone9b11b42009-07-08 19:03:57 +0000563 GV->getType()->getAddressSpace());
Chris Lattner670c8892004-10-08 17:32:09 +0000564 Globals.insert(GV, NGV);
565 NewGlobals.push_back(NGV);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000566
Chris Lattner998182b2008-04-26 07:40:11 +0000567 // Calculate the known alignment of the field. If the original aggregate
568 // had 256 byte alignment for example, something might depend on that:
569 // propagate info to each field.
570 unsigned NewAlign = (unsigned)MinAlign(StartAlignment, EltSize*i);
571 if (NewAlign > EltAlign)
572 NGV->setAlignment(NewAlign);
Chris Lattner670c8892004-10-08 17:32:09 +0000573 }
574 }
575
576 if (NewGlobals.empty())
577 return 0;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000578
David Greene3215b0e2010-01-05 01:28:05 +0000579 DEBUG(dbgs() << "PERFORMING GLOBAL SRA ON: " << *GV);
Chris Lattner30ba5692004-10-11 05:54:41 +0000580
Chris Lattner7b550cc2009-11-06 04:27:31 +0000581 Constant *NullInt =Constant::getNullValue(Type::getInt32Ty(GV->getContext()));
Chris Lattner670c8892004-10-08 17:32:09 +0000582
583 // Loop over all of the uses of the global, replacing the constantexpr geps,
584 // with smaller constantexpr geps or direct references.
585 while (!GV->use_empty()) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000586 User *GEP = GV->use_back();
587 assert(((isa<ConstantExpr>(GEP) &&
588 cast<ConstantExpr>(GEP)->getOpcode()==Instruction::GetElementPtr)||
589 isa<GetElementPtrInst>(GEP)) && "NonGEP CE's are not SRAable!");
Misha Brukmanfd939082005-04-21 23:48:37 +0000590
Chris Lattner670c8892004-10-08 17:32:09 +0000591 // Ignore the 1th operand, which has to be zero or else the program is quite
592 // broken (undefined). Get the 2nd operand, which is the structure or array
593 // index.
Reid Spencerb83eb642006-10-20 07:07:24 +0000594 unsigned Val = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
Chris Lattner670c8892004-10-08 17:32:09 +0000595 if (Val >= NewGlobals.size()) Val = 0; // Out of bound array access.
596
Chris Lattner30ba5692004-10-11 05:54:41 +0000597 Value *NewPtr = NewGlobals[Val];
Chris Lattner670c8892004-10-08 17:32:09 +0000598
599 // Form a shorter GEP if needed.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000600 if (GEP->getNumOperands() > 3) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000601 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEP)) {
Chris Lattner55eb1c42007-01-31 04:40:53 +0000602 SmallVector<Constant*, 8> Idxs;
Chris Lattner30ba5692004-10-11 05:54:41 +0000603 Idxs.push_back(NullInt);
604 for (unsigned i = 3, e = CE->getNumOperands(); i != e; ++i)
605 Idxs.push_back(CE->getOperand(i));
Jay Foaddab3d292011-07-21 14:31:17 +0000606 NewPtr = ConstantExpr::getGetElementPtr(cast<Constant>(NewPtr), Idxs);
Chris Lattner30ba5692004-10-11 05:54:41 +0000607 } else {
608 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(GEP);
Chris Lattner699d1442007-01-31 19:59:55 +0000609 SmallVector<Value*, 8> Idxs;
Chris Lattner30ba5692004-10-11 05:54:41 +0000610 Idxs.push_back(NullInt);
611 for (unsigned i = 3, e = GEPI->getNumOperands(); i != e; ++i)
612 Idxs.push_back(GEPI->getOperand(i));
Jay Foada9203102011-07-25 09:48:08 +0000613 NewPtr = GetElementPtrInst::Create(NewPtr, Idxs,
Daniel Dunbarfe09b202009-07-30 17:37:43 +0000614 GEPI->getName()+"."+Twine(Val),GEPI);
Chris Lattner30ba5692004-10-11 05:54:41 +0000615 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000616 }
Chris Lattner30ba5692004-10-11 05:54:41 +0000617 GEP->replaceAllUsesWith(NewPtr);
618
619 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(GEP))
Chris Lattner7a7ed022004-10-16 18:09:00 +0000620 GEPI->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +0000621 else
622 cast<ConstantExpr>(GEP)->destroyConstant();
Chris Lattner670c8892004-10-08 17:32:09 +0000623 }
624
Chris Lattnere40e2d12004-10-08 20:25:55 +0000625 // Delete the old global, now that it is dead.
626 Globals.erase(GV);
Chris Lattner670c8892004-10-08 17:32:09 +0000627 ++NumSRA;
Chris Lattner30ba5692004-10-11 05:54:41 +0000628
629 // Loop over the new globals array deleting any globals that are obviously
630 // dead. This can arise due to scalarization of a structure or an array that
631 // has elements that are dead.
632 unsigned FirstGlobal = 0;
633 for (unsigned i = 0, e = NewGlobals.size(); i != e; ++i)
634 if (NewGlobals[i]->use_empty()) {
635 Globals.erase(NewGlobals[i]);
636 if (FirstGlobal == i) ++FirstGlobal;
637 }
638
639 return FirstGlobal != NewGlobals.size() ? NewGlobals[FirstGlobal] : 0;
Chris Lattner670c8892004-10-08 17:32:09 +0000640}
641
Chris Lattner9b34a612004-10-09 21:48:45 +0000642/// AllUsesOfValueWillTrapIfNull - Return true if all users of the specified
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000643/// value will trap if the value is dynamically null. PHIs keeps track of any
Chris Lattner81686182007-09-13 16:30:19 +0000644/// phi nodes we've seen to avoid reprocessing them.
Gabor Greif6ce02b52010-04-06 19:24:18 +0000645static bool AllUsesOfValueWillTrapIfNull(const Value *V,
646 SmallPtrSet<const PHINode*, 8> &PHIs) {
647 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;
Gabor Greifa01d6db2010-04-06 19:14:05 +0000648 ++UI) {
Gabor Greif6ce02b52010-04-06 19:24:18 +0000649 const User *U = *UI;
Gabor Greifa01d6db2010-04-06 19:14:05 +0000650
651 if (isa<LoadInst>(U)) {
Chris Lattner9b34a612004-10-09 21:48:45 +0000652 // Will trap.
Gabor Greif6ce02b52010-04-06 19:24:18 +0000653 } else if (const StoreInst *SI = dyn_cast<StoreInst>(U)) {
Chris Lattner9b34a612004-10-09 21:48:45 +0000654 if (SI->getOperand(0) == V) {
Gabor Greifa01d6db2010-04-06 19:14:05 +0000655 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner9b34a612004-10-09 21:48:45 +0000656 return false; // Storing the value.
657 }
Gabor Greif6ce02b52010-04-06 19:24:18 +0000658 } else if (const CallInst *CI = dyn_cast<CallInst>(U)) {
Gabor Greif654c06f2010-03-20 21:00:25 +0000659 if (CI->getCalledValue() != V) {
Gabor Greifa01d6db2010-04-06 19:14:05 +0000660 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner9b34a612004-10-09 21:48:45 +0000661 return false; // Not calling the ptr
662 }
Gabor Greif6ce02b52010-04-06 19:24:18 +0000663 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(U)) {
Gabor Greif654c06f2010-03-20 21:00:25 +0000664 if (II->getCalledValue() != V) {
Gabor Greifa01d6db2010-04-06 19:14:05 +0000665 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner9b34a612004-10-09 21:48:45 +0000666 return false; // Not calling the ptr
667 }
Gabor Greif6ce02b52010-04-06 19:24:18 +0000668 } else if (const BitCastInst *CI = dyn_cast<BitCastInst>(U)) {
Chris Lattner81686182007-09-13 16:30:19 +0000669 if (!AllUsesOfValueWillTrapIfNull(CI, PHIs)) return false;
Gabor Greif6ce02b52010-04-06 19:24:18 +0000670 } else if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
Chris Lattner81686182007-09-13 16:30:19 +0000671 if (!AllUsesOfValueWillTrapIfNull(GEPI, PHIs)) return false;
Gabor Greif6ce02b52010-04-06 19:24:18 +0000672 } else if (const PHINode *PN = dyn_cast<PHINode>(U)) {
Chris Lattner81686182007-09-13 16:30:19 +0000673 // If we've already seen this phi node, ignore it, it has already been
674 // checked.
Jakob Stoklund Olesenb489d0f2010-01-29 23:54:14 +0000675 if (PHIs.insert(PN) && !AllUsesOfValueWillTrapIfNull(PN, PHIs))
676 return false;
Gabor Greifa01d6db2010-04-06 19:14:05 +0000677 } else if (isa<ICmpInst>(U) &&
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000678 isa<ConstantPointerNull>(UI->getOperand(1))) {
Nick Lewyckye7ee59b2010-02-25 06:39:10 +0000679 // Ignore icmp X, null
Chris Lattner9b34a612004-10-09 21:48:45 +0000680 } else {
Gabor Greifa01d6db2010-04-06 19:14:05 +0000681 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner9b34a612004-10-09 21:48:45 +0000682 return false;
683 }
Gabor Greifa01d6db2010-04-06 19:14:05 +0000684 }
Chris Lattner9b34a612004-10-09 21:48:45 +0000685 return true;
686}
687
688/// AllUsesOfLoadedValueWillTrapIfNull - Return true if all uses of any loads
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000689/// from GV will trap if the loaded value is null. Note that this also permits
690/// comparisons of the loaded value against null, as a special case.
Gabor Greif6ce02b52010-04-06 19:24:18 +0000691static bool AllUsesOfLoadedValueWillTrapIfNull(const GlobalVariable *GV) {
692 for (Value::const_use_iterator UI = GV->use_begin(), E = GV->use_end();
Gabor Greifa01d6db2010-04-06 19:14:05 +0000693 UI != E; ++UI) {
Gabor Greif6ce02b52010-04-06 19:24:18 +0000694 const User *U = *UI;
Gabor Greifa01d6db2010-04-06 19:14:05 +0000695
Gabor Greif6ce02b52010-04-06 19:24:18 +0000696 if (const LoadInst *LI = dyn_cast<LoadInst>(U)) {
697 SmallPtrSet<const PHINode*, 8> PHIs;
Chris Lattner81686182007-09-13 16:30:19 +0000698 if (!AllUsesOfValueWillTrapIfNull(LI, PHIs))
Chris Lattner9b34a612004-10-09 21:48:45 +0000699 return false;
Gabor Greifa01d6db2010-04-06 19:14:05 +0000700 } else if (isa<StoreInst>(U)) {
Chris Lattner9b34a612004-10-09 21:48:45 +0000701 // Ignore stores to the global.
702 } else {
703 // We don't know or understand this user, bail out.
Gabor Greifa01d6db2010-04-06 19:14:05 +0000704 //cerr << "UNKNOWN USER OF GLOBAL!: " << *U;
Chris Lattner9b34a612004-10-09 21:48:45 +0000705 return false;
706 }
Gabor Greifa01d6db2010-04-06 19:14:05 +0000707 }
Chris Lattner9b34a612004-10-09 21:48:45 +0000708 return true;
709}
710
Chris Lattner7b550cc2009-11-06 04:27:31 +0000711static bool OptimizeAwayTrappingUsesOfValue(Value *V, Constant *NewV) {
Chris Lattner708148e2004-10-10 23:14:11 +0000712 bool Changed = false;
713 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ) {
714 Instruction *I = cast<Instruction>(*UI++);
715 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
716 LI->setOperand(0, NewV);
717 Changed = true;
718 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
719 if (SI->getOperand(1) == V) {
720 SI->setOperand(1, NewV);
721 Changed = true;
722 }
723 } else if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
Gabor Greiffa1f5c22010-04-06 18:45:08 +0000724 CallSite CS(I);
725 if (CS.getCalledValue() == V) {
Chris Lattner708148e2004-10-10 23:14:11 +0000726 // Calling through the pointer! Turn into a direct call, but be careful
727 // that the pointer is not also being passed as an argument.
Gabor Greiffa1f5c22010-04-06 18:45:08 +0000728 CS.setCalledFunction(NewV);
Chris Lattner708148e2004-10-10 23:14:11 +0000729 Changed = true;
730 bool PassedAsArg = false;
Gabor Greiffa1f5c22010-04-06 18:45:08 +0000731 for (unsigned i = 0, e = CS.arg_size(); i != e; ++i)
732 if (CS.getArgument(i) == V) {
Chris Lattner708148e2004-10-10 23:14:11 +0000733 PassedAsArg = true;
Gabor Greiffa1f5c22010-04-06 18:45:08 +0000734 CS.setArgument(i, NewV);
Chris Lattner708148e2004-10-10 23:14:11 +0000735 }
736
737 if (PassedAsArg) {
738 // Being passed as an argument also. Be careful to not invalidate UI!
739 UI = V->use_begin();
740 }
741 }
742 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
743 Changed |= OptimizeAwayTrappingUsesOfValue(CI,
Owen Andersonbaf3c402009-07-29 18:55:55 +0000744 ConstantExpr::getCast(CI->getOpcode(),
Chris Lattner7b550cc2009-11-06 04:27:31 +0000745 NewV, CI->getType()));
Chris Lattner708148e2004-10-10 23:14:11 +0000746 if (CI->use_empty()) {
747 Changed = true;
Chris Lattner7a7ed022004-10-16 18:09:00 +0000748 CI->eraseFromParent();
Chris Lattner708148e2004-10-10 23:14:11 +0000749 }
750 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
751 // Should handle GEP here.
Chris Lattner55eb1c42007-01-31 04:40:53 +0000752 SmallVector<Constant*, 8> Idxs;
753 Idxs.reserve(GEPI->getNumOperands()-1);
Gabor Greif5e463212008-05-29 01:59:18 +0000754 for (User::op_iterator i = GEPI->op_begin() + 1, e = GEPI->op_end();
755 i != e; ++i)
756 if (Constant *C = dyn_cast<Constant>(*i))
Chris Lattner55eb1c42007-01-31 04:40:53 +0000757 Idxs.push_back(C);
Chris Lattner708148e2004-10-10 23:14:11 +0000758 else
759 break;
Chris Lattner55eb1c42007-01-31 04:40:53 +0000760 if (Idxs.size() == GEPI->getNumOperands()-1)
Chris Lattner708148e2004-10-10 23:14:11 +0000761 Changed |= OptimizeAwayTrappingUsesOfValue(GEPI,
Jay Foaddab3d292011-07-21 14:31:17 +0000762 ConstantExpr::getGetElementPtr(NewV, Idxs));
Chris Lattner708148e2004-10-10 23:14:11 +0000763 if (GEPI->use_empty()) {
764 Changed = true;
Chris Lattner7a7ed022004-10-16 18:09:00 +0000765 GEPI->eraseFromParent();
Chris Lattner708148e2004-10-10 23:14:11 +0000766 }
767 }
768 }
769
770 return Changed;
771}
772
773
774/// OptimizeAwayTrappingUsesOfLoads - The specified global has only one non-null
775/// value stored into it. If there are uses of the loaded value that would trap
776/// if the loaded value is dynamically null, then we know that they cannot be
777/// reachable with a null optimize away the load.
Chris Lattner7b550cc2009-11-06 04:27:31 +0000778static bool OptimizeAwayTrappingUsesOfLoads(GlobalVariable *GV, Constant *LV) {
Chris Lattner708148e2004-10-10 23:14:11 +0000779 bool Changed = false;
780
Chris Lattner92c6bd22009-01-14 00:12:58 +0000781 // Keep track of whether we are able to remove all the uses of the global
782 // other than the store that defines it.
783 bool AllNonStoreUsesGone = true;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000784
Chris Lattner708148e2004-10-10 23:14:11 +0000785 // Replace all uses of loads with uses of uses of the stored value.
Chris Lattner92c6bd22009-01-14 00:12:58 +0000786 for (Value::use_iterator GUI = GV->use_begin(), E = GV->use_end(); GUI != E;){
787 User *GlobalUser = *GUI++;
788 if (LoadInst *LI = dyn_cast<LoadInst>(GlobalUser)) {
Chris Lattner7b550cc2009-11-06 04:27:31 +0000789 Changed |= OptimizeAwayTrappingUsesOfValue(LI, LV);
Chris Lattner92c6bd22009-01-14 00:12:58 +0000790 // If we were able to delete all uses of the loads
791 if (LI->use_empty()) {
792 LI->eraseFromParent();
793 Changed = true;
794 } else {
795 AllNonStoreUsesGone = false;
796 }
797 } else if (isa<StoreInst>(GlobalUser)) {
798 // Ignore the store that stores "LV" to the global.
799 assert(GlobalUser->getOperand(1) == GV &&
800 "Must be storing *to* the global");
Chris Lattner708148e2004-10-10 23:14:11 +0000801 } else {
Chris Lattner92c6bd22009-01-14 00:12:58 +0000802 AllNonStoreUsesGone = false;
803
804 // If we get here we could have other crazy uses that are transitively
805 // loaded.
806 assert((isa<PHINode>(GlobalUser) || isa<SelectInst>(GlobalUser) ||
Chris Lattner98a42b22011-05-22 07:15:13 +0000807 isa<ConstantExpr>(GlobalUser) || isa<CmpInst>(GlobalUser)) &&
808 "Only expect load and stores!");
Chris Lattner708148e2004-10-10 23:14:11 +0000809 }
Chris Lattner92c6bd22009-01-14 00:12:58 +0000810 }
Chris Lattner708148e2004-10-10 23:14:11 +0000811
812 if (Changed) {
David Greene3215b0e2010-01-05 01:28:05 +0000813 DEBUG(dbgs() << "OPTIMIZED LOADS FROM STORED ONCE POINTER: " << *GV);
Chris Lattner708148e2004-10-10 23:14:11 +0000814 ++NumGlobUses;
815 }
816
Chris Lattner708148e2004-10-10 23:14:11 +0000817 // If we nuked all of the loads, then none of the stores are needed either,
818 // nor is the global.
Chris Lattner92c6bd22009-01-14 00:12:58 +0000819 if (AllNonStoreUsesGone) {
David Greene3215b0e2010-01-05 01:28:05 +0000820 DEBUG(dbgs() << " *** GLOBAL NOW DEAD!\n");
Chris Lattner7b550cc2009-11-06 04:27:31 +0000821 CleanupConstantGlobalUsers(GV, 0);
Chris Lattner708148e2004-10-10 23:14:11 +0000822 if (GV->use_empty()) {
Chris Lattner7a7ed022004-10-16 18:09:00 +0000823 GV->eraseFromParent();
Chris Lattner708148e2004-10-10 23:14:11 +0000824 ++NumDeleted;
825 }
826 Changed = true;
827 }
828 return Changed;
829}
830
Chris Lattner30ba5692004-10-11 05:54:41 +0000831/// ConstantPropUsersOf - Walk the use list of V, constant folding all of the
832/// instructions that are foldable.
Chris Lattner7b550cc2009-11-06 04:27:31 +0000833static void ConstantPropUsersOf(Value *V) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000834 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; )
835 if (Instruction *I = dyn_cast<Instruction>(*UI++))
Chris Lattner7b550cc2009-11-06 04:27:31 +0000836 if (Constant *NewC = ConstantFoldInstruction(I)) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000837 I->replaceAllUsesWith(NewC);
838
Chris Lattnerd514d822005-02-01 01:23:31 +0000839 // Advance UI to the next non-I use to avoid invalidating it!
840 // Instructions could multiply use V.
841 while (UI != E && *UI == I)
Chris Lattner30ba5692004-10-11 05:54:41 +0000842 ++UI;
Chris Lattnerd514d822005-02-01 01:23:31 +0000843 I->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +0000844 }
845}
846
847/// OptimizeGlobalAddressOfMalloc - This function takes the specified global
848/// variable, and transforms the program as if it always contained the result of
849/// the specified malloc. Because it is always the result of the specified
850/// malloc, there is no reason to actually DO the malloc. Instead, turn the
Chris Lattner6e8fbad2006-11-30 17:32:29 +0000851/// malloc into a global, and any loads of GV as uses of the new global.
Chris Lattner30ba5692004-10-11 05:54:41 +0000852static GlobalVariable *OptimizeGlobalAddressOfMalloc(GlobalVariable *GV,
Victor Hernandez83d63912009-09-18 22:35:49 +0000853 CallInst *CI,
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000854 Type *AllocTy,
Chris Lattnera6874652010-02-25 22:33:52 +0000855 ConstantInt *NElements,
Victor Hernandez83d63912009-09-18 22:35:49 +0000856 TargetData* TD) {
Chris Lattnera6874652010-02-25 22:33:52 +0000857 DEBUG(errs() << "PROMOTING GLOBAL: " << *GV << " CALL = " << *CI << '\n');
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000858
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000859 Type *GlobalType;
Chris Lattnera6874652010-02-25 22:33:52 +0000860 if (NElements->getZExtValue() == 1)
861 GlobalType = AllocTy;
862 else
863 // If we have an array allocation, the global variable is of an array.
864 GlobalType = ArrayType::get(AllocTy, NElements->getZExtValue());
Victor Hernandez83d63912009-09-18 22:35:49 +0000865
866 // Create the new global variable. The contents of the malloc'd memory is
867 // undefined, so initialize with an undef value.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000868 GlobalVariable *NewGV = new GlobalVariable(*GV->getParent(),
Chris Lattnere9fd4442010-02-26 23:42:13 +0000869 GlobalType, false,
Chris Lattnera6874652010-02-25 22:33:52 +0000870 GlobalValue::InternalLinkage,
Chris Lattnere9fd4442010-02-26 23:42:13 +0000871 UndefValue::get(GlobalType),
Victor Hernandez83d63912009-09-18 22:35:49 +0000872 GV->getName()+".body",
873 GV,
874 GV->isThreadLocal());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000875
Chris Lattnera6874652010-02-25 22:33:52 +0000876 // If there are bitcast users of the malloc (which is typical, usually we have
877 // a malloc + bitcast) then replace them with uses of the new global. Update
878 // other users to use the global as well.
879 BitCastInst *TheBC = 0;
880 while (!CI->use_empty()) {
881 Instruction *User = cast<Instruction>(CI->use_back());
882 if (BitCastInst *BCI = dyn_cast<BitCastInst>(User)) {
883 if (BCI->getType() == NewGV->getType()) {
884 BCI->replaceAllUsesWith(NewGV);
885 BCI->eraseFromParent();
886 } else {
887 BCI->setOperand(0, NewGV);
888 }
889 } else {
890 if (TheBC == 0)
891 TheBC = new BitCastInst(NewGV, CI->getType(), "newgv", CI);
892 User->replaceUsesOfWith(CI, TheBC);
893 }
894 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000895
Victor Hernandez83d63912009-09-18 22:35:49 +0000896 Constant *RepValue = NewGV;
897 if (NewGV->getType() != GV->getType()->getElementType())
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000898 RepValue = ConstantExpr::getBitCast(RepValue,
Victor Hernandez83d63912009-09-18 22:35:49 +0000899 GV->getType()->getElementType());
900
901 // If there is a comparison against null, we will insert a global bool to
902 // keep track of whether the global was initialized yet or not.
903 GlobalVariable *InitBool =
Chris Lattner7b550cc2009-11-06 04:27:31 +0000904 new GlobalVariable(Type::getInt1Ty(GV->getContext()), false,
Victor Hernandez83d63912009-09-18 22:35:49 +0000905 GlobalValue::InternalLinkage,
Chris Lattner7b550cc2009-11-06 04:27:31 +0000906 ConstantInt::getFalse(GV->getContext()),
907 GV->getName()+".init", GV->isThreadLocal());
Victor Hernandez83d63912009-09-18 22:35:49 +0000908 bool InitBoolUsed = false;
909
910 // Loop over all uses of GV, processing them in turn.
Chris Lattnera6874652010-02-25 22:33:52 +0000911 while (!GV->use_empty()) {
912 if (StoreInst *SI = dyn_cast<StoreInst>(GV->use_back())) {
Victor Hernandez83d63912009-09-18 22:35:49 +0000913 // The global is initialized when the store to it occurs.
Chris Lattner7b550cc2009-11-06 04:27:31 +0000914 new StoreInst(ConstantInt::getTrue(GV->getContext()), InitBool, SI);
Victor Hernandez83d63912009-09-18 22:35:49 +0000915 SI->eraseFromParent();
Chris Lattnera6874652010-02-25 22:33:52 +0000916 continue;
Victor Hernandez83d63912009-09-18 22:35:49 +0000917 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000918
Chris Lattnera6874652010-02-25 22:33:52 +0000919 LoadInst *LI = cast<LoadInst>(GV->use_back());
920 while (!LI->use_empty()) {
921 Use &LoadUse = LI->use_begin().getUse();
922 if (!isa<ICmpInst>(LoadUse.getUser())) {
923 LoadUse = RepValue;
924 continue;
925 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000926
Chris Lattnera6874652010-02-25 22:33:52 +0000927 ICmpInst *ICI = cast<ICmpInst>(LoadUse.getUser());
928 // Replace the cmp X, 0 with a use of the bool value.
929 Value *LV = new LoadInst(InitBool, InitBool->getName()+".val", ICI);
930 InitBoolUsed = true;
931 switch (ICI->getPredicate()) {
932 default: llvm_unreachable("Unknown ICmp Predicate!");
933 case ICmpInst::ICMP_ULT:
934 case ICmpInst::ICMP_SLT: // X < null -> always false
935 LV = ConstantInt::getFalse(GV->getContext());
936 break;
937 case ICmpInst::ICMP_ULE:
938 case ICmpInst::ICMP_SLE:
939 case ICmpInst::ICMP_EQ:
940 LV = BinaryOperator::CreateNot(LV, "notinit", ICI);
941 break;
942 case ICmpInst::ICMP_NE:
943 case ICmpInst::ICMP_UGE:
944 case ICmpInst::ICMP_SGE:
945 case ICmpInst::ICMP_UGT:
946 case ICmpInst::ICMP_SGT:
947 break; // no change.
948 }
949 ICI->replaceAllUsesWith(LV);
950 ICI->eraseFromParent();
951 }
952 LI->eraseFromParent();
953 }
Victor Hernandez83d63912009-09-18 22:35:49 +0000954
955 // If the initialization boolean was used, insert it, otherwise delete it.
956 if (!InitBoolUsed) {
957 while (!InitBool->use_empty()) // Delete initializations
Chris Lattnera6874652010-02-25 22:33:52 +0000958 cast<StoreInst>(InitBool->use_back())->eraseFromParent();
Victor Hernandez83d63912009-09-18 22:35:49 +0000959 delete InitBool;
960 } else
961 GV->getParent()->getGlobalList().insert(GV, InitBool);
962
Chris Lattnera6874652010-02-25 22:33:52 +0000963 // Now the GV is dead, nuke it and the malloc..
Victor Hernandez83d63912009-09-18 22:35:49 +0000964 GV->eraseFromParent();
Victor Hernandez83d63912009-09-18 22:35:49 +0000965 CI->eraseFromParent();
966
967 // To further other optimizations, loop over all users of NewGV and try to
968 // constant prop them. This will promote GEP instructions with constant
969 // indices into GEP constant-exprs, which will allow global-opt to hack on it.
Chris Lattner7b550cc2009-11-06 04:27:31 +0000970 ConstantPropUsersOf(NewGV);
Victor Hernandez83d63912009-09-18 22:35:49 +0000971 if (RepValue != NewGV)
Chris Lattner7b550cc2009-11-06 04:27:31 +0000972 ConstantPropUsersOf(RepValue);
Victor Hernandez83d63912009-09-18 22:35:49 +0000973
974 return NewGV;
975}
976
Chris Lattnerfa07e4f2004-12-02 07:11:07 +0000977/// ValueIsOnlyUsedLocallyOrStoredToOneGlobal - Scan the use-list of V checking
978/// to make sure that there are no complex uses of V. We permit simple things
979/// like dereferencing the pointer, but not storing through the address, unless
980/// it is to the specified global.
Gabor Greif0b520db2010-04-06 18:58:22 +0000981static bool ValueIsOnlyUsedLocallyOrStoredToOneGlobal(const Instruction *V,
982 const GlobalVariable *GV,
Gabor Greifa01d6db2010-04-06 19:14:05 +0000983 SmallPtrSet<const PHINode*, 8> &PHIs) {
Gabor Greif0b520db2010-04-06 18:58:22 +0000984 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end();
Gabor Greifa01d6db2010-04-06 19:14:05 +0000985 UI != E; ++UI) {
Gabor Greif0b520db2010-04-06 18:58:22 +0000986 const Instruction *Inst = cast<Instruction>(*UI);
Gabor Greifa01d6db2010-04-06 19:14:05 +0000987
Chris Lattner49b6d4a2008-12-15 21:08:54 +0000988 if (isa<LoadInst>(Inst) || isa<CmpInst>(Inst)) {
989 continue; // Fine, ignore.
990 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000991
Gabor Greif0b520db2010-04-06 18:58:22 +0000992 if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
Chris Lattnerfa07e4f2004-12-02 07:11:07 +0000993 if (SI->getOperand(0) == V && SI->getOperand(1) != GV)
994 return false; // Storing the pointer itself... bad.
Chris Lattner49b6d4a2008-12-15 21:08:54 +0000995 continue; // Otherwise, storing through it, or storing into GV... fine.
996 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000997
Chris Lattnera2fb2342010-04-10 18:19:22 +0000998 // Must index into the array and into the struct.
999 if (isa<GetElementPtrInst>(Inst) && Inst->getNumOperands() >= 3) {
Chris Lattner49b6d4a2008-12-15 21:08:54 +00001000 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(Inst, GV, PHIs))
Chris Lattnerfa07e4f2004-12-02 07:11:07 +00001001 return false;
Chris Lattner49b6d4a2008-12-15 21:08:54 +00001002 continue;
1003 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001004
Gabor Greif0b520db2010-04-06 18:58:22 +00001005 if (const PHINode *PN = dyn_cast<PHINode>(Inst)) {
Chris Lattnerc451f9c2007-09-13 16:37:20 +00001006 // PHIs are ok if all uses are ok. Don't infinitely recurse through PHI
1007 // cycles.
1008 if (PHIs.insert(PN))
Chris Lattner5e6e4942007-09-14 03:41:21 +00001009 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(PN, GV, PHIs))
1010 return false;
Chris Lattner49b6d4a2008-12-15 21:08:54 +00001011 continue;
Chris Lattnerfa07e4f2004-12-02 07:11:07 +00001012 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001013
Gabor Greif0b520db2010-04-06 18:58:22 +00001014 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Inst)) {
Chris Lattner49b6d4a2008-12-15 21:08:54 +00001015 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(BCI, GV, PHIs))
1016 return false;
1017 continue;
1018 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001019
Chris Lattner49b6d4a2008-12-15 21:08:54 +00001020 return false;
1021 }
Chris Lattnerfa07e4f2004-12-02 07:11:07 +00001022 return true;
Chris Lattnerfa07e4f2004-12-02 07:11:07 +00001023}
1024
Chris Lattner86395032006-09-30 23:32:09 +00001025/// ReplaceUsesOfMallocWithGlobal - The Alloc pointer is stored into GV
1026/// somewhere. Transform all uses of the allocation into loads from the
1027/// global and uses of the resultant pointer. Further, delete the store into
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001028/// GV. This assumes that these value pass the
Chris Lattner86395032006-09-30 23:32:09 +00001029/// 'ValueIsOnlyUsedLocallyOrStoredToOneGlobal' predicate.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001030static void ReplaceUsesOfMallocWithGlobal(Instruction *Alloc,
Chris Lattner86395032006-09-30 23:32:09 +00001031 GlobalVariable *GV) {
1032 while (!Alloc->use_empty()) {
Chris Lattnera637a8b2007-09-13 18:00:31 +00001033 Instruction *U = cast<Instruction>(*Alloc->use_begin());
1034 Instruction *InsertPt = U;
Chris Lattner86395032006-09-30 23:32:09 +00001035 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
1036 // If this is the store of the allocation into the global, remove it.
1037 if (SI->getOperand(1) == GV) {
1038 SI->eraseFromParent();
1039 continue;
1040 }
Chris Lattnera637a8b2007-09-13 18:00:31 +00001041 } else if (PHINode *PN = dyn_cast<PHINode>(U)) {
1042 // Insert the load in the corresponding predecessor, not right before the
1043 // PHI.
Gabor Greifa36791d2009-01-23 19:40:15 +00001044 InsertPt = PN->getIncomingBlock(Alloc->use_begin())->getTerminator();
Chris Lattner101f44e2008-12-15 21:44:34 +00001045 } else if (isa<BitCastInst>(U)) {
1046 // Must be bitcast between the malloc and store to initialize the global.
1047 ReplaceUsesOfMallocWithGlobal(U, GV);
1048 U->eraseFromParent();
1049 continue;
1050 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
1051 // If this is a "GEP bitcast" and the user is a store to the global, then
1052 // just process it as a bitcast.
1053 if (GEPI->hasAllZeroIndices() && GEPI->hasOneUse())
1054 if (StoreInst *SI = dyn_cast<StoreInst>(GEPI->use_back()))
1055 if (SI->getOperand(1) == GV) {
1056 // Must be bitcast GEP between the malloc and store to initialize
1057 // the global.
1058 ReplaceUsesOfMallocWithGlobal(GEPI, GV);
1059 GEPI->eraseFromParent();
1060 continue;
1061 }
Chris Lattner86395032006-09-30 23:32:09 +00001062 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001063
Chris Lattner86395032006-09-30 23:32:09 +00001064 // Insert a load from the global, and use it instead of the malloc.
Chris Lattnera637a8b2007-09-13 18:00:31 +00001065 Value *NL = new LoadInst(GV, GV->getName()+".val", InsertPt);
Chris Lattner86395032006-09-30 23:32:09 +00001066 U->replaceUsesOfWith(Alloc, NL);
1067 }
1068}
1069
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001070/// LoadUsesSimpleEnoughForHeapSRA - Verify that all uses of V (a load, or a phi
1071/// of a load) are simple enough to perform heap SRA on. This permits GEP's
1072/// that index through the array and struct field, icmps of null, and PHIs.
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001073static bool LoadUsesSimpleEnoughForHeapSRA(const Value *V,
Gabor Greif27236912010-04-07 18:59:26 +00001074 SmallPtrSet<const PHINode*, 32> &LoadUsingPHIs,
1075 SmallPtrSet<const PHINode*, 32> &LoadUsingPHIsPerLoad) {
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001076 // We permit two users of the load: setcc comparing against the null
1077 // pointer, and a getelementptr of a specific form.
Gabor Greif27236912010-04-07 18:59:26 +00001078 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;
1079 ++UI) {
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001080 const Instruction *User = cast<Instruction>(*UI);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001081
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001082 // Comparison against null is ok.
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001083 if (const ICmpInst *ICI = dyn_cast<ICmpInst>(User)) {
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001084 if (!isa<ConstantPointerNull>(ICI->getOperand(1)))
1085 return false;
1086 continue;
1087 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001088
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001089 // getelementptr is also ok, but only a simple form.
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001090 if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001091 // Must index into the array and into the struct.
1092 if (GEPI->getNumOperands() < 3)
1093 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001094
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001095 // Otherwise the GEP is ok.
1096 continue;
1097 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001098
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001099 if (const PHINode *PN = dyn_cast<PHINode>(User)) {
Evan Cheng5d163962009-06-02 00:56:07 +00001100 if (!LoadUsingPHIsPerLoad.insert(PN))
1101 // This means some phi nodes are dependent on each other.
1102 // Avoid infinite looping!
1103 return false;
1104 if (!LoadUsingPHIs.insert(PN))
1105 // If we have already analyzed this PHI, then it is safe.
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001106 continue;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001107
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001108 // Make sure all uses of the PHI are simple enough to transform.
Evan Cheng5d163962009-06-02 00:56:07 +00001109 if (!LoadUsesSimpleEnoughForHeapSRA(PN,
1110 LoadUsingPHIs, LoadUsingPHIsPerLoad))
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001111 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001112
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001113 continue;
Chris Lattner86395032006-09-30 23:32:09 +00001114 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001115
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001116 // Otherwise we don't know what this is, not ok.
1117 return false;
1118 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001119
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001120 return true;
1121}
1122
1123
1124/// AllGlobalLoadUsesSimpleEnoughForHeapSRA - If all users of values loaded from
1125/// GV are simple enough to perform HeapSRA, return true.
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001126static bool AllGlobalLoadUsesSimpleEnoughForHeapSRA(const GlobalVariable *GV,
Victor Hernandez83d63912009-09-18 22:35:49 +00001127 Instruction *StoredVal) {
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001128 SmallPtrSet<const PHINode*, 32> LoadUsingPHIs;
1129 SmallPtrSet<const PHINode*, 32> LoadUsingPHIsPerLoad;
Gabor Greif27236912010-04-07 18:59:26 +00001130 for (Value::const_use_iterator UI = GV->use_begin(), E = GV->use_end();
1131 UI != E; ++UI)
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001132 if (const LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
Evan Cheng5d163962009-06-02 00:56:07 +00001133 if (!LoadUsesSimpleEnoughForHeapSRA(LI, LoadUsingPHIs,
1134 LoadUsingPHIsPerLoad))
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001135 return false;
Evan Cheng5d163962009-06-02 00:56:07 +00001136 LoadUsingPHIsPerLoad.clear();
1137 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001138
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001139 // If we reach here, we know that all uses of the loads and transitive uses
1140 // (through PHI nodes) are simple enough to transform. However, we don't know
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001141 // that all inputs the to the PHI nodes are in the same equivalence sets.
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001142 // Check to verify that all operands of the PHIs are either PHIS that can be
1143 // transformed, loads from GV, or MI itself.
Gabor Greif27236912010-04-07 18:59:26 +00001144 for (SmallPtrSet<const PHINode*, 32>::const_iterator I = LoadUsingPHIs.begin()
1145 , E = LoadUsingPHIs.end(); I != E; ++I) {
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001146 const PHINode *PN = *I;
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001147 for (unsigned op = 0, e = PN->getNumIncomingValues(); op != e; ++op) {
1148 Value *InVal = PN->getIncomingValue(op);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001149
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001150 // PHI of the stored value itself is ok.
Victor Hernandez83d63912009-09-18 22:35:49 +00001151 if (InVal == StoredVal) continue;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001152
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001153 if (const PHINode *InPN = dyn_cast<PHINode>(InVal)) {
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001154 // One of the PHIs in our set is (optimistically) ok.
1155 if (LoadUsingPHIs.count(InPN))
1156 continue;
1157 return false;
1158 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001159
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001160 // Load from GV is ok.
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001161 if (const LoadInst *LI = dyn_cast<LoadInst>(InVal))
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001162 if (LI->getOperand(0) == GV)
1163 continue;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001164
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001165 // UNDEF? NULL?
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001166
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001167 // Anything else is rejected.
1168 return false;
1169 }
1170 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001171
Chris Lattner86395032006-09-30 23:32:09 +00001172 return true;
1173}
1174
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001175static Value *GetHeapSROAValue(Value *V, unsigned FieldNo,
1176 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001177 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001178 std::vector<Value*> &FieldVals = InsertedScalarizedValues[V];
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001179
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001180 if (FieldNo >= FieldVals.size())
1181 FieldVals.resize(FieldNo+1);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001182
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001183 // If we already have this value, just reuse the previously scalarized
1184 // version.
1185 if (Value *FieldVal = FieldVals[FieldNo])
1186 return FieldVal;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001187
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001188 // Depending on what instruction this is, we have several cases.
1189 Value *Result;
1190 if (LoadInst *LI = dyn_cast<LoadInst>(V)) {
1191 // This is a scalarized version of the load from the global. Just create
1192 // a new Load of the scalarized global.
1193 Result = new LoadInst(GetHeapSROAValue(LI->getOperand(0), FieldNo,
1194 InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001195 PHIsToRewrite),
Daniel Dunbarfe09b202009-07-30 17:37:43 +00001196 LI->getName()+".f"+Twine(FieldNo), LI);
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001197 } else if (PHINode *PN = dyn_cast<PHINode>(V)) {
1198 // PN's type is pointer to struct. Make a new PHI of pointer to struct
1199 // field.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001200 StructType *ST =
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001201 cast<StructType>(cast<PointerType>(PN->getType())->getElementType());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001202
Jay Foadd8b4fb42011-03-30 11:19:20 +00001203 PHINode *NewPN =
Owen Andersondebcb012009-07-29 22:17:13 +00001204 PHINode::Create(PointerType::getUnqual(ST->getElementType(FieldNo)),
Jay Foad3ecfc862011-03-30 11:28:46 +00001205 PN->getNumIncomingValues(),
Daniel Dunbarfe09b202009-07-30 17:37:43 +00001206 PN->getName()+".f"+Twine(FieldNo), PN);
Jay Foadd8b4fb42011-03-30 11:19:20 +00001207 Result = NewPN;
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001208 PHIsToRewrite.push_back(std::make_pair(PN, FieldNo));
1209 } else {
Torok Edwinc23197a2009-07-14 16:55:14 +00001210 llvm_unreachable("Unknown usable value");
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001211 Result = 0;
1212 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001213
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001214 return FieldVals[FieldNo] = Result;
Chris Lattnera637a8b2007-09-13 18:00:31 +00001215}
1216
Chris Lattner330245e2007-09-13 17:29:05 +00001217/// RewriteHeapSROALoadUser - Given a load instruction and a value derived from
1218/// the load, rewrite the derived value to use the HeapSRoA'd load.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001219static void RewriteHeapSROALoadUser(Instruction *LoadUser,
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001220 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001221 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
Chris Lattner330245e2007-09-13 17:29:05 +00001222 // If this is a comparison against null, handle it.
1223 if (ICmpInst *SCI = dyn_cast<ICmpInst>(LoadUser)) {
1224 assert(isa<ConstantPointerNull>(SCI->getOperand(1)));
1225 // If we have a setcc of the loaded pointer, we can use a setcc of any
1226 // field.
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001227 Value *NPtr = GetHeapSROAValue(SCI->getOperand(0), 0,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001228 InsertedScalarizedValues, PHIsToRewrite);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001229
Owen Anderson333c4002009-07-09 23:48:35 +00001230 Value *New = new ICmpInst(SCI, SCI->getPredicate(), NPtr,
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001231 Constant::getNullValue(NPtr->getType()),
Owen Anderson333c4002009-07-09 23:48:35 +00001232 SCI->getName());
Chris Lattner330245e2007-09-13 17:29:05 +00001233 SCI->replaceAllUsesWith(New);
1234 SCI->eraseFromParent();
1235 return;
1236 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001237
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001238 // Handle 'getelementptr Ptr, Idx, i32 FieldNo ...'
Chris Lattnera637a8b2007-09-13 18:00:31 +00001239 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(LoadUser)) {
1240 assert(GEPI->getNumOperands() >= 3 && isa<ConstantInt>(GEPI->getOperand(2))
1241 && "Unexpected GEPI!");
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001242
Chris Lattnera637a8b2007-09-13 18:00:31 +00001243 // Load the pointer for this field.
1244 unsigned FieldNo = cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue();
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001245 Value *NewPtr = GetHeapSROAValue(GEPI->getOperand(0), FieldNo,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001246 InsertedScalarizedValues, PHIsToRewrite);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001247
Chris Lattnera637a8b2007-09-13 18:00:31 +00001248 // Create the new GEP idx vector.
1249 SmallVector<Value*, 8> GEPIdx;
1250 GEPIdx.push_back(GEPI->getOperand(1));
1251 GEPIdx.append(GEPI->op_begin()+3, GEPI->op_end());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001252
Jay Foada9203102011-07-25 09:48:08 +00001253 Value *NGEPI = GetElementPtrInst::Create(NewPtr, GEPIdx,
Gabor Greif051a9502008-04-06 20:25:17 +00001254 GEPI->getName(), GEPI);
Chris Lattnera637a8b2007-09-13 18:00:31 +00001255 GEPI->replaceAllUsesWith(NGEPI);
1256 GEPI->eraseFromParent();
1257 return;
1258 }
Chris Lattner309f20f2007-09-13 21:31:36 +00001259
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001260 // Recursively transform the users of PHI nodes. This will lazily create the
1261 // PHIs that are needed for individual elements. Keep track of what PHIs we
1262 // see in InsertedScalarizedValues so that we don't get infinite loops (very
1263 // antisocial). If the PHI is already in InsertedScalarizedValues, it has
1264 // already been seen first by another load, so its uses have already been
1265 // processed.
1266 PHINode *PN = cast<PHINode>(LoadUser);
Chris Lattnerc30a38f2011-07-21 06:21:31 +00001267 if (!InsertedScalarizedValues.insert(std::make_pair(PN,
1268 std::vector<Value*>())).second)
1269 return;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001270
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001271 // If this is the first time we've seen this PHI, recursively process all
1272 // users.
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001273 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end(); UI != E; ) {
1274 Instruction *User = cast<Instruction>(*UI++);
Chris Lattner7b550cc2009-11-06 04:27:31 +00001275 RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite);
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001276 }
Chris Lattner330245e2007-09-13 17:29:05 +00001277}
1278
Chris Lattner86395032006-09-30 23:32:09 +00001279/// RewriteUsesOfLoadForHeapSRoA - We are performing Heap SRoA on a global. Ptr
1280/// is a value loaded from the global. Eliminate all uses of Ptr, making them
1281/// use FieldGlobals instead. All uses of loaded values satisfy
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001282/// AllGlobalLoadUsesSimpleEnoughForHeapSRA.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001283static void RewriteUsesOfLoadForHeapSRoA(LoadInst *Load,
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001284 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001285 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001286 for (Value::use_iterator UI = Load->use_begin(), E = Load->use_end();
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001287 UI != E; ) {
1288 Instruction *User = cast<Instruction>(*UI++);
Chris Lattner7b550cc2009-11-06 04:27:31 +00001289 RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite);
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001290 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001291
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001292 if (Load->use_empty()) {
1293 Load->eraseFromParent();
1294 InsertedScalarizedValues.erase(Load);
1295 }
Chris Lattner86395032006-09-30 23:32:09 +00001296}
1297
Victor Hernandez83d63912009-09-18 22:35:49 +00001298/// PerformHeapAllocSRoA - CI is an allocation of an array of structures. Break
1299/// it up into multiple allocations of arrays of the fields.
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001300static GlobalVariable *PerformHeapAllocSRoA(GlobalVariable *GV, CallInst *CI,
1301 Value* NElems, TargetData *TD) {
David Greene3215b0e2010-01-05 01:28:05 +00001302 DEBUG(dbgs() << "SROA HEAP ALLOC: " << *GV << " MALLOC = " << *CI << '\n');
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001303 Type* MAT = getMallocAllocatedType(CI);
1304 StructType *STy = cast<StructType>(MAT);
Victor Hernandez83d63912009-09-18 22:35:49 +00001305
1306 // There is guaranteed to be at least one use of the malloc (storing
1307 // it into GV). If there are other uses, change them to be uses of
1308 // the global to simplify later code. This also deletes the store
1309 // into GV.
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001310 ReplaceUsesOfMallocWithGlobal(CI, GV);
1311
Victor Hernandez83d63912009-09-18 22:35:49 +00001312 // Okay, at this point, there are no users of the malloc. Insert N
1313 // new mallocs at the same place as CI, and N globals.
1314 std::vector<Value*> FieldGlobals;
1315 std::vector<Value*> FieldMallocs;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001316
Victor Hernandez83d63912009-09-18 22:35:49 +00001317 for (unsigned FieldNo = 0, e = STy->getNumElements(); FieldNo != e;++FieldNo){
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001318 Type *FieldTy = STy->getElementType(FieldNo);
1319 PointerType *PFieldTy = PointerType::getUnqual(FieldTy);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001320
Victor Hernandez83d63912009-09-18 22:35:49 +00001321 GlobalVariable *NGV =
1322 new GlobalVariable(*GV->getParent(),
1323 PFieldTy, false, GlobalValue::InternalLinkage,
1324 Constant::getNullValue(PFieldTy),
1325 GV->getName() + ".f" + Twine(FieldNo), GV,
1326 GV->isThreadLocal());
1327 FieldGlobals.push_back(NGV);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001328
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001329 unsigned TypeSize = TD->getTypeAllocSize(FieldTy);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001330 if (StructType *ST = dyn_cast<StructType>(FieldTy))
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001331 TypeSize = TD->getStructLayout(ST)->getSizeInBytes();
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001332 Type *IntPtrTy = TD->getIntPtrType(CI->getContext());
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001333 Value *NMI = CallInst::CreateMalloc(CI, IntPtrTy, FieldTy,
1334 ConstantInt::get(IntPtrTy, TypeSize),
Chris Lattner5a30a852010-07-12 00:57:28 +00001335 NElems, 0,
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001336 CI->getName() + ".f" + Twine(FieldNo));
Chris Lattner3f5e0b82010-02-26 18:23:13 +00001337 FieldMallocs.push_back(NMI);
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001338 new StoreInst(NMI, NGV, CI);
Victor Hernandez83d63912009-09-18 22:35:49 +00001339 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001340
Victor Hernandez83d63912009-09-18 22:35:49 +00001341 // The tricky aspect of this transformation is handling the case when malloc
1342 // fails. In the original code, malloc failing would set the result pointer
1343 // of malloc to null. In this case, some mallocs could succeed and others
1344 // could fail. As such, we emit code that looks like this:
1345 // F0 = malloc(field0)
1346 // F1 = malloc(field1)
1347 // F2 = malloc(field2)
1348 // if (F0 == 0 || F1 == 0 || F2 == 0) {
1349 // if (F0) { free(F0); F0 = 0; }
1350 // if (F1) { free(F1); F1 = 0; }
1351 // if (F2) { free(F2); F2 = 0; }
1352 // }
Victor Hernandez8e345a12009-11-10 08:32:25 +00001353 // The malloc can also fail if its argument is too large.
Gabor Greif9e4f2432010-06-24 14:42:01 +00001354 Constant *ConstantZero = ConstantInt::get(CI->getArgOperand(0)->getType(), 0);
1355 Value *RunningOr = new ICmpInst(CI, ICmpInst::ICMP_SLT, CI->getArgOperand(0),
Victor Hernandez8e345a12009-11-10 08:32:25 +00001356 ConstantZero, "isneg");
Victor Hernandez83d63912009-09-18 22:35:49 +00001357 for (unsigned i = 0, e = FieldMallocs.size(); i != e; ++i) {
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001358 Value *Cond = new ICmpInst(CI, ICmpInst::ICMP_EQ, FieldMallocs[i],
1359 Constant::getNullValue(FieldMallocs[i]->getType()),
1360 "isnull");
Victor Hernandez8e345a12009-11-10 08:32:25 +00001361 RunningOr = BinaryOperator::CreateOr(RunningOr, Cond, "tmp", CI);
Victor Hernandez83d63912009-09-18 22:35:49 +00001362 }
1363
1364 // Split the basic block at the old malloc.
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001365 BasicBlock *OrigBB = CI->getParent();
1366 BasicBlock *ContBB = OrigBB->splitBasicBlock(CI, "malloc_cont");
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001367
Victor Hernandez83d63912009-09-18 22:35:49 +00001368 // Create the block to check the first condition. Put all these blocks at the
1369 // end of the function as they are unlikely to be executed.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001370 BasicBlock *NullPtrBlock = BasicBlock::Create(OrigBB->getContext(),
1371 "malloc_ret_null",
Victor Hernandez83d63912009-09-18 22:35:49 +00001372 OrigBB->getParent());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001373
Victor Hernandez83d63912009-09-18 22:35:49 +00001374 // Remove the uncond branch from OrigBB to ContBB, turning it into a cond
1375 // branch on RunningOr.
1376 OrigBB->getTerminator()->eraseFromParent();
1377 BranchInst::Create(NullPtrBlock, ContBB, RunningOr, OrigBB);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001378
Victor Hernandez83d63912009-09-18 22:35:49 +00001379 // Within the NullPtrBlock, we need to emit a comparison and branch for each
1380 // pointer, because some may be null while others are not.
1381 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
1382 Value *GVVal = new LoadInst(FieldGlobals[i], "tmp", NullPtrBlock);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001383 Value *Cmp = new ICmpInst(*NullPtrBlock, ICmpInst::ICMP_NE, GVVal,
Benjamin Kramera9390a42011-09-27 20:39:19 +00001384 Constant::getNullValue(GVVal->getType()));
Chris Lattner7b550cc2009-11-06 04:27:31 +00001385 BasicBlock *FreeBlock = BasicBlock::Create(Cmp->getContext(), "free_it",
Victor Hernandez83d63912009-09-18 22:35:49 +00001386 OrigBB->getParent());
Chris Lattner7b550cc2009-11-06 04:27:31 +00001387 BasicBlock *NextBlock = BasicBlock::Create(Cmp->getContext(), "next",
Victor Hernandez83d63912009-09-18 22:35:49 +00001388 OrigBB->getParent());
Victor Hernandez66284e02009-10-24 04:23:03 +00001389 Instruction *BI = BranchInst::Create(FreeBlock, NextBlock,
1390 Cmp, NullPtrBlock);
Victor Hernandez83d63912009-09-18 22:35:49 +00001391
1392 // Fill in FreeBlock.
Victor Hernandez66284e02009-10-24 04:23:03 +00001393 CallInst::CreateFree(GVVal, BI);
Victor Hernandez83d63912009-09-18 22:35:49 +00001394 new StoreInst(Constant::getNullValue(GVVal->getType()), FieldGlobals[i],
1395 FreeBlock);
1396 BranchInst::Create(NextBlock, FreeBlock);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001397
Victor Hernandez83d63912009-09-18 22:35:49 +00001398 NullPtrBlock = NextBlock;
1399 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001400
Victor Hernandez83d63912009-09-18 22:35:49 +00001401 BranchInst::Create(ContBB, NullPtrBlock);
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001402
1403 // CI is no longer needed, remove it.
Victor Hernandez83d63912009-09-18 22:35:49 +00001404 CI->eraseFromParent();
1405
1406 /// InsertedScalarizedLoads - As we process loads, if we can't immediately
1407 /// update all uses of the load, keep track of what scalarized loads are
1408 /// inserted for a given load.
1409 DenseMap<Value*, std::vector<Value*> > InsertedScalarizedValues;
1410 InsertedScalarizedValues[GV] = FieldGlobals;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001411
Victor Hernandez83d63912009-09-18 22:35:49 +00001412 std::vector<std::pair<PHINode*, unsigned> > PHIsToRewrite;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001413
Victor Hernandez83d63912009-09-18 22:35:49 +00001414 // Okay, the malloc site is completely handled. All of the uses of GV are now
1415 // loads, and all uses of those loads are simple. Rewrite them to use loads
1416 // of the per-field globals instead.
1417 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI != E;) {
1418 Instruction *User = cast<Instruction>(*UI++);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001419
Victor Hernandez83d63912009-09-18 22:35:49 +00001420 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Chris Lattner7b550cc2009-11-06 04:27:31 +00001421 RewriteUsesOfLoadForHeapSRoA(LI, InsertedScalarizedValues, PHIsToRewrite);
Victor Hernandez83d63912009-09-18 22:35:49 +00001422 continue;
1423 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001424
Victor Hernandez83d63912009-09-18 22:35:49 +00001425 // Must be a store of null.
1426 StoreInst *SI = cast<StoreInst>(User);
1427 assert(isa<ConstantPointerNull>(SI->getOperand(0)) &&
1428 "Unexpected heap-sra user!");
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001429
Victor Hernandez83d63912009-09-18 22:35:49 +00001430 // Insert a store of null into each global.
1431 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001432 PointerType *PT = cast<PointerType>(FieldGlobals[i]->getType());
Victor Hernandez83d63912009-09-18 22:35:49 +00001433 Constant *Null = Constant::getNullValue(PT->getElementType());
1434 new StoreInst(Null, FieldGlobals[i], SI);
1435 }
1436 // Erase the original store.
1437 SI->eraseFromParent();
1438 }
1439
1440 // While we have PHIs that are interesting to rewrite, do it.
1441 while (!PHIsToRewrite.empty()) {
1442 PHINode *PN = PHIsToRewrite.back().first;
1443 unsigned FieldNo = PHIsToRewrite.back().second;
1444 PHIsToRewrite.pop_back();
1445 PHINode *FieldPN = cast<PHINode>(InsertedScalarizedValues[PN][FieldNo]);
1446 assert(FieldPN->getNumIncomingValues() == 0 &&"Already processed this phi");
1447
1448 // Add all the incoming values. This can materialize more phis.
1449 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1450 Value *InVal = PN->getIncomingValue(i);
1451 InVal = GetHeapSROAValue(InVal, FieldNo, InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001452 PHIsToRewrite);
Victor Hernandez83d63912009-09-18 22:35:49 +00001453 FieldPN->addIncoming(InVal, PN->getIncomingBlock(i));
1454 }
1455 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001456
Victor Hernandez83d63912009-09-18 22:35:49 +00001457 // Drop all inter-phi links and any loads that made it this far.
1458 for (DenseMap<Value*, std::vector<Value*> >::iterator
1459 I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
1460 I != E; ++I) {
1461 if (PHINode *PN = dyn_cast<PHINode>(I->first))
1462 PN->dropAllReferences();
1463 else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
1464 LI->dropAllReferences();
1465 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001466
Victor Hernandez83d63912009-09-18 22:35:49 +00001467 // Delete all the phis and loads now that inter-references are dead.
1468 for (DenseMap<Value*, std::vector<Value*> >::iterator
1469 I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
1470 I != E; ++I) {
1471 if (PHINode *PN = dyn_cast<PHINode>(I->first))
1472 PN->eraseFromParent();
1473 else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
1474 LI->eraseFromParent();
1475 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001476
Victor Hernandez83d63912009-09-18 22:35:49 +00001477 // The old global is now dead, remove it.
1478 GV->eraseFromParent();
1479
1480 ++NumHeapSRA;
1481 return cast<GlobalVariable>(FieldGlobals[0]);
1482}
1483
Chris Lattnere61d0a62008-12-15 21:02:25 +00001484/// TryToOptimizeStoreOfMallocToGlobal - This function is called when we see a
1485/// pointer global variable with a single value stored it that is a malloc or
1486/// cast of malloc.
1487static bool TryToOptimizeStoreOfMallocToGlobal(GlobalVariable *GV,
Victor Hernandez83d63912009-09-18 22:35:49 +00001488 CallInst *CI,
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001489 Type *AllocTy,
Victor Hernandez83d63912009-09-18 22:35:49 +00001490 Module::global_iterator &GVI,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001491 TargetData *TD) {
Evan Cheng86cd4452010-04-14 20:52:55 +00001492 if (!TD)
1493 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001494
Victor Hernandez83d63912009-09-18 22:35:49 +00001495 // If this is a malloc of an abstract type, don't touch it.
1496 if (!AllocTy->isSized())
1497 return false;
1498
1499 // We can't optimize this global unless all uses of it are *known* to be
1500 // of the malloc value, not of the null initializer value (consider a use
1501 // that compares the global's value against zero to see if the malloc has
1502 // been reached). To do this, we check to see if all uses of the global
1503 // would trap if the global were null: this proves that they must all
1504 // happen after the malloc.
1505 if (!AllUsesOfLoadedValueWillTrapIfNull(GV))
1506 return false;
1507
1508 // We can't optimize this if the malloc itself is used in a complex way,
1509 // for example, being stored into multiple globals. This allows the
1510 // malloc to be stored into the specified global, loaded setcc'd, and
1511 // GEP'd. These are all things we could transform to using the global
1512 // for.
Evan Cheng86cd4452010-04-14 20:52:55 +00001513 SmallPtrSet<const PHINode*, 8> PHIs;
1514 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(CI, GV, PHIs))
1515 return false;
Victor Hernandez83d63912009-09-18 22:35:49 +00001516
1517 // If we have a global that is only initialized with a fixed size malloc,
1518 // transform the program to use global memory instead of malloc'd memory.
1519 // This eliminates dynamic allocation, avoids an indirection accessing the
1520 // data, and exposes the resultant global to further GlobalOpt.
Victor Hernandez8db42d22009-10-16 23:12:25 +00001521 // We cannot optimize the malloc if we cannot determine malloc array size.
Evan Cheng86cd4452010-04-14 20:52:55 +00001522 Value *NElems = getMallocArraySize(CI, TD, true);
1523 if (!NElems)
1524 return false;
Victor Hernandez83d63912009-09-18 22:35:49 +00001525
Evan Cheng86cd4452010-04-14 20:52:55 +00001526 if (ConstantInt *NElements = dyn_cast<ConstantInt>(NElems))
1527 // Restrict this transformation to only working on small allocations
1528 // (2048 bytes currently), as we don't want to introduce a 16M global or
1529 // something.
1530 if (NElements->getZExtValue() * TD->getTypeAllocSize(AllocTy) < 2048) {
1531 GVI = OptimizeGlobalAddressOfMalloc(GV, CI, AllocTy, NElements, TD);
1532 return true;
Victor Hernandez83d63912009-09-18 22:35:49 +00001533 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001534
Evan Cheng86cd4452010-04-14 20:52:55 +00001535 // If the allocation is an array of structures, consider transforming this
1536 // into multiple malloc'd arrays, one for each field. This is basically
1537 // SRoA for malloc'd memory.
1538
1539 // If this is an allocation of a fixed size array of structs, analyze as a
1540 // variable size array. malloc [100 x struct],1 -> malloc struct, 100
Gabor Greif9e4f2432010-06-24 14:42:01 +00001541 if (NElems == ConstantInt::get(CI->getArgOperand(0)->getType(), 1))
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001542 if (ArrayType *AT = dyn_cast<ArrayType>(AllocTy))
Evan Cheng86cd4452010-04-14 20:52:55 +00001543 AllocTy = AT->getElementType();
Gabor Greif9e4f2432010-06-24 14:42:01 +00001544
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001545 StructType *AllocSTy = dyn_cast<StructType>(AllocTy);
Evan Cheng86cd4452010-04-14 20:52:55 +00001546 if (!AllocSTy)
1547 return false;
1548
1549 // This the structure has an unreasonable number of fields, leave it
1550 // alone.
1551 if (AllocSTy->getNumElements() <= 16 && AllocSTy->getNumElements() != 0 &&
1552 AllGlobalLoadUsesSimpleEnoughForHeapSRA(GV, CI)) {
1553
1554 // If this is a fixed size array, transform the Malloc to be an alloc of
1555 // structs. malloc [100 x struct],1 -> malloc struct, 100
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001556 if (ArrayType *AT = dyn_cast<ArrayType>(getMallocAllocatedType(CI))) {
1557 Type *IntPtrTy = TD->getIntPtrType(CI->getContext());
Evan Cheng86cd4452010-04-14 20:52:55 +00001558 unsigned TypeSize = TD->getStructLayout(AllocSTy)->getSizeInBytes();
1559 Value *AllocSize = ConstantInt::get(IntPtrTy, TypeSize);
1560 Value *NumElements = ConstantInt::get(IntPtrTy, AT->getNumElements());
1561 Instruction *Malloc = CallInst::CreateMalloc(CI, IntPtrTy, AllocSTy,
1562 AllocSize, NumElements,
Chris Lattner5a30a852010-07-12 00:57:28 +00001563 0, CI->getName());
Evan Cheng86cd4452010-04-14 20:52:55 +00001564 Instruction *Cast = new BitCastInst(Malloc, CI->getType(), "tmp", CI);
1565 CI->replaceAllUsesWith(Cast);
1566 CI->eraseFromParent();
1567 CI = dyn_cast<BitCastInst>(Malloc) ?
1568 extractMallocCallFromBitCast(Malloc) : cast<CallInst>(Malloc);
1569 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001570
Evan Cheng86cd4452010-04-14 20:52:55 +00001571 GVI = PerformHeapAllocSRoA(GV, CI, getMallocArraySize(CI, TD, true),TD);
1572 return true;
Victor Hernandez83d63912009-09-18 22:35:49 +00001573 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001574
Victor Hernandez83d63912009-09-18 22:35:49 +00001575 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001576}
Victor Hernandez83d63912009-09-18 22:35:49 +00001577
Chris Lattner9b34a612004-10-09 21:48:45 +00001578// OptimizeOnceStoredGlobal - Try to optimize globals based on the knowledge
1579// that only one value (besides its initializer) is ever stored to the global.
Chris Lattner30ba5692004-10-11 05:54:41 +00001580static bool OptimizeOnceStoredGlobal(GlobalVariable *GV, Value *StoredOnceVal,
Chris Lattner7f8897f2006-08-27 22:42:52 +00001581 Module::global_iterator &GVI,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001582 TargetData *TD) {
Chris Lattner344b41c2008-12-15 21:20:32 +00001583 // Ignore no-op GEPs and bitcasts.
1584 StoredOnceVal = StoredOnceVal->stripPointerCasts();
Chris Lattner9b34a612004-10-09 21:48:45 +00001585
Chris Lattner708148e2004-10-10 23:14:11 +00001586 // If we are dealing with a pointer global that is initialized to null and
1587 // only has one (non-null) value stored into it, then we can optimize any
1588 // users of the loaded value (often calls and loads) that would trap if the
1589 // value was null.
Duncan Sands1df98592010-02-16 11:11:14 +00001590 if (GV->getInitializer()->getType()->isPointerTy() &&
Chris Lattner9b34a612004-10-09 21:48:45 +00001591 GV->getInitializer()->isNullValue()) {
Chris Lattner708148e2004-10-10 23:14:11 +00001592 if (Constant *SOVC = dyn_cast<Constant>(StoredOnceVal)) {
1593 if (GV->getInitializer()->getType() != SOVC->getType())
Chris Lattner98a42b22011-05-22 07:15:13 +00001594 SOVC = ConstantExpr::getBitCast(SOVC, GV->getInitializer()->getType());
Misha Brukmanfd939082005-04-21 23:48:37 +00001595
Chris Lattner708148e2004-10-10 23:14:11 +00001596 // Optimize away any trapping uses of the loaded value.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001597 if (OptimizeAwayTrappingUsesOfLoads(GV, SOVC))
Chris Lattner8be80122004-10-10 17:07:12 +00001598 return true;
Victor Hernandez83d63912009-09-18 22:35:49 +00001599 } else if (CallInst *CI = extractMallocCall(StoredOnceVal)) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001600 Type* MallocType = getMallocAllocatedType(CI);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001601 if (MallocType && TryToOptimizeStoreOfMallocToGlobal(GV, CI, MallocType,
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001602 GVI, TD))
1603 return true;
Chris Lattner708148e2004-10-10 23:14:11 +00001604 }
Chris Lattner9b34a612004-10-09 21:48:45 +00001605 }
Chris Lattner30ba5692004-10-11 05:54:41 +00001606
Chris Lattner9b34a612004-10-09 21:48:45 +00001607 return false;
1608}
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001609
Chris Lattner58e44f42008-01-14 01:17:44 +00001610/// TryToShrinkGlobalToBoolean - At this point, we have learned that the only
1611/// two values ever stored into GV are its initializer and OtherVal. See if we
1612/// can shrink the global into a boolean and select between the two values
1613/// whenever it is used. This exposes the values to other scalar optimizations.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001614static bool TryToShrinkGlobalToBoolean(GlobalVariable *GV, Constant *OtherVal) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001615 Type *GVElType = GV->getType()->getElementType();
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001616
Chris Lattner58e44f42008-01-14 01:17:44 +00001617 // If GVElType is already i1, it is already shrunk. If the type of the GV is
Chris Lattner6f6923f2009-03-07 23:32:02 +00001618 // an FP value, pointer or vector, don't do this optimization because a select
1619 // between them is very expensive and unlikely to lead to later
1620 // simplification. In these cases, we typically end up with "cond ? v1 : v2"
1621 // where v1 and v2 both require constant pool loads, a big loss.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001622 if (GVElType == Type::getInt1Ty(GV->getContext()) ||
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001623 GVElType->isFloatingPointTy() ||
Duncan Sands1df98592010-02-16 11:11:14 +00001624 GVElType->isPointerTy() || GVElType->isVectorTy())
Chris Lattner58e44f42008-01-14 01:17:44 +00001625 return false;
Gabor Greifaaaaa022010-07-12 14:13:15 +00001626
Chris Lattner58e44f42008-01-14 01:17:44 +00001627 // Walk the use list of the global seeing if all the uses are load or store.
1628 // If there is anything else, bail out.
Gabor Greifaaaaa022010-07-12 14:13:15 +00001629 for (Value::use_iterator I = GV->use_begin(), E = GV->use_end(); I != E; ++I){
1630 User *U = *I;
1631 if (!isa<LoadInst>(U) && !isa<StoreInst>(U))
Chris Lattner58e44f42008-01-14 01:17:44 +00001632 return false;
Gabor Greifaaaaa022010-07-12 14:13:15 +00001633 }
1634
David Greene3215b0e2010-01-05 01:28:05 +00001635 DEBUG(dbgs() << " *** SHRINKING TO BOOL: " << *GV);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001636
Chris Lattner96a86b22004-12-12 05:53:50 +00001637 // Create the new global, initializing it to false.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001638 GlobalVariable *NewGV = new GlobalVariable(Type::getInt1Ty(GV->getContext()),
1639 false,
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001640 GlobalValue::InternalLinkage,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001641 ConstantInt::getFalse(GV->getContext()),
Nick Lewycky0e670df2009-05-03 03:49:08 +00001642 GV->getName()+".b",
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +00001643 GV->isThreadLocal());
Chris Lattner96a86b22004-12-12 05:53:50 +00001644 GV->getParent()->getGlobalList().insert(GV, NewGV);
1645
1646 Constant *InitVal = GV->getInitializer();
Chris Lattner7b550cc2009-11-06 04:27:31 +00001647 assert(InitVal->getType() != Type::getInt1Ty(GV->getContext()) &&
Owen Anderson1d0be152009-08-13 21:58:54 +00001648 "No reason to shrink to bool!");
Chris Lattner96a86b22004-12-12 05:53:50 +00001649
1650 // If initialized to zero and storing one into the global, we can use a cast
1651 // instead of a select to synthesize the desired value.
1652 bool IsOneZero = false;
1653 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal))
Reid Spencercae57542007-03-02 00:28:52 +00001654 IsOneZero = InitVal->isNullValue() && CI->isOne();
Chris Lattner96a86b22004-12-12 05:53:50 +00001655
1656 while (!GV->use_empty()) {
Devang Patel771281f2009-03-06 01:39:36 +00001657 Instruction *UI = cast<Instruction>(GV->use_back());
1658 if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
Chris Lattner96a86b22004-12-12 05:53:50 +00001659 // Change the store into a boolean store.
1660 bool StoringOther = SI->getOperand(0) == OtherVal;
1661 // Only do this if we weren't storing a loaded value.
Chris Lattner38c25562004-12-12 19:34:41 +00001662 Value *StoreVal;
Chris Lattner96a86b22004-12-12 05:53:50 +00001663 if (StoringOther || SI->getOperand(0) == InitVal)
Chris Lattner7b550cc2009-11-06 04:27:31 +00001664 StoreVal = ConstantInt::get(Type::getInt1Ty(GV->getContext()),
1665 StoringOther);
Chris Lattner38c25562004-12-12 19:34:41 +00001666 else {
1667 // Otherwise, we are storing a previously loaded copy. To do this,
1668 // change the copy from copying the original value to just copying the
1669 // bool.
1670 Instruction *StoredVal = cast<Instruction>(SI->getOperand(0));
1671
Gabor Greif9e4f2432010-06-24 14:42:01 +00001672 // If we've already replaced the input, StoredVal will be a cast or
Chris Lattner38c25562004-12-12 19:34:41 +00001673 // select instruction. If not, it will be a load of the original
1674 // global.
1675 if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
1676 assert(LI->getOperand(0) == GV && "Not a copy!");
1677 // Insert a new load, to preserve the saved value.
1678 StoreVal = new LoadInst(NewGV, LI->getName()+".b", LI);
1679 } else {
1680 assert((isa<CastInst>(StoredVal) || isa<SelectInst>(StoredVal)) &&
1681 "This is not a form that we understand!");
1682 StoreVal = StoredVal->getOperand(0);
1683 assert(isa<LoadInst>(StoreVal) && "Not a load of NewGV!");
1684 }
1685 }
1686 new StoreInst(StoreVal, NewGV, SI);
Devang Patel771281f2009-03-06 01:39:36 +00001687 } else {
Chris Lattner96a86b22004-12-12 05:53:50 +00001688 // Change the load into a load of bool then a select.
Devang Patel771281f2009-03-06 01:39:36 +00001689 LoadInst *LI = cast<LoadInst>(UI);
Chris Lattner046800a2007-02-11 01:08:35 +00001690 LoadInst *NLI = new LoadInst(NewGV, LI->getName()+".b", LI);
Chris Lattner96a86b22004-12-12 05:53:50 +00001691 Value *NSI;
1692 if (IsOneZero)
Chris Lattner046800a2007-02-11 01:08:35 +00001693 NSI = new ZExtInst(NLI, LI->getType(), "", LI);
Misha Brukmanfd939082005-04-21 23:48:37 +00001694 else
Gabor Greif051a9502008-04-06 20:25:17 +00001695 NSI = SelectInst::Create(NLI, OtherVal, InitVal, "", LI);
Chris Lattner046800a2007-02-11 01:08:35 +00001696 NSI->takeName(LI);
Chris Lattner96a86b22004-12-12 05:53:50 +00001697 LI->replaceAllUsesWith(NSI);
Devang Patel771281f2009-03-06 01:39:36 +00001698 }
1699 UI->eraseFromParent();
Chris Lattner96a86b22004-12-12 05:53:50 +00001700 }
1701
1702 GV->eraseFromParent();
Chris Lattner58e44f42008-01-14 01:17:44 +00001703 return true;
Chris Lattner96a86b22004-12-12 05:53:50 +00001704}
1705
1706
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001707/// ProcessInternalGlobal - Analyze the specified global variable and optimize
1708/// it if possible. If we make a change, return true.
Rafael Espindolac4440e32011-01-19 16:32:21 +00001709bool GlobalOpt::ProcessGlobal(GlobalVariable *GV,
1710 Module::global_iterator &GVI) {
1711 if (!GV->hasLocalLinkage())
1712 return false;
1713
1714 // Do more involved optimizations if the global is internal.
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001715 GV->removeDeadConstantUsers();
1716
1717 if (GV->use_empty()) {
David Greene3215b0e2010-01-05 01:28:05 +00001718 DEBUG(dbgs() << "GLOBAL DEAD: " << *GV);
Chris Lattner7a7ed022004-10-16 18:09:00 +00001719 GV->eraseFromParent();
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001720 ++NumDeleted;
1721 return true;
1722 }
1723
Rafael Espindolac4440e32011-01-19 16:32:21 +00001724 SmallPtrSet<const PHINode*, 16> PHIUsers;
1725 GlobalStatus GS;
1726
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001727 if (AnalyzeGlobal(GV, GS, PHIUsers))
1728 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001729
Rafael Espindolac4440e32011-01-19 16:32:21 +00001730 if (!GS.isCompared && !GV->hasUnnamedAddr()) {
1731 GV->setUnnamedAddr(true);
1732 NumUnnamed++;
1733 }
1734
1735 if (GV->isConstant() || !GV->hasInitializer())
1736 return false;
1737
1738 return ProcessInternalGlobal(GV, GVI, PHIUsers, GS);
1739}
1740
1741/// ProcessInternalGlobal - Analyze the specified global variable and optimize
1742/// it if possible. If we make a change, return true.
1743bool GlobalOpt::ProcessInternalGlobal(GlobalVariable *GV,
1744 Module::global_iterator &GVI,
1745 const SmallPtrSet<const PHINode*, 16> &PHIUsers,
1746 const GlobalStatus &GS) {
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001747 // If this is a first class global and has only one accessing function
1748 // and this function is main (which we know is not recursive we can make
1749 // this global a local variable) we replace the global with a local alloca
1750 // in this function.
1751 //
1752 // NOTE: It doesn't make sense to promote non single-value types since we
1753 // are just replacing static memory to stack memory.
1754 //
1755 // If the global is in different address space, don't bring it to stack.
1756 if (!GS.HasMultipleAccessingFunctions &&
1757 GS.AccessingFunction && !GS.HasNonInstructionUser &&
1758 GV->getType()->getElementType()->isSingleValueType() &&
1759 GS.AccessingFunction->getName() == "main" &&
1760 GS.AccessingFunction->hasExternalLinkage() &&
1761 GV->getType()->getAddressSpace() == 0) {
1762 DEBUG(dbgs() << "LOCALIZING GLOBAL: " << *GV);
1763 Instruction& FirstI = const_cast<Instruction&>(*GS.AccessingFunction
1764 ->getEntryBlock().begin());
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001765 Type* ElemTy = GV->getType()->getElementType();
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001766 // FIXME: Pass Global's alignment when globals have alignment
1767 AllocaInst* Alloca = new AllocaInst(ElemTy, NULL, GV->getName(), &FirstI);
1768 if (!isa<UndefValue>(GV->getInitializer()))
1769 new StoreInst(GV->getInitializer(), Alloca, &FirstI);
Misha Brukmanfd939082005-04-21 23:48:37 +00001770
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001771 GV->replaceAllUsesWith(Alloca);
1772 GV->eraseFromParent();
1773 ++NumLocalized;
1774 return true;
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001775 }
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001776
1777 // If the global is never loaded (but may be stored to), it is dead.
1778 // Delete it now.
1779 if (!GS.isLoaded) {
1780 DEBUG(dbgs() << "GLOBAL NEVER LOADED: " << *GV);
1781
1782 // Delete any stores we can find to the global. We may not be able to
1783 // make it completely dead though.
1784 bool Changed = CleanupConstantGlobalUsers(GV, GV->getInitializer());
1785
1786 // If the global is dead now, delete it.
1787 if (GV->use_empty()) {
1788 GV->eraseFromParent();
1789 ++NumDeleted;
1790 Changed = true;
1791 }
1792 return Changed;
1793
1794 } else if (GS.StoredType <= GlobalStatus::isInitializerStored) {
1795 DEBUG(dbgs() << "MARKING CONSTANT: " << *GV);
1796 GV->setConstant(true);
1797
1798 // Clean up any obviously simplifiable users now.
1799 CleanupConstantGlobalUsers(GV, GV->getInitializer());
1800
1801 // If the global is dead now, just nuke it.
1802 if (GV->use_empty()) {
1803 DEBUG(dbgs() << " *** Marking constant allowed us to simplify "
1804 << "all users and delete global!\n");
1805 GV->eraseFromParent();
1806 ++NumDeleted;
1807 }
1808
1809 ++NumMarked;
1810 return true;
1811 } else if (!GV->getInitializer()->getType()->isSingleValueType()) {
1812 if (TargetData *TD = getAnalysisIfAvailable<TargetData>())
1813 if (GlobalVariable *FirstNewGV = SRAGlobal(GV, *TD)) {
1814 GVI = FirstNewGV; // Don't skip the newly produced globals!
1815 return true;
1816 }
1817 } else if (GS.StoredType == GlobalStatus::isStoredOnce) {
1818 // If the initial value for the global was an undef value, and if only
1819 // one other value was stored into it, we can just change the
1820 // initializer to be the stored value, then delete all stores to the
1821 // global. This allows us to mark it constant.
1822 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
1823 if (isa<UndefValue>(GV->getInitializer())) {
1824 // Change the initial value here.
1825 GV->setInitializer(SOVConstant);
1826
1827 // Clean up any obviously simplifiable users now.
1828 CleanupConstantGlobalUsers(GV, GV->getInitializer());
1829
1830 if (GV->use_empty()) {
1831 DEBUG(dbgs() << " *** Substituting initializer allowed us to "
1832 << "simplify all users and delete global!\n");
1833 GV->eraseFromParent();
1834 ++NumDeleted;
1835 } else {
1836 GVI = GV;
1837 }
1838 ++NumSubstitute;
1839 return true;
1840 }
1841
1842 // Try to optimize globals based on the knowledge that only one value
1843 // (besides its initializer) is ever stored to the global.
1844 if (OptimizeOnceStoredGlobal(GV, GS.StoredOnceValue, GVI,
1845 getAnalysisIfAvailable<TargetData>()))
1846 return true;
1847
1848 // Otherwise, if the global was not a boolean, we can shrink it to be a
1849 // boolean.
1850 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
1851 if (TryToShrinkGlobalToBoolean(GV, SOVConstant)) {
1852 ++NumShrunkToBool;
1853 return true;
1854 }
1855 }
1856
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001857 return false;
1858}
1859
Chris Lattnerfb217ad2005-05-08 22:18:06 +00001860/// ChangeCalleesToFastCall - Walk all of the direct calls of the specified
1861/// function, changing them to FastCC.
1862static void ChangeCalleesToFastCall(Function *F) {
1863 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
Duncan Sands548448a2008-02-18 17:32:13 +00001864 CallSite User(cast<Instruction>(*UI));
1865 User.setCallingConv(CallingConv::Fast);
Chris Lattnerfb217ad2005-05-08 22:18:06 +00001866 }
1867}
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001868
Devang Patel05988662008-09-25 21:00:45 +00001869static AttrListPtr StripNest(const AttrListPtr &Attrs) {
Chris Lattner58d74912008-03-12 17:45:29 +00001870 for (unsigned i = 0, e = Attrs.getNumSlots(); i != e; ++i) {
Devang Patel05988662008-09-25 21:00:45 +00001871 if ((Attrs.getSlot(i).Attrs & Attribute::Nest) == 0)
Duncan Sands548448a2008-02-18 17:32:13 +00001872 continue;
1873
Duncan Sands548448a2008-02-18 17:32:13 +00001874 // There can be only one.
Devang Patel05988662008-09-25 21:00:45 +00001875 return Attrs.removeAttr(Attrs.getSlot(i).Index, Attribute::Nest);
Duncan Sands3d5378f2008-02-16 20:56:04 +00001876 }
1877
1878 return Attrs;
1879}
1880
1881static void RemoveNestAttribute(Function *F) {
Devang Patel05988662008-09-25 21:00:45 +00001882 F->setAttributes(StripNest(F->getAttributes()));
Duncan Sands3d5378f2008-02-16 20:56:04 +00001883 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
Duncan Sands548448a2008-02-18 17:32:13 +00001884 CallSite User(cast<Instruction>(*UI));
Devang Patel05988662008-09-25 21:00:45 +00001885 User.setAttributes(StripNest(User.getAttributes()));
Duncan Sands3d5378f2008-02-16 20:56:04 +00001886 }
1887}
1888
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001889bool GlobalOpt::OptimizeFunctions(Module &M) {
1890 bool Changed = false;
1891 // Optimize functions.
1892 for (Module::iterator FI = M.begin(), E = M.end(); FI != E; ) {
1893 Function *F = FI++;
Duncan Sandsfc5940d2009-03-06 10:21:56 +00001894 // Functions without names cannot be referenced outside this module.
1895 if (!F->hasName() && !F->isDeclaration())
1896 F->setLinkage(GlobalValue::InternalLinkage);
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001897 F->removeDeadConstantUsers();
Eli Friedmanc6633052011-10-20 05:23:42 +00001898 if (F->isDefTriviallyDead()) {
Chris Lattnerec4c7b92009-11-01 19:03:42 +00001899 F->eraseFromParent();
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001900 Changed = true;
1901 ++NumFnDeleted;
Rafael Espindolabb46f522009-01-15 20:18:42 +00001902 } else if (F->hasLocalLinkage()) {
Duncan Sands3d5378f2008-02-16 20:56:04 +00001903 if (F->getCallingConv() == CallingConv::C && !F->isVarArg() &&
Jay Foad757068f2009-06-10 08:41:11 +00001904 !F->hasAddressTaken()) {
Duncan Sands3d5378f2008-02-16 20:56:04 +00001905 // If this function has C calling conventions, is not a varargs
1906 // function, and is only called directly, promote it to use the Fast
1907 // calling convention.
1908 F->setCallingConv(CallingConv::Fast);
1909 ChangeCalleesToFastCall(F);
1910 ++NumFastCallFns;
1911 Changed = true;
1912 }
1913
Devang Patel05988662008-09-25 21:00:45 +00001914 if (F->getAttributes().hasAttrSomewhere(Attribute::Nest) &&
Jay Foad757068f2009-06-10 08:41:11 +00001915 !F->hasAddressTaken()) {
Duncan Sands3d5378f2008-02-16 20:56:04 +00001916 // The function is not used by a trampoline intrinsic, so it is safe
1917 // to remove the 'nest' attribute.
1918 RemoveNestAttribute(F);
1919 ++NumNestRemoved;
1920 Changed = true;
1921 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001922 }
1923 }
1924 return Changed;
1925}
1926
1927bool GlobalOpt::OptimizeGlobalVars(Module &M) {
1928 bool Changed = false;
1929 for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
1930 GVI != E; ) {
1931 GlobalVariable *GV = GVI++;
Duncan Sandsfc5940d2009-03-06 10:21:56 +00001932 // Global variables without names cannot be referenced outside this module.
1933 if (!GV->hasName() && !GV->isDeclaration())
1934 GV->setLinkage(GlobalValue::InternalLinkage);
Dan Gohman01b97dd2009-11-23 16:22:21 +00001935 // Simplify the initializer.
1936 if (GV->hasInitializer())
1937 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GV->getInitializer())) {
Dan Gohmanf860db22010-04-02 03:04:37 +00001938 TargetData *TD = getAnalysisIfAvailable<TargetData>();
Dan Gohman01b97dd2009-11-23 16:22:21 +00001939 Constant *New = ConstantFoldConstantExpression(CE, TD);
1940 if (New && New != CE)
1941 GV->setInitializer(New);
1942 }
Rafael Espindolac4440e32011-01-19 16:32:21 +00001943
1944 Changed |= ProcessGlobal(GV, GVI);
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001945 }
1946 return Changed;
1947}
1948
Nick Lewycky2c44a802011-04-08 07:30:21 +00001949/// FindGlobalCtors - Find the llvm.global_ctors list, verifying that all
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001950/// initializers have an init priority of 65535.
1951GlobalVariable *GlobalOpt::FindGlobalCtors(Module &M) {
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00001952 GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
1953 if (GV == 0) return 0;
1954
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00001955 // Verify that the initializer is simple enough for us to handle. We are
1956 // only allowed to optimize the initializer if it is unique.
1957 if (!GV->hasUniqueInitializer()) return 0;
Nick Lewycky5ea5c612011-04-11 22:11:20 +00001958
1959 if (isa<ConstantAggregateZero>(GV->getInitializer()))
1960 return GV;
1961 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
Eli Friedman18a2e502011-04-09 09:11:09 +00001962
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00001963 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i) {
Nick Lewycky5ea5c612011-04-11 22:11:20 +00001964 if (isa<ConstantAggregateZero>(*i))
1965 continue;
1966 ConstantStruct *CS = cast<ConstantStruct>(*i);
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00001967 if (isa<ConstantPointerNull>(CS->getOperand(1)))
1968 continue;
Chris Lattner7d8e58f2005-09-26 02:19:27 +00001969
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00001970 // Must have a function or null ptr.
1971 if (!isa<Function>(CS->getOperand(1)))
1972 return 0;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001973
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00001974 // Init priority must be standard.
Nick Lewycky2c44a802011-04-08 07:30:21 +00001975 ConstantInt *CI = cast<ConstantInt>(CS->getOperand(0));
1976 if (CI->getZExtValue() != 65535)
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00001977 return 0;
1978 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001979
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00001980 return GV;
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001981}
1982
Chris Lattnerdb973e62005-09-26 02:31:18 +00001983/// ParseGlobalCtors - Given a llvm.global_ctors list that we can understand,
1984/// return a list of the functions and null terminator as a vector.
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001985static std::vector<Function*> ParseGlobalCtors(GlobalVariable *GV) {
Nick Lewycky5ea5c612011-04-11 22:11:20 +00001986 if (GV->getInitializer()->isNullValue())
1987 return std::vector<Function*>();
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001988 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
1989 std::vector<Function*> Result;
1990 Result.reserve(CA->getNumOperands());
Gabor Greif5e463212008-05-29 01:59:18 +00001991 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i) {
1992 ConstantStruct *CS = cast<ConstantStruct>(*i);
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001993 Result.push_back(dyn_cast<Function>(CS->getOperand(1)));
1994 }
1995 return Result;
1996}
1997
Chris Lattnerdb973e62005-09-26 02:31:18 +00001998/// InstallGlobalCtors - Given a specified llvm.global_ctors list, install the
1999/// specified array, returning the new global to use.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002000static GlobalVariable *InstallGlobalCtors(GlobalVariable *GCL,
Chris Lattner7b550cc2009-11-06 04:27:31 +00002001 const std::vector<Function*> &Ctors) {
Chris Lattnerdb973e62005-09-26 02:31:18 +00002002 // If we made a change, reassemble the initializer list.
Chris Lattnerb065b062011-06-20 04:01:31 +00002003 Constant *CSVals[2];
2004 CSVals[0] = ConstantInt::get(Type::getInt32Ty(GCL->getContext()), 65535);
2005 CSVals[1] = 0;
2006
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002007 StructType *StructTy =
Chris Lattnerb065b062011-06-20 04:01:31 +00002008 cast <StructType>(
2009 cast<ArrayType>(GCL->getType()->getElementType())->getElementType());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002010
Chris Lattnerdb973e62005-09-26 02:31:18 +00002011 // Create the new init list.
2012 std::vector<Constant*> CAList;
2013 for (unsigned i = 0, e = Ctors.size(); i != e; ++i) {
Chris Lattner79c11012005-09-26 04:44:35 +00002014 if (Ctors[i]) {
Chris Lattnerdb973e62005-09-26 02:31:18 +00002015 CSVals[1] = Ctors[i];
Chris Lattner79c11012005-09-26 04:44:35 +00002016 } else {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002017 Type *FTy = FunctionType::get(Type::getVoidTy(GCL->getContext()),
Chris Lattner7b550cc2009-11-06 04:27:31 +00002018 false);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002019 PointerType *PFTy = PointerType::getUnqual(FTy);
Owen Andersona7235ea2009-07-31 20:28:14 +00002020 CSVals[1] = Constant::getNullValue(PFTy);
Chris Lattner7b550cc2009-11-06 04:27:31 +00002021 CSVals[0] = ConstantInt::get(Type::getInt32Ty(GCL->getContext()),
Nick Lewycky5ea5c612011-04-11 22:11:20 +00002022 0x7fffffff);
Chris Lattnerdb973e62005-09-26 02:31:18 +00002023 }
Chris Lattnerb065b062011-06-20 04:01:31 +00002024 CAList.push_back(ConstantStruct::get(StructTy, CSVals));
Chris Lattnerdb973e62005-09-26 02:31:18 +00002025 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002026
Chris Lattnerdb973e62005-09-26 02:31:18 +00002027 // Create the array initializer.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002028 Constant *CA = ConstantArray::get(ArrayType::get(StructTy,
Nick Lewyckyc332fba2009-09-19 20:30:26 +00002029 CAList.size()), CAList);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002030
Chris Lattnerdb973e62005-09-26 02:31:18 +00002031 // If we didn't change the number of elements, don't create a new GV.
2032 if (CA->getType() == GCL->getInitializer()->getType()) {
2033 GCL->setInitializer(CA);
2034 return GCL;
2035 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002036
Chris Lattnerdb973e62005-09-26 02:31:18 +00002037 // Create the new global and insert it next to the existing list.
Chris Lattner7b550cc2009-11-06 04:27:31 +00002038 GlobalVariable *NGV = new GlobalVariable(CA->getType(), GCL->isConstant(),
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +00002039 GCL->getLinkage(), CA, "",
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +00002040 GCL->isThreadLocal());
Chris Lattnerdb973e62005-09-26 02:31:18 +00002041 GCL->getParent()->getGlobalList().insert(GCL, NGV);
Chris Lattner046800a2007-02-11 01:08:35 +00002042 NGV->takeName(GCL);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002043
Chris Lattnerdb973e62005-09-26 02:31:18 +00002044 // Nuke the old list, replacing any uses with the new one.
2045 if (!GCL->use_empty()) {
2046 Constant *V = NGV;
2047 if (V->getType() != GCL->getType())
Owen Andersonbaf3c402009-07-29 18:55:55 +00002048 V = ConstantExpr::getBitCast(V, GCL->getType());
Chris Lattnerdb973e62005-09-26 02:31:18 +00002049 GCL->replaceAllUsesWith(V);
2050 }
2051 GCL->eraseFromParent();
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002052
Chris Lattnerdb973e62005-09-26 02:31:18 +00002053 if (Ctors.size())
2054 return NGV;
2055 else
2056 return 0;
2057}
Chris Lattner79c11012005-09-26 04:44:35 +00002058
2059
Chris Lattner1945d582010-12-07 04:33:29 +00002060static Constant *getVal(DenseMap<Value*, Constant*> &ComputedValues, Value *V) {
Chris Lattner79c11012005-09-26 04:44:35 +00002061 if (Constant *CV = dyn_cast<Constant>(V)) return CV;
2062 Constant *R = ComputedValues[V];
2063 assert(R && "Reference to an uncomputed value!");
2064 return R;
2065}
2066
Chris Lattner1945d582010-12-07 04:33:29 +00002067static inline bool
2068isSimpleEnoughValueToCommit(Constant *C,
2069 SmallPtrSet<Constant*, 8> &SimpleConstants);
2070
2071
2072/// isSimpleEnoughValueToCommit - Return true if the specified constant can be
2073/// handled by the code generator. We don't want to generate something like:
2074/// void *X = &X/42;
2075/// because the code generator doesn't have a relocation that can handle that.
2076///
2077/// This function should be called if C was not found (but just got inserted)
2078/// in SimpleConstants to avoid having to rescan the same constants all the
2079/// time.
2080static bool isSimpleEnoughValueToCommitHelper(Constant *C,
2081 SmallPtrSet<Constant*, 8> &SimpleConstants) {
2082 // Simple integer, undef, constant aggregate zero, global addresses, etc are
2083 // all supported.
2084 if (C->getNumOperands() == 0 || isa<BlockAddress>(C) ||
2085 isa<GlobalValue>(C))
2086 return true;
2087
2088 // Aggregate values are safe if all their elements are.
2089 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C) ||
2090 isa<ConstantVector>(C)) {
2091 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i) {
2092 Constant *Op = cast<Constant>(C->getOperand(i));
2093 if (!isSimpleEnoughValueToCommit(Op, SimpleConstants))
2094 return false;
2095 }
2096 return true;
2097 }
2098
2099 // We don't know exactly what relocations are allowed in constant expressions,
2100 // so we allow &global+constantoffset, which is safe and uniformly supported
2101 // across targets.
2102 ConstantExpr *CE = cast<ConstantExpr>(C);
2103 switch (CE->getOpcode()) {
2104 case Instruction::BitCast:
2105 case Instruction::IntToPtr:
2106 case Instruction::PtrToInt:
2107 // These casts are always fine if the casted value is.
2108 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants);
2109
2110 // GEP is fine if it is simple + constant offset.
2111 case Instruction::GetElementPtr:
2112 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
2113 if (!isa<ConstantInt>(CE->getOperand(i)))
2114 return false;
2115 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants);
2116
2117 case Instruction::Add:
2118 // We allow simple+cst.
2119 if (!isa<ConstantInt>(CE->getOperand(1)))
2120 return false;
2121 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants);
2122 }
2123 return false;
2124}
2125
2126static inline bool
2127isSimpleEnoughValueToCommit(Constant *C,
2128 SmallPtrSet<Constant*, 8> &SimpleConstants) {
2129 // If we already checked this constant, we win.
2130 if (!SimpleConstants.insert(C)) return true;
2131 // Check the constant.
2132 return isSimpleEnoughValueToCommitHelper(C, SimpleConstants);
2133}
2134
2135
Chris Lattner79c11012005-09-26 04:44:35 +00002136/// isSimpleEnoughPointerToCommit - Return true if this constant is simple
Owen Andersoncff6b372011-01-14 22:19:20 +00002137/// enough for us to understand. In particular, if it is a cast to anything
2138/// other than from one pointer type to another pointer type, we punt.
2139/// We basically just support direct accesses to globals and GEP's of
Chris Lattner79c11012005-09-26 04:44:35 +00002140/// globals. This should be kept up to date with CommitValueTo.
Chris Lattner7b550cc2009-11-06 04:27:31 +00002141static bool isSimpleEnoughPointerToCommit(Constant *C) {
Dan Gohmance5de5b2009-09-07 22:42:05 +00002142 // Conservatively, avoid aggregate types. This is because we don't
2143 // want to worry about them partially overlapping other stores.
2144 if (!cast<PointerType>(C->getType())->getElementType()->isSingleValueType())
2145 return false;
2146
Dan Gohmanfd54a892009-09-07 22:31:26 +00002147 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
Mikhail Glushenkov99fca5d2010-10-19 16:47:23 +00002148 // Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or
Dan Gohmanfd54a892009-09-07 22:31:26 +00002149 // external globals.
Mikhail Glushenkov99fca5d2010-10-19 16:47:23 +00002150 return GV->hasUniqueInitializer();
Dan Gohmanfd54a892009-09-07 22:31:26 +00002151
Owen Andersone95a32c2011-01-14 22:31:13 +00002152 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002153 // Handle a constantexpr gep.
2154 if (CE->getOpcode() == Instruction::GetElementPtr &&
Dan Gohmanc62482d2009-09-07 22:40:13 +00002155 isa<GlobalVariable>(CE->getOperand(0)) &&
2156 cast<GEPOperator>(CE)->isInBounds()) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002157 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
Mikhail Glushenkov99fca5d2010-10-19 16:47:23 +00002158 // Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or
Dan Gohmanfd54a892009-09-07 22:31:26 +00002159 // external globals.
Mikhail Glushenkov99fca5d2010-10-19 16:47:23 +00002160 if (!GV->hasUniqueInitializer())
Dan Gohmanfd54a892009-09-07 22:31:26 +00002161 return false;
Dan Gohman80bdc962009-09-07 22:44:55 +00002162
Dan Gohman80bdc962009-09-07 22:44:55 +00002163 // The first index must be zero.
Oscar Fuentesee56c422010-08-02 06:00:15 +00002164 ConstantInt *CI = dyn_cast<ConstantInt>(*llvm::next(CE->op_begin()));
Dan Gohman80bdc962009-09-07 22:44:55 +00002165 if (!CI || !CI->isZero()) return false;
Dan Gohman80bdc962009-09-07 22:44:55 +00002166
2167 // The remaining indices must be compile-time known integers within the
Dan Gohmane6992f72009-09-10 23:37:55 +00002168 // notional bounds of the corresponding static array types.
2169 if (!CE->isGEPWithNoNotionalOverIndexing())
2170 return false;
Dan Gohman80bdc962009-09-07 22:44:55 +00002171
Dan Gohmanc6f69e92009-10-05 16:36:26 +00002172 return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
Owen Andersoncff6b372011-01-14 22:19:20 +00002173
2174 // A constantexpr bitcast from a pointer to another pointer is a no-op,
2175 // and we know how to evaluate it by moving the bitcast from the pointer
2176 // operand to the value operand.
2177 } else if (CE->getOpcode() == Instruction::BitCast &&
Chris Lattnerd5f656f2011-01-16 02:05:10 +00002178 isa<GlobalVariable>(CE->getOperand(0))) {
Owen Andersoncff6b372011-01-14 22:19:20 +00002179 // Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or
2180 // external globals.
Chris Lattnerd5f656f2011-01-16 02:05:10 +00002181 return cast<GlobalVariable>(CE->getOperand(0))->hasUniqueInitializer();
Chris Lattner798b4d52005-09-26 06:52:44 +00002182 }
Owen Andersone95a32c2011-01-14 22:31:13 +00002183 }
2184
Chris Lattner79c11012005-09-26 04:44:35 +00002185 return false;
2186}
2187
Chris Lattner798b4d52005-09-26 06:52:44 +00002188/// EvaluateStoreInto - Evaluate a piece of a constantexpr store into a global
2189/// initializer. This returns 'Init' modified to reflect 'Val' stored into it.
2190/// At this point, the GEP operands of Addr [0, OpNo) have been stepped into.
2191static Constant *EvaluateStoreInto(Constant *Init, Constant *Val,
Chris Lattner7b550cc2009-11-06 04:27:31 +00002192 ConstantExpr *Addr, unsigned OpNo) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002193 // Base case of the recursion.
2194 if (OpNo == Addr->getNumOperands()) {
2195 assert(Val->getType() == Init->getType() && "Type mismatch!");
2196 return Val;
2197 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002198
Chris Lattnera0e9a242010-01-07 01:16:21 +00002199 std::vector<Constant*> Elts;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002200 if (StructType *STy = dyn_cast<StructType>(Init->getType())) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002201
2202 // Break up the constant into its elements.
2203 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
Gabor Greif5e463212008-05-29 01:59:18 +00002204 for (User::op_iterator i = CS->op_begin(), e = CS->op_end(); i != e; ++i)
2205 Elts.push_back(cast<Constant>(*i));
Chris Lattner798b4d52005-09-26 06:52:44 +00002206 } else if (isa<ConstantAggregateZero>(Init)) {
2207 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
Owen Andersona7235ea2009-07-31 20:28:14 +00002208 Elts.push_back(Constant::getNullValue(STy->getElementType(i)));
Chris Lattner798b4d52005-09-26 06:52:44 +00002209 } else if (isa<UndefValue>(Init)) {
2210 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002211 Elts.push_back(UndefValue::get(STy->getElementType(i)));
Chris Lattner798b4d52005-09-26 06:52:44 +00002212 } else {
Torok Edwinc23197a2009-07-14 16:55:14 +00002213 llvm_unreachable("This code is out of sync with "
Chris Lattner798b4d52005-09-26 06:52:44 +00002214 " ConstantFoldLoadThroughGEPConstantExpr");
2215 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002216
Chris Lattner798b4d52005-09-26 06:52:44 +00002217 // Replace the element that we are supposed to.
Reid Spencerb83eb642006-10-20 07:07:24 +00002218 ConstantInt *CU = cast<ConstantInt>(Addr->getOperand(OpNo));
2219 unsigned Idx = CU->getZExtValue();
2220 assert(Idx < STy->getNumElements() && "Struct index out of range!");
Chris Lattner7b550cc2009-11-06 04:27:31 +00002221 Elts[Idx] = EvaluateStoreInto(Elts[Idx], Val, Addr, OpNo+1);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002222
Chris Lattner798b4d52005-09-26 06:52:44 +00002223 // Return the modified struct.
Chris Lattnerb065b062011-06-20 04:01:31 +00002224 return ConstantStruct::get(STy, Elts);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002225 }
Chris Lattnerb065b062011-06-20 04:01:31 +00002226
2227 ConstantInt *CI = cast<ConstantInt>(Addr->getOperand(OpNo));
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002228 SequentialType *InitTy = cast<SequentialType>(Init->getType());
Chris Lattnerb065b062011-06-20 04:01:31 +00002229
2230 uint64_t NumElts;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002231 if (ArrayType *ATy = dyn_cast<ArrayType>(InitTy))
Chris Lattnerb065b062011-06-20 04:01:31 +00002232 NumElts = ATy->getNumElements();
2233 else
2234 NumElts = cast<VectorType>(InitTy)->getNumElements();
2235
2236 // Break up the array into elements.
2237 if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
2238 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i)
2239 Elts.push_back(cast<Constant>(*i));
2240 } else if (ConstantVector *CV = dyn_cast<ConstantVector>(Init)) {
2241 for (User::op_iterator i = CV->op_begin(), e = CV->op_end(); i != e; ++i)
2242 Elts.push_back(cast<Constant>(*i));
2243 } else if (isa<ConstantAggregateZero>(Init)) {
2244 Elts.assign(NumElts, Constant::getNullValue(InitTy->getElementType()));
2245 } else {
2246 assert(isa<UndefValue>(Init) && "This code is out of sync with "
2247 " ConstantFoldLoadThroughGEPConstantExpr");
2248 Elts.assign(NumElts, UndefValue::get(InitTy->getElementType()));
2249 }
2250
2251 assert(CI->getZExtValue() < NumElts);
2252 Elts[CI->getZExtValue()] =
2253 EvaluateStoreInto(Elts[CI->getZExtValue()], Val, Addr, OpNo+1);
2254
2255 if (Init->getType()->isArrayTy())
2256 return ConstantArray::get(cast<ArrayType>(InitTy), Elts);
2257 return ConstantVector::get(Elts);
Chris Lattner798b4d52005-09-26 06:52:44 +00002258}
2259
Chris Lattner79c11012005-09-26 04:44:35 +00002260/// CommitValueTo - We have decided that Addr (which satisfies the predicate
2261/// isSimpleEnoughPointerToCommit) should get Val as its value. Make it happen.
Chris Lattner7b550cc2009-11-06 04:27:31 +00002262static void CommitValueTo(Constant *Val, Constant *Addr) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002263 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Addr)) {
2264 assert(GV->hasInitializer());
2265 GV->setInitializer(Val);
2266 return;
2267 }
Chris Lattnera0e9a242010-01-07 01:16:21 +00002268
Chris Lattner798b4d52005-09-26 06:52:44 +00002269 ConstantExpr *CE = cast<ConstantExpr>(Addr);
2270 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
Chris Lattnera0e9a242010-01-07 01:16:21 +00002271 GV->setInitializer(EvaluateStoreInto(GV->getInitializer(), Val, CE, 2));
Chris Lattner79c11012005-09-26 04:44:35 +00002272}
2273
Chris Lattner562a0552005-09-26 05:16:34 +00002274/// ComputeLoadResult - Return the value that would be computed by a load from
2275/// P after the stores reflected by 'memory' have been performed. If we can't
2276/// decide, return null.
Chris Lattner04de1cf2005-09-26 05:15:37 +00002277static Constant *ComputeLoadResult(Constant *P,
Chris Lattner7b550cc2009-11-06 04:27:31 +00002278 const DenseMap<Constant*, Constant*> &Memory) {
Chris Lattner04de1cf2005-09-26 05:15:37 +00002279 // If this memory location has been recently stored, use the stored value: it
2280 // is the most up-to-date.
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002281 DenseMap<Constant*, Constant*>::const_iterator I = Memory.find(P);
Chris Lattner04de1cf2005-09-26 05:15:37 +00002282 if (I != Memory.end()) return I->second;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002283
Chris Lattner04de1cf2005-09-26 05:15:37 +00002284 // Access it.
2285 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(P)) {
Dan Gohman82555732009-08-19 18:20:44 +00002286 if (GV->hasDefinitiveInitializer())
Chris Lattner04de1cf2005-09-26 05:15:37 +00002287 return GV->getInitializer();
2288 return 0;
Chris Lattner04de1cf2005-09-26 05:15:37 +00002289 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002290
Chris Lattner798b4d52005-09-26 06:52:44 +00002291 // Handle a constantexpr getelementptr.
2292 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(P))
2293 if (CE->getOpcode() == Instruction::GetElementPtr &&
2294 isa<GlobalVariable>(CE->getOperand(0))) {
2295 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
Dan Gohman82555732009-08-19 18:20:44 +00002296 if (GV->hasDefinitiveInitializer())
Dan Gohmanc6f69e92009-10-05 16:36:26 +00002297 return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
Chris Lattner798b4d52005-09-26 06:52:44 +00002298 }
2299
2300 return 0; // don't know how to evaluate.
Chris Lattner04de1cf2005-09-26 05:15:37 +00002301}
2302
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002303/// EvaluateFunction - Evaluate a call to function F, returning true if
2304/// successful, false if we can't evaluate it. ActualArgs contains the formal
2305/// arguments for the function.
Chris Lattnercd271422005-09-27 04:45:34 +00002306static bool EvaluateFunction(Function *F, Constant *&RetVal,
Duncan Sandsfa6a1cf2009-08-17 14:33:27 +00002307 const SmallVectorImpl<Constant*> &ActualArgs,
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002308 std::vector<Function*> &CallStack,
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002309 DenseMap<Constant*, Constant*> &MutatedMemory,
Chris Lattner1945d582010-12-07 04:33:29 +00002310 std::vector<GlobalVariable*> &AllocaTmps,
2311 SmallPtrSet<Constant*, 8> &SimpleConstants,
Chad Rosier00737bd2011-12-01 21:29:16 +00002312 const TargetData *TD,
2313 const TargetLibraryInfo *TLI) {
Chris Lattnercd271422005-09-27 04:45:34 +00002314 // Check to see if this function is already executing (recursion). If so,
2315 // bail out. TODO: we might want to accept limited recursion.
2316 if (std::find(CallStack.begin(), CallStack.end(), F) != CallStack.end())
2317 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002318
Chris Lattnercd271422005-09-27 04:45:34 +00002319 CallStack.push_back(F);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002320
Chris Lattner79c11012005-09-26 04:44:35 +00002321 /// Values - As we compute SSA register values, we store their contents here.
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002322 DenseMap<Value*, Constant*> Values;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002323
Chris Lattnercd271422005-09-27 04:45:34 +00002324 // Initialize arguments to the incoming values specified.
2325 unsigned ArgNo = 0;
2326 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); AI != E;
2327 ++AI, ++ArgNo)
2328 Values[AI] = ActualArgs[ArgNo];
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002329
Chris Lattnercdf98be2005-09-26 04:57:38 +00002330 /// ExecutedBlocks - We only handle non-looping, non-recursive code. As such,
2331 /// we can only evaluate any one basic block at most once. This set keeps
2332 /// track of what we have executed so we can detect recursive cases etc.
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002333 SmallPtrSet<BasicBlock*, 32> ExecutedBlocks;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002334
Chris Lattner79c11012005-09-26 04:44:35 +00002335 // CurInst - The current instruction we're evaluating.
2336 BasicBlock::iterator CurInst = F->begin()->begin();
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002337
Chris Lattner79c11012005-09-26 04:44:35 +00002338 // This is the main evaluation loop.
2339 while (1) {
2340 Constant *InstResult = 0;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002341
Chris Lattner79c11012005-09-26 04:44:35 +00002342 if (StoreInst *SI = dyn_cast<StoreInst>(CurInst)) {
Eli Friedman33cb4452011-08-16 00:20:11 +00002343 if (!SI->isSimple()) return false; // no volatile/atomic accesses.
Chris Lattner79c11012005-09-26 04:44:35 +00002344 Constant *Ptr = getVal(Values, SI->getOperand(1));
Chris Lattner7b550cc2009-11-06 04:27:31 +00002345 if (!isSimpleEnoughPointerToCommit(Ptr))
Chris Lattner79c11012005-09-26 04:44:35 +00002346 // If this is too complex for us to commit, reject it.
Chris Lattnercd271422005-09-27 04:45:34 +00002347 return false;
Chris Lattner1945d582010-12-07 04:33:29 +00002348
Chris Lattner79c11012005-09-26 04:44:35 +00002349 Constant *Val = getVal(Values, SI->getOperand(0));
Chris Lattner1945d582010-12-07 04:33:29 +00002350
2351 // If this might be too difficult for the backend to handle (e.g. the addr
2352 // of one global variable divided by another) then we can't commit it.
2353 if (!isSimpleEnoughValueToCommit(Val, SimpleConstants))
2354 return false;
Owen Andersoncff6b372011-01-14 22:19:20 +00002355
2356 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
2357 if (CE->getOpcode() == Instruction::BitCast) {
2358 // If we're evaluating a store through a bitcast, then we need
2359 // to pull the bitcast off the pointer type and push it onto the
2360 // stored value.
Chris Lattnerd5f656f2011-01-16 02:05:10 +00002361 Ptr = CE->getOperand(0);
Owen Andersoncff6b372011-01-14 22:19:20 +00002362
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002363 Type *NewTy=cast<PointerType>(Ptr->getType())->getElementType();
Owen Andersoncff6b372011-01-14 22:19:20 +00002364
Owen Anderson66f708f2011-01-16 04:33:33 +00002365 // In order to push the bitcast onto the stored value, a bitcast
2366 // from NewTy to Val's type must be legal. If it's not, we can try
2367 // introspecting NewTy to find a legal conversion.
2368 while (!Val->getType()->canLosslesslyBitCastTo(NewTy)) {
2369 // If NewTy is a struct, we can convert the pointer to the struct
2370 // into a pointer to its first member.
2371 // FIXME: This could be extended to support arrays as well.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002372 if (StructType *STy = dyn_cast<StructType>(NewTy)) {
Owen Anderson66f708f2011-01-16 04:33:33 +00002373 NewTy = STy->getTypeAtIndex(0U);
2374
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002375 IntegerType *IdxTy =IntegerType::get(NewTy->getContext(), 32);
Owen Anderson66f708f2011-01-16 04:33:33 +00002376 Constant *IdxZero = ConstantInt::get(IdxTy, 0, false);
2377 Constant * const IdxList[] = {IdxZero, IdxZero};
2378
Jay Foadb4263a62011-07-22 08:52:50 +00002379 Ptr = ConstantExpr::getGetElementPtr(Ptr, IdxList);
Owen Andersoncff6b372011-01-14 22:19:20 +00002380
Owen Anderson66f708f2011-01-16 04:33:33 +00002381 // If we can't improve the situation by introspecting NewTy,
2382 // we have to give up.
2383 } else {
2384 return 0;
2385 }
Owen Andersoncff6b372011-01-14 22:19:20 +00002386 }
2387
Owen Anderson66f708f2011-01-16 04:33:33 +00002388 // If we found compatible types, go ahead and push the bitcast
2389 // onto the stored value.
Owen Andersoncff6b372011-01-14 22:19:20 +00002390 Val = ConstantExpr::getBitCast(Val, NewTy);
2391 }
2392
Chris Lattner79c11012005-09-26 04:44:35 +00002393 MutatedMemory[Ptr] = Val;
2394 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CurInst)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002395 InstResult = ConstantExpr::get(BO->getOpcode(),
Chris Lattner79c11012005-09-26 04:44:35 +00002396 getVal(Values, BO->getOperand(0)),
2397 getVal(Values, BO->getOperand(1)));
Reid Spencere4d87aa2006-12-23 06:05:41 +00002398 } else if (CmpInst *CI = dyn_cast<CmpInst>(CurInst)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002399 InstResult = ConstantExpr::getCompare(CI->getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00002400 getVal(Values, CI->getOperand(0)),
2401 getVal(Values, CI->getOperand(1)));
Chris Lattner79c11012005-09-26 04:44:35 +00002402 } else if (CastInst *CI = dyn_cast<CastInst>(CurInst)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002403 InstResult = ConstantExpr::getCast(CI->getOpcode(),
Chris Lattner9a989f02006-11-30 17:26:08 +00002404 getVal(Values, CI->getOperand(0)),
Chris Lattner79c11012005-09-26 04:44:35 +00002405 CI->getType());
2406 } else if (SelectInst *SI = dyn_cast<SelectInst>(CurInst)) {
Gabor Greif9e4f2432010-06-24 14:42:01 +00002407 InstResult = ConstantExpr::getSelect(getVal(Values, SI->getOperand(0)),
Eric Christopher551754c2010-04-16 23:37:20 +00002408 getVal(Values, SI->getOperand(1)),
2409 getVal(Values, SI->getOperand(2)));
Chris Lattner04de1cf2005-09-26 05:15:37 +00002410 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurInst)) {
2411 Constant *P = getVal(Values, GEP->getOperand(0));
Chris Lattner55eb1c42007-01-31 04:40:53 +00002412 SmallVector<Constant*, 8> GEPOps;
Gabor Greif5e463212008-05-29 01:59:18 +00002413 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end();
2414 i != e; ++i)
2415 GEPOps.push_back(getVal(Values, *i));
Jay Foad4b5e2072011-07-21 15:15:37 +00002416 InstResult =
2417 ConstantExpr::getGetElementPtr(P, GEPOps,
2418 cast<GEPOperator>(GEP)->isInBounds());
Chris Lattner04de1cf2005-09-26 05:15:37 +00002419 } else if (LoadInst *LI = dyn_cast<LoadInst>(CurInst)) {
Eli Friedman33cb4452011-08-16 00:20:11 +00002420 if (!LI->isSimple()) return false; // no volatile/atomic accesses.
Chris Lattner04de1cf2005-09-26 05:15:37 +00002421 InstResult = ComputeLoadResult(getVal(Values, LI->getOperand(0)),
Chris Lattner7b550cc2009-11-06 04:27:31 +00002422 MutatedMemory);
Chris Lattnercd271422005-09-27 04:45:34 +00002423 if (InstResult == 0) return false; // Could not evaluate load.
Chris Lattnera22fdb02005-09-26 17:07:09 +00002424 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(CurInst)) {
Chris Lattnercd271422005-09-27 04:45:34 +00002425 if (AI->isArrayAllocation()) return false; // Cannot handle array allocs.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002426 Type *Ty = AI->getType()->getElementType();
Chris Lattner7b550cc2009-11-06 04:27:31 +00002427 AllocaTmps.push_back(new GlobalVariable(Ty, false,
Chris Lattnera22fdb02005-09-26 17:07:09 +00002428 GlobalValue::InternalLinkage,
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002429 UndefValue::get(Ty),
Chris Lattnera22fdb02005-09-26 17:07:09 +00002430 AI->getName()));
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002431 InstResult = AllocaTmps.back();
Chris Lattnercd271422005-09-27 04:45:34 +00002432 } else if (CallInst *CI = dyn_cast<CallInst>(CurInst)) {
Devang Patel412a4462009-03-09 23:04:12 +00002433
2434 // Debug info can safely be ignored here.
2435 if (isa<DbgInfoIntrinsic>(CI)) {
2436 ++CurInst;
2437 continue;
2438 }
2439
Chris Lattner7cd580f2006-07-07 21:37:01 +00002440 // Cannot handle inline asm.
Gabor Greifa9b23132010-04-20 13:13:04 +00002441 if (isa<InlineAsm>(CI->getCalledValue())) return false;
Chris Lattner7cd580f2006-07-07 21:37:01 +00002442
Nick Lewycky1f237b02011-05-29 18:41:56 +00002443 if (MemSetInst *MSI = dyn_cast<MemSetInst>(CI)) {
2444 if (MSI->isVolatile()) return false;
2445 Constant *Ptr = getVal(Values, MSI->getDest());
2446 Constant *Val = getVal(Values, MSI->getValue());
2447 Constant *DestVal = ComputeLoadResult(getVal(Values, Ptr),
2448 MutatedMemory);
Nick Lewyckybcb85082011-05-29 19:33:36 +00002449 if (Val->isNullValue() && DestVal && DestVal->isNullValue()) {
Nick Lewycky1f237b02011-05-29 18:41:56 +00002450 // This memset is a no-op.
2451 ++CurInst;
2452 continue;
2453 }
2454 return false;
2455 }
2456
Chris Lattnercd271422005-09-27 04:45:34 +00002457 // Resolve function pointers.
Gabor Greifa3997812010-07-22 10:37:47 +00002458 Function *Callee = dyn_cast<Function>(getVal(Values,
2459 CI->getCalledValue()));
Chris Lattnercd271422005-09-27 04:45:34 +00002460 if (!Callee) return false; // Cannot resolve.
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002461
Duncan Sandsfa6a1cf2009-08-17 14:33:27 +00002462 SmallVector<Constant*, 8> Formals;
Gabor Greif9e4f2432010-06-24 14:42:01 +00002463 CallSite CS(CI);
2464 for (User::op_iterator i = CS.arg_begin(), e = CS.arg_end();
Gabor Greif5e463212008-05-29 01:59:18 +00002465 i != e; ++i)
2466 Formals.push_back(getVal(Values, *i));
Duncan Sandsfa6a1cf2009-08-17 14:33:27 +00002467
Reid Spencer5cbf9852007-01-30 20:08:39 +00002468 if (Callee->isDeclaration()) {
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002469 // If this is a function we can constant fold, do it.
Chad Rosier00737bd2011-12-01 21:29:16 +00002470 if (Constant *C = ConstantFoldCall(Callee, Formals, TLI)) {
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002471 InstResult = C;
2472 } else {
2473 return false;
2474 }
2475 } else {
2476 if (Callee->getFunctionType()->isVarArg())
2477 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002478
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002479 Constant *RetVal;
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002480 // Execute the call, if successful, use the return value.
2481 if (!EvaluateFunction(Callee, RetVal, Formals, CallStack,
Chad Rosier00737bd2011-12-01 21:29:16 +00002482 MutatedMemory, AllocaTmps, SimpleConstants, TD,
2483 TLI))
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002484 return false;
2485 InstResult = RetVal;
2486 }
Reid Spencer3ed469c2006-11-02 20:25:50 +00002487 } else if (isa<TerminatorInst>(CurInst)) {
Chris Lattnercdf98be2005-09-26 04:57:38 +00002488 BasicBlock *NewBB = 0;
2489 if (BranchInst *BI = dyn_cast<BranchInst>(CurInst)) {
2490 if (BI->isUnconditional()) {
2491 NewBB = BI->getSuccessor(0);
2492 } else {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002493 ConstantInt *Cond =
2494 dyn_cast<ConstantInt>(getVal(Values, BI->getCondition()));
Chris Lattner97d1fad2007-01-12 18:30:11 +00002495 if (!Cond) return false; // Cannot determine.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002496
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002497 NewBB = BI->getSuccessor(!Cond->getZExtValue());
Chris Lattnercdf98be2005-09-26 04:57:38 +00002498 }
2499 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(CurInst)) {
2500 ConstantInt *Val =
2501 dyn_cast<ConstantInt>(getVal(Values, SI->getCondition()));
Chris Lattnercd271422005-09-27 04:45:34 +00002502 if (!Val) return false; // Cannot determine.
Chris Lattnercdf98be2005-09-26 04:57:38 +00002503 NewBB = SI->getSuccessor(SI->findCaseValue(Val));
Chris Lattnerb3d5a652009-10-29 05:51:50 +00002504 } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(CurInst)) {
2505 Value *Val = getVal(Values, IBI->getAddress())->stripPointerCasts();
2506 if (BlockAddress *BA = dyn_cast<BlockAddress>(Val))
2507 NewBB = BA->getBasicBlock();
Chris Lattnercdfc9402009-11-01 01:27:45 +00002508 else
2509 return false; // Cannot determine.
Chris Lattnercdf98be2005-09-26 04:57:38 +00002510 } else if (ReturnInst *RI = dyn_cast<ReturnInst>(CurInst)) {
Chris Lattnercd271422005-09-27 04:45:34 +00002511 if (RI->getNumOperands())
2512 RetVal = getVal(Values, RI->getOperand(0));
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002513
Chris Lattnercd271422005-09-27 04:45:34 +00002514 CallStack.pop_back(); // return from fn.
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002515 return true; // We succeeded at evaluating this ctor!
Chris Lattnercdf98be2005-09-26 04:57:38 +00002516 } else {
Bill Wendlingdccc03b2011-07-31 06:30:59 +00002517 // invoke, unwind, resume, unreachable.
Chris Lattnercd271422005-09-27 04:45:34 +00002518 return false; // Cannot handle this terminator.
Chris Lattnercdf98be2005-09-26 04:57:38 +00002519 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002520
Chris Lattnercdf98be2005-09-26 04:57:38 +00002521 // Okay, we succeeded in evaluating this control flow. See if we have
Chris Lattnercd271422005-09-27 04:45:34 +00002522 // executed the new block before. If so, we have a looping function,
2523 // which we cannot evaluate in reasonable time.
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002524 if (!ExecutedBlocks.insert(NewBB))
Chris Lattnercd271422005-09-27 04:45:34 +00002525 return false; // looped!
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002526
Chris Lattnercdf98be2005-09-26 04:57:38 +00002527 // Okay, we have never been in this block before. Check to see if there
2528 // are any PHI nodes. If so, evaluate them with information about where
2529 // we came from.
2530 BasicBlock *OldBB = CurInst->getParent();
2531 CurInst = NewBB->begin();
2532 PHINode *PN;
2533 for (; (PN = dyn_cast<PHINode>(CurInst)); ++CurInst)
2534 Values[PN] = getVal(Values, PN->getIncomingValueForBlock(OldBB));
2535
2536 // Do NOT increment CurInst. We know that the terminator had no value.
2537 continue;
Chris Lattner79c11012005-09-26 04:44:35 +00002538 } else {
Chris Lattner79c11012005-09-26 04:44:35 +00002539 // Did not know how to evaluate this!
Chris Lattnercd271422005-09-27 04:45:34 +00002540 return false;
Chris Lattner79c11012005-09-26 04:44:35 +00002541 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002542
Chris Lattner1945d582010-12-07 04:33:29 +00002543 if (!CurInst->use_empty()) {
2544 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(InstResult))
2545 InstResult = ConstantFoldConstantExpression(CE, TD);
2546
Chris Lattner79c11012005-09-26 04:44:35 +00002547 Values[CurInst] = InstResult;
Chris Lattner1945d582010-12-07 04:33:29 +00002548 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002549
Chris Lattner79c11012005-09-26 04:44:35 +00002550 // Advance program counter.
2551 ++CurInst;
2552 }
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002553}
2554
2555/// EvaluateStaticConstructor - Evaluate static constructors in the function, if
2556/// we can. Return true if we can, false otherwise.
Chad Rosier00737bd2011-12-01 21:29:16 +00002557static bool EvaluateStaticConstructor(Function *F, const TargetData *TD,
2558 const TargetLibraryInfo *TLI) {
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002559 /// MutatedMemory - For each store we execute, we update this map. Loads
2560 /// check this to get the most up-to-date value. If evaluation is successful,
2561 /// this state is committed to the process.
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002562 DenseMap<Constant*, Constant*> MutatedMemory;
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002563
2564 /// AllocaTmps - To 'execute' an alloca, we create a temporary global variable
2565 /// to represent its body. This vector is needed so we can delete the
2566 /// temporary globals when we are done.
2567 std::vector<GlobalVariable*> AllocaTmps;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002568
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002569 /// CallStack - This is used to detect recursion. In pathological situations
2570 /// we could hit exponential behavior, but at least there is nothing
2571 /// unbounded.
2572 std::vector<Function*> CallStack;
2573
Chris Lattner1945d582010-12-07 04:33:29 +00002574 /// SimpleConstants - These are constants we have checked and know to be
2575 /// simple enough to live in a static initializer of a global.
2576 SmallPtrSet<Constant*, 8> SimpleConstants;
2577
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002578 // Call the function.
Chris Lattnercd271422005-09-27 04:45:34 +00002579 Constant *RetValDummy;
Duncan Sandsfa6a1cf2009-08-17 14:33:27 +00002580 bool EvalSuccess = EvaluateFunction(F, RetValDummy,
2581 SmallVector<Constant*, 0>(), CallStack,
Chris Lattner1945d582010-12-07 04:33:29 +00002582 MutatedMemory, AllocaTmps,
Chad Rosier00737bd2011-12-01 21:29:16 +00002583 SimpleConstants, TD, TLI);
Chris Lattner1945d582010-12-07 04:33:29 +00002584
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002585 if (EvalSuccess) {
Chris Lattnera22fdb02005-09-26 17:07:09 +00002586 // We succeeded at evaluation: commit the result.
David Greene3215b0e2010-01-05 01:28:05 +00002587 DEBUG(dbgs() << "FULLY EVALUATED GLOBAL CTOR FUNCTION '"
Daniel Dunbarce63ffb2009-07-25 00:23:56 +00002588 << F->getName() << "' to " << MutatedMemory.size()
2589 << " stores.\n");
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002590 for (DenseMap<Constant*, Constant*>::iterator I = MutatedMemory.begin(),
Chris Lattnera22fdb02005-09-26 17:07:09 +00002591 E = MutatedMemory.end(); I != E; ++I)
Chris Lattner7b550cc2009-11-06 04:27:31 +00002592 CommitValueTo(I->second, I->first);
Chris Lattnera22fdb02005-09-26 17:07:09 +00002593 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002594
Chris Lattnera22fdb02005-09-26 17:07:09 +00002595 // At this point, we are done interpreting. If we created any 'alloca'
2596 // temporaries, release them now.
2597 while (!AllocaTmps.empty()) {
2598 GlobalVariable *Tmp = AllocaTmps.back();
2599 AllocaTmps.pop_back();
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002600
Chris Lattnera22fdb02005-09-26 17:07:09 +00002601 // If there are still users of the alloca, the program is doing something
2602 // silly, e.g. storing the address of the alloca somewhere and using it
2603 // later. Since this is undefined, we'll just make it be null.
2604 if (!Tmp->use_empty())
Owen Andersona7235ea2009-07-31 20:28:14 +00002605 Tmp->replaceAllUsesWith(Constant::getNullValue(Tmp->getType()));
Chris Lattnera22fdb02005-09-26 17:07:09 +00002606 delete Tmp;
2607 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002608
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002609 return EvalSuccess;
Chris Lattner79c11012005-09-26 04:44:35 +00002610}
2611
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002612/// OptimizeGlobalCtorsList - Simplify and evaluation global ctors if possible.
2613/// Return true if anything changed.
2614bool GlobalOpt::OptimizeGlobalCtorsList(GlobalVariable *&GCL) {
2615 std::vector<Function*> Ctors = ParseGlobalCtors(GCL);
2616 bool MadeChange = false;
2617 if (Ctors.empty()) return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002618
Chris Lattner1945d582010-12-07 04:33:29 +00002619 const TargetData *TD = getAnalysisIfAvailable<TargetData>();
Chad Rosier00737bd2011-12-01 21:29:16 +00002620 const TargetLibraryInfo *TLI = &getAnalysis<TargetLibraryInfo>();
2621
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002622 // Loop over global ctors, optimizing them when we can.
2623 for (unsigned i = 0; i != Ctors.size(); ++i) {
2624 Function *F = Ctors[i];
2625 // Found a null terminator in the middle of the list, prune off the rest of
2626 // the list.
Chris Lattner7d8e58f2005-09-26 02:19:27 +00002627 if (F == 0) {
2628 if (i != Ctors.size()-1) {
2629 Ctors.resize(i+1);
2630 MadeChange = true;
2631 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002632 break;
2633 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002634
Chris Lattner79c11012005-09-26 04:44:35 +00002635 // We cannot simplify external ctor functions.
2636 if (F->empty()) continue;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002637
Chris Lattner79c11012005-09-26 04:44:35 +00002638 // If we can evaluate the ctor at compile time, do.
Chad Rosier00737bd2011-12-01 21:29:16 +00002639 if (EvaluateStaticConstructor(F, TD, TLI)) {
Chris Lattner79c11012005-09-26 04:44:35 +00002640 Ctors.erase(Ctors.begin()+i);
2641 MadeChange = true;
2642 --i;
2643 ++NumCtorsEvaluated;
2644 continue;
2645 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002646 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002647
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002648 if (!MadeChange) return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002649
Chris Lattner7b550cc2009-11-06 04:27:31 +00002650 GCL = InstallGlobalCtors(GCL, Ctors);
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002651 return true;
2652}
2653
Duncan Sandsfc5940d2009-03-06 10:21:56 +00002654bool GlobalOpt::OptimizeGlobalAliases(Module &M) {
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002655 bool Changed = false;
2656
Duncan Sands177d84e2009-01-07 20:01:06 +00002657 for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end();
Duncan Sands4782b302009-02-15 09:56:08 +00002658 I != E;) {
2659 Module::alias_iterator J = I++;
Duncan Sandsfc5940d2009-03-06 10:21:56 +00002660 // Aliases without names cannot be referenced outside this module.
2661 if (!J->hasName() && !J->isDeclaration())
2662 J->setLinkage(GlobalValue::InternalLinkage);
Duncan Sands4782b302009-02-15 09:56:08 +00002663 // If the aliasee may change at link time, nothing can be done - bail out.
2664 if (J->mayBeOverridden())
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002665 continue;
2666
Duncan Sands4782b302009-02-15 09:56:08 +00002667 Constant *Aliasee = J->getAliasee();
2668 GlobalValue *Target = cast<GlobalValue>(Aliasee->stripPointerCasts());
Duncan Sands95c5d0f2009-02-18 17:55:38 +00002669 Target->removeDeadConstantUsers();
Duncan Sands4782b302009-02-15 09:56:08 +00002670 bool hasOneUse = Target->hasOneUse() && Aliasee->hasOneUse();
2671
2672 // Make all users of the alias use the aliasee instead.
2673 if (!J->use_empty()) {
2674 J->replaceAllUsesWith(Aliasee);
2675 ++NumAliasesResolved;
2676 Changed = true;
2677 }
2678
Duncan Sands7a154cf2009-12-08 10:10:20 +00002679 // If the alias is externally visible, we may still be able to simplify it.
2680 if (!J->hasLocalLinkage()) {
2681 // If the aliasee has internal linkage, give it the name and linkage
2682 // of the alias, and delete the alias. This turns:
2683 // define internal ... @f(...)
2684 // @a = alias ... @f
2685 // into:
2686 // define ... @a(...)
2687 if (!Target->hasLocalLinkage())
2688 continue;
Duncan Sands4782b302009-02-15 09:56:08 +00002689
Duncan Sands7a154cf2009-12-08 10:10:20 +00002690 // Do not perform the transform if multiple aliases potentially target the
Gabor Greif27236912010-04-07 18:59:26 +00002691 // aliasee. This check also ensures that it is safe to replace the section
Duncan Sands7a154cf2009-12-08 10:10:20 +00002692 // and other attributes of the aliasee with those of the alias.
2693 if (!hasOneUse)
2694 continue;
Duncan Sands4782b302009-02-15 09:56:08 +00002695
Duncan Sands7a154cf2009-12-08 10:10:20 +00002696 // Give the aliasee the name, linkage and other attributes of the alias.
2697 Target->takeName(J);
2698 Target->setLinkage(J->getLinkage());
2699 Target->GlobalValue::copyAttributesFrom(J);
2700 }
Duncan Sands4782b302009-02-15 09:56:08 +00002701
2702 // Delete the alias.
2703 M.getAliasList().erase(J);
2704 ++NumAliasesRemoved;
2705 Changed = true;
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002706 }
2707
2708 return Changed;
2709}
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002710
Anders Carlssona201c4c2011-03-20 17:59:11 +00002711static Function *FindCXAAtExit(Module &M) {
2712 Function *Fn = M.getFunction("__cxa_atexit");
2713
2714 if (!Fn)
2715 return 0;
2716
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002717 FunctionType *FTy = Fn->getFunctionType();
Anders Carlssona201c4c2011-03-20 17:59:11 +00002718
Anders Carlsson1f7c7ba2011-03-20 19:51:13 +00002719 // Checking that the function has the right return type, the right number of
2720 // parameters and that they all have pointer types should be enough.
2721 if (!FTy->getReturnType()->isIntegerTy() ||
2722 FTy->getNumParams() != 3 ||
Anders Carlssona201c4c2011-03-20 17:59:11 +00002723 !FTy->getParamType(0)->isPointerTy() ||
2724 !FTy->getParamType(1)->isPointerTy() ||
2725 !FTy->getParamType(2)->isPointerTy())
2726 return 0;
2727
2728 return Fn;
2729}
2730
2731/// cxxDtorIsEmpty - Returns whether the given function is an empty C++
2732/// destructor and can therefore be eliminated.
2733/// Note that we assume that other optimization passes have already simplified
2734/// the code so we only look for a function with a single basic block, where
2735/// the only allowed instructions are 'ret' or 'call' to empty C++ dtor.
Anders Carlsson372ec6a2011-03-20 20:16:43 +00002736static bool cxxDtorIsEmpty(const Function &Fn,
2737 SmallPtrSet<const Function *, 8> &CalledFunctions) {
Anders Carlsson1f7c7ba2011-03-20 19:51:13 +00002738 // FIXME: We could eliminate C++ destructors if they're readonly/readnone and
Nick Lewycky35ee1c92011-03-21 02:26:01 +00002739 // nounwind, but that doesn't seem worth doing.
Anders Carlsson1f7c7ba2011-03-20 19:51:13 +00002740 if (Fn.isDeclaration())
2741 return false;
Anders Carlssona201c4c2011-03-20 17:59:11 +00002742
2743 if (++Fn.begin() != Fn.end())
2744 return false;
2745
2746 const BasicBlock &EntryBlock = Fn.getEntryBlock();
2747 for (BasicBlock::const_iterator I = EntryBlock.begin(), E = EntryBlock.end();
2748 I != E; ++I) {
2749 if (const CallInst *CI = dyn_cast<CallInst>(I)) {
Anders Carlssonb12caf32011-03-21 14:54:40 +00002750 // Ignore debug intrinsics.
2751 if (isa<DbgInfoIntrinsic>(CI))
2752 continue;
2753
Anders Carlssona201c4c2011-03-20 17:59:11 +00002754 const Function *CalledFn = CI->getCalledFunction();
2755
2756 if (!CalledFn)
2757 return false;
2758
Anders Carlsson807bc2a2011-03-22 03:21:01 +00002759 SmallPtrSet<const Function *, 8> NewCalledFunctions(CalledFunctions);
2760
Anders Carlsson1f7c7ba2011-03-20 19:51:13 +00002761 // Don't treat recursive functions as empty.
Anders Carlsson807bc2a2011-03-22 03:21:01 +00002762 if (!NewCalledFunctions.insert(CalledFn))
Anders Carlsson1f7c7ba2011-03-20 19:51:13 +00002763 return false;
2764
Anders Carlsson807bc2a2011-03-22 03:21:01 +00002765 if (!cxxDtorIsEmpty(*CalledFn, NewCalledFunctions))
Anders Carlssona201c4c2011-03-20 17:59:11 +00002766 return false;
2767 } else if (isa<ReturnInst>(*I))
2768 return true;
2769 else
2770 return false;
2771 }
2772
2773 return false;
2774}
2775
2776bool GlobalOpt::OptimizeEmptyGlobalCXXDtors(Function *CXAAtExitFn) {
2777 /// Itanium C++ ABI p3.3.5:
2778 ///
2779 /// After constructing a global (or local static) object, that will require
2780 /// destruction on exit, a termination function is registered as follows:
2781 ///
2782 /// extern "C" int __cxa_atexit ( void (*f)(void *), void *p, void *d );
2783 ///
2784 /// This registration, e.g. __cxa_atexit(f,p,d), is intended to cause the
2785 /// call f(p) when DSO d is unloaded, before all such termination calls
2786 /// registered before this one. It returns zero if registration is
Nick Lewycky35ee1c92011-03-21 02:26:01 +00002787 /// successful, nonzero on failure.
Anders Carlssona201c4c2011-03-20 17:59:11 +00002788
2789 // This pass will look for calls to __cxa_atexit where the function is trivial
2790 // and remove them.
2791 bool Changed = false;
2792
2793 for (Function::use_iterator I = CXAAtExitFn->use_begin(),
2794 E = CXAAtExitFn->use_end(); I != E;) {
Anders Carlsson4f735ca2011-03-20 20:21:33 +00002795 // We're only interested in calls. Theoretically, we could handle invoke
2796 // instructions as well, but neither llvm-gcc nor clang generate invokes
2797 // to __cxa_atexit.
Anders Carlssonb12caf32011-03-21 14:54:40 +00002798 CallInst *CI = dyn_cast<CallInst>(*I++);
2799 if (!CI)
Anders Carlsson4f735ca2011-03-20 20:21:33 +00002800 continue;
2801
Anders Carlssona201c4c2011-03-20 17:59:11 +00002802 Function *DtorFn =
Anders Carlssonb12caf32011-03-21 14:54:40 +00002803 dyn_cast<Function>(CI->getArgOperand(0)->stripPointerCasts());
Anders Carlssona201c4c2011-03-20 17:59:11 +00002804 if (!DtorFn)
2805 continue;
2806
Anders Carlsson372ec6a2011-03-20 20:16:43 +00002807 SmallPtrSet<const Function *, 8> CalledFunctions;
2808 if (!cxxDtorIsEmpty(*DtorFn, CalledFunctions))
Anders Carlssona201c4c2011-03-20 17:59:11 +00002809 continue;
2810
2811 // Just remove the call.
Anders Carlssonb12caf32011-03-21 14:54:40 +00002812 CI->replaceAllUsesWith(Constant::getNullValue(CI->getType()));
2813 CI->eraseFromParent();
Anders Carlsson1f7c7ba2011-03-20 19:51:13 +00002814
Anders Carlssona201c4c2011-03-20 17:59:11 +00002815 ++NumCXXDtorsRemoved;
2816
2817 Changed |= true;
2818 }
2819
2820 return Changed;
2821}
2822
Chris Lattner7a90b682004-10-07 04:16:33 +00002823bool GlobalOpt::runOnModule(Module &M) {
Chris Lattner079236d2004-02-25 21:34:36 +00002824 bool Changed = false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002825
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002826 // Try to find the llvm.globalctors list.
2827 GlobalVariable *GlobalCtors = FindGlobalCtors(M);
Chris Lattner7a90b682004-10-07 04:16:33 +00002828
Anders Carlssona201c4c2011-03-20 17:59:11 +00002829 Function *CXAAtExitFn = FindCXAAtExit(M);
2830
Chris Lattner7a90b682004-10-07 04:16:33 +00002831 bool LocalChange = true;
2832 while (LocalChange) {
2833 LocalChange = false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002834
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002835 // Delete functions that are trivially dead, ccc -> fastcc
2836 LocalChange |= OptimizeFunctions(M);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002837
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002838 // Optimize global_ctors list.
2839 if (GlobalCtors)
2840 LocalChange |= OptimizeGlobalCtorsList(GlobalCtors);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002841
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002842 // Optimize non-address-taken globals.
2843 LocalChange |= OptimizeGlobalVars(M);
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002844
2845 // Resolve aliases, when possible.
Duncan Sandsfc5940d2009-03-06 10:21:56 +00002846 LocalChange |= OptimizeGlobalAliases(M);
Anders Carlssona201c4c2011-03-20 17:59:11 +00002847
2848 // Try to remove trivial global destructors.
2849 if (CXAAtExitFn)
2850 LocalChange |= OptimizeEmptyGlobalCXXDtors(CXAAtExitFn);
2851
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002852 Changed |= LocalChange;
Chris Lattner7a90b682004-10-07 04:16:33 +00002853 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002854
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002855 // TODO: Move all global ctors functions to the end of the module for code
2856 // layout.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002857
Chris Lattner079236d2004-02-25 21:34:36 +00002858 return Changed;
2859}