blob: 60ce958de0d10f03ebb1e61423a3214d900b147a [file] [log] [blame]
Chris Lattner7a90b682004-10-07 04:16:33 +00001//===- GlobalOpt.cpp - Optimize Global Variables --------------------------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
Chris Lattner079236d2004-02-25 21:34:36 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
Chris Lattner079236d2004-02-25 21:34:36 +00008//===----------------------------------------------------------------------===//
9//
Chris Lattner7a90b682004-10-07 04:16:33 +000010// This pass transforms simple global variables that never have their address
11// taken. If obviously true, it marks read/write globals as constant, deletes
12// variables only stored to, etc.
Chris Lattner079236d2004-02-25 21:34:36 +000013//
14//===----------------------------------------------------------------------===//
15
Chris Lattner7a90b682004-10-07 04:16:33 +000016#define DEBUG_TYPE "globalopt"
Chris Lattner079236d2004-02-25 21:34:36 +000017#include "llvm/Transforms/IPO.h"
Chris Lattnerfb217ad2005-05-08 22:18:06 +000018#include "llvm/CallingConv.h"
Chris Lattner079236d2004-02-25 21:34:36 +000019#include "llvm/Constants.h"
Chris Lattner7a90b682004-10-07 04:16:33 +000020#include "llvm/DerivedTypes.h"
Chris Lattner7d90a272004-02-27 18:09:25 +000021#include "llvm/Instructions.h"
Chris Lattner35c81b02005-02-27 18:58:52 +000022#include "llvm/IntrinsicInst.h"
Chris Lattner079236d2004-02-25 21:34:36 +000023#include "llvm/Module.h"
Jay Foad562b84b2011-04-11 09:35:34 +000024#include "llvm/Operator.h"
Chris Lattner079236d2004-02-25 21:34:36 +000025#include "llvm/Pass.h"
Chris Lattner79066fa2007-01-30 23:46:24 +000026#include "llvm/Analysis/ConstantFolding.h"
Victor Hernandezf006b182009-10-27 20:05:49 +000027#include "llvm/Analysis/MemoryBuiltins.h"
Chris Lattner30ba5692004-10-11 05:54:41 +000028#include "llvm/Target/TargetData.h"
Chad Rosier00737bd2011-12-01 21:29:16 +000029#include "llvm/Target/TargetLibraryInfo.h"
Duncan Sands548448a2008-02-18 17:32:13 +000030#include "llvm/Support/CallSite.h"
Chris Lattner79066fa2007-01-30 23:46:24 +000031#include "llvm/Support/Debug.h"
Torok Edwinc25e7582009-07-11 20:10:48 +000032#include "llvm/Support/ErrorHandling.h"
Chris Lattner941db492008-01-14 02:09:12 +000033#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner998182b2008-04-26 07:40:11 +000034#include "llvm/Support/MathExtras.h"
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000035#include "llvm/Support/raw_ostream.h"
Chris Lattner5a6bb6a2008-12-16 07:34:30 +000036#include "llvm/ADT/DenseMap.h"
Chris Lattner81686182007-09-13 16:30:19 +000037#include "llvm/ADT/SmallPtrSet.h"
Chris Lattner55eb1c42007-01-31 04:40:53 +000038#include "llvm/ADT/SmallVector.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000039#include "llvm/ADT/Statistic.h"
Chris Lattnerbce4afe2008-12-17 05:28:49 +000040#include "llvm/ADT/STLExtras.h"
Chris Lattnere47ba742004-10-06 20:57:02 +000041#include <algorithm>
Chris Lattner079236d2004-02-25 21:34:36 +000042using namespace llvm;
43
Chris Lattner86453c52006-12-19 22:09:18 +000044STATISTIC(NumMarked , "Number of globals marked constant");
Rafael Espindolac4440e32011-01-19 16:32:21 +000045STATISTIC(NumUnnamed , "Number of globals marked unnamed_addr");
Chris Lattner86453c52006-12-19 22:09:18 +000046STATISTIC(NumSRA , "Number of aggregate globals broken into scalars");
47STATISTIC(NumHeapSRA , "Number of heap objects SRA'd");
48STATISTIC(NumSubstitute,"Number of globals with initializers stored into them");
49STATISTIC(NumDeleted , "Number of globals deleted");
50STATISTIC(NumFnDeleted , "Number of functions deleted");
51STATISTIC(NumGlobUses , "Number of global uses devirtualized");
52STATISTIC(NumLocalized , "Number of globals localized");
53STATISTIC(NumShrunkToBool , "Number of global vars shrunk to booleans");
54STATISTIC(NumFastCallFns , "Number of functions converted to fastcc");
55STATISTIC(NumCtorsEvaluated, "Number of static ctors evaluated");
Duncan Sands3d5378f2008-02-16 20:56:04 +000056STATISTIC(NumNestRemoved , "Number of nest attributes removed");
Duncan Sands4782b302009-02-15 09:56:08 +000057STATISTIC(NumAliasesResolved, "Number of global aliases resolved");
58STATISTIC(NumAliasesRemoved, "Number of global aliases eliminated");
Anders Carlssona201c4c2011-03-20 17:59:11 +000059STATISTIC(NumCXXDtorsRemoved, "Number of global C++ destructors removed");
Chris Lattner079236d2004-02-25 21:34:36 +000060
Chris Lattner86453c52006-12-19 22:09:18 +000061namespace {
Rafael Espindolac4440e32011-01-19 16:32:21 +000062 struct GlobalStatus;
Nick Lewycky6726b6d2009-10-25 06:33:48 +000063 struct GlobalOpt : public ModulePass {
Chris Lattner30ba5692004-10-11 05:54:41 +000064 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chad Rosier00737bd2011-12-01 21:29:16 +000065 AU.addRequired<TargetLibraryInfo>();
Chris Lattner30ba5692004-10-11 05:54:41 +000066 }
Nick Lewyckyecd94c82007-05-06 13:37:16 +000067 static char ID; // Pass identification, replacement for typeid
Owen Anderson081c34b2010-10-19 17:21:58 +000068 GlobalOpt() : ModulePass(ID) {
69 initializeGlobalOptPass(*PassRegistry::getPassRegistry());
70 }
Misha Brukmanfd939082005-04-21 23:48:37 +000071
Chris Lattnerb12914b2004-09-20 04:48:05 +000072 bool runOnModule(Module &M);
Chris Lattner30ba5692004-10-11 05:54:41 +000073
74 private:
Chris Lattnerb1ab4582005-09-26 01:43:45 +000075 GlobalVariable *FindGlobalCtors(Module &M);
76 bool OptimizeFunctions(Module &M);
77 bool OptimizeGlobalVars(Module &M);
Duncan Sandsfc5940d2009-03-06 10:21:56 +000078 bool OptimizeGlobalAliases(Module &M);
Chris Lattnerb1ab4582005-09-26 01:43:45 +000079 bool OptimizeGlobalCtorsList(GlobalVariable *&GCL);
Rafael Espindolac4440e32011-01-19 16:32:21 +000080 bool ProcessGlobal(GlobalVariable *GV,Module::global_iterator &GVI);
81 bool ProcessInternalGlobal(GlobalVariable *GV,Module::global_iterator &GVI,
82 const SmallPtrSet<const PHINode*, 16> &PHIUsers,
83 const GlobalStatus &GS);
Anders Carlssona201c4c2011-03-20 17:59:11 +000084 bool OptimizeEmptyGlobalCXXDtors(Function *CXAAtExitFn);
Nick Lewycky6a577f82012-02-12 01:13:18 +000085
86 TargetData *TD;
87 TargetLibraryInfo *TLI;
Chris Lattner079236d2004-02-25 21:34:36 +000088 };
Chris Lattner079236d2004-02-25 21:34:36 +000089}
90
Dan Gohman844731a2008-05-13 00:00:25 +000091char GlobalOpt::ID = 0;
Chad Rosier00737bd2011-12-01 21:29:16 +000092INITIALIZE_PASS_BEGIN(GlobalOpt, "globalopt",
93 "Global Variable Optimizer", false, false)
94INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
95INITIALIZE_PASS_END(GlobalOpt, "globalopt",
Owen Andersonce665bd2010-10-07 22:25:06 +000096 "Global Variable Optimizer", false, false)
Dan Gohman844731a2008-05-13 00:00:25 +000097
Chris Lattner7a90b682004-10-07 04:16:33 +000098ModulePass *llvm::createGlobalOptimizerPass() { return new GlobalOpt(); }
Chris Lattner079236d2004-02-25 21:34:36 +000099
Dan Gohman844731a2008-05-13 00:00:25 +0000100namespace {
101
Chris Lattner7a90b682004-10-07 04:16:33 +0000102/// GlobalStatus - As we analyze each global, keep track of some information
103/// about it. If we find out that the address of the global is taken, none of
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000104/// this info will be accurate.
Nick Lewycky6726b6d2009-10-25 06:33:48 +0000105struct GlobalStatus {
Rafael Espindolac4440e32011-01-19 16:32:21 +0000106 /// isCompared - True if the global's address is used in a comparison.
107 bool isCompared;
108
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000109 /// isLoaded - True if the global is ever loaded. If the global isn't ever
110 /// loaded it can be deleted.
Chris Lattner7a90b682004-10-07 04:16:33 +0000111 bool isLoaded;
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000112
113 /// StoredType - Keep track of what stores to the global look like.
114 ///
Chris Lattner7a90b682004-10-07 04:16:33 +0000115 enum StoredType {
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000116 /// NotStored - There is no store to this global. It can thus be marked
117 /// constant.
118 NotStored,
119
120 /// isInitializerStored - This global is stored to, but the only thing
121 /// stored is the constant it was initialized with. This is only tracked
122 /// for scalar globals.
123 isInitializerStored,
124
125 /// isStoredOnce - This global is stored to, but only its initializer and
126 /// one other value is ever stored to it. If this global isStoredOnce, we
127 /// track the value stored to it in StoredOnceValue below. This is only
128 /// tracked for scalar globals.
129 isStoredOnce,
130
131 /// isStored - This global is stored to by multiple values or something else
132 /// that we cannot track.
133 isStored
Chris Lattner7a90b682004-10-07 04:16:33 +0000134 } StoredType;
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000135
136 /// StoredOnceValue - If only one value (besides the initializer constant) is
137 /// ever stored to this global, keep track of what value it is.
138 Value *StoredOnceValue;
139
Chris Lattner25de4e52006-11-01 18:03:33 +0000140 /// AccessingFunction/HasMultipleAccessingFunctions - These start out
141 /// null/false. When the first accessing function is noticed, it is recorded.
142 /// When a second different accessing function is noticed,
143 /// HasMultipleAccessingFunctions is set to true.
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000144 const Function *AccessingFunction;
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +0000145 bool HasMultipleAccessingFunctions;
146
Chris Lattner25de4e52006-11-01 18:03:33 +0000147 /// HasNonInstructionUser - Set to true if this global has a user that is not
148 /// an instruction (e.g. a constant expr or GV initializer).
Chris Lattner553ca522005-06-15 21:11:48 +0000149 bool HasNonInstructionUser;
150
Chris Lattner25de4e52006-11-01 18:03:33 +0000151 /// HasPHIUser - Set to true if this global has a user that is a PHI node.
152 bool HasPHIUser;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000153
Nick Lewyckyfad4d402012-02-05 19:56:38 +0000154 /// AtomicOrdering - Set to the strongest atomic ordering requirement.
155 AtomicOrdering Ordering;
156
Rafael Espindolac4440e32011-01-19 16:32:21 +0000157 GlobalStatus() : isCompared(false), isLoaded(false), StoredType(NotStored),
158 StoredOnceValue(0), AccessingFunction(0),
Nick Lewyckyfad4d402012-02-05 19:56:38 +0000159 HasMultipleAccessingFunctions(false),
160 HasNonInstructionUser(false), HasPHIUser(false),
161 Ordering(NotAtomic) {}
Chris Lattner7a90b682004-10-07 04:16:33 +0000162};
Chris Lattnere47ba742004-10-06 20:57:02 +0000163
Dan Gohman844731a2008-05-13 00:00:25 +0000164}
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000165
Nick Lewyckyfad4d402012-02-05 19:56:38 +0000166/// StrongerOrdering - Return the stronger of the two ordering. If the two
167/// orderings are acquire and release, then return AcquireRelease.
168///
169static AtomicOrdering StrongerOrdering(AtomicOrdering X, AtomicOrdering Y) {
170 if (X == Acquire && Y == Release) return AcquireRelease;
171 if (Y == Acquire && X == Release) return AcquireRelease;
172 return (AtomicOrdering)std::max(X, Y);
173}
174
Nick Lewyckybc384a12012-02-05 19:48:37 +0000175/// SafeToDestroyConstant - It is safe to destroy a constant iff it is only used
176/// by constants itself. Note that constants cannot be cyclic, so this test is
177/// pretty easy to implement recursively.
178///
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000179static bool SafeToDestroyConstant(const Constant *C) {
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000180 if (isa<GlobalValue>(C)) return false;
181
Gabor Greif27236912010-04-07 18:59:26 +0000182 for (Value::const_use_iterator UI = C->use_begin(), E = C->use_end(); UI != E;
183 ++UI)
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000184 if (const Constant *CU = dyn_cast<Constant>(*UI)) {
Jay Foade3acf152009-06-09 21:37:11 +0000185 if (!SafeToDestroyConstant(CU)) return false;
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000186 } else
187 return false;
188 return true;
189}
190
191
Chris Lattner7a90b682004-10-07 04:16:33 +0000192/// AnalyzeGlobal - Look at all uses of the global and fill in the GlobalStatus
193/// structure. If the global has its address taken, return true to indicate we
194/// can't do anything with it.
Chris Lattner079236d2004-02-25 21:34:36 +0000195///
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000196static bool AnalyzeGlobal(const Value *V, GlobalStatus &GS,
197 SmallPtrSet<const PHINode*, 16> &PHIUsers) {
Gabor Greif27236912010-04-07 18:59:26 +0000198 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;
Gabor Greife6642672010-07-09 16:51:20 +0000199 ++UI) {
200 const User *U = *UI;
201 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
Chris Lattner553ca522005-06-15 21:11:48 +0000202 GS.HasNonInstructionUser = true;
Chris Lattnerd91ed102011-01-01 22:31:46 +0000203
204 // If the result of the constantexpr isn't pointer type, then we won't
205 // know to expect it in various places. Just reject early.
206 if (!isa<PointerType>(CE->getType())) return true;
207
Chris Lattner7a90b682004-10-07 04:16:33 +0000208 if (AnalyzeGlobal(CE, GS, PHIUsers)) return true;
Gabor Greife6642672010-07-09 16:51:20 +0000209 } else if (const Instruction *I = dyn_cast<Instruction>(U)) {
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +0000210 if (!GS.HasMultipleAccessingFunctions) {
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000211 const Function *F = I->getParent()->getParent();
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +0000212 if (GS.AccessingFunction == 0)
213 GS.AccessingFunction = F;
214 else if (GS.AccessingFunction != F)
215 GS.HasMultipleAccessingFunctions = true;
216 }
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000217 if (const LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattner7a90b682004-10-07 04:16:33 +0000218 GS.isLoaded = true;
Nick Lewyckyfad4d402012-02-05 19:56:38 +0000219 // Don't hack on volatile loads.
220 if (LI->isVolatile()) return true;
221 GS.Ordering = StrongerOrdering(GS.Ordering, LI->getOrdering());
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000222 } else if (const StoreInst *SI = dyn_cast<StoreInst>(I)) {
Chris Lattner36025492004-10-07 06:01:25 +0000223 // Don't allow a store OF the address, only stores TO the address.
224 if (SI->getOperand(0) == V) return true;
225
Nick Lewyckyfad4d402012-02-05 19:56:38 +0000226 // Don't hack on volatile stores.
227 if (SI->isVolatile()) return true;
228 GS.Ordering = StrongerOrdering(GS.Ordering, SI->getOrdering());
Chris Lattnerc69d3c92008-01-29 19:01:37 +0000229
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000230 // If this is a direct store to the global (i.e., the global is a scalar
231 // value, not an aggregate), keep more specific information about
232 // stores.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000233 if (GS.StoredType != GlobalStatus::isStored) {
Gabor Greif27236912010-04-07 18:59:26 +0000234 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(
235 SI->getOperand(1))) {
Chris Lattnerbd38edf2004-11-14 20:50:30 +0000236 Value *StoredVal = SI->getOperand(0);
237 if (StoredVal == GV->getInitializer()) {
238 if (GS.StoredType < GlobalStatus::isInitializerStored)
239 GS.StoredType = GlobalStatus::isInitializerStored;
240 } else if (isa<LoadInst>(StoredVal) &&
241 cast<LoadInst>(StoredVal)->getOperand(0) == GV) {
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000242 if (GS.StoredType < GlobalStatus::isInitializerStored)
243 GS.StoredType = GlobalStatus::isInitializerStored;
244 } else if (GS.StoredType < GlobalStatus::isStoredOnce) {
245 GS.StoredType = GlobalStatus::isStoredOnce;
Chris Lattnerbd38edf2004-11-14 20:50:30 +0000246 GS.StoredOnceValue = StoredVal;
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000247 } else if (GS.StoredType == GlobalStatus::isStoredOnce &&
Chris Lattnerbd38edf2004-11-14 20:50:30 +0000248 GS.StoredOnceValue == StoredVal) {
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000249 // noop.
250 } else {
251 GS.StoredType = GlobalStatus::isStored;
252 }
253 } else {
Chris Lattner7a90b682004-10-07 04:16:33 +0000254 GS.StoredType = GlobalStatus::isStored;
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000255 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000256 }
Duncan Sandsb2fe7f12012-07-02 18:55:39 +0000257 } else if (isa<BitCastInst>(I)) {
258 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Chris Lattner35c81b02005-02-27 18:58:52 +0000259 } else if (isa<GetElementPtrInst>(I)) {
Chris Lattner7a90b682004-10-07 04:16:33 +0000260 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Chris Lattner35c81b02005-02-27 18:58:52 +0000261 } else if (isa<SelectInst>(I)) {
Chris Lattner7a90b682004-10-07 04:16:33 +0000262 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000263 } else if (const PHINode *PN = dyn_cast<PHINode>(I)) {
Chris Lattner7a90b682004-10-07 04:16:33 +0000264 // PHI nodes we can check just like select or GEP instructions, but we
265 // have to be careful about infinite recursion.
Chris Lattner5a6bb6a2008-12-16 07:34:30 +0000266 if (PHIUsers.insert(PN)) // Not already visited.
Chris Lattner7a90b682004-10-07 04:16:33 +0000267 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Chris Lattner25de4e52006-11-01 18:03:33 +0000268 GS.HasPHIUser = true;
Reid Spencere4d87aa2006-12-23 06:05:41 +0000269 } else if (isa<CmpInst>(I)) {
Rafael Espindolac4440e32011-01-19 16:32:21 +0000270 GS.isCompared = true;
Nick Lewycky1f237b02011-05-29 18:41:56 +0000271 } else if (const MemTransferInst *MTI = dyn_cast<MemTransferInst>(I)) {
272 if (MTI->isVolatile()) return true;
Gabor Greif9e4f2432010-06-24 14:42:01 +0000273 if (MTI->getArgOperand(0) == V)
Eric Christopher551754c2010-04-16 23:37:20 +0000274 GS.StoredType = GlobalStatus::isStored;
Gabor Greif9e4f2432010-06-24 14:42:01 +0000275 if (MTI->getArgOperand(1) == V)
Chris Lattner35c81b02005-02-27 18:58:52 +0000276 GS.isLoaded = true;
Nick Lewycky1f237b02011-05-29 18:41:56 +0000277 } else if (const MemSetInst *MSI = dyn_cast<MemSetInst>(I)) {
278 assert(MSI->getArgOperand(0) == V && "Memset only takes one pointer!");
279 if (MSI->isVolatile()) return true;
Chris Lattner35c81b02005-02-27 18:58:52 +0000280 GS.StoredType = GlobalStatus::isStored;
Chris Lattner7a90b682004-10-07 04:16:33 +0000281 } else {
282 return true; // Any other non-load instruction might take address!
Chris Lattner9ce30002004-07-20 03:58:07 +0000283 }
Gabor Greife6642672010-07-09 16:51:20 +0000284 } else if (const Constant *C = dyn_cast<Constant>(U)) {
Chris Lattner553ca522005-06-15 21:11:48 +0000285 GS.HasNonInstructionUser = true;
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000286 // We might have a dead and dangling constant hanging off of here.
Jay Foade3acf152009-06-09 21:37:11 +0000287 if (!SafeToDestroyConstant(C))
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000288 return true;
Chris Lattner079236d2004-02-25 21:34:36 +0000289 } else {
Chris Lattner553ca522005-06-15 21:11:48 +0000290 GS.HasNonInstructionUser = true;
291 // Otherwise must be some other user.
Chris Lattner079236d2004-02-25 21:34:36 +0000292 return true;
293 }
Gabor Greife6642672010-07-09 16:51:20 +0000294 }
Chris Lattner079236d2004-02-25 21:34:36 +0000295
296 return false;
297}
298
Nick Lewycky8899d5c2012-07-24 07:21:08 +0000299/// isLeakCheckerRoot - Is this global variable possibly used by a leak checker
300/// as a root? If so, we might not really want to eliminate the stores to it.
301static bool isLeakCheckerRoot(GlobalVariable *GV) {
302 // A global variable is a root if it is a pointer, or could plausibly contain
303 // a pointer. There are two challenges; one is that we could have a struct
304 // the has an inner member which is a pointer. We recurse through the type to
305 // detect these (up to a point). The other is that we may actually be a union
306 // of a pointer and another type, and so our LLVM type is an integer which
307 // gets converted into a pointer, or our type is an [i8 x #] with a pointer
308 // potentially contained here.
309
310 if (GV->hasPrivateLinkage())
311 return false;
312
313 SmallVector<Type *, 4> Types;
314 Types.push_back(cast<PointerType>(GV->getType())->getElementType());
315
316 unsigned Limit = 20;
317 do {
318 Type *Ty = Types.pop_back_val();
319 switch (Ty->getTypeID()) {
320 default: break;
321 case Type::PointerTyID: return true;
322 case Type::ArrayTyID:
323 case Type::VectorTyID: {
324 SequentialType *STy = cast<SequentialType>(Ty);
325 Types.push_back(STy->getElementType());
326 break;
327 }
328 case Type::StructTyID: {
329 StructType *STy = cast<StructType>(Ty);
330 if (STy->isOpaque()) return true;
331 for (StructType::element_iterator I = STy->element_begin(),
332 E = STy->element_end(); I != E; ++I) {
333 Type *InnerTy = *I;
334 if (isa<PointerType>(InnerTy)) return true;
335 if (isa<CompositeType>(InnerTy))
336 Types.push_back(InnerTy);
337 }
338 break;
339 }
340 }
341 if (--Limit == 0) return true;
342 } while (!Types.empty());
343 return false;
344}
345
346/// Given a value that is stored to a global but never read, determine whether
347/// it's safe to remove the store and the chain of computation that feeds the
348/// store.
349static bool IsSafeComputationToRemove(Value *V) {
350 do {
351 if (isa<Constant>(V))
352 return true;
353 if (!V->hasOneUse())
354 return false;
355 if (isa<LoadInst>(V) || isa<Argument>(V) || isa<GlobalValue>(V))
356 return false;
357 if (isAllocationFn(V))
358 return true;
359
360 Instruction *I = cast<Instruction>(V);
361 if (I->mayHaveSideEffects())
362 return false;
363 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
364 if (!GEP->hasAllConstantIndices())
365 return false;
366 } else if (I->getNumOperands() != 1) {
367 return false;
368 }
369
370 V = I->getOperand(0);
371 } while (1);
372}
373
374/// CleanupPointerRootUsers - This GV is a pointer root. Loop over all users
375/// of the global and clean up any that obviously don't assign the global a
376/// value that isn't dynamically allocated.
377///
378static bool CleanupPointerRootUsers(GlobalVariable *GV) {
379 // A brief explanation of leak checkers. The goal is to find bugs where
380 // pointers are forgotten, causing an accumulating growth in memory
381 // usage over time. The common strategy for leak checkers is to whitelist the
382 // memory pointed to by globals at exit. This is popular because it also
383 // solves another problem where the main thread of a C++ program may shut down
384 // before other threads that are still expecting to use those globals. To
385 // handle that case, we expect the program may create a singleton and never
386 // destroy it.
387
388 bool Changed = false;
389
390 // If Dead[n].first is the only use of a malloc result, we can delete its
391 // chain of computation and the store to the global in Dead[n].second.
392 SmallVector<std::pair<Instruction *, Instruction *>, 32> Dead;
393
394 // Constants can't be pointers to dynamically allocated memory.
395 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end();
396 UI != E;) {
397 User *U = *UI++;
398 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
399 Value *V = SI->getValueOperand();
400 if (isa<Constant>(V)) {
401 Changed = true;
402 SI->eraseFromParent();
403 } else if (Instruction *I = dyn_cast<Instruction>(V)) {
404 if (I->hasOneUse())
405 Dead.push_back(std::make_pair(I, SI));
406 }
407 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(U)) {
408 if (isa<Constant>(MSI->getValue())) {
409 Changed = true;
410 MSI->eraseFromParent();
411 } else if (Instruction *I = dyn_cast<Instruction>(MSI->getValue())) {
412 if (I->hasOneUse())
413 Dead.push_back(std::make_pair(I, MSI));
414 }
415 } else if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(U)) {
416 GlobalVariable *MemSrc = dyn_cast<GlobalVariable>(MTI->getSource());
417 if (MemSrc && MemSrc->isConstant()) {
418 Changed = true;
419 MTI->eraseFromParent();
420 } else if (Instruction *I = dyn_cast<Instruction>(MemSrc)) {
421 if (I->hasOneUse())
422 Dead.push_back(std::make_pair(I, MTI));
423 }
424 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
425 if (CE->use_empty()) {
426 CE->destroyConstant();
427 Changed = true;
428 }
429 } else if (Constant *C = dyn_cast<Constant>(U)) {
430 if (SafeToDestroyConstant(C)) {
431 C->destroyConstant();
432 // This could have invalidated UI, start over from scratch.
433 Dead.clear();
434 CleanupPointerRootUsers(GV);
435 return true;
436 }
437 }
438 }
439
440 for (int i = 0, e = Dead.size(); i != e; ++i) {
441 if (IsSafeComputationToRemove(Dead[i].first)) {
442 Dead[i].second->eraseFromParent();
443 Instruction *I = Dead[i].first;
444 do {
445 Instruction *J = dyn_cast<Instruction>(I->getOperand(0));
446 if (!J)
447 break;
448 I->eraseFromParent();
449 I = J;
450 } while (!isAllocationFn(I));
451 I->eraseFromParent();
452 }
453 }
454
455 return Changed;
456}
457
Chris Lattnere47ba742004-10-06 20:57:02 +0000458/// CleanupConstantGlobalUsers - We just marked GV constant. Loop over all
459/// users of the global, cleaning up the obvious ones. This is largely just a
Chris Lattner031955d2004-10-10 16:43:46 +0000460/// quick scan over the use list to clean up the easy and obvious cruft. This
461/// returns true if it made a change.
Nick Lewycky6a577f82012-02-12 01:13:18 +0000462static bool CleanupConstantGlobalUsers(Value *V, Constant *Init,
463 TargetData *TD, TargetLibraryInfo *TLI) {
Chris Lattner031955d2004-10-10 16:43:46 +0000464 bool Changed = false;
Chris Lattner7a90b682004-10-07 04:16:33 +0000465 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;) {
466 User *U = *UI++;
Misha Brukmanfd939082005-04-21 23:48:37 +0000467
Chris Lattner7a90b682004-10-07 04:16:33 +0000468 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
Chris Lattner35c81b02005-02-27 18:58:52 +0000469 if (Init) {
470 // Replace the load with the initializer.
471 LI->replaceAllUsesWith(Init);
472 LI->eraseFromParent();
473 Changed = true;
474 }
Chris Lattner7a90b682004-10-07 04:16:33 +0000475 } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
Chris Lattnere47ba742004-10-06 20:57:02 +0000476 // Store must be unreachable or storing Init into the global.
Chris Lattner7a7ed022004-10-16 18:09:00 +0000477 SI->eraseFromParent();
Chris Lattner031955d2004-10-10 16:43:46 +0000478 Changed = true;
Chris Lattner7a90b682004-10-07 04:16:33 +0000479 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
480 if (CE->getOpcode() == Instruction::GetElementPtr) {
Chris Lattneraae4a1c2005-09-26 07:34:35 +0000481 Constant *SubInit = 0;
482 if (Init)
Dan Gohmanc6f69e92009-10-05 16:36:26 +0000483 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
Nick Lewycky6a577f82012-02-12 01:13:18 +0000484 Changed |= CleanupConstantGlobalUsers(CE, SubInit, TD, TLI);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000485 } else if (CE->getOpcode() == Instruction::BitCast &&
Duncan Sands1df98592010-02-16 11:11:14 +0000486 CE->getType()->isPointerTy()) {
Chris Lattner35c81b02005-02-27 18:58:52 +0000487 // Pointer cast, delete any stores and memsets to the global.
Nick Lewycky6a577f82012-02-12 01:13:18 +0000488 Changed |= CleanupConstantGlobalUsers(CE, 0, TD, TLI);
Chris Lattner35c81b02005-02-27 18:58:52 +0000489 }
490
491 if (CE->use_empty()) {
492 CE->destroyConstant();
493 Changed = true;
Chris Lattner7a90b682004-10-07 04:16:33 +0000494 }
495 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
Chris Lattner7b52fe72007-11-09 17:33:02 +0000496 // Do not transform "gepinst (gep constexpr (GV))" here, because forming
497 // "gepconstexpr (gep constexpr (GV))" will cause the two gep's to fold
498 // and will invalidate our notion of what Init is.
Chris Lattner19450242007-11-13 21:46:23 +0000499 Constant *SubInit = 0;
Chris Lattner7b52fe72007-11-09 17:33:02 +0000500 if (!isa<ConstantExpr>(GEP->getOperand(0))) {
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000501 ConstantExpr *CE =
Nick Lewycky6a577f82012-02-12 01:13:18 +0000502 dyn_cast_or_null<ConstantExpr>(ConstantFoldInstruction(GEP, TD, TLI));
Chris Lattner7b52fe72007-11-09 17:33:02 +0000503 if (Init && CE && CE->getOpcode() == Instruction::GetElementPtr)
Dan Gohmanc6f69e92009-10-05 16:36:26 +0000504 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
Benjamin Kramerc1ea16e2012-03-28 14:50:09 +0000505
506 // If the initializer is an all-null value and we have an inbounds GEP,
507 // we already know what the result of any load from that GEP is.
508 // TODO: Handle splats.
509 if (Init && isa<ConstantAggregateZero>(Init) && GEP->isInBounds())
510 SubInit = Constant::getNullValue(GEP->getType()->getElementType());
Chris Lattner7b52fe72007-11-09 17:33:02 +0000511 }
Nick Lewycky6a577f82012-02-12 01:13:18 +0000512 Changed |= CleanupConstantGlobalUsers(GEP, SubInit, TD, TLI);
Chris Lattnerc4d81b02004-10-10 16:47:33 +0000513
Chris Lattner031955d2004-10-10 16:43:46 +0000514 if (GEP->use_empty()) {
Chris Lattner7a7ed022004-10-16 18:09:00 +0000515 GEP->eraseFromParent();
Chris Lattner031955d2004-10-10 16:43:46 +0000516 Changed = true;
517 }
Chris Lattner35c81b02005-02-27 18:58:52 +0000518 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U)) { // memset/cpy/mv
519 if (MI->getRawDest() == V) {
520 MI->eraseFromParent();
521 Changed = true;
522 }
523
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000524 } else if (Constant *C = dyn_cast<Constant>(U)) {
525 // If we have a chain of dead constantexprs or other things dangling from
526 // us, and if they are all dead, nuke them without remorse.
Jay Foade3acf152009-06-09 21:37:11 +0000527 if (SafeToDestroyConstant(C)) {
Devang Patel743cdf82009-03-06 01:37:41 +0000528 C->destroyConstant();
Chris Lattner35c81b02005-02-27 18:58:52 +0000529 // This could have invalidated UI, start over from scratch.
Nick Lewycky6a577f82012-02-12 01:13:18 +0000530 CleanupConstantGlobalUsers(V, Init, TD, TLI);
Chris Lattner031955d2004-10-10 16:43:46 +0000531 return true;
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000532 }
Chris Lattnere47ba742004-10-06 20:57:02 +0000533 }
534 }
Chris Lattner031955d2004-10-10 16:43:46 +0000535 return Changed;
Chris Lattnere47ba742004-10-06 20:57:02 +0000536}
537
Chris Lattner941db492008-01-14 02:09:12 +0000538/// isSafeSROAElementUse - Return true if the specified instruction is a safe
539/// user of a derived expression from a global that we want to SROA.
540static bool isSafeSROAElementUse(Value *V) {
541 // We might have a dead and dangling constant hanging off of here.
542 if (Constant *C = dyn_cast<Constant>(V))
Jay Foade3acf152009-06-09 21:37:11 +0000543 return SafeToDestroyConstant(C);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000544
Chris Lattner941db492008-01-14 02:09:12 +0000545 Instruction *I = dyn_cast<Instruction>(V);
546 if (!I) return false;
547
548 // Loads are ok.
549 if (isa<LoadInst>(I)) return true;
550
551 // Stores *to* the pointer are ok.
552 if (StoreInst *SI = dyn_cast<StoreInst>(I))
553 return SI->getOperand(0) != V;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000554
Chris Lattner941db492008-01-14 02:09:12 +0000555 // Otherwise, it must be a GEP.
556 GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I);
557 if (GEPI == 0) return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000558
Chris Lattner941db492008-01-14 02:09:12 +0000559 if (GEPI->getNumOperands() < 3 || !isa<Constant>(GEPI->getOperand(1)) ||
560 !cast<Constant>(GEPI->getOperand(1))->isNullValue())
561 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000562
Chris Lattner941db492008-01-14 02:09:12 +0000563 for (Value::use_iterator I = GEPI->use_begin(), E = GEPI->use_end();
564 I != E; ++I)
565 if (!isSafeSROAElementUse(*I))
566 return false;
Chris Lattner727c2102008-01-14 01:31:05 +0000567 return true;
568}
569
Chris Lattner941db492008-01-14 02:09:12 +0000570
571/// IsUserOfGlobalSafeForSRA - U is a direct user of the specified global value.
572/// Look at it and its uses and decide whether it is safe to SROA this global.
573///
574static bool IsUserOfGlobalSafeForSRA(User *U, GlobalValue *GV) {
575 // The user of the global must be a GEP Inst or a ConstantExpr GEP.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000576 if (!isa<GetElementPtrInst>(U) &&
577 (!isa<ConstantExpr>(U) ||
Chris Lattner941db492008-01-14 02:09:12 +0000578 cast<ConstantExpr>(U)->getOpcode() != Instruction::GetElementPtr))
579 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000580
Chris Lattner941db492008-01-14 02:09:12 +0000581 // Check to see if this ConstantExpr GEP is SRA'able. In particular, we
582 // don't like < 3 operand CE's, and we don't like non-constant integer
583 // indices. This enforces that all uses are 'gep GV, 0, C, ...' for some
584 // value of C.
585 if (U->getNumOperands() < 3 || !isa<Constant>(U->getOperand(1)) ||
586 !cast<Constant>(U->getOperand(1))->isNullValue() ||
587 !isa<ConstantInt>(U->getOperand(2)))
588 return false;
589
590 gep_type_iterator GEPI = gep_type_begin(U), E = gep_type_end(U);
591 ++GEPI; // Skip over the pointer index.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000592
Chris Lattner941db492008-01-14 02:09:12 +0000593 // If this is a use of an array allocation, do a bit more checking for sanity.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000594 if (ArrayType *AT = dyn_cast<ArrayType>(*GEPI)) {
Chris Lattner941db492008-01-14 02:09:12 +0000595 uint64_t NumElements = AT->getNumElements();
596 ConstantInt *Idx = cast<ConstantInt>(U->getOperand(2));
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000597
Chris Lattner941db492008-01-14 02:09:12 +0000598 // Check to make sure that index falls within the array. If not,
599 // something funny is going on, so we won't do the optimization.
600 //
601 if (Idx->getZExtValue() >= NumElements)
602 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000603
Chris Lattner941db492008-01-14 02:09:12 +0000604 // We cannot scalar repl this level of the array unless any array
605 // sub-indices are in-range constants. In particular, consider:
606 // A[0][i]. We cannot know that the user isn't doing invalid things like
607 // allowing i to index an out-of-range subscript that accesses A[1].
608 //
609 // Scalar replacing *just* the outer index of the array is probably not
610 // going to be a win anyway, so just give up.
611 for (++GEPI; // Skip array index.
Dan Gohman6874a2a2009-08-18 14:58:19 +0000612 GEPI != E;
Chris Lattner941db492008-01-14 02:09:12 +0000613 ++GEPI) {
614 uint64_t NumElements;
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000615 if (ArrayType *SubArrayTy = dyn_cast<ArrayType>(*GEPI))
Chris Lattner941db492008-01-14 02:09:12 +0000616 NumElements = SubArrayTy->getNumElements();
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000617 else if (VectorType *SubVectorTy = dyn_cast<VectorType>(*GEPI))
Dan Gohman6874a2a2009-08-18 14:58:19 +0000618 NumElements = SubVectorTy->getNumElements();
619 else {
Duncan Sands1df98592010-02-16 11:11:14 +0000620 assert((*GEPI)->isStructTy() &&
Dan Gohman6874a2a2009-08-18 14:58:19 +0000621 "Indexed GEP type is not array, vector, or struct!");
622 continue;
623 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000624
Chris Lattner941db492008-01-14 02:09:12 +0000625 ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPI.getOperand());
626 if (!IdxVal || IdxVal->getZExtValue() >= NumElements)
627 return false;
628 }
629 }
630
631 for (Value::use_iterator I = U->use_begin(), E = U->use_end(); I != E; ++I)
632 if (!isSafeSROAElementUse(*I))
633 return false;
634 return true;
635}
636
637/// GlobalUsersSafeToSRA - Look at all uses of the global and decide whether it
638/// is safe for us to perform this transformation.
639///
640static bool GlobalUsersSafeToSRA(GlobalValue *GV) {
641 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end();
642 UI != E; ++UI) {
643 if (!IsUserOfGlobalSafeForSRA(*UI, GV))
644 return false;
645 }
646 return true;
647}
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000648
Chris Lattner941db492008-01-14 02:09:12 +0000649
Chris Lattner670c8892004-10-08 17:32:09 +0000650/// SRAGlobal - Perform scalar replacement of aggregates on the specified global
651/// variable. This opens the door for other optimizations by exposing the
652/// behavior of the program in a more fine-grained way. We have determined that
653/// this transformation is safe already. We return the first global variable we
654/// insert so that the caller can reprocess it.
Chris Lattner7b550cc2009-11-06 04:27:31 +0000655static GlobalVariable *SRAGlobal(GlobalVariable *GV, const TargetData &TD) {
Chris Lattner727c2102008-01-14 01:31:05 +0000656 // Make sure this global only has simple uses that we can SRA.
Chris Lattner941db492008-01-14 02:09:12 +0000657 if (!GlobalUsersSafeToSRA(GV))
Chris Lattner727c2102008-01-14 01:31:05 +0000658 return 0;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000659
Rafael Espindolabb46f522009-01-15 20:18:42 +0000660 assert(GV->hasLocalLinkage() && !GV->isConstant());
Chris Lattner670c8892004-10-08 17:32:09 +0000661 Constant *Init = GV->getInitializer();
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000662 Type *Ty = Init->getType();
Misha Brukmanfd939082005-04-21 23:48:37 +0000663
Chris Lattner670c8892004-10-08 17:32:09 +0000664 std::vector<GlobalVariable*> NewGlobals;
665 Module::GlobalListType &Globals = GV->getParent()->getGlobalList();
666
Chris Lattner998182b2008-04-26 07:40:11 +0000667 // Get the alignment of the global, either explicit or target-specific.
668 unsigned StartAlignment = GV->getAlignment();
669 if (StartAlignment == 0)
670 StartAlignment = TD.getABITypeAlignment(GV->getType());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000671
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000672 if (StructType *STy = dyn_cast<StructType>(Ty)) {
Chris Lattner670c8892004-10-08 17:32:09 +0000673 NewGlobals.reserve(STy->getNumElements());
Chris Lattner998182b2008-04-26 07:40:11 +0000674 const StructLayout &Layout = *TD.getStructLayout(STy);
Chris Lattner670c8892004-10-08 17:32:09 +0000675 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
Chris Lattnera1f00f42012-01-25 06:48:06 +0000676 Constant *In = Init->getAggregateElement(i);
Chris Lattner670c8892004-10-08 17:32:09 +0000677 assert(In && "Couldn't get element of initializer?");
Chris Lattner7b550cc2009-11-06 04:27:31 +0000678 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(i), false,
Chris Lattner670c8892004-10-08 17:32:09 +0000679 GlobalVariable::InternalLinkage,
Daniel Dunbarfe09b202009-07-30 17:37:43 +0000680 In, GV->getName()+"."+Twine(i),
Hans Wennborgce718ff2012-06-23 11:37:03 +0000681 GV->getThreadLocalMode(),
Owen Anderson3d29df32009-07-08 01:26:06 +0000682 GV->getType()->getAddressSpace());
Chris Lattner670c8892004-10-08 17:32:09 +0000683 Globals.insert(GV, NGV);
684 NewGlobals.push_back(NGV);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000685
Chris Lattner998182b2008-04-26 07:40:11 +0000686 // Calculate the known alignment of the field. If the original aggregate
687 // had 256 byte alignment for example, something might depend on that:
688 // propagate info to each field.
689 uint64_t FieldOffset = Layout.getElementOffset(i);
690 unsigned NewAlign = (unsigned)MinAlign(StartAlignment, FieldOffset);
691 if (NewAlign > TD.getABITypeAlignment(STy->getElementType(i)))
692 NGV->setAlignment(NewAlign);
Chris Lattner670c8892004-10-08 17:32:09 +0000693 }
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000694 } else if (SequentialType *STy = dyn_cast<SequentialType>(Ty)) {
Chris Lattner670c8892004-10-08 17:32:09 +0000695 unsigned NumElements = 0;
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000696 if (ArrayType *ATy = dyn_cast<ArrayType>(STy))
Chris Lattner670c8892004-10-08 17:32:09 +0000697 NumElements = ATy->getNumElements();
Chris Lattner670c8892004-10-08 17:32:09 +0000698 else
Chris Lattner998182b2008-04-26 07:40:11 +0000699 NumElements = cast<VectorType>(STy)->getNumElements();
Chris Lattner670c8892004-10-08 17:32:09 +0000700
Chris Lattner1f21ef12005-02-23 16:53:04 +0000701 if (NumElements > 16 && GV->hasNUsesOrMore(16))
Chris Lattnerd514d822005-02-01 01:23:31 +0000702 return 0; // It's not worth it.
Chris Lattner670c8892004-10-08 17:32:09 +0000703 NewGlobals.reserve(NumElements);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000704
Duncan Sands777d2302009-05-09 07:06:46 +0000705 uint64_t EltSize = TD.getTypeAllocSize(STy->getElementType());
Chris Lattner998182b2008-04-26 07:40:11 +0000706 unsigned EltAlign = TD.getABITypeAlignment(STy->getElementType());
Chris Lattner670c8892004-10-08 17:32:09 +0000707 for (unsigned i = 0, e = NumElements; i != e; ++i) {
Chris Lattnera1f00f42012-01-25 06:48:06 +0000708 Constant *In = Init->getAggregateElement(i);
Chris Lattner670c8892004-10-08 17:32:09 +0000709 assert(In && "Couldn't get element of initializer?");
710
Chris Lattner7b550cc2009-11-06 04:27:31 +0000711 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(), false,
Chris Lattner670c8892004-10-08 17:32:09 +0000712 GlobalVariable::InternalLinkage,
Daniel Dunbarfe09b202009-07-30 17:37:43 +0000713 In, GV->getName()+"."+Twine(i),
Hans Wennborgce718ff2012-06-23 11:37:03 +0000714 GV->getThreadLocalMode(),
Owen Andersone9b11b42009-07-08 19:03:57 +0000715 GV->getType()->getAddressSpace());
Chris Lattner670c8892004-10-08 17:32:09 +0000716 Globals.insert(GV, NGV);
717 NewGlobals.push_back(NGV);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000718
Chris Lattner998182b2008-04-26 07:40:11 +0000719 // Calculate the known alignment of the field. If the original aggregate
720 // had 256 byte alignment for example, something might depend on that:
721 // propagate info to each field.
722 unsigned NewAlign = (unsigned)MinAlign(StartAlignment, EltSize*i);
723 if (NewAlign > EltAlign)
724 NGV->setAlignment(NewAlign);
Chris Lattner670c8892004-10-08 17:32:09 +0000725 }
726 }
727
728 if (NewGlobals.empty())
729 return 0;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000730
David Greene3215b0e2010-01-05 01:28:05 +0000731 DEBUG(dbgs() << "PERFORMING GLOBAL SRA ON: " << *GV);
Chris Lattner30ba5692004-10-11 05:54:41 +0000732
Chris Lattner7b550cc2009-11-06 04:27:31 +0000733 Constant *NullInt =Constant::getNullValue(Type::getInt32Ty(GV->getContext()));
Chris Lattner670c8892004-10-08 17:32:09 +0000734
735 // Loop over all of the uses of the global, replacing the constantexpr geps,
736 // with smaller constantexpr geps or direct references.
737 while (!GV->use_empty()) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000738 User *GEP = GV->use_back();
739 assert(((isa<ConstantExpr>(GEP) &&
740 cast<ConstantExpr>(GEP)->getOpcode()==Instruction::GetElementPtr)||
741 isa<GetElementPtrInst>(GEP)) && "NonGEP CE's are not SRAable!");
Misha Brukmanfd939082005-04-21 23:48:37 +0000742
Chris Lattner670c8892004-10-08 17:32:09 +0000743 // Ignore the 1th operand, which has to be zero or else the program is quite
744 // broken (undefined). Get the 2nd operand, which is the structure or array
745 // index.
Reid Spencerb83eb642006-10-20 07:07:24 +0000746 unsigned Val = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
Chris Lattner670c8892004-10-08 17:32:09 +0000747 if (Val >= NewGlobals.size()) Val = 0; // Out of bound array access.
748
Chris Lattner30ba5692004-10-11 05:54:41 +0000749 Value *NewPtr = NewGlobals[Val];
Chris Lattner670c8892004-10-08 17:32:09 +0000750
751 // Form a shorter GEP if needed.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000752 if (GEP->getNumOperands() > 3) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000753 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEP)) {
Chris Lattner55eb1c42007-01-31 04:40:53 +0000754 SmallVector<Constant*, 8> Idxs;
Chris Lattner30ba5692004-10-11 05:54:41 +0000755 Idxs.push_back(NullInt);
756 for (unsigned i = 3, e = CE->getNumOperands(); i != e; ++i)
757 Idxs.push_back(CE->getOperand(i));
Jay Foaddab3d292011-07-21 14:31:17 +0000758 NewPtr = ConstantExpr::getGetElementPtr(cast<Constant>(NewPtr), Idxs);
Chris Lattner30ba5692004-10-11 05:54:41 +0000759 } else {
760 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(GEP);
Chris Lattner699d1442007-01-31 19:59:55 +0000761 SmallVector<Value*, 8> Idxs;
Chris Lattner30ba5692004-10-11 05:54:41 +0000762 Idxs.push_back(NullInt);
763 for (unsigned i = 3, e = GEPI->getNumOperands(); i != e; ++i)
764 Idxs.push_back(GEPI->getOperand(i));
Jay Foada9203102011-07-25 09:48:08 +0000765 NewPtr = GetElementPtrInst::Create(NewPtr, Idxs,
Daniel Dunbarfe09b202009-07-30 17:37:43 +0000766 GEPI->getName()+"."+Twine(Val),GEPI);
Chris Lattner30ba5692004-10-11 05:54:41 +0000767 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000768 }
Chris Lattner30ba5692004-10-11 05:54:41 +0000769 GEP->replaceAllUsesWith(NewPtr);
770
771 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(GEP))
Chris Lattner7a7ed022004-10-16 18:09:00 +0000772 GEPI->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +0000773 else
774 cast<ConstantExpr>(GEP)->destroyConstant();
Chris Lattner670c8892004-10-08 17:32:09 +0000775 }
776
Chris Lattnere40e2d12004-10-08 20:25:55 +0000777 // Delete the old global, now that it is dead.
778 Globals.erase(GV);
Chris Lattner670c8892004-10-08 17:32:09 +0000779 ++NumSRA;
Chris Lattner30ba5692004-10-11 05:54:41 +0000780
781 // Loop over the new globals array deleting any globals that are obviously
782 // dead. This can arise due to scalarization of a structure or an array that
783 // has elements that are dead.
784 unsigned FirstGlobal = 0;
785 for (unsigned i = 0, e = NewGlobals.size(); i != e; ++i)
786 if (NewGlobals[i]->use_empty()) {
787 Globals.erase(NewGlobals[i]);
788 if (FirstGlobal == i) ++FirstGlobal;
789 }
790
791 return FirstGlobal != NewGlobals.size() ? NewGlobals[FirstGlobal] : 0;
Chris Lattner670c8892004-10-08 17:32:09 +0000792}
793
Chris Lattner9b34a612004-10-09 21:48:45 +0000794/// AllUsesOfValueWillTrapIfNull - Return true if all users of the specified
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000795/// value will trap if the value is dynamically null. PHIs keeps track of any
Chris Lattner81686182007-09-13 16:30:19 +0000796/// phi nodes we've seen to avoid reprocessing them.
Gabor Greif6ce02b52010-04-06 19:24:18 +0000797static bool AllUsesOfValueWillTrapIfNull(const Value *V,
798 SmallPtrSet<const PHINode*, 8> &PHIs) {
799 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;
Gabor Greifa01d6db2010-04-06 19:14:05 +0000800 ++UI) {
Gabor Greif6ce02b52010-04-06 19:24:18 +0000801 const User *U = *UI;
Gabor Greifa01d6db2010-04-06 19:14:05 +0000802
803 if (isa<LoadInst>(U)) {
Chris Lattner9b34a612004-10-09 21:48:45 +0000804 // Will trap.
Gabor Greif6ce02b52010-04-06 19:24:18 +0000805 } else if (const StoreInst *SI = dyn_cast<StoreInst>(U)) {
Chris Lattner9b34a612004-10-09 21:48:45 +0000806 if (SI->getOperand(0) == V) {
Gabor Greifa01d6db2010-04-06 19:14:05 +0000807 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner9b34a612004-10-09 21:48:45 +0000808 return false; // Storing the value.
809 }
Gabor Greif6ce02b52010-04-06 19:24:18 +0000810 } else if (const CallInst *CI = dyn_cast<CallInst>(U)) {
Gabor Greif654c06f2010-03-20 21:00:25 +0000811 if (CI->getCalledValue() != V) {
Gabor Greifa01d6db2010-04-06 19:14:05 +0000812 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner9b34a612004-10-09 21:48:45 +0000813 return false; // Not calling the ptr
814 }
Gabor Greif6ce02b52010-04-06 19:24:18 +0000815 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(U)) {
Gabor Greif654c06f2010-03-20 21:00:25 +0000816 if (II->getCalledValue() != V) {
Gabor Greifa01d6db2010-04-06 19:14:05 +0000817 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner9b34a612004-10-09 21:48:45 +0000818 return false; // Not calling the ptr
819 }
Gabor Greif6ce02b52010-04-06 19:24:18 +0000820 } else if (const BitCastInst *CI = dyn_cast<BitCastInst>(U)) {
Chris Lattner81686182007-09-13 16:30:19 +0000821 if (!AllUsesOfValueWillTrapIfNull(CI, PHIs)) return false;
Gabor Greif6ce02b52010-04-06 19:24:18 +0000822 } else if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
Chris Lattner81686182007-09-13 16:30:19 +0000823 if (!AllUsesOfValueWillTrapIfNull(GEPI, PHIs)) return false;
Gabor Greif6ce02b52010-04-06 19:24:18 +0000824 } else if (const PHINode *PN = dyn_cast<PHINode>(U)) {
Chris Lattner81686182007-09-13 16:30:19 +0000825 // If we've already seen this phi node, ignore it, it has already been
826 // checked.
Jakob Stoklund Olesenb489d0f2010-01-29 23:54:14 +0000827 if (PHIs.insert(PN) && !AllUsesOfValueWillTrapIfNull(PN, PHIs))
828 return false;
Gabor Greifa01d6db2010-04-06 19:14:05 +0000829 } else if (isa<ICmpInst>(U) &&
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000830 isa<ConstantPointerNull>(UI->getOperand(1))) {
Nick Lewyckye7ee59b2010-02-25 06:39:10 +0000831 // Ignore icmp X, null
Chris Lattner9b34a612004-10-09 21:48:45 +0000832 } else {
Gabor Greifa01d6db2010-04-06 19:14:05 +0000833 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner9b34a612004-10-09 21:48:45 +0000834 return false;
835 }
Gabor Greifa01d6db2010-04-06 19:14:05 +0000836 }
Chris Lattner9b34a612004-10-09 21:48:45 +0000837 return true;
838}
839
840/// AllUsesOfLoadedValueWillTrapIfNull - Return true if all uses of any loads
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000841/// from GV will trap if the loaded value is null. Note that this also permits
842/// comparisons of the loaded value against null, as a special case.
Gabor Greif6ce02b52010-04-06 19:24:18 +0000843static bool AllUsesOfLoadedValueWillTrapIfNull(const GlobalVariable *GV) {
844 for (Value::const_use_iterator UI = GV->use_begin(), E = GV->use_end();
Gabor Greifa01d6db2010-04-06 19:14:05 +0000845 UI != E; ++UI) {
Gabor Greif6ce02b52010-04-06 19:24:18 +0000846 const User *U = *UI;
Gabor Greifa01d6db2010-04-06 19:14:05 +0000847
Gabor Greif6ce02b52010-04-06 19:24:18 +0000848 if (const LoadInst *LI = dyn_cast<LoadInst>(U)) {
849 SmallPtrSet<const PHINode*, 8> PHIs;
Chris Lattner81686182007-09-13 16:30:19 +0000850 if (!AllUsesOfValueWillTrapIfNull(LI, PHIs))
Chris Lattner9b34a612004-10-09 21:48:45 +0000851 return false;
Gabor Greifa01d6db2010-04-06 19:14:05 +0000852 } else if (isa<StoreInst>(U)) {
Chris Lattner9b34a612004-10-09 21:48:45 +0000853 // Ignore stores to the global.
854 } else {
855 // We don't know or understand this user, bail out.
Gabor Greifa01d6db2010-04-06 19:14:05 +0000856 //cerr << "UNKNOWN USER OF GLOBAL!: " << *U;
Chris Lattner9b34a612004-10-09 21:48:45 +0000857 return false;
858 }
Gabor Greifa01d6db2010-04-06 19:14:05 +0000859 }
Chris Lattner9b34a612004-10-09 21:48:45 +0000860 return true;
861}
862
Chris Lattner7b550cc2009-11-06 04:27:31 +0000863static bool OptimizeAwayTrappingUsesOfValue(Value *V, Constant *NewV) {
Chris Lattner708148e2004-10-10 23:14:11 +0000864 bool Changed = false;
865 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ) {
866 Instruction *I = cast<Instruction>(*UI++);
867 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
868 LI->setOperand(0, NewV);
869 Changed = true;
870 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
871 if (SI->getOperand(1) == V) {
872 SI->setOperand(1, NewV);
873 Changed = true;
874 }
875 } else if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
Gabor Greiffa1f5c22010-04-06 18:45:08 +0000876 CallSite CS(I);
877 if (CS.getCalledValue() == V) {
Chris Lattner708148e2004-10-10 23:14:11 +0000878 // Calling through the pointer! Turn into a direct call, but be careful
879 // that the pointer is not also being passed as an argument.
Gabor Greiffa1f5c22010-04-06 18:45:08 +0000880 CS.setCalledFunction(NewV);
Chris Lattner708148e2004-10-10 23:14:11 +0000881 Changed = true;
882 bool PassedAsArg = false;
Gabor Greiffa1f5c22010-04-06 18:45:08 +0000883 for (unsigned i = 0, e = CS.arg_size(); i != e; ++i)
884 if (CS.getArgument(i) == V) {
Chris Lattner708148e2004-10-10 23:14:11 +0000885 PassedAsArg = true;
Gabor Greiffa1f5c22010-04-06 18:45:08 +0000886 CS.setArgument(i, NewV);
Chris Lattner708148e2004-10-10 23:14:11 +0000887 }
888
889 if (PassedAsArg) {
890 // Being passed as an argument also. Be careful to not invalidate UI!
891 UI = V->use_begin();
892 }
893 }
894 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
895 Changed |= OptimizeAwayTrappingUsesOfValue(CI,
Owen Andersonbaf3c402009-07-29 18:55:55 +0000896 ConstantExpr::getCast(CI->getOpcode(),
Chris Lattner7b550cc2009-11-06 04:27:31 +0000897 NewV, CI->getType()));
Chris Lattner708148e2004-10-10 23:14:11 +0000898 if (CI->use_empty()) {
899 Changed = true;
Chris Lattner7a7ed022004-10-16 18:09:00 +0000900 CI->eraseFromParent();
Chris Lattner708148e2004-10-10 23:14:11 +0000901 }
902 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
903 // Should handle GEP here.
Chris Lattner55eb1c42007-01-31 04:40:53 +0000904 SmallVector<Constant*, 8> Idxs;
905 Idxs.reserve(GEPI->getNumOperands()-1);
Gabor Greif5e463212008-05-29 01:59:18 +0000906 for (User::op_iterator i = GEPI->op_begin() + 1, e = GEPI->op_end();
907 i != e; ++i)
908 if (Constant *C = dyn_cast<Constant>(*i))
Chris Lattner55eb1c42007-01-31 04:40:53 +0000909 Idxs.push_back(C);
Chris Lattner708148e2004-10-10 23:14:11 +0000910 else
911 break;
Chris Lattner55eb1c42007-01-31 04:40:53 +0000912 if (Idxs.size() == GEPI->getNumOperands()-1)
Chris Lattner708148e2004-10-10 23:14:11 +0000913 Changed |= OptimizeAwayTrappingUsesOfValue(GEPI,
Jay Foaddab3d292011-07-21 14:31:17 +0000914 ConstantExpr::getGetElementPtr(NewV, Idxs));
Chris Lattner708148e2004-10-10 23:14:11 +0000915 if (GEPI->use_empty()) {
916 Changed = true;
Chris Lattner7a7ed022004-10-16 18:09:00 +0000917 GEPI->eraseFromParent();
Chris Lattner708148e2004-10-10 23:14:11 +0000918 }
919 }
920 }
921
922 return Changed;
923}
924
925
926/// OptimizeAwayTrappingUsesOfLoads - The specified global has only one non-null
927/// value stored into it. If there are uses of the loaded value that would trap
928/// if the loaded value is dynamically null, then we know that they cannot be
929/// reachable with a null optimize away the load.
Nick Lewycky6a577f82012-02-12 01:13:18 +0000930static bool OptimizeAwayTrappingUsesOfLoads(GlobalVariable *GV, Constant *LV,
931 TargetData *TD,
932 TargetLibraryInfo *TLI) {
Chris Lattner708148e2004-10-10 23:14:11 +0000933 bool Changed = false;
934
Chris Lattner92c6bd22009-01-14 00:12:58 +0000935 // Keep track of whether we are able to remove all the uses of the global
936 // other than the store that defines it.
937 bool AllNonStoreUsesGone = true;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000938
Chris Lattner708148e2004-10-10 23:14:11 +0000939 // Replace all uses of loads with uses of uses of the stored value.
Chris Lattner92c6bd22009-01-14 00:12:58 +0000940 for (Value::use_iterator GUI = GV->use_begin(), E = GV->use_end(); GUI != E;){
941 User *GlobalUser = *GUI++;
942 if (LoadInst *LI = dyn_cast<LoadInst>(GlobalUser)) {
Chris Lattner7b550cc2009-11-06 04:27:31 +0000943 Changed |= OptimizeAwayTrappingUsesOfValue(LI, LV);
Chris Lattner92c6bd22009-01-14 00:12:58 +0000944 // If we were able to delete all uses of the loads
945 if (LI->use_empty()) {
946 LI->eraseFromParent();
947 Changed = true;
948 } else {
949 AllNonStoreUsesGone = false;
950 }
951 } else if (isa<StoreInst>(GlobalUser)) {
952 // Ignore the store that stores "LV" to the global.
953 assert(GlobalUser->getOperand(1) == GV &&
954 "Must be storing *to* the global");
Chris Lattner708148e2004-10-10 23:14:11 +0000955 } else {
Chris Lattner92c6bd22009-01-14 00:12:58 +0000956 AllNonStoreUsesGone = false;
957
958 // If we get here we could have other crazy uses that are transitively
959 // loaded.
960 assert((isa<PHINode>(GlobalUser) || isa<SelectInst>(GlobalUser) ||
Chris Lattner98a42b22011-05-22 07:15:13 +0000961 isa<ConstantExpr>(GlobalUser) || isa<CmpInst>(GlobalUser)) &&
962 "Only expect load and stores!");
Chris Lattner708148e2004-10-10 23:14:11 +0000963 }
Chris Lattner92c6bd22009-01-14 00:12:58 +0000964 }
Chris Lattner708148e2004-10-10 23:14:11 +0000965
966 if (Changed) {
David Greene3215b0e2010-01-05 01:28:05 +0000967 DEBUG(dbgs() << "OPTIMIZED LOADS FROM STORED ONCE POINTER: " << *GV);
Chris Lattner708148e2004-10-10 23:14:11 +0000968 ++NumGlobUses;
969 }
970
Chris Lattner708148e2004-10-10 23:14:11 +0000971 // If we nuked all of the loads, then none of the stores are needed either,
972 // nor is the global.
Chris Lattner92c6bd22009-01-14 00:12:58 +0000973 if (AllNonStoreUsesGone) {
Nick Lewycky8899d5c2012-07-24 07:21:08 +0000974 if (isLeakCheckerRoot(GV)) {
975 Changed |= CleanupPointerRootUsers(GV);
976 } else {
977 Changed = true;
978 CleanupConstantGlobalUsers(GV, 0, TD, TLI);
979 }
Chris Lattner708148e2004-10-10 23:14:11 +0000980 if (GV->use_empty()) {
Nick Lewycky8899d5c2012-07-24 07:21:08 +0000981 DEBUG(dbgs() << " *** GLOBAL NOW DEAD!\n");
982 Changed = true;
Chris Lattner7a7ed022004-10-16 18:09:00 +0000983 GV->eraseFromParent();
Chris Lattner708148e2004-10-10 23:14:11 +0000984 ++NumDeleted;
985 }
Chris Lattner708148e2004-10-10 23:14:11 +0000986 }
987 return Changed;
988}
989
Chris Lattner30ba5692004-10-11 05:54:41 +0000990/// ConstantPropUsersOf - Walk the use list of V, constant folding all of the
991/// instructions that are foldable.
Nick Lewycky6a577f82012-02-12 01:13:18 +0000992static void ConstantPropUsersOf(Value *V,
993 TargetData *TD, TargetLibraryInfo *TLI) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000994 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; )
995 if (Instruction *I = dyn_cast<Instruction>(*UI++))
Nick Lewycky6a577f82012-02-12 01:13:18 +0000996 if (Constant *NewC = ConstantFoldInstruction(I, TD, TLI)) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000997 I->replaceAllUsesWith(NewC);
998
Chris Lattnerd514d822005-02-01 01:23:31 +0000999 // Advance UI to the next non-I use to avoid invalidating it!
1000 // Instructions could multiply use V.
1001 while (UI != E && *UI == I)
Chris Lattner30ba5692004-10-11 05:54:41 +00001002 ++UI;
Chris Lattnerd514d822005-02-01 01:23:31 +00001003 I->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +00001004 }
1005}
1006
1007/// OptimizeGlobalAddressOfMalloc - This function takes the specified global
1008/// variable, and transforms the program as if it always contained the result of
1009/// the specified malloc. Because it is always the result of the specified
1010/// malloc, there is no reason to actually DO the malloc. Instead, turn the
Chris Lattner6e8fbad2006-11-30 17:32:29 +00001011/// malloc into a global, and any loads of GV as uses of the new global.
Chris Lattner30ba5692004-10-11 05:54:41 +00001012static GlobalVariable *OptimizeGlobalAddressOfMalloc(GlobalVariable *GV,
Victor Hernandez83d63912009-09-18 22:35:49 +00001013 CallInst *CI,
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001014 Type *AllocTy,
Chris Lattnera6874652010-02-25 22:33:52 +00001015 ConstantInt *NElements,
Nick Lewycky6a577f82012-02-12 01:13:18 +00001016 TargetData *TD,
1017 TargetLibraryInfo *TLI) {
Chris Lattnera6874652010-02-25 22:33:52 +00001018 DEBUG(errs() << "PROMOTING GLOBAL: " << *GV << " CALL = " << *CI << '\n');
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001019
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001020 Type *GlobalType;
Chris Lattnera6874652010-02-25 22:33:52 +00001021 if (NElements->getZExtValue() == 1)
1022 GlobalType = AllocTy;
1023 else
1024 // If we have an array allocation, the global variable is of an array.
1025 GlobalType = ArrayType::get(AllocTy, NElements->getZExtValue());
Victor Hernandez83d63912009-09-18 22:35:49 +00001026
1027 // Create the new global variable. The contents of the malloc'd memory is
1028 // undefined, so initialize with an undef value.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001029 GlobalVariable *NewGV = new GlobalVariable(*GV->getParent(),
Chris Lattnere9fd4442010-02-26 23:42:13 +00001030 GlobalType, false,
Chris Lattnera6874652010-02-25 22:33:52 +00001031 GlobalValue::InternalLinkage,
Chris Lattnere9fd4442010-02-26 23:42:13 +00001032 UndefValue::get(GlobalType),
Victor Hernandez83d63912009-09-18 22:35:49 +00001033 GV->getName()+".body",
1034 GV,
Hans Wennborgce718ff2012-06-23 11:37:03 +00001035 GV->getThreadLocalMode());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001036
Chris Lattnera6874652010-02-25 22:33:52 +00001037 // If there are bitcast users of the malloc (which is typical, usually we have
1038 // a malloc + bitcast) then replace them with uses of the new global. Update
1039 // other users to use the global as well.
1040 BitCastInst *TheBC = 0;
1041 while (!CI->use_empty()) {
1042 Instruction *User = cast<Instruction>(CI->use_back());
1043 if (BitCastInst *BCI = dyn_cast<BitCastInst>(User)) {
1044 if (BCI->getType() == NewGV->getType()) {
1045 BCI->replaceAllUsesWith(NewGV);
1046 BCI->eraseFromParent();
1047 } else {
1048 BCI->setOperand(0, NewGV);
1049 }
1050 } else {
1051 if (TheBC == 0)
1052 TheBC = new BitCastInst(NewGV, CI->getType(), "newgv", CI);
1053 User->replaceUsesOfWith(CI, TheBC);
1054 }
1055 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001056
Victor Hernandez83d63912009-09-18 22:35:49 +00001057 Constant *RepValue = NewGV;
1058 if (NewGV->getType() != GV->getType()->getElementType())
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001059 RepValue = ConstantExpr::getBitCast(RepValue,
Victor Hernandez83d63912009-09-18 22:35:49 +00001060 GV->getType()->getElementType());
1061
1062 // If there is a comparison against null, we will insert a global bool to
1063 // keep track of whether the global was initialized yet or not.
1064 GlobalVariable *InitBool =
Chris Lattner7b550cc2009-11-06 04:27:31 +00001065 new GlobalVariable(Type::getInt1Ty(GV->getContext()), false,
Victor Hernandez83d63912009-09-18 22:35:49 +00001066 GlobalValue::InternalLinkage,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001067 ConstantInt::getFalse(GV->getContext()),
Hans Wennborgce718ff2012-06-23 11:37:03 +00001068 GV->getName()+".init", GV->getThreadLocalMode());
Victor Hernandez83d63912009-09-18 22:35:49 +00001069 bool InitBoolUsed = false;
1070
1071 // Loop over all uses of GV, processing them in turn.
Chris Lattnera6874652010-02-25 22:33:52 +00001072 while (!GV->use_empty()) {
1073 if (StoreInst *SI = dyn_cast<StoreInst>(GV->use_back())) {
Victor Hernandez83d63912009-09-18 22:35:49 +00001074 // The global is initialized when the store to it occurs.
Nick Lewyckyfad4d402012-02-05 19:56:38 +00001075 new StoreInst(ConstantInt::getTrue(GV->getContext()), InitBool, false, 0,
1076 SI->getOrdering(), SI->getSynchScope(), SI);
Victor Hernandez83d63912009-09-18 22:35:49 +00001077 SI->eraseFromParent();
Chris Lattnera6874652010-02-25 22:33:52 +00001078 continue;
Victor Hernandez83d63912009-09-18 22:35:49 +00001079 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001080
Chris Lattnera6874652010-02-25 22:33:52 +00001081 LoadInst *LI = cast<LoadInst>(GV->use_back());
1082 while (!LI->use_empty()) {
1083 Use &LoadUse = LI->use_begin().getUse();
1084 if (!isa<ICmpInst>(LoadUse.getUser())) {
1085 LoadUse = RepValue;
1086 continue;
1087 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001088
Chris Lattnera6874652010-02-25 22:33:52 +00001089 ICmpInst *ICI = cast<ICmpInst>(LoadUse.getUser());
1090 // Replace the cmp X, 0 with a use of the bool value.
Nick Lewyckyfad4d402012-02-05 19:56:38 +00001091 // Sink the load to where the compare was, if atomic rules allow us to.
1092 Value *LV = new LoadInst(InitBool, InitBool->getName()+".val", false, 0,
1093 LI->getOrdering(), LI->getSynchScope(),
1094 LI->isUnordered() ? (Instruction*)ICI : LI);
Chris Lattnera6874652010-02-25 22:33:52 +00001095 InitBoolUsed = true;
1096 switch (ICI->getPredicate()) {
1097 default: llvm_unreachable("Unknown ICmp Predicate!");
1098 case ICmpInst::ICMP_ULT:
1099 case ICmpInst::ICMP_SLT: // X < null -> always false
1100 LV = ConstantInt::getFalse(GV->getContext());
1101 break;
1102 case ICmpInst::ICMP_ULE:
1103 case ICmpInst::ICMP_SLE:
1104 case ICmpInst::ICMP_EQ:
1105 LV = BinaryOperator::CreateNot(LV, "notinit", ICI);
1106 break;
1107 case ICmpInst::ICMP_NE:
1108 case ICmpInst::ICMP_UGE:
1109 case ICmpInst::ICMP_SGE:
1110 case ICmpInst::ICMP_UGT:
1111 case ICmpInst::ICMP_SGT:
1112 break; // no change.
1113 }
1114 ICI->replaceAllUsesWith(LV);
1115 ICI->eraseFromParent();
1116 }
1117 LI->eraseFromParent();
1118 }
Victor Hernandez83d63912009-09-18 22:35:49 +00001119
1120 // If the initialization boolean was used, insert it, otherwise delete it.
1121 if (!InitBoolUsed) {
1122 while (!InitBool->use_empty()) // Delete initializations
Chris Lattnera6874652010-02-25 22:33:52 +00001123 cast<StoreInst>(InitBool->use_back())->eraseFromParent();
Victor Hernandez83d63912009-09-18 22:35:49 +00001124 delete InitBool;
1125 } else
1126 GV->getParent()->getGlobalList().insert(GV, InitBool);
1127
Chris Lattnera6874652010-02-25 22:33:52 +00001128 // Now the GV is dead, nuke it and the malloc..
Victor Hernandez83d63912009-09-18 22:35:49 +00001129 GV->eraseFromParent();
Victor Hernandez83d63912009-09-18 22:35:49 +00001130 CI->eraseFromParent();
1131
1132 // To further other optimizations, loop over all users of NewGV and try to
1133 // constant prop them. This will promote GEP instructions with constant
1134 // indices into GEP constant-exprs, which will allow global-opt to hack on it.
Nick Lewycky6a577f82012-02-12 01:13:18 +00001135 ConstantPropUsersOf(NewGV, TD, TLI);
Victor Hernandez83d63912009-09-18 22:35:49 +00001136 if (RepValue != NewGV)
Nick Lewycky6a577f82012-02-12 01:13:18 +00001137 ConstantPropUsersOf(RepValue, TD, TLI);
Victor Hernandez83d63912009-09-18 22:35:49 +00001138
1139 return NewGV;
1140}
1141
Chris Lattnerfa07e4f2004-12-02 07:11:07 +00001142/// ValueIsOnlyUsedLocallyOrStoredToOneGlobal - Scan the use-list of V checking
1143/// to make sure that there are no complex uses of V. We permit simple things
1144/// like dereferencing the pointer, but not storing through the address, unless
1145/// it is to the specified global.
Gabor Greif0b520db2010-04-06 18:58:22 +00001146static bool ValueIsOnlyUsedLocallyOrStoredToOneGlobal(const Instruction *V,
1147 const GlobalVariable *GV,
Gabor Greifa01d6db2010-04-06 19:14:05 +00001148 SmallPtrSet<const PHINode*, 8> &PHIs) {
Gabor Greif0b520db2010-04-06 18:58:22 +00001149 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end();
Gabor Greifa01d6db2010-04-06 19:14:05 +00001150 UI != E; ++UI) {
Gabor Greif0b520db2010-04-06 18:58:22 +00001151 const Instruction *Inst = cast<Instruction>(*UI);
Gabor Greifa01d6db2010-04-06 19:14:05 +00001152
Chris Lattner49b6d4a2008-12-15 21:08:54 +00001153 if (isa<LoadInst>(Inst) || isa<CmpInst>(Inst)) {
1154 continue; // Fine, ignore.
1155 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001156
Gabor Greif0b520db2010-04-06 18:58:22 +00001157 if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
Chris Lattnerfa07e4f2004-12-02 07:11:07 +00001158 if (SI->getOperand(0) == V && SI->getOperand(1) != GV)
1159 return false; // Storing the pointer itself... bad.
Chris Lattner49b6d4a2008-12-15 21:08:54 +00001160 continue; // Otherwise, storing through it, or storing into GV... fine.
1161 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001162
Chris Lattnera2fb2342010-04-10 18:19:22 +00001163 // Must index into the array and into the struct.
1164 if (isa<GetElementPtrInst>(Inst) && Inst->getNumOperands() >= 3) {
Chris Lattner49b6d4a2008-12-15 21:08:54 +00001165 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(Inst, GV, PHIs))
Chris Lattnerfa07e4f2004-12-02 07:11:07 +00001166 return false;
Chris Lattner49b6d4a2008-12-15 21:08:54 +00001167 continue;
1168 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001169
Gabor Greif0b520db2010-04-06 18:58:22 +00001170 if (const PHINode *PN = dyn_cast<PHINode>(Inst)) {
Chris Lattnerc451f9c2007-09-13 16:37:20 +00001171 // PHIs are ok if all uses are ok. Don't infinitely recurse through PHI
1172 // cycles.
1173 if (PHIs.insert(PN))
Chris Lattner5e6e4942007-09-14 03:41:21 +00001174 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(PN, GV, PHIs))
1175 return false;
Chris Lattner49b6d4a2008-12-15 21:08:54 +00001176 continue;
Chris Lattnerfa07e4f2004-12-02 07:11:07 +00001177 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001178
Gabor Greif0b520db2010-04-06 18:58:22 +00001179 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Inst)) {
Chris Lattner49b6d4a2008-12-15 21:08:54 +00001180 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(BCI, GV, PHIs))
1181 return false;
1182 continue;
1183 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001184
Chris Lattner49b6d4a2008-12-15 21:08:54 +00001185 return false;
1186 }
Chris Lattnerfa07e4f2004-12-02 07:11:07 +00001187 return true;
Chris Lattnerfa07e4f2004-12-02 07:11:07 +00001188}
1189
Chris Lattner86395032006-09-30 23:32:09 +00001190/// ReplaceUsesOfMallocWithGlobal - The Alloc pointer is stored into GV
1191/// somewhere. Transform all uses of the allocation into loads from the
1192/// global and uses of the resultant pointer. Further, delete the store into
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001193/// GV. This assumes that these value pass the
Chris Lattner86395032006-09-30 23:32:09 +00001194/// 'ValueIsOnlyUsedLocallyOrStoredToOneGlobal' predicate.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001195static void ReplaceUsesOfMallocWithGlobal(Instruction *Alloc,
Chris Lattner86395032006-09-30 23:32:09 +00001196 GlobalVariable *GV) {
1197 while (!Alloc->use_empty()) {
Chris Lattnera637a8b2007-09-13 18:00:31 +00001198 Instruction *U = cast<Instruction>(*Alloc->use_begin());
1199 Instruction *InsertPt = U;
Chris Lattner86395032006-09-30 23:32:09 +00001200 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
1201 // If this is the store of the allocation into the global, remove it.
1202 if (SI->getOperand(1) == GV) {
1203 SI->eraseFromParent();
1204 continue;
1205 }
Chris Lattnera637a8b2007-09-13 18:00:31 +00001206 } else if (PHINode *PN = dyn_cast<PHINode>(U)) {
1207 // Insert the load in the corresponding predecessor, not right before the
1208 // PHI.
Gabor Greifa36791d2009-01-23 19:40:15 +00001209 InsertPt = PN->getIncomingBlock(Alloc->use_begin())->getTerminator();
Chris Lattner101f44e2008-12-15 21:44:34 +00001210 } else if (isa<BitCastInst>(U)) {
1211 // Must be bitcast between the malloc and store to initialize the global.
1212 ReplaceUsesOfMallocWithGlobal(U, GV);
1213 U->eraseFromParent();
1214 continue;
1215 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
1216 // If this is a "GEP bitcast" and the user is a store to the global, then
1217 // just process it as a bitcast.
1218 if (GEPI->hasAllZeroIndices() && GEPI->hasOneUse())
1219 if (StoreInst *SI = dyn_cast<StoreInst>(GEPI->use_back()))
1220 if (SI->getOperand(1) == GV) {
1221 // Must be bitcast GEP between the malloc and store to initialize
1222 // the global.
1223 ReplaceUsesOfMallocWithGlobal(GEPI, GV);
1224 GEPI->eraseFromParent();
1225 continue;
1226 }
Chris Lattner86395032006-09-30 23:32:09 +00001227 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001228
Chris Lattner86395032006-09-30 23:32:09 +00001229 // Insert a load from the global, and use it instead of the malloc.
Chris Lattnera637a8b2007-09-13 18:00:31 +00001230 Value *NL = new LoadInst(GV, GV->getName()+".val", InsertPt);
Chris Lattner86395032006-09-30 23:32:09 +00001231 U->replaceUsesOfWith(Alloc, NL);
1232 }
1233}
1234
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001235/// LoadUsesSimpleEnoughForHeapSRA - Verify that all uses of V (a load, or a phi
1236/// of a load) are simple enough to perform heap SRA on. This permits GEP's
1237/// that index through the array and struct field, icmps of null, and PHIs.
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001238static bool LoadUsesSimpleEnoughForHeapSRA(const Value *V,
Gabor Greif27236912010-04-07 18:59:26 +00001239 SmallPtrSet<const PHINode*, 32> &LoadUsingPHIs,
1240 SmallPtrSet<const PHINode*, 32> &LoadUsingPHIsPerLoad) {
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001241 // We permit two users of the load: setcc comparing against the null
1242 // pointer, and a getelementptr of a specific form.
Gabor Greif27236912010-04-07 18:59:26 +00001243 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;
1244 ++UI) {
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001245 const Instruction *User = cast<Instruction>(*UI);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001246
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001247 // Comparison against null is ok.
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001248 if (const ICmpInst *ICI = dyn_cast<ICmpInst>(User)) {
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001249 if (!isa<ConstantPointerNull>(ICI->getOperand(1)))
1250 return false;
1251 continue;
1252 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001253
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001254 // getelementptr is also ok, but only a simple form.
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001255 if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001256 // Must index into the array and into the struct.
1257 if (GEPI->getNumOperands() < 3)
1258 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001259
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001260 // Otherwise the GEP is ok.
1261 continue;
1262 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001263
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001264 if (const PHINode *PN = dyn_cast<PHINode>(User)) {
Evan Cheng5d163962009-06-02 00:56:07 +00001265 if (!LoadUsingPHIsPerLoad.insert(PN))
1266 // This means some phi nodes are dependent on each other.
1267 // Avoid infinite looping!
1268 return false;
1269 if (!LoadUsingPHIs.insert(PN))
1270 // If we have already analyzed this PHI, then it is safe.
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001271 continue;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001272
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001273 // Make sure all uses of the PHI are simple enough to transform.
Evan Cheng5d163962009-06-02 00:56:07 +00001274 if (!LoadUsesSimpleEnoughForHeapSRA(PN,
1275 LoadUsingPHIs, LoadUsingPHIsPerLoad))
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001276 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001277
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001278 continue;
Chris Lattner86395032006-09-30 23:32:09 +00001279 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001280
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001281 // Otherwise we don't know what this is, not ok.
1282 return false;
1283 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001284
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001285 return true;
1286}
1287
1288
1289/// AllGlobalLoadUsesSimpleEnoughForHeapSRA - If all users of values loaded from
1290/// GV are simple enough to perform HeapSRA, return true.
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001291static bool AllGlobalLoadUsesSimpleEnoughForHeapSRA(const GlobalVariable *GV,
Victor Hernandez83d63912009-09-18 22:35:49 +00001292 Instruction *StoredVal) {
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001293 SmallPtrSet<const PHINode*, 32> LoadUsingPHIs;
1294 SmallPtrSet<const PHINode*, 32> LoadUsingPHIsPerLoad;
Gabor Greif27236912010-04-07 18:59:26 +00001295 for (Value::const_use_iterator UI = GV->use_begin(), E = GV->use_end();
1296 UI != E; ++UI)
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001297 if (const LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
Evan Cheng5d163962009-06-02 00:56:07 +00001298 if (!LoadUsesSimpleEnoughForHeapSRA(LI, LoadUsingPHIs,
1299 LoadUsingPHIsPerLoad))
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001300 return false;
Evan Cheng5d163962009-06-02 00:56:07 +00001301 LoadUsingPHIsPerLoad.clear();
1302 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001303
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001304 // If we reach here, we know that all uses of the loads and transitive uses
1305 // (through PHI nodes) are simple enough to transform. However, we don't know
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001306 // that all inputs the to the PHI nodes are in the same equivalence sets.
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001307 // Check to verify that all operands of the PHIs are either PHIS that can be
1308 // transformed, loads from GV, or MI itself.
Gabor Greif27236912010-04-07 18:59:26 +00001309 for (SmallPtrSet<const PHINode*, 32>::const_iterator I = LoadUsingPHIs.begin()
1310 , E = LoadUsingPHIs.end(); I != E; ++I) {
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001311 const PHINode *PN = *I;
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001312 for (unsigned op = 0, e = PN->getNumIncomingValues(); op != e; ++op) {
1313 Value *InVal = PN->getIncomingValue(op);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001314
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001315 // PHI of the stored value itself is ok.
Victor Hernandez83d63912009-09-18 22:35:49 +00001316 if (InVal == StoredVal) continue;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001317
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001318 if (const PHINode *InPN = dyn_cast<PHINode>(InVal)) {
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001319 // One of the PHIs in our set is (optimistically) ok.
1320 if (LoadUsingPHIs.count(InPN))
1321 continue;
1322 return false;
1323 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001324
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001325 // Load from GV is ok.
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001326 if (const LoadInst *LI = dyn_cast<LoadInst>(InVal))
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001327 if (LI->getOperand(0) == GV)
1328 continue;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001329
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001330 // UNDEF? NULL?
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001331
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001332 // Anything else is rejected.
1333 return false;
1334 }
1335 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001336
Chris Lattner86395032006-09-30 23:32:09 +00001337 return true;
1338}
1339
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001340static Value *GetHeapSROAValue(Value *V, unsigned FieldNo,
1341 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001342 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001343 std::vector<Value*> &FieldVals = InsertedScalarizedValues[V];
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001344
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001345 if (FieldNo >= FieldVals.size())
1346 FieldVals.resize(FieldNo+1);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001347
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001348 // If we already have this value, just reuse the previously scalarized
1349 // version.
1350 if (Value *FieldVal = FieldVals[FieldNo])
1351 return FieldVal;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001352
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001353 // Depending on what instruction this is, we have several cases.
1354 Value *Result;
1355 if (LoadInst *LI = dyn_cast<LoadInst>(V)) {
1356 // This is a scalarized version of the load from the global. Just create
1357 // a new Load of the scalarized global.
1358 Result = new LoadInst(GetHeapSROAValue(LI->getOperand(0), FieldNo,
1359 InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001360 PHIsToRewrite),
Daniel Dunbarfe09b202009-07-30 17:37:43 +00001361 LI->getName()+".f"+Twine(FieldNo), LI);
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001362 } else if (PHINode *PN = dyn_cast<PHINode>(V)) {
1363 // PN's type is pointer to struct. Make a new PHI of pointer to struct
1364 // field.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001365 StructType *ST =
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001366 cast<StructType>(cast<PointerType>(PN->getType())->getElementType());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001367
Jay Foadd8b4fb42011-03-30 11:19:20 +00001368 PHINode *NewPN =
Owen Andersondebcb012009-07-29 22:17:13 +00001369 PHINode::Create(PointerType::getUnqual(ST->getElementType(FieldNo)),
Jay Foad3ecfc862011-03-30 11:28:46 +00001370 PN->getNumIncomingValues(),
Daniel Dunbarfe09b202009-07-30 17:37:43 +00001371 PN->getName()+".f"+Twine(FieldNo), PN);
Jay Foadd8b4fb42011-03-30 11:19:20 +00001372 Result = NewPN;
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001373 PHIsToRewrite.push_back(std::make_pair(PN, FieldNo));
1374 } else {
Torok Edwinc23197a2009-07-14 16:55:14 +00001375 llvm_unreachable("Unknown usable value");
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001376 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001377
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001378 return FieldVals[FieldNo] = Result;
Chris Lattnera637a8b2007-09-13 18:00:31 +00001379}
1380
Chris Lattner330245e2007-09-13 17:29:05 +00001381/// RewriteHeapSROALoadUser - Given a load instruction and a value derived from
1382/// the load, rewrite the derived value to use the HeapSRoA'd load.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001383static void RewriteHeapSROALoadUser(Instruction *LoadUser,
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001384 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001385 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
Chris Lattner330245e2007-09-13 17:29:05 +00001386 // If this is a comparison against null, handle it.
1387 if (ICmpInst *SCI = dyn_cast<ICmpInst>(LoadUser)) {
1388 assert(isa<ConstantPointerNull>(SCI->getOperand(1)));
1389 // If we have a setcc of the loaded pointer, we can use a setcc of any
1390 // field.
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001391 Value *NPtr = GetHeapSROAValue(SCI->getOperand(0), 0,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001392 InsertedScalarizedValues, PHIsToRewrite);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001393
Owen Anderson333c4002009-07-09 23:48:35 +00001394 Value *New = new ICmpInst(SCI, SCI->getPredicate(), NPtr,
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001395 Constant::getNullValue(NPtr->getType()),
Owen Anderson333c4002009-07-09 23:48:35 +00001396 SCI->getName());
Chris Lattner330245e2007-09-13 17:29:05 +00001397 SCI->replaceAllUsesWith(New);
1398 SCI->eraseFromParent();
1399 return;
1400 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001401
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001402 // Handle 'getelementptr Ptr, Idx, i32 FieldNo ...'
Chris Lattnera637a8b2007-09-13 18:00:31 +00001403 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(LoadUser)) {
1404 assert(GEPI->getNumOperands() >= 3 && isa<ConstantInt>(GEPI->getOperand(2))
1405 && "Unexpected GEPI!");
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001406
Chris Lattnera637a8b2007-09-13 18:00:31 +00001407 // Load the pointer for this field.
1408 unsigned FieldNo = cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue();
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001409 Value *NewPtr = GetHeapSROAValue(GEPI->getOperand(0), FieldNo,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001410 InsertedScalarizedValues, PHIsToRewrite);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001411
Chris Lattnera637a8b2007-09-13 18:00:31 +00001412 // Create the new GEP idx vector.
1413 SmallVector<Value*, 8> GEPIdx;
1414 GEPIdx.push_back(GEPI->getOperand(1));
1415 GEPIdx.append(GEPI->op_begin()+3, GEPI->op_end());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001416
Jay Foada9203102011-07-25 09:48:08 +00001417 Value *NGEPI = GetElementPtrInst::Create(NewPtr, GEPIdx,
Gabor Greif051a9502008-04-06 20:25:17 +00001418 GEPI->getName(), GEPI);
Chris Lattnera637a8b2007-09-13 18:00:31 +00001419 GEPI->replaceAllUsesWith(NGEPI);
1420 GEPI->eraseFromParent();
1421 return;
1422 }
Chris Lattner309f20f2007-09-13 21:31:36 +00001423
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001424 // Recursively transform the users of PHI nodes. This will lazily create the
1425 // PHIs that are needed for individual elements. Keep track of what PHIs we
1426 // see in InsertedScalarizedValues so that we don't get infinite loops (very
1427 // antisocial). If the PHI is already in InsertedScalarizedValues, it has
1428 // already been seen first by another load, so its uses have already been
1429 // processed.
1430 PHINode *PN = cast<PHINode>(LoadUser);
Chris Lattnerc30a38f2011-07-21 06:21:31 +00001431 if (!InsertedScalarizedValues.insert(std::make_pair(PN,
1432 std::vector<Value*>())).second)
1433 return;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001434
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001435 // If this is the first time we've seen this PHI, recursively process all
1436 // users.
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001437 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end(); UI != E; ) {
1438 Instruction *User = cast<Instruction>(*UI++);
Chris Lattner7b550cc2009-11-06 04:27:31 +00001439 RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite);
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001440 }
Chris Lattner330245e2007-09-13 17:29:05 +00001441}
1442
Chris Lattner86395032006-09-30 23:32:09 +00001443/// RewriteUsesOfLoadForHeapSRoA - We are performing Heap SRoA on a global. Ptr
1444/// is a value loaded from the global. Eliminate all uses of Ptr, making them
1445/// use FieldGlobals instead. All uses of loaded values satisfy
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001446/// AllGlobalLoadUsesSimpleEnoughForHeapSRA.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001447static void RewriteUsesOfLoadForHeapSRoA(LoadInst *Load,
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001448 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001449 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001450 for (Value::use_iterator UI = Load->use_begin(), E = Load->use_end();
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001451 UI != E; ) {
1452 Instruction *User = cast<Instruction>(*UI++);
Chris Lattner7b550cc2009-11-06 04:27:31 +00001453 RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite);
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001454 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001455
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001456 if (Load->use_empty()) {
1457 Load->eraseFromParent();
1458 InsertedScalarizedValues.erase(Load);
1459 }
Chris Lattner86395032006-09-30 23:32:09 +00001460}
1461
Victor Hernandez83d63912009-09-18 22:35:49 +00001462/// PerformHeapAllocSRoA - CI is an allocation of an array of structures. Break
1463/// it up into multiple allocations of arrays of the fields.
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001464static GlobalVariable *PerformHeapAllocSRoA(GlobalVariable *GV, CallInst *CI,
Nick Lewyckybc384a12012-02-05 19:48:37 +00001465 Value *NElems, TargetData *TD) {
David Greene3215b0e2010-01-05 01:28:05 +00001466 DEBUG(dbgs() << "SROA HEAP ALLOC: " << *GV << " MALLOC = " << *CI << '\n');
Nick Lewyckybc384a12012-02-05 19:48:37 +00001467 Type *MAT = getMallocAllocatedType(CI);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001468 StructType *STy = cast<StructType>(MAT);
Victor Hernandez83d63912009-09-18 22:35:49 +00001469
1470 // There is guaranteed to be at least one use of the malloc (storing
1471 // it into GV). If there are other uses, change them to be uses of
1472 // the global to simplify later code. This also deletes the store
1473 // into GV.
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001474 ReplaceUsesOfMallocWithGlobal(CI, GV);
1475
Victor Hernandez83d63912009-09-18 22:35:49 +00001476 // Okay, at this point, there are no users of the malloc. Insert N
1477 // new mallocs at the same place as CI, and N globals.
1478 std::vector<Value*> FieldGlobals;
1479 std::vector<Value*> FieldMallocs;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001480
Victor Hernandez83d63912009-09-18 22:35:49 +00001481 for (unsigned FieldNo = 0, e = STy->getNumElements(); FieldNo != e;++FieldNo){
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001482 Type *FieldTy = STy->getElementType(FieldNo);
1483 PointerType *PFieldTy = PointerType::getUnqual(FieldTy);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001484
Victor Hernandez83d63912009-09-18 22:35:49 +00001485 GlobalVariable *NGV =
1486 new GlobalVariable(*GV->getParent(),
1487 PFieldTy, false, GlobalValue::InternalLinkage,
1488 Constant::getNullValue(PFieldTy),
1489 GV->getName() + ".f" + Twine(FieldNo), GV,
Hans Wennborgce718ff2012-06-23 11:37:03 +00001490 GV->getThreadLocalMode());
Victor Hernandez83d63912009-09-18 22:35:49 +00001491 FieldGlobals.push_back(NGV);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001492
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001493 unsigned TypeSize = TD->getTypeAllocSize(FieldTy);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001494 if (StructType *ST = dyn_cast<StructType>(FieldTy))
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001495 TypeSize = TD->getStructLayout(ST)->getSizeInBytes();
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001496 Type *IntPtrTy = TD->getIntPtrType(CI->getContext());
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001497 Value *NMI = CallInst::CreateMalloc(CI, IntPtrTy, FieldTy,
1498 ConstantInt::get(IntPtrTy, TypeSize),
Chris Lattner5a30a852010-07-12 00:57:28 +00001499 NElems, 0,
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001500 CI->getName() + ".f" + Twine(FieldNo));
Chris Lattner3f5e0b82010-02-26 18:23:13 +00001501 FieldMallocs.push_back(NMI);
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001502 new StoreInst(NMI, NGV, CI);
Victor Hernandez83d63912009-09-18 22:35:49 +00001503 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001504
Victor Hernandez83d63912009-09-18 22:35:49 +00001505 // The tricky aspect of this transformation is handling the case when malloc
1506 // fails. In the original code, malloc failing would set the result pointer
1507 // of malloc to null. In this case, some mallocs could succeed and others
1508 // could fail. As such, we emit code that looks like this:
1509 // F0 = malloc(field0)
1510 // F1 = malloc(field1)
1511 // F2 = malloc(field2)
1512 // if (F0 == 0 || F1 == 0 || F2 == 0) {
1513 // if (F0) { free(F0); F0 = 0; }
1514 // if (F1) { free(F1); F1 = 0; }
1515 // if (F2) { free(F2); F2 = 0; }
1516 // }
Victor Hernandez8e345a12009-11-10 08:32:25 +00001517 // The malloc can also fail if its argument is too large.
Gabor Greif9e4f2432010-06-24 14:42:01 +00001518 Constant *ConstantZero = ConstantInt::get(CI->getArgOperand(0)->getType(), 0);
1519 Value *RunningOr = new ICmpInst(CI, ICmpInst::ICMP_SLT, CI->getArgOperand(0),
Victor Hernandez8e345a12009-11-10 08:32:25 +00001520 ConstantZero, "isneg");
Victor Hernandez83d63912009-09-18 22:35:49 +00001521 for (unsigned i = 0, e = FieldMallocs.size(); i != e; ++i) {
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001522 Value *Cond = new ICmpInst(CI, ICmpInst::ICMP_EQ, FieldMallocs[i],
1523 Constant::getNullValue(FieldMallocs[i]->getType()),
1524 "isnull");
Victor Hernandez8e345a12009-11-10 08:32:25 +00001525 RunningOr = BinaryOperator::CreateOr(RunningOr, Cond, "tmp", CI);
Victor Hernandez83d63912009-09-18 22:35:49 +00001526 }
1527
1528 // Split the basic block at the old malloc.
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001529 BasicBlock *OrigBB = CI->getParent();
1530 BasicBlock *ContBB = OrigBB->splitBasicBlock(CI, "malloc_cont");
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001531
Victor Hernandez83d63912009-09-18 22:35:49 +00001532 // Create the block to check the first condition. Put all these blocks at the
1533 // end of the function as they are unlikely to be executed.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001534 BasicBlock *NullPtrBlock = BasicBlock::Create(OrigBB->getContext(),
1535 "malloc_ret_null",
Victor Hernandez83d63912009-09-18 22:35:49 +00001536 OrigBB->getParent());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001537
Victor Hernandez83d63912009-09-18 22:35:49 +00001538 // Remove the uncond branch from OrigBB to ContBB, turning it into a cond
1539 // branch on RunningOr.
1540 OrigBB->getTerminator()->eraseFromParent();
1541 BranchInst::Create(NullPtrBlock, ContBB, RunningOr, OrigBB);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001542
Victor Hernandez83d63912009-09-18 22:35:49 +00001543 // Within the NullPtrBlock, we need to emit a comparison and branch for each
1544 // pointer, because some may be null while others are not.
1545 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
1546 Value *GVVal = new LoadInst(FieldGlobals[i], "tmp", NullPtrBlock);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001547 Value *Cmp = new ICmpInst(*NullPtrBlock, ICmpInst::ICMP_NE, GVVal,
Benjamin Kramera9390a42011-09-27 20:39:19 +00001548 Constant::getNullValue(GVVal->getType()));
Chris Lattner7b550cc2009-11-06 04:27:31 +00001549 BasicBlock *FreeBlock = BasicBlock::Create(Cmp->getContext(), "free_it",
Victor Hernandez83d63912009-09-18 22:35:49 +00001550 OrigBB->getParent());
Chris Lattner7b550cc2009-11-06 04:27:31 +00001551 BasicBlock *NextBlock = BasicBlock::Create(Cmp->getContext(), "next",
Victor Hernandez83d63912009-09-18 22:35:49 +00001552 OrigBB->getParent());
Victor Hernandez66284e02009-10-24 04:23:03 +00001553 Instruction *BI = BranchInst::Create(FreeBlock, NextBlock,
1554 Cmp, NullPtrBlock);
Victor Hernandez83d63912009-09-18 22:35:49 +00001555
1556 // Fill in FreeBlock.
Victor Hernandez66284e02009-10-24 04:23:03 +00001557 CallInst::CreateFree(GVVal, BI);
Victor Hernandez83d63912009-09-18 22:35:49 +00001558 new StoreInst(Constant::getNullValue(GVVal->getType()), FieldGlobals[i],
1559 FreeBlock);
1560 BranchInst::Create(NextBlock, FreeBlock);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001561
Victor Hernandez83d63912009-09-18 22:35:49 +00001562 NullPtrBlock = NextBlock;
1563 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001564
Victor Hernandez83d63912009-09-18 22:35:49 +00001565 BranchInst::Create(ContBB, NullPtrBlock);
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001566
1567 // CI is no longer needed, remove it.
Victor Hernandez83d63912009-09-18 22:35:49 +00001568 CI->eraseFromParent();
1569
1570 /// InsertedScalarizedLoads - As we process loads, if we can't immediately
1571 /// update all uses of the load, keep track of what scalarized loads are
1572 /// inserted for a given load.
1573 DenseMap<Value*, std::vector<Value*> > InsertedScalarizedValues;
1574 InsertedScalarizedValues[GV] = FieldGlobals;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001575
Victor Hernandez83d63912009-09-18 22:35:49 +00001576 std::vector<std::pair<PHINode*, unsigned> > PHIsToRewrite;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001577
Victor Hernandez83d63912009-09-18 22:35:49 +00001578 // Okay, the malloc site is completely handled. All of the uses of GV are now
1579 // loads, and all uses of those loads are simple. Rewrite them to use loads
1580 // of the per-field globals instead.
1581 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI != E;) {
1582 Instruction *User = cast<Instruction>(*UI++);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001583
Victor Hernandez83d63912009-09-18 22:35:49 +00001584 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Chris Lattner7b550cc2009-11-06 04:27:31 +00001585 RewriteUsesOfLoadForHeapSRoA(LI, InsertedScalarizedValues, PHIsToRewrite);
Victor Hernandez83d63912009-09-18 22:35:49 +00001586 continue;
1587 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001588
Victor Hernandez83d63912009-09-18 22:35:49 +00001589 // Must be a store of null.
1590 StoreInst *SI = cast<StoreInst>(User);
1591 assert(isa<ConstantPointerNull>(SI->getOperand(0)) &&
1592 "Unexpected heap-sra user!");
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001593
Victor Hernandez83d63912009-09-18 22:35:49 +00001594 // Insert a store of null into each global.
1595 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001596 PointerType *PT = cast<PointerType>(FieldGlobals[i]->getType());
Victor Hernandez83d63912009-09-18 22:35:49 +00001597 Constant *Null = Constant::getNullValue(PT->getElementType());
1598 new StoreInst(Null, FieldGlobals[i], SI);
1599 }
1600 // Erase the original store.
1601 SI->eraseFromParent();
1602 }
1603
1604 // While we have PHIs that are interesting to rewrite, do it.
1605 while (!PHIsToRewrite.empty()) {
1606 PHINode *PN = PHIsToRewrite.back().first;
1607 unsigned FieldNo = PHIsToRewrite.back().second;
1608 PHIsToRewrite.pop_back();
1609 PHINode *FieldPN = cast<PHINode>(InsertedScalarizedValues[PN][FieldNo]);
1610 assert(FieldPN->getNumIncomingValues() == 0 &&"Already processed this phi");
1611
1612 // Add all the incoming values. This can materialize more phis.
1613 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1614 Value *InVal = PN->getIncomingValue(i);
1615 InVal = GetHeapSROAValue(InVal, FieldNo, InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001616 PHIsToRewrite);
Victor Hernandez83d63912009-09-18 22:35:49 +00001617 FieldPN->addIncoming(InVal, PN->getIncomingBlock(i));
1618 }
1619 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001620
Victor Hernandez83d63912009-09-18 22:35:49 +00001621 // Drop all inter-phi links and any loads that made it this far.
1622 for (DenseMap<Value*, std::vector<Value*> >::iterator
1623 I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
1624 I != E; ++I) {
1625 if (PHINode *PN = dyn_cast<PHINode>(I->first))
1626 PN->dropAllReferences();
1627 else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
1628 LI->dropAllReferences();
1629 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001630
Victor Hernandez83d63912009-09-18 22:35:49 +00001631 // Delete all the phis and loads now that inter-references are dead.
1632 for (DenseMap<Value*, std::vector<Value*> >::iterator
1633 I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
1634 I != E; ++I) {
1635 if (PHINode *PN = dyn_cast<PHINode>(I->first))
1636 PN->eraseFromParent();
1637 else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
1638 LI->eraseFromParent();
1639 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001640
Victor Hernandez83d63912009-09-18 22:35:49 +00001641 // The old global is now dead, remove it.
1642 GV->eraseFromParent();
1643
1644 ++NumHeapSRA;
1645 return cast<GlobalVariable>(FieldGlobals[0]);
1646}
1647
Chris Lattnere61d0a62008-12-15 21:02:25 +00001648/// TryToOptimizeStoreOfMallocToGlobal - This function is called when we see a
1649/// pointer global variable with a single value stored it that is a malloc or
1650/// cast of malloc.
1651static bool TryToOptimizeStoreOfMallocToGlobal(GlobalVariable *GV,
Victor Hernandez83d63912009-09-18 22:35:49 +00001652 CallInst *CI,
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001653 Type *AllocTy,
Nick Lewyckyfad4d402012-02-05 19:56:38 +00001654 AtomicOrdering Ordering,
Victor Hernandez83d63912009-09-18 22:35:49 +00001655 Module::global_iterator &GVI,
Nick Lewycky6a577f82012-02-12 01:13:18 +00001656 TargetData *TD,
1657 TargetLibraryInfo *TLI) {
Evan Cheng86cd4452010-04-14 20:52:55 +00001658 if (!TD)
1659 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001660
Victor Hernandez83d63912009-09-18 22:35:49 +00001661 // If this is a malloc of an abstract type, don't touch it.
1662 if (!AllocTy->isSized())
1663 return false;
1664
1665 // We can't optimize this global unless all uses of it are *known* to be
1666 // of the malloc value, not of the null initializer value (consider a use
1667 // that compares the global's value against zero to see if the malloc has
1668 // been reached). To do this, we check to see if all uses of the global
1669 // would trap if the global were null: this proves that they must all
1670 // happen after the malloc.
1671 if (!AllUsesOfLoadedValueWillTrapIfNull(GV))
1672 return false;
1673
1674 // We can't optimize this if the malloc itself is used in a complex way,
1675 // for example, being stored into multiple globals. This allows the
Nick Lewyckybc384a12012-02-05 19:48:37 +00001676 // malloc to be stored into the specified global, loaded icmp'd, and
Victor Hernandez83d63912009-09-18 22:35:49 +00001677 // GEP'd. These are all things we could transform to using the global
1678 // for.
Evan Cheng86cd4452010-04-14 20:52:55 +00001679 SmallPtrSet<const PHINode*, 8> PHIs;
1680 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(CI, GV, PHIs))
1681 return false;
Victor Hernandez83d63912009-09-18 22:35:49 +00001682
1683 // If we have a global that is only initialized with a fixed size malloc,
1684 // transform the program to use global memory instead of malloc'd memory.
1685 // This eliminates dynamic allocation, avoids an indirection accessing the
1686 // data, and exposes the resultant global to further GlobalOpt.
Victor Hernandez8db42d22009-10-16 23:12:25 +00001687 // We cannot optimize the malloc if we cannot determine malloc array size.
Evan Cheng86cd4452010-04-14 20:52:55 +00001688 Value *NElems = getMallocArraySize(CI, TD, true);
1689 if (!NElems)
1690 return false;
Victor Hernandez83d63912009-09-18 22:35:49 +00001691
Evan Cheng86cd4452010-04-14 20:52:55 +00001692 if (ConstantInt *NElements = dyn_cast<ConstantInt>(NElems))
1693 // Restrict this transformation to only working on small allocations
1694 // (2048 bytes currently), as we don't want to introduce a 16M global or
1695 // something.
1696 if (NElements->getZExtValue() * TD->getTypeAllocSize(AllocTy) < 2048) {
Nick Lewycky6a577f82012-02-12 01:13:18 +00001697 GVI = OptimizeGlobalAddressOfMalloc(GV, CI, AllocTy, NElements, TD, TLI);
Evan Cheng86cd4452010-04-14 20:52:55 +00001698 return true;
Victor Hernandez83d63912009-09-18 22:35:49 +00001699 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001700
Evan Cheng86cd4452010-04-14 20:52:55 +00001701 // If the allocation is an array of structures, consider transforming this
1702 // into multiple malloc'd arrays, one for each field. This is basically
1703 // SRoA for malloc'd memory.
1704
Nick Lewyckyfad4d402012-02-05 19:56:38 +00001705 if (Ordering != NotAtomic)
1706 return false;
1707
Evan Cheng86cd4452010-04-14 20:52:55 +00001708 // If this is an allocation of a fixed size array of structs, analyze as a
1709 // variable size array. malloc [100 x struct],1 -> malloc struct, 100
Gabor Greif9e4f2432010-06-24 14:42:01 +00001710 if (NElems == ConstantInt::get(CI->getArgOperand(0)->getType(), 1))
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001711 if (ArrayType *AT = dyn_cast<ArrayType>(AllocTy))
Evan Cheng86cd4452010-04-14 20:52:55 +00001712 AllocTy = AT->getElementType();
Gabor Greif9e4f2432010-06-24 14:42:01 +00001713
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001714 StructType *AllocSTy = dyn_cast<StructType>(AllocTy);
Evan Cheng86cd4452010-04-14 20:52:55 +00001715 if (!AllocSTy)
1716 return false;
1717
1718 // This the structure has an unreasonable number of fields, leave it
1719 // alone.
1720 if (AllocSTy->getNumElements() <= 16 && AllocSTy->getNumElements() != 0 &&
1721 AllGlobalLoadUsesSimpleEnoughForHeapSRA(GV, CI)) {
1722
1723 // If this is a fixed size array, transform the Malloc to be an alloc of
1724 // structs. malloc [100 x struct],1 -> malloc struct, 100
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001725 if (ArrayType *AT = dyn_cast<ArrayType>(getMallocAllocatedType(CI))) {
1726 Type *IntPtrTy = TD->getIntPtrType(CI->getContext());
Evan Cheng86cd4452010-04-14 20:52:55 +00001727 unsigned TypeSize = TD->getStructLayout(AllocSTy)->getSizeInBytes();
1728 Value *AllocSize = ConstantInt::get(IntPtrTy, TypeSize);
1729 Value *NumElements = ConstantInt::get(IntPtrTy, AT->getNumElements());
1730 Instruction *Malloc = CallInst::CreateMalloc(CI, IntPtrTy, AllocSTy,
1731 AllocSize, NumElements,
Chris Lattner5a30a852010-07-12 00:57:28 +00001732 0, CI->getName());
Evan Cheng86cd4452010-04-14 20:52:55 +00001733 Instruction *Cast = new BitCastInst(Malloc, CI->getType(), "tmp", CI);
1734 CI->replaceAllUsesWith(Cast);
1735 CI->eraseFromParent();
Nuno Lopeseb7c6862012-06-22 00:25:01 +00001736 if (BitCastInst *BCI = dyn_cast<BitCastInst>(Malloc))
1737 CI = cast<CallInst>(BCI->getOperand(0));
1738 else
Nuno Lopescd88efe2012-06-22 00:29:58 +00001739 CI = cast<CallInst>(Malloc);
Evan Cheng86cd4452010-04-14 20:52:55 +00001740 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001741
Nick Lewyckybc384a12012-02-05 19:48:37 +00001742 GVI = PerformHeapAllocSRoA(GV, CI, getMallocArraySize(CI, TD, true), TD);
Evan Cheng86cd4452010-04-14 20:52:55 +00001743 return true;
Victor Hernandez83d63912009-09-18 22:35:49 +00001744 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001745
Victor Hernandez83d63912009-09-18 22:35:49 +00001746 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001747}
Victor Hernandez83d63912009-09-18 22:35:49 +00001748
Chris Lattner9b34a612004-10-09 21:48:45 +00001749// OptimizeOnceStoredGlobal - Try to optimize globals based on the knowledge
1750// that only one value (besides its initializer) is ever stored to the global.
Chris Lattner30ba5692004-10-11 05:54:41 +00001751static bool OptimizeOnceStoredGlobal(GlobalVariable *GV, Value *StoredOnceVal,
Nick Lewyckyfad4d402012-02-05 19:56:38 +00001752 AtomicOrdering Ordering,
Chris Lattner7f8897f2006-08-27 22:42:52 +00001753 Module::global_iterator &GVI,
Nick Lewycky6a577f82012-02-12 01:13:18 +00001754 TargetData *TD, TargetLibraryInfo *TLI) {
Chris Lattner344b41c2008-12-15 21:20:32 +00001755 // Ignore no-op GEPs and bitcasts.
1756 StoredOnceVal = StoredOnceVal->stripPointerCasts();
Chris Lattner9b34a612004-10-09 21:48:45 +00001757
Chris Lattner708148e2004-10-10 23:14:11 +00001758 // If we are dealing with a pointer global that is initialized to null and
1759 // only has one (non-null) value stored into it, then we can optimize any
1760 // users of the loaded value (often calls and loads) that would trap if the
1761 // value was null.
Duncan Sands1df98592010-02-16 11:11:14 +00001762 if (GV->getInitializer()->getType()->isPointerTy() &&
Chris Lattner9b34a612004-10-09 21:48:45 +00001763 GV->getInitializer()->isNullValue()) {
Chris Lattner708148e2004-10-10 23:14:11 +00001764 if (Constant *SOVC = dyn_cast<Constant>(StoredOnceVal)) {
1765 if (GV->getInitializer()->getType() != SOVC->getType())
Chris Lattner98a42b22011-05-22 07:15:13 +00001766 SOVC = ConstantExpr::getBitCast(SOVC, GV->getInitializer()->getType());
Misha Brukmanfd939082005-04-21 23:48:37 +00001767
Chris Lattner708148e2004-10-10 23:14:11 +00001768 // Optimize away any trapping uses of the loaded value.
Nick Lewycky6a577f82012-02-12 01:13:18 +00001769 if (OptimizeAwayTrappingUsesOfLoads(GV, SOVC, TD, TLI))
Chris Lattner8be80122004-10-10 17:07:12 +00001770 return true;
Victor Hernandez83d63912009-09-18 22:35:49 +00001771 } else if (CallInst *CI = extractMallocCall(StoredOnceVal)) {
Nick Lewyckybc384a12012-02-05 19:48:37 +00001772 Type *MallocType = getMallocAllocatedType(CI);
Nick Lewycky6a577f82012-02-12 01:13:18 +00001773 if (MallocType &&
1774 TryToOptimizeStoreOfMallocToGlobal(GV, CI, MallocType, Ordering, GVI,
1775 TD, TLI))
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001776 return true;
Chris Lattner708148e2004-10-10 23:14:11 +00001777 }
Chris Lattner9b34a612004-10-09 21:48:45 +00001778 }
Chris Lattner30ba5692004-10-11 05:54:41 +00001779
Chris Lattner9b34a612004-10-09 21:48:45 +00001780 return false;
1781}
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001782
Chris Lattner58e44f42008-01-14 01:17:44 +00001783/// TryToShrinkGlobalToBoolean - At this point, we have learned that the only
1784/// two values ever stored into GV are its initializer and OtherVal. See if we
1785/// can shrink the global into a boolean and select between the two values
1786/// whenever it is used. This exposes the values to other scalar optimizations.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001787static bool TryToShrinkGlobalToBoolean(GlobalVariable *GV, Constant *OtherVal) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001788 Type *GVElType = GV->getType()->getElementType();
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001789
Chris Lattner58e44f42008-01-14 01:17:44 +00001790 // If GVElType is already i1, it is already shrunk. If the type of the GV is
Chris Lattner6f6923f2009-03-07 23:32:02 +00001791 // an FP value, pointer or vector, don't do this optimization because a select
1792 // between them is very expensive and unlikely to lead to later
1793 // simplification. In these cases, we typically end up with "cond ? v1 : v2"
1794 // where v1 and v2 both require constant pool loads, a big loss.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001795 if (GVElType == Type::getInt1Ty(GV->getContext()) ||
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001796 GVElType->isFloatingPointTy() ||
Duncan Sands1df98592010-02-16 11:11:14 +00001797 GVElType->isPointerTy() || GVElType->isVectorTy())
Chris Lattner58e44f42008-01-14 01:17:44 +00001798 return false;
Gabor Greifaaaaa022010-07-12 14:13:15 +00001799
Chris Lattner58e44f42008-01-14 01:17:44 +00001800 // Walk the use list of the global seeing if all the uses are load or store.
1801 // If there is anything else, bail out.
Gabor Greifaaaaa022010-07-12 14:13:15 +00001802 for (Value::use_iterator I = GV->use_begin(), E = GV->use_end(); I != E; ++I){
1803 User *U = *I;
1804 if (!isa<LoadInst>(U) && !isa<StoreInst>(U))
Chris Lattner58e44f42008-01-14 01:17:44 +00001805 return false;
Gabor Greifaaaaa022010-07-12 14:13:15 +00001806 }
1807
David Greene3215b0e2010-01-05 01:28:05 +00001808 DEBUG(dbgs() << " *** SHRINKING TO BOOL: " << *GV);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001809
Chris Lattner96a86b22004-12-12 05:53:50 +00001810 // Create the new global, initializing it to false.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001811 GlobalVariable *NewGV = new GlobalVariable(Type::getInt1Ty(GV->getContext()),
1812 false,
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001813 GlobalValue::InternalLinkage,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001814 ConstantInt::getFalse(GV->getContext()),
Nick Lewycky0e670df2009-05-03 03:49:08 +00001815 GV->getName()+".b",
Hans Wennborgce718ff2012-06-23 11:37:03 +00001816 GV->getThreadLocalMode());
Chris Lattner96a86b22004-12-12 05:53:50 +00001817 GV->getParent()->getGlobalList().insert(GV, NewGV);
1818
1819 Constant *InitVal = GV->getInitializer();
Chris Lattner7b550cc2009-11-06 04:27:31 +00001820 assert(InitVal->getType() != Type::getInt1Ty(GV->getContext()) &&
Owen Anderson1d0be152009-08-13 21:58:54 +00001821 "No reason to shrink to bool!");
Chris Lattner96a86b22004-12-12 05:53:50 +00001822
1823 // If initialized to zero and storing one into the global, we can use a cast
1824 // instead of a select to synthesize the desired value.
1825 bool IsOneZero = false;
1826 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal))
Reid Spencercae57542007-03-02 00:28:52 +00001827 IsOneZero = InitVal->isNullValue() && CI->isOne();
Chris Lattner96a86b22004-12-12 05:53:50 +00001828
1829 while (!GV->use_empty()) {
Devang Patel771281f2009-03-06 01:39:36 +00001830 Instruction *UI = cast<Instruction>(GV->use_back());
1831 if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
Chris Lattner96a86b22004-12-12 05:53:50 +00001832 // Change the store into a boolean store.
1833 bool StoringOther = SI->getOperand(0) == OtherVal;
1834 // Only do this if we weren't storing a loaded value.
Chris Lattner38c25562004-12-12 19:34:41 +00001835 Value *StoreVal;
Chris Lattner96a86b22004-12-12 05:53:50 +00001836 if (StoringOther || SI->getOperand(0) == InitVal)
Chris Lattner7b550cc2009-11-06 04:27:31 +00001837 StoreVal = ConstantInt::get(Type::getInt1Ty(GV->getContext()),
1838 StoringOther);
Chris Lattner38c25562004-12-12 19:34:41 +00001839 else {
1840 // Otherwise, we are storing a previously loaded copy. To do this,
1841 // change the copy from copying the original value to just copying the
1842 // bool.
1843 Instruction *StoredVal = cast<Instruction>(SI->getOperand(0));
1844
Gabor Greif9e4f2432010-06-24 14:42:01 +00001845 // If we've already replaced the input, StoredVal will be a cast or
Chris Lattner38c25562004-12-12 19:34:41 +00001846 // select instruction. If not, it will be a load of the original
1847 // global.
1848 if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
1849 assert(LI->getOperand(0) == GV && "Not a copy!");
1850 // Insert a new load, to preserve the saved value.
Nick Lewyckyfad4d402012-02-05 19:56:38 +00001851 StoreVal = new LoadInst(NewGV, LI->getName()+".b", false, 0,
1852 LI->getOrdering(), LI->getSynchScope(), LI);
Chris Lattner38c25562004-12-12 19:34:41 +00001853 } else {
1854 assert((isa<CastInst>(StoredVal) || isa<SelectInst>(StoredVal)) &&
1855 "This is not a form that we understand!");
1856 StoreVal = StoredVal->getOperand(0);
1857 assert(isa<LoadInst>(StoreVal) && "Not a load of NewGV!");
1858 }
1859 }
Nick Lewyckyfad4d402012-02-05 19:56:38 +00001860 new StoreInst(StoreVal, NewGV, false, 0,
1861 SI->getOrdering(), SI->getSynchScope(), SI);
Devang Patel771281f2009-03-06 01:39:36 +00001862 } else {
Chris Lattner96a86b22004-12-12 05:53:50 +00001863 // Change the load into a load of bool then a select.
Devang Patel771281f2009-03-06 01:39:36 +00001864 LoadInst *LI = cast<LoadInst>(UI);
Nick Lewyckyfad4d402012-02-05 19:56:38 +00001865 LoadInst *NLI = new LoadInst(NewGV, LI->getName()+".b", false, 0,
1866 LI->getOrdering(), LI->getSynchScope(), LI);
Chris Lattner96a86b22004-12-12 05:53:50 +00001867 Value *NSI;
1868 if (IsOneZero)
Chris Lattner046800a2007-02-11 01:08:35 +00001869 NSI = new ZExtInst(NLI, LI->getType(), "", LI);
Misha Brukmanfd939082005-04-21 23:48:37 +00001870 else
Gabor Greif051a9502008-04-06 20:25:17 +00001871 NSI = SelectInst::Create(NLI, OtherVal, InitVal, "", LI);
Chris Lattner046800a2007-02-11 01:08:35 +00001872 NSI->takeName(LI);
Chris Lattner96a86b22004-12-12 05:53:50 +00001873 LI->replaceAllUsesWith(NSI);
Devang Patel771281f2009-03-06 01:39:36 +00001874 }
1875 UI->eraseFromParent();
Chris Lattner96a86b22004-12-12 05:53:50 +00001876 }
1877
1878 GV->eraseFromParent();
Chris Lattner58e44f42008-01-14 01:17:44 +00001879 return true;
Chris Lattner96a86b22004-12-12 05:53:50 +00001880}
1881
1882
Nick Lewyckydb292a62012-02-12 00:52:26 +00001883/// ProcessGlobal - Analyze the specified global variable and optimize it if
1884/// possible. If we make a change, return true.
Rafael Espindolac4440e32011-01-19 16:32:21 +00001885bool GlobalOpt::ProcessGlobal(GlobalVariable *GV,
1886 Module::global_iterator &GVI) {
Rafael Espindola03977292012-06-14 22:48:13 +00001887 if (!GV->isDiscardableIfUnused())
Rafael Espindolac4440e32011-01-19 16:32:21 +00001888 return false;
1889
1890 // Do more involved optimizations if the global is internal.
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001891 GV->removeDeadConstantUsers();
1892
1893 if (GV->use_empty()) {
David Greene3215b0e2010-01-05 01:28:05 +00001894 DEBUG(dbgs() << "GLOBAL DEAD: " << *GV);
Chris Lattner7a7ed022004-10-16 18:09:00 +00001895 GV->eraseFromParent();
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001896 ++NumDeleted;
1897 return true;
1898 }
1899
Rafael Espindola2f135d42012-06-15 18:00:24 +00001900 if (!GV->hasLocalLinkage())
1901 return false;
1902
Rafael Espindolac4440e32011-01-19 16:32:21 +00001903 SmallPtrSet<const PHINode*, 16> PHIUsers;
1904 GlobalStatus GS;
1905
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001906 if (AnalyzeGlobal(GV, GS, PHIUsers))
1907 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001908
Rafael Espindolac4440e32011-01-19 16:32:21 +00001909 if (!GS.isCompared && !GV->hasUnnamedAddr()) {
1910 GV->setUnnamedAddr(true);
1911 NumUnnamed++;
1912 }
1913
1914 if (GV->isConstant() || !GV->hasInitializer())
1915 return false;
1916
1917 return ProcessInternalGlobal(GV, GVI, PHIUsers, GS);
1918}
1919
1920/// ProcessInternalGlobal - Analyze the specified global variable and optimize
1921/// it if possible. If we make a change, return true.
1922bool GlobalOpt::ProcessInternalGlobal(GlobalVariable *GV,
1923 Module::global_iterator &GVI,
Nick Lewyckydb292a62012-02-12 00:52:26 +00001924 const SmallPtrSet<const PHINode*, 16> &PHIUsers,
Rafael Espindolac4440e32011-01-19 16:32:21 +00001925 const GlobalStatus &GS) {
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001926 // If this is a first class global and has only one accessing function
1927 // and this function is main (which we know is not recursive we can make
1928 // this global a local variable) we replace the global with a local alloca
1929 // in this function.
1930 //
1931 // NOTE: It doesn't make sense to promote non single-value types since we
1932 // are just replacing static memory to stack memory.
1933 //
1934 // If the global is in different address space, don't bring it to stack.
1935 if (!GS.HasMultipleAccessingFunctions &&
1936 GS.AccessingFunction && !GS.HasNonInstructionUser &&
1937 GV->getType()->getElementType()->isSingleValueType() &&
1938 GS.AccessingFunction->getName() == "main" &&
1939 GS.AccessingFunction->hasExternalLinkage() &&
1940 GV->getType()->getAddressSpace() == 0) {
1941 DEBUG(dbgs() << "LOCALIZING GLOBAL: " << *GV);
Nick Lewyckybc384a12012-02-05 19:48:37 +00001942 Instruction &FirstI = const_cast<Instruction&>(*GS.AccessingFunction
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001943 ->getEntryBlock().begin());
Nick Lewyckybc384a12012-02-05 19:48:37 +00001944 Type *ElemTy = GV->getType()->getElementType();
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001945 // FIXME: Pass Global's alignment when globals have alignment
Nick Lewyckybc384a12012-02-05 19:48:37 +00001946 AllocaInst *Alloca = new AllocaInst(ElemTy, NULL, GV->getName(), &FirstI);
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001947 if (!isa<UndefValue>(GV->getInitializer()))
1948 new StoreInst(GV->getInitializer(), Alloca, &FirstI);
Misha Brukmanfd939082005-04-21 23:48:37 +00001949
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001950 GV->replaceAllUsesWith(Alloca);
1951 GV->eraseFromParent();
1952 ++NumLocalized;
1953 return true;
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001954 }
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001955
1956 // If the global is never loaded (but may be stored to), it is dead.
1957 // Delete it now.
1958 if (!GS.isLoaded) {
1959 DEBUG(dbgs() << "GLOBAL NEVER LOADED: " << *GV);
1960
Nick Lewycky8899d5c2012-07-24 07:21:08 +00001961 bool Changed;
1962 if (isLeakCheckerRoot(GV)) {
1963 // Delete any constant stores to the global.
1964 Changed = CleanupPointerRootUsers(GV);
1965 } else {
1966 // Delete any stores we can find to the global. We may not be able to
1967 // make it completely dead though.
1968 Changed = CleanupConstantGlobalUsers(GV, GV->getInitializer(), TD, TLI);
1969 }
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001970
1971 // If the global is dead now, delete it.
1972 if (GV->use_empty()) {
1973 GV->eraseFromParent();
1974 ++NumDeleted;
1975 Changed = true;
1976 }
1977 return Changed;
1978
1979 } else if (GS.StoredType <= GlobalStatus::isInitializerStored) {
1980 DEBUG(dbgs() << "MARKING CONSTANT: " << *GV);
1981 GV->setConstant(true);
1982
1983 // Clean up any obviously simplifiable users now.
Nick Lewycky6a577f82012-02-12 01:13:18 +00001984 CleanupConstantGlobalUsers(GV, GV->getInitializer(), TD, TLI);
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001985
1986 // If the global is dead now, just nuke it.
1987 if (GV->use_empty()) {
1988 DEBUG(dbgs() << " *** Marking constant allowed us to simplify "
1989 << "all users and delete global!\n");
1990 GV->eraseFromParent();
1991 ++NumDeleted;
1992 }
1993
1994 ++NumMarked;
1995 return true;
1996 } else if (!GV->getInitializer()->getType()->isSingleValueType()) {
1997 if (TargetData *TD = getAnalysisIfAvailable<TargetData>())
1998 if (GlobalVariable *FirstNewGV = SRAGlobal(GV, *TD)) {
1999 GVI = FirstNewGV; // Don't skip the newly produced globals!
2000 return true;
2001 }
2002 } else if (GS.StoredType == GlobalStatus::isStoredOnce) {
2003 // If the initial value for the global was an undef value, and if only
2004 // one other value was stored into it, we can just change the
2005 // initializer to be the stored value, then delete all stores to the
2006 // global. This allows us to mark it constant.
2007 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
2008 if (isa<UndefValue>(GV->getInitializer())) {
2009 // Change the initial value here.
2010 GV->setInitializer(SOVConstant);
2011
2012 // Clean up any obviously simplifiable users now.
Nick Lewycky6a577f82012-02-12 01:13:18 +00002013 CleanupConstantGlobalUsers(GV, GV->getInitializer(), TD, TLI);
Rafael Espindoladaad56a2011-01-18 04:36:06 +00002014
2015 if (GV->use_empty()) {
2016 DEBUG(dbgs() << " *** Substituting initializer allowed us to "
Nick Lewycky8899d5c2012-07-24 07:21:08 +00002017 << "simplify all users and delete global!\n");
Rafael Espindoladaad56a2011-01-18 04:36:06 +00002018 GV->eraseFromParent();
2019 ++NumDeleted;
2020 } else {
2021 GVI = GV;
2022 }
2023 ++NumSubstitute;
2024 return true;
2025 }
2026
2027 // Try to optimize globals based on the knowledge that only one value
2028 // (besides its initializer) is ever stored to the global.
Nick Lewyckyfad4d402012-02-05 19:56:38 +00002029 if (OptimizeOnceStoredGlobal(GV, GS.StoredOnceValue, GS.Ordering, GVI,
Nick Lewycky6a577f82012-02-12 01:13:18 +00002030 TD, TLI))
Rafael Espindoladaad56a2011-01-18 04:36:06 +00002031 return true;
2032
2033 // Otherwise, if the global was not a boolean, we can shrink it to be a
2034 // boolean.
2035 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
2036 if (TryToShrinkGlobalToBoolean(GV, SOVConstant)) {
2037 ++NumShrunkToBool;
2038 return true;
2039 }
2040 }
2041
Chris Lattnera4be1dc2004-10-08 20:59:28 +00002042 return false;
2043}
2044
Chris Lattnerfb217ad2005-05-08 22:18:06 +00002045/// ChangeCalleesToFastCall - Walk all of the direct calls of the specified
2046/// function, changing them to FastCC.
2047static void ChangeCalleesToFastCall(Function *F) {
2048 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
Jay Foadb7454fd2012-05-12 08:30:16 +00002049 if (isa<BlockAddress>(*UI))
2050 continue;
Duncan Sands548448a2008-02-18 17:32:13 +00002051 CallSite User(cast<Instruction>(*UI));
2052 User.setCallingConv(CallingConv::Fast);
Chris Lattnerfb217ad2005-05-08 22:18:06 +00002053 }
2054}
Chris Lattnera4be1dc2004-10-08 20:59:28 +00002055
Devang Patel05988662008-09-25 21:00:45 +00002056static AttrListPtr StripNest(const AttrListPtr &Attrs) {
Chris Lattner58d74912008-03-12 17:45:29 +00002057 for (unsigned i = 0, e = Attrs.getNumSlots(); i != e; ++i) {
Devang Patel05988662008-09-25 21:00:45 +00002058 if ((Attrs.getSlot(i).Attrs & Attribute::Nest) == 0)
Duncan Sands548448a2008-02-18 17:32:13 +00002059 continue;
2060
Duncan Sands548448a2008-02-18 17:32:13 +00002061 // There can be only one.
Devang Patel05988662008-09-25 21:00:45 +00002062 return Attrs.removeAttr(Attrs.getSlot(i).Index, Attribute::Nest);
Duncan Sands3d5378f2008-02-16 20:56:04 +00002063 }
2064
2065 return Attrs;
2066}
2067
2068static void RemoveNestAttribute(Function *F) {
Devang Patel05988662008-09-25 21:00:45 +00002069 F->setAttributes(StripNest(F->getAttributes()));
Duncan Sands3d5378f2008-02-16 20:56:04 +00002070 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
Jay Foadb7454fd2012-05-12 08:30:16 +00002071 if (isa<BlockAddress>(*UI))
2072 continue;
Duncan Sands548448a2008-02-18 17:32:13 +00002073 CallSite User(cast<Instruction>(*UI));
Devang Patel05988662008-09-25 21:00:45 +00002074 User.setAttributes(StripNest(User.getAttributes()));
Duncan Sands3d5378f2008-02-16 20:56:04 +00002075 }
2076}
2077
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002078bool GlobalOpt::OptimizeFunctions(Module &M) {
2079 bool Changed = false;
2080 // Optimize functions.
2081 for (Module::iterator FI = M.begin(), E = M.end(); FI != E; ) {
2082 Function *F = FI++;
Duncan Sandsfc5940d2009-03-06 10:21:56 +00002083 // Functions without names cannot be referenced outside this module.
2084 if (!F->hasName() && !F->isDeclaration())
2085 F->setLinkage(GlobalValue::InternalLinkage);
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002086 F->removeDeadConstantUsers();
Eli Friedmanc6633052011-10-20 05:23:42 +00002087 if (F->isDefTriviallyDead()) {
Chris Lattnerec4c7b92009-11-01 19:03:42 +00002088 F->eraseFromParent();
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002089 Changed = true;
2090 ++NumFnDeleted;
Rafael Espindolabb46f522009-01-15 20:18:42 +00002091 } else if (F->hasLocalLinkage()) {
Duncan Sands3d5378f2008-02-16 20:56:04 +00002092 if (F->getCallingConv() == CallingConv::C && !F->isVarArg() &&
Jay Foad757068f2009-06-10 08:41:11 +00002093 !F->hasAddressTaken()) {
Duncan Sands3d5378f2008-02-16 20:56:04 +00002094 // If this function has C calling conventions, is not a varargs
2095 // function, and is only called directly, promote it to use the Fast
2096 // calling convention.
2097 F->setCallingConv(CallingConv::Fast);
2098 ChangeCalleesToFastCall(F);
2099 ++NumFastCallFns;
2100 Changed = true;
2101 }
2102
Devang Patel05988662008-09-25 21:00:45 +00002103 if (F->getAttributes().hasAttrSomewhere(Attribute::Nest) &&
Jay Foad757068f2009-06-10 08:41:11 +00002104 !F->hasAddressTaken()) {
Duncan Sands3d5378f2008-02-16 20:56:04 +00002105 // The function is not used by a trampoline intrinsic, so it is safe
2106 // to remove the 'nest' attribute.
2107 RemoveNestAttribute(F);
2108 ++NumNestRemoved;
2109 Changed = true;
2110 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002111 }
2112 }
2113 return Changed;
2114}
2115
2116bool GlobalOpt::OptimizeGlobalVars(Module &M) {
2117 bool Changed = false;
2118 for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
2119 GVI != E; ) {
2120 GlobalVariable *GV = GVI++;
Duncan Sandsfc5940d2009-03-06 10:21:56 +00002121 // Global variables without names cannot be referenced outside this module.
2122 if (!GV->hasName() && !GV->isDeclaration())
2123 GV->setLinkage(GlobalValue::InternalLinkage);
Dan Gohman01b97dd2009-11-23 16:22:21 +00002124 // Simplify the initializer.
2125 if (GV->hasInitializer())
2126 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GV->getInitializer())) {
Chad Rosieraab8e282011-12-02 01:26:24 +00002127 Constant *New = ConstantFoldConstantExpression(CE, TD, TLI);
Dan Gohman01b97dd2009-11-23 16:22:21 +00002128 if (New && New != CE)
2129 GV->setInitializer(New);
2130 }
Rafael Espindolac4440e32011-01-19 16:32:21 +00002131
2132 Changed |= ProcessGlobal(GV, GVI);
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002133 }
2134 return Changed;
2135}
2136
Nick Lewycky2c44a802011-04-08 07:30:21 +00002137/// FindGlobalCtors - Find the llvm.global_ctors list, verifying that all
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002138/// initializers have an init priority of 65535.
2139GlobalVariable *GlobalOpt::FindGlobalCtors(Module &M) {
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00002140 GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
2141 if (GV == 0) return 0;
2142
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00002143 // Verify that the initializer is simple enough for us to handle. We are
2144 // only allowed to optimize the initializer if it is unique.
2145 if (!GV->hasUniqueInitializer()) return 0;
Nick Lewycky5ea5c612011-04-11 22:11:20 +00002146
2147 if (isa<ConstantAggregateZero>(GV->getInitializer()))
2148 return GV;
2149 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
Eli Friedman18a2e502011-04-09 09:11:09 +00002150
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00002151 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i) {
Nick Lewycky5ea5c612011-04-11 22:11:20 +00002152 if (isa<ConstantAggregateZero>(*i))
2153 continue;
2154 ConstantStruct *CS = cast<ConstantStruct>(*i);
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00002155 if (isa<ConstantPointerNull>(CS->getOperand(1)))
2156 continue;
Chris Lattner7d8e58f2005-09-26 02:19:27 +00002157
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00002158 // Must have a function or null ptr.
2159 if (!isa<Function>(CS->getOperand(1)))
2160 return 0;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002161
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00002162 // Init priority must be standard.
Nick Lewycky2c44a802011-04-08 07:30:21 +00002163 ConstantInt *CI = cast<ConstantInt>(CS->getOperand(0));
2164 if (CI->getZExtValue() != 65535)
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00002165 return 0;
2166 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002167
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00002168 return GV;
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002169}
2170
Chris Lattnerdb973e62005-09-26 02:31:18 +00002171/// ParseGlobalCtors - Given a llvm.global_ctors list that we can understand,
2172/// return a list of the functions and null terminator as a vector.
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002173static std::vector<Function*> ParseGlobalCtors(GlobalVariable *GV) {
Nick Lewycky5ea5c612011-04-11 22:11:20 +00002174 if (GV->getInitializer()->isNullValue())
2175 return std::vector<Function*>();
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002176 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
2177 std::vector<Function*> Result;
2178 Result.reserve(CA->getNumOperands());
Gabor Greif5e463212008-05-29 01:59:18 +00002179 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i) {
2180 ConstantStruct *CS = cast<ConstantStruct>(*i);
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002181 Result.push_back(dyn_cast<Function>(CS->getOperand(1)));
2182 }
2183 return Result;
2184}
2185
Chris Lattnerdb973e62005-09-26 02:31:18 +00002186/// InstallGlobalCtors - Given a specified llvm.global_ctors list, install the
2187/// specified array, returning the new global to use.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002188static GlobalVariable *InstallGlobalCtors(GlobalVariable *GCL,
Chris Lattner7b550cc2009-11-06 04:27:31 +00002189 const std::vector<Function*> &Ctors) {
Chris Lattnerdb973e62005-09-26 02:31:18 +00002190 // If we made a change, reassemble the initializer list.
Chris Lattnerb065b062011-06-20 04:01:31 +00002191 Constant *CSVals[2];
2192 CSVals[0] = ConstantInt::get(Type::getInt32Ty(GCL->getContext()), 65535);
2193 CSVals[1] = 0;
2194
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002195 StructType *StructTy =
Chris Lattnerb065b062011-06-20 04:01:31 +00002196 cast <StructType>(
2197 cast<ArrayType>(GCL->getType()->getElementType())->getElementType());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002198
Chris Lattnerdb973e62005-09-26 02:31:18 +00002199 // Create the new init list.
2200 std::vector<Constant*> CAList;
2201 for (unsigned i = 0, e = Ctors.size(); i != e; ++i) {
Chris Lattner79c11012005-09-26 04:44:35 +00002202 if (Ctors[i]) {
Chris Lattnerdb973e62005-09-26 02:31:18 +00002203 CSVals[1] = Ctors[i];
Chris Lattner79c11012005-09-26 04:44:35 +00002204 } else {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002205 Type *FTy = FunctionType::get(Type::getVoidTy(GCL->getContext()),
Chris Lattner7b550cc2009-11-06 04:27:31 +00002206 false);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002207 PointerType *PFTy = PointerType::getUnqual(FTy);
Owen Andersona7235ea2009-07-31 20:28:14 +00002208 CSVals[1] = Constant::getNullValue(PFTy);
Chris Lattner7b550cc2009-11-06 04:27:31 +00002209 CSVals[0] = ConstantInt::get(Type::getInt32Ty(GCL->getContext()),
Nick Lewycky5ea5c612011-04-11 22:11:20 +00002210 0x7fffffff);
Chris Lattnerdb973e62005-09-26 02:31:18 +00002211 }
Chris Lattnerb065b062011-06-20 04:01:31 +00002212 CAList.push_back(ConstantStruct::get(StructTy, CSVals));
Chris Lattnerdb973e62005-09-26 02:31:18 +00002213 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002214
Chris Lattnerdb973e62005-09-26 02:31:18 +00002215 // Create the array initializer.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002216 Constant *CA = ConstantArray::get(ArrayType::get(StructTy,
Nick Lewyckyc332fba2009-09-19 20:30:26 +00002217 CAList.size()), CAList);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002218
Chris Lattnerdb973e62005-09-26 02:31:18 +00002219 // If we didn't change the number of elements, don't create a new GV.
2220 if (CA->getType() == GCL->getInitializer()->getType()) {
2221 GCL->setInitializer(CA);
2222 return GCL;
2223 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002224
Chris Lattnerdb973e62005-09-26 02:31:18 +00002225 // Create the new global and insert it next to the existing list.
Chris Lattner7b550cc2009-11-06 04:27:31 +00002226 GlobalVariable *NGV = new GlobalVariable(CA->getType(), GCL->isConstant(),
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +00002227 GCL->getLinkage(), CA, "",
Hans Wennborgce718ff2012-06-23 11:37:03 +00002228 GCL->getThreadLocalMode());
Chris Lattnerdb973e62005-09-26 02:31:18 +00002229 GCL->getParent()->getGlobalList().insert(GCL, NGV);
Chris Lattner046800a2007-02-11 01:08:35 +00002230 NGV->takeName(GCL);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002231
Chris Lattnerdb973e62005-09-26 02:31:18 +00002232 // Nuke the old list, replacing any uses with the new one.
2233 if (!GCL->use_empty()) {
2234 Constant *V = NGV;
2235 if (V->getType() != GCL->getType())
Owen Andersonbaf3c402009-07-29 18:55:55 +00002236 V = ConstantExpr::getBitCast(V, GCL->getType());
Chris Lattnerdb973e62005-09-26 02:31:18 +00002237 GCL->replaceAllUsesWith(V);
2238 }
2239 GCL->eraseFromParent();
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002240
Chris Lattnerdb973e62005-09-26 02:31:18 +00002241 if (Ctors.size())
2242 return NGV;
2243 else
2244 return 0;
2245}
Chris Lattner79c11012005-09-26 04:44:35 +00002246
2247
Chris Lattner1945d582010-12-07 04:33:29 +00002248static inline bool
2249isSimpleEnoughValueToCommit(Constant *C,
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002250 SmallPtrSet<Constant*, 8> &SimpleConstants,
2251 const TargetData *TD);
Chris Lattner1945d582010-12-07 04:33:29 +00002252
2253
2254/// isSimpleEnoughValueToCommit - Return true if the specified constant can be
2255/// handled by the code generator. We don't want to generate something like:
2256/// void *X = &X/42;
2257/// because the code generator doesn't have a relocation that can handle that.
2258///
2259/// This function should be called if C was not found (but just got inserted)
2260/// in SimpleConstants to avoid having to rescan the same constants all the
2261/// time.
2262static bool isSimpleEnoughValueToCommitHelper(Constant *C,
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002263 SmallPtrSet<Constant*, 8> &SimpleConstants,
2264 const TargetData *TD) {
Chris Lattner1945d582010-12-07 04:33:29 +00002265 // Simple integer, undef, constant aggregate zero, global addresses, etc are
2266 // all supported.
2267 if (C->getNumOperands() == 0 || isa<BlockAddress>(C) ||
2268 isa<GlobalValue>(C))
2269 return true;
2270
2271 // Aggregate values are safe if all their elements are.
2272 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C) ||
2273 isa<ConstantVector>(C)) {
2274 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i) {
2275 Constant *Op = cast<Constant>(C->getOperand(i));
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002276 if (!isSimpleEnoughValueToCommit(Op, SimpleConstants, TD))
Chris Lattner1945d582010-12-07 04:33:29 +00002277 return false;
2278 }
2279 return true;
2280 }
2281
2282 // We don't know exactly what relocations are allowed in constant expressions,
2283 // so we allow &global+constantoffset, which is safe and uniformly supported
2284 // across targets.
2285 ConstantExpr *CE = cast<ConstantExpr>(C);
2286 switch (CE->getOpcode()) {
2287 case Instruction::BitCast:
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002288 // Bitcast is fine if the casted value is fine.
2289 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, TD);
2290
Chris Lattner1945d582010-12-07 04:33:29 +00002291 case Instruction::IntToPtr:
2292 case Instruction::PtrToInt:
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002293 // int <=> ptr is fine if the int type is the same size as the
2294 // pointer type.
2295 if (!TD || TD->getTypeSizeInBits(CE->getType()) !=
2296 TD->getTypeSizeInBits(CE->getOperand(0)->getType()))
2297 return false;
2298 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, TD);
Chris Lattner1945d582010-12-07 04:33:29 +00002299
2300 // GEP is fine if it is simple + constant offset.
2301 case Instruction::GetElementPtr:
2302 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
2303 if (!isa<ConstantInt>(CE->getOperand(i)))
2304 return false;
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002305 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, TD);
Chris Lattner1945d582010-12-07 04:33:29 +00002306
2307 case Instruction::Add:
2308 // We allow simple+cst.
2309 if (!isa<ConstantInt>(CE->getOperand(1)))
2310 return false;
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002311 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, TD);
Chris Lattner1945d582010-12-07 04:33:29 +00002312 }
2313 return false;
2314}
2315
2316static inline bool
2317isSimpleEnoughValueToCommit(Constant *C,
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002318 SmallPtrSet<Constant*, 8> &SimpleConstants,
2319 const TargetData *TD) {
Chris Lattner1945d582010-12-07 04:33:29 +00002320 // If we already checked this constant, we win.
2321 if (!SimpleConstants.insert(C)) return true;
2322 // Check the constant.
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002323 return isSimpleEnoughValueToCommitHelper(C, SimpleConstants, TD);
Chris Lattner1945d582010-12-07 04:33:29 +00002324}
2325
2326
Chris Lattner79c11012005-09-26 04:44:35 +00002327/// isSimpleEnoughPointerToCommit - Return true if this constant is simple
Owen Andersoncff6b372011-01-14 22:19:20 +00002328/// enough for us to understand. In particular, if it is a cast to anything
2329/// other than from one pointer type to another pointer type, we punt.
2330/// We basically just support direct accesses to globals and GEP's of
Chris Lattner79c11012005-09-26 04:44:35 +00002331/// globals. This should be kept up to date with CommitValueTo.
Chris Lattner7b550cc2009-11-06 04:27:31 +00002332static bool isSimpleEnoughPointerToCommit(Constant *C) {
Dan Gohmance5de5b2009-09-07 22:42:05 +00002333 // Conservatively, avoid aggregate types. This is because we don't
2334 // want to worry about them partially overlapping other stores.
2335 if (!cast<PointerType>(C->getType())->getElementType()->isSingleValueType())
2336 return false;
2337
Dan Gohmanfd54a892009-09-07 22:31:26 +00002338 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
Mikhail Glushenkov99fca5d2010-10-19 16:47:23 +00002339 // Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or
Dan Gohmanfd54a892009-09-07 22:31:26 +00002340 // external globals.
Mikhail Glushenkov99fca5d2010-10-19 16:47:23 +00002341 return GV->hasUniqueInitializer();
Dan Gohmanfd54a892009-09-07 22:31:26 +00002342
Owen Andersone95a32c2011-01-14 22:31:13 +00002343 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002344 // Handle a constantexpr gep.
2345 if (CE->getOpcode() == Instruction::GetElementPtr &&
Dan Gohmanc62482d2009-09-07 22:40:13 +00002346 isa<GlobalVariable>(CE->getOperand(0)) &&
2347 cast<GEPOperator>(CE)->isInBounds()) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002348 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
Mikhail Glushenkov99fca5d2010-10-19 16:47:23 +00002349 // Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or
Dan Gohmanfd54a892009-09-07 22:31:26 +00002350 // external globals.
Mikhail Glushenkov99fca5d2010-10-19 16:47:23 +00002351 if (!GV->hasUniqueInitializer())
Dan Gohmanfd54a892009-09-07 22:31:26 +00002352 return false;
Dan Gohman80bdc962009-09-07 22:44:55 +00002353
Dan Gohman80bdc962009-09-07 22:44:55 +00002354 // The first index must be zero.
Oscar Fuentesee56c422010-08-02 06:00:15 +00002355 ConstantInt *CI = dyn_cast<ConstantInt>(*llvm::next(CE->op_begin()));
Dan Gohman80bdc962009-09-07 22:44:55 +00002356 if (!CI || !CI->isZero()) return false;
Dan Gohman80bdc962009-09-07 22:44:55 +00002357
2358 // The remaining indices must be compile-time known integers within the
Dan Gohmane6992f72009-09-10 23:37:55 +00002359 // notional bounds of the corresponding static array types.
2360 if (!CE->isGEPWithNoNotionalOverIndexing())
2361 return false;
Dan Gohman80bdc962009-09-07 22:44:55 +00002362
Dan Gohmanc6f69e92009-10-05 16:36:26 +00002363 return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
Owen Andersoncff6b372011-01-14 22:19:20 +00002364
2365 // A constantexpr bitcast from a pointer to another pointer is a no-op,
2366 // and we know how to evaluate it by moving the bitcast from the pointer
2367 // operand to the value operand.
2368 } else if (CE->getOpcode() == Instruction::BitCast &&
Chris Lattnerd5f656f2011-01-16 02:05:10 +00002369 isa<GlobalVariable>(CE->getOperand(0))) {
Owen Andersoncff6b372011-01-14 22:19:20 +00002370 // Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or
2371 // external globals.
Chris Lattnerd5f656f2011-01-16 02:05:10 +00002372 return cast<GlobalVariable>(CE->getOperand(0))->hasUniqueInitializer();
Chris Lattner798b4d52005-09-26 06:52:44 +00002373 }
Owen Andersone95a32c2011-01-14 22:31:13 +00002374 }
2375
Chris Lattner79c11012005-09-26 04:44:35 +00002376 return false;
2377}
2378
Chris Lattner798b4d52005-09-26 06:52:44 +00002379/// EvaluateStoreInto - Evaluate a piece of a constantexpr store into a global
2380/// initializer. This returns 'Init' modified to reflect 'Val' stored into it.
2381/// At this point, the GEP operands of Addr [0, OpNo) have been stepped into.
2382static Constant *EvaluateStoreInto(Constant *Init, Constant *Val,
Chris Lattner7b550cc2009-11-06 04:27:31 +00002383 ConstantExpr *Addr, unsigned OpNo) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002384 // Base case of the recursion.
2385 if (OpNo == Addr->getNumOperands()) {
2386 assert(Val->getType() == Init->getType() && "Type mismatch!");
2387 return Val;
2388 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002389
Chris Lattnera78fa8c2012-01-27 03:08:05 +00002390 SmallVector<Constant*, 32> Elts;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002391 if (StructType *STy = dyn_cast<StructType>(Init->getType())) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002392 // Break up the constant into its elements.
Chris Lattnerd59ae902012-01-26 02:32:04 +00002393 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
2394 Elts.push_back(Init->getAggregateElement(i));
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002395
Chris Lattner798b4d52005-09-26 06:52:44 +00002396 // Replace the element that we are supposed to.
Reid Spencerb83eb642006-10-20 07:07:24 +00002397 ConstantInt *CU = cast<ConstantInt>(Addr->getOperand(OpNo));
2398 unsigned Idx = CU->getZExtValue();
2399 assert(Idx < STy->getNumElements() && "Struct index out of range!");
Chris Lattner7b550cc2009-11-06 04:27:31 +00002400 Elts[Idx] = EvaluateStoreInto(Elts[Idx], Val, Addr, OpNo+1);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002401
Chris Lattner798b4d52005-09-26 06:52:44 +00002402 // Return the modified struct.
Chris Lattnerb065b062011-06-20 04:01:31 +00002403 return ConstantStruct::get(STy, Elts);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002404 }
Chris Lattnerb065b062011-06-20 04:01:31 +00002405
2406 ConstantInt *CI = cast<ConstantInt>(Addr->getOperand(OpNo));
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002407 SequentialType *InitTy = cast<SequentialType>(Init->getType());
Chris Lattnerb065b062011-06-20 04:01:31 +00002408
2409 uint64_t NumElts;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002410 if (ArrayType *ATy = dyn_cast<ArrayType>(InitTy))
Chris Lattnerb065b062011-06-20 04:01:31 +00002411 NumElts = ATy->getNumElements();
2412 else
Chris Lattnerd59ae902012-01-26 02:32:04 +00002413 NumElts = InitTy->getVectorNumElements();
Chris Lattnerb065b062011-06-20 04:01:31 +00002414
2415 // Break up the array into elements.
Chris Lattnerd59ae902012-01-26 02:32:04 +00002416 for (uint64_t i = 0, e = NumElts; i != e; ++i)
2417 Elts.push_back(Init->getAggregateElement(i));
Chris Lattnerb065b062011-06-20 04:01:31 +00002418
2419 assert(CI->getZExtValue() < NumElts);
2420 Elts[CI->getZExtValue()] =
2421 EvaluateStoreInto(Elts[CI->getZExtValue()], Val, Addr, OpNo+1);
2422
2423 if (Init->getType()->isArrayTy())
2424 return ConstantArray::get(cast<ArrayType>(InitTy), Elts);
2425 return ConstantVector::get(Elts);
Chris Lattner798b4d52005-09-26 06:52:44 +00002426}
2427
Chris Lattner79c11012005-09-26 04:44:35 +00002428/// CommitValueTo - We have decided that Addr (which satisfies the predicate
2429/// isSimpleEnoughPointerToCommit) should get Val as its value. Make it happen.
Chris Lattner7b550cc2009-11-06 04:27:31 +00002430static void CommitValueTo(Constant *Val, Constant *Addr) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002431 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Addr)) {
2432 assert(GV->hasInitializer());
2433 GV->setInitializer(Val);
2434 return;
2435 }
Chris Lattnera0e9a242010-01-07 01:16:21 +00002436
Chris Lattner798b4d52005-09-26 06:52:44 +00002437 ConstantExpr *CE = cast<ConstantExpr>(Addr);
2438 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
Chris Lattnera0e9a242010-01-07 01:16:21 +00002439 GV->setInitializer(EvaluateStoreInto(GV->getInitializer(), Val, CE, 2));
Chris Lattner79c11012005-09-26 04:44:35 +00002440}
2441
Nick Lewycky7fa76772012-02-20 03:25:59 +00002442namespace {
2443
2444/// Evaluator - This class evaluates LLVM IR, producing the Constant
2445/// representing each SSA instruction. Changes to global variables are stored
2446/// in a mapping that can be iterated over after the evaluation is complete.
2447/// Once an evaluation call fails, the evaluation object should not be reused.
2448class Evaluator {
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002449public:
Nick Lewycky7fa76772012-02-20 03:25:59 +00002450 Evaluator(const TargetData *TD, const TargetLibraryInfo *TLI)
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002451 : TD(TD), TLI(TLI) {
2452 ValueStack.push_back(new DenseMap<Value*, Constant*>);
2453 }
2454
Nick Lewycky7fa76772012-02-20 03:25:59 +00002455 ~Evaluator() {
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002456 DeleteContainerPointers(ValueStack);
2457 while (!AllocaTmps.empty()) {
2458 GlobalVariable *Tmp = AllocaTmps.back();
2459 AllocaTmps.pop_back();
2460
2461 // If there are still users of the alloca, the program is doing something
2462 // silly, e.g. storing the address of the alloca somewhere and using it
2463 // later. Since this is undefined, we'll just make it be null.
2464 if (!Tmp->use_empty())
2465 Tmp->replaceAllUsesWith(Constant::getNullValue(Tmp->getType()));
2466 delete Tmp;
2467 }
2468 }
2469
2470 /// EvaluateFunction - Evaluate a call to function F, returning true if
2471 /// successful, false if we can't evaluate it. ActualArgs contains the formal
2472 /// arguments for the function.
2473 bool EvaluateFunction(Function *F, Constant *&RetVal,
2474 const SmallVectorImpl<Constant*> &ActualArgs);
2475
2476 /// EvaluateBlock - Evaluate all instructions in block BB, returning true if
2477 /// successful, false if we can't evaluate it. NewBB returns the next BB that
2478 /// control flows into, or null upon return.
2479 bool EvaluateBlock(BasicBlock::iterator CurInst, BasicBlock *&NextBB);
2480
2481 Constant *getVal(Value *V) {
2482 if (Constant *CV = dyn_cast<Constant>(V)) return CV;
2483 Constant *R = ValueStack.back()->lookup(V);
2484 assert(R && "Reference to an uncomputed value!");
2485 return R;
2486 }
2487
2488 void setVal(Value *V, Constant *C) {
2489 ValueStack.back()->operator[](V) = C;
2490 }
2491
2492 const DenseMap<Constant*, Constant*> &getMutatedMemory() const {
2493 return MutatedMemory;
2494 }
2495
2496 const SmallPtrSet<GlobalVariable*, 8> &getInvariants() const {
2497 return Invariants;
2498 }
2499
2500private:
2501 Constant *ComputeLoadResult(Constant *P);
2502
2503 /// ValueStack - As we compute SSA register values, we store their contents
2504 /// here. The back of the vector contains the current function and the stack
2505 /// contains the values in the calling frames.
2506 SmallVector<DenseMap<Value*, Constant*>*, 4> ValueStack;
2507
2508 /// CallStack - This is used to detect recursion. In pathological situations
2509 /// we could hit exponential behavior, but at least there is nothing
2510 /// unbounded.
2511 SmallVector<Function*, 4> CallStack;
2512
2513 /// MutatedMemory - For each store we execute, we update this map. Loads
2514 /// check this to get the most up-to-date value. If evaluation is successful,
2515 /// this state is committed to the process.
2516 DenseMap<Constant*, Constant*> MutatedMemory;
2517
2518 /// AllocaTmps - To 'execute' an alloca, we create a temporary global variable
2519 /// to represent its body. This vector is needed so we can delete the
2520 /// temporary globals when we are done.
2521 SmallVector<GlobalVariable*, 32> AllocaTmps;
2522
2523 /// Invariants - These global variables have been marked invariant by the
2524 /// static constructor.
2525 SmallPtrSet<GlobalVariable*, 8> Invariants;
2526
2527 /// SimpleConstants - These are constants we have checked and know to be
2528 /// simple enough to live in a static initializer of a global.
2529 SmallPtrSet<Constant*, 8> SimpleConstants;
2530
2531 const TargetData *TD;
2532 const TargetLibraryInfo *TLI;
2533};
2534
Nick Lewycky7fa76772012-02-20 03:25:59 +00002535} // anonymous namespace
2536
Chris Lattner562a0552005-09-26 05:16:34 +00002537/// ComputeLoadResult - Return the value that would be computed by a load from
2538/// P after the stores reflected by 'memory' have been performed. If we can't
2539/// decide, return null.
Nick Lewycky7fa76772012-02-20 03:25:59 +00002540Constant *Evaluator::ComputeLoadResult(Constant *P) {
Chris Lattner04de1cf2005-09-26 05:15:37 +00002541 // If this memory location has been recently stored, use the stored value: it
2542 // is the most up-to-date.
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002543 DenseMap<Constant*, Constant*>::const_iterator I = MutatedMemory.find(P);
2544 if (I != MutatedMemory.end()) return I->second;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002545
Chris Lattner04de1cf2005-09-26 05:15:37 +00002546 // Access it.
2547 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(P)) {
Dan Gohman82555732009-08-19 18:20:44 +00002548 if (GV->hasDefinitiveInitializer())
Chris Lattner04de1cf2005-09-26 05:15:37 +00002549 return GV->getInitializer();
2550 return 0;
Chris Lattner04de1cf2005-09-26 05:15:37 +00002551 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002552
Chris Lattner798b4d52005-09-26 06:52:44 +00002553 // Handle a constantexpr getelementptr.
2554 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(P))
2555 if (CE->getOpcode() == Instruction::GetElementPtr &&
2556 isa<GlobalVariable>(CE->getOperand(0))) {
2557 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
Dan Gohman82555732009-08-19 18:20:44 +00002558 if (GV->hasDefinitiveInitializer())
Dan Gohmanc6f69e92009-10-05 16:36:26 +00002559 return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
Chris Lattner798b4d52005-09-26 06:52:44 +00002560 }
2561
2562 return 0; // don't know how to evaluate.
Chris Lattner04de1cf2005-09-26 05:15:37 +00002563}
2564
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002565/// EvaluateBlock - Evaluate all instructions in block BB, returning true if
2566/// successful, false if we can't evaluate it. NewBB returns the next BB that
2567/// control flows into, or null upon return.
Nick Lewycky7fa76772012-02-20 03:25:59 +00002568bool Evaluator::EvaluateBlock(BasicBlock::iterator CurInst,
2569 BasicBlock *&NextBB) {
Chris Lattner79c11012005-09-26 04:44:35 +00002570 // This is the main evaluation loop.
2571 while (1) {
2572 Constant *InstResult = 0;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002573
Chris Lattner79c11012005-09-26 04:44:35 +00002574 if (StoreInst *SI = dyn_cast<StoreInst>(CurInst)) {
Eli Friedman33cb4452011-08-16 00:20:11 +00002575 if (!SI->isSimple()) return false; // no volatile/atomic accesses.
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002576 Constant *Ptr = getVal(SI->getOperand(1));
Nick Lewyckya641c072012-02-21 22:08:06 +00002577 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
2578 Ptr = ConstantFoldConstantExpression(CE, TD, TLI);
Chris Lattner7b550cc2009-11-06 04:27:31 +00002579 if (!isSimpleEnoughPointerToCommit(Ptr))
Chris Lattner79c11012005-09-26 04:44:35 +00002580 // If this is too complex for us to commit, reject it.
Chris Lattnercd271422005-09-27 04:45:34 +00002581 return false;
Chris Lattner1945d582010-12-07 04:33:29 +00002582
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002583 Constant *Val = getVal(SI->getOperand(0));
Chris Lattner1945d582010-12-07 04:33:29 +00002584
2585 // If this might be too difficult for the backend to handle (e.g. the addr
2586 // of one global variable divided by another) then we can't commit it.
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002587 if (!isSimpleEnoughValueToCommit(Val, SimpleConstants, TD))
Chris Lattner1945d582010-12-07 04:33:29 +00002588 return false;
Owen Andersoncff6b372011-01-14 22:19:20 +00002589
2590 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
2591 if (CE->getOpcode() == Instruction::BitCast) {
2592 // If we're evaluating a store through a bitcast, then we need
2593 // to pull the bitcast off the pointer type and push it onto the
2594 // stored value.
Chris Lattnerd5f656f2011-01-16 02:05:10 +00002595 Ptr = CE->getOperand(0);
Owen Andersoncff6b372011-01-14 22:19:20 +00002596
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002597 Type *NewTy = cast<PointerType>(Ptr->getType())->getElementType();
Owen Andersoncff6b372011-01-14 22:19:20 +00002598
Owen Anderson66f708f2011-01-16 04:33:33 +00002599 // In order to push the bitcast onto the stored value, a bitcast
2600 // from NewTy to Val's type must be legal. If it's not, we can try
2601 // introspecting NewTy to find a legal conversion.
2602 while (!Val->getType()->canLosslesslyBitCastTo(NewTy)) {
2603 // If NewTy is a struct, we can convert the pointer to the struct
2604 // into a pointer to its first member.
2605 // FIXME: This could be extended to support arrays as well.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002606 if (StructType *STy = dyn_cast<StructType>(NewTy)) {
Owen Anderson66f708f2011-01-16 04:33:33 +00002607 NewTy = STy->getTypeAtIndex(0U);
2608
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002609 IntegerType *IdxTy = IntegerType::get(NewTy->getContext(), 32);
Owen Anderson66f708f2011-01-16 04:33:33 +00002610 Constant *IdxZero = ConstantInt::get(IdxTy, 0, false);
2611 Constant * const IdxList[] = {IdxZero, IdxZero};
2612
Jay Foadb4263a62011-07-22 08:52:50 +00002613 Ptr = ConstantExpr::getGetElementPtr(Ptr, IdxList);
Nick Lewyckya641c072012-02-21 22:08:06 +00002614 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
2615 Ptr = ConstantFoldConstantExpression(CE, TD, TLI);
2616
Owen Anderson66f708f2011-01-16 04:33:33 +00002617 // If we can't improve the situation by introspecting NewTy,
2618 // we have to give up.
2619 } else {
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002620 return false;
Owen Anderson66f708f2011-01-16 04:33:33 +00002621 }
Owen Andersoncff6b372011-01-14 22:19:20 +00002622 }
2623
Owen Anderson66f708f2011-01-16 04:33:33 +00002624 // If we found compatible types, go ahead and push the bitcast
2625 // onto the stored value.
Owen Andersoncff6b372011-01-14 22:19:20 +00002626 Val = ConstantExpr::getBitCast(Val, NewTy);
2627 }
2628
Chris Lattner79c11012005-09-26 04:44:35 +00002629 MutatedMemory[Ptr] = Val;
2630 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CurInst)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002631 InstResult = ConstantExpr::get(BO->getOpcode(),
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002632 getVal(BO->getOperand(0)),
2633 getVal(BO->getOperand(1)));
Reid Spencere4d87aa2006-12-23 06:05:41 +00002634 } else if (CmpInst *CI = dyn_cast<CmpInst>(CurInst)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002635 InstResult = ConstantExpr::getCompare(CI->getPredicate(),
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002636 getVal(CI->getOperand(0)),
2637 getVal(CI->getOperand(1)));
Chris Lattner79c11012005-09-26 04:44:35 +00002638 } else if (CastInst *CI = dyn_cast<CastInst>(CurInst)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002639 InstResult = ConstantExpr::getCast(CI->getOpcode(),
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002640 getVal(CI->getOperand(0)),
Chris Lattner79c11012005-09-26 04:44:35 +00002641 CI->getType());
2642 } else if (SelectInst *SI = dyn_cast<SelectInst>(CurInst)) {
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002643 InstResult = ConstantExpr::getSelect(getVal(SI->getOperand(0)),
2644 getVal(SI->getOperand(1)),
2645 getVal(SI->getOperand(2)));
Chris Lattner04de1cf2005-09-26 05:15:37 +00002646 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurInst)) {
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002647 Constant *P = getVal(GEP->getOperand(0));
Chris Lattner55eb1c42007-01-31 04:40:53 +00002648 SmallVector<Constant*, 8> GEPOps;
Gabor Greif5e463212008-05-29 01:59:18 +00002649 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end();
2650 i != e; ++i)
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002651 GEPOps.push_back(getVal(*i));
Jay Foad4b5e2072011-07-21 15:15:37 +00002652 InstResult =
2653 ConstantExpr::getGetElementPtr(P, GEPOps,
2654 cast<GEPOperator>(GEP)->isInBounds());
Chris Lattner04de1cf2005-09-26 05:15:37 +00002655 } else if (LoadInst *LI = dyn_cast<LoadInst>(CurInst)) {
Eli Friedman33cb4452011-08-16 00:20:11 +00002656 if (!LI->isSimple()) return false; // no volatile/atomic accesses.
Nick Lewyckya641c072012-02-21 22:08:06 +00002657 Constant *Ptr = getVal(LI->getOperand(0));
2658 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
2659 Ptr = ConstantFoldConstantExpression(CE, TD, TLI);
2660 InstResult = ComputeLoadResult(Ptr);
Chris Lattnercd271422005-09-27 04:45:34 +00002661 if (InstResult == 0) return false; // Could not evaluate load.
Chris Lattnera22fdb02005-09-26 17:07:09 +00002662 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(CurInst)) {
Chris Lattnercd271422005-09-27 04:45:34 +00002663 if (AI->isArrayAllocation()) return false; // Cannot handle array allocs.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002664 Type *Ty = AI->getType()->getElementType();
Chris Lattner7b550cc2009-11-06 04:27:31 +00002665 AllocaTmps.push_back(new GlobalVariable(Ty, false,
Chris Lattnera22fdb02005-09-26 17:07:09 +00002666 GlobalValue::InternalLinkage,
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002667 UndefValue::get(Ty),
Chris Lattnera22fdb02005-09-26 17:07:09 +00002668 AI->getName()));
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002669 InstResult = AllocaTmps.back();
Nick Lewycky132bd9c2012-02-12 05:09:35 +00002670 } else if (isa<CallInst>(CurInst) || isa<InvokeInst>(CurInst)) {
2671 CallSite CS(CurInst);
Devang Patel412a4462009-03-09 23:04:12 +00002672
2673 // Debug info can safely be ignored here.
Nick Lewycky132bd9c2012-02-12 05:09:35 +00002674 if (isa<DbgInfoIntrinsic>(CS.getInstruction())) {
Devang Patel412a4462009-03-09 23:04:12 +00002675 ++CurInst;
2676 continue;
2677 }
2678
Chris Lattner7cd580f2006-07-07 21:37:01 +00002679 // Cannot handle inline asm.
Nick Lewycky132bd9c2012-02-12 05:09:35 +00002680 if (isa<InlineAsm>(CS.getCalledValue())) return false;
Chris Lattner7cd580f2006-07-07 21:37:01 +00002681
Nick Lewycky81266c52012-02-17 06:59:21 +00002682 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CS.getInstruction())) {
2683 if (MemSetInst *MSI = dyn_cast<MemSetInst>(II)) {
2684 if (MSI->isVolatile()) return false;
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002685 Constant *Ptr = getVal(MSI->getDest());
2686 Constant *Val = getVal(MSI->getValue());
2687 Constant *DestVal = ComputeLoadResult(getVal(Ptr));
Nick Lewycky81266c52012-02-17 06:59:21 +00002688 if (Val->isNullValue() && DestVal && DestVal->isNullValue()) {
2689 // This memset is a no-op.
2690 ++CurInst;
2691 continue;
2692 }
2693 }
2694
2695 if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
2696 II->getIntrinsicID() == Intrinsic::lifetime_end) {
2697 ++CurInst;
2698 continue;
2699 }
2700
2701 if (II->getIntrinsicID() == Intrinsic::invariant_start) {
2702 // We don't insert an entry into Values, as it doesn't have a
2703 // meaningful return value.
2704 if (!II->use_empty())
2705 return false;
2706 ConstantInt *Size = cast<ConstantInt>(II->getArgOperand(0));
Nick Lewycky0ef05572012-02-20 23:32:26 +00002707 Value *PtrArg = getVal(II->getArgOperand(1));
2708 Value *Ptr = PtrArg->stripPointerCasts();
2709 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr)) {
2710 Type *ElemTy = cast<PointerType>(GV->getType())->getElementType();
2711 if (!Size->isAllOnesValue() &&
2712 Size->getValue().getLimitedValue() >=
2713 TD->getTypeStoreSize(ElemTy))
Nick Lewycky81266c52012-02-17 06:59:21 +00002714 Invariants.insert(GV);
2715 }
2716 // Continue even if we do nothing.
Nick Lewycky1f237b02011-05-29 18:41:56 +00002717 ++CurInst;
2718 continue;
2719 }
2720 return false;
2721 }
2722
Chris Lattnercd271422005-09-27 04:45:34 +00002723 // Resolve function pointers.
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002724 Function *Callee = dyn_cast<Function>(getVal(CS.getCalledValue()));
Nick Lewycky132bd9c2012-02-12 05:09:35 +00002725 if (!Callee || Callee->mayBeOverridden())
2726 return false; // Cannot resolve.
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002727
Duncan Sandsfa6a1cf2009-08-17 14:33:27 +00002728 SmallVector<Constant*, 8> Formals;
Nick Lewycky132bd9c2012-02-12 05:09:35 +00002729 for (User::op_iterator i = CS.arg_begin(), e = CS.arg_end(); i != e; ++i)
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002730 Formals.push_back(getVal(*i));
Duncan Sandsfa6a1cf2009-08-17 14:33:27 +00002731
Reid Spencer5cbf9852007-01-30 20:08:39 +00002732 if (Callee->isDeclaration()) {
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002733 // If this is a function we can constant fold, do it.
Chad Rosier00737bd2011-12-01 21:29:16 +00002734 if (Constant *C = ConstantFoldCall(Callee, Formals, TLI)) {
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002735 InstResult = C;
2736 } else {
2737 return false;
2738 }
2739 } else {
2740 if (Callee->getFunctionType()->isVarArg())
2741 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002742
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002743 Constant *RetVal;
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002744 // Execute the call, if successful, use the return value.
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002745 ValueStack.push_back(new DenseMap<Value*, Constant*>);
2746 if (!EvaluateFunction(Callee, RetVal, Formals))
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002747 return false;
Benjamin Kramer3bbf2b62012-02-27 12:48:24 +00002748 delete ValueStack.pop_back_val();
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002749 InstResult = RetVal;
2750 }
Reid Spencer3ed469c2006-11-02 20:25:50 +00002751 } else if (isa<TerminatorInst>(CurInst)) {
Chris Lattnercdf98be2005-09-26 04:57:38 +00002752 if (BranchInst *BI = dyn_cast<BranchInst>(CurInst)) {
2753 if (BI->isUnconditional()) {
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002754 NextBB = BI->getSuccessor(0);
Chris Lattnercdf98be2005-09-26 04:57:38 +00002755 } else {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002756 ConstantInt *Cond =
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002757 dyn_cast<ConstantInt>(getVal(BI->getCondition()));
Chris Lattner97d1fad2007-01-12 18:30:11 +00002758 if (!Cond) return false; // Cannot determine.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002759
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002760 NextBB = BI->getSuccessor(!Cond->getZExtValue());
Chris Lattnercdf98be2005-09-26 04:57:38 +00002761 }
2762 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(CurInst)) {
2763 ConstantInt *Val =
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002764 dyn_cast<ConstantInt>(getVal(SI->getCondition()));
Chris Lattnercd271422005-09-27 04:45:34 +00002765 if (!Val) return false; // Cannot determine.
Stepan Dyatkovskiyc10fa6c2012-03-08 07:06:20 +00002766 NextBB = SI->findCaseValue(Val).getCaseSuccessor();
Chris Lattnerb3d5a652009-10-29 05:51:50 +00002767 } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(CurInst)) {
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002768 Value *Val = getVal(IBI->getAddress())->stripPointerCasts();
Chris Lattnerb3d5a652009-10-29 05:51:50 +00002769 if (BlockAddress *BA = dyn_cast<BlockAddress>(Val))
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002770 NextBB = BA->getBasicBlock();
Chris Lattnercdfc9402009-11-01 01:27:45 +00002771 else
2772 return false; // Cannot determine.
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002773 } else if (isa<ReturnInst>(CurInst)) {
2774 NextBB = 0;
Chris Lattnercdf98be2005-09-26 04:57:38 +00002775 } else {
Bill Wendlingdccc03b2011-07-31 06:30:59 +00002776 // invoke, unwind, resume, unreachable.
Chris Lattnercd271422005-09-27 04:45:34 +00002777 return false; // Cannot handle this terminator.
Chris Lattnercdf98be2005-09-26 04:57:38 +00002778 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002779
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002780 // We succeeded at evaluating this block!
2781 return true;
Chris Lattner79c11012005-09-26 04:44:35 +00002782 } else {
Chris Lattner79c11012005-09-26 04:44:35 +00002783 // Did not know how to evaluate this!
Chris Lattnercd271422005-09-27 04:45:34 +00002784 return false;
Chris Lattner79c11012005-09-26 04:44:35 +00002785 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002786
Chris Lattner1945d582010-12-07 04:33:29 +00002787 if (!CurInst->use_empty()) {
2788 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(InstResult))
Chad Rosieraab8e282011-12-02 01:26:24 +00002789 InstResult = ConstantFoldConstantExpression(CE, TD, TLI);
Chris Lattner1945d582010-12-07 04:33:29 +00002790
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002791 setVal(CurInst, InstResult);
Chris Lattner1945d582010-12-07 04:33:29 +00002792 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002793
Dan Gohmanf1ce79f2012-03-13 18:01:37 +00002794 // If we just processed an invoke, we finished evaluating the block.
2795 if (InvokeInst *II = dyn_cast<InvokeInst>(CurInst)) {
2796 NextBB = II->getNormalDest();
2797 return true;
2798 }
2799
Chris Lattner79c11012005-09-26 04:44:35 +00002800 // Advance program counter.
2801 ++CurInst;
2802 }
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002803}
2804
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002805/// EvaluateFunction - Evaluate a call to function F, returning true if
2806/// successful, false if we can't evaluate it. ActualArgs contains the formal
2807/// arguments for the function.
Nick Lewycky7fa76772012-02-20 03:25:59 +00002808bool Evaluator::EvaluateFunction(Function *F, Constant *&RetVal,
2809 const SmallVectorImpl<Constant*> &ActualArgs) {
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002810 // Check to see if this function is already executing (recursion). If so,
2811 // bail out. TODO: we might want to accept limited recursion.
2812 if (std::find(CallStack.begin(), CallStack.end(), F) != CallStack.end())
2813 return false;
2814
2815 CallStack.push_back(F);
2816
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002817 // Initialize arguments to the incoming values specified.
2818 unsigned ArgNo = 0;
2819 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); AI != E;
2820 ++AI, ++ArgNo)
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002821 setVal(AI, ActualArgs[ArgNo]);
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002822
2823 // ExecutedBlocks - We only handle non-looping, non-recursive code. As such,
2824 // we can only evaluate any one basic block at most once. This set keeps
2825 // track of what we have executed so we can detect recursive cases etc.
2826 SmallPtrSet<BasicBlock*, 32> ExecutedBlocks;
2827
2828 // CurBB - The current basic block we're evaluating.
2829 BasicBlock *CurBB = F->begin();
2830
Nick Lewycky8e4ba6b2012-02-12 00:47:24 +00002831 BasicBlock::iterator CurInst = CurBB->begin();
2832
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002833 while (1) {
Duncan Sands4b794f82012-02-23 08:23:06 +00002834 BasicBlock *NextBB = 0; // Initialized to avoid compiler warnings.
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002835 if (!EvaluateBlock(CurInst, NextBB))
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002836 return false;
2837
2838 if (NextBB == 0) {
2839 // Successfully running until there's no next block means that we found
2840 // the return. Fill it the return value and pop the call stack.
2841 ReturnInst *RI = cast<ReturnInst>(CurBB->getTerminator());
2842 if (RI->getNumOperands())
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002843 RetVal = getVal(RI->getOperand(0));
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002844 CallStack.pop_back();
2845 return true;
2846 }
2847
2848 // Okay, we succeeded in evaluating this control flow. See if we have
2849 // executed the new block before. If so, we have a looping function,
2850 // which we cannot evaluate in reasonable time.
2851 if (!ExecutedBlocks.insert(NextBB))
2852 return false; // looped!
2853
2854 // Okay, we have never been in this block before. Check to see if there
2855 // are any PHI nodes. If so, evaluate them with information about where
2856 // we came from.
2857 PHINode *PN = 0;
Nick Lewycky8e4ba6b2012-02-12 00:47:24 +00002858 for (CurInst = NextBB->begin();
2859 (PN = dyn_cast<PHINode>(CurInst)); ++CurInst)
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002860 setVal(PN, getVal(PN->getIncomingValueForBlock(CurBB)));
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002861
2862 // Advance to the next block.
2863 CurBB = NextBB;
2864 }
2865}
2866
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002867/// EvaluateStaticConstructor - Evaluate static constructors in the function, if
2868/// we can. Return true if we can, false otherwise.
Chad Rosier00737bd2011-12-01 21:29:16 +00002869static bool EvaluateStaticConstructor(Function *F, const TargetData *TD,
2870 const TargetLibraryInfo *TLI) {
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002871 // Call the function.
Nick Lewycky7fa76772012-02-20 03:25:59 +00002872 Evaluator Eval(TD, TLI);
Chris Lattnercd271422005-09-27 04:45:34 +00002873 Constant *RetValDummy;
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002874 bool EvalSuccess = Eval.EvaluateFunction(F, RetValDummy,
2875 SmallVector<Constant*, 0>());
Chris Lattner1945d582010-12-07 04:33:29 +00002876
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002877 if (EvalSuccess) {
Chris Lattnera22fdb02005-09-26 17:07:09 +00002878 // We succeeded at evaluation: commit the result.
David Greene3215b0e2010-01-05 01:28:05 +00002879 DEBUG(dbgs() << "FULLY EVALUATED GLOBAL CTOR FUNCTION '"
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002880 << F->getName() << "' to " << Eval.getMutatedMemory().size()
Daniel Dunbarce63ffb2009-07-25 00:23:56 +00002881 << " stores.\n");
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002882 for (DenseMap<Constant*, Constant*>::const_iterator I =
2883 Eval.getMutatedMemory().begin(), E = Eval.getMutatedMemory().end();
Nick Lewycky3eab3c42012-06-24 04:07:14 +00002884 I != E; ++I)
Chris Lattner7b550cc2009-11-06 04:27:31 +00002885 CommitValueTo(I->second, I->first);
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002886 for (SmallPtrSet<GlobalVariable*, 8>::const_iterator I =
2887 Eval.getInvariants().begin(), E = Eval.getInvariants().end();
2888 I != E; ++I)
Nick Lewycky81266c52012-02-17 06:59:21 +00002889 (*I)->setConstant(true);
Chris Lattnera22fdb02005-09-26 17:07:09 +00002890 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002891
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002892 return EvalSuccess;
Chris Lattner79c11012005-09-26 04:44:35 +00002893}
2894
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002895/// OptimizeGlobalCtorsList - Simplify and evaluation global ctors if possible.
2896/// Return true if anything changed.
2897bool GlobalOpt::OptimizeGlobalCtorsList(GlobalVariable *&GCL) {
2898 std::vector<Function*> Ctors = ParseGlobalCtors(GCL);
2899 bool MadeChange = false;
2900 if (Ctors.empty()) return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002901
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002902 // Loop over global ctors, optimizing them when we can.
2903 for (unsigned i = 0; i != Ctors.size(); ++i) {
2904 Function *F = Ctors[i];
2905 // Found a null terminator in the middle of the list, prune off the rest of
2906 // the list.
Chris Lattner7d8e58f2005-09-26 02:19:27 +00002907 if (F == 0) {
2908 if (i != Ctors.size()-1) {
2909 Ctors.resize(i+1);
2910 MadeChange = true;
2911 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002912 break;
2913 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002914
Chris Lattner79c11012005-09-26 04:44:35 +00002915 // We cannot simplify external ctor functions.
2916 if (F->empty()) continue;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002917
Chris Lattner79c11012005-09-26 04:44:35 +00002918 // If we can evaluate the ctor at compile time, do.
Chad Rosier00737bd2011-12-01 21:29:16 +00002919 if (EvaluateStaticConstructor(F, TD, TLI)) {
Chris Lattner79c11012005-09-26 04:44:35 +00002920 Ctors.erase(Ctors.begin()+i);
2921 MadeChange = true;
2922 --i;
2923 ++NumCtorsEvaluated;
2924 continue;
2925 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002926 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002927
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002928 if (!MadeChange) return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002929
Chris Lattner7b550cc2009-11-06 04:27:31 +00002930 GCL = InstallGlobalCtors(GCL, Ctors);
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002931 return true;
2932}
2933
Duncan Sandsfc5940d2009-03-06 10:21:56 +00002934bool GlobalOpt::OptimizeGlobalAliases(Module &M) {
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002935 bool Changed = false;
2936
Duncan Sands177d84e2009-01-07 20:01:06 +00002937 for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end();
Duncan Sands4782b302009-02-15 09:56:08 +00002938 I != E;) {
2939 Module::alias_iterator J = I++;
Duncan Sandsfc5940d2009-03-06 10:21:56 +00002940 // Aliases without names cannot be referenced outside this module.
2941 if (!J->hasName() && !J->isDeclaration())
2942 J->setLinkage(GlobalValue::InternalLinkage);
Duncan Sands4782b302009-02-15 09:56:08 +00002943 // If the aliasee may change at link time, nothing can be done - bail out.
2944 if (J->mayBeOverridden())
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002945 continue;
2946
Duncan Sands4782b302009-02-15 09:56:08 +00002947 Constant *Aliasee = J->getAliasee();
2948 GlobalValue *Target = cast<GlobalValue>(Aliasee->stripPointerCasts());
Duncan Sands95c5d0f2009-02-18 17:55:38 +00002949 Target->removeDeadConstantUsers();
Duncan Sands4782b302009-02-15 09:56:08 +00002950 bool hasOneUse = Target->hasOneUse() && Aliasee->hasOneUse();
2951
2952 // Make all users of the alias use the aliasee instead.
2953 if (!J->use_empty()) {
2954 J->replaceAllUsesWith(Aliasee);
2955 ++NumAliasesResolved;
2956 Changed = true;
2957 }
2958
Duncan Sands7a154cf2009-12-08 10:10:20 +00002959 // If the alias is externally visible, we may still be able to simplify it.
2960 if (!J->hasLocalLinkage()) {
2961 // If the aliasee has internal linkage, give it the name and linkage
2962 // of the alias, and delete the alias. This turns:
2963 // define internal ... @f(...)
2964 // @a = alias ... @f
2965 // into:
2966 // define ... @a(...)
2967 if (!Target->hasLocalLinkage())
2968 continue;
Duncan Sands4782b302009-02-15 09:56:08 +00002969
Duncan Sands7a154cf2009-12-08 10:10:20 +00002970 // Do not perform the transform if multiple aliases potentially target the
Gabor Greif27236912010-04-07 18:59:26 +00002971 // aliasee. This check also ensures that it is safe to replace the section
Duncan Sands7a154cf2009-12-08 10:10:20 +00002972 // and other attributes of the aliasee with those of the alias.
2973 if (!hasOneUse)
2974 continue;
Duncan Sands4782b302009-02-15 09:56:08 +00002975
Duncan Sands7a154cf2009-12-08 10:10:20 +00002976 // Give the aliasee the name, linkage and other attributes of the alias.
2977 Target->takeName(J);
2978 Target->setLinkage(J->getLinkage());
2979 Target->GlobalValue::copyAttributesFrom(J);
2980 }
Duncan Sands4782b302009-02-15 09:56:08 +00002981
2982 // Delete the alias.
2983 M.getAliasList().erase(J);
2984 ++NumAliasesRemoved;
2985 Changed = true;
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002986 }
2987
2988 return Changed;
2989}
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002990
Nick Lewycky6a7df9a2012-02-12 02:15:20 +00002991static Function *FindCXAAtExit(Module &M, TargetLibraryInfo *TLI) {
2992 if (!TLI->has(LibFunc::cxa_atexit))
Nick Lewycky6f160d32012-02-12 02:17:18 +00002993 return 0;
Nick Lewycky6a7df9a2012-02-12 02:15:20 +00002994
2995 Function *Fn = M.getFunction(TLI->getName(LibFunc::cxa_atexit));
Anders Carlssona201c4c2011-03-20 17:59:11 +00002996
2997 if (!Fn)
2998 return 0;
Nick Lewycky6a7df9a2012-02-12 02:15:20 +00002999
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003000 FunctionType *FTy = Fn->getFunctionType();
Anders Carlssona201c4c2011-03-20 17:59:11 +00003001
Anders Carlsson1f7c7ba2011-03-20 19:51:13 +00003002 // Checking that the function has the right return type, the right number of
3003 // parameters and that they all have pointer types should be enough.
3004 if (!FTy->getReturnType()->isIntegerTy() ||
3005 FTy->getNumParams() != 3 ||
Anders Carlssona201c4c2011-03-20 17:59:11 +00003006 !FTy->getParamType(0)->isPointerTy() ||
3007 !FTy->getParamType(1)->isPointerTy() ||
3008 !FTy->getParamType(2)->isPointerTy())
3009 return 0;
3010
3011 return Fn;
3012}
3013
3014/// cxxDtorIsEmpty - Returns whether the given function is an empty C++
3015/// destructor and can therefore be eliminated.
3016/// Note that we assume that other optimization passes have already simplified
3017/// the code so we only look for a function with a single basic block, where
Benjamin Kramerc1322a12012-02-09 16:28:15 +00003018/// the only allowed instructions are 'ret', 'call' to an empty C++ dtor and
3019/// other side-effect free instructions.
Anders Carlsson372ec6a2011-03-20 20:16:43 +00003020static bool cxxDtorIsEmpty(const Function &Fn,
3021 SmallPtrSet<const Function *, 8> &CalledFunctions) {
Anders Carlsson1f7c7ba2011-03-20 19:51:13 +00003022 // FIXME: We could eliminate C++ destructors if they're readonly/readnone and
Nick Lewycky35ee1c92011-03-21 02:26:01 +00003023 // nounwind, but that doesn't seem worth doing.
Anders Carlsson1f7c7ba2011-03-20 19:51:13 +00003024 if (Fn.isDeclaration())
3025 return false;
Anders Carlssona201c4c2011-03-20 17:59:11 +00003026
3027 if (++Fn.begin() != Fn.end())
3028 return false;
3029
3030 const BasicBlock &EntryBlock = Fn.getEntryBlock();
3031 for (BasicBlock::const_iterator I = EntryBlock.begin(), E = EntryBlock.end();
3032 I != E; ++I) {
3033 if (const CallInst *CI = dyn_cast<CallInst>(I)) {
Anders Carlssonb12caf32011-03-21 14:54:40 +00003034 // Ignore debug intrinsics.
3035 if (isa<DbgInfoIntrinsic>(CI))
3036 continue;
3037
Anders Carlssona201c4c2011-03-20 17:59:11 +00003038 const Function *CalledFn = CI->getCalledFunction();
3039
3040 if (!CalledFn)
3041 return false;
3042
Anders Carlsson807bc2a2011-03-22 03:21:01 +00003043 SmallPtrSet<const Function *, 8> NewCalledFunctions(CalledFunctions);
3044
Anders Carlsson1f7c7ba2011-03-20 19:51:13 +00003045 // Don't treat recursive functions as empty.
Anders Carlsson807bc2a2011-03-22 03:21:01 +00003046 if (!NewCalledFunctions.insert(CalledFn))
Anders Carlsson1f7c7ba2011-03-20 19:51:13 +00003047 return false;
3048
Anders Carlsson807bc2a2011-03-22 03:21:01 +00003049 if (!cxxDtorIsEmpty(*CalledFn, NewCalledFunctions))
Anders Carlssona201c4c2011-03-20 17:59:11 +00003050 return false;
3051 } else if (isa<ReturnInst>(*I))
Benjamin Kramerd4692742012-02-09 14:26:06 +00003052 return true; // We're done.
3053 else if (I->mayHaveSideEffects())
3054 return false; // Destructor with side effects, bail.
Anders Carlssona201c4c2011-03-20 17:59:11 +00003055 }
3056
3057 return false;
3058}
3059
3060bool GlobalOpt::OptimizeEmptyGlobalCXXDtors(Function *CXAAtExitFn) {
3061 /// Itanium C++ ABI p3.3.5:
3062 ///
3063 /// After constructing a global (or local static) object, that will require
3064 /// destruction on exit, a termination function is registered as follows:
3065 ///
3066 /// extern "C" int __cxa_atexit ( void (*f)(void *), void *p, void *d );
3067 ///
3068 /// This registration, e.g. __cxa_atexit(f,p,d), is intended to cause the
3069 /// call f(p) when DSO d is unloaded, before all such termination calls
3070 /// registered before this one. It returns zero if registration is
Nick Lewycky35ee1c92011-03-21 02:26:01 +00003071 /// successful, nonzero on failure.
Anders Carlssona201c4c2011-03-20 17:59:11 +00003072
3073 // This pass will look for calls to __cxa_atexit where the function is trivial
3074 // and remove them.
3075 bool Changed = false;
3076
3077 for (Function::use_iterator I = CXAAtExitFn->use_begin(),
3078 E = CXAAtExitFn->use_end(); I != E;) {
Anders Carlsson4f735ca2011-03-20 20:21:33 +00003079 // We're only interested in calls. Theoretically, we could handle invoke
3080 // instructions as well, but neither llvm-gcc nor clang generate invokes
3081 // to __cxa_atexit.
Anders Carlssonb12caf32011-03-21 14:54:40 +00003082 CallInst *CI = dyn_cast<CallInst>(*I++);
3083 if (!CI)
Anders Carlsson4f735ca2011-03-20 20:21:33 +00003084 continue;
3085
Anders Carlssona201c4c2011-03-20 17:59:11 +00003086 Function *DtorFn =
Anders Carlssonb12caf32011-03-21 14:54:40 +00003087 dyn_cast<Function>(CI->getArgOperand(0)->stripPointerCasts());
Anders Carlssona201c4c2011-03-20 17:59:11 +00003088 if (!DtorFn)
3089 continue;
3090
Anders Carlsson372ec6a2011-03-20 20:16:43 +00003091 SmallPtrSet<const Function *, 8> CalledFunctions;
3092 if (!cxxDtorIsEmpty(*DtorFn, CalledFunctions))
Anders Carlssona201c4c2011-03-20 17:59:11 +00003093 continue;
3094
3095 // Just remove the call.
Anders Carlssonb12caf32011-03-21 14:54:40 +00003096 CI->replaceAllUsesWith(Constant::getNullValue(CI->getType()));
3097 CI->eraseFromParent();
Anders Carlsson1f7c7ba2011-03-20 19:51:13 +00003098
Anders Carlssona201c4c2011-03-20 17:59:11 +00003099 ++NumCXXDtorsRemoved;
3100
3101 Changed |= true;
3102 }
3103
3104 return Changed;
3105}
3106
Chris Lattner7a90b682004-10-07 04:16:33 +00003107bool GlobalOpt::runOnModule(Module &M) {
Chris Lattner079236d2004-02-25 21:34:36 +00003108 bool Changed = false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00003109
Nick Lewycky6a577f82012-02-12 01:13:18 +00003110 TD = getAnalysisIfAvailable<TargetData>();
Nick Lewycky6a7df9a2012-02-12 02:15:20 +00003111 TLI = &getAnalysis<TargetLibraryInfo>();
Nick Lewycky6a577f82012-02-12 01:13:18 +00003112
Chris Lattnerb1ab4582005-09-26 01:43:45 +00003113 // Try to find the llvm.globalctors list.
3114 GlobalVariable *GlobalCtors = FindGlobalCtors(M);
Chris Lattner7a90b682004-10-07 04:16:33 +00003115
Nick Lewycky6a7df9a2012-02-12 02:15:20 +00003116 Function *CXAAtExitFn = FindCXAAtExit(M, TLI);
Anders Carlssona201c4c2011-03-20 17:59:11 +00003117
Chris Lattner7a90b682004-10-07 04:16:33 +00003118 bool LocalChange = true;
3119 while (LocalChange) {
3120 LocalChange = false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00003121
Chris Lattnerb1ab4582005-09-26 01:43:45 +00003122 // Delete functions that are trivially dead, ccc -> fastcc
3123 LocalChange |= OptimizeFunctions(M);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00003124
Chris Lattnerb1ab4582005-09-26 01:43:45 +00003125 // Optimize global_ctors list.
3126 if (GlobalCtors)
3127 LocalChange |= OptimizeGlobalCtorsList(GlobalCtors);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00003128
Chris Lattnerb1ab4582005-09-26 01:43:45 +00003129 // Optimize non-address-taken globals.
3130 LocalChange |= OptimizeGlobalVars(M);
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00003131
3132 // Resolve aliases, when possible.
Duncan Sandsfc5940d2009-03-06 10:21:56 +00003133 LocalChange |= OptimizeGlobalAliases(M);
Anders Carlssona201c4c2011-03-20 17:59:11 +00003134
3135 // Try to remove trivial global destructors.
3136 if (CXAAtExitFn)
3137 LocalChange |= OptimizeEmptyGlobalCXXDtors(CXAAtExitFn);
3138
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00003139 Changed |= LocalChange;
Chris Lattner7a90b682004-10-07 04:16:33 +00003140 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00003141
Chris Lattnerb1ab4582005-09-26 01:43:45 +00003142 // TODO: Move all global ctors functions to the end of the module for code
3143 // layout.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00003144
Chris Lattner079236d2004-02-25 21:34:36 +00003145 return Changed;
3146}