blob: d4cb71272f76774ff5b35414f07592f082523e52 [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");
Chris Lattner079236d2004-02-25 21:34:36 +000057
Chris Lattner86453c52006-12-19 22:09:18 +000058namespace {
Rafael Espindolac4440e32011-01-19 16:32:21 +000059 struct GlobalStatus;
Nick Lewycky6726b6d2009-10-25 06:33:48 +000060 struct GlobalOpt : public ModulePass {
Chris Lattner30ba5692004-10-11 05:54:41 +000061 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner30ba5692004-10-11 05:54:41 +000062 }
Nick Lewyckyecd94c82007-05-06 13:37:16 +000063 static char ID; // Pass identification, replacement for typeid
Owen Anderson081c34b2010-10-19 17:21:58 +000064 GlobalOpt() : ModulePass(ID) {
65 initializeGlobalOptPass(*PassRegistry::getPassRegistry());
66 }
Misha Brukmanfd939082005-04-21 23:48:37 +000067
Chris Lattnerb12914b2004-09-20 04:48:05 +000068 bool runOnModule(Module &M);
Chris Lattner30ba5692004-10-11 05:54:41 +000069
70 private:
Chris Lattnerb1ab4582005-09-26 01:43:45 +000071 GlobalVariable *FindGlobalCtors(Module &M);
72 bool OptimizeFunctions(Module &M);
73 bool OptimizeGlobalVars(Module &M);
Duncan Sandsfc5940d2009-03-06 10:21:56 +000074 bool OptimizeGlobalAliases(Module &M);
Chris Lattnerb1ab4582005-09-26 01:43:45 +000075 bool OptimizeGlobalCtorsList(GlobalVariable *&GCL);
Rafael Espindolac4440e32011-01-19 16:32:21 +000076 bool ProcessGlobal(GlobalVariable *GV,Module::global_iterator &GVI);
77 bool ProcessInternalGlobal(GlobalVariable *GV,Module::global_iterator &GVI,
78 const SmallPtrSet<const PHINode*, 16> &PHIUsers,
79 const GlobalStatus &GS);
Chris Lattner079236d2004-02-25 21:34:36 +000080 };
Chris Lattner079236d2004-02-25 21:34:36 +000081}
82
Dan Gohman844731a2008-05-13 00:00:25 +000083char GlobalOpt::ID = 0;
Owen Andersond13db2c2010-07-21 22:09:45 +000084INITIALIZE_PASS(GlobalOpt, "globalopt",
Owen Andersonce665bd2010-10-07 22:25:06 +000085 "Global Variable Optimizer", false, false)
Dan Gohman844731a2008-05-13 00:00:25 +000086
Chris Lattner7a90b682004-10-07 04:16:33 +000087ModulePass *llvm::createGlobalOptimizerPass() { return new GlobalOpt(); }
Chris Lattner079236d2004-02-25 21:34:36 +000088
Dan Gohman844731a2008-05-13 00:00:25 +000089namespace {
90
Chris Lattner7a90b682004-10-07 04:16:33 +000091/// GlobalStatus - As we analyze each global, keep track of some information
92/// about it. If we find out that the address of the global is taken, none of
Chris Lattnercf4d2a52004-10-07 21:30:30 +000093/// this info will be accurate.
Nick Lewycky6726b6d2009-10-25 06:33:48 +000094struct GlobalStatus {
Rafael Espindolac4440e32011-01-19 16:32:21 +000095 /// isCompared - True if the global's address is used in a comparison.
96 bool isCompared;
97
Chris Lattnercf4d2a52004-10-07 21:30:30 +000098 /// isLoaded - True if the global is ever loaded. If the global isn't ever
99 /// loaded it can be deleted.
Chris Lattner7a90b682004-10-07 04:16:33 +0000100 bool isLoaded;
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000101
102 /// StoredType - Keep track of what stores to the global look like.
103 ///
Chris Lattner7a90b682004-10-07 04:16:33 +0000104 enum StoredType {
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000105 /// NotStored - There is no store to this global. It can thus be marked
106 /// constant.
107 NotStored,
108
109 /// isInitializerStored - This global is stored to, but the only thing
110 /// stored is the constant it was initialized with. This is only tracked
111 /// for scalar globals.
112 isInitializerStored,
113
114 /// isStoredOnce - This global is stored to, but only its initializer and
115 /// one other value is ever stored to it. If this global isStoredOnce, we
116 /// track the value stored to it in StoredOnceValue below. This is only
117 /// tracked for scalar globals.
118 isStoredOnce,
119
120 /// isStored - This global is stored to by multiple values or something else
121 /// that we cannot track.
122 isStored
Chris Lattner7a90b682004-10-07 04:16:33 +0000123 } StoredType;
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000124
125 /// StoredOnceValue - If only one value (besides the initializer constant) is
126 /// ever stored to this global, keep track of what value it is.
127 Value *StoredOnceValue;
128
Chris Lattner25de4e52006-11-01 18:03:33 +0000129 /// AccessingFunction/HasMultipleAccessingFunctions - These start out
130 /// null/false. When the first accessing function is noticed, it is recorded.
131 /// When a second different accessing function is noticed,
132 /// HasMultipleAccessingFunctions is set to true.
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000133 const Function *AccessingFunction;
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +0000134 bool HasMultipleAccessingFunctions;
135
Chris Lattner25de4e52006-11-01 18:03:33 +0000136 /// HasNonInstructionUser - Set to true if this global has a user that is not
137 /// an instruction (e.g. a constant expr or GV initializer).
Chris Lattner553ca522005-06-15 21:11:48 +0000138 bool HasNonInstructionUser;
139
Chris Lattner25de4e52006-11-01 18:03:33 +0000140 /// HasPHIUser - Set to true if this global has a user that is a PHI node.
141 bool HasPHIUser;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000142
Rafael Espindolac4440e32011-01-19 16:32:21 +0000143 GlobalStatus() : isCompared(false), isLoaded(false), StoredType(NotStored),
144 StoredOnceValue(0), AccessingFunction(0),
145 HasMultipleAccessingFunctions(false), HasNonInstructionUser(false),
146 HasPHIUser(false) {}
Chris Lattner7a90b682004-10-07 04:16:33 +0000147};
Chris Lattnere47ba742004-10-06 20:57:02 +0000148
Dan Gohman844731a2008-05-13 00:00:25 +0000149}
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000150
Jay Foade3acf152009-06-09 21:37:11 +0000151// SafeToDestroyConstant - It is safe to destroy a constant iff it is only used
152// by constants itself. Note that constants cannot be cyclic, so this test is
153// pretty easy to implement recursively.
154//
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000155static bool SafeToDestroyConstant(const Constant *C) {
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000156 if (isa<GlobalValue>(C)) return false;
157
Gabor Greif27236912010-04-07 18:59:26 +0000158 for (Value::const_use_iterator UI = C->use_begin(), E = C->use_end(); UI != E;
159 ++UI)
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000160 if (const Constant *CU = dyn_cast<Constant>(*UI)) {
Jay Foade3acf152009-06-09 21:37:11 +0000161 if (!SafeToDestroyConstant(CU)) return false;
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000162 } else
163 return false;
164 return true;
165}
166
167
Chris Lattner7a90b682004-10-07 04:16:33 +0000168/// AnalyzeGlobal - Look at all uses of the global and fill in the GlobalStatus
169/// structure. If the global has its address taken, return true to indicate we
170/// can't do anything with it.
Chris Lattner079236d2004-02-25 21:34:36 +0000171///
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000172static bool AnalyzeGlobal(const Value *V, GlobalStatus &GS,
173 SmallPtrSet<const PHINode*, 16> &PHIUsers) {
Gabor Greif27236912010-04-07 18:59:26 +0000174 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;
Gabor Greife6642672010-07-09 16:51:20 +0000175 ++UI) {
176 const User *U = *UI;
177 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
Chris Lattner553ca522005-06-15 21:11:48 +0000178 GS.HasNonInstructionUser = true;
Chris Lattnerd91ed102011-01-01 22:31:46 +0000179
180 // If the result of the constantexpr isn't pointer type, then we won't
181 // know to expect it in various places. Just reject early.
182 if (!isa<PointerType>(CE->getType())) return true;
183
Chris Lattner7a90b682004-10-07 04:16:33 +0000184 if (AnalyzeGlobal(CE, GS, PHIUsers)) return true;
Gabor Greife6642672010-07-09 16:51:20 +0000185 } else if (const Instruction *I = dyn_cast<Instruction>(U)) {
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +0000186 if (!GS.HasMultipleAccessingFunctions) {
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000187 const Function *F = I->getParent()->getParent();
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +0000188 if (GS.AccessingFunction == 0)
189 GS.AccessingFunction = F;
190 else if (GS.AccessingFunction != F)
191 GS.HasMultipleAccessingFunctions = true;
192 }
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000193 if (const LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattner7a90b682004-10-07 04:16:33 +0000194 GS.isLoaded = true;
Chris Lattnerc69d3c92008-01-29 19:01:37 +0000195 if (LI->isVolatile()) return true; // Don't hack on volatile loads.
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000196 } else if (const StoreInst *SI = dyn_cast<StoreInst>(I)) {
Chris Lattner36025492004-10-07 06:01:25 +0000197 // Don't allow a store OF the address, only stores TO the address.
198 if (SI->getOperand(0) == V) return true;
199
Chris Lattnerc69d3c92008-01-29 19:01:37 +0000200 if (SI->isVolatile()) return true; // Don't hack on volatile stores.
201
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000202 // If this is a direct store to the global (i.e., the global is a scalar
203 // value, not an aggregate), keep more specific information about
204 // stores.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000205 if (GS.StoredType != GlobalStatus::isStored) {
Gabor Greif27236912010-04-07 18:59:26 +0000206 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(
207 SI->getOperand(1))) {
Chris Lattnerbd38edf2004-11-14 20:50:30 +0000208 Value *StoredVal = SI->getOperand(0);
209 if (StoredVal == GV->getInitializer()) {
210 if (GS.StoredType < GlobalStatus::isInitializerStored)
211 GS.StoredType = GlobalStatus::isInitializerStored;
212 } else if (isa<LoadInst>(StoredVal) &&
213 cast<LoadInst>(StoredVal)->getOperand(0) == GV) {
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000214 if (GS.StoredType < GlobalStatus::isInitializerStored)
215 GS.StoredType = GlobalStatus::isInitializerStored;
216 } else if (GS.StoredType < GlobalStatus::isStoredOnce) {
217 GS.StoredType = GlobalStatus::isStoredOnce;
Chris Lattnerbd38edf2004-11-14 20:50:30 +0000218 GS.StoredOnceValue = StoredVal;
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000219 } else if (GS.StoredType == GlobalStatus::isStoredOnce &&
Chris Lattnerbd38edf2004-11-14 20:50:30 +0000220 GS.StoredOnceValue == StoredVal) {
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000221 // noop.
222 } else {
223 GS.StoredType = GlobalStatus::isStored;
224 }
225 } else {
Chris Lattner7a90b682004-10-07 04:16:33 +0000226 GS.StoredType = GlobalStatus::isStored;
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000227 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000228 }
Chris Lattner35c81b02005-02-27 18:58:52 +0000229 } else if (isa<GetElementPtrInst>(I)) {
Chris Lattner7a90b682004-10-07 04:16:33 +0000230 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Chris Lattner35c81b02005-02-27 18:58:52 +0000231 } else if (isa<SelectInst>(I)) {
Chris Lattner7a90b682004-10-07 04:16:33 +0000232 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000233 } else if (const PHINode *PN = dyn_cast<PHINode>(I)) {
Chris Lattner7a90b682004-10-07 04:16:33 +0000234 // PHI nodes we can check just like select or GEP instructions, but we
235 // have to be careful about infinite recursion.
Chris Lattner5a6bb6a2008-12-16 07:34:30 +0000236 if (PHIUsers.insert(PN)) // Not already visited.
Chris Lattner7a90b682004-10-07 04:16:33 +0000237 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Chris Lattner25de4e52006-11-01 18:03:33 +0000238 GS.HasPHIUser = true;
Reid Spencere4d87aa2006-12-23 06:05:41 +0000239 } else if (isa<CmpInst>(I)) {
Rafael Espindolac4440e32011-01-19 16:32:21 +0000240 GS.isCompared = true;
Chris Lattner8e108442009-03-08 03:37:35 +0000241 } else if (isa<MemTransferInst>(I)) {
Gabor Greif9e4f2432010-06-24 14:42:01 +0000242 const MemTransferInst *MTI = cast<MemTransferInst>(I);
243 if (MTI->getArgOperand(0) == V)
Eric Christopher551754c2010-04-16 23:37:20 +0000244 GS.StoredType = GlobalStatus::isStored;
Gabor Greif9e4f2432010-06-24 14:42:01 +0000245 if (MTI->getArgOperand(1) == V)
Chris Lattner35c81b02005-02-27 18:58:52 +0000246 GS.isLoaded = true;
Chris Lattner35c81b02005-02-27 18:58:52 +0000247 } else if (isa<MemSetInst>(I)) {
Gabor Greif9e4f2432010-06-24 14:42:01 +0000248 assert(cast<MemSetInst>(I)->getArgOperand(0) == V &&
249 "Memset only takes one pointer!");
Chris Lattner35c81b02005-02-27 18:58:52 +0000250 GS.StoredType = GlobalStatus::isStored;
Chris Lattner7a90b682004-10-07 04:16:33 +0000251 } else {
252 return true; // Any other non-load instruction might take address!
Chris Lattner9ce30002004-07-20 03:58:07 +0000253 }
Gabor Greife6642672010-07-09 16:51:20 +0000254 } else if (const Constant *C = dyn_cast<Constant>(U)) {
Chris Lattner553ca522005-06-15 21:11:48 +0000255 GS.HasNonInstructionUser = true;
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000256 // We might have a dead and dangling constant hanging off of here.
Jay Foade3acf152009-06-09 21:37:11 +0000257 if (!SafeToDestroyConstant(C))
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000258 return true;
Chris Lattner079236d2004-02-25 21:34:36 +0000259 } else {
Chris Lattner553ca522005-06-15 21:11:48 +0000260 GS.HasNonInstructionUser = true;
261 // Otherwise must be some other user.
Chris Lattner079236d2004-02-25 21:34:36 +0000262 return true;
263 }
Gabor Greife6642672010-07-09 16:51:20 +0000264 }
Chris Lattner079236d2004-02-25 21:34:36 +0000265
266 return false;
267}
268
Chris Lattner7b550cc2009-11-06 04:27:31 +0000269static Constant *getAggregateConstantElement(Constant *Agg, Constant *Idx) {
Chris Lattner670c8892004-10-08 17:32:09 +0000270 ConstantInt *CI = dyn_cast<ConstantInt>(Idx);
271 if (!CI) return 0;
Reid Spencerb83eb642006-10-20 07:07:24 +0000272 unsigned IdxV = CI->getZExtValue();
Chris Lattner7a90b682004-10-07 04:16:33 +0000273
Chris Lattner670c8892004-10-08 17:32:09 +0000274 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Agg)) {
275 if (IdxV < CS->getNumOperands()) return CS->getOperand(IdxV);
276 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Agg)) {
277 if (IdxV < CA->getNumOperands()) return CA->getOperand(IdxV);
Reid Spencer9d6565a2007-02-15 02:26:10 +0000278 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Agg)) {
Chris Lattner670c8892004-10-08 17:32:09 +0000279 if (IdxV < CP->getNumOperands()) return CP->getOperand(IdxV);
Chris Lattner7a7ed022004-10-16 18:09:00 +0000280 } else if (isa<ConstantAggregateZero>(Agg)) {
Chris Lattner670c8892004-10-08 17:32:09 +0000281 if (const StructType *STy = dyn_cast<StructType>(Agg->getType())) {
282 if (IdxV < STy->getNumElements())
Owen Andersona7235ea2009-07-31 20:28:14 +0000283 return Constant::getNullValue(STy->getElementType(IdxV));
Chris Lattner670c8892004-10-08 17:32:09 +0000284 } else if (const SequentialType *STy =
285 dyn_cast<SequentialType>(Agg->getType())) {
Owen Andersona7235ea2009-07-31 20:28:14 +0000286 return Constant::getNullValue(STy->getElementType());
Chris Lattner670c8892004-10-08 17:32:09 +0000287 }
Chris Lattner7a7ed022004-10-16 18:09:00 +0000288 } else if (isa<UndefValue>(Agg)) {
289 if (const StructType *STy = dyn_cast<StructType>(Agg->getType())) {
290 if (IdxV < STy->getNumElements())
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000291 return UndefValue::get(STy->getElementType(IdxV));
Chris Lattner7a7ed022004-10-16 18:09:00 +0000292 } else if (const SequentialType *STy =
293 dyn_cast<SequentialType>(Agg->getType())) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000294 return UndefValue::get(STy->getElementType());
Chris Lattner7a7ed022004-10-16 18:09:00 +0000295 }
Chris Lattner670c8892004-10-08 17:32:09 +0000296 }
297 return 0;
298}
Chris Lattner7a90b682004-10-07 04:16:33 +0000299
Chris Lattner7a90b682004-10-07 04:16:33 +0000300
Chris Lattnere47ba742004-10-06 20:57:02 +0000301/// CleanupConstantGlobalUsers - We just marked GV constant. Loop over all
302/// users of the global, cleaning up the obvious ones. This is largely just a
Chris Lattner031955d2004-10-10 16:43:46 +0000303/// quick scan over the use list to clean up the easy and obvious cruft. This
304/// returns true if it made a change.
Chris Lattner7b550cc2009-11-06 04:27:31 +0000305static bool CleanupConstantGlobalUsers(Value *V, Constant *Init) {
Chris Lattner031955d2004-10-10 16:43:46 +0000306 bool Changed = false;
Chris Lattner7a90b682004-10-07 04:16:33 +0000307 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;) {
308 User *U = *UI++;
Misha Brukmanfd939082005-04-21 23:48:37 +0000309
Chris Lattner7a90b682004-10-07 04:16:33 +0000310 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
Chris Lattner35c81b02005-02-27 18:58:52 +0000311 if (Init) {
312 // Replace the load with the initializer.
313 LI->replaceAllUsesWith(Init);
314 LI->eraseFromParent();
315 Changed = true;
316 }
Chris Lattner7a90b682004-10-07 04:16:33 +0000317 } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
Chris Lattnere47ba742004-10-06 20:57:02 +0000318 // Store must be unreachable or storing Init into the global.
Chris Lattner7a7ed022004-10-16 18:09:00 +0000319 SI->eraseFromParent();
Chris Lattner031955d2004-10-10 16:43:46 +0000320 Changed = true;
Chris Lattner7a90b682004-10-07 04:16:33 +0000321 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
322 if (CE->getOpcode() == Instruction::GetElementPtr) {
Chris Lattneraae4a1c2005-09-26 07:34:35 +0000323 Constant *SubInit = 0;
324 if (Init)
Dan Gohmanc6f69e92009-10-05 16:36:26 +0000325 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
Chris Lattner7b550cc2009-11-06 04:27:31 +0000326 Changed |= CleanupConstantGlobalUsers(CE, SubInit);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000327 } else if (CE->getOpcode() == Instruction::BitCast &&
Duncan Sands1df98592010-02-16 11:11:14 +0000328 CE->getType()->isPointerTy()) {
Chris Lattner35c81b02005-02-27 18:58:52 +0000329 // Pointer cast, delete any stores and memsets to the global.
Chris Lattner7b550cc2009-11-06 04:27:31 +0000330 Changed |= CleanupConstantGlobalUsers(CE, 0);
Chris Lattner35c81b02005-02-27 18:58:52 +0000331 }
332
333 if (CE->use_empty()) {
334 CE->destroyConstant();
335 Changed = true;
Chris Lattner7a90b682004-10-07 04:16:33 +0000336 }
337 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
Chris Lattner7b52fe72007-11-09 17:33:02 +0000338 // Do not transform "gepinst (gep constexpr (GV))" here, because forming
339 // "gepconstexpr (gep constexpr (GV))" will cause the two gep's to fold
340 // and will invalidate our notion of what Init is.
Chris Lattner19450242007-11-13 21:46:23 +0000341 Constant *SubInit = 0;
Chris Lattner7b52fe72007-11-09 17:33:02 +0000342 if (!isa<ConstantExpr>(GEP->getOperand(0))) {
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000343 ConstantExpr *CE =
Chris Lattner7b550cc2009-11-06 04:27:31 +0000344 dyn_cast_or_null<ConstantExpr>(ConstantFoldInstruction(GEP));
Chris Lattner7b52fe72007-11-09 17:33:02 +0000345 if (Init && CE && CE->getOpcode() == Instruction::GetElementPtr)
Dan Gohmanc6f69e92009-10-05 16:36:26 +0000346 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
Chris Lattner7b52fe72007-11-09 17:33:02 +0000347 }
Chris Lattner7b550cc2009-11-06 04:27:31 +0000348 Changed |= CleanupConstantGlobalUsers(GEP, SubInit);
Chris Lattnerc4d81b02004-10-10 16:47:33 +0000349
Chris Lattner031955d2004-10-10 16:43:46 +0000350 if (GEP->use_empty()) {
Chris Lattner7a7ed022004-10-16 18:09:00 +0000351 GEP->eraseFromParent();
Chris Lattner031955d2004-10-10 16:43:46 +0000352 Changed = true;
353 }
Chris Lattner35c81b02005-02-27 18:58:52 +0000354 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U)) { // memset/cpy/mv
355 if (MI->getRawDest() == V) {
356 MI->eraseFromParent();
357 Changed = true;
358 }
359
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000360 } else if (Constant *C = dyn_cast<Constant>(U)) {
361 // If we have a chain of dead constantexprs or other things dangling from
362 // us, and if they are all dead, nuke them without remorse.
Jay Foade3acf152009-06-09 21:37:11 +0000363 if (SafeToDestroyConstant(C)) {
Devang Patel743cdf82009-03-06 01:37:41 +0000364 C->destroyConstant();
Chris Lattner35c81b02005-02-27 18:58:52 +0000365 // This could have invalidated UI, start over from scratch.
Chris Lattner7b550cc2009-11-06 04:27:31 +0000366 CleanupConstantGlobalUsers(V, Init);
Chris Lattner031955d2004-10-10 16:43:46 +0000367 return true;
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000368 }
Chris Lattnere47ba742004-10-06 20:57:02 +0000369 }
370 }
Chris Lattner031955d2004-10-10 16:43:46 +0000371 return Changed;
Chris Lattnere47ba742004-10-06 20:57:02 +0000372}
373
Chris Lattner941db492008-01-14 02:09:12 +0000374/// isSafeSROAElementUse - Return true if the specified instruction is a safe
375/// user of a derived expression from a global that we want to SROA.
376static bool isSafeSROAElementUse(Value *V) {
377 // We might have a dead and dangling constant hanging off of here.
378 if (Constant *C = dyn_cast<Constant>(V))
Jay Foade3acf152009-06-09 21:37:11 +0000379 return SafeToDestroyConstant(C);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000380
Chris Lattner941db492008-01-14 02:09:12 +0000381 Instruction *I = dyn_cast<Instruction>(V);
382 if (!I) return false;
383
384 // Loads are ok.
385 if (isa<LoadInst>(I)) return true;
386
387 // Stores *to* the pointer are ok.
388 if (StoreInst *SI = dyn_cast<StoreInst>(I))
389 return SI->getOperand(0) != V;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000390
Chris Lattner941db492008-01-14 02:09:12 +0000391 // Otherwise, it must be a GEP.
392 GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I);
393 if (GEPI == 0) return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000394
Chris Lattner941db492008-01-14 02:09:12 +0000395 if (GEPI->getNumOperands() < 3 || !isa<Constant>(GEPI->getOperand(1)) ||
396 !cast<Constant>(GEPI->getOperand(1))->isNullValue())
397 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000398
Chris Lattner941db492008-01-14 02:09:12 +0000399 for (Value::use_iterator I = GEPI->use_begin(), E = GEPI->use_end();
400 I != E; ++I)
401 if (!isSafeSROAElementUse(*I))
402 return false;
Chris Lattner727c2102008-01-14 01:31:05 +0000403 return true;
404}
405
Chris Lattner941db492008-01-14 02:09:12 +0000406
407/// IsUserOfGlobalSafeForSRA - U is a direct user of the specified global value.
408/// Look at it and its uses and decide whether it is safe to SROA this global.
409///
410static bool IsUserOfGlobalSafeForSRA(User *U, GlobalValue *GV) {
411 // The user of the global must be a GEP Inst or a ConstantExpr GEP.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000412 if (!isa<GetElementPtrInst>(U) &&
413 (!isa<ConstantExpr>(U) ||
Chris Lattner941db492008-01-14 02:09:12 +0000414 cast<ConstantExpr>(U)->getOpcode() != Instruction::GetElementPtr))
415 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000416
Chris Lattner941db492008-01-14 02:09:12 +0000417 // Check to see if this ConstantExpr GEP is SRA'able. In particular, we
418 // don't like < 3 operand CE's, and we don't like non-constant integer
419 // indices. This enforces that all uses are 'gep GV, 0, C, ...' for some
420 // value of C.
421 if (U->getNumOperands() < 3 || !isa<Constant>(U->getOperand(1)) ||
422 !cast<Constant>(U->getOperand(1))->isNullValue() ||
423 !isa<ConstantInt>(U->getOperand(2)))
424 return false;
425
426 gep_type_iterator GEPI = gep_type_begin(U), E = gep_type_end(U);
427 ++GEPI; // Skip over the pointer index.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000428
Chris Lattner941db492008-01-14 02:09:12 +0000429 // If this is a use of an array allocation, do a bit more checking for sanity.
430 if (const ArrayType *AT = dyn_cast<ArrayType>(*GEPI)) {
431 uint64_t NumElements = AT->getNumElements();
432 ConstantInt *Idx = cast<ConstantInt>(U->getOperand(2));
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000433
Chris Lattner941db492008-01-14 02:09:12 +0000434 // Check to make sure that index falls within the array. If not,
435 // something funny is going on, so we won't do the optimization.
436 //
437 if (Idx->getZExtValue() >= NumElements)
438 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000439
Chris Lattner941db492008-01-14 02:09:12 +0000440 // We cannot scalar repl this level of the array unless any array
441 // sub-indices are in-range constants. In particular, consider:
442 // A[0][i]. We cannot know that the user isn't doing invalid things like
443 // allowing i to index an out-of-range subscript that accesses A[1].
444 //
445 // Scalar replacing *just* the outer index of the array is probably not
446 // going to be a win anyway, so just give up.
447 for (++GEPI; // Skip array index.
Dan Gohman6874a2a2009-08-18 14:58:19 +0000448 GEPI != E;
Chris Lattner941db492008-01-14 02:09:12 +0000449 ++GEPI) {
450 uint64_t NumElements;
451 if (const ArrayType *SubArrayTy = dyn_cast<ArrayType>(*GEPI))
452 NumElements = SubArrayTy->getNumElements();
Dan Gohman6874a2a2009-08-18 14:58:19 +0000453 else if (const VectorType *SubVectorTy = dyn_cast<VectorType>(*GEPI))
454 NumElements = SubVectorTy->getNumElements();
455 else {
Duncan Sands1df98592010-02-16 11:11:14 +0000456 assert((*GEPI)->isStructTy() &&
Dan Gohman6874a2a2009-08-18 14:58:19 +0000457 "Indexed GEP type is not array, vector, or struct!");
458 continue;
459 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000460
Chris Lattner941db492008-01-14 02:09:12 +0000461 ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPI.getOperand());
462 if (!IdxVal || IdxVal->getZExtValue() >= NumElements)
463 return false;
464 }
465 }
466
467 for (Value::use_iterator I = U->use_begin(), E = U->use_end(); I != E; ++I)
468 if (!isSafeSROAElementUse(*I))
469 return false;
470 return true;
471}
472
473/// GlobalUsersSafeToSRA - Look at all uses of the global and decide whether it
474/// is safe for us to perform this transformation.
475///
476static bool GlobalUsersSafeToSRA(GlobalValue *GV) {
477 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end();
478 UI != E; ++UI) {
479 if (!IsUserOfGlobalSafeForSRA(*UI, GV))
480 return false;
481 }
482 return true;
483}
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000484
Chris Lattner941db492008-01-14 02:09:12 +0000485
Chris Lattner670c8892004-10-08 17:32:09 +0000486/// SRAGlobal - Perform scalar replacement of aggregates on the specified global
487/// variable. This opens the door for other optimizations by exposing the
488/// behavior of the program in a more fine-grained way. We have determined that
489/// this transformation is safe already. We return the first global variable we
490/// insert so that the caller can reprocess it.
Chris Lattner7b550cc2009-11-06 04:27:31 +0000491static GlobalVariable *SRAGlobal(GlobalVariable *GV, const TargetData &TD) {
Chris Lattner727c2102008-01-14 01:31:05 +0000492 // Make sure this global only has simple uses that we can SRA.
Chris Lattner941db492008-01-14 02:09:12 +0000493 if (!GlobalUsersSafeToSRA(GV))
Chris Lattner727c2102008-01-14 01:31:05 +0000494 return 0;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000495
Rafael Espindolabb46f522009-01-15 20:18:42 +0000496 assert(GV->hasLocalLinkage() && !GV->isConstant());
Chris Lattner670c8892004-10-08 17:32:09 +0000497 Constant *Init = GV->getInitializer();
498 const Type *Ty = Init->getType();
Misha Brukmanfd939082005-04-21 23:48:37 +0000499
Chris Lattner670c8892004-10-08 17:32:09 +0000500 std::vector<GlobalVariable*> NewGlobals;
501 Module::GlobalListType &Globals = GV->getParent()->getGlobalList();
502
Chris Lattner998182b2008-04-26 07:40:11 +0000503 // Get the alignment of the global, either explicit or target-specific.
504 unsigned StartAlignment = GV->getAlignment();
505 if (StartAlignment == 0)
506 StartAlignment = TD.getABITypeAlignment(GV->getType());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000507
Chris Lattner670c8892004-10-08 17:32:09 +0000508 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
509 NewGlobals.reserve(STy->getNumElements());
Chris Lattner998182b2008-04-26 07:40:11 +0000510 const StructLayout &Layout = *TD.getStructLayout(STy);
Chris Lattner670c8892004-10-08 17:32:09 +0000511 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
512 Constant *In = getAggregateConstantElement(Init,
Chris Lattner7b550cc2009-11-06 04:27:31 +0000513 ConstantInt::get(Type::getInt32Ty(STy->getContext()), i));
Chris Lattner670c8892004-10-08 17:32:09 +0000514 assert(In && "Couldn't get element of initializer?");
Chris Lattner7b550cc2009-11-06 04:27:31 +0000515 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(i), false,
Chris Lattner670c8892004-10-08 17:32:09 +0000516 GlobalVariable::InternalLinkage,
Daniel Dunbarfe09b202009-07-30 17:37:43 +0000517 In, GV->getName()+"."+Twine(i),
Matthijs Kooijmanbc1f9892008-07-17 11:59:53 +0000518 GV->isThreadLocal(),
Owen Anderson3d29df32009-07-08 01:26:06 +0000519 GV->getType()->getAddressSpace());
Chris Lattner670c8892004-10-08 17:32:09 +0000520 Globals.insert(GV, NGV);
521 NewGlobals.push_back(NGV);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000522
Chris Lattner998182b2008-04-26 07:40:11 +0000523 // Calculate the known alignment of the field. If the original aggregate
524 // had 256 byte alignment for example, something might depend on that:
525 // propagate info to each field.
526 uint64_t FieldOffset = Layout.getElementOffset(i);
527 unsigned NewAlign = (unsigned)MinAlign(StartAlignment, FieldOffset);
528 if (NewAlign > TD.getABITypeAlignment(STy->getElementType(i)))
529 NGV->setAlignment(NewAlign);
Chris Lattner670c8892004-10-08 17:32:09 +0000530 }
531 } else if (const SequentialType *STy = dyn_cast<SequentialType>(Ty)) {
532 unsigned NumElements = 0;
533 if (const ArrayType *ATy = dyn_cast<ArrayType>(STy))
534 NumElements = ATy->getNumElements();
Chris Lattner670c8892004-10-08 17:32:09 +0000535 else
Chris Lattner998182b2008-04-26 07:40:11 +0000536 NumElements = cast<VectorType>(STy)->getNumElements();
Chris Lattner670c8892004-10-08 17:32:09 +0000537
Chris Lattner1f21ef12005-02-23 16:53:04 +0000538 if (NumElements > 16 && GV->hasNUsesOrMore(16))
Chris Lattnerd514d822005-02-01 01:23:31 +0000539 return 0; // It's not worth it.
Chris Lattner670c8892004-10-08 17:32:09 +0000540 NewGlobals.reserve(NumElements);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000541
Duncan Sands777d2302009-05-09 07:06:46 +0000542 uint64_t EltSize = TD.getTypeAllocSize(STy->getElementType());
Chris Lattner998182b2008-04-26 07:40:11 +0000543 unsigned EltAlign = TD.getABITypeAlignment(STy->getElementType());
Chris Lattner670c8892004-10-08 17:32:09 +0000544 for (unsigned i = 0, e = NumElements; i != e; ++i) {
545 Constant *In = getAggregateConstantElement(Init,
Chris Lattner7b550cc2009-11-06 04:27:31 +0000546 ConstantInt::get(Type::getInt32Ty(Init->getContext()), i));
Chris Lattner670c8892004-10-08 17:32:09 +0000547 assert(In && "Couldn't get element of initializer?");
548
Chris Lattner7b550cc2009-11-06 04:27:31 +0000549 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(), false,
Chris Lattner670c8892004-10-08 17:32:09 +0000550 GlobalVariable::InternalLinkage,
Daniel Dunbarfe09b202009-07-30 17:37:43 +0000551 In, GV->getName()+"."+Twine(i),
Matthijs Kooijmanbc1f9892008-07-17 11:59:53 +0000552 GV->isThreadLocal(),
Owen Andersone9b11b42009-07-08 19:03:57 +0000553 GV->getType()->getAddressSpace());
Chris Lattner670c8892004-10-08 17:32:09 +0000554 Globals.insert(GV, NGV);
555 NewGlobals.push_back(NGV);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000556
Chris Lattner998182b2008-04-26 07:40:11 +0000557 // Calculate the known alignment of the field. If the original aggregate
558 // had 256 byte alignment for example, something might depend on that:
559 // propagate info to each field.
560 unsigned NewAlign = (unsigned)MinAlign(StartAlignment, EltSize*i);
561 if (NewAlign > EltAlign)
562 NGV->setAlignment(NewAlign);
Chris Lattner670c8892004-10-08 17:32:09 +0000563 }
564 }
565
566 if (NewGlobals.empty())
567 return 0;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000568
David Greene3215b0e2010-01-05 01:28:05 +0000569 DEBUG(dbgs() << "PERFORMING GLOBAL SRA ON: " << *GV);
Chris Lattner30ba5692004-10-11 05:54:41 +0000570
Chris Lattner7b550cc2009-11-06 04:27:31 +0000571 Constant *NullInt =Constant::getNullValue(Type::getInt32Ty(GV->getContext()));
Chris Lattner670c8892004-10-08 17:32:09 +0000572
573 // Loop over all of the uses of the global, replacing the constantexpr geps,
574 // with smaller constantexpr geps or direct references.
575 while (!GV->use_empty()) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000576 User *GEP = GV->use_back();
577 assert(((isa<ConstantExpr>(GEP) &&
578 cast<ConstantExpr>(GEP)->getOpcode()==Instruction::GetElementPtr)||
579 isa<GetElementPtrInst>(GEP)) && "NonGEP CE's are not SRAable!");
Misha Brukmanfd939082005-04-21 23:48:37 +0000580
Chris Lattner670c8892004-10-08 17:32:09 +0000581 // Ignore the 1th operand, which has to be zero or else the program is quite
582 // broken (undefined). Get the 2nd operand, which is the structure or array
583 // index.
Reid Spencerb83eb642006-10-20 07:07:24 +0000584 unsigned Val = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
Chris Lattner670c8892004-10-08 17:32:09 +0000585 if (Val >= NewGlobals.size()) Val = 0; // Out of bound array access.
586
Chris Lattner30ba5692004-10-11 05:54:41 +0000587 Value *NewPtr = NewGlobals[Val];
Chris Lattner670c8892004-10-08 17:32:09 +0000588
589 // Form a shorter GEP if needed.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000590 if (GEP->getNumOperands() > 3) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000591 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEP)) {
Chris Lattner55eb1c42007-01-31 04:40:53 +0000592 SmallVector<Constant*, 8> Idxs;
Chris Lattner30ba5692004-10-11 05:54:41 +0000593 Idxs.push_back(NullInt);
594 for (unsigned i = 3, e = CE->getNumOperands(); i != e; ++i)
595 Idxs.push_back(CE->getOperand(i));
Owen Andersonbaf3c402009-07-29 18:55:55 +0000596 NewPtr = ConstantExpr::getGetElementPtr(cast<Constant>(NewPtr),
Chris Lattner55eb1c42007-01-31 04:40:53 +0000597 &Idxs[0], Idxs.size());
Chris Lattner30ba5692004-10-11 05:54:41 +0000598 } else {
599 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(GEP);
Chris Lattner699d1442007-01-31 19:59:55 +0000600 SmallVector<Value*, 8> Idxs;
Chris Lattner30ba5692004-10-11 05:54:41 +0000601 Idxs.push_back(NullInt);
602 for (unsigned i = 3, e = GEPI->getNumOperands(); i != e; ++i)
603 Idxs.push_back(GEPI->getOperand(i));
Gabor Greif051a9502008-04-06 20:25:17 +0000604 NewPtr = GetElementPtrInst::Create(NewPtr, Idxs.begin(), Idxs.end(),
Daniel Dunbarfe09b202009-07-30 17:37:43 +0000605 GEPI->getName()+"."+Twine(Val),GEPI);
Chris Lattner30ba5692004-10-11 05:54:41 +0000606 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000607 }
Chris Lattner30ba5692004-10-11 05:54:41 +0000608 GEP->replaceAllUsesWith(NewPtr);
609
610 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(GEP))
Chris Lattner7a7ed022004-10-16 18:09:00 +0000611 GEPI->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +0000612 else
613 cast<ConstantExpr>(GEP)->destroyConstant();
Chris Lattner670c8892004-10-08 17:32:09 +0000614 }
615
Chris Lattnere40e2d12004-10-08 20:25:55 +0000616 // Delete the old global, now that it is dead.
617 Globals.erase(GV);
Chris Lattner670c8892004-10-08 17:32:09 +0000618 ++NumSRA;
Chris Lattner30ba5692004-10-11 05:54:41 +0000619
620 // Loop over the new globals array deleting any globals that are obviously
621 // dead. This can arise due to scalarization of a structure or an array that
622 // has elements that are dead.
623 unsigned FirstGlobal = 0;
624 for (unsigned i = 0, e = NewGlobals.size(); i != e; ++i)
625 if (NewGlobals[i]->use_empty()) {
626 Globals.erase(NewGlobals[i]);
627 if (FirstGlobal == i) ++FirstGlobal;
628 }
629
630 return FirstGlobal != NewGlobals.size() ? NewGlobals[FirstGlobal] : 0;
Chris Lattner670c8892004-10-08 17:32:09 +0000631}
632
Chris Lattner9b34a612004-10-09 21:48:45 +0000633/// AllUsesOfValueWillTrapIfNull - Return true if all users of the specified
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000634/// value will trap if the value is dynamically null. PHIs keeps track of any
Chris Lattner81686182007-09-13 16:30:19 +0000635/// phi nodes we've seen to avoid reprocessing them.
Gabor Greif6ce02b52010-04-06 19:24:18 +0000636static bool AllUsesOfValueWillTrapIfNull(const Value *V,
637 SmallPtrSet<const PHINode*, 8> &PHIs) {
638 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;
Gabor Greifa01d6db2010-04-06 19:14:05 +0000639 ++UI) {
Gabor Greif6ce02b52010-04-06 19:24:18 +0000640 const User *U = *UI;
Gabor Greifa01d6db2010-04-06 19:14:05 +0000641
642 if (isa<LoadInst>(U)) {
Chris Lattner9b34a612004-10-09 21:48:45 +0000643 // Will trap.
Gabor Greif6ce02b52010-04-06 19:24:18 +0000644 } else if (const StoreInst *SI = dyn_cast<StoreInst>(U)) {
Chris Lattner9b34a612004-10-09 21:48:45 +0000645 if (SI->getOperand(0) == V) {
Gabor Greifa01d6db2010-04-06 19:14:05 +0000646 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner9b34a612004-10-09 21:48:45 +0000647 return false; // Storing the value.
648 }
Gabor Greif6ce02b52010-04-06 19:24:18 +0000649 } else if (const CallInst *CI = dyn_cast<CallInst>(U)) {
Gabor Greif654c06f2010-03-20 21:00:25 +0000650 if (CI->getCalledValue() != V) {
Gabor Greifa01d6db2010-04-06 19:14:05 +0000651 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner9b34a612004-10-09 21:48:45 +0000652 return false; // Not calling the ptr
653 }
Gabor Greif6ce02b52010-04-06 19:24:18 +0000654 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(U)) {
Gabor Greif654c06f2010-03-20 21:00:25 +0000655 if (II->getCalledValue() != V) {
Gabor Greifa01d6db2010-04-06 19:14:05 +0000656 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner9b34a612004-10-09 21:48:45 +0000657 return false; // Not calling the ptr
658 }
Gabor Greif6ce02b52010-04-06 19:24:18 +0000659 } else if (const BitCastInst *CI = dyn_cast<BitCastInst>(U)) {
Chris Lattner81686182007-09-13 16:30:19 +0000660 if (!AllUsesOfValueWillTrapIfNull(CI, PHIs)) return false;
Gabor Greif6ce02b52010-04-06 19:24:18 +0000661 } else if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
Chris Lattner81686182007-09-13 16:30:19 +0000662 if (!AllUsesOfValueWillTrapIfNull(GEPI, PHIs)) return false;
Gabor Greif6ce02b52010-04-06 19:24:18 +0000663 } else if (const PHINode *PN = dyn_cast<PHINode>(U)) {
Chris Lattner81686182007-09-13 16:30:19 +0000664 // If we've already seen this phi node, ignore it, it has already been
665 // checked.
Jakob Stoklund Olesenb489d0f2010-01-29 23:54:14 +0000666 if (PHIs.insert(PN) && !AllUsesOfValueWillTrapIfNull(PN, PHIs))
667 return false;
Gabor Greifa01d6db2010-04-06 19:14:05 +0000668 } else if (isa<ICmpInst>(U) &&
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000669 isa<ConstantPointerNull>(UI->getOperand(1))) {
Nick Lewyckye7ee59b2010-02-25 06:39:10 +0000670 // Ignore icmp X, null
Chris Lattner9b34a612004-10-09 21:48:45 +0000671 } else {
Gabor Greifa01d6db2010-04-06 19:14:05 +0000672 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner9b34a612004-10-09 21:48:45 +0000673 return false;
674 }
Gabor Greifa01d6db2010-04-06 19:14:05 +0000675 }
Chris Lattner9b34a612004-10-09 21:48:45 +0000676 return true;
677}
678
679/// AllUsesOfLoadedValueWillTrapIfNull - Return true if all uses of any loads
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000680/// from GV will trap if the loaded value is null. Note that this also permits
681/// comparisons of the loaded value against null, as a special case.
Gabor Greif6ce02b52010-04-06 19:24:18 +0000682static bool AllUsesOfLoadedValueWillTrapIfNull(const GlobalVariable *GV) {
683 for (Value::const_use_iterator UI = GV->use_begin(), E = GV->use_end();
Gabor Greifa01d6db2010-04-06 19:14:05 +0000684 UI != E; ++UI) {
Gabor Greif6ce02b52010-04-06 19:24:18 +0000685 const User *U = *UI;
Gabor Greifa01d6db2010-04-06 19:14:05 +0000686
Gabor Greif6ce02b52010-04-06 19:24:18 +0000687 if (const LoadInst *LI = dyn_cast<LoadInst>(U)) {
688 SmallPtrSet<const PHINode*, 8> PHIs;
Chris Lattner81686182007-09-13 16:30:19 +0000689 if (!AllUsesOfValueWillTrapIfNull(LI, PHIs))
Chris Lattner9b34a612004-10-09 21:48:45 +0000690 return false;
Gabor Greifa01d6db2010-04-06 19:14:05 +0000691 } else if (isa<StoreInst>(U)) {
Chris Lattner9b34a612004-10-09 21:48:45 +0000692 // Ignore stores to the global.
693 } else {
694 // We don't know or understand this user, bail out.
Gabor Greifa01d6db2010-04-06 19:14:05 +0000695 //cerr << "UNKNOWN USER OF GLOBAL!: " << *U;
Chris Lattner9b34a612004-10-09 21:48:45 +0000696 return false;
697 }
Gabor Greifa01d6db2010-04-06 19:14:05 +0000698 }
Chris Lattner9b34a612004-10-09 21:48:45 +0000699 return true;
700}
701
Chris Lattner7b550cc2009-11-06 04:27:31 +0000702static bool OptimizeAwayTrappingUsesOfValue(Value *V, Constant *NewV) {
Chris Lattner708148e2004-10-10 23:14:11 +0000703 bool Changed = false;
704 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ) {
705 Instruction *I = cast<Instruction>(*UI++);
706 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
707 LI->setOperand(0, NewV);
708 Changed = true;
709 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
710 if (SI->getOperand(1) == V) {
711 SI->setOperand(1, NewV);
712 Changed = true;
713 }
714 } else if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
Gabor Greiffa1f5c22010-04-06 18:45:08 +0000715 CallSite CS(I);
716 if (CS.getCalledValue() == V) {
Chris Lattner708148e2004-10-10 23:14:11 +0000717 // Calling through the pointer! Turn into a direct call, but be careful
718 // that the pointer is not also being passed as an argument.
Gabor Greiffa1f5c22010-04-06 18:45:08 +0000719 CS.setCalledFunction(NewV);
Chris Lattner708148e2004-10-10 23:14:11 +0000720 Changed = true;
721 bool PassedAsArg = false;
Gabor Greiffa1f5c22010-04-06 18:45:08 +0000722 for (unsigned i = 0, e = CS.arg_size(); i != e; ++i)
723 if (CS.getArgument(i) == V) {
Chris Lattner708148e2004-10-10 23:14:11 +0000724 PassedAsArg = true;
Gabor Greiffa1f5c22010-04-06 18:45:08 +0000725 CS.setArgument(i, NewV);
Chris Lattner708148e2004-10-10 23:14:11 +0000726 }
727
728 if (PassedAsArg) {
729 // Being passed as an argument also. Be careful to not invalidate UI!
730 UI = V->use_begin();
731 }
732 }
733 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
734 Changed |= OptimizeAwayTrappingUsesOfValue(CI,
Owen Andersonbaf3c402009-07-29 18:55:55 +0000735 ConstantExpr::getCast(CI->getOpcode(),
Chris Lattner7b550cc2009-11-06 04:27:31 +0000736 NewV, CI->getType()));
Chris Lattner708148e2004-10-10 23:14:11 +0000737 if (CI->use_empty()) {
738 Changed = true;
Chris Lattner7a7ed022004-10-16 18:09:00 +0000739 CI->eraseFromParent();
Chris Lattner708148e2004-10-10 23:14:11 +0000740 }
741 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
742 // Should handle GEP here.
Chris Lattner55eb1c42007-01-31 04:40:53 +0000743 SmallVector<Constant*, 8> Idxs;
744 Idxs.reserve(GEPI->getNumOperands()-1);
Gabor Greif5e463212008-05-29 01:59:18 +0000745 for (User::op_iterator i = GEPI->op_begin() + 1, e = GEPI->op_end();
746 i != e; ++i)
747 if (Constant *C = dyn_cast<Constant>(*i))
Chris Lattner55eb1c42007-01-31 04:40:53 +0000748 Idxs.push_back(C);
Chris Lattner708148e2004-10-10 23:14:11 +0000749 else
750 break;
Chris Lattner55eb1c42007-01-31 04:40:53 +0000751 if (Idxs.size() == GEPI->getNumOperands()-1)
Chris Lattner708148e2004-10-10 23:14:11 +0000752 Changed |= OptimizeAwayTrappingUsesOfValue(GEPI,
Owen Andersonbaf3c402009-07-29 18:55:55 +0000753 ConstantExpr::getGetElementPtr(NewV, &Idxs[0],
Chris Lattner7b550cc2009-11-06 04:27:31 +0000754 Idxs.size()));
Chris Lattner708148e2004-10-10 23:14:11 +0000755 if (GEPI->use_empty()) {
756 Changed = true;
Chris Lattner7a7ed022004-10-16 18:09:00 +0000757 GEPI->eraseFromParent();
Chris Lattner708148e2004-10-10 23:14:11 +0000758 }
759 }
760 }
761
762 return Changed;
763}
764
765
766/// OptimizeAwayTrappingUsesOfLoads - The specified global has only one non-null
767/// value stored into it. If there are uses of the loaded value that would trap
768/// if the loaded value is dynamically null, then we know that they cannot be
769/// reachable with a null optimize away the load.
Chris Lattner7b550cc2009-11-06 04:27:31 +0000770static bool OptimizeAwayTrappingUsesOfLoads(GlobalVariable *GV, Constant *LV) {
Chris Lattner708148e2004-10-10 23:14:11 +0000771 bool Changed = false;
772
Chris Lattner92c6bd22009-01-14 00:12:58 +0000773 // Keep track of whether we are able to remove all the uses of the global
774 // other than the store that defines it.
775 bool AllNonStoreUsesGone = true;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000776
Chris Lattner708148e2004-10-10 23:14:11 +0000777 // Replace all uses of loads with uses of uses of the stored value.
Chris Lattner92c6bd22009-01-14 00:12:58 +0000778 for (Value::use_iterator GUI = GV->use_begin(), E = GV->use_end(); GUI != E;){
779 User *GlobalUser = *GUI++;
780 if (LoadInst *LI = dyn_cast<LoadInst>(GlobalUser)) {
Chris Lattner7b550cc2009-11-06 04:27:31 +0000781 Changed |= OptimizeAwayTrappingUsesOfValue(LI, LV);
Chris Lattner92c6bd22009-01-14 00:12:58 +0000782 // If we were able to delete all uses of the loads
783 if (LI->use_empty()) {
784 LI->eraseFromParent();
785 Changed = true;
786 } else {
787 AllNonStoreUsesGone = false;
788 }
789 } else if (isa<StoreInst>(GlobalUser)) {
790 // Ignore the store that stores "LV" to the global.
791 assert(GlobalUser->getOperand(1) == GV &&
792 "Must be storing *to* the global");
Chris Lattner708148e2004-10-10 23:14:11 +0000793 } else {
Chris Lattner92c6bd22009-01-14 00:12:58 +0000794 AllNonStoreUsesGone = false;
795
796 // If we get here we could have other crazy uses that are transitively
797 // loaded.
798 assert((isa<PHINode>(GlobalUser) || isa<SelectInst>(GlobalUser) ||
799 isa<ConstantExpr>(GlobalUser)) && "Only expect load and stores!");
Chris Lattner708148e2004-10-10 23:14:11 +0000800 }
Chris Lattner92c6bd22009-01-14 00:12:58 +0000801 }
Chris Lattner708148e2004-10-10 23:14:11 +0000802
803 if (Changed) {
David Greene3215b0e2010-01-05 01:28:05 +0000804 DEBUG(dbgs() << "OPTIMIZED LOADS FROM STORED ONCE POINTER: " << *GV);
Chris Lattner708148e2004-10-10 23:14:11 +0000805 ++NumGlobUses;
806 }
807
Chris Lattner708148e2004-10-10 23:14:11 +0000808 // If we nuked all of the loads, then none of the stores are needed either,
809 // nor is the global.
Chris Lattner92c6bd22009-01-14 00:12:58 +0000810 if (AllNonStoreUsesGone) {
David Greene3215b0e2010-01-05 01:28:05 +0000811 DEBUG(dbgs() << " *** GLOBAL NOW DEAD!\n");
Chris Lattner7b550cc2009-11-06 04:27:31 +0000812 CleanupConstantGlobalUsers(GV, 0);
Chris Lattner708148e2004-10-10 23:14:11 +0000813 if (GV->use_empty()) {
Chris Lattner7a7ed022004-10-16 18:09:00 +0000814 GV->eraseFromParent();
Chris Lattner708148e2004-10-10 23:14:11 +0000815 ++NumDeleted;
816 }
817 Changed = true;
818 }
819 return Changed;
820}
821
Chris Lattner30ba5692004-10-11 05:54:41 +0000822/// ConstantPropUsersOf - Walk the use list of V, constant folding all of the
823/// instructions that are foldable.
Chris Lattner7b550cc2009-11-06 04:27:31 +0000824static void ConstantPropUsersOf(Value *V) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000825 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; )
826 if (Instruction *I = dyn_cast<Instruction>(*UI++))
Chris Lattner7b550cc2009-11-06 04:27:31 +0000827 if (Constant *NewC = ConstantFoldInstruction(I)) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000828 I->replaceAllUsesWith(NewC);
829
Chris Lattnerd514d822005-02-01 01:23:31 +0000830 // Advance UI to the next non-I use to avoid invalidating it!
831 // Instructions could multiply use V.
832 while (UI != E && *UI == I)
Chris Lattner30ba5692004-10-11 05:54:41 +0000833 ++UI;
Chris Lattnerd514d822005-02-01 01:23:31 +0000834 I->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +0000835 }
836}
837
838/// OptimizeGlobalAddressOfMalloc - This function takes the specified global
839/// variable, and transforms the program as if it always contained the result of
840/// the specified malloc. Because it is always the result of the specified
841/// malloc, there is no reason to actually DO the malloc. Instead, turn the
Chris Lattner6e8fbad2006-11-30 17:32:29 +0000842/// malloc into a global, and any loads of GV as uses of the new global.
Chris Lattner30ba5692004-10-11 05:54:41 +0000843static GlobalVariable *OptimizeGlobalAddressOfMalloc(GlobalVariable *GV,
Victor Hernandez83d63912009-09-18 22:35:49 +0000844 CallInst *CI,
Victor Hernandez9d0b7042009-11-07 00:16:28 +0000845 const Type *AllocTy,
Chris Lattnera6874652010-02-25 22:33:52 +0000846 ConstantInt *NElements,
Victor Hernandez83d63912009-09-18 22:35:49 +0000847 TargetData* TD) {
Chris Lattnera6874652010-02-25 22:33:52 +0000848 DEBUG(errs() << "PROMOTING GLOBAL: " << *GV << " CALL = " << *CI << '\n');
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000849
Chris Lattnera6874652010-02-25 22:33:52 +0000850 const Type *GlobalType;
851 if (NElements->getZExtValue() == 1)
852 GlobalType = AllocTy;
853 else
854 // If we have an array allocation, the global variable is of an array.
855 GlobalType = ArrayType::get(AllocTy, NElements->getZExtValue());
Victor Hernandez83d63912009-09-18 22:35:49 +0000856
857 // Create the new global variable. The contents of the malloc'd memory is
858 // undefined, so initialize with an undef value.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000859 GlobalVariable *NewGV = new GlobalVariable(*GV->getParent(),
Chris Lattnere9fd4442010-02-26 23:42:13 +0000860 GlobalType, false,
Chris Lattnera6874652010-02-25 22:33:52 +0000861 GlobalValue::InternalLinkage,
Chris Lattnere9fd4442010-02-26 23:42:13 +0000862 UndefValue::get(GlobalType),
Victor Hernandez83d63912009-09-18 22:35:49 +0000863 GV->getName()+".body",
864 GV,
865 GV->isThreadLocal());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000866
Chris Lattnera6874652010-02-25 22:33:52 +0000867 // If there are bitcast users of the malloc (which is typical, usually we have
868 // a malloc + bitcast) then replace them with uses of the new global. Update
869 // other users to use the global as well.
870 BitCastInst *TheBC = 0;
871 while (!CI->use_empty()) {
872 Instruction *User = cast<Instruction>(CI->use_back());
873 if (BitCastInst *BCI = dyn_cast<BitCastInst>(User)) {
874 if (BCI->getType() == NewGV->getType()) {
875 BCI->replaceAllUsesWith(NewGV);
876 BCI->eraseFromParent();
877 } else {
878 BCI->setOperand(0, NewGV);
879 }
880 } else {
881 if (TheBC == 0)
882 TheBC = new BitCastInst(NewGV, CI->getType(), "newgv", CI);
883 User->replaceUsesOfWith(CI, TheBC);
884 }
885 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000886
Victor Hernandez83d63912009-09-18 22:35:49 +0000887 Constant *RepValue = NewGV;
888 if (NewGV->getType() != GV->getType()->getElementType())
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000889 RepValue = ConstantExpr::getBitCast(RepValue,
Victor Hernandez83d63912009-09-18 22:35:49 +0000890 GV->getType()->getElementType());
891
892 // If there is a comparison against null, we will insert a global bool to
893 // keep track of whether the global was initialized yet or not.
894 GlobalVariable *InitBool =
Chris Lattner7b550cc2009-11-06 04:27:31 +0000895 new GlobalVariable(Type::getInt1Ty(GV->getContext()), false,
Victor Hernandez83d63912009-09-18 22:35:49 +0000896 GlobalValue::InternalLinkage,
Chris Lattner7b550cc2009-11-06 04:27:31 +0000897 ConstantInt::getFalse(GV->getContext()),
898 GV->getName()+".init", GV->isThreadLocal());
Victor Hernandez83d63912009-09-18 22:35:49 +0000899 bool InitBoolUsed = false;
900
901 // Loop over all uses of GV, processing them in turn.
Chris Lattnera6874652010-02-25 22:33:52 +0000902 while (!GV->use_empty()) {
903 if (StoreInst *SI = dyn_cast<StoreInst>(GV->use_back())) {
Victor Hernandez83d63912009-09-18 22:35:49 +0000904 // The global is initialized when the store to it occurs.
Chris Lattner7b550cc2009-11-06 04:27:31 +0000905 new StoreInst(ConstantInt::getTrue(GV->getContext()), InitBool, SI);
Victor Hernandez83d63912009-09-18 22:35:49 +0000906 SI->eraseFromParent();
Chris Lattnera6874652010-02-25 22:33:52 +0000907 continue;
Victor Hernandez83d63912009-09-18 22:35:49 +0000908 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000909
Chris Lattnera6874652010-02-25 22:33:52 +0000910 LoadInst *LI = cast<LoadInst>(GV->use_back());
911 while (!LI->use_empty()) {
912 Use &LoadUse = LI->use_begin().getUse();
913 if (!isa<ICmpInst>(LoadUse.getUser())) {
914 LoadUse = RepValue;
915 continue;
916 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000917
Chris Lattnera6874652010-02-25 22:33:52 +0000918 ICmpInst *ICI = cast<ICmpInst>(LoadUse.getUser());
919 // Replace the cmp X, 0 with a use of the bool value.
920 Value *LV = new LoadInst(InitBool, InitBool->getName()+".val", ICI);
921 InitBoolUsed = true;
922 switch (ICI->getPredicate()) {
923 default: llvm_unreachable("Unknown ICmp Predicate!");
924 case ICmpInst::ICMP_ULT:
925 case ICmpInst::ICMP_SLT: // X < null -> always false
926 LV = ConstantInt::getFalse(GV->getContext());
927 break;
928 case ICmpInst::ICMP_ULE:
929 case ICmpInst::ICMP_SLE:
930 case ICmpInst::ICMP_EQ:
931 LV = BinaryOperator::CreateNot(LV, "notinit", ICI);
932 break;
933 case ICmpInst::ICMP_NE:
934 case ICmpInst::ICMP_UGE:
935 case ICmpInst::ICMP_SGE:
936 case ICmpInst::ICMP_UGT:
937 case ICmpInst::ICMP_SGT:
938 break; // no change.
939 }
940 ICI->replaceAllUsesWith(LV);
941 ICI->eraseFromParent();
942 }
943 LI->eraseFromParent();
944 }
Victor Hernandez83d63912009-09-18 22:35:49 +0000945
946 // If the initialization boolean was used, insert it, otherwise delete it.
947 if (!InitBoolUsed) {
948 while (!InitBool->use_empty()) // Delete initializations
Chris Lattnera6874652010-02-25 22:33:52 +0000949 cast<StoreInst>(InitBool->use_back())->eraseFromParent();
Victor Hernandez83d63912009-09-18 22:35:49 +0000950 delete InitBool;
951 } else
952 GV->getParent()->getGlobalList().insert(GV, InitBool);
953
Chris Lattnera6874652010-02-25 22:33:52 +0000954 // Now the GV is dead, nuke it and the malloc..
Victor Hernandez83d63912009-09-18 22:35:49 +0000955 GV->eraseFromParent();
Victor Hernandez83d63912009-09-18 22:35:49 +0000956 CI->eraseFromParent();
957
958 // To further other optimizations, loop over all users of NewGV and try to
959 // constant prop them. This will promote GEP instructions with constant
960 // indices into GEP constant-exprs, which will allow global-opt to hack on it.
Chris Lattner7b550cc2009-11-06 04:27:31 +0000961 ConstantPropUsersOf(NewGV);
Victor Hernandez83d63912009-09-18 22:35:49 +0000962 if (RepValue != NewGV)
Chris Lattner7b550cc2009-11-06 04:27:31 +0000963 ConstantPropUsersOf(RepValue);
Victor Hernandez83d63912009-09-18 22:35:49 +0000964
965 return NewGV;
966}
967
Chris Lattnerfa07e4f2004-12-02 07:11:07 +0000968/// ValueIsOnlyUsedLocallyOrStoredToOneGlobal - Scan the use-list of V checking
969/// to make sure that there are no complex uses of V. We permit simple things
970/// like dereferencing the pointer, but not storing through the address, unless
971/// it is to the specified global.
Gabor Greif0b520db2010-04-06 18:58:22 +0000972static bool ValueIsOnlyUsedLocallyOrStoredToOneGlobal(const Instruction *V,
973 const GlobalVariable *GV,
Gabor Greifa01d6db2010-04-06 19:14:05 +0000974 SmallPtrSet<const PHINode*, 8> &PHIs) {
Gabor Greif0b520db2010-04-06 18:58:22 +0000975 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end();
Gabor Greifa01d6db2010-04-06 19:14:05 +0000976 UI != E; ++UI) {
Gabor Greif0b520db2010-04-06 18:58:22 +0000977 const Instruction *Inst = cast<Instruction>(*UI);
Gabor Greifa01d6db2010-04-06 19:14:05 +0000978
Chris Lattner49b6d4a2008-12-15 21:08:54 +0000979 if (isa<LoadInst>(Inst) || isa<CmpInst>(Inst)) {
980 continue; // Fine, ignore.
981 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000982
Gabor Greif0b520db2010-04-06 18:58:22 +0000983 if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
Chris Lattnerfa07e4f2004-12-02 07:11:07 +0000984 if (SI->getOperand(0) == V && SI->getOperand(1) != GV)
985 return false; // Storing the pointer itself... bad.
Chris Lattner49b6d4a2008-12-15 21:08:54 +0000986 continue; // Otherwise, storing through it, or storing into GV... fine.
987 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000988
Chris Lattnera2fb2342010-04-10 18:19:22 +0000989 // Must index into the array and into the struct.
990 if (isa<GetElementPtrInst>(Inst) && Inst->getNumOperands() >= 3) {
Chris Lattner49b6d4a2008-12-15 21:08:54 +0000991 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(Inst, GV, PHIs))
Chris Lattnerfa07e4f2004-12-02 07:11:07 +0000992 return false;
Chris Lattner49b6d4a2008-12-15 21:08:54 +0000993 continue;
994 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000995
Gabor Greif0b520db2010-04-06 18:58:22 +0000996 if (const PHINode *PN = dyn_cast<PHINode>(Inst)) {
Chris Lattnerc451f9c2007-09-13 16:37:20 +0000997 // PHIs are ok if all uses are ok. Don't infinitely recurse through PHI
998 // cycles.
999 if (PHIs.insert(PN))
Chris Lattner5e6e4942007-09-14 03:41:21 +00001000 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(PN, GV, PHIs))
1001 return false;
Chris Lattner49b6d4a2008-12-15 21:08:54 +00001002 continue;
Chris Lattnerfa07e4f2004-12-02 07:11:07 +00001003 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001004
Gabor Greif0b520db2010-04-06 18:58:22 +00001005 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Inst)) {
Chris Lattner49b6d4a2008-12-15 21:08:54 +00001006 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(BCI, GV, PHIs))
1007 return false;
1008 continue;
1009 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001010
Chris Lattner49b6d4a2008-12-15 21:08:54 +00001011 return false;
1012 }
Chris Lattnerfa07e4f2004-12-02 07:11:07 +00001013 return true;
Chris Lattnerfa07e4f2004-12-02 07:11:07 +00001014}
1015
Chris Lattner86395032006-09-30 23:32:09 +00001016/// ReplaceUsesOfMallocWithGlobal - The Alloc pointer is stored into GV
1017/// somewhere. Transform all uses of the allocation into loads from the
1018/// global and uses of the resultant pointer. Further, delete the store into
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001019/// GV. This assumes that these value pass the
Chris Lattner86395032006-09-30 23:32:09 +00001020/// 'ValueIsOnlyUsedLocallyOrStoredToOneGlobal' predicate.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001021static void ReplaceUsesOfMallocWithGlobal(Instruction *Alloc,
Chris Lattner86395032006-09-30 23:32:09 +00001022 GlobalVariable *GV) {
1023 while (!Alloc->use_empty()) {
Chris Lattnera637a8b2007-09-13 18:00:31 +00001024 Instruction *U = cast<Instruction>(*Alloc->use_begin());
1025 Instruction *InsertPt = U;
Chris Lattner86395032006-09-30 23:32:09 +00001026 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
1027 // If this is the store of the allocation into the global, remove it.
1028 if (SI->getOperand(1) == GV) {
1029 SI->eraseFromParent();
1030 continue;
1031 }
Chris Lattnera637a8b2007-09-13 18:00:31 +00001032 } else if (PHINode *PN = dyn_cast<PHINode>(U)) {
1033 // Insert the load in the corresponding predecessor, not right before the
1034 // PHI.
Gabor Greifa36791d2009-01-23 19:40:15 +00001035 InsertPt = PN->getIncomingBlock(Alloc->use_begin())->getTerminator();
Chris Lattner101f44e2008-12-15 21:44:34 +00001036 } else if (isa<BitCastInst>(U)) {
1037 // Must be bitcast between the malloc and store to initialize the global.
1038 ReplaceUsesOfMallocWithGlobal(U, GV);
1039 U->eraseFromParent();
1040 continue;
1041 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
1042 // If this is a "GEP bitcast" and the user is a store to the global, then
1043 // just process it as a bitcast.
1044 if (GEPI->hasAllZeroIndices() && GEPI->hasOneUse())
1045 if (StoreInst *SI = dyn_cast<StoreInst>(GEPI->use_back()))
1046 if (SI->getOperand(1) == GV) {
1047 // Must be bitcast GEP between the malloc and store to initialize
1048 // the global.
1049 ReplaceUsesOfMallocWithGlobal(GEPI, GV);
1050 GEPI->eraseFromParent();
1051 continue;
1052 }
Chris Lattner86395032006-09-30 23:32:09 +00001053 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001054
Chris Lattner86395032006-09-30 23:32:09 +00001055 // Insert a load from the global, and use it instead of the malloc.
Chris Lattnera637a8b2007-09-13 18:00:31 +00001056 Value *NL = new LoadInst(GV, GV->getName()+".val", InsertPt);
Chris Lattner86395032006-09-30 23:32:09 +00001057 U->replaceUsesOfWith(Alloc, NL);
1058 }
1059}
1060
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001061/// LoadUsesSimpleEnoughForHeapSRA - Verify that all uses of V (a load, or a phi
1062/// of a load) are simple enough to perform heap SRA on. This permits GEP's
1063/// that index through the array and struct field, icmps of null, and PHIs.
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001064static bool LoadUsesSimpleEnoughForHeapSRA(const Value *V,
Gabor Greif27236912010-04-07 18:59:26 +00001065 SmallPtrSet<const PHINode*, 32> &LoadUsingPHIs,
1066 SmallPtrSet<const PHINode*, 32> &LoadUsingPHIsPerLoad) {
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001067 // We permit two users of the load: setcc comparing against the null
1068 // pointer, and a getelementptr of a specific form.
Gabor Greif27236912010-04-07 18:59:26 +00001069 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;
1070 ++UI) {
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001071 const Instruction *User = cast<Instruction>(*UI);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001072
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001073 // Comparison against null is ok.
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001074 if (const ICmpInst *ICI = dyn_cast<ICmpInst>(User)) {
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001075 if (!isa<ConstantPointerNull>(ICI->getOperand(1)))
1076 return false;
1077 continue;
1078 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001079
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001080 // getelementptr is also ok, but only a simple form.
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001081 if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001082 // Must index into the array and into the struct.
1083 if (GEPI->getNumOperands() < 3)
1084 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001085
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001086 // Otherwise the GEP is ok.
1087 continue;
1088 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001089
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001090 if (const PHINode *PN = dyn_cast<PHINode>(User)) {
Evan Cheng5d163962009-06-02 00:56:07 +00001091 if (!LoadUsingPHIsPerLoad.insert(PN))
1092 // This means some phi nodes are dependent on each other.
1093 // Avoid infinite looping!
1094 return false;
1095 if (!LoadUsingPHIs.insert(PN))
1096 // If we have already analyzed this PHI, then it is safe.
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001097 continue;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001098
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001099 // Make sure all uses of the PHI are simple enough to transform.
Evan Cheng5d163962009-06-02 00:56:07 +00001100 if (!LoadUsesSimpleEnoughForHeapSRA(PN,
1101 LoadUsingPHIs, LoadUsingPHIsPerLoad))
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001102 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001103
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001104 continue;
Chris Lattner86395032006-09-30 23:32:09 +00001105 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001106
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001107 // Otherwise we don't know what this is, not ok.
1108 return false;
1109 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001110
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001111 return true;
1112}
1113
1114
1115/// AllGlobalLoadUsesSimpleEnoughForHeapSRA - If all users of values loaded from
1116/// GV are simple enough to perform HeapSRA, return true.
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001117static bool AllGlobalLoadUsesSimpleEnoughForHeapSRA(const GlobalVariable *GV,
Victor Hernandez83d63912009-09-18 22:35:49 +00001118 Instruction *StoredVal) {
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001119 SmallPtrSet<const PHINode*, 32> LoadUsingPHIs;
1120 SmallPtrSet<const PHINode*, 32> LoadUsingPHIsPerLoad;
Gabor Greif27236912010-04-07 18:59:26 +00001121 for (Value::const_use_iterator UI = GV->use_begin(), E = GV->use_end();
1122 UI != E; ++UI)
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001123 if (const LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
Evan Cheng5d163962009-06-02 00:56:07 +00001124 if (!LoadUsesSimpleEnoughForHeapSRA(LI, LoadUsingPHIs,
1125 LoadUsingPHIsPerLoad))
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001126 return false;
Evan Cheng5d163962009-06-02 00:56:07 +00001127 LoadUsingPHIsPerLoad.clear();
1128 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001129
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001130 // If we reach here, we know that all uses of the loads and transitive uses
1131 // (through PHI nodes) are simple enough to transform. However, we don't know
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001132 // that all inputs the to the PHI nodes are in the same equivalence sets.
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001133 // Check to verify that all operands of the PHIs are either PHIS that can be
1134 // transformed, loads from GV, or MI itself.
Gabor Greif27236912010-04-07 18:59:26 +00001135 for (SmallPtrSet<const PHINode*, 32>::const_iterator I = LoadUsingPHIs.begin()
1136 , E = LoadUsingPHIs.end(); I != E; ++I) {
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001137 const PHINode *PN = *I;
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001138 for (unsigned op = 0, e = PN->getNumIncomingValues(); op != e; ++op) {
1139 Value *InVal = PN->getIncomingValue(op);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001140
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001141 // PHI of the stored value itself is ok.
Victor Hernandez83d63912009-09-18 22:35:49 +00001142 if (InVal == StoredVal) continue;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001143
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001144 if (const PHINode *InPN = dyn_cast<PHINode>(InVal)) {
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001145 // One of the PHIs in our set is (optimistically) ok.
1146 if (LoadUsingPHIs.count(InPN))
1147 continue;
1148 return false;
1149 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001150
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001151 // Load from GV is ok.
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001152 if (const LoadInst *LI = dyn_cast<LoadInst>(InVal))
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001153 if (LI->getOperand(0) == GV)
1154 continue;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001155
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001156 // UNDEF? NULL?
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001157
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001158 // Anything else is rejected.
1159 return false;
1160 }
1161 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001162
Chris Lattner86395032006-09-30 23:32:09 +00001163 return true;
1164}
1165
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001166static Value *GetHeapSROAValue(Value *V, unsigned FieldNo,
1167 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001168 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001169 std::vector<Value*> &FieldVals = InsertedScalarizedValues[V];
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001170
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001171 if (FieldNo >= FieldVals.size())
1172 FieldVals.resize(FieldNo+1);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001173
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001174 // If we already have this value, just reuse the previously scalarized
1175 // version.
1176 if (Value *FieldVal = FieldVals[FieldNo])
1177 return FieldVal;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001178
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001179 // Depending on what instruction this is, we have several cases.
1180 Value *Result;
1181 if (LoadInst *LI = dyn_cast<LoadInst>(V)) {
1182 // This is a scalarized version of the load from the global. Just create
1183 // a new Load of the scalarized global.
1184 Result = new LoadInst(GetHeapSROAValue(LI->getOperand(0), FieldNo,
1185 InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001186 PHIsToRewrite),
Daniel Dunbarfe09b202009-07-30 17:37:43 +00001187 LI->getName()+".f"+Twine(FieldNo), LI);
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001188 } else if (PHINode *PN = dyn_cast<PHINode>(V)) {
1189 // PN's type is pointer to struct. Make a new PHI of pointer to struct
1190 // field.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001191 const StructType *ST =
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001192 cast<StructType>(cast<PointerType>(PN->getType())->getElementType());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001193
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001194 Result =
Owen Andersondebcb012009-07-29 22:17:13 +00001195 PHINode::Create(PointerType::getUnqual(ST->getElementType(FieldNo)),
Daniel Dunbarfe09b202009-07-30 17:37:43 +00001196 PN->getName()+".f"+Twine(FieldNo), PN);
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001197 PHIsToRewrite.push_back(std::make_pair(PN, FieldNo));
1198 } else {
Torok Edwinc23197a2009-07-14 16:55:14 +00001199 llvm_unreachable("Unknown usable value");
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001200 Result = 0;
1201 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001202
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001203 return FieldVals[FieldNo] = Result;
Chris Lattnera637a8b2007-09-13 18:00:31 +00001204}
1205
Chris Lattner330245e2007-09-13 17:29:05 +00001206/// RewriteHeapSROALoadUser - Given a load instruction and a value derived from
1207/// the load, rewrite the derived value to use the HeapSRoA'd load.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001208static void RewriteHeapSROALoadUser(Instruction *LoadUser,
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001209 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001210 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
Chris Lattner330245e2007-09-13 17:29:05 +00001211 // If this is a comparison against null, handle it.
1212 if (ICmpInst *SCI = dyn_cast<ICmpInst>(LoadUser)) {
1213 assert(isa<ConstantPointerNull>(SCI->getOperand(1)));
1214 // If we have a setcc of the loaded pointer, we can use a setcc of any
1215 // field.
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001216 Value *NPtr = GetHeapSROAValue(SCI->getOperand(0), 0,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001217 InsertedScalarizedValues, PHIsToRewrite);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001218
Owen Anderson333c4002009-07-09 23:48:35 +00001219 Value *New = new ICmpInst(SCI, SCI->getPredicate(), NPtr,
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001220 Constant::getNullValue(NPtr->getType()),
Owen Anderson333c4002009-07-09 23:48:35 +00001221 SCI->getName());
Chris Lattner330245e2007-09-13 17:29:05 +00001222 SCI->replaceAllUsesWith(New);
1223 SCI->eraseFromParent();
1224 return;
1225 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001226
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001227 // Handle 'getelementptr Ptr, Idx, i32 FieldNo ...'
Chris Lattnera637a8b2007-09-13 18:00:31 +00001228 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(LoadUser)) {
1229 assert(GEPI->getNumOperands() >= 3 && isa<ConstantInt>(GEPI->getOperand(2))
1230 && "Unexpected GEPI!");
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001231
Chris Lattnera637a8b2007-09-13 18:00:31 +00001232 // Load the pointer for this field.
1233 unsigned FieldNo = cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue();
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001234 Value *NewPtr = GetHeapSROAValue(GEPI->getOperand(0), FieldNo,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001235 InsertedScalarizedValues, PHIsToRewrite);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001236
Chris Lattnera637a8b2007-09-13 18:00:31 +00001237 // Create the new GEP idx vector.
1238 SmallVector<Value*, 8> GEPIdx;
1239 GEPIdx.push_back(GEPI->getOperand(1));
1240 GEPIdx.append(GEPI->op_begin()+3, GEPI->op_end());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001241
Gabor Greifb1dbcd82008-05-15 10:04:30 +00001242 Value *NGEPI = GetElementPtrInst::Create(NewPtr,
1243 GEPIdx.begin(), GEPIdx.end(),
Gabor Greif051a9502008-04-06 20:25:17 +00001244 GEPI->getName(), GEPI);
Chris Lattnera637a8b2007-09-13 18:00:31 +00001245 GEPI->replaceAllUsesWith(NGEPI);
1246 GEPI->eraseFromParent();
1247 return;
1248 }
Chris Lattner309f20f2007-09-13 21:31:36 +00001249
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001250 // Recursively transform the users of PHI nodes. This will lazily create the
1251 // PHIs that are needed for individual elements. Keep track of what PHIs we
1252 // see in InsertedScalarizedValues so that we don't get infinite loops (very
1253 // antisocial). If the PHI is already in InsertedScalarizedValues, it has
1254 // already been seen first by another load, so its uses have already been
1255 // processed.
1256 PHINode *PN = cast<PHINode>(LoadUser);
1257 bool Inserted;
1258 DenseMap<Value*, std::vector<Value*> >::iterator InsertPos;
1259 tie(InsertPos, Inserted) =
1260 InsertedScalarizedValues.insert(std::make_pair(PN, std::vector<Value*>()));
1261 if (!Inserted) return;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001262
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001263 // If this is the first time we've seen this PHI, recursively process all
1264 // users.
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001265 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end(); UI != E; ) {
1266 Instruction *User = cast<Instruction>(*UI++);
Chris Lattner7b550cc2009-11-06 04:27:31 +00001267 RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite);
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001268 }
Chris Lattner330245e2007-09-13 17:29:05 +00001269}
1270
Chris Lattner86395032006-09-30 23:32:09 +00001271/// RewriteUsesOfLoadForHeapSRoA - We are performing Heap SRoA on a global. Ptr
1272/// is a value loaded from the global. Eliminate all uses of Ptr, making them
1273/// use FieldGlobals instead. All uses of loaded values satisfy
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001274/// AllGlobalLoadUsesSimpleEnoughForHeapSRA.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001275static void RewriteUsesOfLoadForHeapSRoA(LoadInst *Load,
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001276 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001277 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001278 for (Value::use_iterator UI = Load->use_begin(), E = Load->use_end();
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001279 UI != E; ) {
1280 Instruction *User = cast<Instruction>(*UI++);
Chris Lattner7b550cc2009-11-06 04:27:31 +00001281 RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite);
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001282 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001283
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001284 if (Load->use_empty()) {
1285 Load->eraseFromParent();
1286 InsertedScalarizedValues.erase(Load);
1287 }
Chris Lattner86395032006-09-30 23:32:09 +00001288}
1289
Victor Hernandez83d63912009-09-18 22:35:49 +00001290/// PerformHeapAllocSRoA - CI is an allocation of an array of structures. Break
1291/// it up into multiple allocations of arrays of the fields.
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001292static GlobalVariable *PerformHeapAllocSRoA(GlobalVariable *GV, CallInst *CI,
1293 Value* NElems, TargetData *TD) {
David Greene3215b0e2010-01-05 01:28:05 +00001294 DEBUG(dbgs() << "SROA HEAP ALLOC: " << *GV << " MALLOC = " << *CI << '\n');
Victor Hernandez83d63912009-09-18 22:35:49 +00001295 const Type* MAT = getMallocAllocatedType(CI);
1296 const StructType *STy = cast<StructType>(MAT);
1297
1298 // There is guaranteed to be at least one use of the malloc (storing
1299 // it into GV). If there are other uses, change them to be uses of
1300 // the global to simplify later code. This also deletes the store
1301 // into GV.
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001302 ReplaceUsesOfMallocWithGlobal(CI, GV);
1303
Victor Hernandez83d63912009-09-18 22:35:49 +00001304 // Okay, at this point, there are no users of the malloc. Insert N
1305 // new mallocs at the same place as CI, and N globals.
1306 std::vector<Value*> FieldGlobals;
1307 std::vector<Value*> FieldMallocs;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001308
Victor Hernandez83d63912009-09-18 22:35:49 +00001309 for (unsigned FieldNo = 0, e = STy->getNumElements(); FieldNo != e;++FieldNo){
1310 const Type *FieldTy = STy->getElementType(FieldNo);
1311 const PointerType *PFieldTy = PointerType::getUnqual(FieldTy);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001312
Victor Hernandez83d63912009-09-18 22:35:49 +00001313 GlobalVariable *NGV =
1314 new GlobalVariable(*GV->getParent(),
1315 PFieldTy, false, GlobalValue::InternalLinkage,
1316 Constant::getNullValue(PFieldTy),
1317 GV->getName() + ".f" + Twine(FieldNo), GV,
1318 GV->isThreadLocal());
1319 FieldGlobals.push_back(NGV);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001320
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001321 unsigned TypeSize = TD->getTypeAllocSize(FieldTy);
Victor Hernandez631f3c02009-11-07 00:41:19 +00001322 if (const StructType *ST = dyn_cast<StructType>(FieldTy))
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001323 TypeSize = TD->getStructLayout(ST)->getSizeInBytes();
Victor Hernandez631f3c02009-11-07 00:41:19 +00001324 const Type *IntPtrTy = TD->getIntPtrType(CI->getContext());
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001325 Value *NMI = CallInst::CreateMalloc(CI, IntPtrTy, FieldTy,
1326 ConstantInt::get(IntPtrTy, TypeSize),
Chris Lattner5a30a852010-07-12 00:57:28 +00001327 NElems, 0,
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001328 CI->getName() + ".f" + Twine(FieldNo));
Chris Lattner3f5e0b82010-02-26 18:23:13 +00001329 FieldMallocs.push_back(NMI);
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001330 new StoreInst(NMI, NGV, CI);
Victor Hernandez83d63912009-09-18 22:35:49 +00001331 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001332
Victor Hernandez83d63912009-09-18 22:35:49 +00001333 // The tricky aspect of this transformation is handling the case when malloc
1334 // fails. In the original code, malloc failing would set the result pointer
1335 // of malloc to null. In this case, some mallocs could succeed and others
1336 // could fail. As such, we emit code that looks like this:
1337 // F0 = malloc(field0)
1338 // F1 = malloc(field1)
1339 // F2 = malloc(field2)
1340 // if (F0 == 0 || F1 == 0 || F2 == 0) {
1341 // if (F0) { free(F0); F0 = 0; }
1342 // if (F1) { free(F1); F1 = 0; }
1343 // if (F2) { free(F2); F2 = 0; }
1344 // }
Victor Hernandez8e345a12009-11-10 08:32:25 +00001345 // The malloc can also fail if its argument is too large.
Gabor Greif9e4f2432010-06-24 14:42:01 +00001346 Constant *ConstantZero = ConstantInt::get(CI->getArgOperand(0)->getType(), 0);
1347 Value *RunningOr = new ICmpInst(CI, ICmpInst::ICMP_SLT, CI->getArgOperand(0),
Victor Hernandez8e345a12009-11-10 08:32:25 +00001348 ConstantZero, "isneg");
Victor Hernandez83d63912009-09-18 22:35:49 +00001349 for (unsigned i = 0, e = FieldMallocs.size(); i != e; ++i) {
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001350 Value *Cond = new ICmpInst(CI, ICmpInst::ICMP_EQ, FieldMallocs[i],
1351 Constant::getNullValue(FieldMallocs[i]->getType()),
1352 "isnull");
Victor Hernandez8e345a12009-11-10 08:32:25 +00001353 RunningOr = BinaryOperator::CreateOr(RunningOr, Cond, "tmp", CI);
Victor Hernandez83d63912009-09-18 22:35:49 +00001354 }
1355
1356 // Split the basic block at the old malloc.
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001357 BasicBlock *OrigBB = CI->getParent();
1358 BasicBlock *ContBB = OrigBB->splitBasicBlock(CI, "malloc_cont");
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001359
Victor Hernandez83d63912009-09-18 22:35:49 +00001360 // Create the block to check the first condition. Put all these blocks at the
1361 // end of the function as they are unlikely to be executed.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001362 BasicBlock *NullPtrBlock = BasicBlock::Create(OrigBB->getContext(),
1363 "malloc_ret_null",
Victor Hernandez83d63912009-09-18 22:35:49 +00001364 OrigBB->getParent());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001365
Victor Hernandez83d63912009-09-18 22:35:49 +00001366 // Remove the uncond branch from OrigBB to ContBB, turning it into a cond
1367 // branch on RunningOr.
1368 OrigBB->getTerminator()->eraseFromParent();
1369 BranchInst::Create(NullPtrBlock, ContBB, RunningOr, OrigBB);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001370
Victor Hernandez83d63912009-09-18 22:35:49 +00001371 // Within the NullPtrBlock, we need to emit a comparison and branch for each
1372 // pointer, because some may be null while others are not.
1373 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
1374 Value *GVVal = new LoadInst(FieldGlobals[i], "tmp", NullPtrBlock);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001375 Value *Cmp = new ICmpInst(*NullPtrBlock, ICmpInst::ICMP_NE, GVVal,
Victor Hernandez83d63912009-09-18 22:35:49 +00001376 Constant::getNullValue(GVVal->getType()),
1377 "tmp");
Chris Lattner7b550cc2009-11-06 04:27:31 +00001378 BasicBlock *FreeBlock = BasicBlock::Create(Cmp->getContext(), "free_it",
Victor Hernandez83d63912009-09-18 22:35:49 +00001379 OrigBB->getParent());
Chris Lattner7b550cc2009-11-06 04:27:31 +00001380 BasicBlock *NextBlock = BasicBlock::Create(Cmp->getContext(), "next",
Victor Hernandez83d63912009-09-18 22:35:49 +00001381 OrigBB->getParent());
Victor Hernandez66284e02009-10-24 04:23:03 +00001382 Instruction *BI = BranchInst::Create(FreeBlock, NextBlock,
1383 Cmp, NullPtrBlock);
Victor Hernandez83d63912009-09-18 22:35:49 +00001384
1385 // Fill in FreeBlock.
Victor Hernandez66284e02009-10-24 04:23:03 +00001386 CallInst::CreateFree(GVVal, BI);
Victor Hernandez83d63912009-09-18 22:35:49 +00001387 new StoreInst(Constant::getNullValue(GVVal->getType()), FieldGlobals[i],
1388 FreeBlock);
1389 BranchInst::Create(NextBlock, FreeBlock);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001390
Victor Hernandez83d63912009-09-18 22:35:49 +00001391 NullPtrBlock = NextBlock;
1392 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001393
Victor Hernandez83d63912009-09-18 22:35:49 +00001394 BranchInst::Create(ContBB, NullPtrBlock);
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001395
1396 // CI is no longer needed, remove it.
Victor Hernandez83d63912009-09-18 22:35:49 +00001397 CI->eraseFromParent();
1398
1399 /// InsertedScalarizedLoads - As we process loads, if we can't immediately
1400 /// update all uses of the load, keep track of what scalarized loads are
1401 /// inserted for a given load.
1402 DenseMap<Value*, std::vector<Value*> > InsertedScalarizedValues;
1403 InsertedScalarizedValues[GV] = FieldGlobals;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001404
Victor Hernandez83d63912009-09-18 22:35:49 +00001405 std::vector<std::pair<PHINode*, unsigned> > PHIsToRewrite;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001406
Victor Hernandez83d63912009-09-18 22:35:49 +00001407 // Okay, the malloc site is completely handled. All of the uses of GV are now
1408 // loads, and all uses of those loads are simple. Rewrite them to use loads
1409 // of the per-field globals instead.
1410 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI != E;) {
1411 Instruction *User = cast<Instruction>(*UI++);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001412
Victor Hernandez83d63912009-09-18 22:35:49 +00001413 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Chris Lattner7b550cc2009-11-06 04:27:31 +00001414 RewriteUsesOfLoadForHeapSRoA(LI, InsertedScalarizedValues, PHIsToRewrite);
Victor Hernandez83d63912009-09-18 22:35:49 +00001415 continue;
1416 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001417
Victor Hernandez83d63912009-09-18 22:35:49 +00001418 // Must be a store of null.
1419 StoreInst *SI = cast<StoreInst>(User);
1420 assert(isa<ConstantPointerNull>(SI->getOperand(0)) &&
1421 "Unexpected heap-sra user!");
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001422
Victor Hernandez83d63912009-09-18 22:35:49 +00001423 // Insert a store of null into each global.
1424 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
1425 const PointerType *PT = cast<PointerType>(FieldGlobals[i]->getType());
1426 Constant *Null = Constant::getNullValue(PT->getElementType());
1427 new StoreInst(Null, FieldGlobals[i], SI);
1428 }
1429 // Erase the original store.
1430 SI->eraseFromParent();
1431 }
1432
1433 // While we have PHIs that are interesting to rewrite, do it.
1434 while (!PHIsToRewrite.empty()) {
1435 PHINode *PN = PHIsToRewrite.back().first;
1436 unsigned FieldNo = PHIsToRewrite.back().second;
1437 PHIsToRewrite.pop_back();
1438 PHINode *FieldPN = cast<PHINode>(InsertedScalarizedValues[PN][FieldNo]);
1439 assert(FieldPN->getNumIncomingValues() == 0 &&"Already processed this phi");
1440
1441 // Add all the incoming values. This can materialize more phis.
1442 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1443 Value *InVal = PN->getIncomingValue(i);
1444 InVal = GetHeapSROAValue(InVal, FieldNo, InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001445 PHIsToRewrite);
Victor Hernandez83d63912009-09-18 22:35:49 +00001446 FieldPN->addIncoming(InVal, PN->getIncomingBlock(i));
1447 }
1448 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001449
Victor Hernandez83d63912009-09-18 22:35:49 +00001450 // Drop all inter-phi links and any loads that made it this far.
1451 for (DenseMap<Value*, std::vector<Value*> >::iterator
1452 I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
1453 I != E; ++I) {
1454 if (PHINode *PN = dyn_cast<PHINode>(I->first))
1455 PN->dropAllReferences();
1456 else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
1457 LI->dropAllReferences();
1458 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001459
Victor Hernandez83d63912009-09-18 22:35:49 +00001460 // Delete all the phis and loads now that inter-references are dead.
1461 for (DenseMap<Value*, std::vector<Value*> >::iterator
1462 I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
1463 I != E; ++I) {
1464 if (PHINode *PN = dyn_cast<PHINode>(I->first))
1465 PN->eraseFromParent();
1466 else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
1467 LI->eraseFromParent();
1468 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001469
Victor Hernandez83d63912009-09-18 22:35:49 +00001470 // The old global is now dead, remove it.
1471 GV->eraseFromParent();
1472
1473 ++NumHeapSRA;
1474 return cast<GlobalVariable>(FieldGlobals[0]);
1475}
1476
Chris Lattnere61d0a62008-12-15 21:02:25 +00001477/// TryToOptimizeStoreOfMallocToGlobal - This function is called when we see a
1478/// pointer global variable with a single value stored it that is a malloc or
1479/// cast of malloc.
1480static bool TryToOptimizeStoreOfMallocToGlobal(GlobalVariable *GV,
Victor Hernandez83d63912009-09-18 22:35:49 +00001481 CallInst *CI,
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001482 const Type *AllocTy,
Victor Hernandez83d63912009-09-18 22:35:49 +00001483 Module::global_iterator &GVI,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001484 TargetData *TD) {
Evan Cheng86cd4452010-04-14 20:52:55 +00001485 if (!TD)
1486 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001487
Victor Hernandez83d63912009-09-18 22:35:49 +00001488 // If this is a malloc of an abstract type, don't touch it.
1489 if (!AllocTy->isSized())
1490 return false;
1491
1492 // We can't optimize this global unless all uses of it are *known* to be
1493 // of the malloc value, not of the null initializer value (consider a use
1494 // that compares the global's value against zero to see if the malloc has
1495 // been reached). To do this, we check to see if all uses of the global
1496 // would trap if the global were null: this proves that they must all
1497 // happen after the malloc.
1498 if (!AllUsesOfLoadedValueWillTrapIfNull(GV))
1499 return false;
1500
1501 // We can't optimize this if the malloc itself is used in a complex way,
1502 // for example, being stored into multiple globals. This allows the
1503 // malloc to be stored into the specified global, loaded setcc'd, and
1504 // GEP'd. These are all things we could transform to using the global
1505 // for.
Evan Cheng86cd4452010-04-14 20:52:55 +00001506 SmallPtrSet<const PHINode*, 8> PHIs;
1507 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(CI, GV, PHIs))
1508 return false;
Victor Hernandez83d63912009-09-18 22:35:49 +00001509
1510 // If we have a global that is only initialized with a fixed size malloc,
1511 // transform the program to use global memory instead of malloc'd memory.
1512 // This eliminates dynamic allocation, avoids an indirection accessing the
1513 // data, and exposes the resultant global to further GlobalOpt.
Victor Hernandez8db42d22009-10-16 23:12:25 +00001514 // We cannot optimize the malloc if we cannot determine malloc array size.
Evan Cheng86cd4452010-04-14 20:52:55 +00001515 Value *NElems = getMallocArraySize(CI, TD, true);
1516 if (!NElems)
1517 return false;
Victor Hernandez83d63912009-09-18 22:35:49 +00001518
Evan Cheng86cd4452010-04-14 20:52:55 +00001519 if (ConstantInt *NElements = dyn_cast<ConstantInt>(NElems))
1520 // Restrict this transformation to only working on small allocations
1521 // (2048 bytes currently), as we don't want to introduce a 16M global or
1522 // something.
1523 if (NElements->getZExtValue() * TD->getTypeAllocSize(AllocTy) < 2048) {
1524 GVI = OptimizeGlobalAddressOfMalloc(GV, CI, AllocTy, NElements, TD);
1525 return true;
Victor Hernandez83d63912009-09-18 22:35:49 +00001526 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001527
Evan Cheng86cd4452010-04-14 20:52:55 +00001528 // If the allocation is an array of structures, consider transforming this
1529 // into multiple malloc'd arrays, one for each field. This is basically
1530 // SRoA for malloc'd memory.
1531
1532 // If this is an allocation of a fixed size array of structs, analyze as a
1533 // variable size array. malloc [100 x struct],1 -> malloc struct, 100
Gabor Greif9e4f2432010-06-24 14:42:01 +00001534 if (NElems == ConstantInt::get(CI->getArgOperand(0)->getType(), 1))
Evan Cheng86cd4452010-04-14 20:52:55 +00001535 if (const ArrayType *AT = dyn_cast<ArrayType>(AllocTy))
1536 AllocTy = AT->getElementType();
Gabor Greif9e4f2432010-06-24 14:42:01 +00001537
Evan Cheng86cd4452010-04-14 20:52:55 +00001538 const StructType *AllocSTy = dyn_cast<StructType>(AllocTy);
1539 if (!AllocSTy)
1540 return false;
1541
1542 // This the structure has an unreasonable number of fields, leave it
1543 // alone.
1544 if (AllocSTy->getNumElements() <= 16 && AllocSTy->getNumElements() != 0 &&
1545 AllGlobalLoadUsesSimpleEnoughForHeapSRA(GV, CI)) {
1546
1547 // If this is a fixed size array, transform the Malloc to be an alloc of
1548 // structs. malloc [100 x struct],1 -> malloc struct, 100
1549 if (const ArrayType *AT = dyn_cast<ArrayType>(getMallocAllocatedType(CI))) {
1550 const Type *IntPtrTy = TD->getIntPtrType(CI->getContext());
1551 unsigned TypeSize = TD->getStructLayout(AllocSTy)->getSizeInBytes();
1552 Value *AllocSize = ConstantInt::get(IntPtrTy, TypeSize);
1553 Value *NumElements = ConstantInt::get(IntPtrTy, AT->getNumElements());
1554 Instruction *Malloc = CallInst::CreateMalloc(CI, IntPtrTy, AllocSTy,
1555 AllocSize, NumElements,
Chris Lattner5a30a852010-07-12 00:57:28 +00001556 0, CI->getName());
Evan Cheng86cd4452010-04-14 20:52:55 +00001557 Instruction *Cast = new BitCastInst(Malloc, CI->getType(), "tmp", CI);
1558 CI->replaceAllUsesWith(Cast);
1559 CI->eraseFromParent();
1560 CI = dyn_cast<BitCastInst>(Malloc) ?
1561 extractMallocCallFromBitCast(Malloc) : cast<CallInst>(Malloc);
1562 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001563
Evan Cheng86cd4452010-04-14 20:52:55 +00001564 GVI = PerformHeapAllocSRoA(GV, CI, getMallocArraySize(CI, TD, true),TD);
1565 return true;
Victor Hernandez83d63912009-09-18 22:35:49 +00001566 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001567
Victor Hernandez83d63912009-09-18 22:35:49 +00001568 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001569}
Victor Hernandez83d63912009-09-18 22:35:49 +00001570
Chris Lattner9b34a612004-10-09 21:48:45 +00001571// OptimizeOnceStoredGlobal - Try to optimize globals based on the knowledge
1572// that only one value (besides its initializer) is ever stored to the global.
Chris Lattner30ba5692004-10-11 05:54:41 +00001573static bool OptimizeOnceStoredGlobal(GlobalVariable *GV, Value *StoredOnceVal,
Chris Lattner7f8897f2006-08-27 22:42:52 +00001574 Module::global_iterator &GVI,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001575 TargetData *TD) {
Chris Lattner344b41c2008-12-15 21:20:32 +00001576 // Ignore no-op GEPs and bitcasts.
1577 StoredOnceVal = StoredOnceVal->stripPointerCasts();
Chris Lattner9b34a612004-10-09 21:48:45 +00001578
Chris Lattner708148e2004-10-10 23:14:11 +00001579 // If we are dealing with a pointer global that is initialized to null and
1580 // only has one (non-null) value stored into it, then we can optimize any
1581 // users of the loaded value (often calls and loads) that would trap if the
1582 // value was null.
Duncan Sands1df98592010-02-16 11:11:14 +00001583 if (GV->getInitializer()->getType()->isPointerTy() &&
Chris Lattner9b34a612004-10-09 21:48:45 +00001584 GV->getInitializer()->isNullValue()) {
Chris Lattner708148e2004-10-10 23:14:11 +00001585 if (Constant *SOVC = dyn_cast<Constant>(StoredOnceVal)) {
1586 if (GV->getInitializer()->getType() != SOVC->getType())
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001587 SOVC =
Owen Andersonbaf3c402009-07-29 18:55:55 +00001588 ConstantExpr::getBitCast(SOVC, GV->getInitializer()->getType());
Misha Brukmanfd939082005-04-21 23:48:37 +00001589
Chris Lattner708148e2004-10-10 23:14:11 +00001590 // Optimize away any trapping uses of the loaded value.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001591 if (OptimizeAwayTrappingUsesOfLoads(GV, SOVC))
Chris Lattner8be80122004-10-10 17:07:12 +00001592 return true;
Victor Hernandez83d63912009-09-18 22:35:49 +00001593 } else if (CallInst *CI = extractMallocCall(StoredOnceVal)) {
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001594 const Type* MallocType = getMallocAllocatedType(CI);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001595 if (MallocType && TryToOptimizeStoreOfMallocToGlobal(GV, CI, MallocType,
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001596 GVI, TD))
1597 return true;
Chris Lattner708148e2004-10-10 23:14:11 +00001598 }
Chris Lattner9b34a612004-10-09 21:48:45 +00001599 }
Chris Lattner30ba5692004-10-11 05:54:41 +00001600
Chris Lattner9b34a612004-10-09 21:48:45 +00001601 return false;
1602}
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001603
Chris Lattner58e44f42008-01-14 01:17:44 +00001604/// TryToShrinkGlobalToBoolean - At this point, we have learned that the only
1605/// two values ever stored into GV are its initializer and OtherVal. See if we
1606/// can shrink the global into a boolean and select between the two values
1607/// whenever it is used. This exposes the values to other scalar optimizations.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001608static bool TryToShrinkGlobalToBoolean(GlobalVariable *GV, Constant *OtherVal) {
Chris Lattner58e44f42008-01-14 01:17:44 +00001609 const Type *GVElType = GV->getType()->getElementType();
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001610
Chris Lattner58e44f42008-01-14 01:17:44 +00001611 // If GVElType is already i1, it is already shrunk. If the type of the GV is
Chris Lattner6f6923f2009-03-07 23:32:02 +00001612 // an FP value, pointer or vector, don't do this optimization because a select
1613 // between them is very expensive and unlikely to lead to later
1614 // simplification. In these cases, we typically end up with "cond ? v1 : v2"
1615 // where v1 and v2 both require constant pool loads, a big loss.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001616 if (GVElType == Type::getInt1Ty(GV->getContext()) ||
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001617 GVElType->isFloatingPointTy() ||
Duncan Sands1df98592010-02-16 11:11:14 +00001618 GVElType->isPointerTy() || GVElType->isVectorTy())
Chris Lattner58e44f42008-01-14 01:17:44 +00001619 return false;
Gabor Greifaaaaa022010-07-12 14:13:15 +00001620
Chris Lattner58e44f42008-01-14 01:17:44 +00001621 // Walk the use list of the global seeing if all the uses are load or store.
1622 // If there is anything else, bail out.
Gabor Greifaaaaa022010-07-12 14:13:15 +00001623 for (Value::use_iterator I = GV->use_begin(), E = GV->use_end(); I != E; ++I){
1624 User *U = *I;
1625 if (!isa<LoadInst>(U) && !isa<StoreInst>(U))
Chris Lattner58e44f42008-01-14 01:17:44 +00001626 return false;
Gabor Greifaaaaa022010-07-12 14:13:15 +00001627 }
1628
David Greene3215b0e2010-01-05 01:28:05 +00001629 DEBUG(dbgs() << " *** SHRINKING TO BOOL: " << *GV);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001630
Chris Lattner96a86b22004-12-12 05:53:50 +00001631 // Create the new global, initializing it to false.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001632 GlobalVariable *NewGV = new GlobalVariable(Type::getInt1Ty(GV->getContext()),
1633 false,
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001634 GlobalValue::InternalLinkage,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001635 ConstantInt::getFalse(GV->getContext()),
Nick Lewycky0e670df2009-05-03 03:49:08 +00001636 GV->getName()+".b",
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +00001637 GV->isThreadLocal());
Chris Lattner96a86b22004-12-12 05:53:50 +00001638 GV->getParent()->getGlobalList().insert(GV, NewGV);
1639
1640 Constant *InitVal = GV->getInitializer();
Chris Lattner7b550cc2009-11-06 04:27:31 +00001641 assert(InitVal->getType() != Type::getInt1Ty(GV->getContext()) &&
Owen Anderson1d0be152009-08-13 21:58:54 +00001642 "No reason to shrink to bool!");
Chris Lattner96a86b22004-12-12 05:53:50 +00001643
1644 // If initialized to zero and storing one into the global, we can use a cast
1645 // instead of a select to synthesize the desired value.
1646 bool IsOneZero = false;
1647 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal))
Reid Spencercae57542007-03-02 00:28:52 +00001648 IsOneZero = InitVal->isNullValue() && CI->isOne();
Chris Lattner96a86b22004-12-12 05:53:50 +00001649
1650 while (!GV->use_empty()) {
Devang Patel771281f2009-03-06 01:39:36 +00001651 Instruction *UI = cast<Instruction>(GV->use_back());
1652 if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
Chris Lattner96a86b22004-12-12 05:53:50 +00001653 // Change the store into a boolean store.
1654 bool StoringOther = SI->getOperand(0) == OtherVal;
1655 // Only do this if we weren't storing a loaded value.
Chris Lattner38c25562004-12-12 19:34:41 +00001656 Value *StoreVal;
Chris Lattner96a86b22004-12-12 05:53:50 +00001657 if (StoringOther || SI->getOperand(0) == InitVal)
Chris Lattner7b550cc2009-11-06 04:27:31 +00001658 StoreVal = ConstantInt::get(Type::getInt1Ty(GV->getContext()),
1659 StoringOther);
Chris Lattner38c25562004-12-12 19:34:41 +00001660 else {
1661 // Otherwise, we are storing a previously loaded copy. To do this,
1662 // change the copy from copying the original value to just copying the
1663 // bool.
1664 Instruction *StoredVal = cast<Instruction>(SI->getOperand(0));
1665
Gabor Greif9e4f2432010-06-24 14:42:01 +00001666 // If we've already replaced the input, StoredVal will be a cast or
Chris Lattner38c25562004-12-12 19:34:41 +00001667 // select instruction. If not, it will be a load of the original
1668 // global.
1669 if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
1670 assert(LI->getOperand(0) == GV && "Not a copy!");
1671 // Insert a new load, to preserve the saved value.
1672 StoreVal = new LoadInst(NewGV, LI->getName()+".b", LI);
1673 } else {
1674 assert((isa<CastInst>(StoredVal) || isa<SelectInst>(StoredVal)) &&
1675 "This is not a form that we understand!");
1676 StoreVal = StoredVal->getOperand(0);
1677 assert(isa<LoadInst>(StoreVal) && "Not a load of NewGV!");
1678 }
1679 }
1680 new StoreInst(StoreVal, NewGV, SI);
Devang Patel771281f2009-03-06 01:39:36 +00001681 } else {
Chris Lattner96a86b22004-12-12 05:53:50 +00001682 // Change the load into a load of bool then a select.
Devang Patel771281f2009-03-06 01:39:36 +00001683 LoadInst *LI = cast<LoadInst>(UI);
Chris Lattner046800a2007-02-11 01:08:35 +00001684 LoadInst *NLI = new LoadInst(NewGV, LI->getName()+".b", LI);
Chris Lattner96a86b22004-12-12 05:53:50 +00001685 Value *NSI;
1686 if (IsOneZero)
Chris Lattner046800a2007-02-11 01:08:35 +00001687 NSI = new ZExtInst(NLI, LI->getType(), "", LI);
Misha Brukmanfd939082005-04-21 23:48:37 +00001688 else
Gabor Greif051a9502008-04-06 20:25:17 +00001689 NSI = SelectInst::Create(NLI, OtherVal, InitVal, "", LI);
Chris Lattner046800a2007-02-11 01:08:35 +00001690 NSI->takeName(LI);
Chris Lattner96a86b22004-12-12 05:53:50 +00001691 LI->replaceAllUsesWith(NSI);
Devang Patel771281f2009-03-06 01:39:36 +00001692 }
1693 UI->eraseFromParent();
Chris Lattner96a86b22004-12-12 05:53:50 +00001694 }
1695
1696 GV->eraseFromParent();
Chris Lattner58e44f42008-01-14 01:17:44 +00001697 return true;
Chris Lattner96a86b22004-12-12 05:53:50 +00001698}
1699
1700
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001701/// ProcessInternalGlobal - Analyze the specified global variable and optimize
1702/// it if possible. If we make a change, return true.
Rafael Espindolac4440e32011-01-19 16:32:21 +00001703bool GlobalOpt::ProcessGlobal(GlobalVariable *GV,
1704 Module::global_iterator &GVI) {
1705 if (!GV->hasLocalLinkage())
1706 return false;
1707
1708 // Do more involved optimizations if the global is internal.
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001709 GV->removeDeadConstantUsers();
1710
1711 if (GV->use_empty()) {
David Greene3215b0e2010-01-05 01:28:05 +00001712 DEBUG(dbgs() << "GLOBAL DEAD: " << *GV);
Chris Lattner7a7ed022004-10-16 18:09:00 +00001713 GV->eraseFromParent();
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001714 ++NumDeleted;
1715 return true;
1716 }
1717
Rafael Espindolac4440e32011-01-19 16:32:21 +00001718 SmallPtrSet<const PHINode*, 16> PHIUsers;
1719 GlobalStatus GS;
1720
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001721 if (AnalyzeGlobal(GV, GS, PHIUsers))
1722 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001723
Rafael Espindolac4440e32011-01-19 16:32:21 +00001724 if (!GS.isCompared && !GV->hasUnnamedAddr()) {
1725 GV->setUnnamedAddr(true);
1726 NumUnnamed++;
1727 }
1728
1729 if (GV->isConstant() || !GV->hasInitializer())
1730 return false;
1731
1732 return ProcessInternalGlobal(GV, GVI, PHIUsers, GS);
1733}
1734
1735/// ProcessInternalGlobal - Analyze the specified global variable and optimize
1736/// it if possible. If we make a change, return true.
1737bool GlobalOpt::ProcessInternalGlobal(GlobalVariable *GV,
1738 Module::global_iterator &GVI,
1739 const SmallPtrSet<const PHINode*, 16> &PHIUsers,
1740 const GlobalStatus &GS) {
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001741 // If this is a first class global and has only one accessing function
1742 // and this function is main (which we know is not recursive we can make
1743 // this global a local variable) we replace the global with a local alloca
1744 // in this function.
1745 //
1746 // NOTE: It doesn't make sense to promote non single-value types since we
1747 // are just replacing static memory to stack memory.
1748 //
1749 // If the global is in different address space, don't bring it to stack.
1750 if (!GS.HasMultipleAccessingFunctions &&
1751 GS.AccessingFunction && !GS.HasNonInstructionUser &&
1752 GV->getType()->getElementType()->isSingleValueType() &&
1753 GS.AccessingFunction->getName() == "main" &&
1754 GS.AccessingFunction->hasExternalLinkage() &&
1755 GV->getType()->getAddressSpace() == 0) {
1756 DEBUG(dbgs() << "LOCALIZING GLOBAL: " << *GV);
1757 Instruction& FirstI = const_cast<Instruction&>(*GS.AccessingFunction
1758 ->getEntryBlock().begin());
1759 const Type* ElemTy = GV->getType()->getElementType();
1760 // FIXME: Pass Global's alignment when globals have alignment
1761 AllocaInst* Alloca = new AllocaInst(ElemTy, NULL, GV->getName(), &FirstI);
1762 if (!isa<UndefValue>(GV->getInitializer()))
1763 new StoreInst(GV->getInitializer(), Alloca, &FirstI);
Misha Brukmanfd939082005-04-21 23:48:37 +00001764
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001765 GV->replaceAllUsesWith(Alloca);
1766 GV->eraseFromParent();
1767 ++NumLocalized;
1768 return true;
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001769 }
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001770
1771 // If the global is never loaded (but may be stored to), it is dead.
1772 // Delete it now.
1773 if (!GS.isLoaded) {
1774 DEBUG(dbgs() << "GLOBAL NEVER LOADED: " << *GV);
1775
1776 // Delete any stores we can find to the global. We may not be able to
1777 // make it completely dead though.
1778 bool Changed = CleanupConstantGlobalUsers(GV, GV->getInitializer());
1779
1780 // If the global is dead now, delete it.
1781 if (GV->use_empty()) {
1782 GV->eraseFromParent();
1783 ++NumDeleted;
1784 Changed = true;
1785 }
1786 return Changed;
1787
1788 } else if (GS.StoredType <= GlobalStatus::isInitializerStored) {
1789 DEBUG(dbgs() << "MARKING CONSTANT: " << *GV);
1790 GV->setConstant(true);
1791
1792 // Clean up any obviously simplifiable users now.
1793 CleanupConstantGlobalUsers(GV, GV->getInitializer());
1794
1795 // If the global is dead now, just nuke it.
1796 if (GV->use_empty()) {
1797 DEBUG(dbgs() << " *** Marking constant allowed us to simplify "
1798 << "all users and delete global!\n");
1799 GV->eraseFromParent();
1800 ++NumDeleted;
1801 }
1802
1803 ++NumMarked;
1804 return true;
1805 } else if (!GV->getInitializer()->getType()->isSingleValueType()) {
1806 if (TargetData *TD = getAnalysisIfAvailable<TargetData>())
1807 if (GlobalVariable *FirstNewGV = SRAGlobal(GV, *TD)) {
1808 GVI = FirstNewGV; // Don't skip the newly produced globals!
1809 return true;
1810 }
1811 } else if (GS.StoredType == GlobalStatus::isStoredOnce) {
1812 // If the initial value for the global was an undef value, and if only
1813 // one other value was stored into it, we can just change the
1814 // initializer to be the stored value, then delete all stores to the
1815 // global. This allows us to mark it constant.
1816 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
1817 if (isa<UndefValue>(GV->getInitializer())) {
1818 // Change the initial value here.
1819 GV->setInitializer(SOVConstant);
1820
1821 // Clean up any obviously simplifiable users now.
1822 CleanupConstantGlobalUsers(GV, GV->getInitializer());
1823
1824 if (GV->use_empty()) {
1825 DEBUG(dbgs() << " *** Substituting initializer allowed us to "
1826 << "simplify all users and delete global!\n");
1827 GV->eraseFromParent();
1828 ++NumDeleted;
1829 } else {
1830 GVI = GV;
1831 }
1832 ++NumSubstitute;
1833 return true;
1834 }
1835
1836 // Try to optimize globals based on the knowledge that only one value
1837 // (besides its initializer) is ever stored to the global.
1838 if (OptimizeOnceStoredGlobal(GV, GS.StoredOnceValue, GVI,
1839 getAnalysisIfAvailable<TargetData>()))
1840 return true;
1841
1842 // Otherwise, if the global was not a boolean, we can shrink it to be a
1843 // boolean.
1844 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
1845 if (TryToShrinkGlobalToBoolean(GV, SOVConstant)) {
1846 ++NumShrunkToBool;
1847 return true;
1848 }
1849 }
1850
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001851 return false;
1852}
1853
Chris Lattnerfb217ad2005-05-08 22:18:06 +00001854/// ChangeCalleesToFastCall - Walk all of the direct calls of the specified
1855/// function, changing them to FastCC.
1856static void ChangeCalleesToFastCall(Function *F) {
1857 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
Duncan Sands548448a2008-02-18 17:32:13 +00001858 CallSite User(cast<Instruction>(*UI));
1859 User.setCallingConv(CallingConv::Fast);
Chris Lattnerfb217ad2005-05-08 22:18:06 +00001860 }
1861}
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001862
Devang Patel05988662008-09-25 21:00:45 +00001863static AttrListPtr StripNest(const AttrListPtr &Attrs) {
Chris Lattner58d74912008-03-12 17:45:29 +00001864 for (unsigned i = 0, e = Attrs.getNumSlots(); i != e; ++i) {
Devang Patel05988662008-09-25 21:00:45 +00001865 if ((Attrs.getSlot(i).Attrs & Attribute::Nest) == 0)
Duncan Sands548448a2008-02-18 17:32:13 +00001866 continue;
1867
Duncan Sands548448a2008-02-18 17:32:13 +00001868 // There can be only one.
Devang Patel05988662008-09-25 21:00:45 +00001869 return Attrs.removeAttr(Attrs.getSlot(i).Index, Attribute::Nest);
Duncan Sands3d5378f2008-02-16 20:56:04 +00001870 }
1871
1872 return Attrs;
1873}
1874
1875static void RemoveNestAttribute(Function *F) {
Devang Patel05988662008-09-25 21:00:45 +00001876 F->setAttributes(StripNest(F->getAttributes()));
Duncan Sands3d5378f2008-02-16 20:56:04 +00001877 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
Duncan Sands548448a2008-02-18 17:32:13 +00001878 CallSite User(cast<Instruction>(*UI));
Devang Patel05988662008-09-25 21:00:45 +00001879 User.setAttributes(StripNest(User.getAttributes()));
Duncan Sands3d5378f2008-02-16 20:56:04 +00001880 }
1881}
1882
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001883bool GlobalOpt::OptimizeFunctions(Module &M) {
1884 bool Changed = false;
1885 // Optimize functions.
1886 for (Module::iterator FI = M.begin(), E = M.end(); FI != E; ) {
1887 Function *F = FI++;
Duncan Sandsfc5940d2009-03-06 10:21:56 +00001888 // Functions without names cannot be referenced outside this module.
1889 if (!F->hasName() && !F->isDeclaration())
1890 F->setLinkage(GlobalValue::InternalLinkage);
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001891 F->removeDeadConstantUsers();
Chris Lattnerec4c7b92009-11-01 19:03:42 +00001892 if (F->use_empty() && (F->hasLocalLinkage() || F->hasLinkOnceLinkage())) {
1893 F->eraseFromParent();
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001894 Changed = true;
1895 ++NumFnDeleted;
Rafael Espindolabb46f522009-01-15 20:18:42 +00001896 } else if (F->hasLocalLinkage()) {
Duncan Sands3d5378f2008-02-16 20:56:04 +00001897 if (F->getCallingConv() == CallingConv::C && !F->isVarArg() &&
Jay Foad757068f2009-06-10 08:41:11 +00001898 !F->hasAddressTaken()) {
Duncan Sands3d5378f2008-02-16 20:56:04 +00001899 // If this function has C calling conventions, is not a varargs
1900 // function, and is only called directly, promote it to use the Fast
1901 // calling convention.
1902 F->setCallingConv(CallingConv::Fast);
1903 ChangeCalleesToFastCall(F);
1904 ++NumFastCallFns;
1905 Changed = true;
1906 }
1907
Devang Patel05988662008-09-25 21:00:45 +00001908 if (F->getAttributes().hasAttrSomewhere(Attribute::Nest) &&
Jay Foad757068f2009-06-10 08:41:11 +00001909 !F->hasAddressTaken()) {
Duncan Sands3d5378f2008-02-16 20:56:04 +00001910 // The function is not used by a trampoline intrinsic, so it is safe
1911 // to remove the 'nest' attribute.
1912 RemoveNestAttribute(F);
1913 ++NumNestRemoved;
1914 Changed = true;
1915 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001916 }
1917 }
1918 return Changed;
1919}
1920
1921bool GlobalOpt::OptimizeGlobalVars(Module &M) {
1922 bool Changed = false;
1923 for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
1924 GVI != E; ) {
1925 GlobalVariable *GV = GVI++;
Duncan Sandsfc5940d2009-03-06 10:21:56 +00001926 // Global variables without names cannot be referenced outside this module.
1927 if (!GV->hasName() && !GV->isDeclaration())
1928 GV->setLinkage(GlobalValue::InternalLinkage);
Dan Gohman01b97dd2009-11-23 16:22:21 +00001929 // Simplify the initializer.
1930 if (GV->hasInitializer())
1931 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GV->getInitializer())) {
Dan Gohmanf860db22010-04-02 03:04:37 +00001932 TargetData *TD = getAnalysisIfAvailable<TargetData>();
Dan Gohman01b97dd2009-11-23 16:22:21 +00001933 Constant *New = ConstantFoldConstantExpression(CE, TD);
1934 if (New && New != CE)
1935 GV->setInitializer(New);
1936 }
Rafael Espindolac4440e32011-01-19 16:32:21 +00001937
1938 Changed |= ProcessGlobal(GV, GVI);
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001939 }
1940 return Changed;
1941}
1942
1943/// FindGlobalCtors - Find the llvm.globalctors list, verifying that all
1944/// initializers have an init priority of 65535.
1945GlobalVariable *GlobalOpt::FindGlobalCtors(Module &M) {
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00001946 GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
1947 if (GV == 0) return 0;
1948
1949 // Found it, verify it's an array of { int, void()* }.
1950 const ArrayType *ATy =dyn_cast<ArrayType>(GV->getType()->getElementType());
1951 if (!ATy) return 0;
1952 const StructType *STy = dyn_cast<StructType>(ATy->getElementType());
1953 if (!STy || STy->getNumElements() != 2 ||
1954 !STy->getElementType(0)->isIntegerTy(32)) return 0;
1955 const PointerType *PFTy = dyn_cast<PointerType>(STy->getElementType(1));
1956 if (!PFTy) return 0;
1957 const FunctionType *FTy = dyn_cast<FunctionType>(PFTy->getElementType());
1958 if (!FTy || !FTy->getReturnType()->isVoidTy() ||
1959 FTy->isVarArg() || FTy->getNumParams() != 0)
1960 return 0;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001961
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00001962 // Verify that the initializer is simple enough for us to handle. We are
1963 // only allowed to optimize the initializer if it is unique.
1964 if (!GV->hasUniqueInitializer()) return 0;
1965
1966 ConstantArray *CA = dyn_cast<ConstantArray>(GV->getInitializer());
1967 if (!CA) return 0;
1968
1969 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i) {
1970 ConstantStruct *CS = dyn_cast<ConstantStruct>(*i);
1971 if (CS == 0) return 0;
1972
1973 if (isa<ConstantPointerNull>(CS->getOperand(1)))
1974 continue;
Chris Lattner7d8e58f2005-09-26 02:19:27 +00001975
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00001976 // Must have a function or null ptr.
1977 if (!isa<Function>(CS->getOperand(1)))
1978 return 0;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001979
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00001980 // Init priority must be standard.
1981 ConstantInt *CI = dyn_cast<ConstantInt>(CS->getOperand(0));
1982 if (!CI || CI->getZExtValue() != 65535)
1983 return 0;
1984 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001985
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00001986 return GV;
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001987}
1988
Chris Lattnerdb973e62005-09-26 02:31:18 +00001989/// ParseGlobalCtors - Given a llvm.global_ctors list that we can understand,
1990/// return a list of the functions and null terminator as a vector.
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001991static std::vector<Function*> ParseGlobalCtors(GlobalVariable *GV) {
1992 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
1993 std::vector<Function*> Result;
1994 Result.reserve(CA->getNumOperands());
Gabor Greif5e463212008-05-29 01:59:18 +00001995 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i) {
1996 ConstantStruct *CS = cast<ConstantStruct>(*i);
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001997 Result.push_back(dyn_cast<Function>(CS->getOperand(1)));
1998 }
1999 return Result;
2000}
2001
Chris Lattnerdb973e62005-09-26 02:31:18 +00002002/// InstallGlobalCtors - Given a specified llvm.global_ctors list, install the
2003/// specified array, returning the new global to use.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002004static GlobalVariable *InstallGlobalCtors(GlobalVariable *GCL,
Chris Lattner7b550cc2009-11-06 04:27:31 +00002005 const std::vector<Function*> &Ctors) {
Chris Lattnerdb973e62005-09-26 02:31:18 +00002006 // If we made a change, reassemble the initializer list.
2007 std::vector<Constant*> CSVals;
Chris Lattner7b550cc2009-11-06 04:27:31 +00002008 CSVals.push_back(ConstantInt::get(Type::getInt32Ty(GCL->getContext()),65535));
Chris Lattnerdb973e62005-09-26 02:31:18 +00002009 CSVals.push_back(0);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002010
Chris Lattnerdb973e62005-09-26 02:31:18 +00002011 // Create the new init list.
2012 std::vector<Constant*> CAList;
2013 for (unsigned i = 0, e = Ctors.size(); i != e; ++i) {
Chris Lattner79c11012005-09-26 04:44:35 +00002014 if (Ctors[i]) {
Chris Lattnerdb973e62005-09-26 02:31:18 +00002015 CSVals[1] = Ctors[i];
Chris Lattner79c11012005-09-26 04:44:35 +00002016 } else {
Chris Lattner7b550cc2009-11-06 04:27:31 +00002017 const Type *FTy = FunctionType::get(Type::getVoidTy(GCL->getContext()),
2018 false);
Owen Andersondebcb012009-07-29 22:17:13 +00002019 const PointerType *PFTy = PointerType::getUnqual(FTy);
Owen Andersona7235ea2009-07-31 20:28:14 +00002020 CSVals[1] = Constant::getNullValue(PFTy);
Chris Lattner7b550cc2009-11-06 04:27:31 +00002021 CSVals[0] = ConstantInt::get(Type::getInt32Ty(GCL->getContext()),
2022 2147483647);
Chris Lattnerdb973e62005-09-26 02:31:18 +00002023 }
Chris Lattner7b550cc2009-11-06 04:27:31 +00002024 CAList.push_back(ConstantStruct::get(GCL->getContext(), CSVals, false));
Chris Lattnerdb973e62005-09-26 02:31:18 +00002025 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002026
Chris Lattnerdb973e62005-09-26 02:31:18 +00002027 // Create the array initializer.
2028 const Type *StructTy =
Nick Lewyckyc332fba2009-09-19 20:30:26 +00002029 cast<ArrayType>(GCL->getType()->getElementType())->getElementType();
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002030 Constant *CA = ConstantArray::get(ArrayType::get(StructTy,
Nick Lewyckyc332fba2009-09-19 20:30:26 +00002031 CAList.size()), CAList);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002032
Chris Lattnerdb973e62005-09-26 02:31:18 +00002033 // If we didn't change the number of elements, don't create a new GV.
2034 if (CA->getType() == GCL->getInitializer()->getType()) {
2035 GCL->setInitializer(CA);
2036 return GCL;
2037 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002038
Chris Lattnerdb973e62005-09-26 02:31:18 +00002039 // Create the new global and insert it next to the existing list.
Chris Lattner7b550cc2009-11-06 04:27:31 +00002040 GlobalVariable *NGV = new GlobalVariable(CA->getType(), GCL->isConstant(),
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +00002041 GCL->getLinkage(), CA, "",
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +00002042 GCL->isThreadLocal());
Chris Lattnerdb973e62005-09-26 02:31:18 +00002043 GCL->getParent()->getGlobalList().insert(GCL, NGV);
Chris Lattner046800a2007-02-11 01:08:35 +00002044 NGV->takeName(GCL);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002045
Chris Lattnerdb973e62005-09-26 02:31:18 +00002046 // Nuke the old list, replacing any uses with the new one.
2047 if (!GCL->use_empty()) {
2048 Constant *V = NGV;
2049 if (V->getType() != GCL->getType())
Owen Andersonbaf3c402009-07-29 18:55:55 +00002050 V = ConstantExpr::getBitCast(V, GCL->getType());
Chris Lattnerdb973e62005-09-26 02:31:18 +00002051 GCL->replaceAllUsesWith(V);
2052 }
2053 GCL->eraseFromParent();
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002054
Chris Lattnerdb973e62005-09-26 02:31:18 +00002055 if (Ctors.size())
2056 return NGV;
2057 else
2058 return 0;
2059}
Chris Lattner79c11012005-09-26 04:44:35 +00002060
2061
Chris Lattner1945d582010-12-07 04:33:29 +00002062static Constant *getVal(DenseMap<Value*, Constant*> &ComputedValues, Value *V) {
Chris Lattner79c11012005-09-26 04:44:35 +00002063 if (Constant *CV = dyn_cast<Constant>(V)) return CV;
2064 Constant *R = ComputedValues[V];
2065 assert(R && "Reference to an uncomputed value!");
2066 return R;
2067}
2068
Chris Lattner1945d582010-12-07 04:33:29 +00002069static inline bool
2070isSimpleEnoughValueToCommit(Constant *C,
2071 SmallPtrSet<Constant*, 8> &SimpleConstants);
2072
2073
2074/// isSimpleEnoughValueToCommit - Return true if the specified constant can be
2075/// handled by the code generator. We don't want to generate something like:
2076/// void *X = &X/42;
2077/// because the code generator doesn't have a relocation that can handle that.
2078///
2079/// This function should be called if C was not found (but just got inserted)
2080/// in SimpleConstants to avoid having to rescan the same constants all the
2081/// time.
2082static bool isSimpleEnoughValueToCommitHelper(Constant *C,
2083 SmallPtrSet<Constant*, 8> &SimpleConstants) {
2084 // Simple integer, undef, constant aggregate zero, global addresses, etc are
2085 // all supported.
2086 if (C->getNumOperands() == 0 || isa<BlockAddress>(C) ||
2087 isa<GlobalValue>(C))
2088 return true;
2089
2090 // Aggregate values are safe if all their elements are.
2091 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C) ||
2092 isa<ConstantVector>(C)) {
2093 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i) {
2094 Constant *Op = cast<Constant>(C->getOperand(i));
2095 if (!isSimpleEnoughValueToCommit(Op, SimpleConstants))
2096 return false;
2097 }
2098 return true;
2099 }
2100
2101 // We don't know exactly what relocations are allowed in constant expressions,
2102 // so we allow &global+constantoffset, which is safe and uniformly supported
2103 // across targets.
2104 ConstantExpr *CE = cast<ConstantExpr>(C);
2105 switch (CE->getOpcode()) {
2106 case Instruction::BitCast:
2107 case Instruction::IntToPtr:
2108 case Instruction::PtrToInt:
2109 // These casts are always fine if the casted value is.
2110 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants);
2111
2112 // GEP is fine if it is simple + constant offset.
2113 case Instruction::GetElementPtr:
2114 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
2115 if (!isa<ConstantInt>(CE->getOperand(i)))
2116 return false;
2117 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants);
2118
2119 case Instruction::Add:
2120 // We allow simple+cst.
2121 if (!isa<ConstantInt>(CE->getOperand(1)))
2122 return false;
2123 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants);
2124 }
2125 return false;
2126}
2127
2128static inline bool
2129isSimpleEnoughValueToCommit(Constant *C,
2130 SmallPtrSet<Constant*, 8> &SimpleConstants) {
2131 // If we already checked this constant, we win.
2132 if (!SimpleConstants.insert(C)) return true;
2133 // Check the constant.
2134 return isSimpleEnoughValueToCommitHelper(C, SimpleConstants);
2135}
2136
2137
Chris Lattner79c11012005-09-26 04:44:35 +00002138/// isSimpleEnoughPointerToCommit - Return true if this constant is simple
Owen Andersoncff6b372011-01-14 22:19:20 +00002139/// enough for us to understand. In particular, if it is a cast to anything
2140/// other than from one pointer type to another pointer type, we punt.
2141/// We basically just support direct accesses to globals and GEP's of
Chris Lattner79c11012005-09-26 04:44:35 +00002142/// globals. This should be kept up to date with CommitValueTo.
Chris Lattner7b550cc2009-11-06 04:27:31 +00002143static bool isSimpleEnoughPointerToCommit(Constant *C) {
Dan Gohmance5de5b2009-09-07 22:42:05 +00002144 // Conservatively, avoid aggregate types. This is because we don't
2145 // want to worry about them partially overlapping other stores.
2146 if (!cast<PointerType>(C->getType())->getElementType()->isSingleValueType())
2147 return false;
2148
Dan Gohmanfd54a892009-09-07 22:31:26 +00002149 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
Mikhail Glushenkov99fca5d2010-10-19 16:47:23 +00002150 // Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or
Dan Gohmanfd54a892009-09-07 22:31:26 +00002151 // external globals.
Mikhail Glushenkov99fca5d2010-10-19 16:47:23 +00002152 return GV->hasUniqueInitializer();
Dan Gohmanfd54a892009-09-07 22:31:26 +00002153
Owen Andersone95a32c2011-01-14 22:31:13 +00002154 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002155 // Handle a constantexpr gep.
2156 if (CE->getOpcode() == Instruction::GetElementPtr &&
Dan Gohmanc62482d2009-09-07 22:40:13 +00002157 isa<GlobalVariable>(CE->getOperand(0)) &&
2158 cast<GEPOperator>(CE)->isInBounds()) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002159 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
Mikhail Glushenkov99fca5d2010-10-19 16:47:23 +00002160 // Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or
Dan Gohmanfd54a892009-09-07 22:31:26 +00002161 // external globals.
Mikhail Glushenkov99fca5d2010-10-19 16:47:23 +00002162 if (!GV->hasUniqueInitializer())
Dan Gohmanfd54a892009-09-07 22:31:26 +00002163 return false;
Dan Gohman80bdc962009-09-07 22:44:55 +00002164
Dan Gohman80bdc962009-09-07 22:44:55 +00002165 // The first index must be zero.
Oscar Fuentesee56c422010-08-02 06:00:15 +00002166 ConstantInt *CI = dyn_cast<ConstantInt>(*llvm::next(CE->op_begin()));
Dan Gohman80bdc962009-09-07 22:44:55 +00002167 if (!CI || !CI->isZero()) return false;
Dan Gohman80bdc962009-09-07 22:44:55 +00002168
2169 // The remaining indices must be compile-time known integers within the
Dan Gohmane6992f72009-09-10 23:37:55 +00002170 // notional bounds of the corresponding static array types.
2171 if (!CE->isGEPWithNoNotionalOverIndexing())
2172 return false;
Dan Gohman80bdc962009-09-07 22:44:55 +00002173
Dan Gohmanc6f69e92009-10-05 16:36:26 +00002174 return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
Owen Andersoncff6b372011-01-14 22:19:20 +00002175
2176 // A constantexpr bitcast from a pointer to another pointer is a no-op,
2177 // and we know how to evaluate it by moving the bitcast from the pointer
2178 // operand to the value operand.
2179 } else if (CE->getOpcode() == Instruction::BitCast &&
Chris Lattnerd5f656f2011-01-16 02:05:10 +00002180 isa<GlobalVariable>(CE->getOperand(0))) {
Owen Andersoncff6b372011-01-14 22:19:20 +00002181 // Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or
2182 // external globals.
Chris Lattnerd5f656f2011-01-16 02:05:10 +00002183 return cast<GlobalVariable>(CE->getOperand(0))->hasUniqueInitializer();
Chris Lattner798b4d52005-09-26 06:52:44 +00002184 }
Owen Andersone95a32c2011-01-14 22:31:13 +00002185 }
2186
Chris Lattner79c11012005-09-26 04:44:35 +00002187 return false;
2188}
2189
Chris Lattner798b4d52005-09-26 06:52:44 +00002190/// EvaluateStoreInto - Evaluate a piece of a constantexpr store into a global
2191/// initializer. This returns 'Init' modified to reflect 'Val' stored into it.
2192/// At this point, the GEP operands of Addr [0, OpNo) have been stepped into.
2193static Constant *EvaluateStoreInto(Constant *Init, Constant *Val,
Chris Lattner7b550cc2009-11-06 04:27:31 +00002194 ConstantExpr *Addr, unsigned OpNo) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002195 // Base case of the recursion.
2196 if (OpNo == Addr->getNumOperands()) {
2197 assert(Val->getType() == Init->getType() && "Type mismatch!");
2198 return Val;
2199 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002200
Chris Lattnera0e9a242010-01-07 01:16:21 +00002201 std::vector<Constant*> Elts;
Chris Lattner798b4d52005-09-26 06:52:44 +00002202 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002203
2204 // Break up the constant into its elements.
2205 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
Gabor Greif5e463212008-05-29 01:59:18 +00002206 for (User::op_iterator i = CS->op_begin(), e = CS->op_end(); i != e; ++i)
2207 Elts.push_back(cast<Constant>(*i));
Chris Lattner798b4d52005-09-26 06:52:44 +00002208 } else if (isa<ConstantAggregateZero>(Init)) {
2209 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
Owen Andersona7235ea2009-07-31 20:28:14 +00002210 Elts.push_back(Constant::getNullValue(STy->getElementType(i)));
Chris Lattner798b4d52005-09-26 06:52:44 +00002211 } else if (isa<UndefValue>(Init)) {
2212 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002213 Elts.push_back(UndefValue::get(STy->getElementType(i)));
Chris Lattner798b4d52005-09-26 06:52:44 +00002214 } else {
Torok Edwinc23197a2009-07-14 16:55:14 +00002215 llvm_unreachable("This code is out of sync with "
Chris Lattner798b4d52005-09-26 06:52:44 +00002216 " ConstantFoldLoadThroughGEPConstantExpr");
2217 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002218
Chris Lattner798b4d52005-09-26 06:52:44 +00002219 // Replace the element that we are supposed to.
Reid Spencerb83eb642006-10-20 07:07:24 +00002220 ConstantInt *CU = cast<ConstantInt>(Addr->getOperand(OpNo));
2221 unsigned Idx = CU->getZExtValue();
2222 assert(Idx < STy->getNumElements() && "Struct index out of range!");
Chris Lattner7b550cc2009-11-06 04:27:31 +00002223 Elts[Idx] = EvaluateStoreInto(Elts[Idx], Val, Addr, OpNo+1);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002224
Chris Lattner798b4d52005-09-26 06:52:44 +00002225 // Return the modified struct.
Chris Lattner7b550cc2009-11-06 04:27:31 +00002226 return ConstantStruct::get(Init->getContext(), &Elts[0], Elts.size(),
2227 STy->isPacked());
Chris Lattner798b4d52005-09-26 06:52:44 +00002228 } else {
2229 ConstantInt *CI = cast<ConstantInt>(Addr->getOperand(OpNo));
Chris Lattnera0e9a242010-01-07 01:16:21 +00002230 const SequentialType *InitTy = cast<SequentialType>(Init->getType());
Chris Lattner798b4d52005-09-26 06:52:44 +00002231
Chris Lattnera0e9a242010-01-07 01:16:21 +00002232 uint64_t NumElts;
2233 if (const ArrayType *ATy = dyn_cast<ArrayType>(InitTy))
2234 NumElts = ATy->getNumElements();
2235 else
2236 NumElts = cast<VectorType>(InitTy)->getNumElements();
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002237
2238
Chris Lattner798b4d52005-09-26 06:52:44 +00002239 // Break up the array into elements.
Chris Lattner798b4d52005-09-26 06:52:44 +00002240 if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
Gabor Greif5e463212008-05-29 01:59:18 +00002241 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i)
2242 Elts.push_back(cast<Constant>(*i));
Chris Lattner4039bd02010-01-07 01:20:20 +00002243 } else if (ConstantVector *CV = dyn_cast<ConstantVector>(Init)) {
2244 for (User::op_iterator i = CV->op_begin(), e = CV->op_end(); i != e; ++i)
2245 Elts.push_back(cast<Constant>(*i));
Chris Lattner798b4d52005-09-26 06:52:44 +00002246 } else if (isa<ConstantAggregateZero>(Init)) {
Chris Lattnera0e9a242010-01-07 01:16:21 +00002247 Elts.assign(NumElts, Constant::getNullValue(InitTy->getElementType()));
Chris Lattner798b4d52005-09-26 06:52:44 +00002248 } else {
Chris Lattnera0e9a242010-01-07 01:16:21 +00002249 assert(isa<UndefValue>(Init) && "This code is out of sync with "
Chris Lattner798b4d52005-09-26 06:52:44 +00002250 " ConstantFoldLoadThroughGEPConstantExpr");
Chris Lattnera0e9a242010-01-07 01:16:21 +00002251 Elts.assign(NumElts, UndefValue::get(InitTy->getElementType()));
Chris Lattner798b4d52005-09-26 06:52:44 +00002252 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002253
Chris Lattnera0e9a242010-01-07 01:16:21 +00002254 assert(CI->getZExtValue() < NumElts);
Reid Spencerb83eb642006-10-20 07:07:24 +00002255 Elts[CI->getZExtValue()] =
Chris Lattner7b550cc2009-11-06 04:27:31 +00002256 EvaluateStoreInto(Elts[CI->getZExtValue()], Val, Addr, OpNo+1);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002257
Duncan Sands1df98592010-02-16 11:11:14 +00002258 if (Init->getType()->isArrayTy())
Chris Lattnera0e9a242010-01-07 01:16:21 +00002259 return ConstantArray::get(cast<ArrayType>(InitTy), Elts);
Chris Lattner2ca5c862011-02-15 00:14:00 +00002260 return ConstantVector::get(Elts);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002261 }
Chris Lattner798b4d52005-09-26 06:52:44 +00002262}
2263
Chris Lattner79c11012005-09-26 04:44:35 +00002264/// CommitValueTo - We have decided that Addr (which satisfies the predicate
2265/// isSimpleEnoughPointerToCommit) should get Val as its value. Make it happen.
Chris Lattner7b550cc2009-11-06 04:27:31 +00002266static void CommitValueTo(Constant *Val, Constant *Addr) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002267 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Addr)) {
2268 assert(GV->hasInitializer());
2269 GV->setInitializer(Val);
2270 return;
2271 }
Chris Lattnera0e9a242010-01-07 01:16:21 +00002272
Chris Lattner798b4d52005-09-26 06:52:44 +00002273 ConstantExpr *CE = cast<ConstantExpr>(Addr);
2274 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
Chris Lattnera0e9a242010-01-07 01:16:21 +00002275 GV->setInitializer(EvaluateStoreInto(GV->getInitializer(), Val, CE, 2));
Chris Lattner79c11012005-09-26 04:44:35 +00002276}
2277
Chris Lattner562a0552005-09-26 05:16:34 +00002278/// ComputeLoadResult - Return the value that would be computed by a load from
2279/// P after the stores reflected by 'memory' have been performed. If we can't
2280/// decide, return null.
Chris Lattner04de1cf2005-09-26 05:15:37 +00002281static Constant *ComputeLoadResult(Constant *P,
Chris Lattner7b550cc2009-11-06 04:27:31 +00002282 const DenseMap<Constant*, Constant*> &Memory) {
Chris Lattner04de1cf2005-09-26 05:15:37 +00002283 // If this memory location has been recently stored, use the stored value: it
2284 // is the most up-to-date.
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002285 DenseMap<Constant*, Constant*>::const_iterator I = Memory.find(P);
Chris Lattner04de1cf2005-09-26 05:15:37 +00002286 if (I != Memory.end()) return I->second;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002287
Chris Lattner04de1cf2005-09-26 05:15:37 +00002288 // Access it.
2289 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(P)) {
Dan Gohman82555732009-08-19 18:20:44 +00002290 if (GV->hasDefinitiveInitializer())
Chris Lattner04de1cf2005-09-26 05:15:37 +00002291 return GV->getInitializer();
2292 return 0;
Chris Lattner04de1cf2005-09-26 05:15:37 +00002293 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002294
Chris Lattner798b4d52005-09-26 06:52:44 +00002295 // Handle a constantexpr getelementptr.
2296 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(P))
2297 if (CE->getOpcode() == Instruction::GetElementPtr &&
2298 isa<GlobalVariable>(CE->getOperand(0))) {
2299 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
Dan Gohman82555732009-08-19 18:20:44 +00002300 if (GV->hasDefinitiveInitializer())
Dan Gohmanc6f69e92009-10-05 16:36:26 +00002301 return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
Chris Lattner798b4d52005-09-26 06:52:44 +00002302 }
2303
2304 return 0; // don't know how to evaluate.
Chris Lattner04de1cf2005-09-26 05:15:37 +00002305}
2306
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002307/// EvaluateFunction - Evaluate a call to function F, returning true if
2308/// successful, false if we can't evaluate it. ActualArgs contains the formal
2309/// arguments for the function.
Chris Lattnercd271422005-09-27 04:45:34 +00002310static bool EvaluateFunction(Function *F, Constant *&RetVal,
Duncan Sandsfa6a1cf2009-08-17 14:33:27 +00002311 const SmallVectorImpl<Constant*> &ActualArgs,
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002312 std::vector<Function*> &CallStack,
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002313 DenseMap<Constant*, Constant*> &MutatedMemory,
Chris Lattner1945d582010-12-07 04:33:29 +00002314 std::vector<GlobalVariable*> &AllocaTmps,
2315 SmallPtrSet<Constant*, 8> &SimpleConstants,
2316 const TargetData *TD) {
Chris Lattnercd271422005-09-27 04:45:34 +00002317 // Check to see if this function is already executing (recursion). If so,
2318 // bail out. TODO: we might want to accept limited recursion.
2319 if (std::find(CallStack.begin(), CallStack.end(), F) != CallStack.end())
2320 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002321
Chris Lattnercd271422005-09-27 04:45:34 +00002322 CallStack.push_back(F);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002323
Chris Lattner79c11012005-09-26 04:44:35 +00002324 /// Values - As we compute SSA register values, we store their contents here.
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002325 DenseMap<Value*, Constant*> Values;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002326
Chris Lattnercd271422005-09-27 04:45:34 +00002327 // Initialize arguments to the incoming values specified.
2328 unsigned ArgNo = 0;
2329 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); AI != E;
2330 ++AI, ++ArgNo)
2331 Values[AI] = ActualArgs[ArgNo];
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002332
Chris Lattnercdf98be2005-09-26 04:57:38 +00002333 /// ExecutedBlocks - We only handle non-looping, non-recursive code. As such,
2334 /// we can only evaluate any one basic block at most once. This set keeps
2335 /// track of what we have executed so we can detect recursive cases etc.
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002336 SmallPtrSet<BasicBlock*, 32> ExecutedBlocks;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002337
Chris Lattner79c11012005-09-26 04:44:35 +00002338 // CurInst - The current instruction we're evaluating.
2339 BasicBlock::iterator CurInst = F->begin()->begin();
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002340
Chris Lattner79c11012005-09-26 04:44:35 +00002341 // This is the main evaluation loop.
2342 while (1) {
2343 Constant *InstResult = 0;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002344
Chris Lattner79c11012005-09-26 04:44:35 +00002345 if (StoreInst *SI = dyn_cast<StoreInst>(CurInst)) {
Chris Lattnercd271422005-09-27 04:45:34 +00002346 if (SI->isVolatile()) return false; // no volatile accesses.
Chris Lattner79c11012005-09-26 04:44:35 +00002347 Constant *Ptr = getVal(Values, SI->getOperand(1));
Chris Lattner7b550cc2009-11-06 04:27:31 +00002348 if (!isSimpleEnoughPointerToCommit(Ptr))
Chris Lattner79c11012005-09-26 04:44:35 +00002349 // If this is too complex for us to commit, reject it.
Chris Lattnercd271422005-09-27 04:45:34 +00002350 return false;
Chris Lattner1945d582010-12-07 04:33:29 +00002351
Chris Lattner79c11012005-09-26 04:44:35 +00002352 Constant *Val = getVal(Values, SI->getOperand(0));
Chris Lattner1945d582010-12-07 04:33:29 +00002353
2354 // If this might be too difficult for the backend to handle (e.g. the addr
2355 // of one global variable divided by another) then we can't commit it.
2356 if (!isSimpleEnoughValueToCommit(Val, SimpleConstants))
2357 return false;
Owen Andersoncff6b372011-01-14 22:19:20 +00002358
2359 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
2360 if (CE->getOpcode() == Instruction::BitCast) {
2361 // If we're evaluating a store through a bitcast, then we need
2362 // to pull the bitcast off the pointer type and push it onto the
2363 // stored value.
Chris Lattnerd5f656f2011-01-16 02:05:10 +00002364 Ptr = CE->getOperand(0);
Owen Andersoncff6b372011-01-14 22:19:20 +00002365
Chris Lattnerd5f656f2011-01-16 02:05:10 +00002366 const Type *NewTy=cast<PointerType>(Ptr->getType())->getElementType();
Owen Andersoncff6b372011-01-14 22:19:20 +00002367
Owen Anderson66f708f2011-01-16 04:33:33 +00002368 // In order to push the bitcast onto the stored value, a bitcast
2369 // from NewTy to Val's type must be legal. If it's not, we can try
2370 // introspecting NewTy to find a legal conversion.
2371 while (!Val->getType()->canLosslesslyBitCastTo(NewTy)) {
2372 // If NewTy is a struct, we can convert the pointer to the struct
2373 // into a pointer to its first member.
2374 // FIXME: This could be extended to support arrays as well.
2375 if (const StructType *STy = dyn_cast<StructType>(NewTy)) {
2376 NewTy = STy->getTypeAtIndex(0U);
2377
2378 const IntegerType *IdxTy =IntegerType::get(NewTy->getContext(), 32);
2379 Constant *IdxZero = ConstantInt::get(IdxTy, 0, false);
2380 Constant * const IdxList[] = {IdxZero, IdxZero};
2381
2382 Ptr = ConstantExpr::getGetElementPtr(Ptr, IdxList, 2);
Owen Andersoncff6b372011-01-14 22:19:20 +00002383
Owen Anderson66f708f2011-01-16 04:33:33 +00002384 // If we can't improve the situation by introspecting NewTy,
2385 // we have to give up.
2386 } else {
2387 return 0;
2388 }
Owen Andersoncff6b372011-01-14 22:19:20 +00002389 }
2390
Owen Anderson66f708f2011-01-16 04:33:33 +00002391 // If we found compatible types, go ahead and push the bitcast
2392 // onto the stored value.
Owen Andersoncff6b372011-01-14 22:19:20 +00002393 Val = ConstantExpr::getBitCast(Val, NewTy);
2394 }
2395
Chris Lattner79c11012005-09-26 04:44:35 +00002396 MutatedMemory[Ptr] = Val;
2397 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CurInst)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002398 InstResult = ConstantExpr::get(BO->getOpcode(),
Chris Lattner79c11012005-09-26 04:44:35 +00002399 getVal(Values, BO->getOperand(0)),
2400 getVal(Values, BO->getOperand(1)));
Reid Spencere4d87aa2006-12-23 06:05:41 +00002401 } else if (CmpInst *CI = dyn_cast<CmpInst>(CurInst)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002402 InstResult = ConstantExpr::getCompare(CI->getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00002403 getVal(Values, CI->getOperand(0)),
2404 getVal(Values, CI->getOperand(1)));
Chris Lattner79c11012005-09-26 04:44:35 +00002405 } else if (CastInst *CI = dyn_cast<CastInst>(CurInst)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002406 InstResult = ConstantExpr::getCast(CI->getOpcode(),
Chris Lattner9a989f02006-11-30 17:26:08 +00002407 getVal(Values, CI->getOperand(0)),
Chris Lattner79c11012005-09-26 04:44:35 +00002408 CI->getType());
2409 } else if (SelectInst *SI = dyn_cast<SelectInst>(CurInst)) {
Gabor Greif9e4f2432010-06-24 14:42:01 +00002410 InstResult = ConstantExpr::getSelect(getVal(Values, SI->getOperand(0)),
Eric Christopher551754c2010-04-16 23:37:20 +00002411 getVal(Values, SI->getOperand(1)),
2412 getVal(Values, SI->getOperand(2)));
Chris Lattner04de1cf2005-09-26 05:15:37 +00002413 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurInst)) {
2414 Constant *P = getVal(Values, GEP->getOperand(0));
Chris Lattner55eb1c42007-01-31 04:40:53 +00002415 SmallVector<Constant*, 8> GEPOps;
Gabor Greif5e463212008-05-29 01:59:18 +00002416 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end();
2417 i != e; ++i)
2418 GEPOps.push_back(getVal(Values, *i));
Dan Gohman4a7e6b72009-09-07 22:34:43 +00002419 InstResult = cast<GEPOperator>(GEP)->isInBounds() ?
2420 ConstantExpr::getInBoundsGetElementPtr(P, &GEPOps[0], GEPOps.size()) :
2421 ConstantExpr::getGetElementPtr(P, &GEPOps[0], GEPOps.size());
Chris Lattner04de1cf2005-09-26 05:15:37 +00002422 } else if (LoadInst *LI = dyn_cast<LoadInst>(CurInst)) {
Chris Lattnercd271422005-09-27 04:45:34 +00002423 if (LI->isVolatile()) return false; // no volatile accesses.
Chris Lattner04de1cf2005-09-26 05:15:37 +00002424 InstResult = ComputeLoadResult(getVal(Values, LI->getOperand(0)),
Chris Lattner7b550cc2009-11-06 04:27:31 +00002425 MutatedMemory);
Chris Lattnercd271422005-09-27 04:45:34 +00002426 if (InstResult == 0) return false; // Could not evaluate load.
Chris Lattnera22fdb02005-09-26 17:07:09 +00002427 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(CurInst)) {
Chris Lattnercd271422005-09-27 04:45:34 +00002428 if (AI->isArrayAllocation()) return false; // Cannot handle array allocs.
Chris Lattnera22fdb02005-09-26 17:07:09 +00002429 const Type *Ty = AI->getType()->getElementType();
Chris Lattner7b550cc2009-11-06 04:27:31 +00002430 AllocaTmps.push_back(new GlobalVariable(Ty, false,
Chris Lattnera22fdb02005-09-26 17:07:09 +00002431 GlobalValue::InternalLinkage,
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002432 UndefValue::get(Ty),
Chris Lattnera22fdb02005-09-26 17:07:09 +00002433 AI->getName()));
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002434 InstResult = AllocaTmps.back();
Chris Lattnercd271422005-09-27 04:45:34 +00002435 } else if (CallInst *CI = dyn_cast<CallInst>(CurInst)) {
Devang Patel412a4462009-03-09 23:04:12 +00002436
2437 // Debug info can safely be ignored here.
2438 if (isa<DbgInfoIntrinsic>(CI)) {
2439 ++CurInst;
2440 continue;
2441 }
2442
Chris Lattner7cd580f2006-07-07 21:37:01 +00002443 // Cannot handle inline asm.
Gabor Greifa9b23132010-04-20 13:13:04 +00002444 if (isa<InlineAsm>(CI->getCalledValue())) return false;
Chris Lattner7cd580f2006-07-07 21:37:01 +00002445
Chris Lattnercd271422005-09-27 04:45:34 +00002446 // Resolve function pointers.
Gabor Greifa3997812010-07-22 10:37:47 +00002447 Function *Callee = dyn_cast<Function>(getVal(Values,
2448 CI->getCalledValue()));
Chris Lattnercd271422005-09-27 04:45:34 +00002449 if (!Callee) return false; // Cannot resolve.
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002450
Duncan Sandsfa6a1cf2009-08-17 14:33:27 +00002451 SmallVector<Constant*, 8> Formals;
Gabor Greif9e4f2432010-06-24 14:42:01 +00002452 CallSite CS(CI);
2453 for (User::op_iterator i = CS.arg_begin(), e = CS.arg_end();
Gabor Greif5e463212008-05-29 01:59:18 +00002454 i != e; ++i)
2455 Formals.push_back(getVal(Values, *i));
Duncan Sandsfa6a1cf2009-08-17 14:33:27 +00002456
Reid Spencer5cbf9852007-01-30 20:08:39 +00002457 if (Callee->isDeclaration()) {
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002458 // If this is a function we can constant fold, do it.
Duncan Sandsfa6a1cf2009-08-17 14:33:27 +00002459 if (Constant *C = ConstantFoldCall(Callee, Formals.data(),
Chris Lattner6c1f5652007-01-30 23:14:52 +00002460 Formals.size())) {
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002461 InstResult = C;
2462 } else {
2463 return false;
2464 }
2465 } else {
2466 if (Callee->getFunctionType()->isVarArg())
2467 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002468
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002469 Constant *RetVal;
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002470 // Execute the call, if successful, use the return value.
2471 if (!EvaluateFunction(Callee, RetVal, Formals, CallStack,
Chris Lattner1945d582010-12-07 04:33:29 +00002472 MutatedMemory, AllocaTmps, SimpleConstants, TD))
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002473 return false;
2474 InstResult = RetVal;
2475 }
Reid Spencer3ed469c2006-11-02 20:25:50 +00002476 } else if (isa<TerminatorInst>(CurInst)) {
Chris Lattnercdf98be2005-09-26 04:57:38 +00002477 BasicBlock *NewBB = 0;
2478 if (BranchInst *BI = dyn_cast<BranchInst>(CurInst)) {
2479 if (BI->isUnconditional()) {
2480 NewBB = BI->getSuccessor(0);
2481 } else {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002482 ConstantInt *Cond =
2483 dyn_cast<ConstantInt>(getVal(Values, BI->getCondition()));
Chris Lattner97d1fad2007-01-12 18:30:11 +00002484 if (!Cond) return false; // Cannot determine.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002485
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002486 NewBB = BI->getSuccessor(!Cond->getZExtValue());
Chris Lattnercdf98be2005-09-26 04:57:38 +00002487 }
2488 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(CurInst)) {
2489 ConstantInt *Val =
2490 dyn_cast<ConstantInt>(getVal(Values, SI->getCondition()));
Chris Lattnercd271422005-09-27 04:45:34 +00002491 if (!Val) return false; // Cannot determine.
Chris Lattnercdf98be2005-09-26 04:57:38 +00002492 NewBB = SI->getSuccessor(SI->findCaseValue(Val));
Chris Lattnerb3d5a652009-10-29 05:51:50 +00002493 } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(CurInst)) {
2494 Value *Val = getVal(Values, IBI->getAddress())->stripPointerCasts();
2495 if (BlockAddress *BA = dyn_cast<BlockAddress>(Val))
2496 NewBB = BA->getBasicBlock();
Chris Lattnercdfc9402009-11-01 01:27:45 +00002497 else
2498 return false; // Cannot determine.
Chris Lattnercdf98be2005-09-26 04:57:38 +00002499 } else if (ReturnInst *RI = dyn_cast<ReturnInst>(CurInst)) {
Chris Lattnercd271422005-09-27 04:45:34 +00002500 if (RI->getNumOperands())
2501 RetVal = getVal(Values, RI->getOperand(0));
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002502
Chris Lattnercd271422005-09-27 04:45:34 +00002503 CallStack.pop_back(); // return from fn.
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002504 return true; // We succeeded at evaluating this ctor!
Chris Lattnercdf98be2005-09-26 04:57:38 +00002505 } else {
Chris Lattnercd271422005-09-27 04:45:34 +00002506 // invoke, unwind, unreachable.
2507 return false; // Cannot handle this terminator.
Chris Lattnercdf98be2005-09-26 04:57:38 +00002508 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002509
Chris Lattnercdf98be2005-09-26 04:57:38 +00002510 // Okay, we succeeded in evaluating this control flow. See if we have
Chris Lattnercd271422005-09-27 04:45:34 +00002511 // executed the new block before. If so, we have a looping function,
2512 // which we cannot evaluate in reasonable time.
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002513 if (!ExecutedBlocks.insert(NewBB))
Chris Lattnercd271422005-09-27 04:45:34 +00002514 return false; // looped!
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002515
Chris Lattnercdf98be2005-09-26 04:57:38 +00002516 // Okay, we have never been in this block before. Check to see if there
2517 // are any PHI nodes. If so, evaluate them with information about where
2518 // we came from.
2519 BasicBlock *OldBB = CurInst->getParent();
2520 CurInst = NewBB->begin();
2521 PHINode *PN;
2522 for (; (PN = dyn_cast<PHINode>(CurInst)); ++CurInst)
2523 Values[PN] = getVal(Values, PN->getIncomingValueForBlock(OldBB));
2524
2525 // Do NOT increment CurInst. We know that the terminator had no value.
2526 continue;
Chris Lattner79c11012005-09-26 04:44:35 +00002527 } else {
Chris Lattner79c11012005-09-26 04:44:35 +00002528 // Did not know how to evaluate this!
Chris Lattnercd271422005-09-27 04:45:34 +00002529 return false;
Chris Lattner79c11012005-09-26 04:44:35 +00002530 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002531
Chris Lattner1945d582010-12-07 04:33:29 +00002532 if (!CurInst->use_empty()) {
2533 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(InstResult))
2534 InstResult = ConstantFoldConstantExpression(CE, TD);
2535
Chris Lattner79c11012005-09-26 04:44:35 +00002536 Values[CurInst] = InstResult;
Chris Lattner1945d582010-12-07 04:33:29 +00002537 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002538
Chris Lattner79c11012005-09-26 04:44:35 +00002539 // Advance program counter.
2540 ++CurInst;
2541 }
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002542}
2543
2544/// EvaluateStaticConstructor - Evaluate static constructors in the function, if
2545/// we can. Return true if we can, false otherwise.
Chris Lattner1945d582010-12-07 04:33:29 +00002546static bool EvaluateStaticConstructor(Function *F, const TargetData *TD) {
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002547 /// MutatedMemory - For each store we execute, we update this map. Loads
2548 /// check this to get the most up-to-date value. If evaluation is successful,
2549 /// this state is committed to the process.
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002550 DenseMap<Constant*, Constant*> MutatedMemory;
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002551
2552 /// AllocaTmps - To 'execute' an alloca, we create a temporary global variable
2553 /// to represent its body. This vector is needed so we can delete the
2554 /// temporary globals when we are done.
2555 std::vector<GlobalVariable*> AllocaTmps;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002556
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002557 /// CallStack - This is used to detect recursion. In pathological situations
2558 /// we could hit exponential behavior, but at least there is nothing
2559 /// unbounded.
2560 std::vector<Function*> CallStack;
2561
Chris Lattner1945d582010-12-07 04:33:29 +00002562 /// SimpleConstants - These are constants we have checked and know to be
2563 /// simple enough to live in a static initializer of a global.
2564 SmallPtrSet<Constant*, 8> SimpleConstants;
2565
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002566 // Call the function.
Chris Lattnercd271422005-09-27 04:45:34 +00002567 Constant *RetValDummy;
Duncan Sandsfa6a1cf2009-08-17 14:33:27 +00002568 bool EvalSuccess = EvaluateFunction(F, RetValDummy,
2569 SmallVector<Constant*, 0>(), CallStack,
Chris Lattner1945d582010-12-07 04:33:29 +00002570 MutatedMemory, AllocaTmps,
2571 SimpleConstants, TD);
2572
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002573 if (EvalSuccess) {
Chris Lattnera22fdb02005-09-26 17:07:09 +00002574 // We succeeded at evaluation: commit the result.
David Greene3215b0e2010-01-05 01:28:05 +00002575 DEBUG(dbgs() << "FULLY EVALUATED GLOBAL CTOR FUNCTION '"
Daniel Dunbarce63ffb2009-07-25 00:23:56 +00002576 << F->getName() << "' to " << MutatedMemory.size()
2577 << " stores.\n");
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002578 for (DenseMap<Constant*, Constant*>::iterator I = MutatedMemory.begin(),
Chris Lattnera22fdb02005-09-26 17:07:09 +00002579 E = MutatedMemory.end(); I != E; ++I)
Chris Lattner7b550cc2009-11-06 04:27:31 +00002580 CommitValueTo(I->second, I->first);
Chris Lattnera22fdb02005-09-26 17:07:09 +00002581 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002582
Chris Lattnera22fdb02005-09-26 17:07:09 +00002583 // At this point, we are done interpreting. If we created any 'alloca'
2584 // temporaries, release them now.
2585 while (!AllocaTmps.empty()) {
2586 GlobalVariable *Tmp = AllocaTmps.back();
2587 AllocaTmps.pop_back();
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002588
Chris Lattnera22fdb02005-09-26 17:07:09 +00002589 // If there are still users of the alloca, the program is doing something
2590 // silly, e.g. storing the address of the alloca somewhere and using it
2591 // later. Since this is undefined, we'll just make it be null.
2592 if (!Tmp->use_empty())
Owen Andersona7235ea2009-07-31 20:28:14 +00002593 Tmp->replaceAllUsesWith(Constant::getNullValue(Tmp->getType()));
Chris Lattnera22fdb02005-09-26 17:07:09 +00002594 delete Tmp;
2595 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002596
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002597 return EvalSuccess;
Chris Lattner79c11012005-09-26 04:44:35 +00002598}
2599
Chris Lattnerdb973e62005-09-26 02:31:18 +00002600
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002601
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002602/// OptimizeGlobalCtorsList - Simplify and evaluation global ctors if possible.
2603/// Return true if anything changed.
2604bool GlobalOpt::OptimizeGlobalCtorsList(GlobalVariable *&GCL) {
2605 std::vector<Function*> Ctors = ParseGlobalCtors(GCL);
2606 bool MadeChange = false;
2607 if (Ctors.empty()) return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002608
Chris Lattner1945d582010-12-07 04:33:29 +00002609 const TargetData *TD = getAnalysisIfAvailable<TargetData>();
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002610 // Loop over global ctors, optimizing them when we can.
2611 for (unsigned i = 0; i != Ctors.size(); ++i) {
2612 Function *F = Ctors[i];
2613 // Found a null terminator in the middle of the list, prune off the rest of
2614 // the list.
Chris Lattner7d8e58f2005-09-26 02:19:27 +00002615 if (F == 0) {
2616 if (i != Ctors.size()-1) {
2617 Ctors.resize(i+1);
2618 MadeChange = true;
2619 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002620 break;
2621 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002622
Chris Lattner79c11012005-09-26 04:44:35 +00002623 // We cannot simplify external ctor functions.
2624 if (F->empty()) continue;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002625
Chris Lattner79c11012005-09-26 04:44:35 +00002626 // If we can evaluate the ctor at compile time, do.
Chris Lattner1945d582010-12-07 04:33:29 +00002627 if (EvaluateStaticConstructor(F, TD)) {
Chris Lattner79c11012005-09-26 04:44:35 +00002628 Ctors.erase(Ctors.begin()+i);
2629 MadeChange = true;
2630 --i;
2631 ++NumCtorsEvaluated;
2632 continue;
2633 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002634 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002635
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002636 if (!MadeChange) return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002637
Chris Lattner7b550cc2009-11-06 04:27:31 +00002638 GCL = InstallGlobalCtors(GCL, Ctors);
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002639 return true;
2640}
2641
Duncan Sandsfc5940d2009-03-06 10:21:56 +00002642bool GlobalOpt::OptimizeGlobalAliases(Module &M) {
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002643 bool Changed = false;
2644
Duncan Sands177d84e2009-01-07 20:01:06 +00002645 for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end();
Duncan Sands4782b302009-02-15 09:56:08 +00002646 I != E;) {
2647 Module::alias_iterator J = I++;
Duncan Sandsfc5940d2009-03-06 10:21:56 +00002648 // Aliases without names cannot be referenced outside this module.
2649 if (!J->hasName() && !J->isDeclaration())
2650 J->setLinkage(GlobalValue::InternalLinkage);
Duncan Sands4782b302009-02-15 09:56:08 +00002651 // If the aliasee may change at link time, nothing can be done - bail out.
2652 if (J->mayBeOverridden())
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002653 continue;
2654
Duncan Sands4782b302009-02-15 09:56:08 +00002655 Constant *Aliasee = J->getAliasee();
2656 GlobalValue *Target = cast<GlobalValue>(Aliasee->stripPointerCasts());
Duncan Sands95c5d0f2009-02-18 17:55:38 +00002657 Target->removeDeadConstantUsers();
Duncan Sands4782b302009-02-15 09:56:08 +00002658 bool hasOneUse = Target->hasOneUse() && Aliasee->hasOneUse();
2659
2660 // Make all users of the alias use the aliasee instead.
2661 if (!J->use_empty()) {
2662 J->replaceAllUsesWith(Aliasee);
2663 ++NumAliasesResolved;
2664 Changed = true;
2665 }
2666
Duncan Sands7a154cf2009-12-08 10:10:20 +00002667 // If the alias is externally visible, we may still be able to simplify it.
2668 if (!J->hasLocalLinkage()) {
2669 // If the aliasee has internal linkage, give it the name and linkage
2670 // of the alias, and delete the alias. This turns:
2671 // define internal ... @f(...)
2672 // @a = alias ... @f
2673 // into:
2674 // define ... @a(...)
2675 if (!Target->hasLocalLinkage())
2676 continue;
Duncan Sands4782b302009-02-15 09:56:08 +00002677
Duncan Sands7a154cf2009-12-08 10:10:20 +00002678 // Do not perform the transform if multiple aliases potentially target the
Gabor Greif27236912010-04-07 18:59:26 +00002679 // aliasee. This check also ensures that it is safe to replace the section
Duncan Sands7a154cf2009-12-08 10:10:20 +00002680 // and other attributes of the aliasee with those of the alias.
2681 if (!hasOneUse)
2682 continue;
Duncan Sands4782b302009-02-15 09:56:08 +00002683
Duncan Sands7a154cf2009-12-08 10:10:20 +00002684 // Give the aliasee the name, linkage and other attributes of the alias.
2685 Target->takeName(J);
2686 Target->setLinkage(J->getLinkage());
2687 Target->GlobalValue::copyAttributesFrom(J);
2688 }
Duncan Sands4782b302009-02-15 09:56:08 +00002689
2690 // Delete the alias.
2691 M.getAliasList().erase(J);
2692 ++NumAliasesRemoved;
2693 Changed = true;
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002694 }
2695
2696 return Changed;
2697}
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002698
Chris Lattner7a90b682004-10-07 04:16:33 +00002699bool GlobalOpt::runOnModule(Module &M) {
Chris Lattner079236d2004-02-25 21:34:36 +00002700 bool Changed = false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002701
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002702 // Try to find the llvm.globalctors list.
2703 GlobalVariable *GlobalCtors = FindGlobalCtors(M);
Chris Lattner7a90b682004-10-07 04:16:33 +00002704
Chris Lattner7a90b682004-10-07 04:16:33 +00002705 bool LocalChange = true;
2706 while (LocalChange) {
2707 LocalChange = false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002708
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002709 // Delete functions that are trivially dead, ccc -> fastcc
2710 LocalChange |= OptimizeFunctions(M);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002711
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002712 // Optimize global_ctors list.
2713 if (GlobalCtors)
2714 LocalChange |= OptimizeGlobalCtorsList(GlobalCtors);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002715
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002716 // Optimize non-address-taken globals.
2717 LocalChange |= OptimizeGlobalVars(M);
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002718
2719 // Resolve aliases, when possible.
Duncan Sandsfc5940d2009-03-06 10:21:56 +00002720 LocalChange |= OptimizeGlobalAliases(M);
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002721 Changed |= LocalChange;
Chris Lattner7a90b682004-10-07 04:16:33 +00002722 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002723
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002724 // TODO: Move all global ctors functions to the end of the module for code
2725 // layout.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002726
Chris Lattner079236d2004-02-25 21:34:36 +00002727 return Changed;
2728}