blob: 71d13edc96f753dd1c2b9ec154bd115533ef88b0 [file] [log] [blame]
Chris Lattner7a90b682004-10-07 04:16:33 +00001//===- GlobalOpt.cpp - Optimize Global Variables --------------------------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
Chris Lattner079236d2004-02-25 21:34:36 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
Chris Lattner079236d2004-02-25 21:34:36 +00008//===----------------------------------------------------------------------===//
9//
Chris Lattner7a90b682004-10-07 04:16:33 +000010// This pass transforms simple global variables that never have their address
11// taken. If obviously true, it marks read/write globals as constant, deletes
12// variables only stored to, etc.
Chris Lattner079236d2004-02-25 21:34:36 +000013//
14//===----------------------------------------------------------------------===//
15
Chris Lattner7a90b682004-10-07 04:16:33 +000016#define DEBUG_TYPE "globalopt"
Chris Lattner079236d2004-02-25 21:34:36 +000017#include "llvm/Transforms/IPO.h"
Chris Lattnerfb217ad2005-05-08 22:18:06 +000018#include "llvm/CallingConv.h"
Chris Lattner079236d2004-02-25 21:34:36 +000019#include "llvm/Constants.h"
Chris Lattner7a90b682004-10-07 04:16:33 +000020#include "llvm/DerivedTypes.h"
Chris Lattner7d90a272004-02-27 18:09:25 +000021#include "llvm/Instructions.h"
Chris Lattner35c81b02005-02-27 18:58:52 +000022#include "llvm/IntrinsicInst.h"
Chris Lattner079236d2004-02-25 21:34:36 +000023#include "llvm/Module.h"
24#include "llvm/Pass.h"
Chris Lattner79066fa2007-01-30 23:46:24 +000025#include "llvm/Analysis/ConstantFolding.h"
Victor Hernandezf006b182009-10-27 20:05:49 +000026#include "llvm/Analysis/MemoryBuiltins.h"
Chris Lattner30ba5692004-10-11 05:54:41 +000027#include "llvm/Target/TargetData.h"
Duncan Sands548448a2008-02-18 17:32:13 +000028#include "llvm/Support/CallSite.h"
Chris Lattner79066fa2007-01-30 23:46:24 +000029#include "llvm/Support/Debug.h"
Torok Edwinc25e7582009-07-11 20:10:48 +000030#include "llvm/Support/ErrorHandling.h"
Chris Lattner941db492008-01-14 02:09:12 +000031#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner998182b2008-04-26 07:40:11 +000032#include "llvm/Support/MathExtras.h"
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000033#include "llvm/Support/raw_ostream.h"
Chris Lattner5a6bb6a2008-12-16 07:34:30 +000034#include "llvm/ADT/DenseMap.h"
Chris Lattner81686182007-09-13 16:30:19 +000035#include "llvm/ADT/SmallPtrSet.h"
Chris Lattner55eb1c42007-01-31 04:40:53 +000036#include "llvm/ADT/SmallVector.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000037#include "llvm/ADT/Statistic.h"
Chris Lattnerbce4afe2008-12-17 05:28:49 +000038#include "llvm/ADT/STLExtras.h"
Chris Lattnere47ba742004-10-06 20:57:02 +000039#include <algorithm>
Chris Lattner079236d2004-02-25 21:34:36 +000040using namespace llvm;
41
Chris Lattner86453c52006-12-19 22:09:18 +000042STATISTIC(NumMarked , "Number of globals marked constant");
Rafael Espindolac4440e32011-01-19 16:32:21 +000043STATISTIC(NumUnnamed , "Number of globals marked unnamed_addr");
Chris Lattner86453c52006-12-19 22:09:18 +000044STATISTIC(NumSRA , "Number of aggregate globals broken into scalars");
45STATISTIC(NumHeapSRA , "Number of heap objects SRA'd");
46STATISTIC(NumSubstitute,"Number of globals with initializers stored into them");
47STATISTIC(NumDeleted , "Number of globals deleted");
48STATISTIC(NumFnDeleted , "Number of functions deleted");
49STATISTIC(NumGlobUses , "Number of global uses devirtualized");
50STATISTIC(NumLocalized , "Number of globals localized");
51STATISTIC(NumShrunkToBool , "Number of global vars shrunk to booleans");
52STATISTIC(NumFastCallFns , "Number of functions converted to fastcc");
53STATISTIC(NumCtorsEvaluated, "Number of static ctors evaluated");
Duncan Sands3d5378f2008-02-16 20:56:04 +000054STATISTIC(NumNestRemoved , "Number of nest attributes removed");
Duncan Sands4782b302009-02-15 09:56:08 +000055STATISTIC(NumAliasesResolved, "Number of global aliases resolved");
56STATISTIC(NumAliasesRemoved, "Number of global aliases eliminated");
Anders Carlssona201c4c2011-03-20 17:59:11 +000057STATISTIC(NumCXXDtorsRemoved, "Number of global C++ destructors removed");
Chris Lattner079236d2004-02-25 21:34:36 +000058
Chris Lattner86453c52006-12-19 22:09:18 +000059namespace {
Rafael Espindolac4440e32011-01-19 16:32:21 +000060 struct GlobalStatus;
Nick Lewycky6726b6d2009-10-25 06:33:48 +000061 struct GlobalOpt : public ModulePass {
Chris Lattner30ba5692004-10-11 05:54:41 +000062 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner30ba5692004-10-11 05:54:41 +000063 }
Nick Lewyckyecd94c82007-05-06 13:37:16 +000064 static char ID; // Pass identification, replacement for typeid
Owen Anderson081c34b2010-10-19 17:21:58 +000065 GlobalOpt() : ModulePass(ID) {
66 initializeGlobalOptPass(*PassRegistry::getPassRegistry());
67 }
Misha Brukmanfd939082005-04-21 23:48:37 +000068
Chris Lattnerb12914b2004-09-20 04:48:05 +000069 bool runOnModule(Module &M);
Chris Lattner30ba5692004-10-11 05:54:41 +000070
71 private:
Chris Lattnerb1ab4582005-09-26 01:43:45 +000072 GlobalVariable *FindGlobalCtors(Module &M);
73 bool OptimizeFunctions(Module &M);
74 bool OptimizeGlobalVars(Module &M);
Duncan Sandsfc5940d2009-03-06 10:21:56 +000075 bool OptimizeGlobalAliases(Module &M);
Chris Lattnerb1ab4582005-09-26 01:43:45 +000076 bool OptimizeGlobalCtorsList(GlobalVariable *&GCL);
Rafael Espindolac4440e32011-01-19 16:32:21 +000077 bool ProcessGlobal(GlobalVariable *GV,Module::global_iterator &GVI);
78 bool ProcessInternalGlobal(GlobalVariable *GV,Module::global_iterator &GVI,
79 const SmallPtrSet<const PHINode*, 16> &PHIUsers,
80 const GlobalStatus &GS);
Anders Carlssona201c4c2011-03-20 17:59:11 +000081 bool OptimizeEmptyGlobalCXXDtors(Function *CXAAtExitFn);
Chris Lattner079236d2004-02-25 21:34:36 +000082 };
Chris Lattner079236d2004-02-25 21:34:36 +000083}
84
Dan Gohman844731a2008-05-13 00:00:25 +000085char GlobalOpt::ID = 0;
Owen Andersond13db2c2010-07-21 22:09:45 +000086INITIALIZE_PASS(GlobalOpt, "globalopt",
Owen Andersonce665bd2010-10-07 22:25:06 +000087 "Global Variable Optimizer", false, false)
Dan Gohman844731a2008-05-13 00:00:25 +000088
Chris Lattner7a90b682004-10-07 04:16:33 +000089ModulePass *llvm::createGlobalOptimizerPass() { return new GlobalOpt(); }
Chris Lattner079236d2004-02-25 21:34:36 +000090
Dan Gohman844731a2008-05-13 00:00:25 +000091namespace {
92
Chris Lattner7a90b682004-10-07 04:16:33 +000093/// GlobalStatus - As we analyze each global, keep track of some information
94/// about it. If we find out that the address of the global is taken, none of
Chris Lattnercf4d2a52004-10-07 21:30:30 +000095/// this info will be accurate.
Nick Lewycky6726b6d2009-10-25 06:33:48 +000096struct GlobalStatus {
Rafael Espindolac4440e32011-01-19 16:32:21 +000097 /// isCompared - True if the global's address is used in a comparison.
98 bool isCompared;
99
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000100 /// isLoaded - True if the global is ever loaded. If the global isn't ever
101 /// loaded it can be deleted.
Chris Lattner7a90b682004-10-07 04:16:33 +0000102 bool isLoaded;
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000103
104 /// StoredType - Keep track of what stores to the global look like.
105 ///
Chris Lattner7a90b682004-10-07 04:16:33 +0000106 enum StoredType {
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000107 /// NotStored - There is no store to this global. It can thus be marked
108 /// constant.
109 NotStored,
110
111 /// isInitializerStored - This global is stored to, but the only thing
112 /// stored is the constant it was initialized with. This is only tracked
113 /// for scalar globals.
114 isInitializerStored,
115
116 /// isStoredOnce - This global is stored to, but only its initializer and
117 /// one other value is ever stored to it. If this global isStoredOnce, we
118 /// track the value stored to it in StoredOnceValue below. This is only
119 /// tracked for scalar globals.
120 isStoredOnce,
121
122 /// isStored - This global is stored to by multiple values or something else
123 /// that we cannot track.
124 isStored
Chris Lattner7a90b682004-10-07 04:16:33 +0000125 } StoredType;
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000126
127 /// StoredOnceValue - If only one value (besides the initializer constant) is
128 /// ever stored to this global, keep track of what value it is.
129 Value *StoredOnceValue;
130
Chris Lattner25de4e52006-11-01 18:03:33 +0000131 /// AccessingFunction/HasMultipleAccessingFunctions - These start out
132 /// null/false. When the first accessing function is noticed, it is recorded.
133 /// When a second different accessing function is noticed,
134 /// HasMultipleAccessingFunctions is set to true.
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000135 const Function *AccessingFunction;
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +0000136 bool HasMultipleAccessingFunctions;
137
Chris Lattner25de4e52006-11-01 18:03:33 +0000138 /// HasNonInstructionUser - Set to true if this global has a user that is not
139 /// an instruction (e.g. a constant expr or GV initializer).
Chris Lattner553ca522005-06-15 21:11:48 +0000140 bool HasNonInstructionUser;
141
Chris Lattner25de4e52006-11-01 18:03:33 +0000142 /// HasPHIUser - Set to true if this global has a user that is a PHI node.
143 bool HasPHIUser;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000144
Rafael Espindolac4440e32011-01-19 16:32:21 +0000145 GlobalStatus() : isCompared(false), isLoaded(false), StoredType(NotStored),
146 StoredOnceValue(0), AccessingFunction(0),
147 HasMultipleAccessingFunctions(false), HasNonInstructionUser(false),
148 HasPHIUser(false) {}
Chris Lattner7a90b682004-10-07 04:16:33 +0000149};
Chris Lattnere47ba742004-10-06 20:57:02 +0000150
Dan Gohman844731a2008-05-13 00:00:25 +0000151}
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000152
Jay Foade3acf152009-06-09 21:37:11 +0000153// SafeToDestroyConstant - It is safe to destroy a constant iff it is only used
154// by constants itself. Note that constants cannot be cyclic, so this test is
155// pretty easy to implement recursively.
156//
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000157static bool SafeToDestroyConstant(const Constant *C) {
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000158 if (isa<GlobalValue>(C)) return false;
159
Gabor Greif27236912010-04-07 18:59:26 +0000160 for (Value::const_use_iterator UI = C->use_begin(), E = C->use_end(); UI != E;
161 ++UI)
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000162 if (const Constant *CU = dyn_cast<Constant>(*UI)) {
Jay Foade3acf152009-06-09 21:37:11 +0000163 if (!SafeToDestroyConstant(CU)) return false;
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000164 } else
165 return false;
166 return true;
167}
168
169
Chris Lattner7a90b682004-10-07 04:16:33 +0000170/// AnalyzeGlobal - Look at all uses of the global and fill in the GlobalStatus
171/// structure. If the global has its address taken, return true to indicate we
172/// can't do anything with it.
Chris Lattner079236d2004-02-25 21:34:36 +0000173///
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000174static bool AnalyzeGlobal(const Value *V, GlobalStatus &GS,
175 SmallPtrSet<const PHINode*, 16> &PHIUsers) {
Gabor Greif27236912010-04-07 18:59:26 +0000176 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;
Gabor Greife6642672010-07-09 16:51:20 +0000177 ++UI) {
178 const User *U = *UI;
179 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
Chris Lattner553ca522005-06-15 21:11:48 +0000180 GS.HasNonInstructionUser = true;
Chris Lattnerd91ed102011-01-01 22:31:46 +0000181
182 // If the result of the constantexpr isn't pointer type, then we won't
183 // know to expect it in various places. Just reject early.
184 if (!isa<PointerType>(CE->getType())) return true;
185
Chris Lattner7a90b682004-10-07 04:16:33 +0000186 if (AnalyzeGlobal(CE, GS, PHIUsers)) return true;
Gabor Greife6642672010-07-09 16:51:20 +0000187 } else if (const Instruction *I = dyn_cast<Instruction>(U)) {
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +0000188 if (!GS.HasMultipleAccessingFunctions) {
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000189 const Function *F = I->getParent()->getParent();
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +0000190 if (GS.AccessingFunction == 0)
191 GS.AccessingFunction = F;
192 else if (GS.AccessingFunction != F)
193 GS.HasMultipleAccessingFunctions = true;
194 }
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000195 if (const LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattner7a90b682004-10-07 04:16:33 +0000196 GS.isLoaded = true;
Chris Lattnerc69d3c92008-01-29 19:01:37 +0000197 if (LI->isVolatile()) return true; // Don't hack on volatile loads.
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000198 } else if (const StoreInst *SI = dyn_cast<StoreInst>(I)) {
Chris Lattner36025492004-10-07 06:01:25 +0000199 // Don't allow a store OF the address, only stores TO the address.
200 if (SI->getOperand(0) == V) return true;
201
Chris Lattnerc69d3c92008-01-29 19:01:37 +0000202 if (SI->isVolatile()) return true; // Don't hack on volatile stores.
203
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000204 // If this is a direct store to the global (i.e., the global is a scalar
205 // value, not an aggregate), keep more specific information about
206 // stores.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000207 if (GS.StoredType != GlobalStatus::isStored) {
Gabor Greif27236912010-04-07 18:59:26 +0000208 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(
209 SI->getOperand(1))) {
Chris Lattnerbd38edf2004-11-14 20:50:30 +0000210 Value *StoredVal = SI->getOperand(0);
211 if (StoredVal == GV->getInitializer()) {
212 if (GS.StoredType < GlobalStatus::isInitializerStored)
213 GS.StoredType = GlobalStatus::isInitializerStored;
214 } else if (isa<LoadInst>(StoredVal) &&
215 cast<LoadInst>(StoredVal)->getOperand(0) == GV) {
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000216 if (GS.StoredType < GlobalStatus::isInitializerStored)
217 GS.StoredType = GlobalStatus::isInitializerStored;
218 } else if (GS.StoredType < GlobalStatus::isStoredOnce) {
219 GS.StoredType = GlobalStatus::isStoredOnce;
Chris Lattnerbd38edf2004-11-14 20:50:30 +0000220 GS.StoredOnceValue = StoredVal;
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000221 } else if (GS.StoredType == GlobalStatus::isStoredOnce &&
Chris Lattnerbd38edf2004-11-14 20:50:30 +0000222 GS.StoredOnceValue == StoredVal) {
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000223 // noop.
224 } else {
225 GS.StoredType = GlobalStatus::isStored;
226 }
227 } else {
Chris Lattner7a90b682004-10-07 04:16:33 +0000228 GS.StoredType = GlobalStatus::isStored;
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000229 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000230 }
Chris Lattner35c81b02005-02-27 18:58:52 +0000231 } else if (isa<GetElementPtrInst>(I)) {
Chris Lattner7a90b682004-10-07 04:16:33 +0000232 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Chris Lattner35c81b02005-02-27 18:58:52 +0000233 } else if (isa<SelectInst>(I)) {
Chris Lattner7a90b682004-10-07 04:16:33 +0000234 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000235 } else if (const PHINode *PN = dyn_cast<PHINode>(I)) {
Chris Lattner7a90b682004-10-07 04:16:33 +0000236 // PHI nodes we can check just like select or GEP instructions, but we
237 // have to be careful about infinite recursion.
Chris Lattner5a6bb6a2008-12-16 07:34:30 +0000238 if (PHIUsers.insert(PN)) // Not already visited.
Chris Lattner7a90b682004-10-07 04:16:33 +0000239 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Chris Lattner25de4e52006-11-01 18:03:33 +0000240 GS.HasPHIUser = true;
Reid Spencere4d87aa2006-12-23 06:05:41 +0000241 } else if (isa<CmpInst>(I)) {
Rafael Espindolac4440e32011-01-19 16:32:21 +0000242 GS.isCompared = true;
Chris Lattner8e108442009-03-08 03:37:35 +0000243 } else if (isa<MemTransferInst>(I)) {
Gabor Greif9e4f2432010-06-24 14:42:01 +0000244 const MemTransferInst *MTI = cast<MemTransferInst>(I);
245 if (MTI->getArgOperand(0) == V)
Eric Christopher551754c2010-04-16 23:37:20 +0000246 GS.StoredType = GlobalStatus::isStored;
Gabor Greif9e4f2432010-06-24 14:42:01 +0000247 if (MTI->getArgOperand(1) == V)
Chris Lattner35c81b02005-02-27 18:58:52 +0000248 GS.isLoaded = true;
Chris Lattner35c81b02005-02-27 18:58:52 +0000249 } else if (isa<MemSetInst>(I)) {
Gabor Greif9e4f2432010-06-24 14:42:01 +0000250 assert(cast<MemSetInst>(I)->getArgOperand(0) == V &&
251 "Memset only takes one pointer!");
Chris Lattner35c81b02005-02-27 18:58:52 +0000252 GS.StoredType = GlobalStatus::isStored;
Chris Lattner7a90b682004-10-07 04:16:33 +0000253 } else {
254 return true; // Any other non-load instruction might take address!
Chris Lattner9ce30002004-07-20 03:58:07 +0000255 }
Gabor Greife6642672010-07-09 16:51:20 +0000256 } else if (const Constant *C = dyn_cast<Constant>(U)) {
Chris Lattner553ca522005-06-15 21:11:48 +0000257 GS.HasNonInstructionUser = true;
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000258 // We might have a dead and dangling constant hanging off of here.
Jay Foade3acf152009-06-09 21:37:11 +0000259 if (!SafeToDestroyConstant(C))
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000260 return true;
Chris Lattner079236d2004-02-25 21:34:36 +0000261 } else {
Chris Lattner553ca522005-06-15 21:11:48 +0000262 GS.HasNonInstructionUser = true;
263 // Otherwise must be some other user.
Chris Lattner079236d2004-02-25 21:34:36 +0000264 return true;
265 }
Gabor Greife6642672010-07-09 16:51:20 +0000266 }
Chris Lattner079236d2004-02-25 21:34:36 +0000267
268 return false;
269}
270
Chris Lattner7b550cc2009-11-06 04:27:31 +0000271static Constant *getAggregateConstantElement(Constant *Agg, Constant *Idx) {
Chris Lattner670c8892004-10-08 17:32:09 +0000272 ConstantInt *CI = dyn_cast<ConstantInt>(Idx);
273 if (!CI) return 0;
Reid Spencerb83eb642006-10-20 07:07:24 +0000274 unsigned IdxV = CI->getZExtValue();
Chris Lattner7a90b682004-10-07 04:16:33 +0000275
Chris Lattner670c8892004-10-08 17:32:09 +0000276 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Agg)) {
277 if (IdxV < CS->getNumOperands()) return CS->getOperand(IdxV);
278 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Agg)) {
279 if (IdxV < CA->getNumOperands()) return CA->getOperand(IdxV);
Reid Spencer9d6565a2007-02-15 02:26:10 +0000280 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Agg)) {
Chris Lattner670c8892004-10-08 17:32:09 +0000281 if (IdxV < CP->getNumOperands()) return CP->getOperand(IdxV);
Chris Lattner7a7ed022004-10-16 18:09:00 +0000282 } else if (isa<ConstantAggregateZero>(Agg)) {
Chris Lattner670c8892004-10-08 17:32:09 +0000283 if (const StructType *STy = dyn_cast<StructType>(Agg->getType())) {
284 if (IdxV < STy->getNumElements())
Owen Andersona7235ea2009-07-31 20:28:14 +0000285 return Constant::getNullValue(STy->getElementType(IdxV));
Chris Lattner670c8892004-10-08 17:32:09 +0000286 } else if (const SequentialType *STy =
287 dyn_cast<SequentialType>(Agg->getType())) {
Owen Andersona7235ea2009-07-31 20:28:14 +0000288 return Constant::getNullValue(STy->getElementType());
Chris Lattner670c8892004-10-08 17:32:09 +0000289 }
Chris Lattner7a7ed022004-10-16 18:09:00 +0000290 } else if (isa<UndefValue>(Agg)) {
291 if (const StructType *STy = dyn_cast<StructType>(Agg->getType())) {
292 if (IdxV < STy->getNumElements())
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000293 return UndefValue::get(STy->getElementType(IdxV));
Chris Lattner7a7ed022004-10-16 18:09:00 +0000294 } else if (const SequentialType *STy =
295 dyn_cast<SequentialType>(Agg->getType())) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000296 return UndefValue::get(STy->getElementType());
Chris Lattner7a7ed022004-10-16 18:09:00 +0000297 }
Chris Lattner670c8892004-10-08 17:32:09 +0000298 }
299 return 0;
300}
Chris Lattner7a90b682004-10-07 04:16:33 +0000301
Chris Lattner7a90b682004-10-07 04:16:33 +0000302
Chris Lattnere47ba742004-10-06 20:57:02 +0000303/// CleanupConstantGlobalUsers - We just marked GV constant. Loop over all
304/// users of the global, cleaning up the obvious ones. This is largely just a
Chris Lattner031955d2004-10-10 16:43:46 +0000305/// quick scan over the use list to clean up the easy and obvious cruft. This
306/// returns true if it made a change.
Chris Lattner7b550cc2009-11-06 04:27:31 +0000307static bool CleanupConstantGlobalUsers(Value *V, Constant *Init) {
Chris Lattner031955d2004-10-10 16:43:46 +0000308 bool Changed = false;
Chris Lattner7a90b682004-10-07 04:16:33 +0000309 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;) {
310 User *U = *UI++;
Misha Brukmanfd939082005-04-21 23:48:37 +0000311
Chris Lattner7a90b682004-10-07 04:16:33 +0000312 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
Chris Lattner35c81b02005-02-27 18:58:52 +0000313 if (Init) {
314 // Replace the load with the initializer.
315 LI->replaceAllUsesWith(Init);
316 LI->eraseFromParent();
317 Changed = true;
318 }
Chris Lattner7a90b682004-10-07 04:16:33 +0000319 } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
Chris Lattnere47ba742004-10-06 20:57:02 +0000320 // Store must be unreachable or storing Init into the global.
Chris Lattner7a7ed022004-10-16 18:09:00 +0000321 SI->eraseFromParent();
Chris Lattner031955d2004-10-10 16:43:46 +0000322 Changed = true;
Chris Lattner7a90b682004-10-07 04:16:33 +0000323 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
324 if (CE->getOpcode() == Instruction::GetElementPtr) {
Chris Lattneraae4a1c2005-09-26 07:34:35 +0000325 Constant *SubInit = 0;
326 if (Init)
Dan Gohmanc6f69e92009-10-05 16:36:26 +0000327 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
Chris Lattner7b550cc2009-11-06 04:27:31 +0000328 Changed |= CleanupConstantGlobalUsers(CE, SubInit);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000329 } else if (CE->getOpcode() == Instruction::BitCast &&
Duncan Sands1df98592010-02-16 11:11:14 +0000330 CE->getType()->isPointerTy()) {
Chris Lattner35c81b02005-02-27 18:58:52 +0000331 // Pointer cast, delete any stores and memsets to the global.
Chris Lattner7b550cc2009-11-06 04:27:31 +0000332 Changed |= CleanupConstantGlobalUsers(CE, 0);
Chris Lattner35c81b02005-02-27 18:58:52 +0000333 }
334
335 if (CE->use_empty()) {
336 CE->destroyConstant();
337 Changed = true;
Chris Lattner7a90b682004-10-07 04:16:33 +0000338 }
339 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
Chris Lattner7b52fe72007-11-09 17:33:02 +0000340 // Do not transform "gepinst (gep constexpr (GV))" here, because forming
341 // "gepconstexpr (gep constexpr (GV))" will cause the two gep's to fold
342 // and will invalidate our notion of what Init is.
Chris Lattner19450242007-11-13 21:46:23 +0000343 Constant *SubInit = 0;
Chris Lattner7b52fe72007-11-09 17:33:02 +0000344 if (!isa<ConstantExpr>(GEP->getOperand(0))) {
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000345 ConstantExpr *CE =
Chris Lattner7b550cc2009-11-06 04:27:31 +0000346 dyn_cast_or_null<ConstantExpr>(ConstantFoldInstruction(GEP));
Chris Lattner7b52fe72007-11-09 17:33:02 +0000347 if (Init && CE && CE->getOpcode() == Instruction::GetElementPtr)
Dan Gohmanc6f69e92009-10-05 16:36:26 +0000348 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
Chris Lattner7b52fe72007-11-09 17:33:02 +0000349 }
Chris Lattner7b550cc2009-11-06 04:27:31 +0000350 Changed |= CleanupConstantGlobalUsers(GEP, SubInit);
Chris Lattnerc4d81b02004-10-10 16:47:33 +0000351
Chris Lattner031955d2004-10-10 16:43:46 +0000352 if (GEP->use_empty()) {
Chris Lattner7a7ed022004-10-16 18:09:00 +0000353 GEP->eraseFromParent();
Chris Lattner031955d2004-10-10 16:43:46 +0000354 Changed = true;
355 }
Chris Lattner35c81b02005-02-27 18:58:52 +0000356 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U)) { // memset/cpy/mv
357 if (MI->getRawDest() == V) {
358 MI->eraseFromParent();
359 Changed = true;
360 }
361
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000362 } else if (Constant *C = dyn_cast<Constant>(U)) {
363 // If we have a chain of dead constantexprs or other things dangling from
364 // us, and if they are all dead, nuke them without remorse.
Jay Foade3acf152009-06-09 21:37:11 +0000365 if (SafeToDestroyConstant(C)) {
Devang Patel743cdf82009-03-06 01:37:41 +0000366 C->destroyConstant();
Chris Lattner35c81b02005-02-27 18:58:52 +0000367 // This could have invalidated UI, start over from scratch.
Chris Lattner7b550cc2009-11-06 04:27:31 +0000368 CleanupConstantGlobalUsers(V, Init);
Chris Lattner031955d2004-10-10 16:43:46 +0000369 return true;
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000370 }
Chris Lattnere47ba742004-10-06 20:57:02 +0000371 }
372 }
Chris Lattner031955d2004-10-10 16:43:46 +0000373 return Changed;
Chris Lattnere47ba742004-10-06 20:57:02 +0000374}
375
Chris Lattner941db492008-01-14 02:09:12 +0000376/// isSafeSROAElementUse - Return true if the specified instruction is a safe
377/// user of a derived expression from a global that we want to SROA.
378static bool isSafeSROAElementUse(Value *V) {
379 // We might have a dead and dangling constant hanging off of here.
380 if (Constant *C = dyn_cast<Constant>(V))
Jay Foade3acf152009-06-09 21:37:11 +0000381 return SafeToDestroyConstant(C);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000382
Chris Lattner941db492008-01-14 02:09:12 +0000383 Instruction *I = dyn_cast<Instruction>(V);
384 if (!I) return false;
385
386 // Loads are ok.
387 if (isa<LoadInst>(I)) return true;
388
389 // Stores *to* the pointer are ok.
390 if (StoreInst *SI = dyn_cast<StoreInst>(I))
391 return SI->getOperand(0) != V;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000392
Chris Lattner941db492008-01-14 02:09:12 +0000393 // Otherwise, it must be a GEP.
394 GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I);
395 if (GEPI == 0) return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000396
Chris Lattner941db492008-01-14 02:09:12 +0000397 if (GEPI->getNumOperands() < 3 || !isa<Constant>(GEPI->getOperand(1)) ||
398 !cast<Constant>(GEPI->getOperand(1))->isNullValue())
399 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000400
Chris Lattner941db492008-01-14 02:09:12 +0000401 for (Value::use_iterator I = GEPI->use_begin(), E = GEPI->use_end();
402 I != E; ++I)
403 if (!isSafeSROAElementUse(*I))
404 return false;
Chris Lattner727c2102008-01-14 01:31:05 +0000405 return true;
406}
407
Chris Lattner941db492008-01-14 02:09:12 +0000408
409/// IsUserOfGlobalSafeForSRA - U is a direct user of the specified global value.
410/// Look at it and its uses and decide whether it is safe to SROA this global.
411///
412static bool IsUserOfGlobalSafeForSRA(User *U, GlobalValue *GV) {
413 // The user of the global must be a GEP Inst or a ConstantExpr GEP.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000414 if (!isa<GetElementPtrInst>(U) &&
415 (!isa<ConstantExpr>(U) ||
Chris Lattner941db492008-01-14 02:09:12 +0000416 cast<ConstantExpr>(U)->getOpcode() != Instruction::GetElementPtr))
417 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000418
Chris Lattner941db492008-01-14 02:09:12 +0000419 // Check to see if this ConstantExpr GEP is SRA'able. In particular, we
420 // don't like < 3 operand CE's, and we don't like non-constant integer
421 // indices. This enforces that all uses are 'gep GV, 0, C, ...' for some
422 // value of C.
423 if (U->getNumOperands() < 3 || !isa<Constant>(U->getOperand(1)) ||
424 !cast<Constant>(U->getOperand(1))->isNullValue() ||
425 !isa<ConstantInt>(U->getOperand(2)))
426 return false;
427
428 gep_type_iterator GEPI = gep_type_begin(U), E = gep_type_end(U);
429 ++GEPI; // Skip over the pointer index.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000430
Chris Lattner941db492008-01-14 02:09:12 +0000431 // If this is a use of an array allocation, do a bit more checking for sanity.
432 if (const ArrayType *AT = dyn_cast<ArrayType>(*GEPI)) {
433 uint64_t NumElements = AT->getNumElements();
434 ConstantInt *Idx = cast<ConstantInt>(U->getOperand(2));
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000435
Chris Lattner941db492008-01-14 02:09:12 +0000436 // Check to make sure that index falls within the array. If not,
437 // something funny is going on, so we won't do the optimization.
438 //
439 if (Idx->getZExtValue() >= NumElements)
440 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000441
Chris Lattner941db492008-01-14 02:09:12 +0000442 // We cannot scalar repl this level of the array unless any array
443 // sub-indices are in-range constants. In particular, consider:
444 // A[0][i]. We cannot know that the user isn't doing invalid things like
445 // allowing i to index an out-of-range subscript that accesses A[1].
446 //
447 // Scalar replacing *just* the outer index of the array is probably not
448 // going to be a win anyway, so just give up.
449 for (++GEPI; // Skip array index.
Dan Gohman6874a2a2009-08-18 14:58:19 +0000450 GEPI != E;
Chris Lattner941db492008-01-14 02:09:12 +0000451 ++GEPI) {
452 uint64_t NumElements;
453 if (const ArrayType *SubArrayTy = dyn_cast<ArrayType>(*GEPI))
454 NumElements = SubArrayTy->getNumElements();
Dan Gohman6874a2a2009-08-18 14:58:19 +0000455 else if (const VectorType *SubVectorTy = dyn_cast<VectorType>(*GEPI))
456 NumElements = SubVectorTy->getNumElements();
457 else {
Duncan Sands1df98592010-02-16 11:11:14 +0000458 assert((*GEPI)->isStructTy() &&
Dan Gohman6874a2a2009-08-18 14:58:19 +0000459 "Indexed GEP type is not array, vector, or struct!");
460 continue;
461 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000462
Chris Lattner941db492008-01-14 02:09:12 +0000463 ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPI.getOperand());
464 if (!IdxVal || IdxVal->getZExtValue() >= NumElements)
465 return false;
466 }
467 }
468
469 for (Value::use_iterator I = U->use_begin(), E = U->use_end(); I != E; ++I)
470 if (!isSafeSROAElementUse(*I))
471 return false;
472 return true;
473}
474
475/// GlobalUsersSafeToSRA - Look at all uses of the global and decide whether it
476/// is safe for us to perform this transformation.
477///
478static bool GlobalUsersSafeToSRA(GlobalValue *GV) {
479 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end();
480 UI != E; ++UI) {
481 if (!IsUserOfGlobalSafeForSRA(*UI, GV))
482 return false;
483 }
484 return true;
485}
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000486
Chris Lattner941db492008-01-14 02:09:12 +0000487
Chris Lattner670c8892004-10-08 17:32:09 +0000488/// SRAGlobal - Perform scalar replacement of aggregates on the specified global
489/// variable. This opens the door for other optimizations by exposing the
490/// behavior of the program in a more fine-grained way. We have determined that
491/// this transformation is safe already. We return the first global variable we
492/// insert so that the caller can reprocess it.
Chris Lattner7b550cc2009-11-06 04:27:31 +0000493static GlobalVariable *SRAGlobal(GlobalVariable *GV, const TargetData &TD) {
Chris Lattner727c2102008-01-14 01:31:05 +0000494 // Make sure this global only has simple uses that we can SRA.
Chris Lattner941db492008-01-14 02:09:12 +0000495 if (!GlobalUsersSafeToSRA(GV))
Chris Lattner727c2102008-01-14 01:31:05 +0000496 return 0;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000497
Rafael Espindolabb46f522009-01-15 20:18:42 +0000498 assert(GV->hasLocalLinkage() && !GV->isConstant());
Chris Lattner670c8892004-10-08 17:32:09 +0000499 Constant *Init = GV->getInitializer();
500 const Type *Ty = Init->getType();
Misha Brukmanfd939082005-04-21 23:48:37 +0000501
Chris Lattner670c8892004-10-08 17:32:09 +0000502 std::vector<GlobalVariable*> NewGlobals;
503 Module::GlobalListType &Globals = GV->getParent()->getGlobalList();
504
Chris Lattner998182b2008-04-26 07:40:11 +0000505 // Get the alignment of the global, either explicit or target-specific.
506 unsigned StartAlignment = GV->getAlignment();
507 if (StartAlignment == 0)
508 StartAlignment = TD.getABITypeAlignment(GV->getType());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000509
Chris Lattner670c8892004-10-08 17:32:09 +0000510 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
511 NewGlobals.reserve(STy->getNumElements());
Chris Lattner998182b2008-04-26 07:40:11 +0000512 const StructLayout &Layout = *TD.getStructLayout(STy);
Chris Lattner670c8892004-10-08 17:32:09 +0000513 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
514 Constant *In = getAggregateConstantElement(Init,
Chris Lattner7b550cc2009-11-06 04:27:31 +0000515 ConstantInt::get(Type::getInt32Ty(STy->getContext()), i));
Chris Lattner670c8892004-10-08 17:32:09 +0000516 assert(In && "Couldn't get element of initializer?");
Chris Lattner7b550cc2009-11-06 04:27:31 +0000517 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(i), false,
Chris Lattner670c8892004-10-08 17:32:09 +0000518 GlobalVariable::InternalLinkage,
Daniel Dunbarfe09b202009-07-30 17:37:43 +0000519 In, GV->getName()+"."+Twine(i),
Matthijs Kooijmanbc1f9892008-07-17 11:59:53 +0000520 GV->isThreadLocal(),
Owen Anderson3d29df32009-07-08 01:26:06 +0000521 GV->getType()->getAddressSpace());
Chris Lattner670c8892004-10-08 17:32:09 +0000522 Globals.insert(GV, NGV);
523 NewGlobals.push_back(NGV);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000524
Chris Lattner998182b2008-04-26 07:40:11 +0000525 // Calculate the known alignment of the field. If the original aggregate
526 // had 256 byte alignment for example, something might depend on that:
527 // propagate info to each field.
528 uint64_t FieldOffset = Layout.getElementOffset(i);
529 unsigned NewAlign = (unsigned)MinAlign(StartAlignment, FieldOffset);
530 if (NewAlign > TD.getABITypeAlignment(STy->getElementType(i)))
531 NGV->setAlignment(NewAlign);
Chris Lattner670c8892004-10-08 17:32:09 +0000532 }
533 } else if (const SequentialType *STy = dyn_cast<SequentialType>(Ty)) {
534 unsigned NumElements = 0;
535 if (const ArrayType *ATy = dyn_cast<ArrayType>(STy))
536 NumElements = ATy->getNumElements();
Chris Lattner670c8892004-10-08 17:32:09 +0000537 else
Chris Lattner998182b2008-04-26 07:40:11 +0000538 NumElements = cast<VectorType>(STy)->getNumElements();
Chris Lattner670c8892004-10-08 17:32:09 +0000539
Chris Lattner1f21ef12005-02-23 16:53:04 +0000540 if (NumElements > 16 && GV->hasNUsesOrMore(16))
Chris Lattnerd514d822005-02-01 01:23:31 +0000541 return 0; // It's not worth it.
Chris Lattner670c8892004-10-08 17:32:09 +0000542 NewGlobals.reserve(NumElements);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000543
Duncan Sands777d2302009-05-09 07:06:46 +0000544 uint64_t EltSize = TD.getTypeAllocSize(STy->getElementType());
Chris Lattner998182b2008-04-26 07:40:11 +0000545 unsigned EltAlign = TD.getABITypeAlignment(STy->getElementType());
Chris Lattner670c8892004-10-08 17:32:09 +0000546 for (unsigned i = 0, e = NumElements; i != e; ++i) {
547 Constant *In = getAggregateConstantElement(Init,
Chris Lattner7b550cc2009-11-06 04:27:31 +0000548 ConstantInt::get(Type::getInt32Ty(Init->getContext()), i));
Chris Lattner670c8892004-10-08 17:32:09 +0000549 assert(In && "Couldn't get element of initializer?");
550
Chris Lattner7b550cc2009-11-06 04:27:31 +0000551 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(), false,
Chris Lattner670c8892004-10-08 17:32:09 +0000552 GlobalVariable::InternalLinkage,
Daniel Dunbarfe09b202009-07-30 17:37:43 +0000553 In, GV->getName()+"."+Twine(i),
Matthijs Kooijmanbc1f9892008-07-17 11:59:53 +0000554 GV->isThreadLocal(),
Owen Andersone9b11b42009-07-08 19:03:57 +0000555 GV->getType()->getAddressSpace());
Chris Lattner670c8892004-10-08 17:32:09 +0000556 Globals.insert(GV, NGV);
557 NewGlobals.push_back(NGV);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000558
Chris Lattner998182b2008-04-26 07:40:11 +0000559 // Calculate the known alignment of the field. If the original aggregate
560 // had 256 byte alignment for example, something might depend on that:
561 // propagate info to each field.
562 unsigned NewAlign = (unsigned)MinAlign(StartAlignment, EltSize*i);
563 if (NewAlign > EltAlign)
564 NGV->setAlignment(NewAlign);
Chris Lattner670c8892004-10-08 17:32:09 +0000565 }
566 }
567
568 if (NewGlobals.empty())
569 return 0;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000570
David Greene3215b0e2010-01-05 01:28:05 +0000571 DEBUG(dbgs() << "PERFORMING GLOBAL SRA ON: " << *GV);
Chris Lattner30ba5692004-10-11 05:54:41 +0000572
Chris Lattner7b550cc2009-11-06 04:27:31 +0000573 Constant *NullInt =Constant::getNullValue(Type::getInt32Ty(GV->getContext()));
Chris Lattner670c8892004-10-08 17:32:09 +0000574
575 // Loop over all of the uses of the global, replacing the constantexpr geps,
576 // with smaller constantexpr geps or direct references.
577 while (!GV->use_empty()) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000578 User *GEP = GV->use_back();
579 assert(((isa<ConstantExpr>(GEP) &&
580 cast<ConstantExpr>(GEP)->getOpcode()==Instruction::GetElementPtr)||
581 isa<GetElementPtrInst>(GEP)) && "NonGEP CE's are not SRAable!");
Misha Brukmanfd939082005-04-21 23:48:37 +0000582
Chris Lattner670c8892004-10-08 17:32:09 +0000583 // Ignore the 1th operand, which has to be zero or else the program is quite
584 // broken (undefined). Get the 2nd operand, which is the structure or array
585 // index.
Reid Spencerb83eb642006-10-20 07:07:24 +0000586 unsigned Val = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
Chris Lattner670c8892004-10-08 17:32:09 +0000587 if (Val >= NewGlobals.size()) Val = 0; // Out of bound array access.
588
Chris Lattner30ba5692004-10-11 05:54:41 +0000589 Value *NewPtr = NewGlobals[Val];
Chris Lattner670c8892004-10-08 17:32:09 +0000590
591 // Form a shorter GEP if needed.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000592 if (GEP->getNumOperands() > 3) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000593 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEP)) {
Chris Lattner55eb1c42007-01-31 04:40:53 +0000594 SmallVector<Constant*, 8> Idxs;
Chris Lattner30ba5692004-10-11 05:54:41 +0000595 Idxs.push_back(NullInt);
596 for (unsigned i = 3, e = CE->getNumOperands(); i != e; ++i)
597 Idxs.push_back(CE->getOperand(i));
Owen Andersonbaf3c402009-07-29 18:55:55 +0000598 NewPtr = ConstantExpr::getGetElementPtr(cast<Constant>(NewPtr),
Chris Lattner55eb1c42007-01-31 04:40:53 +0000599 &Idxs[0], Idxs.size());
Chris Lattner30ba5692004-10-11 05:54:41 +0000600 } else {
601 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(GEP);
Chris Lattner699d1442007-01-31 19:59:55 +0000602 SmallVector<Value*, 8> Idxs;
Chris Lattner30ba5692004-10-11 05:54:41 +0000603 Idxs.push_back(NullInt);
604 for (unsigned i = 3, e = GEPI->getNumOperands(); i != e; ++i)
605 Idxs.push_back(GEPI->getOperand(i));
Gabor Greif051a9502008-04-06 20:25:17 +0000606 NewPtr = GetElementPtrInst::Create(NewPtr, Idxs.begin(), Idxs.end(),
Daniel Dunbarfe09b202009-07-30 17:37:43 +0000607 GEPI->getName()+"."+Twine(Val),GEPI);
Chris Lattner30ba5692004-10-11 05:54:41 +0000608 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000609 }
Chris Lattner30ba5692004-10-11 05:54:41 +0000610 GEP->replaceAllUsesWith(NewPtr);
611
612 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(GEP))
Chris Lattner7a7ed022004-10-16 18:09:00 +0000613 GEPI->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +0000614 else
615 cast<ConstantExpr>(GEP)->destroyConstant();
Chris Lattner670c8892004-10-08 17:32:09 +0000616 }
617
Chris Lattnere40e2d12004-10-08 20:25:55 +0000618 // Delete the old global, now that it is dead.
619 Globals.erase(GV);
Chris Lattner670c8892004-10-08 17:32:09 +0000620 ++NumSRA;
Chris Lattner30ba5692004-10-11 05:54:41 +0000621
622 // Loop over the new globals array deleting any globals that are obviously
623 // dead. This can arise due to scalarization of a structure or an array that
624 // has elements that are dead.
625 unsigned FirstGlobal = 0;
626 for (unsigned i = 0, e = NewGlobals.size(); i != e; ++i)
627 if (NewGlobals[i]->use_empty()) {
628 Globals.erase(NewGlobals[i]);
629 if (FirstGlobal == i) ++FirstGlobal;
630 }
631
632 return FirstGlobal != NewGlobals.size() ? NewGlobals[FirstGlobal] : 0;
Chris Lattner670c8892004-10-08 17:32:09 +0000633}
634
Chris Lattner9b34a612004-10-09 21:48:45 +0000635/// AllUsesOfValueWillTrapIfNull - Return true if all users of the specified
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000636/// value will trap if the value is dynamically null. PHIs keeps track of any
Chris Lattner81686182007-09-13 16:30:19 +0000637/// phi nodes we've seen to avoid reprocessing them.
Gabor Greif6ce02b52010-04-06 19:24:18 +0000638static bool AllUsesOfValueWillTrapIfNull(const Value *V,
639 SmallPtrSet<const PHINode*, 8> &PHIs) {
640 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;
Gabor Greifa01d6db2010-04-06 19:14:05 +0000641 ++UI) {
Gabor Greif6ce02b52010-04-06 19:24:18 +0000642 const User *U = *UI;
Gabor Greifa01d6db2010-04-06 19:14:05 +0000643
644 if (isa<LoadInst>(U)) {
Chris Lattner9b34a612004-10-09 21:48:45 +0000645 // Will trap.
Gabor Greif6ce02b52010-04-06 19:24:18 +0000646 } else if (const StoreInst *SI = dyn_cast<StoreInst>(U)) {
Chris Lattner9b34a612004-10-09 21:48:45 +0000647 if (SI->getOperand(0) == V) {
Gabor Greifa01d6db2010-04-06 19:14:05 +0000648 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner9b34a612004-10-09 21:48:45 +0000649 return false; // Storing the value.
650 }
Gabor Greif6ce02b52010-04-06 19:24:18 +0000651 } else if (const CallInst *CI = dyn_cast<CallInst>(U)) {
Gabor Greif654c06f2010-03-20 21:00:25 +0000652 if (CI->getCalledValue() != V) {
Gabor Greifa01d6db2010-04-06 19:14:05 +0000653 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner9b34a612004-10-09 21:48:45 +0000654 return false; // Not calling the ptr
655 }
Gabor Greif6ce02b52010-04-06 19:24:18 +0000656 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(U)) {
Gabor Greif654c06f2010-03-20 21:00:25 +0000657 if (II->getCalledValue() != V) {
Gabor Greifa01d6db2010-04-06 19:14:05 +0000658 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner9b34a612004-10-09 21:48:45 +0000659 return false; // Not calling the ptr
660 }
Gabor Greif6ce02b52010-04-06 19:24:18 +0000661 } else if (const BitCastInst *CI = dyn_cast<BitCastInst>(U)) {
Chris Lattner81686182007-09-13 16:30:19 +0000662 if (!AllUsesOfValueWillTrapIfNull(CI, PHIs)) return false;
Gabor Greif6ce02b52010-04-06 19:24:18 +0000663 } else if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
Chris Lattner81686182007-09-13 16:30:19 +0000664 if (!AllUsesOfValueWillTrapIfNull(GEPI, PHIs)) return false;
Gabor Greif6ce02b52010-04-06 19:24:18 +0000665 } else if (const PHINode *PN = dyn_cast<PHINode>(U)) {
Chris Lattner81686182007-09-13 16:30:19 +0000666 // If we've already seen this phi node, ignore it, it has already been
667 // checked.
Jakob Stoklund Olesenb489d0f2010-01-29 23:54:14 +0000668 if (PHIs.insert(PN) && !AllUsesOfValueWillTrapIfNull(PN, PHIs))
669 return false;
Gabor Greifa01d6db2010-04-06 19:14:05 +0000670 } else if (isa<ICmpInst>(U) &&
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000671 isa<ConstantPointerNull>(UI->getOperand(1))) {
Nick Lewyckye7ee59b2010-02-25 06:39:10 +0000672 // Ignore icmp X, null
Chris Lattner9b34a612004-10-09 21:48:45 +0000673 } else {
Gabor Greifa01d6db2010-04-06 19:14:05 +0000674 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner9b34a612004-10-09 21:48:45 +0000675 return false;
676 }
Gabor Greifa01d6db2010-04-06 19:14:05 +0000677 }
Chris Lattner9b34a612004-10-09 21:48:45 +0000678 return true;
679}
680
681/// AllUsesOfLoadedValueWillTrapIfNull - Return true if all uses of any loads
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000682/// from GV will trap if the loaded value is null. Note that this also permits
683/// comparisons of the loaded value against null, as a special case.
Gabor Greif6ce02b52010-04-06 19:24:18 +0000684static bool AllUsesOfLoadedValueWillTrapIfNull(const GlobalVariable *GV) {
685 for (Value::const_use_iterator UI = GV->use_begin(), E = GV->use_end();
Gabor Greifa01d6db2010-04-06 19:14:05 +0000686 UI != E; ++UI) {
Gabor Greif6ce02b52010-04-06 19:24:18 +0000687 const User *U = *UI;
Gabor Greifa01d6db2010-04-06 19:14:05 +0000688
Gabor Greif6ce02b52010-04-06 19:24:18 +0000689 if (const LoadInst *LI = dyn_cast<LoadInst>(U)) {
690 SmallPtrSet<const PHINode*, 8> PHIs;
Chris Lattner81686182007-09-13 16:30:19 +0000691 if (!AllUsesOfValueWillTrapIfNull(LI, PHIs))
Chris Lattner9b34a612004-10-09 21:48:45 +0000692 return false;
Gabor Greifa01d6db2010-04-06 19:14:05 +0000693 } else if (isa<StoreInst>(U)) {
Chris Lattner9b34a612004-10-09 21:48:45 +0000694 // Ignore stores to the global.
695 } else {
696 // We don't know or understand this user, bail out.
Gabor Greifa01d6db2010-04-06 19:14:05 +0000697 //cerr << "UNKNOWN USER OF GLOBAL!: " << *U;
Chris Lattner9b34a612004-10-09 21:48:45 +0000698 return false;
699 }
Gabor Greifa01d6db2010-04-06 19:14:05 +0000700 }
Chris Lattner9b34a612004-10-09 21:48:45 +0000701 return true;
702}
703
Chris Lattner7b550cc2009-11-06 04:27:31 +0000704static bool OptimizeAwayTrappingUsesOfValue(Value *V, Constant *NewV) {
Chris Lattner708148e2004-10-10 23:14:11 +0000705 bool Changed = false;
706 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ) {
707 Instruction *I = cast<Instruction>(*UI++);
708 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
709 LI->setOperand(0, NewV);
710 Changed = true;
711 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
712 if (SI->getOperand(1) == V) {
713 SI->setOperand(1, NewV);
714 Changed = true;
715 }
716 } else if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
Gabor Greiffa1f5c22010-04-06 18:45:08 +0000717 CallSite CS(I);
718 if (CS.getCalledValue() == V) {
Chris Lattner708148e2004-10-10 23:14:11 +0000719 // Calling through the pointer! Turn into a direct call, but be careful
720 // that the pointer is not also being passed as an argument.
Gabor Greiffa1f5c22010-04-06 18:45:08 +0000721 CS.setCalledFunction(NewV);
Chris Lattner708148e2004-10-10 23:14:11 +0000722 Changed = true;
723 bool PassedAsArg = false;
Gabor Greiffa1f5c22010-04-06 18:45:08 +0000724 for (unsigned i = 0, e = CS.arg_size(); i != e; ++i)
725 if (CS.getArgument(i) == V) {
Chris Lattner708148e2004-10-10 23:14:11 +0000726 PassedAsArg = true;
Gabor Greiffa1f5c22010-04-06 18:45:08 +0000727 CS.setArgument(i, NewV);
Chris Lattner708148e2004-10-10 23:14:11 +0000728 }
729
730 if (PassedAsArg) {
731 // Being passed as an argument also. Be careful to not invalidate UI!
732 UI = V->use_begin();
733 }
734 }
735 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
736 Changed |= OptimizeAwayTrappingUsesOfValue(CI,
Owen Andersonbaf3c402009-07-29 18:55:55 +0000737 ConstantExpr::getCast(CI->getOpcode(),
Chris Lattner7b550cc2009-11-06 04:27:31 +0000738 NewV, CI->getType()));
Chris Lattner708148e2004-10-10 23:14:11 +0000739 if (CI->use_empty()) {
740 Changed = true;
Chris Lattner7a7ed022004-10-16 18:09:00 +0000741 CI->eraseFromParent();
Chris Lattner708148e2004-10-10 23:14:11 +0000742 }
743 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
744 // Should handle GEP here.
Chris Lattner55eb1c42007-01-31 04:40:53 +0000745 SmallVector<Constant*, 8> Idxs;
746 Idxs.reserve(GEPI->getNumOperands()-1);
Gabor Greif5e463212008-05-29 01:59:18 +0000747 for (User::op_iterator i = GEPI->op_begin() + 1, e = GEPI->op_end();
748 i != e; ++i)
749 if (Constant *C = dyn_cast<Constant>(*i))
Chris Lattner55eb1c42007-01-31 04:40:53 +0000750 Idxs.push_back(C);
Chris Lattner708148e2004-10-10 23:14:11 +0000751 else
752 break;
Chris Lattner55eb1c42007-01-31 04:40:53 +0000753 if (Idxs.size() == GEPI->getNumOperands()-1)
Chris Lattner708148e2004-10-10 23:14:11 +0000754 Changed |= OptimizeAwayTrappingUsesOfValue(GEPI,
Owen Andersonbaf3c402009-07-29 18:55:55 +0000755 ConstantExpr::getGetElementPtr(NewV, &Idxs[0],
Chris Lattner7b550cc2009-11-06 04:27:31 +0000756 Idxs.size()));
Chris Lattner708148e2004-10-10 23:14:11 +0000757 if (GEPI->use_empty()) {
758 Changed = true;
Chris Lattner7a7ed022004-10-16 18:09:00 +0000759 GEPI->eraseFromParent();
Chris Lattner708148e2004-10-10 23:14:11 +0000760 }
761 }
762 }
763
764 return Changed;
765}
766
767
768/// OptimizeAwayTrappingUsesOfLoads - The specified global has only one non-null
769/// value stored into it. If there are uses of the loaded value that would trap
770/// if the loaded value is dynamically null, then we know that they cannot be
771/// reachable with a null optimize away the load.
Chris Lattner7b550cc2009-11-06 04:27:31 +0000772static bool OptimizeAwayTrappingUsesOfLoads(GlobalVariable *GV, Constant *LV) {
Chris Lattner708148e2004-10-10 23:14:11 +0000773 bool Changed = false;
774
Chris Lattner92c6bd22009-01-14 00:12:58 +0000775 // Keep track of whether we are able to remove all the uses of the global
776 // other than the store that defines it.
777 bool AllNonStoreUsesGone = true;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000778
Chris Lattner708148e2004-10-10 23:14:11 +0000779 // Replace all uses of loads with uses of uses of the stored value.
Chris Lattner92c6bd22009-01-14 00:12:58 +0000780 for (Value::use_iterator GUI = GV->use_begin(), E = GV->use_end(); GUI != E;){
781 User *GlobalUser = *GUI++;
782 if (LoadInst *LI = dyn_cast<LoadInst>(GlobalUser)) {
Chris Lattner7b550cc2009-11-06 04:27:31 +0000783 Changed |= OptimizeAwayTrappingUsesOfValue(LI, LV);
Chris Lattner92c6bd22009-01-14 00:12:58 +0000784 // If we were able to delete all uses of the loads
785 if (LI->use_empty()) {
786 LI->eraseFromParent();
787 Changed = true;
788 } else {
789 AllNonStoreUsesGone = false;
790 }
791 } else if (isa<StoreInst>(GlobalUser)) {
792 // Ignore the store that stores "LV" to the global.
793 assert(GlobalUser->getOperand(1) == GV &&
794 "Must be storing *to* the global");
Chris Lattner708148e2004-10-10 23:14:11 +0000795 } else {
Chris Lattner92c6bd22009-01-14 00:12:58 +0000796 AllNonStoreUsesGone = false;
797
798 // If we get here we could have other crazy uses that are transitively
799 // loaded.
800 assert((isa<PHINode>(GlobalUser) || isa<SelectInst>(GlobalUser) ||
801 isa<ConstantExpr>(GlobalUser)) && "Only expect load and stores!");
Chris Lattner708148e2004-10-10 23:14:11 +0000802 }
Chris Lattner92c6bd22009-01-14 00:12:58 +0000803 }
Chris Lattner708148e2004-10-10 23:14:11 +0000804
805 if (Changed) {
David Greene3215b0e2010-01-05 01:28:05 +0000806 DEBUG(dbgs() << "OPTIMIZED LOADS FROM STORED ONCE POINTER: " << *GV);
Chris Lattner708148e2004-10-10 23:14:11 +0000807 ++NumGlobUses;
808 }
809
Chris Lattner708148e2004-10-10 23:14:11 +0000810 // If we nuked all of the loads, then none of the stores are needed either,
811 // nor is the global.
Chris Lattner92c6bd22009-01-14 00:12:58 +0000812 if (AllNonStoreUsesGone) {
David Greene3215b0e2010-01-05 01:28:05 +0000813 DEBUG(dbgs() << " *** GLOBAL NOW DEAD!\n");
Chris Lattner7b550cc2009-11-06 04:27:31 +0000814 CleanupConstantGlobalUsers(GV, 0);
Chris Lattner708148e2004-10-10 23:14:11 +0000815 if (GV->use_empty()) {
Chris Lattner7a7ed022004-10-16 18:09:00 +0000816 GV->eraseFromParent();
Chris Lattner708148e2004-10-10 23:14:11 +0000817 ++NumDeleted;
818 }
819 Changed = true;
820 }
821 return Changed;
822}
823
Chris Lattner30ba5692004-10-11 05:54:41 +0000824/// ConstantPropUsersOf - Walk the use list of V, constant folding all of the
825/// instructions that are foldable.
Chris Lattner7b550cc2009-11-06 04:27:31 +0000826static void ConstantPropUsersOf(Value *V) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000827 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; )
828 if (Instruction *I = dyn_cast<Instruction>(*UI++))
Chris Lattner7b550cc2009-11-06 04:27:31 +0000829 if (Constant *NewC = ConstantFoldInstruction(I)) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000830 I->replaceAllUsesWith(NewC);
831
Chris Lattnerd514d822005-02-01 01:23:31 +0000832 // Advance UI to the next non-I use to avoid invalidating it!
833 // Instructions could multiply use V.
834 while (UI != E && *UI == I)
Chris Lattner30ba5692004-10-11 05:54:41 +0000835 ++UI;
Chris Lattnerd514d822005-02-01 01:23:31 +0000836 I->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +0000837 }
838}
839
840/// OptimizeGlobalAddressOfMalloc - This function takes the specified global
841/// variable, and transforms the program as if it always contained the result of
842/// the specified malloc. Because it is always the result of the specified
843/// malloc, there is no reason to actually DO the malloc. Instead, turn the
Chris Lattner6e8fbad2006-11-30 17:32:29 +0000844/// malloc into a global, and any loads of GV as uses of the new global.
Chris Lattner30ba5692004-10-11 05:54:41 +0000845static GlobalVariable *OptimizeGlobalAddressOfMalloc(GlobalVariable *GV,
Victor Hernandez83d63912009-09-18 22:35:49 +0000846 CallInst *CI,
Victor Hernandez9d0b7042009-11-07 00:16:28 +0000847 const Type *AllocTy,
Chris Lattnera6874652010-02-25 22:33:52 +0000848 ConstantInt *NElements,
Victor Hernandez83d63912009-09-18 22:35:49 +0000849 TargetData* TD) {
Chris Lattnera6874652010-02-25 22:33:52 +0000850 DEBUG(errs() << "PROMOTING GLOBAL: " << *GV << " CALL = " << *CI << '\n');
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000851
Chris Lattnera6874652010-02-25 22:33:52 +0000852 const Type *GlobalType;
853 if (NElements->getZExtValue() == 1)
854 GlobalType = AllocTy;
855 else
856 // If we have an array allocation, the global variable is of an array.
857 GlobalType = ArrayType::get(AllocTy, NElements->getZExtValue());
Victor Hernandez83d63912009-09-18 22:35:49 +0000858
859 // Create the new global variable. The contents of the malloc'd memory is
860 // undefined, so initialize with an undef value.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000861 GlobalVariable *NewGV = new GlobalVariable(*GV->getParent(),
Chris Lattnere9fd4442010-02-26 23:42:13 +0000862 GlobalType, false,
Chris Lattnera6874652010-02-25 22:33:52 +0000863 GlobalValue::InternalLinkage,
Chris Lattnere9fd4442010-02-26 23:42:13 +0000864 UndefValue::get(GlobalType),
Victor Hernandez83d63912009-09-18 22:35:49 +0000865 GV->getName()+".body",
866 GV,
867 GV->isThreadLocal());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000868
Chris Lattnera6874652010-02-25 22:33:52 +0000869 // If there are bitcast users of the malloc (which is typical, usually we have
870 // a malloc + bitcast) then replace them with uses of the new global. Update
871 // other users to use the global as well.
872 BitCastInst *TheBC = 0;
873 while (!CI->use_empty()) {
874 Instruction *User = cast<Instruction>(CI->use_back());
875 if (BitCastInst *BCI = dyn_cast<BitCastInst>(User)) {
876 if (BCI->getType() == NewGV->getType()) {
877 BCI->replaceAllUsesWith(NewGV);
878 BCI->eraseFromParent();
879 } else {
880 BCI->setOperand(0, NewGV);
881 }
882 } else {
883 if (TheBC == 0)
884 TheBC = new BitCastInst(NewGV, CI->getType(), "newgv", CI);
885 User->replaceUsesOfWith(CI, TheBC);
886 }
887 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000888
Victor Hernandez83d63912009-09-18 22:35:49 +0000889 Constant *RepValue = NewGV;
890 if (NewGV->getType() != GV->getType()->getElementType())
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000891 RepValue = ConstantExpr::getBitCast(RepValue,
Victor Hernandez83d63912009-09-18 22:35:49 +0000892 GV->getType()->getElementType());
893
894 // If there is a comparison against null, we will insert a global bool to
895 // keep track of whether the global was initialized yet or not.
896 GlobalVariable *InitBool =
Chris Lattner7b550cc2009-11-06 04:27:31 +0000897 new GlobalVariable(Type::getInt1Ty(GV->getContext()), false,
Victor Hernandez83d63912009-09-18 22:35:49 +0000898 GlobalValue::InternalLinkage,
Chris Lattner7b550cc2009-11-06 04:27:31 +0000899 ConstantInt::getFalse(GV->getContext()),
900 GV->getName()+".init", GV->isThreadLocal());
Victor Hernandez83d63912009-09-18 22:35:49 +0000901 bool InitBoolUsed = false;
902
903 // Loop over all uses of GV, processing them in turn.
Chris Lattnera6874652010-02-25 22:33:52 +0000904 while (!GV->use_empty()) {
905 if (StoreInst *SI = dyn_cast<StoreInst>(GV->use_back())) {
Victor Hernandez83d63912009-09-18 22:35:49 +0000906 // The global is initialized when the store to it occurs.
Chris Lattner7b550cc2009-11-06 04:27:31 +0000907 new StoreInst(ConstantInt::getTrue(GV->getContext()), InitBool, SI);
Victor Hernandez83d63912009-09-18 22:35:49 +0000908 SI->eraseFromParent();
Chris Lattnera6874652010-02-25 22:33:52 +0000909 continue;
Victor Hernandez83d63912009-09-18 22:35:49 +0000910 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000911
Chris Lattnera6874652010-02-25 22:33:52 +0000912 LoadInst *LI = cast<LoadInst>(GV->use_back());
913 while (!LI->use_empty()) {
914 Use &LoadUse = LI->use_begin().getUse();
915 if (!isa<ICmpInst>(LoadUse.getUser())) {
916 LoadUse = RepValue;
917 continue;
918 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000919
Chris Lattnera6874652010-02-25 22:33:52 +0000920 ICmpInst *ICI = cast<ICmpInst>(LoadUse.getUser());
921 // Replace the cmp X, 0 with a use of the bool value.
922 Value *LV = new LoadInst(InitBool, InitBool->getName()+".val", ICI);
923 InitBoolUsed = true;
924 switch (ICI->getPredicate()) {
925 default: llvm_unreachable("Unknown ICmp Predicate!");
926 case ICmpInst::ICMP_ULT:
927 case ICmpInst::ICMP_SLT: // X < null -> always false
928 LV = ConstantInt::getFalse(GV->getContext());
929 break;
930 case ICmpInst::ICMP_ULE:
931 case ICmpInst::ICMP_SLE:
932 case ICmpInst::ICMP_EQ:
933 LV = BinaryOperator::CreateNot(LV, "notinit", ICI);
934 break;
935 case ICmpInst::ICMP_NE:
936 case ICmpInst::ICMP_UGE:
937 case ICmpInst::ICMP_SGE:
938 case ICmpInst::ICMP_UGT:
939 case ICmpInst::ICMP_SGT:
940 break; // no change.
941 }
942 ICI->replaceAllUsesWith(LV);
943 ICI->eraseFromParent();
944 }
945 LI->eraseFromParent();
946 }
Victor Hernandez83d63912009-09-18 22:35:49 +0000947
948 // If the initialization boolean was used, insert it, otherwise delete it.
949 if (!InitBoolUsed) {
950 while (!InitBool->use_empty()) // Delete initializations
Chris Lattnera6874652010-02-25 22:33:52 +0000951 cast<StoreInst>(InitBool->use_back())->eraseFromParent();
Victor Hernandez83d63912009-09-18 22:35:49 +0000952 delete InitBool;
953 } else
954 GV->getParent()->getGlobalList().insert(GV, InitBool);
955
Chris Lattnera6874652010-02-25 22:33:52 +0000956 // Now the GV is dead, nuke it and the malloc..
Victor Hernandez83d63912009-09-18 22:35:49 +0000957 GV->eraseFromParent();
Victor Hernandez83d63912009-09-18 22:35:49 +0000958 CI->eraseFromParent();
959
960 // To further other optimizations, loop over all users of NewGV and try to
961 // constant prop them. This will promote GEP instructions with constant
962 // indices into GEP constant-exprs, which will allow global-opt to hack on it.
Chris Lattner7b550cc2009-11-06 04:27:31 +0000963 ConstantPropUsersOf(NewGV);
Victor Hernandez83d63912009-09-18 22:35:49 +0000964 if (RepValue != NewGV)
Chris Lattner7b550cc2009-11-06 04:27:31 +0000965 ConstantPropUsersOf(RepValue);
Victor Hernandez83d63912009-09-18 22:35:49 +0000966
967 return NewGV;
968}
969
Chris Lattnerfa07e4f2004-12-02 07:11:07 +0000970/// ValueIsOnlyUsedLocallyOrStoredToOneGlobal - Scan the use-list of V checking
971/// to make sure that there are no complex uses of V. We permit simple things
972/// like dereferencing the pointer, but not storing through the address, unless
973/// it is to the specified global.
Gabor Greif0b520db2010-04-06 18:58:22 +0000974static bool ValueIsOnlyUsedLocallyOrStoredToOneGlobal(const Instruction *V,
975 const GlobalVariable *GV,
Gabor Greifa01d6db2010-04-06 19:14:05 +0000976 SmallPtrSet<const PHINode*, 8> &PHIs) {
Gabor Greif0b520db2010-04-06 18:58:22 +0000977 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end();
Gabor Greifa01d6db2010-04-06 19:14:05 +0000978 UI != E; ++UI) {
Gabor Greif0b520db2010-04-06 18:58:22 +0000979 const Instruction *Inst = cast<Instruction>(*UI);
Gabor Greifa01d6db2010-04-06 19:14:05 +0000980
Chris Lattner49b6d4a2008-12-15 21:08:54 +0000981 if (isa<LoadInst>(Inst) || isa<CmpInst>(Inst)) {
982 continue; // Fine, ignore.
983 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000984
Gabor Greif0b520db2010-04-06 18:58:22 +0000985 if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
Chris Lattnerfa07e4f2004-12-02 07:11:07 +0000986 if (SI->getOperand(0) == V && SI->getOperand(1) != GV)
987 return false; // Storing the pointer itself... bad.
Chris Lattner49b6d4a2008-12-15 21:08:54 +0000988 continue; // Otherwise, storing through it, or storing into GV... fine.
989 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000990
Chris Lattnera2fb2342010-04-10 18:19:22 +0000991 // Must index into the array and into the struct.
992 if (isa<GetElementPtrInst>(Inst) && Inst->getNumOperands() >= 3) {
Chris Lattner49b6d4a2008-12-15 21:08:54 +0000993 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(Inst, GV, PHIs))
Chris Lattnerfa07e4f2004-12-02 07:11:07 +0000994 return false;
Chris Lattner49b6d4a2008-12-15 21:08:54 +0000995 continue;
996 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000997
Gabor Greif0b520db2010-04-06 18:58:22 +0000998 if (const PHINode *PN = dyn_cast<PHINode>(Inst)) {
Chris Lattnerc451f9c2007-09-13 16:37:20 +0000999 // PHIs are ok if all uses are ok. Don't infinitely recurse through PHI
1000 // cycles.
1001 if (PHIs.insert(PN))
Chris Lattner5e6e4942007-09-14 03:41:21 +00001002 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(PN, GV, PHIs))
1003 return false;
Chris Lattner49b6d4a2008-12-15 21:08:54 +00001004 continue;
Chris Lattnerfa07e4f2004-12-02 07:11:07 +00001005 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001006
Gabor Greif0b520db2010-04-06 18:58:22 +00001007 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Inst)) {
Chris Lattner49b6d4a2008-12-15 21:08:54 +00001008 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(BCI, GV, PHIs))
1009 return false;
1010 continue;
1011 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001012
Chris Lattner49b6d4a2008-12-15 21:08:54 +00001013 return false;
1014 }
Chris Lattnerfa07e4f2004-12-02 07:11:07 +00001015 return true;
Chris Lattnerfa07e4f2004-12-02 07:11:07 +00001016}
1017
Chris Lattner86395032006-09-30 23:32:09 +00001018/// ReplaceUsesOfMallocWithGlobal - The Alloc pointer is stored into GV
1019/// somewhere. Transform all uses of the allocation into loads from the
1020/// global and uses of the resultant pointer. Further, delete the store into
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001021/// GV. This assumes that these value pass the
Chris Lattner86395032006-09-30 23:32:09 +00001022/// 'ValueIsOnlyUsedLocallyOrStoredToOneGlobal' predicate.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001023static void ReplaceUsesOfMallocWithGlobal(Instruction *Alloc,
Chris Lattner86395032006-09-30 23:32:09 +00001024 GlobalVariable *GV) {
1025 while (!Alloc->use_empty()) {
Chris Lattnera637a8b2007-09-13 18:00:31 +00001026 Instruction *U = cast<Instruction>(*Alloc->use_begin());
1027 Instruction *InsertPt = U;
Chris Lattner86395032006-09-30 23:32:09 +00001028 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
1029 // If this is the store of the allocation into the global, remove it.
1030 if (SI->getOperand(1) == GV) {
1031 SI->eraseFromParent();
1032 continue;
1033 }
Chris Lattnera637a8b2007-09-13 18:00:31 +00001034 } else if (PHINode *PN = dyn_cast<PHINode>(U)) {
1035 // Insert the load in the corresponding predecessor, not right before the
1036 // PHI.
Gabor Greifa36791d2009-01-23 19:40:15 +00001037 InsertPt = PN->getIncomingBlock(Alloc->use_begin())->getTerminator();
Chris Lattner101f44e2008-12-15 21:44:34 +00001038 } else if (isa<BitCastInst>(U)) {
1039 // Must be bitcast between the malloc and store to initialize the global.
1040 ReplaceUsesOfMallocWithGlobal(U, GV);
1041 U->eraseFromParent();
1042 continue;
1043 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
1044 // If this is a "GEP bitcast" and the user is a store to the global, then
1045 // just process it as a bitcast.
1046 if (GEPI->hasAllZeroIndices() && GEPI->hasOneUse())
1047 if (StoreInst *SI = dyn_cast<StoreInst>(GEPI->use_back()))
1048 if (SI->getOperand(1) == GV) {
1049 // Must be bitcast GEP between the malloc and store to initialize
1050 // the global.
1051 ReplaceUsesOfMallocWithGlobal(GEPI, GV);
1052 GEPI->eraseFromParent();
1053 continue;
1054 }
Chris Lattner86395032006-09-30 23:32:09 +00001055 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001056
Chris Lattner86395032006-09-30 23:32:09 +00001057 // Insert a load from the global, and use it instead of the malloc.
Chris Lattnera637a8b2007-09-13 18:00:31 +00001058 Value *NL = new LoadInst(GV, GV->getName()+".val", InsertPt);
Chris Lattner86395032006-09-30 23:32:09 +00001059 U->replaceUsesOfWith(Alloc, NL);
1060 }
1061}
1062
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001063/// LoadUsesSimpleEnoughForHeapSRA - Verify that all uses of V (a load, or a phi
1064/// of a load) are simple enough to perform heap SRA on. This permits GEP's
1065/// that index through the array and struct field, icmps of null, and PHIs.
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001066static bool LoadUsesSimpleEnoughForHeapSRA(const Value *V,
Gabor Greif27236912010-04-07 18:59:26 +00001067 SmallPtrSet<const PHINode*, 32> &LoadUsingPHIs,
1068 SmallPtrSet<const PHINode*, 32> &LoadUsingPHIsPerLoad) {
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001069 // We permit two users of the load: setcc comparing against the null
1070 // pointer, and a getelementptr of a specific form.
Gabor Greif27236912010-04-07 18:59:26 +00001071 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;
1072 ++UI) {
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001073 const Instruction *User = cast<Instruction>(*UI);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001074
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001075 // Comparison against null is ok.
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001076 if (const ICmpInst *ICI = dyn_cast<ICmpInst>(User)) {
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001077 if (!isa<ConstantPointerNull>(ICI->getOperand(1)))
1078 return false;
1079 continue;
1080 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001081
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001082 // getelementptr is also ok, but only a simple form.
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001083 if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001084 // Must index into the array and into the struct.
1085 if (GEPI->getNumOperands() < 3)
1086 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001087
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001088 // Otherwise the GEP is ok.
1089 continue;
1090 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001091
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001092 if (const PHINode *PN = dyn_cast<PHINode>(User)) {
Evan Cheng5d163962009-06-02 00:56:07 +00001093 if (!LoadUsingPHIsPerLoad.insert(PN))
1094 // This means some phi nodes are dependent on each other.
1095 // Avoid infinite looping!
1096 return false;
1097 if (!LoadUsingPHIs.insert(PN))
1098 // If we have already analyzed this PHI, then it is safe.
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001099 continue;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001100
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001101 // Make sure all uses of the PHI are simple enough to transform.
Evan Cheng5d163962009-06-02 00:56:07 +00001102 if (!LoadUsesSimpleEnoughForHeapSRA(PN,
1103 LoadUsingPHIs, LoadUsingPHIsPerLoad))
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001104 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001105
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001106 continue;
Chris Lattner86395032006-09-30 23:32:09 +00001107 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001108
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001109 // Otherwise we don't know what this is, not ok.
1110 return false;
1111 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001112
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001113 return true;
1114}
1115
1116
1117/// AllGlobalLoadUsesSimpleEnoughForHeapSRA - If all users of values loaded from
1118/// GV are simple enough to perform HeapSRA, return true.
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001119static bool AllGlobalLoadUsesSimpleEnoughForHeapSRA(const GlobalVariable *GV,
Victor Hernandez83d63912009-09-18 22:35:49 +00001120 Instruction *StoredVal) {
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001121 SmallPtrSet<const PHINode*, 32> LoadUsingPHIs;
1122 SmallPtrSet<const PHINode*, 32> LoadUsingPHIsPerLoad;
Gabor Greif27236912010-04-07 18:59:26 +00001123 for (Value::const_use_iterator UI = GV->use_begin(), E = GV->use_end();
1124 UI != E; ++UI)
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001125 if (const LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
Evan Cheng5d163962009-06-02 00:56:07 +00001126 if (!LoadUsesSimpleEnoughForHeapSRA(LI, LoadUsingPHIs,
1127 LoadUsingPHIsPerLoad))
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001128 return false;
Evan Cheng5d163962009-06-02 00:56:07 +00001129 LoadUsingPHIsPerLoad.clear();
1130 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001131
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001132 // If we reach here, we know that all uses of the loads and transitive uses
1133 // (through PHI nodes) are simple enough to transform. However, we don't know
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001134 // that all inputs the to the PHI nodes are in the same equivalence sets.
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001135 // Check to verify that all operands of the PHIs are either PHIS that can be
1136 // transformed, loads from GV, or MI itself.
Gabor Greif27236912010-04-07 18:59:26 +00001137 for (SmallPtrSet<const PHINode*, 32>::const_iterator I = LoadUsingPHIs.begin()
1138 , E = LoadUsingPHIs.end(); I != E; ++I) {
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001139 const PHINode *PN = *I;
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001140 for (unsigned op = 0, e = PN->getNumIncomingValues(); op != e; ++op) {
1141 Value *InVal = PN->getIncomingValue(op);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001142
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001143 // PHI of the stored value itself is ok.
Victor Hernandez83d63912009-09-18 22:35:49 +00001144 if (InVal == StoredVal) continue;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001145
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001146 if (const PHINode *InPN = dyn_cast<PHINode>(InVal)) {
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001147 // One of the PHIs in our set is (optimistically) ok.
1148 if (LoadUsingPHIs.count(InPN))
1149 continue;
1150 return false;
1151 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001152
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001153 // Load from GV is ok.
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001154 if (const LoadInst *LI = dyn_cast<LoadInst>(InVal))
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001155 if (LI->getOperand(0) == GV)
1156 continue;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001157
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001158 // UNDEF? NULL?
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001159
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001160 // Anything else is rejected.
1161 return false;
1162 }
1163 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001164
Chris Lattner86395032006-09-30 23:32:09 +00001165 return true;
1166}
1167
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001168static Value *GetHeapSROAValue(Value *V, unsigned FieldNo,
1169 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001170 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001171 std::vector<Value*> &FieldVals = InsertedScalarizedValues[V];
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001172
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001173 if (FieldNo >= FieldVals.size())
1174 FieldVals.resize(FieldNo+1);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001175
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001176 // If we already have this value, just reuse the previously scalarized
1177 // version.
1178 if (Value *FieldVal = FieldVals[FieldNo])
1179 return FieldVal;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001180
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001181 // Depending on what instruction this is, we have several cases.
1182 Value *Result;
1183 if (LoadInst *LI = dyn_cast<LoadInst>(V)) {
1184 // This is a scalarized version of the load from the global. Just create
1185 // a new Load of the scalarized global.
1186 Result = new LoadInst(GetHeapSROAValue(LI->getOperand(0), FieldNo,
1187 InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001188 PHIsToRewrite),
Daniel Dunbarfe09b202009-07-30 17:37:43 +00001189 LI->getName()+".f"+Twine(FieldNo), LI);
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001190 } else if (PHINode *PN = dyn_cast<PHINode>(V)) {
1191 // PN's type is pointer to struct. Make a new PHI of pointer to struct
1192 // field.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001193 const StructType *ST =
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001194 cast<StructType>(cast<PointerType>(PN->getType())->getElementType());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001195
Jay Foadd8b4fb42011-03-30 11:19:20 +00001196 PHINode *NewPN =
Owen Andersondebcb012009-07-29 22:17:13 +00001197 PHINode::Create(PointerType::getUnqual(ST->getElementType(FieldNo)),
Jay Foad3ecfc862011-03-30 11:28:46 +00001198 PN->getNumIncomingValues(),
Daniel Dunbarfe09b202009-07-30 17:37:43 +00001199 PN->getName()+".f"+Twine(FieldNo), PN);
Jay Foadd8b4fb42011-03-30 11:19:20 +00001200 Result = NewPN;
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001201 PHIsToRewrite.push_back(std::make_pair(PN, FieldNo));
1202 } else {
Torok Edwinc23197a2009-07-14 16:55:14 +00001203 llvm_unreachable("Unknown usable value");
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001204 Result = 0;
1205 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001206
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001207 return FieldVals[FieldNo] = Result;
Chris Lattnera637a8b2007-09-13 18:00:31 +00001208}
1209
Chris Lattner330245e2007-09-13 17:29:05 +00001210/// RewriteHeapSROALoadUser - Given a load instruction and a value derived from
1211/// the load, rewrite the derived value to use the HeapSRoA'd load.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001212static void RewriteHeapSROALoadUser(Instruction *LoadUser,
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001213 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001214 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
Chris Lattner330245e2007-09-13 17:29:05 +00001215 // If this is a comparison against null, handle it.
1216 if (ICmpInst *SCI = dyn_cast<ICmpInst>(LoadUser)) {
1217 assert(isa<ConstantPointerNull>(SCI->getOperand(1)));
1218 // If we have a setcc of the loaded pointer, we can use a setcc of any
1219 // field.
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001220 Value *NPtr = GetHeapSROAValue(SCI->getOperand(0), 0,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001221 InsertedScalarizedValues, PHIsToRewrite);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001222
Owen Anderson333c4002009-07-09 23:48:35 +00001223 Value *New = new ICmpInst(SCI, SCI->getPredicate(), NPtr,
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001224 Constant::getNullValue(NPtr->getType()),
Owen Anderson333c4002009-07-09 23:48:35 +00001225 SCI->getName());
Chris Lattner330245e2007-09-13 17:29:05 +00001226 SCI->replaceAllUsesWith(New);
1227 SCI->eraseFromParent();
1228 return;
1229 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001230
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001231 // Handle 'getelementptr Ptr, Idx, i32 FieldNo ...'
Chris Lattnera637a8b2007-09-13 18:00:31 +00001232 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(LoadUser)) {
1233 assert(GEPI->getNumOperands() >= 3 && isa<ConstantInt>(GEPI->getOperand(2))
1234 && "Unexpected GEPI!");
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001235
Chris Lattnera637a8b2007-09-13 18:00:31 +00001236 // Load the pointer for this field.
1237 unsigned FieldNo = cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue();
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001238 Value *NewPtr = GetHeapSROAValue(GEPI->getOperand(0), FieldNo,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001239 InsertedScalarizedValues, PHIsToRewrite);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001240
Chris Lattnera637a8b2007-09-13 18:00:31 +00001241 // Create the new GEP idx vector.
1242 SmallVector<Value*, 8> GEPIdx;
1243 GEPIdx.push_back(GEPI->getOperand(1));
1244 GEPIdx.append(GEPI->op_begin()+3, GEPI->op_end());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001245
Gabor Greifb1dbcd82008-05-15 10:04:30 +00001246 Value *NGEPI = GetElementPtrInst::Create(NewPtr,
1247 GEPIdx.begin(), GEPIdx.end(),
Gabor Greif051a9502008-04-06 20:25:17 +00001248 GEPI->getName(), GEPI);
Chris Lattnera637a8b2007-09-13 18:00:31 +00001249 GEPI->replaceAllUsesWith(NGEPI);
1250 GEPI->eraseFromParent();
1251 return;
1252 }
Chris Lattner309f20f2007-09-13 21:31:36 +00001253
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001254 // Recursively transform the users of PHI nodes. This will lazily create the
1255 // PHIs that are needed for individual elements. Keep track of what PHIs we
1256 // see in InsertedScalarizedValues so that we don't get infinite loops (very
1257 // antisocial). If the PHI is already in InsertedScalarizedValues, it has
1258 // already been seen first by another load, so its uses have already been
1259 // processed.
1260 PHINode *PN = cast<PHINode>(LoadUser);
1261 bool Inserted;
1262 DenseMap<Value*, std::vector<Value*> >::iterator InsertPos;
1263 tie(InsertPos, Inserted) =
1264 InsertedScalarizedValues.insert(std::make_pair(PN, std::vector<Value*>()));
1265 if (!Inserted) return;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001266
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001267 // If this is the first time we've seen this PHI, recursively process all
1268 // users.
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001269 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end(); UI != E; ) {
1270 Instruction *User = cast<Instruction>(*UI++);
Chris Lattner7b550cc2009-11-06 04:27:31 +00001271 RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite);
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001272 }
Chris Lattner330245e2007-09-13 17:29:05 +00001273}
1274
Chris Lattner86395032006-09-30 23:32:09 +00001275/// RewriteUsesOfLoadForHeapSRoA - We are performing Heap SRoA on a global. Ptr
1276/// is a value loaded from the global. Eliminate all uses of Ptr, making them
1277/// use FieldGlobals instead. All uses of loaded values satisfy
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001278/// AllGlobalLoadUsesSimpleEnoughForHeapSRA.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001279static void RewriteUsesOfLoadForHeapSRoA(LoadInst *Load,
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001280 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001281 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001282 for (Value::use_iterator UI = Load->use_begin(), E = Load->use_end();
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001283 UI != E; ) {
1284 Instruction *User = cast<Instruction>(*UI++);
Chris Lattner7b550cc2009-11-06 04:27:31 +00001285 RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite);
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001286 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001287
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001288 if (Load->use_empty()) {
1289 Load->eraseFromParent();
1290 InsertedScalarizedValues.erase(Load);
1291 }
Chris Lattner86395032006-09-30 23:32:09 +00001292}
1293
Victor Hernandez83d63912009-09-18 22:35:49 +00001294/// PerformHeapAllocSRoA - CI is an allocation of an array of structures. Break
1295/// it up into multiple allocations of arrays of the fields.
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001296static GlobalVariable *PerformHeapAllocSRoA(GlobalVariable *GV, CallInst *CI,
1297 Value* NElems, TargetData *TD) {
David Greene3215b0e2010-01-05 01:28:05 +00001298 DEBUG(dbgs() << "SROA HEAP ALLOC: " << *GV << " MALLOC = " << *CI << '\n');
Victor Hernandez83d63912009-09-18 22:35:49 +00001299 const Type* MAT = getMallocAllocatedType(CI);
1300 const StructType *STy = cast<StructType>(MAT);
1301
1302 // There is guaranteed to be at least one use of the malloc (storing
1303 // it into GV). If there are other uses, change them to be uses of
1304 // the global to simplify later code. This also deletes the store
1305 // into GV.
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001306 ReplaceUsesOfMallocWithGlobal(CI, GV);
1307
Victor Hernandez83d63912009-09-18 22:35:49 +00001308 // Okay, at this point, there are no users of the malloc. Insert N
1309 // new mallocs at the same place as CI, and N globals.
1310 std::vector<Value*> FieldGlobals;
1311 std::vector<Value*> FieldMallocs;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001312
Victor Hernandez83d63912009-09-18 22:35:49 +00001313 for (unsigned FieldNo = 0, e = STy->getNumElements(); FieldNo != e;++FieldNo){
1314 const Type *FieldTy = STy->getElementType(FieldNo);
1315 const PointerType *PFieldTy = PointerType::getUnqual(FieldTy);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001316
Victor Hernandez83d63912009-09-18 22:35:49 +00001317 GlobalVariable *NGV =
1318 new GlobalVariable(*GV->getParent(),
1319 PFieldTy, false, GlobalValue::InternalLinkage,
1320 Constant::getNullValue(PFieldTy),
1321 GV->getName() + ".f" + Twine(FieldNo), GV,
1322 GV->isThreadLocal());
1323 FieldGlobals.push_back(NGV);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001324
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001325 unsigned TypeSize = TD->getTypeAllocSize(FieldTy);
Victor Hernandez631f3c02009-11-07 00:41:19 +00001326 if (const StructType *ST = dyn_cast<StructType>(FieldTy))
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001327 TypeSize = TD->getStructLayout(ST)->getSizeInBytes();
Victor Hernandez631f3c02009-11-07 00:41:19 +00001328 const Type *IntPtrTy = TD->getIntPtrType(CI->getContext());
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001329 Value *NMI = CallInst::CreateMalloc(CI, IntPtrTy, FieldTy,
1330 ConstantInt::get(IntPtrTy, TypeSize),
Chris Lattner5a30a852010-07-12 00:57:28 +00001331 NElems, 0,
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001332 CI->getName() + ".f" + Twine(FieldNo));
Chris Lattner3f5e0b82010-02-26 18:23:13 +00001333 FieldMallocs.push_back(NMI);
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001334 new StoreInst(NMI, NGV, CI);
Victor Hernandez83d63912009-09-18 22:35:49 +00001335 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001336
Victor Hernandez83d63912009-09-18 22:35:49 +00001337 // The tricky aspect of this transformation is handling the case when malloc
1338 // fails. In the original code, malloc failing would set the result pointer
1339 // of malloc to null. In this case, some mallocs could succeed and others
1340 // could fail. As such, we emit code that looks like this:
1341 // F0 = malloc(field0)
1342 // F1 = malloc(field1)
1343 // F2 = malloc(field2)
1344 // if (F0 == 0 || F1 == 0 || F2 == 0) {
1345 // if (F0) { free(F0); F0 = 0; }
1346 // if (F1) { free(F1); F1 = 0; }
1347 // if (F2) { free(F2); F2 = 0; }
1348 // }
Victor Hernandez8e345a12009-11-10 08:32:25 +00001349 // The malloc can also fail if its argument is too large.
Gabor Greif9e4f2432010-06-24 14:42:01 +00001350 Constant *ConstantZero = ConstantInt::get(CI->getArgOperand(0)->getType(), 0);
1351 Value *RunningOr = new ICmpInst(CI, ICmpInst::ICMP_SLT, CI->getArgOperand(0),
Victor Hernandez8e345a12009-11-10 08:32:25 +00001352 ConstantZero, "isneg");
Victor Hernandez83d63912009-09-18 22:35:49 +00001353 for (unsigned i = 0, e = FieldMallocs.size(); i != e; ++i) {
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001354 Value *Cond = new ICmpInst(CI, ICmpInst::ICMP_EQ, FieldMallocs[i],
1355 Constant::getNullValue(FieldMallocs[i]->getType()),
1356 "isnull");
Victor Hernandez8e345a12009-11-10 08:32:25 +00001357 RunningOr = BinaryOperator::CreateOr(RunningOr, Cond, "tmp", CI);
Victor Hernandez83d63912009-09-18 22:35:49 +00001358 }
1359
1360 // Split the basic block at the old malloc.
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001361 BasicBlock *OrigBB = CI->getParent();
1362 BasicBlock *ContBB = OrigBB->splitBasicBlock(CI, "malloc_cont");
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001363
Victor Hernandez83d63912009-09-18 22:35:49 +00001364 // Create the block to check the first condition. Put all these blocks at the
1365 // end of the function as they are unlikely to be executed.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001366 BasicBlock *NullPtrBlock = BasicBlock::Create(OrigBB->getContext(),
1367 "malloc_ret_null",
Victor Hernandez83d63912009-09-18 22:35:49 +00001368 OrigBB->getParent());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001369
Victor Hernandez83d63912009-09-18 22:35:49 +00001370 // Remove the uncond branch from OrigBB to ContBB, turning it into a cond
1371 // branch on RunningOr.
1372 OrigBB->getTerminator()->eraseFromParent();
1373 BranchInst::Create(NullPtrBlock, ContBB, RunningOr, OrigBB);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001374
Victor Hernandez83d63912009-09-18 22:35:49 +00001375 // Within the NullPtrBlock, we need to emit a comparison and branch for each
1376 // pointer, because some may be null while others are not.
1377 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
1378 Value *GVVal = new LoadInst(FieldGlobals[i], "tmp", NullPtrBlock);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001379 Value *Cmp = new ICmpInst(*NullPtrBlock, ICmpInst::ICMP_NE, GVVal,
Victor Hernandez83d63912009-09-18 22:35:49 +00001380 Constant::getNullValue(GVVal->getType()),
1381 "tmp");
Chris Lattner7b550cc2009-11-06 04:27:31 +00001382 BasicBlock *FreeBlock = BasicBlock::Create(Cmp->getContext(), "free_it",
Victor Hernandez83d63912009-09-18 22:35:49 +00001383 OrigBB->getParent());
Chris Lattner7b550cc2009-11-06 04:27:31 +00001384 BasicBlock *NextBlock = BasicBlock::Create(Cmp->getContext(), "next",
Victor Hernandez83d63912009-09-18 22:35:49 +00001385 OrigBB->getParent());
Victor Hernandez66284e02009-10-24 04:23:03 +00001386 Instruction *BI = BranchInst::Create(FreeBlock, NextBlock,
1387 Cmp, NullPtrBlock);
Victor Hernandez83d63912009-09-18 22:35:49 +00001388
1389 // Fill in FreeBlock.
Victor Hernandez66284e02009-10-24 04:23:03 +00001390 CallInst::CreateFree(GVVal, BI);
Victor Hernandez83d63912009-09-18 22:35:49 +00001391 new StoreInst(Constant::getNullValue(GVVal->getType()), FieldGlobals[i],
1392 FreeBlock);
1393 BranchInst::Create(NextBlock, FreeBlock);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001394
Victor Hernandez83d63912009-09-18 22:35:49 +00001395 NullPtrBlock = NextBlock;
1396 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001397
Victor Hernandez83d63912009-09-18 22:35:49 +00001398 BranchInst::Create(ContBB, NullPtrBlock);
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001399
1400 // CI is no longer needed, remove it.
Victor Hernandez83d63912009-09-18 22:35:49 +00001401 CI->eraseFromParent();
1402
1403 /// InsertedScalarizedLoads - As we process loads, if we can't immediately
1404 /// update all uses of the load, keep track of what scalarized loads are
1405 /// inserted for a given load.
1406 DenseMap<Value*, std::vector<Value*> > InsertedScalarizedValues;
1407 InsertedScalarizedValues[GV] = FieldGlobals;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001408
Victor Hernandez83d63912009-09-18 22:35:49 +00001409 std::vector<std::pair<PHINode*, unsigned> > PHIsToRewrite;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001410
Victor Hernandez83d63912009-09-18 22:35:49 +00001411 // Okay, the malloc site is completely handled. All of the uses of GV are now
1412 // loads, and all uses of those loads are simple. Rewrite them to use loads
1413 // of the per-field globals instead.
1414 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI != E;) {
1415 Instruction *User = cast<Instruction>(*UI++);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001416
Victor Hernandez83d63912009-09-18 22:35:49 +00001417 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Chris Lattner7b550cc2009-11-06 04:27:31 +00001418 RewriteUsesOfLoadForHeapSRoA(LI, InsertedScalarizedValues, PHIsToRewrite);
Victor Hernandez83d63912009-09-18 22:35:49 +00001419 continue;
1420 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001421
Victor Hernandez83d63912009-09-18 22:35:49 +00001422 // Must be a store of null.
1423 StoreInst *SI = cast<StoreInst>(User);
1424 assert(isa<ConstantPointerNull>(SI->getOperand(0)) &&
1425 "Unexpected heap-sra user!");
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001426
Victor Hernandez83d63912009-09-18 22:35:49 +00001427 // Insert a store of null into each global.
1428 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
1429 const PointerType *PT = cast<PointerType>(FieldGlobals[i]->getType());
1430 Constant *Null = Constant::getNullValue(PT->getElementType());
1431 new StoreInst(Null, FieldGlobals[i], SI);
1432 }
1433 // Erase the original store.
1434 SI->eraseFromParent();
1435 }
1436
1437 // While we have PHIs that are interesting to rewrite, do it.
1438 while (!PHIsToRewrite.empty()) {
1439 PHINode *PN = PHIsToRewrite.back().first;
1440 unsigned FieldNo = PHIsToRewrite.back().second;
1441 PHIsToRewrite.pop_back();
1442 PHINode *FieldPN = cast<PHINode>(InsertedScalarizedValues[PN][FieldNo]);
1443 assert(FieldPN->getNumIncomingValues() == 0 &&"Already processed this phi");
1444
1445 // Add all the incoming values. This can materialize more phis.
1446 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1447 Value *InVal = PN->getIncomingValue(i);
1448 InVal = GetHeapSROAValue(InVal, FieldNo, InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001449 PHIsToRewrite);
Victor Hernandez83d63912009-09-18 22:35:49 +00001450 FieldPN->addIncoming(InVal, PN->getIncomingBlock(i));
1451 }
1452 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001453
Victor Hernandez83d63912009-09-18 22:35:49 +00001454 // Drop all inter-phi links and any loads that made it this far.
1455 for (DenseMap<Value*, std::vector<Value*> >::iterator
1456 I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
1457 I != E; ++I) {
1458 if (PHINode *PN = dyn_cast<PHINode>(I->first))
1459 PN->dropAllReferences();
1460 else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
1461 LI->dropAllReferences();
1462 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001463
Victor Hernandez83d63912009-09-18 22:35:49 +00001464 // Delete all the phis and loads now that inter-references are dead.
1465 for (DenseMap<Value*, std::vector<Value*> >::iterator
1466 I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
1467 I != E; ++I) {
1468 if (PHINode *PN = dyn_cast<PHINode>(I->first))
1469 PN->eraseFromParent();
1470 else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
1471 LI->eraseFromParent();
1472 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001473
Victor Hernandez83d63912009-09-18 22:35:49 +00001474 // The old global is now dead, remove it.
1475 GV->eraseFromParent();
1476
1477 ++NumHeapSRA;
1478 return cast<GlobalVariable>(FieldGlobals[0]);
1479}
1480
Chris Lattnere61d0a62008-12-15 21:02:25 +00001481/// TryToOptimizeStoreOfMallocToGlobal - This function is called when we see a
1482/// pointer global variable with a single value stored it that is a malloc or
1483/// cast of malloc.
1484static bool TryToOptimizeStoreOfMallocToGlobal(GlobalVariable *GV,
Victor Hernandez83d63912009-09-18 22:35:49 +00001485 CallInst *CI,
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001486 const Type *AllocTy,
Victor Hernandez83d63912009-09-18 22:35:49 +00001487 Module::global_iterator &GVI,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001488 TargetData *TD) {
Evan Cheng86cd4452010-04-14 20:52:55 +00001489 if (!TD)
1490 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001491
Victor Hernandez83d63912009-09-18 22:35:49 +00001492 // If this is a malloc of an abstract type, don't touch it.
1493 if (!AllocTy->isSized())
1494 return false;
1495
1496 // We can't optimize this global unless all uses of it are *known* to be
1497 // of the malloc value, not of the null initializer value (consider a use
1498 // that compares the global's value against zero to see if the malloc has
1499 // been reached). To do this, we check to see if all uses of the global
1500 // would trap if the global were null: this proves that they must all
1501 // happen after the malloc.
1502 if (!AllUsesOfLoadedValueWillTrapIfNull(GV))
1503 return false;
1504
1505 // We can't optimize this if the malloc itself is used in a complex way,
1506 // for example, being stored into multiple globals. This allows the
1507 // malloc to be stored into the specified global, loaded setcc'd, and
1508 // GEP'd. These are all things we could transform to using the global
1509 // for.
Evan Cheng86cd4452010-04-14 20:52:55 +00001510 SmallPtrSet<const PHINode*, 8> PHIs;
1511 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(CI, GV, PHIs))
1512 return false;
Victor Hernandez83d63912009-09-18 22:35:49 +00001513
1514 // If we have a global that is only initialized with a fixed size malloc,
1515 // transform the program to use global memory instead of malloc'd memory.
1516 // This eliminates dynamic allocation, avoids an indirection accessing the
1517 // data, and exposes the resultant global to further GlobalOpt.
Victor Hernandez8db42d22009-10-16 23:12:25 +00001518 // We cannot optimize the malloc if we cannot determine malloc array size.
Evan Cheng86cd4452010-04-14 20:52:55 +00001519 Value *NElems = getMallocArraySize(CI, TD, true);
1520 if (!NElems)
1521 return false;
Victor Hernandez83d63912009-09-18 22:35:49 +00001522
Evan Cheng86cd4452010-04-14 20:52:55 +00001523 if (ConstantInt *NElements = dyn_cast<ConstantInt>(NElems))
1524 // Restrict this transformation to only working on small allocations
1525 // (2048 bytes currently), as we don't want to introduce a 16M global or
1526 // something.
1527 if (NElements->getZExtValue() * TD->getTypeAllocSize(AllocTy) < 2048) {
1528 GVI = OptimizeGlobalAddressOfMalloc(GV, CI, AllocTy, NElements, TD);
1529 return true;
Victor Hernandez83d63912009-09-18 22:35:49 +00001530 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001531
Evan Cheng86cd4452010-04-14 20:52:55 +00001532 // If the allocation is an array of structures, consider transforming this
1533 // into multiple malloc'd arrays, one for each field. This is basically
1534 // SRoA for malloc'd memory.
1535
1536 // If this is an allocation of a fixed size array of structs, analyze as a
1537 // variable size array. malloc [100 x struct],1 -> malloc struct, 100
Gabor Greif9e4f2432010-06-24 14:42:01 +00001538 if (NElems == ConstantInt::get(CI->getArgOperand(0)->getType(), 1))
Evan Cheng86cd4452010-04-14 20:52:55 +00001539 if (const ArrayType *AT = dyn_cast<ArrayType>(AllocTy))
1540 AllocTy = AT->getElementType();
Gabor Greif9e4f2432010-06-24 14:42:01 +00001541
Evan Cheng86cd4452010-04-14 20:52:55 +00001542 const StructType *AllocSTy = dyn_cast<StructType>(AllocTy);
1543 if (!AllocSTy)
1544 return false;
1545
1546 // This the structure has an unreasonable number of fields, leave it
1547 // alone.
1548 if (AllocSTy->getNumElements() <= 16 && AllocSTy->getNumElements() != 0 &&
1549 AllGlobalLoadUsesSimpleEnoughForHeapSRA(GV, CI)) {
1550
1551 // If this is a fixed size array, transform the Malloc to be an alloc of
1552 // structs. malloc [100 x struct],1 -> malloc struct, 100
1553 if (const ArrayType *AT = dyn_cast<ArrayType>(getMallocAllocatedType(CI))) {
1554 const Type *IntPtrTy = TD->getIntPtrType(CI->getContext());
1555 unsigned TypeSize = TD->getStructLayout(AllocSTy)->getSizeInBytes();
1556 Value *AllocSize = ConstantInt::get(IntPtrTy, TypeSize);
1557 Value *NumElements = ConstantInt::get(IntPtrTy, AT->getNumElements());
1558 Instruction *Malloc = CallInst::CreateMalloc(CI, IntPtrTy, AllocSTy,
1559 AllocSize, NumElements,
Chris Lattner5a30a852010-07-12 00:57:28 +00001560 0, CI->getName());
Evan Cheng86cd4452010-04-14 20:52:55 +00001561 Instruction *Cast = new BitCastInst(Malloc, CI->getType(), "tmp", CI);
1562 CI->replaceAllUsesWith(Cast);
1563 CI->eraseFromParent();
1564 CI = dyn_cast<BitCastInst>(Malloc) ?
1565 extractMallocCallFromBitCast(Malloc) : cast<CallInst>(Malloc);
1566 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001567
Evan Cheng86cd4452010-04-14 20:52:55 +00001568 GVI = PerformHeapAllocSRoA(GV, CI, getMallocArraySize(CI, TD, true),TD);
1569 return true;
Victor Hernandez83d63912009-09-18 22:35:49 +00001570 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001571
Victor Hernandez83d63912009-09-18 22:35:49 +00001572 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001573}
Victor Hernandez83d63912009-09-18 22:35:49 +00001574
Chris Lattner9b34a612004-10-09 21:48:45 +00001575// OptimizeOnceStoredGlobal - Try to optimize globals based on the knowledge
1576// that only one value (besides its initializer) is ever stored to the global.
Chris Lattner30ba5692004-10-11 05:54:41 +00001577static bool OptimizeOnceStoredGlobal(GlobalVariable *GV, Value *StoredOnceVal,
Chris Lattner7f8897f2006-08-27 22:42:52 +00001578 Module::global_iterator &GVI,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001579 TargetData *TD) {
Chris Lattner344b41c2008-12-15 21:20:32 +00001580 // Ignore no-op GEPs and bitcasts.
1581 StoredOnceVal = StoredOnceVal->stripPointerCasts();
Chris Lattner9b34a612004-10-09 21:48:45 +00001582
Chris Lattner708148e2004-10-10 23:14:11 +00001583 // If we are dealing with a pointer global that is initialized to null and
1584 // only has one (non-null) value stored into it, then we can optimize any
1585 // users of the loaded value (often calls and loads) that would trap if the
1586 // value was null.
Duncan Sands1df98592010-02-16 11:11:14 +00001587 if (GV->getInitializer()->getType()->isPointerTy() &&
Chris Lattner9b34a612004-10-09 21:48:45 +00001588 GV->getInitializer()->isNullValue()) {
Chris Lattner708148e2004-10-10 23:14:11 +00001589 if (Constant *SOVC = dyn_cast<Constant>(StoredOnceVal)) {
1590 if (GV->getInitializer()->getType() != SOVC->getType())
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001591 SOVC =
Owen Andersonbaf3c402009-07-29 18:55:55 +00001592 ConstantExpr::getBitCast(SOVC, GV->getInitializer()->getType());
Misha Brukmanfd939082005-04-21 23:48:37 +00001593
Chris Lattner708148e2004-10-10 23:14:11 +00001594 // Optimize away any trapping uses of the loaded value.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001595 if (OptimizeAwayTrappingUsesOfLoads(GV, SOVC))
Chris Lattner8be80122004-10-10 17:07:12 +00001596 return true;
Victor Hernandez83d63912009-09-18 22:35:49 +00001597 } else if (CallInst *CI = extractMallocCall(StoredOnceVal)) {
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001598 const Type* MallocType = getMallocAllocatedType(CI);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001599 if (MallocType && TryToOptimizeStoreOfMallocToGlobal(GV, CI, MallocType,
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001600 GVI, TD))
1601 return true;
Chris Lattner708148e2004-10-10 23:14:11 +00001602 }
Chris Lattner9b34a612004-10-09 21:48:45 +00001603 }
Chris Lattner30ba5692004-10-11 05:54:41 +00001604
Chris Lattner9b34a612004-10-09 21:48:45 +00001605 return false;
1606}
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001607
Chris Lattner58e44f42008-01-14 01:17:44 +00001608/// TryToShrinkGlobalToBoolean - At this point, we have learned that the only
1609/// two values ever stored into GV are its initializer and OtherVal. See if we
1610/// can shrink the global into a boolean and select between the two values
1611/// whenever it is used. This exposes the values to other scalar optimizations.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001612static bool TryToShrinkGlobalToBoolean(GlobalVariable *GV, Constant *OtherVal) {
Chris Lattner58e44f42008-01-14 01:17:44 +00001613 const Type *GVElType = GV->getType()->getElementType();
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001614
Chris Lattner58e44f42008-01-14 01:17:44 +00001615 // If GVElType is already i1, it is already shrunk. If the type of the GV is
Chris Lattner6f6923f2009-03-07 23:32:02 +00001616 // an FP value, pointer or vector, don't do this optimization because a select
1617 // between them is very expensive and unlikely to lead to later
1618 // simplification. In these cases, we typically end up with "cond ? v1 : v2"
1619 // where v1 and v2 both require constant pool loads, a big loss.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001620 if (GVElType == Type::getInt1Ty(GV->getContext()) ||
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001621 GVElType->isFloatingPointTy() ||
Duncan Sands1df98592010-02-16 11:11:14 +00001622 GVElType->isPointerTy() || GVElType->isVectorTy())
Chris Lattner58e44f42008-01-14 01:17:44 +00001623 return false;
Gabor Greifaaaaa022010-07-12 14:13:15 +00001624
Chris Lattner58e44f42008-01-14 01:17:44 +00001625 // Walk the use list of the global seeing if all the uses are load or store.
1626 // If there is anything else, bail out.
Gabor Greifaaaaa022010-07-12 14:13:15 +00001627 for (Value::use_iterator I = GV->use_begin(), E = GV->use_end(); I != E; ++I){
1628 User *U = *I;
1629 if (!isa<LoadInst>(U) && !isa<StoreInst>(U))
Chris Lattner58e44f42008-01-14 01:17:44 +00001630 return false;
Gabor Greifaaaaa022010-07-12 14:13:15 +00001631 }
1632
David Greene3215b0e2010-01-05 01:28:05 +00001633 DEBUG(dbgs() << " *** SHRINKING TO BOOL: " << *GV);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001634
Chris Lattner96a86b22004-12-12 05:53:50 +00001635 // Create the new global, initializing it to false.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001636 GlobalVariable *NewGV = new GlobalVariable(Type::getInt1Ty(GV->getContext()),
1637 false,
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001638 GlobalValue::InternalLinkage,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001639 ConstantInt::getFalse(GV->getContext()),
Nick Lewycky0e670df2009-05-03 03:49:08 +00001640 GV->getName()+".b",
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +00001641 GV->isThreadLocal());
Chris Lattner96a86b22004-12-12 05:53:50 +00001642 GV->getParent()->getGlobalList().insert(GV, NewGV);
1643
1644 Constant *InitVal = GV->getInitializer();
Chris Lattner7b550cc2009-11-06 04:27:31 +00001645 assert(InitVal->getType() != Type::getInt1Ty(GV->getContext()) &&
Owen Anderson1d0be152009-08-13 21:58:54 +00001646 "No reason to shrink to bool!");
Chris Lattner96a86b22004-12-12 05:53:50 +00001647
1648 // If initialized to zero and storing one into the global, we can use a cast
1649 // instead of a select to synthesize the desired value.
1650 bool IsOneZero = false;
1651 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal))
Reid Spencercae57542007-03-02 00:28:52 +00001652 IsOneZero = InitVal->isNullValue() && CI->isOne();
Chris Lattner96a86b22004-12-12 05:53:50 +00001653
1654 while (!GV->use_empty()) {
Devang Patel771281f2009-03-06 01:39:36 +00001655 Instruction *UI = cast<Instruction>(GV->use_back());
1656 if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
Chris Lattner96a86b22004-12-12 05:53:50 +00001657 // Change the store into a boolean store.
1658 bool StoringOther = SI->getOperand(0) == OtherVal;
1659 // Only do this if we weren't storing a loaded value.
Chris Lattner38c25562004-12-12 19:34:41 +00001660 Value *StoreVal;
Chris Lattner96a86b22004-12-12 05:53:50 +00001661 if (StoringOther || SI->getOperand(0) == InitVal)
Chris Lattner7b550cc2009-11-06 04:27:31 +00001662 StoreVal = ConstantInt::get(Type::getInt1Ty(GV->getContext()),
1663 StoringOther);
Chris Lattner38c25562004-12-12 19:34:41 +00001664 else {
1665 // Otherwise, we are storing a previously loaded copy. To do this,
1666 // change the copy from copying the original value to just copying the
1667 // bool.
1668 Instruction *StoredVal = cast<Instruction>(SI->getOperand(0));
1669
Gabor Greif9e4f2432010-06-24 14:42:01 +00001670 // If we've already replaced the input, StoredVal will be a cast or
Chris Lattner38c25562004-12-12 19:34:41 +00001671 // select instruction. If not, it will be a load of the original
1672 // global.
1673 if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
1674 assert(LI->getOperand(0) == GV && "Not a copy!");
1675 // Insert a new load, to preserve the saved value.
1676 StoreVal = new LoadInst(NewGV, LI->getName()+".b", LI);
1677 } else {
1678 assert((isa<CastInst>(StoredVal) || isa<SelectInst>(StoredVal)) &&
1679 "This is not a form that we understand!");
1680 StoreVal = StoredVal->getOperand(0);
1681 assert(isa<LoadInst>(StoreVal) && "Not a load of NewGV!");
1682 }
1683 }
1684 new StoreInst(StoreVal, NewGV, SI);
Devang Patel771281f2009-03-06 01:39:36 +00001685 } else {
Chris Lattner96a86b22004-12-12 05:53:50 +00001686 // Change the load into a load of bool then a select.
Devang Patel771281f2009-03-06 01:39:36 +00001687 LoadInst *LI = cast<LoadInst>(UI);
Chris Lattner046800a2007-02-11 01:08:35 +00001688 LoadInst *NLI = new LoadInst(NewGV, LI->getName()+".b", LI);
Chris Lattner96a86b22004-12-12 05:53:50 +00001689 Value *NSI;
1690 if (IsOneZero)
Chris Lattner046800a2007-02-11 01:08:35 +00001691 NSI = new ZExtInst(NLI, LI->getType(), "", LI);
Misha Brukmanfd939082005-04-21 23:48:37 +00001692 else
Gabor Greif051a9502008-04-06 20:25:17 +00001693 NSI = SelectInst::Create(NLI, OtherVal, InitVal, "", LI);
Chris Lattner046800a2007-02-11 01:08:35 +00001694 NSI->takeName(LI);
Chris Lattner96a86b22004-12-12 05:53:50 +00001695 LI->replaceAllUsesWith(NSI);
Devang Patel771281f2009-03-06 01:39:36 +00001696 }
1697 UI->eraseFromParent();
Chris Lattner96a86b22004-12-12 05:53:50 +00001698 }
1699
1700 GV->eraseFromParent();
Chris Lattner58e44f42008-01-14 01:17:44 +00001701 return true;
Chris Lattner96a86b22004-12-12 05:53:50 +00001702}
1703
1704
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001705/// ProcessInternalGlobal - Analyze the specified global variable and optimize
1706/// it if possible. If we make a change, return true.
Rafael Espindolac4440e32011-01-19 16:32:21 +00001707bool GlobalOpt::ProcessGlobal(GlobalVariable *GV,
1708 Module::global_iterator &GVI) {
1709 if (!GV->hasLocalLinkage())
1710 return false;
1711
1712 // Do more involved optimizations if the global is internal.
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001713 GV->removeDeadConstantUsers();
1714
1715 if (GV->use_empty()) {
David Greene3215b0e2010-01-05 01:28:05 +00001716 DEBUG(dbgs() << "GLOBAL DEAD: " << *GV);
Chris Lattner7a7ed022004-10-16 18:09:00 +00001717 GV->eraseFromParent();
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001718 ++NumDeleted;
1719 return true;
1720 }
1721
Rafael Espindolac4440e32011-01-19 16:32:21 +00001722 SmallPtrSet<const PHINode*, 16> PHIUsers;
1723 GlobalStatus GS;
1724
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001725 if (AnalyzeGlobal(GV, GS, PHIUsers))
1726 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001727
Rafael Espindolac4440e32011-01-19 16:32:21 +00001728 if (!GS.isCompared && !GV->hasUnnamedAddr()) {
1729 GV->setUnnamedAddr(true);
1730 NumUnnamed++;
1731 }
1732
1733 if (GV->isConstant() || !GV->hasInitializer())
1734 return false;
1735
1736 return ProcessInternalGlobal(GV, GVI, PHIUsers, GS);
1737}
1738
1739/// ProcessInternalGlobal - Analyze the specified global variable and optimize
1740/// it if possible. If we make a change, return true.
1741bool GlobalOpt::ProcessInternalGlobal(GlobalVariable *GV,
1742 Module::global_iterator &GVI,
1743 const SmallPtrSet<const PHINode*, 16> &PHIUsers,
1744 const GlobalStatus &GS) {
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001745 // If this is a first class global and has only one accessing function
1746 // and this function is main (which we know is not recursive we can make
1747 // this global a local variable) we replace the global with a local alloca
1748 // in this function.
1749 //
1750 // NOTE: It doesn't make sense to promote non single-value types since we
1751 // are just replacing static memory to stack memory.
1752 //
1753 // If the global is in different address space, don't bring it to stack.
1754 if (!GS.HasMultipleAccessingFunctions &&
1755 GS.AccessingFunction && !GS.HasNonInstructionUser &&
1756 GV->getType()->getElementType()->isSingleValueType() &&
1757 GS.AccessingFunction->getName() == "main" &&
1758 GS.AccessingFunction->hasExternalLinkage() &&
1759 GV->getType()->getAddressSpace() == 0) {
1760 DEBUG(dbgs() << "LOCALIZING GLOBAL: " << *GV);
1761 Instruction& FirstI = const_cast<Instruction&>(*GS.AccessingFunction
1762 ->getEntryBlock().begin());
1763 const Type* ElemTy = GV->getType()->getElementType();
1764 // FIXME: Pass Global's alignment when globals have alignment
1765 AllocaInst* Alloca = new AllocaInst(ElemTy, NULL, GV->getName(), &FirstI);
1766 if (!isa<UndefValue>(GV->getInitializer()))
1767 new StoreInst(GV->getInitializer(), Alloca, &FirstI);
Misha Brukmanfd939082005-04-21 23:48:37 +00001768
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001769 GV->replaceAllUsesWith(Alloca);
1770 GV->eraseFromParent();
1771 ++NumLocalized;
1772 return true;
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001773 }
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001774
1775 // If the global is never loaded (but may be stored to), it is dead.
1776 // Delete it now.
1777 if (!GS.isLoaded) {
1778 DEBUG(dbgs() << "GLOBAL NEVER LOADED: " << *GV);
1779
1780 // Delete any stores we can find to the global. We may not be able to
1781 // make it completely dead though.
1782 bool Changed = CleanupConstantGlobalUsers(GV, GV->getInitializer());
1783
1784 // If the global is dead now, delete it.
1785 if (GV->use_empty()) {
1786 GV->eraseFromParent();
1787 ++NumDeleted;
1788 Changed = true;
1789 }
1790 return Changed;
1791
1792 } else if (GS.StoredType <= GlobalStatus::isInitializerStored) {
1793 DEBUG(dbgs() << "MARKING CONSTANT: " << *GV);
1794 GV->setConstant(true);
1795
1796 // Clean up any obviously simplifiable users now.
1797 CleanupConstantGlobalUsers(GV, GV->getInitializer());
1798
1799 // If the global is dead now, just nuke it.
1800 if (GV->use_empty()) {
1801 DEBUG(dbgs() << " *** Marking constant allowed us to simplify "
1802 << "all users and delete global!\n");
1803 GV->eraseFromParent();
1804 ++NumDeleted;
1805 }
1806
1807 ++NumMarked;
1808 return true;
1809 } else if (!GV->getInitializer()->getType()->isSingleValueType()) {
1810 if (TargetData *TD = getAnalysisIfAvailable<TargetData>())
1811 if (GlobalVariable *FirstNewGV = SRAGlobal(GV, *TD)) {
1812 GVI = FirstNewGV; // Don't skip the newly produced globals!
1813 return true;
1814 }
1815 } else if (GS.StoredType == GlobalStatus::isStoredOnce) {
1816 // If the initial value for the global was an undef value, and if only
1817 // one other value was stored into it, we can just change the
1818 // initializer to be the stored value, then delete all stores to the
1819 // global. This allows us to mark it constant.
1820 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
1821 if (isa<UndefValue>(GV->getInitializer())) {
1822 // Change the initial value here.
1823 GV->setInitializer(SOVConstant);
1824
1825 // Clean up any obviously simplifiable users now.
1826 CleanupConstantGlobalUsers(GV, GV->getInitializer());
1827
1828 if (GV->use_empty()) {
1829 DEBUG(dbgs() << " *** Substituting initializer allowed us to "
1830 << "simplify all users and delete global!\n");
1831 GV->eraseFromParent();
1832 ++NumDeleted;
1833 } else {
1834 GVI = GV;
1835 }
1836 ++NumSubstitute;
1837 return true;
1838 }
1839
1840 // Try to optimize globals based on the knowledge that only one value
1841 // (besides its initializer) is ever stored to the global.
1842 if (OptimizeOnceStoredGlobal(GV, GS.StoredOnceValue, GVI,
1843 getAnalysisIfAvailable<TargetData>()))
1844 return true;
1845
1846 // Otherwise, if the global was not a boolean, we can shrink it to be a
1847 // boolean.
1848 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
1849 if (TryToShrinkGlobalToBoolean(GV, SOVConstant)) {
1850 ++NumShrunkToBool;
1851 return true;
1852 }
1853 }
1854
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001855 return false;
1856}
1857
Chris Lattnerfb217ad2005-05-08 22:18:06 +00001858/// ChangeCalleesToFastCall - Walk all of the direct calls of the specified
1859/// function, changing them to FastCC.
1860static void ChangeCalleesToFastCall(Function *F) {
1861 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
Duncan Sands548448a2008-02-18 17:32:13 +00001862 CallSite User(cast<Instruction>(*UI));
1863 User.setCallingConv(CallingConv::Fast);
Chris Lattnerfb217ad2005-05-08 22:18:06 +00001864 }
1865}
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001866
Devang Patel05988662008-09-25 21:00:45 +00001867static AttrListPtr StripNest(const AttrListPtr &Attrs) {
Chris Lattner58d74912008-03-12 17:45:29 +00001868 for (unsigned i = 0, e = Attrs.getNumSlots(); i != e; ++i) {
Devang Patel05988662008-09-25 21:00:45 +00001869 if ((Attrs.getSlot(i).Attrs & Attribute::Nest) == 0)
Duncan Sands548448a2008-02-18 17:32:13 +00001870 continue;
1871
Duncan Sands548448a2008-02-18 17:32:13 +00001872 // There can be only one.
Devang Patel05988662008-09-25 21:00:45 +00001873 return Attrs.removeAttr(Attrs.getSlot(i).Index, Attribute::Nest);
Duncan Sands3d5378f2008-02-16 20:56:04 +00001874 }
1875
1876 return Attrs;
1877}
1878
1879static void RemoveNestAttribute(Function *F) {
Devang Patel05988662008-09-25 21:00:45 +00001880 F->setAttributes(StripNest(F->getAttributes()));
Duncan Sands3d5378f2008-02-16 20:56:04 +00001881 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
Duncan Sands548448a2008-02-18 17:32:13 +00001882 CallSite User(cast<Instruction>(*UI));
Devang Patel05988662008-09-25 21:00:45 +00001883 User.setAttributes(StripNest(User.getAttributes()));
Duncan Sands3d5378f2008-02-16 20:56:04 +00001884 }
1885}
1886
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001887bool GlobalOpt::OptimizeFunctions(Module &M) {
1888 bool Changed = false;
1889 // Optimize functions.
1890 for (Module::iterator FI = M.begin(), E = M.end(); FI != E; ) {
1891 Function *F = FI++;
Duncan Sandsfc5940d2009-03-06 10:21:56 +00001892 // Functions without names cannot be referenced outside this module.
1893 if (!F->hasName() && !F->isDeclaration())
1894 F->setLinkage(GlobalValue::InternalLinkage);
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001895 F->removeDeadConstantUsers();
Chris Lattnerec4c7b92009-11-01 19:03:42 +00001896 if (F->use_empty() && (F->hasLocalLinkage() || F->hasLinkOnceLinkage())) {
1897 F->eraseFromParent();
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001898 Changed = true;
1899 ++NumFnDeleted;
Rafael Espindolabb46f522009-01-15 20:18:42 +00001900 } else if (F->hasLocalLinkage()) {
Duncan Sands3d5378f2008-02-16 20:56:04 +00001901 if (F->getCallingConv() == CallingConv::C && !F->isVarArg() &&
Jay Foad757068f2009-06-10 08:41:11 +00001902 !F->hasAddressTaken()) {
Duncan Sands3d5378f2008-02-16 20:56:04 +00001903 // If this function has C calling conventions, is not a varargs
1904 // function, and is only called directly, promote it to use the Fast
1905 // calling convention.
1906 F->setCallingConv(CallingConv::Fast);
1907 ChangeCalleesToFastCall(F);
1908 ++NumFastCallFns;
1909 Changed = true;
1910 }
1911
Devang Patel05988662008-09-25 21:00:45 +00001912 if (F->getAttributes().hasAttrSomewhere(Attribute::Nest) &&
Jay Foad757068f2009-06-10 08:41:11 +00001913 !F->hasAddressTaken()) {
Duncan Sands3d5378f2008-02-16 20:56:04 +00001914 // The function is not used by a trampoline intrinsic, so it is safe
1915 // to remove the 'nest' attribute.
1916 RemoveNestAttribute(F);
1917 ++NumNestRemoved;
1918 Changed = true;
1919 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001920 }
1921 }
1922 return Changed;
1923}
1924
1925bool GlobalOpt::OptimizeGlobalVars(Module &M) {
1926 bool Changed = false;
1927 for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
1928 GVI != E; ) {
1929 GlobalVariable *GV = GVI++;
Duncan Sandsfc5940d2009-03-06 10:21:56 +00001930 // Global variables without names cannot be referenced outside this module.
1931 if (!GV->hasName() && !GV->isDeclaration())
1932 GV->setLinkage(GlobalValue::InternalLinkage);
Dan Gohman01b97dd2009-11-23 16:22:21 +00001933 // Simplify the initializer.
1934 if (GV->hasInitializer())
1935 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GV->getInitializer())) {
Dan Gohmanf860db22010-04-02 03:04:37 +00001936 TargetData *TD = getAnalysisIfAvailable<TargetData>();
Dan Gohman01b97dd2009-11-23 16:22:21 +00001937 Constant *New = ConstantFoldConstantExpression(CE, TD);
1938 if (New && New != CE)
1939 GV->setInitializer(New);
1940 }
Rafael Espindolac4440e32011-01-19 16:32:21 +00001941
1942 Changed |= ProcessGlobal(GV, GVI);
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001943 }
1944 return Changed;
1945}
1946
Nick Lewycky2c44a802011-04-08 07:30:21 +00001947/// FindGlobalCtors - Find the llvm.global_ctors list, verifying that all
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001948/// initializers have an init priority of 65535.
1949GlobalVariable *GlobalOpt::FindGlobalCtors(Module &M) {
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00001950 GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
1951 if (GV == 0) return 0;
1952
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00001953 // Verify that the initializer is simple enough for us to handle. We are
1954 // only allowed to optimize the initializer if it is unique.
1955 if (!GV->hasUniqueInitializer()) return 0;
1956
Eli Friedman18a2e502011-04-09 09:11:09 +00001957 ConstantArray *CA = dyn_cast<ConstantArray>(GV->getInitializer());
1958 if (!CA) return 0;
1959
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00001960 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i) {
Eli Friedman18a2e502011-04-09 09:11:09 +00001961 ConstantStruct *CS = dyn_cast<ConstantStruct>(*i);
1962 if (!CS) return 0;
1963
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00001964 if (isa<ConstantPointerNull>(CS->getOperand(1)))
1965 continue;
Chris Lattner7d8e58f2005-09-26 02:19:27 +00001966
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00001967 // Must have a function or null ptr.
1968 if (!isa<Function>(CS->getOperand(1)))
1969 return 0;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001970
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00001971 // Init priority must be standard.
Nick Lewycky2c44a802011-04-08 07:30:21 +00001972 ConstantInt *CI = cast<ConstantInt>(CS->getOperand(0));
1973 if (CI->getZExtValue() != 65535)
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00001974 return 0;
1975 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001976
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00001977 return GV;
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001978}
1979
Chris Lattnerdb973e62005-09-26 02:31:18 +00001980/// ParseGlobalCtors - Given a llvm.global_ctors list that we can understand,
1981/// return a list of the functions and null terminator as a vector.
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001982static std::vector<Function*> ParseGlobalCtors(GlobalVariable *GV) {
1983 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
1984 std::vector<Function*> Result;
1985 Result.reserve(CA->getNumOperands());
Gabor Greif5e463212008-05-29 01:59:18 +00001986 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i) {
1987 ConstantStruct *CS = cast<ConstantStruct>(*i);
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001988 Result.push_back(dyn_cast<Function>(CS->getOperand(1)));
1989 }
1990 return Result;
1991}
1992
Chris Lattnerdb973e62005-09-26 02:31:18 +00001993/// InstallGlobalCtors - Given a specified llvm.global_ctors list, install the
1994/// specified array, returning the new global to use.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001995static GlobalVariable *InstallGlobalCtors(GlobalVariable *GCL,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001996 const std::vector<Function*> &Ctors) {
Chris Lattnerdb973e62005-09-26 02:31:18 +00001997 // If we made a change, reassemble the initializer list.
1998 std::vector<Constant*> CSVals;
Chris Lattner7b550cc2009-11-06 04:27:31 +00001999 CSVals.push_back(ConstantInt::get(Type::getInt32Ty(GCL->getContext()),65535));
Chris Lattnerdb973e62005-09-26 02:31:18 +00002000 CSVals.push_back(0);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002001
Chris Lattnerdb973e62005-09-26 02:31:18 +00002002 // Create the new init list.
2003 std::vector<Constant*> CAList;
2004 for (unsigned i = 0, e = Ctors.size(); i != e; ++i) {
Chris Lattner79c11012005-09-26 04:44:35 +00002005 if (Ctors[i]) {
Chris Lattnerdb973e62005-09-26 02:31:18 +00002006 CSVals[1] = Ctors[i];
Chris Lattner79c11012005-09-26 04:44:35 +00002007 } else {
Chris Lattner7b550cc2009-11-06 04:27:31 +00002008 const Type *FTy = FunctionType::get(Type::getVoidTy(GCL->getContext()),
2009 false);
Owen Andersondebcb012009-07-29 22:17:13 +00002010 const PointerType *PFTy = PointerType::getUnqual(FTy);
Owen Andersona7235ea2009-07-31 20:28:14 +00002011 CSVals[1] = Constant::getNullValue(PFTy);
Chris Lattner7b550cc2009-11-06 04:27:31 +00002012 CSVals[0] = ConstantInt::get(Type::getInt32Ty(GCL->getContext()),
2013 2147483647);
Chris Lattnerdb973e62005-09-26 02:31:18 +00002014 }
Chris Lattner7b550cc2009-11-06 04:27:31 +00002015 CAList.push_back(ConstantStruct::get(GCL->getContext(), CSVals, false));
Chris Lattnerdb973e62005-09-26 02:31:18 +00002016 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002017
Chris Lattnerdb973e62005-09-26 02:31:18 +00002018 // Create the array initializer.
2019 const Type *StructTy =
Nick Lewyckyc332fba2009-09-19 20:30:26 +00002020 cast<ArrayType>(GCL->getType()->getElementType())->getElementType();
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002021 Constant *CA = ConstantArray::get(ArrayType::get(StructTy,
Nick Lewyckyc332fba2009-09-19 20:30:26 +00002022 CAList.size()), CAList);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002023
Chris Lattnerdb973e62005-09-26 02:31:18 +00002024 // If we didn't change the number of elements, don't create a new GV.
2025 if (CA->getType() == GCL->getInitializer()->getType()) {
2026 GCL->setInitializer(CA);
2027 return GCL;
2028 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002029
Chris Lattnerdb973e62005-09-26 02:31:18 +00002030 // Create the new global and insert it next to the existing list.
Chris Lattner7b550cc2009-11-06 04:27:31 +00002031 GlobalVariable *NGV = new GlobalVariable(CA->getType(), GCL->isConstant(),
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +00002032 GCL->getLinkage(), CA, "",
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +00002033 GCL->isThreadLocal());
Chris Lattnerdb973e62005-09-26 02:31:18 +00002034 GCL->getParent()->getGlobalList().insert(GCL, NGV);
Chris Lattner046800a2007-02-11 01:08:35 +00002035 NGV->takeName(GCL);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002036
Chris Lattnerdb973e62005-09-26 02:31:18 +00002037 // Nuke the old list, replacing any uses with the new one.
2038 if (!GCL->use_empty()) {
2039 Constant *V = NGV;
2040 if (V->getType() != GCL->getType())
Owen Andersonbaf3c402009-07-29 18:55:55 +00002041 V = ConstantExpr::getBitCast(V, GCL->getType());
Chris Lattnerdb973e62005-09-26 02:31:18 +00002042 GCL->replaceAllUsesWith(V);
2043 }
2044 GCL->eraseFromParent();
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002045
Chris Lattnerdb973e62005-09-26 02:31:18 +00002046 if (Ctors.size())
2047 return NGV;
2048 else
2049 return 0;
2050}
Chris Lattner79c11012005-09-26 04:44:35 +00002051
2052
Chris Lattner1945d582010-12-07 04:33:29 +00002053static Constant *getVal(DenseMap<Value*, Constant*> &ComputedValues, Value *V) {
Chris Lattner79c11012005-09-26 04:44:35 +00002054 if (Constant *CV = dyn_cast<Constant>(V)) return CV;
2055 Constant *R = ComputedValues[V];
2056 assert(R && "Reference to an uncomputed value!");
2057 return R;
2058}
2059
Chris Lattner1945d582010-12-07 04:33:29 +00002060static inline bool
2061isSimpleEnoughValueToCommit(Constant *C,
2062 SmallPtrSet<Constant*, 8> &SimpleConstants);
2063
2064
2065/// isSimpleEnoughValueToCommit - Return true if the specified constant can be
2066/// handled by the code generator. We don't want to generate something like:
2067/// void *X = &X/42;
2068/// because the code generator doesn't have a relocation that can handle that.
2069///
2070/// This function should be called if C was not found (but just got inserted)
2071/// in SimpleConstants to avoid having to rescan the same constants all the
2072/// time.
2073static bool isSimpleEnoughValueToCommitHelper(Constant *C,
2074 SmallPtrSet<Constant*, 8> &SimpleConstants) {
2075 // Simple integer, undef, constant aggregate zero, global addresses, etc are
2076 // all supported.
2077 if (C->getNumOperands() == 0 || isa<BlockAddress>(C) ||
2078 isa<GlobalValue>(C))
2079 return true;
2080
2081 // Aggregate values are safe if all their elements are.
2082 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C) ||
2083 isa<ConstantVector>(C)) {
2084 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i) {
2085 Constant *Op = cast<Constant>(C->getOperand(i));
2086 if (!isSimpleEnoughValueToCommit(Op, SimpleConstants))
2087 return false;
2088 }
2089 return true;
2090 }
2091
2092 // We don't know exactly what relocations are allowed in constant expressions,
2093 // so we allow &global+constantoffset, which is safe and uniformly supported
2094 // across targets.
2095 ConstantExpr *CE = cast<ConstantExpr>(C);
2096 switch (CE->getOpcode()) {
2097 case Instruction::BitCast:
2098 case Instruction::IntToPtr:
2099 case Instruction::PtrToInt:
2100 // These casts are always fine if the casted value is.
2101 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants);
2102
2103 // GEP is fine if it is simple + constant offset.
2104 case Instruction::GetElementPtr:
2105 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
2106 if (!isa<ConstantInt>(CE->getOperand(i)))
2107 return false;
2108 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants);
2109
2110 case Instruction::Add:
2111 // We allow simple+cst.
2112 if (!isa<ConstantInt>(CE->getOperand(1)))
2113 return false;
2114 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants);
2115 }
2116 return false;
2117}
2118
2119static inline bool
2120isSimpleEnoughValueToCommit(Constant *C,
2121 SmallPtrSet<Constant*, 8> &SimpleConstants) {
2122 // If we already checked this constant, we win.
2123 if (!SimpleConstants.insert(C)) return true;
2124 // Check the constant.
2125 return isSimpleEnoughValueToCommitHelper(C, SimpleConstants);
2126}
2127
2128
Chris Lattner79c11012005-09-26 04:44:35 +00002129/// isSimpleEnoughPointerToCommit - Return true if this constant is simple
Owen Andersoncff6b372011-01-14 22:19:20 +00002130/// enough for us to understand. In particular, if it is a cast to anything
2131/// other than from one pointer type to another pointer type, we punt.
2132/// We basically just support direct accesses to globals and GEP's of
Chris Lattner79c11012005-09-26 04:44:35 +00002133/// globals. This should be kept up to date with CommitValueTo.
Chris Lattner7b550cc2009-11-06 04:27:31 +00002134static bool isSimpleEnoughPointerToCommit(Constant *C) {
Dan Gohmance5de5b2009-09-07 22:42:05 +00002135 // Conservatively, avoid aggregate types. This is because we don't
2136 // want to worry about them partially overlapping other stores.
2137 if (!cast<PointerType>(C->getType())->getElementType()->isSingleValueType())
2138 return false;
2139
Dan Gohmanfd54a892009-09-07 22:31:26 +00002140 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
Mikhail Glushenkov99fca5d2010-10-19 16:47:23 +00002141 // Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or
Dan Gohmanfd54a892009-09-07 22:31:26 +00002142 // external globals.
Mikhail Glushenkov99fca5d2010-10-19 16:47:23 +00002143 return GV->hasUniqueInitializer();
Dan Gohmanfd54a892009-09-07 22:31:26 +00002144
Owen Andersone95a32c2011-01-14 22:31:13 +00002145 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002146 // Handle a constantexpr gep.
2147 if (CE->getOpcode() == Instruction::GetElementPtr &&
Dan Gohmanc62482d2009-09-07 22:40:13 +00002148 isa<GlobalVariable>(CE->getOperand(0)) &&
2149 cast<GEPOperator>(CE)->isInBounds()) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002150 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
Mikhail Glushenkov99fca5d2010-10-19 16:47:23 +00002151 // Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or
Dan Gohmanfd54a892009-09-07 22:31:26 +00002152 // external globals.
Mikhail Glushenkov99fca5d2010-10-19 16:47:23 +00002153 if (!GV->hasUniqueInitializer())
Dan Gohmanfd54a892009-09-07 22:31:26 +00002154 return false;
Dan Gohman80bdc962009-09-07 22:44:55 +00002155
Dan Gohman80bdc962009-09-07 22:44:55 +00002156 // The first index must be zero.
Oscar Fuentesee56c422010-08-02 06:00:15 +00002157 ConstantInt *CI = dyn_cast<ConstantInt>(*llvm::next(CE->op_begin()));
Dan Gohman80bdc962009-09-07 22:44:55 +00002158 if (!CI || !CI->isZero()) return false;
Dan Gohman80bdc962009-09-07 22:44:55 +00002159
2160 // The remaining indices must be compile-time known integers within the
Dan Gohmane6992f72009-09-10 23:37:55 +00002161 // notional bounds of the corresponding static array types.
2162 if (!CE->isGEPWithNoNotionalOverIndexing())
2163 return false;
Dan Gohman80bdc962009-09-07 22:44:55 +00002164
Dan Gohmanc6f69e92009-10-05 16:36:26 +00002165 return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
Owen Andersoncff6b372011-01-14 22:19:20 +00002166
2167 // A constantexpr bitcast from a pointer to another pointer is a no-op,
2168 // and we know how to evaluate it by moving the bitcast from the pointer
2169 // operand to the value operand.
2170 } else if (CE->getOpcode() == Instruction::BitCast &&
Chris Lattnerd5f656f2011-01-16 02:05:10 +00002171 isa<GlobalVariable>(CE->getOperand(0))) {
Owen Andersoncff6b372011-01-14 22:19:20 +00002172 // Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or
2173 // external globals.
Chris Lattnerd5f656f2011-01-16 02:05:10 +00002174 return cast<GlobalVariable>(CE->getOperand(0))->hasUniqueInitializer();
Chris Lattner798b4d52005-09-26 06:52:44 +00002175 }
Owen Andersone95a32c2011-01-14 22:31:13 +00002176 }
2177
Chris Lattner79c11012005-09-26 04:44:35 +00002178 return false;
2179}
2180
Chris Lattner798b4d52005-09-26 06:52:44 +00002181/// EvaluateStoreInto - Evaluate a piece of a constantexpr store into a global
2182/// initializer. This returns 'Init' modified to reflect 'Val' stored into it.
2183/// At this point, the GEP operands of Addr [0, OpNo) have been stepped into.
2184static Constant *EvaluateStoreInto(Constant *Init, Constant *Val,
Chris Lattner7b550cc2009-11-06 04:27:31 +00002185 ConstantExpr *Addr, unsigned OpNo) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002186 // Base case of the recursion.
2187 if (OpNo == Addr->getNumOperands()) {
2188 assert(Val->getType() == Init->getType() && "Type mismatch!");
2189 return Val;
2190 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002191
Chris Lattnera0e9a242010-01-07 01:16:21 +00002192 std::vector<Constant*> Elts;
Chris Lattner798b4d52005-09-26 06:52:44 +00002193 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002194
2195 // Break up the constant into its elements.
2196 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
Gabor Greif5e463212008-05-29 01:59:18 +00002197 for (User::op_iterator i = CS->op_begin(), e = CS->op_end(); i != e; ++i)
2198 Elts.push_back(cast<Constant>(*i));
Chris Lattner798b4d52005-09-26 06:52:44 +00002199 } else if (isa<ConstantAggregateZero>(Init)) {
2200 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
Owen Andersona7235ea2009-07-31 20:28:14 +00002201 Elts.push_back(Constant::getNullValue(STy->getElementType(i)));
Chris Lattner798b4d52005-09-26 06:52:44 +00002202 } else if (isa<UndefValue>(Init)) {
2203 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002204 Elts.push_back(UndefValue::get(STy->getElementType(i)));
Chris Lattner798b4d52005-09-26 06:52:44 +00002205 } else {
Torok Edwinc23197a2009-07-14 16:55:14 +00002206 llvm_unreachable("This code is out of sync with "
Chris Lattner798b4d52005-09-26 06:52:44 +00002207 " ConstantFoldLoadThroughGEPConstantExpr");
2208 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002209
Chris Lattner798b4d52005-09-26 06:52:44 +00002210 // Replace the element that we are supposed to.
Reid Spencerb83eb642006-10-20 07:07:24 +00002211 ConstantInt *CU = cast<ConstantInt>(Addr->getOperand(OpNo));
2212 unsigned Idx = CU->getZExtValue();
2213 assert(Idx < STy->getNumElements() && "Struct index out of range!");
Chris Lattner7b550cc2009-11-06 04:27:31 +00002214 Elts[Idx] = EvaluateStoreInto(Elts[Idx], Val, Addr, OpNo+1);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002215
Chris Lattner798b4d52005-09-26 06:52:44 +00002216 // Return the modified struct.
Chris Lattner7b550cc2009-11-06 04:27:31 +00002217 return ConstantStruct::get(Init->getContext(), &Elts[0], Elts.size(),
2218 STy->isPacked());
Chris Lattner798b4d52005-09-26 06:52:44 +00002219 } else {
2220 ConstantInt *CI = cast<ConstantInt>(Addr->getOperand(OpNo));
Chris Lattnera0e9a242010-01-07 01:16:21 +00002221 const SequentialType *InitTy = cast<SequentialType>(Init->getType());
Chris Lattner798b4d52005-09-26 06:52:44 +00002222
Chris Lattnera0e9a242010-01-07 01:16:21 +00002223 uint64_t NumElts;
2224 if (const ArrayType *ATy = dyn_cast<ArrayType>(InitTy))
2225 NumElts = ATy->getNumElements();
2226 else
2227 NumElts = cast<VectorType>(InitTy)->getNumElements();
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002228
2229
Chris Lattner798b4d52005-09-26 06:52:44 +00002230 // Break up the array into elements.
Chris Lattner798b4d52005-09-26 06:52:44 +00002231 if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
Gabor Greif5e463212008-05-29 01:59:18 +00002232 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i)
2233 Elts.push_back(cast<Constant>(*i));
Chris Lattner4039bd02010-01-07 01:20:20 +00002234 } else if (ConstantVector *CV = dyn_cast<ConstantVector>(Init)) {
2235 for (User::op_iterator i = CV->op_begin(), e = CV->op_end(); i != e; ++i)
2236 Elts.push_back(cast<Constant>(*i));
Chris Lattner798b4d52005-09-26 06:52:44 +00002237 } else if (isa<ConstantAggregateZero>(Init)) {
Chris Lattnera0e9a242010-01-07 01:16:21 +00002238 Elts.assign(NumElts, Constant::getNullValue(InitTy->getElementType()));
Chris Lattner798b4d52005-09-26 06:52:44 +00002239 } else {
Chris Lattnera0e9a242010-01-07 01:16:21 +00002240 assert(isa<UndefValue>(Init) && "This code is out of sync with "
Chris Lattner798b4d52005-09-26 06:52:44 +00002241 " ConstantFoldLoadThroughGEPConstantExpr");
Chris Lattnera0e9a242010-01-07 01:16:21 +00002242 Elts.assign(NumElts, UndefValue::get(InitTy->getElementType()));
Chris Lattner798b4d52005-09-26 06:52:44 +00002243 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002244
Chris Lattnera0e9a242010-01-07 01:16:21 +00002245 assert(CI->getZExtValue() < NumElts);
Reid Spencerb83eb642006-10-20 07:07:24 +00002246 Elts[CI->getZExtValue()] =
Chris Lattner7b550cc2009-11-06 04:27:31 +00002247 EvaluateStoreInto(Elts[CI->getZExtValue()], Val, Addr, OpNo+1);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002248
Duncan Sands1df98592010-02-16 11:11:14 +00002249 if (Init->getType()->isArrayTy())
Chris Lattnera0e9a242010-01-07 01:16:21 +00002250 return ConstantArray::get(cast<ArrayType>(InitTy), Elts);
Chris Lattner2ca5c862011-02-15 00:14:00 +00002251 return ConstantVector::get(Elts);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002252 }
Chris Lattner798b4d52005-09-26 06:52:44 +00002253}
2254
Chris Lattner79c11012005-09-26 04:44:35 +00002255/// CommitValueTo - We have decided that Addr (which satisfies the predicate
2256/// isSimpleEnoughPointerToCommit) should get Val as its value. Make it happen.
Chris Lattner7b550cc2009-11-06 04:27:31 +00002257static void CommitValueTo(Constant *Val, Constant *Addr) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002258 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Addr)) {
2259 assert(GV->hasInitializer());
2260 GV->setInitializer(Val);
2261 return;
2262 }
Chris Lattnera0e9a242010-01-07 01:16:21 +00002263
Chris Lattner798b4d52005-09-26 06:52:44 +00002264 ConstantExpr *CE = cast<ConstantExpr>(Addr);
2265 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
Chris Lattnera0e9a242010-01-07 01:16:21 +00002266 GV->setInitializer(EvaluateStoreInto(GV->getInitializer(), Val, CE, 2));
Chris Lattner79c11012005-09-26 04:44:35 +00002267}
2268
Chris Lattner562a0552005-09-26 05:16:34 +00002269/// ComputeLoadResult - Return the value that would be computed by a load from
2270/// P after the stores reflected by 'memory' have been performed. If we can't
2271/// decide, return null.
Chris Lattner04de1cf2005-09-26 05:15:37 +00002272static Constant *ComputeLoadResult(Constant *P,
Chris Lattner7b550cc2009-11-06 04:27:31 +00002273 const DenseMap<Constant*, Constant*> &Memory) {
Chris Lattner04de1cf2005-09-26 05:15:37 +00002274 // If this memory location has been recently stored, use the stored value: it
2275 // is the most up-to-date.
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002276 DenseMap<Constant*, Constant*>::const_iterator I = Memory.find(P);
Chris Lattner04de1cf2005-09-26 05:15:37 +00002277 if (I != Memory.end()) return I->second;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002278
Chris Lattner04de1cf2005-09-26 05:15:37 +00002279 // Access it.
2280 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(P)) {
Dan Gohman82555732009-08-19 18:20:44 +00002281 if (GV->hasDefinitiveInitializer())
Chris Lattner04de1cf2005-09-26 05:15:37 +00002282 return GV->getInitializer();
2283 return 0;
Chris Lattner04de1cf2005-09-26 05:15:37 +00002284 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002285
Chris Lattner798b4d52005-09-26 06:52:44 +00002286 // Handle a constantexpr getelementptr.
2287 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(P))
2288 if (CE->getOpcode() == Instruction::GetElementPtr &&
2289 isa<GlobalVariable>(CE->getOperand(0))) {
2290 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
Dan Gohman82555732009-08-19 18:20:44 +00002291 if (GV->hasDefinitiveInitializer())
Dan Gohmanc6f69e92009-10-05 16:36:26 +00002292 return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
Chris Lattner798b4d52005-09-26 06:52:44 +00002293 }
2294
2295 return 0; // don't know how to evaluate.
Chris Lattner04de1cf2005-09-26 05:15:37 +00002296}
2297
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002298/// EvaluateFunction - Evaluate a call to function F, returning true if
2299/// successful, false if we can't evaluate it. ActualArgs contains the formal
2300/// arguments for the function.
Chris Lattnercd271422005-09-27 04:45:34 +00002301static bool EvaluateFunction(Function *F, Constant *&RetVal,
Duncan Sandsfa6a1cf2009-08-17 14:33:27 +00002302 const SmallVectorImpl<Constant*> &ActualArgs,
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002303 std::vector<Function*> &CallStack,
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002304 DenseMap<Constant*, Constant*> &MutatedMemory,
Chris Lattner1945d582010-12-07 04:33:29 +00002305 std::vector<GlobalVariable*> &AllocaTmps,
2306 SmallPtrSet<Constant*, 8> &SimpleConstants,
2307 const TargetData *TD) {
Chris Lattnercd271422005-09-27 04:45:34 +00002308 // Check to see if this function is already executing (recursion). If so,
2309 // bail out. TODO: we might want to accept limited recursion.
2310 if (std::find(CallStack.begin(), CallStack.end(), F) != CallStack.end())
2311 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002312
Chris Lattnercd271422005-09-27 04:45:34 +00002313 CallStack.push_back(F);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002314
Chris Lattner79c11012005-09-26 04:44:35 +00002315 /// Values - As we compute SSA register values, we store their contents here.
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002316 DenseMap<Value*, Constant*> Values;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002317
Chris Lattnercd271422005-09-27 04:45:34 +00002318 // Initialize arguments to the incoming values specified.
2319 unsigned ArgNo = 0;
2320 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); AI != E;
2321 ++AI, ++ArgNo)
2322 Values[AI] = ActualArgs[ArgNo];
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002323
Chris Lattnercdf98be2005-09-26 04:57:38 +00002324 /// ExecutedBlocks - We only handle non-looping, non-recursive code. As such,
2325 /// we can only evaluate any one basic block at most once. This set keeps
2326 /// track of what we have executed so we can detect recursive cases etc.
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002327 SmallPtrSet<BasicBlock*, 32> ExecutedBlocks;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002328
Chris Lattner79c11012005-09-26 04:44:35 +00002329 // CurInst - The current instruction we're evaluating.
2330 BasicBlock::iterator CurInst = F->begin()->begin();
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002331
Chris Lattner79c11012005-09-26 04:44:35 +00002332 // This is the main evaluation loop.
2333 while (1) {
2334 Constant *InstResult = 0;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002335
Chris Lattner79c11012005-09-26 04:44:35 +00002336 if (StoreInst *SI = dyn_cast<StoreInst>(CurInst)) {
Chris Lattnercd271422005-09-27 04:45:34 +00002337 if (SI->isVolatile()) return false; // no volatile accesses.
Chris Lattner79c11012005-09-26 04:44:35 +00002338 Constant *Ptr = getVal(Values, SI->getOperand(1));
Chris Lattner7b550cc2009-11-06 04:27:31 +00002339 if (!isSimpleEnoughPointerToCommit(Ptr))
Chris Lattner79c11012005-09-26 04:44:35 +00002340 // If this is too complex for us to commit, reject it.
Chris Lattnercd271422005-09-27 04:45:34 +00002341 return false;
Chris Lattner1945d582010-12-07 04:33:29 +00002342
Chris Lattner79c11012005-09-26 04:44:35 +00002343 Constant *Val = getVal(Values, SI->getOperand(0));
Chris Lattner1945d582010-12-07 04:33:29 +00002344
2345 // If this might be too difficult for the backend to handle (e.g. the addr
2346 // of one global variable divided by another) then we can't commit it.
2347 if (!isSimpleEnoughValueToCommit(Val, SimpleConstants))
2348 return false;
Owen Andersoncff6b372011-01-14 22:19:20 +00002349
2350 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
2351 if (CE->getOpcode() == Instruction::BitCast) {
2352 // If we're evaluating a store through a bitcast, then we need
2353 // to pull the bitcast off the pointer type and push it onto the
2354 // stored value.
Chris Lattnerd5f656f2011-01-16 02:05:10 +00002355 Ptr = CE->getOperand(0);
Owen Andersoncff6b372011-01-14 22:19:20 +00002356
Chris Lattnerd5f656f2011-01-16 02:05:10 +00002357 const Type *NewTy=cast<PointerType>(Ptr->getType())->getElementType();
Owen Andersoncff6b372011-01-14 22:19:20 +00002358
Owen Anderson66f708f2011-01-16 04:33:33 +00002359 // In order to push the bitcast onto the stored value, a bitcast
2360 // from NewTy to Val's type must be legal. If it's not, we can try
2361 // introspecting NewTy to find a legal conversion.
2362 while (!Val->getType()->canLosslesslyBitCastTo(NewTy)) {
2363 // If NewTy is a struct, we can convert the pointer to the struct
2364 // into a pointer to its first member.
2365 // FIXME: This could be extended to support arrays as well.
2366 if (const StructType *STy = dyn_cast<StructType>(NewTy)) {
2367 NewTy = STy->getTypeAtIndex(0U);
2368
2369 const IntegerType *IdxTy =IntegerType::get(NewTy->getContext(), 32);
2370 Constant *IdxZero = ConstantInt::get(IdxTy, 0, false);
2371 Constant * const IdxList[] = {IdxZero, IdxZero};
2372
2373 Ptr = ConstantExpr::getGetElementPtr(Ptr, IdxList, 2);
Owen Andersoncff6b372011-01-14 22:19:20 +00002374
Owen Anderson66f708f2011-01-16 04:33:33 +00002375 // If we can't improve the situation by introspecting NewTy,
2376 // we have to give up.
2377 } else {
2378 return 0;
2379 }
Owen Andersoncff6b372011-01-14 22:19:20 +00002380 }
2381
Owen Anderson66f708f2011-01-16 04:33:33 +00002382 // If we found compatible types, go ahead and push the bitcast
2383 // onto the stored value.
Owen Andersoncff6b372011-01-14 22:19:20 +00002384 Val = ConstantExpr::getBitCast(Val, NewTy);
2385 }
2386
Chris Lattner79c11012005-09-26 04:44:35 +00002387 MutatedMemory[Ptr] = Val;
2388 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CurInst)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002389 InstResult = ConstantExpr::get(BO->getOpcode(),
Chris Lattner79c11012005-09-26 04:44:35 +00002390 getVal(Values, BO->getOperand(0)),
2391 getVal(Values, BO->getOperand(1)));
Reid Spencere4d87aa2006-12-23 06:05:41 +00002392 } else if (CmpInst *CI = dyn_cast<CmpInst>(CurInst)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002393 InstResult = ConstantExpr::getCompare(CI->getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00002394 getVal(Values, CI->getOperand(0)),
2395 getVal(Values, CI->getOperand(1)));
Chris Lattner79c11012005-09-26 04:44:35 +00002396 } else if (CastInst *CI = dyn_cast<CastInst>(CurInst)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002397 InstResult = ConstantExpr::getCast(CI->getOpcode(),
Chris Lattner9a989f02006-11-30 17:26:08 +00002398 getVal(Values, CI->getOperand(0)),
Chris Lattner79c11012005-09-26 04:44:35 +00002399 CI->getType());
2400 } else if (SelectInst *SI = dyn_cast<SelectInst>(CurInst)) {
Gabor Greif9e4f2432010-06-24 14:42:01 +00002401 InstResult = ConstantExpr::getSelect(getVal(Values, SI->getOperand(0)),
Eric Christopher551754c2010-04-16 23:37:20 +00002402 getVal(Values, SI->getOperand(1)),
2403 getVal(Values, SI->getOperand(2)));
Chris Lattner04de1cf2005-09-26 05:15:37 +00002404 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurInst)) {
2405 Constant *P = getVal(Values, GEP->getOperand(0));
Chris Lattner55eb1c42007-01-31 04:40:53 +00002406 SmallVector<Constant*, 8> GEPOps;
Gabor Greif5e463212008-05-29 01:59:18 +00002407 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end();
2408 i != e; ++i)
2409 GEPOps.push_back(getVal(Values, *i));
Dan Gohman4a7e6b72009-09-07 22:34:43 +00002410 InstResult = cast<GEPOperator>(GEP)->isInBounds() ?
2411 ConstantExpr::getInBoundsGetElementPtr(P, &GEPOps[0], GEPOps.size()) :
2412 ConstantExpr::getGetElementPtr(P, &GEPOps[0], GEPOps.size());
Chris Lattner04de1cf2005-09-26 05:15:37 +00002413 } else if (LoadInst *LI = dyn_cast<LoadInst>(CurInst)) {
Chris Lattnercd271422005-09-27 04:45:34 +00002414 if (LI->isVolatile()) return false; // no volatile accesses.
Chris Lattner04de1cf2005-09-26 05:15:37 +00002415 InstResult = ComputeLoadResult(getVal(Values, LI->getOperand(0)),
Chris Lattner7b550cc2009-11-06 04:27:31 +00002416 MutatedMemory);
Chris Lattnercd271422005-09-27 04:45:34 +00002417 if (InstResult == 0) return false; // Could not evaluate load.
Chris Lattnera22fdb02005-09-26 17:07:09 +00002418 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(CurInst)) {
Chris Lattnercd271422005-09-27 04:45:34 +00002419 if (AI->isArrayAllocation()) return false; // Cannot handle array allocs.
Chris Lattnera22fdb02005-09-26 17:07:09 +00002420 const Type *Ty = AI->getType()->getElementType();
Chris Lattner7b550cc2009-11-06 04:27:31 +00002421 AllocaTmps.push_back(new GlobalVariable(Ty, false,
Chris Lattnera22fdb02005-09-26 17:07:09 +00002422 GlobalValue::InternalLinkage,
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002423 UndefValue::get(Ty),
Chris Lattnera22fdb02005-09-26 17:07:09 +00002424 AI->getName()));
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002425 InstResult = AllocaTmps.back();
Chris Lattnercd271422005-09-27 04:45:34 +00002426 } else if (CallInst *CI = dyn_cast<CallInst>(CurInst)) {
Devang Patel412a4462009-03-09 23:04:12 +00002427
2428 // Debug info can safely be ignored here.
2429 if (isa<DbgInfoIntrinsic>(CI)) {
2430 ++CurInst;
2431 continue;
2432 }
2433
Chris Lattner7cd580f2006-07-07 21:37:01 +00002434 // Cannot handle inline asm.
Gabor Greifa9b23132010-04-20 13:13:04 +00002435 if (isa<InlineAsm>(CI->getCalledValue())) return false;
Chris Lattner7cd580f2006-07-07 21:37:01 +00002436
Chris Lattnercd271422005-09-27 04:45:34 +00002437 // Resolve function pointers.
Gabor Greifa3997812010-07-22 10:37:47 +00002438 Function *Callee = dyn_cast<Function>(getVal(Values,
2439 CI->getCalledValue()));
Chris Lattnercd271422005-09-27 04:45:34 +00002440 if (!Callee) return false; // Cannot resolve.
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002441
Duncan Sandsfa6a1cf2009-08-17 14:33:27 +00002442 SmallVector<Constant*, 8> Formals;
Gabor Greif9e4f2432010-06-24 14:42:01 +00002443 CallSite CS(CI);
2444 for (User::op_iterator i = CS.arg_begin(), e = CS.arg_end();
Gabor Greif5e463212008-05-29 01:59:18 +00002445 i != e; ++i)
2446 Formals.push_back(getVal(Values, *i));
Duncan Sandsfa6a1cf2009-08-17 14:33:27 +00002447
Reid Spencer5cbf9852007-01-30 20:08:39 +00002448 if (Callee->isDeclaration()) {
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002449 // If this is a function we can constant fold, do it.
Duncan Sandsfa6a1cf2009-08-17 14:33:27 +00002450 if (Constant *C = ConstantFoldCall(Callee, Formals.data(),
Chris Lattner6c1f5652007-01-30 23:14:52 +00002451 Formals.size())) {
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002452 InstResult = C;
2453 } else {
2454 return false;
2455 }
2456 } else {
2457 if (Callee->getFunctionType()->isVarArg())
2458 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002459
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002460 Constant *RetVal;
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002461 // Execute the call, if successful, use the return value.
2462 if (!EvaluateFunction(Callee, RetVal, Formals, CallStack,
Chris Lattner1945d582010-12-07 04:33:29 +00002463 MutatedMemory, AllocaTmps, SimpleConstants, TD))
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002464 return false;
2465 InstResult = RetVal;
2466 }
Reid Spencer3ed469c2006-11-02 20:25:50 +00002467 } else if (isa<TerminatorInst>(CurInst)) {
Chris Lattnercdf98be2005-09-26 04:57:38 +00002468 BasicBlock *NewBB = 0;
2469 if (BranchInst *BI = dyn_cast<BranchInst>(CurInst)) {
2470 if (BI->isUnconditional()) {
2471 NewBB = BI->getSuccessor(0);
2472 } else {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002473 ConstantInt *Cond =
2474 dyn_cast<ConstantInt>(getVal(Values, BI->getCondition()));
Chris Lattner97d1fad2007-01-12 18:30:11 +00002475 if (!Cond) return false; // Cannot determine.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002476
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002477 NewBB = BI->getSuccessor(!Cond->getZExtValue());
Chris Lattnercdf98be2005-09-26 04:57:38 +00002478 }
2479 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(CurInst)) {
2480 ConstantInt *Val =
2481 dyn_cast<ConstantInt>(getVal(Values, SI->getCondition()));
Chris Lattnercd271422005-09-27 04:45:34 +00002482 if (!Val) return false; // Cannot determine.
Chris Lattnercdf98be2005-09-26 04:57:38 +00002483 NewBB = SI->getSuccessor(SI->findCaseValue(Val));
Chris Lattnerb3d5a652009-10-29 05:51:50 +00002484 } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(CurInst)) {
2485 Value *Val = getVal(Values, IBI->getAddress())->stripPointerCasts();
2486 if (BlockAddress *BA = dyn_cast<BlockAddress>(Val))
2487 NewBB = BA->getBasicBlock();
Chris Lattnercdfc9402009-11-01 01:27:45 +00002488 else
2489 return false; // Cannot determine.
Chris Lattnercdf98be2005-09-26 04:57:38 +00002490 } else if (ReturnInst *RI = dyn_cast<ReturnInst>(CurInst)) {
Chris Lattnercd271422005-09-27 04:45:34 +00002491 if (RI->getNumOperands())
2492 RetVal = getVal(Values, RI->getOperand(0));
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002493
Chris Lattnercd271422005-09-27 04:45:34 +00002494 CallStack.pop_back(); // return from fn.
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002495 return true; // We succeeded at evaluating this ctor!
Chris Lattnercdf98be2005-09-26 04:57:38 +00002496 } else {
Chris Lattnercd271422005-09-27 04:45:34 +00002497 // invoke, unwind, unreachable.
2498 return false; // Cannot handle this terminator.
Chris Lattnercdf98be2005-09-26 04:57:38 +00002499 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002500
Chris Lattnercdf98be2005-09-26 04:57:38 +00002501 // Okay, we succeeded in evaluating this control flow. See if we have
Chris Lattnercd271422005-09-27 04:45:34 +00002502 // executed the new block before. If so, we have a looping function,
2503 // which we cannot evaluate in reasonable time.
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002504 if (!ExecutedBlocks.insert(NewBB))
Chris Lattnercd271422005-09-27 04:45:34 +00002505 return false; // looped!
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002506
Chris Lattnercdf98be2005-09-26 04:57:38 +00002507 // Okay, we have never been in this block before. Check to see if there
2508 // are any PHI nodes. If so, evaluate them with information about where
2509 // we came from.
2510 BasicBlock *OldBB = CurInst->getParent();
2511 CurInst = NewBB->begin();
2512 PHINode *PN;
2513 for (; (PN = dyn_cast<PHINode>(CurInst)); ++CurInst)
2514 Values[PN] = getVal(Values, PN->getIncomingValueForBlock(OldBB));
2515
2516 // Do NOT increment CurInst. We know that the terminator had no value.
2517 continue;
Chris Lattner79c11012005-09-26 04:44:35 +00002518 } else {
Chris Lattner79c11012005-09-26 04:44:35 +00002519 // Did not know how to evaluate this!
Chris Lattnercd271422005-09-27 04:45:34 +00002520 return false;
Chris Lattner79c11012005-09-26 04:44:35 +00002521 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002522
Chris Lattner1945d582010-12-07 04:33:29 +00002523 if (!CurInst->use_empty()) {
2524 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(InstResult))
2525 InstResult = ConstantFoldConstantExpression(CE, TD);
2526
Chris Lattner79c11012005-09-26 04:44:35 +00002527 Values[CurInst] = InstResult;
Chris Lattner1945d582010-12-07 04:33:29 +00002528 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002529
Chris Lattner79c11012005-09-26 04:44:35 +00002530 // Advance program counter.
2531 ++CurInst;
2532 }
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002533}
2534
2535/// EvaluateStaticConstructor - Evaluate static constructors in the function, if
2536/// we can. Return true if we can, false otherwise.
Chris Lattner1945d582010-12-07 04:33:29 +00002537static bool EvaluateStaticConstructor(Function *F, const TargetData *TD) {
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002538 /// MutatedMemory - For each store we execute, we update this map. Loads
2539 /// check this to get the most up-to-date value. If evaluation is successful,
2540 /// this state is committed to the process.
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002541 DenseMap<Constant*, Constant*> MutatedMemory;
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002542
2543 /// AllocaTmps - To 'execute' an alloca, we create a temporary global variable
2544 /// to represent its body. This vector is needed so we can delete the
2545 /// temporary globals when we are done.
2546 std::vector<GlobalVariable*> AllocaTmps;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002547
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002548 /// CallStack - This is used to detect recursion. In pathological situations
2549 /// we could hit exponential behavior, but at least there is nothing
2550 /// unbounded.
2551 std::vector<Function*> CallStack;
2552
Chris Lattner1945d582010-12-07 04:33:29 +00002553 /// SimpleConstants - These are constants we have checked and know to be
2554 /// simple enough to live in a static initializer of a global.
2555 SmallPtrSet<Constant*, 8> SimpleConstants;
2556
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002557 // Call the function.
Chris Lattnercd271422005-09-27 04:45:34 +00002558 Constant *RetValDummy;
Duncan Sandsfa6a1cf2009-08-17 14:33:27 +00002559 bool EvalSuccess = EvaluateFunction(F, RetValDummy,
2560 SmallVector<Constant*, 0>(), CallStack,
Chris Lattner1945d582010-12-07 04:33:29 +00002561 MutatedMemory, AllocaTmps,
2562 SimpleConstants, TD);
2563
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002564 if (EvalSuccess) {
Chris Lattnera22fdb02005-09-26 17:07:09 +00002565 // We succeeded at evaluation: commit the result.
David Greene3215b0e2010-01-05 01:28:05 +00002566 DEBUG(dbgs() << "FULLY EVALUATED GLOBAL CTOR FUNCTION '"
Daniel Dunbarce63ffb2009-07-25 00:23:56 +00002567 << F->getName() << "' to " << MutatedMemory.size()
2568 << " stores.\n");
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002569 for (DenseMap<Constant*, Constant*>::iterator I = MutatedMemory.begin(),
Chris Lattnera22fdb02005-09-26 17:07:09 +00002570 E = MutatedMemory.end(); I != E; ++I)
Chris Lattner7b550cc2009-11-06 04:27:31 +00002571 CommitValueTo(I->second, I->first);
Chris Lattnera22fdb02005-09-26 17:07:09 +00002572 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002573
Chris Lattnera22fdb02005-09-26 17:07:09 +00002574 // At this point, we are done interpreting. If we created any 'alloca'
2575 // temporaries, release them now.
2576 while (!AllocaTmps.empty()) {
2577 GlobalVariable *Tmp = AllocaTmps.back();
2578 AllocaTmps.pop_back();
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002579
Chris Lattnera22fdb02005-09-26 17:07:09 +00002580 // If there are still users of the alloca, the program is doing something
2581 // silly, e.g. storing the address of the alloca somewhere and using it
2582 // later. Since this is undefined, we'll just make it be null.
2583 if (!Tmp->use_empty())
Owen Andersona7235ea2009-07-31 20:28:14 +00002584 Tmp->replaceAllUsesWith(Constant::getNullValue(Tmp->getType()));
Chris Lattnera22fdb02005-09-26 17:07:09 +00002585 delete Tmp;
2586 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002587
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002588 return EvalSuccess;
Chris Lattner79c11012005-09-26 04:44:35 +00002589}
2590
Chris Lattnerdb973e62005-09-26 02:31:18 +00002591
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002592
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002593/// OptimizeGlobalCtorsList - Simplify and evaluation global ctors if possible.
2594/// Return true if anything changed.
2595bool GlobalOpt::OptimizeGlobalCtorsList(GlobalVariable *&GCL) {
2596 std::vector<Function*> Ctors = ParseGlobalCtors(GCL);
2597 bool MadeChange = false;
2598 if (Ctors.empty()) return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002599
Chris Lattner1945d582010-12-07 04:33:29 +00002600 const TargetData *TD = getAnalysisIfAvailable<TargetData>();
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002601 // Loop over global ctors, optimizing them when we can.
2602 for (unsigned i = 0; i != Ctors.size(); ++i) {
2603 Function *F = Ctors[i];
2604 // Found a null terminator in the middle of the list, prune off the rest of
2605 // the list.
Chris Lattner7d8e58f2005-09-26 02:19:27 +00002606 if (F == 0) {
2607 if (i != Ctors.size()-1) {
2608 Ctors.resize(i+1);
2609 MadeChange = true;
2610 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002611 break;
2612 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002613
Chris Lattner79c11012005-09-26 04:44:35 +00002614 // We cannot simplify external ctor functions.
2615 if (F->empty()) continue;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002616
Chris Lattner79c11012005-09-26 04:44:35 +00002617 // If we can evaluate the ctor at compile time, do.
Chris Lattner1945d582010-12-07 04:33:29 +00002618 if (EvaluateStaticConstructor(F, TD)) {
Chris Lattner79c11012005-09-26 04:44:35 +00002619 Ctors.erase(Ctors.begin()+i);
2620 MadeChange = true;
2621 --i;
2622 ++NumCtorsEvaluated;
2623 continue;
2624 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002625 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002626
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002627 if (!MadeChange) return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002628
Chris Lattner7b550cc2009-11-06 04:27:31 +00002629 GCL = InstallGlobalCtors(GCL, Ctors);
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002630 return true;
2631}
2632
Duncan Sandsfc5940d2009-03-06 10:21:56 +00002633bool GlobalOpt::OptimizeGlobalAliases(Module &M) {
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002634 bool Changed = false;
2635
Duncan Sands177d84e2009-01-07 20:01:06 +00002636 for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end();
Duncan Sands4782b302009-02-15 09:56:08 +00002637 I != E;) {
2638 Module::alias_iterator J = I++;
Duncan Sandsfc5940d2009-03-06 10:21:56 +00002639 // Aliases without names cannot be referenced outside this module.
2640 if (!J->hasName() && !J->isDeclaration())
2641 J->setLinkage(GlobalValue::InternalLinkage);
Duncan Sands4782b302009-02-15 09:56:08 +00002642 // If the aliasee may change at link time, nothing can be done - bail out.
2643 if (J->mayBeOverridden())
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002644 continue;
2645
Duncan Sands4782b302009-02-15 09:56:08 +00002646 Constant *Aliasee = J->getAliasee();
2647 GlobalValue *Target = cast<GlobalValue>(Aliasee->stripPointerCasts());
Duncan Sands95c5d0f2009-02-18 17:55:38 +00002648 Target->removeDeadConstantUsers();
Duncan Sands4782b302009-02-15 09:56:08 +00002649 bool hasOneUse = Target->hasOneUse() && Aliasee->hasOneUse();
2650
2651 // Make all users of the alias use the aliasee instead.
2652 if (!J->use_empty()) {
2653 J->replaceAllUsesWith(Aliasee);
2654 ++NumAliasesResolved;
2655 Changed = true;
2656 }
2657
Duncan Sands7a154cf2009-12-08 10:10:20 +00002658 // If the alias is externally visible, we may still be able to simplify it.
2659 if (!J->hasLocalLinkage()) {
2660 // If the aliasee has internal linkage, give it the name and linkage
2661 // of the alias, and delete the alias. This turns:
2662 // define internal ... @f(...)
2663 // @a = alias ... @f
2664 // into:
2665 // define ... @a(...)
2666 if (!Target->hasLocalLinkage())
2667 continue;
Duncan Sands4782b302009-02-15 09:56:08 +00002668
Duncan Sands7a154cf2009-12-08 10:10:20 +00002669 // Do not perform the transform if multiple aliases potentially target the
Gabor Greif27236912010-04-07 18:59:26 +00002670 // aliasee. This check also ensures that it is safe to replace the section
Duncan Sands7a154cf2009-12-08 10:10:20 +00002671 // and other attributes of the aliasee with those of the alias.
2672 if (!hasOneUse)
2673 continue;
Duncan Sands4782b302009-02-15 09:56:08 +00002674
Duncan Sands7a154cf2009-12-08 10:10:20 +00002675 // Give the aliasee the name, linkage and other attributes of the alias.
2676 Target->takeName(J);
2677 Target->setLinkage(J->getLinkage());
2678 Target->GlobalValue::copyAttributesFrom(J);
2679 }
Duncan Sands4782b302009-02-15 09:56:08 +00002680
2681 // Delete the alias.
2682 M.getAliasList().erase(J);
2683 ++NumAliasesRemoved;
2684 Changed = true;
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002685 }
2686
2687 return Changed;
2688}
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002689
Anders Carlssona201c4c2011-03-20 17:59:11 +00002690static Function *FindCXAAtExit(Module &M) {
2691 Function *Fn = M.getFunction("__cxa_atexit");
2692
2693 if (!Fn)
2694 return 0;
2695
2696 const FunctionType *FTy = Fn->getFunctionType();
2697
Anders Carlsson1f7c7ba2011-03-20 19:51:13 +00002698 // Checking that the function has the right return type, the right number of
2699 // parameters and that they all have pointer types should be enough.
2700 if (!FTy->getReturnType()->isIntegerTy() ||
2701 FTy->getNumParams() != 3 ||
Anders Carlssona201c4c2011-03-20 17:59:11 +00002702 !FTy->getParamType(0)->isPointerTy() ||
2703 !FTy->getParamType(1)->isPointerTy() ||
2704 !FTy->getParamType(2)->isPointerTy())
2705 return 0;
2706
2707 return Fn;
2708}
2709
2710/// cxxDtorIsEmpty - Returns whether the given function is an empty C++
2711/// destructor and can therefore be eliminated.
2712/// Note that we assume that other optimization passes have already simplified
2713/// the code so we only look for a function with a single basic block, where
2714/// the only allowed instructions are 'ret' or 'call' to empty C++ dtor.
Anders Carlsson372ec6a2011-03-20 20:16:43 +00002715static bool cxxDtorIsEmpty(const Function &Fn,
2716 SmallPtrSet<const Function *, 8> &CalledFunctions) {
Anders Carlsson1f7c7ba2011-03-20 19:51:13 +00002717 // FIXME: We could eliminate C++ destructors if they're readonly/readnone and
Nick Lewycky35ee1c92011-03-21 02:26:01 +00002718 // nounwind, but that doesn't seem worth doing.
Anders Carlsson1f7c7ba2011-03-20 19:51:13 +00002719 if (Fn.isDeclaration())
2720 return false;
Anders Carlssona201c4c2011-03-20 17:59:11 +00002721
2722 if (++Fn.begin() != Fn.end())
2723 return false;
2724
2725 const BasicBlock &EntryBlock = Fn.getEntryBlock();
2726 for (BasicBlock::const_iterator I = EntryBlock.begin(), E = EntryBlock.end();
2727 I != E; ++I) {
2728 if (const CallInst *CI = dyn_cast<CallInst>(I)) {
Anders Carlssonb12caf32011-03-21 14:54:40 +00002729 // Ignore debug intrinsics.
2730 if (isa<DbgInfoIntrinsic>(CI))
2731 continue;
2732
Anders Carlssona201c4c2011-03-20 17:59:11 +00002733 const Function *CalledFn = CI->getCalledFunction();
2734
2735 if (!CalledFn)
2736 return false;
2737
Anders Carlsson807bc2a2011-03-22 03:21:01 +00002738 SmallPtrSet<const Function *, 8> NewCalledFunctions(CalledFunctions);
2739
Anders Carlsson1f7c7ba2011-03-20 19:51:13 +00002740 // Don't treat recursive functions as empty.
Anders Carlsson807bc2a2011-03-22 03:21:01 +00002741 if (!NewCalledFunctions.insert(CalledFn))
Anders Carlsson1f7c7ba2011-03-20 19:51:13 +00002742 return false;
2743
Anders Carlsson807bc2a2011-03-22 03:21:01 +00002744 if (!cxxDtorIsEmpty(*CalledFn, NewCalledFunctions))
Anders Carlssona201c4c2011-03-20 17:59:11 +00002745 return false;
2746 } else if (isa<ReturnInst>(*I))
2747 return true;
2748 else
2749 return false;
2750 }
2751
2752 return false;
2753}
2754
2755bool GlobalOpt::OptimizeEmptyGlobalCXXDtors(Function *CXAAtExitFn) {
2756 /// Itanium C++ ABI p3.3.5:
2757 ///
2758 /// After constructing a global (or local static) object, that will require
2759 /// destruction on exit, a termination function is registered as follows:
2760 ///
2761 /// extern "C" int __cxa_atexit ( void (*f)(void *), void *p, void *d );
2762 ///
2763 /// This registration, e.g. __cxa_atexit(f,p,d), is intended to cause the
2764 /// call f(p) when DSO d is unloaded, before all such termination calls
2765 /// registered before this one. It returns zero if registration is
Nick Lewycky35ee1c92011-03-21 02:26:01 +00002766 /// successful, nonzero on failure.
Anders Carlssona201c4c2011-03-20 17:59:11 +00002767
2768 // This pass will look for calls to __cxa_atexit where the function is trivial
2769 // and remove them.
2770 bool Changed = false;
2771
2772 for (Function::use_iterator I = CXAAtExitFn->use_begin(),
2773 E = CXAAtExitFn->use_end(); I != E;) {
Anders Carlsson4f735ca2011-03-20 20:21:33 +00002774 // We're only interested in calls. Theoretically, we could handle invoke
2775 // instructions as well, but neither llvm-gcc nor clang generate invokes
2776 // to __cxa_atexit.
Anders Carlssonb12caf32011-03-21 14:54:40 +00002777 CallInst *CI = dyn_cast<CallInst>(*I++);
2778 if (!CI)
Anders Carlsson4f735ca2011-03-20 20:21:33 +00002779 continue;
2780
Anders Carlssona201c4c2011-03-20 17:59:11 +00002781 Function *DtorFn =
Anders Carlssonb12caf32011-03-21 14:54:40 +00002782 dyn_cast<Function>(CI->getArgOperand(0)->stripPointerCasts());
Anders Carlssona201c4c2011-03-20 17:59:11 +00002783 if (!DtorFn)
2784 continue;
2785
Anders Carlsson372ec6a2011-03-20 20:16:43 +00002786 SmallPtrSet<const Function *, 8> CalledFunctions;
2787 if (!cxxDtorIsEmpty(*DtorFn, CalledFunctions))
Anders Carlssona201c4c2011-03-20 17:59:11 +00002788 continue;
2789
2790 // Just remove the call.
Anders Carlssonb12caf32011-03-21 14:54:40 +00002791 CI->replaceAllUsesWith(Constant::getNullValue(CI->getType()));
2792 CI->eraseFromParent();
Anders Carlsson1f7c7ba2011-03-20 19:51:13 +00002793
Anders Carlssona201c4c2011-03-20 17:59:11 +00002794 ++NumCXXDtorsRemoved;
2795
2796 Changed |= true;
2797 }
2798
2799 return Changed;
2800}
2801
Chris Lattner7a90b682004-10-07 04:16:33 +00002802bool GlobalOpt::runOnModule(Module &M) {
Chris Lattner079236d2004-02-25 21:34:36 +00002803 bool Changed = false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002804
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002805 // Try to find the llvm.globalctors list.
2806 GlobalVariable *GlobalCtors = FindGlobalCtors(M);
Chris Lattner7a90b682004-10-07 04:16:33 +00002807
Anders Carlssona201c4c2011-03-20 17:59:11 +00002808 Function *CXAAtExitFn = FindCXAAtExit(M);
2809
Chris Lattner7a90b682004-10-07 04:16:33 +00002810 bool LocalChange = true;
2811 while (LocalChange) {
2812 LocalChange = false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002813
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002814 // Delete functions that are trivially dead, ccc -> fastcc
2815 LocalChange |= OptimizeFunctions(M);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002816
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002817 // Optimize global_ctors list.
2818 if (GlobalCtors)
2819 LocalChange |= OptimizeGlobalCtorsList(GlobalCtors);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002820
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002821 // Optimize non-address-taken globals.
2822 LocalChange |= OptimizeGlobalVars(M);
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002823
2824 // Resolve aliases, when possible.
Duncan Sandsfc5940d2009-03-06 10:21:56 +00002825 LocalChange |= OptimizeGlobalAliases(M);
Anders Carlssona201c4c2011-03-20 17:59:11 +00002826
2827 // Try to remove trivial global destructors.
2828 if (CXAAtExitFn)
2829 LocalChange |= OptimizeEmptyGlobalCXXDtors(CXAAtExitFn);
2830
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002831 Changed |= LocalChange;
Chris Lattner7a90b682004-10-07 04:16:33 +00002832 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002833
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002834 // TODO: Move all global ctors functions to the end of the module for code
2835 // layout.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002836
Chris Lattner079236d2004-02-25 21:34:36 +00002837 return Changed;
2838}