blob: b888e9598200f1deddee79c3a60d46c66bd72eeb [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.
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000349static bool IsSafeComputationToRemove(Value *V, const TargetLibraryInfo *TLI) {
Nick Lewycky8899d5c2012-07-24 07:21:08 +0000350 do {
351 if (isa<Constant>(V))
352 return true;
353 if (!V->hasOneUse())
354 return false;
Nick Lewyckyb8cd66b2012-07-25 21:19:40 +0000355 if (isa<LoadInst>(V) || isa<InvokeInst>(V) || isa<Argument>(V) ||
356 isa<GlobalValue>(V))
Nick Lewycky8899d5c2012-07-24 07:21:08 +0000357 return false;
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000358 if (isAllocationFn(V, TLI))
Nick Lewycky8899d5c2012-07-24 07:21:08 +0000359 return true;
360
361 Instruction *I = cast<Instruction>(V);
362 if (I->mayHaveSideEffects())
363 return false;
364 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
365 if (!GEP->hasAllConstantIndices())
366 return false;
367 } else if (I->getNumOperands() != 1) {
368 return false;
369 }
370
371 V = I->getOperand(0);
372 } while (1);
373}
374
375/// CleanupPointerRootUsers - This GV is a pointer root. Loop over all users
376/// of the global and clean up any that obviously don't assign the global a
377/// value that isn't dynamically allocated.
378///
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000379static bool CleanupPointerRootUsers(GlobalVariable *GV,
380 const TargetLibraryInfo *TLI) {
Nick Lewycky8899d5c2012-07-24 07:21:08 +0000381 // A brief explanation of leak checkers. The goal is to find bugs where
382 // pointers are forgotten, causing an accumulating growth in memory
383 // usage over time. The common strategy for leak checkers is to whitelist the
384 // memory pointed to by globals at exit. This is popular because it also
385 // solves another problem where the main thread of a C++ program may shut down
386 // before other threads that are still expecting to use those globals. To
387 // handle that case, we expect the program may create a singleton and never
388 // destroy it.
389
390 bool Changed = false;
391
392 // If Dead[n].first is the only use of a malloc result, we can delete its
393 // chain of computation and the store to the global in Dead[n].second.
394 SmallVector<std::pair<Instruction *, Instruction *>, 32> Dead;
395
396 // Constants can't be pointers to dynamically allocated memory.
397 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end();
398 UI != E;) {
399 User *U = *UI++;
400 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
401 Value *V = SI->getValueOperand();
402 if (isa<Constant>(V)) {
403 Changed = true;
404 SI->eraseFromParent();
405 } else if (Instruction *I = dyn_cast<Instruction>(V)) {
406 if (I->hasOneUse())
407 Dead.push_back(std::make_pair(I, SI));
408 }
409 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(U)) {
410 if (isa<Constant>(MSI->getValue())) {
411 Changed = true;
412 MSI->eraseFromParent();
413 } else if (Instruction *I = dyn_cast<Instruction>(MSI->getValue())) {
414 if (I->hasOneUse())
415 Dead.push_back(std::make_pair(I, MSI));
416 }
417 } else if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(U)) {
418 GlobalVariable *MemSrc = dyn_cast<GlobalVariable>(MTI->getSource());
419 if (MemSrc && MemSrc->isConstant()) {
420 Changed = true;
421 MTI->eraseFromParent();
422 } else if (Instruction *I = dyn_cast<Instruction>(MemSrc)) {
423 if (I->hasOneUse())
424 Dead.push_back(std::make_pair(I, MTI));
425 }
426 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
427 if (CE->use_empty()) {
428 CE->destroyConstant();
429 Changed = true;
430 }
431 } else if (Constant *C = dyn_cast<Constant>(U)) {
432 if (SafeToDestroyConstant(C)) {
433 C->destroyConstant();
434 // This could have invalidated UI, start over from scratch.
435 Dead.clear();
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000436 CleanupPointerRootUsers(GV, TLI);
Nick Lewycky8899d5c2012-07-24 07:21:08 +0000437 return true;
438 }
439 }
440 }
441
442 for (int i = 0, e = Dead.size(); i != e; ++i) {
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000443 if (IsSafeComputationToRemove(Dead[i].first, TLI)) {
Nick Lewycky8899d5c2012-07-24 07:21:08 +0000444 Dead[i].second->eraseFromParent();
445 Instruction *I = Dead[i].first;
446 do {
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000447 if (isAllocationFn(I, TLI))
Nick Lewycky952f5d52012-07-24 21:33:00 +0000448 break;
Nick Lewycky8899d5c2012-07-24 07:21:08 +0000449 Instruction *J = dyn_cast<Instruction>(I->getOperand(0));
450 if (!J)
451 break;
452 I->eraseFromParent();
453 I = J;
Nick Lewycky952f5d52012-07-24 21:33:00 +0000454 } while (1);
Nick Lewycky8899d5c2012-07-24 07:21:08 +0000455 I->eraseFromParent();
456 }
457 }
458
459 return Changed;
460}
461
Chris Lattnere47ba742004-10-06 20:57:02 +0000462/// CleanupConstantGlobalUsers - We just marked GV constant. Loop over all
463/// users of the global, cleaning up the obvious ones. This is largely just a
Chris Lattner031955d2004-10-10 16:43:46 +0000464/// quick scan over the use list to clean up the easy and obvious cruft. This
465/// returns true if it made a change.
Nick Lewycky6a577f82012-02-12 01:13:18 +0000466static bool CleanupConstantGlobalUsers(Value *V, Constant *Init,
467 TargetData *TD, TargetLibraryInfo *TLI) {
Chris Lattner031955d2004-10-10 16:43:46 +0000468 bool Changed = false;
Chris Lattner7a90b682004-10-07 04:16:33 +0000469 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;) {
470 User *U = *UI++;
Misha Brukmanfd939082005-04-21 23:48:37 +0000471
Chris Lattner7a90b682004-10-07 04:16:33 +0000472 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
Chris Lattner35c81b02005-02-27 18:58:52 +0000473 if (Init) {
474 // Replace the load with the initializer.
475 LI->replaceAllUsesWith(Init);
476 LI->eraseFromParent();
477 Changed = true;
478 }
Chris Lattner7a90b682004-10-07 04:16:33 +0000479 } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
Chris Lattnere47ba742004-10-06 20:57:02 +0000480 // Store must be unreachable or storing Init into the global.
Chris Lattner7a7ed022004-10-16 18:09:00 +0000481 SI->eraseFromParent();
Chris Lattner031955d2004-10-10 16:43:46 +0000482 Changed = true;
Chris Lattner7a90b682004-10-07 04:16:33 +0000483 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
484 if (CE->getOpcode() == Instruction::GetElementPtr) {
Chris Lattneraae4a1c2005-09-26 07:34:35 +0000485 Constant *SubInit = 0;
486 if (Init)
Dan Gohmanc6f69e92009-10-05 16:36:26 +0000487 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
Nick Lewycky6a577f82012-02-12 01:13:18 +0000488 Changed |= CleanupConstantGlobalUsers(CE, SubInit, TD, TLI);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000489 } else if (CE->getOpcode() == Instruction::BitCast &&
Duncan Sands1df98592010-02-16 11:11:14 +0000490 CE->getType()->isPointerTy()) {
Chris Lattner35c81b02005-02-27 18:58:52 +0000491 // Pointer cast, delete any stores and memsets to the global.
Nick Lewycky6a577f82012-02-12 01:13:18 +0000492 Changed |= CleanupConstantGlobalUsers(CE, 0, TD, TLI);
Chris Lattner35c81b02005-02-27 18:58:52 +0000493 }
494
495 if (CE->use_empty()) {
496 CE->destroyConstant();
497 Changed = true;
Chris Lattner7a90b682004-10-07 04:16:33 +0000498 }
499 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
Chris Lattner7b52fe72007-11-09 17:33:02 +0000500 // Do not transform "gepinst (gep constexpr (GV))" here, because forming
501 // "gepconstexpr (gep constexpr (GV))" will cause the two gep's to fold
502 // and will invalidate our notion of what Init is.
Chris Lattner19450242007-11-13 21:46:23 +0000503 Constant *SubInit = 0;
Chris Lattner7b52fe72007-11-09 17:33:02 +0000504 if (!isa<ConstantExpr>(GEP->getOperand(0))) {
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000505 ConstantExpr *CE =
Nick Lewycky6a577f82012-02-12 01:13:18 +0000506 dyn_cast_or_null<ConstantExpr>(ConstantFoldInstruction(GEP, TD, TLI));
Chris Lattner7b52fe72007-11-09 17:33:02 +0000507 if (Init && CE && CE->getOpcode() == Instruction::GetElementPtr)
Dan Gohmanc6f69e92009-10-05 16:36:26 +0000508 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
Benjamin Kramerc1ea16e2012-03-28 14:50:09 +0000509
510 // If the initializer is an all-null value and we have an inbounds GEP,
511 // we already know what the result of any load from that GEP is.
512 // TODO: Handle splats.
513 if (Init && isa<ConstantAggregateZero>(Init) && GEP->isInBounds())
514 SubInit = Constant::getNullValue(GEP->getType()->getElementType());
Chris Lattner7b52fe72007-11-09 17:33:02 +0000515 }
Nick Lewycky6a577f82012-02-12 01:13:18 +0000516 Changed |= CleanupConstantGlobalUsers(GEP, SubInit, TD, TLI);
Chris Lattnerc4d81b02004-10-10 16:47:33 +0000517
Chris Lattner031955d2004-10-10 16:43:46 +0000518 if (GEP->use_empty()) {
Chris Lattner7a7ed022004-10-16 18:09:00 +0000519 GEP->eraseFromParent();
Chris Lattner031955d2004-10-10 16:43:46 +0000520 Changed = true;
521 }
Chris Lattner35c81b02005-02-27 18:58:52 +0000522 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U)) { // memset/cpy/mv
523 if (MI->getRawDest() == V) {
524 MI->eraseFromParent();
525 Changed = true;
526 }
527
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000528 } else if (Constant *C = dyn_cast<Constant>(U)) {
529 // If we have a chain of dead constantexprs or other things dangling from
530 // us, and if they are all dead, nuke them without remorse.
Jay Foade3acf152009-06-09 21:37:11 +0000531 if (SafeToDestroyConstant(C)) {
Devang Patel743cdf82009-03-06 01:37:41 +0000532 C->destroyConstant();
Chris Lattner35c81b02005-02-27 18:58:52 +0000533 // This could have invalidated UI, start over from scratch.
Nick Lewycky6a577f82012-02-12 01:13:18 +0000534 CleanupConstantGlobalUsers(V, Init, TD, TLI);
Chris Lattner031955d2004-10-10 16:43:46 +0000535 return true;
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000536 }
Chris Lattnere47ba742004-10-06 20:57:02 +0000537 }
538 }
Chris Lattner031955d2004-10-10 16:43:46 +0000539 return Changed;
Chris Lattnere47ba742004-10-06 20:57:02 +0000540}
541
Chris Lattner941db492008-01-14 02:09:12 +0000542/// isSafeSROAElementUse - Return true if the specified instruction is a safe
543/// user of a derived expression from a global that we want to SROA.
544static bool isSafeSROAElementUse(Value *V) {
545 // We might have a dead and dangling constant hanging off of here.
546 if (Constant *C = dyn_cast<Constant>(V))
Jay Foade3acf152009-06-09 21:37:11 +0000547 return SafeToDestroyConstant(C);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000548
Chris Lattner941db492008-01-14 02:09:12 +0000549 Instruction *I = dyn_cast<Instruction>(V);
550 if (!I) return false;
551
552 // Loads are ok.
553 if (isa<LoadInst>(I)) return true;
554
555 // Stores *to* the pointer are ok.
556 if (StoreInst *SI = dyn_cast<StoreInst>(I))
557 return SI->getOperand(0) != V;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000558
Chris Lattner941db492008-01-14 02:09:12 +0000559 // Otherwise, it must be a GEP.
560 GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I);
561 if (GEPI == 0) return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000562
Chris Lattner941db492008-01-14 02:09:12 +0000563 if (GEPI->getNumOperands() < 3 || !isa<Constant>(GEPI->getOperand(1)) ||
564 !cast<Constant>(GEPI->getOperand(1))->isNullValue())
565 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000566
Chris Lattner941db492008-01-14 02:09:12 +0000567 for (Value::use_iterator I = GEPI->use_begin(), E = GEPI->use_end();
568 I != E; ++I)
569 if (!isSafeSROAElementUse(*I))
570 return false;
Chris Lattner727c2102008-01-14 01:31:05 +0000571 return true;
572}
573
Chris Lattner941db492008-01-14 02:09:12 +0000574
575/// IsUserOfGlobalSafeForSRA - U is a direct user of the specified global value.
576/// Look at it and its uses and decide whether it is safe to SROA this global.
577///
578static bool IsUserOfGlobalSafeForSRA(User *U, GlobalValue *GV) {
579 // The user of the global must be a GEP Inst or a ConstantExpr GEP.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000580 if (!isa<GetElementPtrInst>(U) &&
581 (!isa<ConstantExpr>(U) ||
Chris Lattner941db492008-01-14 02:09:12 +0000582 cast<ConstantExpr>(U)->getOpcode() != Instruction::GetElementPtr))
583 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000584
Chris Lattner941db492008-01-14 02:09:12 +0000585 // Check to see if this ConstantExpr GEP is SRA'able. In particular, we
586 // don't like < 3 operand CE's, and we don't like non-constant integer
587 // indices. This enforces that all uses are 'gep GV, 0, C, ...' for some
588 // value of C.
589 if (U->getNumOperands() < 3 || !isa<Constant>(U->getOperand(1)) ||
590 !cast<Constant>(U->getOperand(1))->isNullValue() ||
591 !isa<ConstantInt>(U->getOperand(2)))
592 return false;
593
594 gep_type_iterator GEPI = gep_type_begin(U), E = gep_type_end(U);
595 ++GEPI; // Skip over the pointer index.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000596
Chris Lattner941db492008-01-14 02:09:12 +0000597 // If this is a use of an array allocation, do a bit more checking for sanity.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000598 if (ArrayType *AT = dyn_cast<ArrayType>(*GEPI)) {
Chris Lattner941db492008-01-14 02:09:12 +0000599 uint64_t NumElements = AT->getNumElements();
600 ConstantInt *Idx = cast<ConstantInt>(U->getOperand(2));
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000601
Chris Lattner941db492008-01-14 02:09:12 +0000602 // Check to make sure that index falls within the array. If not,
603 // something funny is going on, so we won't do the optimization.
604 //
605 if (Idx->getZExtValue() >= NumElements)
606 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000607
Chris Lattner941db492008-01-14 02:09:12 +0000608 // We cannot scalar repl this level of the array unless any array
609 // sub-indices are in-range constants. In particular, consider:
610 // A[0][i]. We cannot know that the user isn't doing invalid things like
611 // allowing i to index an out-of-range subscript that accesses A[1].
612 //
613 // Scalar replacing *just* the outer index of the array is probably not
614 // going to be a win anyway, so just give up.
615 for (++GEPI; // Skip array index.
Dan Gohman6874a2a2009-08-18 14:58:19 +0000616 GEPI != E;
Chris Lattner941db492008-01-14 02:09:12 +0000617 ++GEPI) {
618 uint64_t NumElements;
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000619 if (ArrayType *SubArrayTy = dyn_cast<ArrayType>(*GEPI))
Chris Lattner941db492008-01-14 02:09:12 +0000620 NumElements = SubArrayTy->getNumElements();
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000621 else if (VectorType *SubVectorTy = dyn_cast<VectorType>(*GEPI))
Dan Gohman6874a2a2009-08-18 14:58:19 +0000622 NumElements = SubVectorTy->getNumElements();
623 else {
Duncan Sands1df98592010-02-16 11:11:14 +0000624 assert((*GEPI)->isStructTy() &&
Dan Gohman6874a2a2009-08-18 14:58:19 +0000625 "Indexed GEP type is not array, vector, or struct!");
626 continue;
627 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000628
Chris Lattner941db492008-01-14 02:09:12 +0000629 ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPI.getOperand());
630 if (!IdxVal || IdxVal->getZExtValue() >= NumElements)
631 return false;
632 }
633 }
634
635 for (Value::use_iterator I = U->use_begin(), E = U->use_end(); I != E; ++I)
636 if (!isSafeSROAElementUse(*I))
637 return false;
638 return true;
639}
640
641/// GlobalUsersSafeToSRA - Look at all uses of the global and decide whether it
642/// is safe for us to perform this transformation.
643///
644static bool GlobalUsersSafeToSRA(GlobalValue *GV) {
645 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end();
646 UI != E; ++UI) {
647 if (!IsUserOfGlobalSafeForSRA(*UI, GV))
648 return false;
649 }
650 return true;
651}
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000652
Chris Lattner941db492008-01-14 02:09:12 +0000653
Chris Lattner670c8892004-10-08 17:32:09 +0000654/// SRAGlobal - Perform scalar replacement of aggregates on the specified global
655/// variable. This opens the door for other optimizations by exposing the
656/// behavior of the program in a more fine-grained way. We have determined that
657/// this transformation is safe already. We return the first global variable we
658/// insert so that the caller can reprocess it.
Chris Lattner7b550cc2009-11-06 04:27:31 +0000659static GlobalVariable *SRAGlobal(GlobalVariable *GV, const TargetData &TD) {
Chris Lattner727c2102008-01-14 01:31:05 +0000660 // Make sure this global only has simple uses that we can SRA.
Chris Lattner941db492008-01-14 02:09:12 +0000661 if (!GlobalUsersSafeToSRA(GV))
Chris Lattner727c2102008-01-14 01:31:05 +0000662 return 0;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000663
Rafael Espindolabb46f522009-01-15 20:18:42 +0000664 assert(GV->hasLocalLinkage() && !GV->isConstant());
Chris Lattner670c8892004-10-08 17:32:09 +0000665 Constant *Init = GV->getInitializer();
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000666 Type *Ty = Init->getType();
Misha Brukmanfd939082005-04-21 23:48:37 +0000667
Chris Lattner670c8892004-10-08 17:32:09 +0000668 std::vector<GlobalVariable*> NewGlobals;
669 Module::GlobalListType &Globals = GV->getParent()->getGlobalList();
670
Chris Lattner998182b2008-04-26 07:40:11 +0000671 // Get the alignment of the global, either explicit or target-specific.
672 unsigned StartAlignment = GV->getAlignment();
673 if (StartAlignment == 0)
674 StartAlignment = TD.getABITypeAlignment(GV->getType());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000675
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000676 if (StructType *STy = dyn_cast<StructType>(Ty)) {
Chris Lattner670c8892004-10-08 17:32:09 +0000677 NewGlobals.reserve(STy->getNumElements());
Chris Lattner998182b2008-04-26 07:40:11 +0000678 const StructLayout &Layout = *TD.getStructLayout(STy);
Chris Lattner670c8892004-10-08 17:32:09 +0000679 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
Chris Lattnera1f00f42012-01-25 06:48:06 +0000680 Constant *In = Init->getAggregateElement(i);
Chris Lattner670c8892004-10-08 17:32:09 +0000681 assert(In && "Couldn't get element of initializer?");
Chris Lattner7b550cc2009-11-06 04:27:31 +0000682 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(i), false,
Chris Lattner670c8892004-10-08 17:32:09 +0000683 GlobalVariable::InternalLinkage,
Daniel Dunbarfe09b202009-07-30 17:37:43 +0000684 In, GV->getName()+"."+Twine(i),
Hans Wennborgce718ff2012-06-23 11:37:03 +0000685 GV->getThreadLocalMode(),
Owen Anderson3d29df32009-07-08 01:26:06 +0000686 GV->getType()->getAddressSpace());
Chris Lattner670c8892004-10-08 17:32:09 +0000687 Globals.insert(GV, NGV);
688 NewGlobals.push_back(NGV);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000689
Chris Lattner998182b2008-04-26 07:40:11 +0000690 // Calculate the known alignment of the field. If the original aggregate
691 // had 256 byte alignment for example, something might depend on that:
692 // propagate info to each field.
693 uint64_t FieldOffset = Layout.getElementOffset(i);
694 unsigned NewAlign = (unsigned)MinAlign(StartAlignment, FieldOffset);
695 if (NewAlign > TD.getABITypeAlignment(STy->getElementType(i)))
696 NGV->setAlignment(NewAlign);
Chris Lattner670c8892004-10-08 17:32:09 +0000697 }
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000698 } else if (SequentialType *STy = dyn_cast<SequentialType>(Ty)) {
Chris Lattner670c8892004-10-08 17:32:09 +0000699 unsigned NumElements = 0;
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000700 if (ArrayType *ATy = dyn_cast<ArrayType>(STy))
Chris Lattner670c8892004-10-08 17:32:09 +0000701 NumElements = ATy->getNumElements();
Chris Lattner670c8892004-10-08 17:32:09 +0000702 else
Chris Lattner998182b2008-04-26 07:40:11 +0000703 NumElements = cast<VectorType>(STy)->getNumElements();
Chris Lattner670c8892004-10-08 17:32:09 +0000704
Chris Lattner1f21ef12005-02-23 16:53:04 +0000705 if (NumElements > 16 && GV->hasNUsesOrMore(16))
Chris Lattnerd514d822005-02-01 01:23:31 +0000706 return 0; // It's not worth it.
Chris Lattner670c8892004-10-08 17:32:09 +0000707 NewGlobals.reserve(NumElements);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000708
Duncan Sands777d2302009-05-09 07:06:46 +0000709 uint64_t EltSize = TD.getTypeAllocSize(STy->getElementType());
Chris Lattner998182b2008-04-26 07:40:11 +0000710 unsigned EltAlign = TD.getABITypeAlignment(STy->getElementType());
Chris Lattner670c8892004-10-08 17:32:09 +0000711 for (unsigned i = 0, e = NumElements; i != e; ++i) {
Chris Lattnera1f00f42012-01-25 06:48:06 +0000712 Constant *In = Init->getAggregateElement(i);
Chris Lattner670c8892004-10-08 17:32:09 +0000713 assert(In && "Couldn't get element of initializer?");
714
Chris Lattner7b550cc2009-11-06 04:27:31 +0000715 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(), false,
Chris Lattner670c8892004-10-08 17:32:09 +0000716 GlobalVariable::InternalLinkage,
Daniel Dunbarfe09b202009-07-30 17:37:43 +0000717 In, GV->getName()+"."+Twine(i),
Hans Wennborgce718ff2012-06-23 11:37:03 +0000718 GV->getThreadLocalMode(),
Owen Andersone9b11b42009-07-08 19:03:57 +0000719 GV->getType()->getAddressSpace());
Chris Lattner670c8892004-10-08 17:32:09 +0000720 Globals.insert(GV, NGV);
721 NewGlobals.push_back(NGV);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000722
Chris Lattner998182b2008-04-26 07:40:11 +0000723 // Calculate the known alignment of the field. If the original aggregate
724 // had 256 byte alignment for example, something might depend on that:
725 // propagate info to each field.
726 unsigned NewAlign = (unsigned)MinAlign(StartAlignment, EltSize*i);
727 if (NewAlign > EltAlign)
728 NGV->setAlignment(NewAlign);
Chris Lattner670c8892004-10-08 17:32:09 +0000729 }
730 }
731
732 if (NewGlobals.empty())
733 return 0;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000734
David Greene3215b0e2010-01-05 01:28:05 +0000735 DEBUG(dbgs() << "PERFORMING GLOBAL SRA ON: " << *GV);
Chris Lattner30ba5692004-10-11 05:54:41 +0000736
Chris Lattner7b550cc2009-11-06 04:27:31 +0000737 Constant *NullInt =Constant::getNullValue(Type::getInt32Ty(GV->getContext()));
Chris Lattner670c8892004-10-08 17:32:09 +0000738
739 // Loop over all of the uses of the global, replacing the constantexpr geps,
740 // with smaller constantexpr geps or direct references.
741 while (!GV->use_empty()) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000742 User *GEP = GV->use_back();
743 assert(((isa<ConstantExpr>(GEP) &&
744 cast<ConstantExpr>(GEP)->getOpcode()==Instruction::GetElementPtr)||
745 isa<GetElementPtrInst>(GEP)) && "NonGEP CE's are not SRAable!");
Misha Brukmanfd939082005-04-21 23:48:37 +0000746
Chris Lattner670c8892004-10-08 17:32:09 +0000747 // Ignore the 1th operand, which has to be zero or else the program is quite
748 // broken (undefined). Get the 2nd operand, which is the structure or array
749 // index.
Reid Spencerb83eb642006-10-20 07:07:24 +0000750 unsigned Val = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
Chris Lattner670c8892004-10-08 17:32:09 +0000751 if (Val >= NewGlobals.size()) Val = 0; // Out of bound array access.
752
Chris Lattner30ba5692004-10-11 05:54:41 +0000753 Value *NewPtr = NewGlobals[Val];
Chris Lattner670c8892004-10-08 17:32:09 +0000754
755 // Form a shorter GEP if needed.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000756 if (GEP->getNumOperands() > 3) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000757 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEP)) {
Chris Lattner55eb1c42007-01-31 04:40:53 +0000758 SmallVector<Constant*, 8> Idxs;
Chris Lattner30ba5692004-10-11 05:54:41 +0000759 Idxs.push_back(NullInt);
760 for (unsigned i = 3, e = CE->getNumOperands(); i != e; ++i)
761 Idxs.push_back(CE->getOperand(i));
Jay Foaddab3d292011-07-21 14:31:17 +0000762 NewPtr = ConstantExpr::getGetElementPtr(cast<Constant>(NewPtr), Idxs);
Chris Lattner30ba5692004-10-11 05:54:41 +0000763 } else {
764 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(GEP);
Chris Lattner699d1442007-01-31 19:59:55 +0000765 SmallVector<Value*, 8> Idxs;
Chris Lattner30ba5692004-10-11 05:54:41 +0000766 Idxs.push_back(NullInt);
767 for (unsigned i = 3, e = GEPI->getNumOperands(); i != e; ++i)
768 Idxs.push_back(GEPI->getOperand(i));
Jay Foada9203102011-07-25 09:48:08 +0000769 NewPtr = GetElementPtrInst::Create(NewPtr, Idxs,
Daniel Dunbarfe09b202009-07-30 17:37:43 +0000770 GEPI->getName()+"."+Twine(Val),GEPI);
Chris Lattner30ba5692004-10-11 05:54:41 +0000771 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000772 }
Chris Lattner30ba5692004-10-11 05:54:41 +0000773 GEP->replaceAllUsesWith(NewPtr);
774
775 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(GEP))
Chris Lattner7a7ed022004-10-16 18:09:00 +0000776 GEPI->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +0000777 else
778 cast<ConstantExpr>(GEP)->destroyConstant();
Chris Lattner670c8892004-10-08 17:32:09 +0000779 }
780
Chris Lattnere40e2d12004-10-08 20:25:55 +0000781 // Delete the old global, now that it is dead.
782 Globals.erase(GV);
Chris Lattner670c8892004-10-08 17:32:09 +0000783 ++NumSRA;
Chris Lattner30ba5692004-10-11 05:54:41 +0000784
785 // Loop over the new globals array deleting any globals that are obviously
786 // dead. This can arise due to scalarization of a structure or an array that
787 // has elements that are dead.
788 unsigned FirstGlobal = 0;
789 for (unsigned i = 0, e = NewGlobals.size(); i != e; ++i)
790 if (NewGlobals[i]->use_empty()) {
791 Globals.erase(NewGlobals[i]);
792 if (FirstGlobal == i) ++FirstGlobal;
793 }
794
795 return FirstGlobal != NewGlobals.size() ? NewGlobals[FirstGlobal] : 0;
Chris Lattner670c8892004-10-08 17:32:09 +0000796}
797
Chris Lattner9b34a612004-10-09 21:48:45 +0000798/// AllUsesOfValueWillTrapIfNull - Return true if all users of the specified
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000799/// value will trap if the value is dynamically null. PHIs keeps track of any
Chris Lattner81686182007-09-13 16:30:19 +0000800/// phi nodes we've seen to avoid reprocessing them.
Gabor Greif6ce02b52010-04-06 19:24:18 +0000801static bool AllUsesOfValueWillTrapIfNull(const Value *V,
802 SmallPtrSet<const PHINode*, 8> &PHIs) {
803 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;
Gabor Greifa01d6db2010-04-06 19:14:05 +0000804 ++UI) {
Gabor Greif6ce02b52010-04-06 19:24:18 +0000805 const User *U = *UI;
Gabor Greifa01d6db2010-04-06 19:14:05 +0000806
807 if (isa<LoadInst>(U)) {
Chris Lattner9b34a612004-10-09 21:48:45 +0000808 // Will trap.
Gabor Greif6ce02b52010-04-06 19:24:18 +0000809 } else if (const StoreInst *SI = dyn_cast<StoreInst>(U)) {
Chris Lattner9b34a612004-10-09 21:48:45 +0000810 if (SI->getOperand(0) == V) {
Gabor Greifa01d6db2010-04-06 19:14:05 +0000811 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner9b34a612004-10-09 21:48:45 +0000812 return false; // Storing the value.
813 }
Gabor Greif6ce02b52010-04-06 19:24:18 +0000814 } else if (const CallInst *CI = dyn_cast<CallInst>(U)) {
Gabor Greif654c06f2010-03-20 21:00:25 +0000815 if (CI->getCalledValue() != V) {
Gabor Greifa01d6db2010-04-06 19:14:05 +0000816 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner9b34a612004-10-09 21:48:45 +0000817 return false; // Not calling the ptr
818 }
Gabor Greif6ce02b52010-04-06 19:24:18 +0000819 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(U)) {
Gabor Greif654c06f2010-03-20 21:00:25 +0000820 if (II->getCalledValue() != V) {
Gabor Greifa01d6db2010-04-06 19:14:05 +0000821 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner9b34a612004-10-09 21:48:45 +0000822 return false; // Not calling the ptr
823 }
Gabor Greif6ce02b52010-04-06 19:24:18 +0000824 } else if (const BitCastInst *CI = dyn_cast<BitCastInst>(U)) {
Chris Lattner81686182007-09-13 16:30:19 +0000825 if (!AllUsesOfValueWillTrapIfNull(CI, PHIs)) return false;
Gabor Greif6ce02b52010-04-06 19:24:18 +0000826 } else if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
Chris Lattner81686182007-09-13 16:30:19 +0000827 if (!AllUsesOfValueWillTrapIfNull(GEPI, PHIs)) return false;
Gabor Greif6ce02b52010-04-06 19:24:18 +0000828 } else if (const PHINode *PN = dyn_cast<PHINode>(U)) {
Chris Lattner81686182007-09-13 16:30:19 +0000829 // If we've already seen this phi node, ignore it, it has already been
830 // checked.
Jakob Stoklund Olesenb489d0f2010-01-29 23:54:14 +0000831 if (PHIs.insert(PN) && !AllUsesOfValueWillTrapIfNull(PN, PHIs))
832 return false;
Gabor Greifa01d6db2010-04-06 19:14:05 +0000833 } else if (isa<ICmpInst>(U) &&
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000834 isa<ConstantPointerNull>(UI->getOperand(1))) {
Nick Lewyckye7ee59b2010-02-25 06:39:10 +0000835 // Ignore icmp X, null
Chris Lattner9b34a612004-10-09 21:48:45 +0000836 } else {
Gabor Greifa01d6db2010-04-06 19:14:05 +0000837 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner9b34a612004-10-09 21:48:45 +0000838 return false;
839 }
Gabor Greifa01d6db2010-04-06 19:14:05 +0000840 }
Chris Lattner9b34a612004-10-09 21:48:45 +0000841 return true;
842}
843
844/// AllUsesOfLoadedValueWillTrapIfNull - Return true if all uses of any loads
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000845/// from GV will trap if the loaded value is null. Note that this also permits
846/// comparisons of the loaded value against null, as a special case.
Gabor Greif6ce02b52010-04-06 19:24:18 +0000847static bool AllUsesOfLoadedValueWillTrapIfNull(const GlobalVariable *GV) {
848 for (Value::const_use_iterator UI = GV->use_begin(), E = GV->use_end();
Gabor Greifa01d6db2010-04-06 19:14:05 +0000849 UI != E; ++UI) {
Gabor Greif6ce02b52010-04-06 19:24:18 +0000850 const User *U = *UI;
Gabor Greifa01d6db2010-04-06 19:14:05 +0000851
Gabor Greif6ce02b52010-04-06 19:24:18 +0000852 if (const LoadInst *LI = dyn_cast<LoadInst>(U)) {
853 SmallPtrSet<const PHINode*, 8> PHIs;
Chris Lattner81686182007-09-13 16:30:19 +0000854 if (!AllUsesOfValueWillTrapIfNull(LI, PHIs))
Chris Lattner9b34a612004-10-09 21:48:45 +0000855 return false;
Gabor Greifa01d6db2010-04-06 19:14:05 +0000856 } else if (isa<StoreInst>(U)) {
Chris Lattner9b34a612004-10-09 21:48:45 +0000857 // Ignore stores to the global.
858 } else {
859 // We don't know or understand this user, bail out.
Gabor Greifa01d6db2010-04-06 19:14:05 +0000860 //cerr << "UNKNOWN USER OF GLOBAL!: " << *U;
Chris Lattner9b34a612004-10-09 21:48:45 +0000861 return false;
862 }
Gabor Greifa01d6db2010-04-06 19:14:05 +0000863 }
Chris Lattner9b34a612004-10-09 21:48:45 +0000864 return true;
865}
866
Chris Lattner7b550cc2009-11-06 04:27:31 +0000867static bool OptimizeAwayTrappingUsesOfValue(Value *V, Constant *NewV) {
Chris Lattner708148e2004-10-10 23:14:11 +0000868 bool Changed = false;
869 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ) {
870 Instruction *I = cast<Instruction>(*UI++);
871 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
872 LI->setOperand(0, NewV);
873 Changed = true;
874 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
875 if (SI->getOperand(1) == V) {
876 SI->setOperand(1, NewV);
877 Changed = true;
878 }
879 } else if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
Gabor Greiffa1f5c22010-04-06 18:45:08 +0000880 CallSite CS(I);
881 if (CS.getCalledValue() == V) {
Chris Lattner708148e2004-10-10 23:14:11 +0000882 // Calling through the pointer! Turn into a direct call, but be careful
883 // that the pointer is not also being passed as an argument.
Gabor Greiffa1f5c22010-04-06 18:45:08 +0000884 CS.setCalledFunction(NewV);
Chris Lattner708148e2004-10-10 23:14:11 +0000885 Changed = true;
886 bool PassedAsArg = false;
Gabor Greiffa1f5c22010-04-06 18:45:08 +0000887 for (unsigned i = 0, e = CS.arg_size(); i != e; ++i)
888 if (CS.getArgument(i) == V) {
Chris Lattner708148e2004-10-10 23:14:11 +0000889 PassedAsArg = true;
Gabor Greiffa1f5c22010-04-06 18:45:08 +0000890 CS.setArgument(i, NewV);
Chris Lattner708148e2004-10-10 23:14:11 +0000891 }
892
893 if (PassedAsArg) {
894 // Being passed as an argument also. Be careful to not invalidate UI!
895 UI = V->use_begin();
896 }
897 }
898 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
899 Changed |= OptimizeAwayTrappingUsesOfValue(CI,
Owen Andersonbaf3c402009-07-29 18:55:55 +0000900 ConstantExpr::getCast(CI->getOpcode(),
Chris Lattner7b550cc2009-11-06 04:27:31 +0000901 NewV, CI->getType()));
Chris Lattner708148e2004-10-10 23:14:11 +0000902 if (CI->use_empty()) {
903 Changed = true;
Chris Lattner7a7ed022004-10-16 18:09:00 +0000904 CI->eraseFromParent();
Chris Lattner708148e2004-10-10 23:14:11 +0000905 }
906 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
907 // Should handle GEP here.
Chris Lattner55eb1c42007-01-31 04:40:53 +0000908 SmallVector<Constant*, 8> Idxs;
909 Idxs.reserve(GEPI->getNumOperands()-1);
Gabor Greif5e463212008-05-29 01:59:18 +0000910 for (User::op_iterator i = GEPI->op_begin() + 1, e = GEPI->op_end();
911 i != e; ++i)
912 if (Constant *C = dyn_cast<Constant>(*i))
Chris Lattner55eb1c42007-01-31 04:40:53 +0000913 Idxs.push_back(C);
Chris Lattner708148e2004-10-10 23:14:11 +0000914 else
915 break;
Chris Lattner55eb1c42007-01-31 04:40:53 +0000916 if (Idxs.size() == GEPI->getNumOperands()-1)
Chris Lattner708148e2004-10-10 23:14:11 +0000917 Changed |= OptimizeAwayTrappingUsesOfValue(GEPI,
Jay Foaddab3d292011-07-21 14:31:17 +0000918 ConstantExpr::getGetElementPtr(NewV, Idxs));
Chris Lattner708148e2004-10-10 23:14:11 +0000919 if (GEPI->use_empty()) {
920 Changed = true;
Chris Lattner7a7ed022004-10-16 18:09:00 +0000921 GEPI->eraseFromParent();
Chris Lattner708148e2004-10-10 23:14:11 +0000922 }
923 }
924 }
925
926 return Changed;
927}
928
929
930/// OptimizeAwayTrappingUsesOfLoads - The specified global has only one non-null
931/// value stored into it. If there are uses of the loaded value that would trap
932/// if the loaded value is dynamically null, then we know that they cannot be
933/// reachable with a null optimize away the load.
Nick Lewycky6a577f82012-02-12 01:13:18 +0000934static bool OptimizeAwayTrappingUsesOfLoads(GlobalVariable *GV, Constant *LV,
935 TargetData *TD,
936 TargetLibraryInfo *TLI) {
Chris Lattner708148e2004-10-10 23:14:11 +0000937 bool Changed = false;
938
Chris Lattner92c6bd22009-01-14 00:12:58 +0000939 // Keep track of whether we are able to remove all the uses of the global
940 // other than the store that defines it.
941 bool AllNonStoreUsesGone = true;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000942
Chris Lattner708148e2004-10-10 23:14:11 +0000943 // Replace all uses of loads with uses of uses of the stored value.
Chris Lattner92c6bd22009-01-14 00:12:58 +0000944 for (Value::use_iterator GUI = GV->use_begin(), E = GV->use_end(); GUI != E;){
945 User *GlobalUser = *GUI++;
946 if (LoadInst *LI = dyn_cast<LoadInst>(GlobalUser)) {
Chris Lattner7b550cc2009-11-06 04:27:31 +0000947 Changed |= OptimizeAwayTrappingUsesOfValue(LI, LV);
Chris Lattner92c6bd22009-01-14 00:12:58 +0000948 // If we were able to delete all uses of the loads
949 if (LI->use_empty()) {
950 LI->eraseFromParent();
951 Changed = true;
952 } else {
953 AllNonStoreUsesGone = false;
954 }
955 } else if (isa<StoreInst>(GlobalUser)) {
956 // Ignore the store that stores "LV" to the global.
957 assert(GlobalUser->getOperand(1) == GV &&
958 "Must be storing *to* the global");
Chris Lattner708148e2004-10-10 23:14:11 +0000959 } else {
Chris Lattner92c6bd22009-01-14 00:12:58 +0000960 AllNonStoreUsesGone = false;
961
962 // If we get here we could have other crazy uses that are transitively
963 // loaded.
964 assert((isa<PHINode>(GlobalUser) || isa<SelectInst>(GlobalUser) ||
Chris Lattner98a42b22011-05-22 07:15:13 +0000965 isa<ConstantExpr>(GlobalUser) || isa<CmpInst>(GlobalUser)) &&
966 "Only expect load and stores!");
Chris Lattner708148e2004-10-10 23:14:11 +0000967 }
Chris Lattner92c6bd22009-01-14 00:12:58 +0000968 }
Chris Lattner708148e2004-10-10 23:14:11 +0000969
970 if (Changed) {
David Greene3215b0e2010-01-05 01:28:05 +0000971 DEBUG(dbgs() << "OPTIMIZED LOADS FROM STORED ONCE POINTER: " << *GV);
Chris Lattner708148e2004-10-10 23:14:11 +0000972 ++NumGlobUses;
973 }
974
Chris Lattner708148e2004-10-10 23:14:11 +0000975 // If we nuked all of the loads, then none of the stores are needed either,
976 // nor is the global.
Chris Lattner92c6bd22009-01-14 00:12:58 +0000977 if (AllNonStoreUsesGone) {
Nick Lewycky8899d5c2012-07-24 07:21:08 +0000978 if (isLeakCheckerRoot(GV)) {
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000979 Changed |= CleanupPointerRootUsers(GV, TLI);
Nick Lewycky8899d5c2012-07-24 07:21:08 +0000980 } else {
981 Changed = true;
982 CleanupConstantGlobalUsers(GV, 0, TD, TLI);
983 }
Chris Lattner708148e2004-10-10 23:14:11 +0000984 if (GV->use_empty()) {
Nick Lewycky8899d5c2012-07-24 07:21:08 +0000985 DEBUG(dbgs() << " *** GLOBAL NOW DEAD!\n");
986 Changed = true;
Chris Lattner7a7ed022004-10-16 18:09:00 +0000987 GV->eraseFromParent();
Chris Lattner708148e2004-10-10 23:14:11 +0000988 ++NumDeleted;
989 }
Chris Lattner708148e2004-10-10 23:14:11 +0000990 }
991 return Changed;
992}
993
Chris Lattner30ba5692004-10-11 05:54:41 +0000994/// ConstantPropUsersOf - Walk the use list of V, constant folding all of the
995/// instructions that are foldable.
Nick Lewycky6a577f82012-02-12 01:13:18 +0000996static void ConstantPropUsersOf(Value *V,
997 TargetData *TD, TargetLibraryInfo *TLI) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000998 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; )
999 if (Instruction *I = dyn_cast<Instruction>(*UI++))
Nick Lewycky6a577f82012-02-12 01:13:18 +00001000 if (Constant *NewC = ConstantFoldInstruction(I, TD, TLI)) {
Chris Lattner30ba5692004-10-11 05:54:41 +00001001 I->replaceAllUsesWith(NewC);
1002
Chris Lattnerd514d822005-02-01 01:23:31 +00001003 // Advance UI to the next non-I use to avoid invalidating it!
1004 // Instructions could multiply use V.
1005 while (UI != E && *UI == I)
Chris Lattner30ba5692004-10-11 05:54:41 +00001006 ++UI;
Chris Lattnerd514d822005-02-01 01:23:31 +00001007 I->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +00001008 }
1009}
1010
1011/// OptimizeGlobalAddressOfMalloc - This function takes the specified global
1012/// variable, and transforms the program as if it always contained the result of
1013/// the specified malloc. Because it is always the result of the specified
1014/// malloc, there is no reason to actually DO the malloc. Instead, turn the
Chris Lattner6e8fbad2006-11-30 17:32:29 +00001015/// malloc into a global, and any loads of GV as uses of the new global.
Chris Lattner30ba5692004-10-11 05:54:41 +00001016static GlobalVariable *OptimizeGlobalAddressOfMalloc(GlobalVariable *GV,
Victor Hernandez83d63912009-09-18 22:35:49 +00001017 CallInst *CI,
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001018 Type *AllocTy,
Chris Lattnera6874652010-02-25 22:33:52 +00001019 ConstantInt *NElements,
Nick Lewycky6a577f82012-02-12 01:13:18 +00001020 TargetData *TD,
1021 TargetLibraryInfo *TLI) {
Chris Lattnera6874652010-02-25 22:33:52 +00001022 DEBUG(errs() << "PROMOTING GLOBAL: " << *GV << " CALL = " << *CI << '\n');
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001023
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001024 Type *GlobalType;
Chris Lattnera6874652010-02-25 22:33:52 +00001025 if (NElements->getZExtValue() == 1)
1026 GlobalType = AllocTy;
1027 else
1028 // If we have an array allocation, the global variable is of an array.
1029 GlobalType = ArrayType::get(AllocTy, NElements->getZExtValue());
Victor Hernandez83d63912009-09-18 22:35:49 +00001030
1031 // Create the new global variable. The contents of the malloc'd memory is
1032 // undefined, so initialize with an undef value.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001033 GlobalVariable *NewGV = new GlobalVariable(*GV->getParent(),
Chris Lattnere9fd4442010-02-26 23:42:13 +00001034 GlobalType, false,
Chris Lattnera6874652010-02-25 22:33:52 +00001035 GlobalValue::InternalLinkage,
Chris Lattnere9fd4442010-02-26 23:42:13 +00001036 UndefValue::get(GlobalType),
Victor Hernandez83d63912009-09-18 22:35:49 +00001037 GV->getName()+".body",
1038 GV,
Hans Wennborgce718ff2012-06-23 11:37:03 +00001039 GV->getThreadLocalMode());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001040
Chris Lattnera6874652010-02-25 22:33:52 +00001041 // If there are bitcast users of the malloc (which is typical, usually we have
1042 // a malloc + bitcast) then replace them with uses of the new global. Update
1043 // other users to use the global as well.
1044 BitCastInst *TheBC = 0;
1045 while (!CI->use_empty()) {
1046 Instruction *User = cast<Instruction>(CI->use_back());
1047 if (BitCastInst *BCI = dyn_cast<BitCastInst>(User)) {
1048 if (BCI->getType() == NewGV->getType()) {
1049 BCI->replaceAllUsesWith(NewGV);
1050 BCI->eraseFromParent();
1051 } else {
1052 BCI->setOperand(0, NewGV);
1053 }
1054 } else {
1055 if (TheBC == 0)
1056 TheBC = new BitCastInst(NewGV, CI->getType(), "newgv", CI);
1057 User->replaceUsesOfWith(CI, TheBC);
1058 }
1059 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001060
Victor Hernandez83d63912009-09-18 22:35:49 +00001061 Constant *RepValue = NewGV;
1062 if (NewGV->getType() != GV->getType()->getElementType())
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001063 RepValue = ConstantExpr::getBitCast(RepValue,
Victor Hernandez83d63912009-09-18 22:35:49 +00001064 GV->getType()->getElementType());
1065
1066 // If there is a comparison against null, we will insert a global bool to
1067 // keep track of whether the global was initialized yet or not.
1068 GlobalVariable *InitBool =
Chris Lattner7b550cc2009-11-06 04:27:31 +00001069 new GlobalVariable(Type::getInt1Ty(GV->getContext()), false,
Victor Hernandez83d63912009-09-18 22:35:49 +00001070 GlobalValue::InternalLinkage,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001071 ConstantInt::getFalse(GV->getContext()),
Hans Wennborgce718ff2012-06-23 11:37:03 +00001072 GV->getName()+".init", GV->getThreadLocalMode());
Victor Hernandez83d63912009-09-18 22:35:49 +00001073 bool InitBoolUsed = false;
1074
1075 // Loop over all uses of GV, processing them in turn.
Chris Lattnera6874652010-02-25 22:33:52 +00001076 while (!GV->use_empty()) {
1077 if (StoreInst *SI = dyn_cast<StoreInst>(GV->use_back())) {
Victor Hernandez83d63912009-09-18 22:35:49 +00001078 // The global is initialized when the store to it occurs.
Nick Lewyckyfad4d402012-02-05 19:56:38 +00001079 new StoreInst(ConstantInt::getTrue(GV->getContext()), InitBool, false, 0,
1080 SI->getOrdering(), SI->getSynchScope(), SI);
Victor Hernandez83d63912009-09-18 22:35:49 +00001081 SI->eraseFromParent();
Chris Lattnera6874652010-02-25 22:33:52 +00001082 continue;
Victor Hernandez83d63912009-09-18 22:35:49 +00001083 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001084
Chris Lattnera6874652010-02-25 22:33:52 +00001085 LoadInst *LI = cast<LoadInst>(GV->use_back());
1086 while (!LI->use_empty()) {
1087 Use &LoadUse = LI->use_begin().getUse();
1088 if (!isa<ICmpInst>(LoadUse.getUser())) {
1089 LoadUse = RepValue;
1090 continue;
1091 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001092
Chris Lattnera6874652010-02-25 22:33:52 +00001093 ICmpInst *ICI = cast<ICmpInst>(LoadUse.getUser());
1094 // Replace the cmp X, 0 with a use of the bool value.
Nick Lewyckyfad4d402012-02-05 19:56:38 +00001095 // Sink the load to where the compare was, if atomic rules allow us to.
1096 Value *LV = new LoadInst(InitBool, InitBool->getName()+".val", false, 0,
1097 LI->getOrdering(), LI->getSynchScope(),
1098 LI->isUnordered() ? (Instruction*)ICI : LI);
Chris Lattnera6874652010-02-25 22:33:52 +00001099 InitBoolUsed = true;
1100 switch (ICI->getPredicate()) {
1101 default: llvm_unreachable("Unknown ICmp Predicate!");
1102 case ICmpInst::ICMP_ULT:
1103 case ICmpInst::ICMP_SLT: // X < null -> always false
1104 LV = ConstantInt::getFalse(GV->getContext());
1105 break;
1106 case ICmpInst::ICMP_ULE:
1107 case ICmpInst::ICMP_SLE:
1108 case ICmpInst::ICMP_EQ:
1109 LV = BinaryOperator::CreateNot(LV, "notinit", ICI);
1110 break;
1111 case ICmpInst::ICMP_NE:
1112 case ICmpInst::ICMP_UGE:
1113 case ICmpInst::ICMP_SGE:
1114 case ICmpInst::ICMP_UGT:
1115 case ICmpInst::ICMP_SGT:
1116 break; // no change.
1117 }
1118 ICI->replaceAllUsesWith(LV);
1119 ICI->eraseFromParent();
1120 }
1121 LI->eraseFromParent();
1122 }
Victor Hernandez83d63912009-09-18 22:35:49 +00001123
1124 // If the initialization boolean was used, insert it, otherwise delete it.
1125 if (!InitBoolUsed) {
1126 while (!InitBool->use_empty()) // Delete initializations
Chris Lattnera6874652010-02-25 22:33:52 +00001127 cast<StoreInst>(InitBool->use_back())->eraseFromParent();
Victor Hernandez83d63912009-09-18 22:35:49 +00001128 delete InitBool;
1129 } else
1130 GV->getParent()->getGlobalList().insert(GV, InitBool);
1131
Chris Lattnera6874652010-02-25 22:33:52 +00001132 // Now the GV is dead, nuke it and the malloc..
Victor Hernandez83d63912009-09-18 22:35:49 +00001133 GV->eraseFromParent();
Victor Hernandez83d63912009-09-18 22:35:49 +00001134 CI->eraseFromParent();
1135
1136 // To further other optimizations, loop over all users of NewGV and try to
1137 // constant prop them. This will promote GEP instructions with constant
1138 // indices into GEP constant-exprs, which will allow global-opt to hack on it.
Nick Lewycky6a577f82012-02-12 01:13:18 +00001139 ConstantPropUsersOf(NewGV, TD, TLI);
Victor Hernandez83d63912009-09-18 22:35:49 +00001140 if (RepValue != NewGV)
Nick Lewycky6a577f82012-02-12 01:13:18 +00001141 ConstantPropUsersOf(RepValue, TD, TLI);
Victor Hernandez83d63912009-09-18 22:35:49 +00001142
1143 return NewGV;
1144}
1145
Chris Lattnerfa07e4f2004-12-02 07:11:07 +00001146/// ValueIsOnlyUsedLocallyOrStoredToOneGlobal - Scan the use-list of V checking
1147/// to make sure that there are no complex uses of V. We permit simple things
1148/// like dereferencing the pointer, but not storing through the address, unless
1149/// it is to the specified global.
Gabor Greif0b520db2010-04-06 18:58:22 +00001150static bool ValueIsOnlyUsedLocallyOrStoredToOneGlobal(const Instruction *V,
1151 const GlobalVariable *GV,
Gabor Greifa01d6db2010-04-06 19:14:05 +00001152 SmallPtrSet<const PHINode*, 8> &PHIs) {
Gabor Greif0b520db2010-04-06 18:58:22 +00001153 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end();
Gabor Greifa01d6db2010-04-06 19:14:05 +00001154 UI != E; ++UI) {
Gabor Greif0b520db2010-04-06 18:58:22 +00001155 const Instruction *Inst = cast<Instruction>(*UI);
Gabor Greifa01d6db2010-04-06 19:14:05 +00001156
Chris Lattner49b6d4a2008-12-15 21:08:54 +00001157 if (isa<LoadInst>(Inst) || isa<CmpInst>(Inst)) {
1158 continue; // Fine, ignore.
1159 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001160
Gabor Greif0b520db2010-04-06 18:58:22 +00001161 if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
Chris Lattnerfa07e4f2004-12-02 07:11:07 +00001162 if (SI->getOperand(0) == V && SI->getOperand(1) != GV)
1163 return false; // Storing the pointer itself... bad.
Chris Lattner49b6d4a2008-12-15 21:08:54 +00001164 continue; // Otherwise, storing through it, or storing into GV... fine.
1165 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001166
Chris Lattnera2fb2342010-04-10 18:19:22 +00001167 // Must index into the array and into the struct.
1168 if (isa<GetElementPtrInst>(Inst) && Inst->getNumOperands() >= 3) {
Chris Lattner49b6d4a2008-12-15 21:08:54 +00001169 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(Inst, GV, PHIs))
Chris Lattnerfa07e4f2004-12-02 07:11:07 +00001170 return false;
Chris Lattner49b6d4a2008-12-15 21:08:54 +00001171 continue;
1172 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001173
Gabor Greif0b520db2010-04-06 18:58:22 +00001174 if (const PHINode *PN = dyn_cast<PHINode>(Inst)) {
Chris Lattnerc451f9c2007-09-13 16:37:20 +00001175 // PHIs are ok if all uses are ok. Don't infinitely recurse through PHI
1176 // cycles.
1177 if (PHIs.insert(PN))
Chris Lattner5e6e4942007-09-14 03:41:21 +00001178 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(PN, GV, PHIs))
1179 return false;
Chris Lattner49b6d4a2008-12-15 21:08:54 +00001180 continue;
Chris Lattnerfa07e4f2004-12-02 07:11:07 +00001181 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001182
Gabor Greif0b520db2010-04-06 18:58:22 +00001183 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Inst)) {
Chris Lattner49b6d4a2008-12-15 21:08:54 +00001184 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(BCI, GV, PHIs))
1185 return false;
1186 continue;
1187 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001188
Chris Lattner49b6d4a2008-12-15 21:08:54 +00001189 return false;
1190 }
Chris Lattnerfa07e4f2004-12-02 07:11:07 +00001191 return true;
Chris Lattnerfa07e4f2004-12-02 07:11:07 +00001192}
1193
Chris Lattner86395032006-09-30 23:32:09 +00001194/// ReplaceUsesOfMallocWithGlobal - The Alloc pointer is stored into GV
1195/// somewhere. Transform all uses of the allocation into loads from the
1196/// global and uses of the resultant pointer. Further, delete the store into
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001197/// GV. This assumes that these value pass the
Chris Lattner86395032006-09-30 23:32:09 +00001198/// 'ValueIsOnlyUsedLocallyOrStoredToOneGlobal' predicate.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001199static void ReplaceUsesOfMallocWithGlobal(Instruction *Alloc,
Chris Lattner86395032006-09-30 23:32:09 +00001200 GlobalVariable *GV) {
1201 while (!Alloc->use_empty()) {
Chris Lattnera637a8b2007-09-13 18:00:31 +00001202 Instruction *U = cast<Instruction>(*Alloc->use_begin());
1203 Instruction *InsertPt = U;
Chris Lattner86395032006-09-30 23:32:09 +00001204 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
1205 // If this is the store of the allocation into the global, remove it.
1206 if (SI->getOperand(1) == GV) {
1207 SI->eraseFromParent();
1208 continue;
1209 }
Chris Lattnera637a8b2007-09-13 18:00:31 +00001210 } else if (PHINode *PN = dyn_cast<PHINode>(U)) {
1211 // Insert the load in the corresponding predecessor, not right before the
1212 // PHI.
Gabor Greifa36791d2009-01-23 19:40:15 +00001213 InsertPt = PN->getIncomingBlock(Alloc->use_begin())->getTerminator();
Chris Lattner101f44e2008-12-15 21:44:34 +00001214 } else if (isa<BitCastInst>(U)) {
1215 // Must be bitcast between the malloc and store to initialize the global.
1216 ReplaceUsesOfMallocWithGlobal(U, GV);
1217 U->eraseFromParent();
1218 continue;
1219 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
1220 // If this is a "GEP bitcast" and the user is a store to the global, then
1221 // just process it as a bitcast.
1222 if (GEPI->hasAllZeroIndices() && GEPI->hasOneUse())
1223 if (StoreInst *SI = dyn_cast<StoreInst>(GEPI->use_back()))
1224 if (SI->getOperand(1) == GV) {
1225 // Must be bitcast GEP between the malloc and store to initialize
1226 // the global.
1227 ReplaceUsesOfMallocWithGlobal(GEPI, GV);
1228 GEPI->eraseFromParent();
1229 continue;
1230 }
Chris Lattner86395032006-09-30 23:32:09 +00001231 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001232
Chris Lattner86395032006-09-30 23:32:09 +00001233 // Insert a load from the global, and use it instead of the malloc.
Chris Lattnera637a8b2007-09-13 18:00:31 +00001234 Value *NL = new LoadInst(GV, GV->getName()+".val", InsertPt);
Chris Lattner86395032006-09-30 23:32:09 +00001235 U->replaceUsesOfWith(Alloc, NL);
1236 }
1237}
1238
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001239/// LoadUsesSimpleEnoughForHeapSRA - Verify that all uses of V (a load, or a phi
1240/// of a load) are simple enough to perform heap SRA on. This permits GEP's
1241/// that index through the array and struct field, icmps of null, and PHIs.
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001242static bool LoadUsesSimpleEnoughForHeapSRA(const Value *V,
Gabor Greif27236912010-04-07 18:59:26 +00001243 SmallPtrSet<const PHINode*, 32> &LoadUsingPHIs,
1244 SmallPtrSet<const PHINode*, 32> &LoadUsingPHIsPerLoad) {
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001245 // We permit two users of the load: setcc comparing against the null
1246 // pointer, and a getelementptr of a specific form.
Gabor Greif27236912010-04-07 18:59:26 +00001247 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;
1248 ++UI) {
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001249 const Instruction *User = cast<Instruction>(*UI);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001250
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001251 // Comparison against null is ok.
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001252 if (const ICmpInst *ICI = dyn_cast<ICmpInst>(User)) {
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001253 if (!isa<ConstantPointerNull>(ICI->getOperand(1)))
1254 return false;
1255 continue;
1256 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001257
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001258 // getelementptr is also ok, but only a simple form.
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001259 if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001260 // Must index into the array and into the struct.
1261 if (GEPI->getNumOperands() < 3)
1262 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001263
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001264 // Otherwise the GEP is ok.
1265 continue;
1266 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001267
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001268 if (const PHINode *PN = dyn_cast<PHINode>(User)) {
Evan Cheng5d163962009-06-02 00:56:07 +00001269 if (!LoadUsingPHIsPerLoad.insert(PN))
1270 // This means some phi nodes are dependent on each other.
1271 // Avoid infinite looping!
1272 return false;
1273 if (!LoadUsingPHIs.insert(PN))
1274 // If we have already analyzed this PHI, then it is safe.
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001275 continue;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001276
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001277 // Make sure all uses of the PHI are simple enough to transform.
Evan Cheng5d163962009-06-02 00:56:07 +00001278 if (!LoadUsesSimpleEnoughForHeapSRA(PN,
1279 LoadUsingPHIs, LoadUsingPHIsPerLoad))
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001280 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001281
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001282 continue;
Chris Lattner86395032006-09-30 23:32:09 +00001283 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001284
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001285 // Otherwise we don't know what this is, not ok.
1286 return false;
1287 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001288
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001289 return true;
1290}
1291
1292
1293/// AllGlobalLoadUsesSimpleEnoughForHeapSRA - If all users of values loaded from
1294/// GV are simple enough to perform HeapSRA, return true.
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001295static bool AllGlobalLoadUsesSimpleEnoughForHeapSRA(const GlobalVariable *GV,
Victor Hernandez83d63912009-09-18 22:35:49 +00001296 Instruction *StoredVal) {
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001297 SmallPtrSet<const PHINode*, 32> LoadUsingPHIs;
1298 SmallPtrSet<const PHINode*, 32> LoadUsingPHIsPerLoad;
Gabor Greif27236912010-04-07 18:59:26 +00001299 for (Value::const_use_iterator UI = GV->use_begin(), E = GV->use_end();
1300 UI != E; ++UI)
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001301 if (const LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
Evan Cheng5d163962009-06-02 00:56:07 +00001302 if (!LoadUsesSimpleEnoughForHeapSRA(LI, LoadUsingPHIs,
1303 LoadUsingPHIsPerLoad))
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001304 return false;
Evan Cheng5d163962009-06-02 00:56:07 +00001305 LoadUsingPHIsPerLoad.clear();
1306 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001307
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001308 // If we reach here, we know that all uses of the loads and transitive uses
1309 // (through PHI nodes) are simple enough to transform. However, we don't know
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001310 // that all inputs the to the PHI nodes are in the same equivalence sets.
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001311 // Check to verify that all operands of the PHIs are either PHIS that can be
1312 // transformed, loads from GV, or MI itself.
Gabor Greif27236912010-04-07 18:59:26 +00001313 for (SmallPtrSet<const PHINode*, 32>::const_iterator I = LoadUsingPHIs.begin()
1314 , E = LoadUsingPHIs.end(); I != E; ++I) {
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001315 const PHINode *PN = *I;
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001316 for (unsigned op = 0, e = PN->getNumIncomingValues(); op != e; ++op) {
1317 Value *InVal = PN->getIncomingValue(op);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001318
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001319 // PHI of the stored value itself is ok.
Victor Hernandez83d63912009-09-18 22:35:49 +00001320 if (InVal == StoredVal) continue;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001321
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001322 if (const PHINode *InPN = dyn_cast<PHINode>(InVal)) {
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001323 // One of the PHIs in our set is (optimistically) ok.
1324 if (LoadUsingPHIs.count(InPN))
1325 continue;
1326 return false;
1327 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001328
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001329 // Load from GV is ok.
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001330 if (const LoadInst *LI = dyn_cast<LoadInst>(InVal))
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001331 if (LI->getOperand(0) == GV)
1332 continue;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001333
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001334 // UNDEF? NULL?
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001335
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001336 // Anything else is rejected.
1337 return false;
1338 }
1339 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001340
Chris Lattner86395032006-09-30 23:32:09 +00001341 return true;
1342}
1343
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001344static Value *GetHeapSROAValue(Value *V, unsigned FieldNo,
1345 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001346 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001347 std::vector<Value*> &FieldVals = InsertedScalarizedValues[V];
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001348
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001349 if (FieldNo >= FieldVals.size())
1350 FieldVals.resize(FieldNo+1);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001351
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001352 // If we already have this value, just reuse the previously scalarized
1353 // version.
1354 if (Value *FieldVal = FieldVals[FieldNo])
1355 return FieldVal;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001356
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001357 // Depending on what instruction this is, we have several cases.
1358 Value *Result;
1359 if (LoadInst *LI = dyn_cast<LoadInst>(V)) {
1360 // This is a scalarized version of the load from the global. Just create
1361 // a new Load of the scalarized global.
1362 Result = new LoadInst(GetHeapSROAValue(LI->getOperand(0), FieldNo,
1363 InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001364 PHIsToRewrite),
Daniel Dunbarfe09b202009-07-30 17:37:43 +00001365 LI->getName()+".f"+Twine(FieldNo), LI);
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001366 } else if (PHINode *PN = dyn_cast<PHINode>(V)) {
1367 // PN's type is pointer to struct. Make a new PHI of pointer to struct
1368 // field.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001369 StructType *ST =
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001370 cast<StructType>(cast<PointerType>(PN->getType())->getElementType());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001371
Jay Foadd8b4fb42011-03-30 11:19:20 +00001372 PHINode *NewPN =
Owen Andersondebcb012009-07-29 22:17:13 +00001373 PHINode::Create(PointerType::getUnqual(ST->getElementType(FieldNo)),
Jay Foad3ecfc862011-03-30 11:28:46 +00001374 PN->getNumIncomingValues(),
Daniel Dunbarfe09b202009-07-30 17:37:43 +00001375 PN->getName()+".f"+Twine(FieldNo), PN);
Jay Foadd8b4fb42011-03-30 11:19:20 +00001376 Result = NewPN;
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001377 PHIsToRewrite.push_back(std::make_pair(PN, FieldNo));
1378 } else {
Torok Edwinc23197a2009-07-14 16:55:14 +00001379 llvm_unreachable("Unknown usable value");
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001380 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001381
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001382 return FieldVals[FieldNo] = Result;
Chris Lattnera637a8b2007-09-13 18:00:31 +00001383}
1384
Chris Lattner330245e2007-09-13 17:29:05 +00001385/// RewriteHeapSROALoadUser - Given a load instruction and a value derived from
1386/// the load, rewrite the derived value to use the HeapSRoA'd load.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001387static void RewriteHeapSROALoadUser(Instruction *LoadUser,
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001388 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001389 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
Chris Lattner330245e2007-09-13 17:29:05 +00001390 // If this is a comparison against null, handle it.
1391 if (ICmpInst *SCI = dyn_cast<ICmpInst>(LoadUser)) {
1392 assert(isa<ConstantPointerNull>(SCI->getOperand(1)));
1393 // If we have a setcc of the loaded pointer, we can use a setcc of any
1394 // field.
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001395 Value *NPtr = GetHeapSROAValue(SCI->getOperand(0), 0,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001396 InsertedScalarizedValues, PHIsToRewrite);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001397
Owen Anderson333c4002009-07-09 23:48:35 +00001398 Value *New = new ICmpInst(SCI, SCI->getPredicate(), NPtr,
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001399 Constant::getNullValue(NPtr->getType()),
Owen Anderson333c4002009-07-09 23:48:35 +00001400 SCI->getName());
Chris Lattner330245e2007-09-13 17:29:05 +00001401 SCI->replaceAllUsesWith(New);
1402 SCI->eraseFromParent();
1403 return;
1404 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001405
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001406 // Handle 'getelementptr Ptr, Idx, i32 FieldNo ...'
Chris Lattnera637a8b2007-09-13 18:00:31 +00001407 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(LoadUser)) {
1408 assert(GEPI->getNumOperands() >= 3 && isa<ConstantInt>(GEPI->getOperand(2))
1409 && "Unexpected GEPI!");
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001410
Chris Lattnera637a8b2007-09-13 18:00:31 +00001411 // Load the pointer for this field.
1412 unsigned FieldNo = cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue();
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001413 Value *NewPtr = GetHeapSROAValue(GEPI->getOperand(0), FieldNo,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001414 InsertedScalarizedValues, PHIsToRewrite);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001415
Chris Lattnera637a8b2007-09-13 18:00:31 +00001416 // Create the new GEP idx vector.
1417 SmallVector<Value*, 8> GEPIdx;
1418 GEPIdx.push_back(GEPI->getOperand(1));
1419 GEPIdx.append(GEPI->op_begin()+3, GEPI->op_end());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001420
Jay Foada9203102011-07-25 09:48:08 +00001421 Value *NGEPI = GetElementPtrInst::Create(NewPtr, GEPIdx,
Gabor Greif051a9502008-04-06 20:25:17 +00001422 GEPI->getName(), GEPI);
Chris Lattnera637a8b2007-09-13 18:00:31 +00001423 GEPI->replaceAllUsesWith(NGEPI);
1424 GEPI->eraseFromParent();
1425 return;
1426 }
Chris Lattner309f20f2007-09-13 21:31:36 +00001427
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001428 // Recursively transform the users of PHI nodes. This will lazily create the
1429 // PHIs that are needed for individual elements. Keep track of what PHIs we
1430 // see in InsertedScalarizedValues so that we don't get infinite loops (very
1431 // antisocial). If the PHI is already in InsertedScalarizedValues, it has
1432 // already been seen first by another load, so its uses have already been
1433 // processed.
1434 PHINode *PN = cast<PHINode>(LoadUser);
Chris Lattnerc30a38f2011-07-21 06:21:31 +00001435 if (!InsertedScalarizedValues.insert(std::make_pair(PN,
1436 std::vector<Value*>())).second)
1437 return;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001438
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001439 // If this is the first time we've seen this PHI, recursively process all
1440 // users.
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001441 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end(); UI != E; ) {
1442 Instruction *User = cast<Instruction>(*UI++);
Chris Lattner7b550cc2009-11-06 04:27:31 +00001443 RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite);
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001444 }
Chris Lattner330245e2007-09-13 17:29:05 +00001445}
1446
Chris Lattner86395032006-09-30 23:32:09 +00001447/// RewriteUsesOfLoadForHeapSRoA - We are performing Heap SRoA on a global. Ptr
1448/// is a value loaded from the global. Eliminate all uses of Ptr, making them
1449/// use FieldGlobals instead. All uses of loaded values satisfy
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001450/// AllGlobalLoadUsesSimpleEnoughForHeapSRA.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001451static void RewriteUsesOfLoadForHeapSRoA(LoadInst *Load,
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001452 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001453 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001454 for (Value::use_iterator UI = Load->use_begin(), E = Load->use_end();
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001455 UI != E; ) {
1456 Instruction *User = cast<Instruction>(*UI++);
Chris Lattner7b550cc2009-11-06 04:27:31 +00001457 RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite);
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001458 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001459
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001460 if (Load->use_empty()) {
1461 Load->eraseFromParent();
1462 InsertedScalarizedValues.erase(Load);
1463 }
Chris Lattner86395032006-09-30 23:32:09 +00001464}
1465
Victor Hernandez83d63912009-09-18 22:35:49 +00001466/// PerformHeapAllocSRoA - CI is an allocation of an array of structures. Break
1467/// it up into multiple allocations of arrays of the fields.
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001468static GlobalVariable *PerformHeapAllocSRoA(GlobalVariable *GV, CallInst *CI,
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +00001469 Value *NElems, TargetData *TD,
1470 const TargetLibraryInfo *TLI) {
David Greene3215b0e2010-01-05 01:28:05 +00001471 DEBUG(dbgs() << "SROA HEAP ALLOC: " << *GV << " MALLOC = " << *CI << '\n');
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +00001472 Type *MAT = getMallocAllocatedType(CI, TLI);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001473 StructType *STy = cast<StructType>(MAT);
Victor Hernandez83d63912009-09-18 22:35:49 +00001474
1475 // There is guaranteed to be at least one use of the malloc (storing
1476 // it into GV). If there are other uses, change them to be uses of
1477 // the global to simplify later code. This also deletes the store
1478 // into GV.
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001479 ReplaceUsesOfMallocWithGlobal(CI, GV);
1480
Victor Hernandez83d63912009-09-18 22:35:49 +00001481 // Okay, at this point, there are no users of the malloc. Insert N
1482 // new mallocs at the same place as CI, and N globals.
1483 std::vector<Value*> FieldGlobals;
1484 std::vector<Value*> FieldMallocs;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001485
Victor Hernandez83d63912009-09-18 22:35:49 +00001486 for (unsigned FieldNo = 0, e = STy->getNumElements(); FieldNo != e;++FieldNo){
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001487 Type *FieldTy = STy->getElementType(FieldNo);
1488 PointerType *PFieldTy = PointerType::getUnqual(FieldTy);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001489
Victor Hernandez83d63912009-09-18 22:35:49 +00001490 GlobalVariable *NGV =
1491 new GlobalVariable(*GV->getParent(),
1492 PFieldTy, false, GlobalValue::InternalLinkage,
1493 Constant::getNullValue(PFieldTy),
1494 GV->getName() + ".f" + Twine(FieldNo), GV,
Hans Wennborgce718ff2012-06-23 11:37:03 +00001495 GV->getThreadLocalMode());
Victor Hernandez83d63912009-09-18 22:35:49 +00001496 FieldGlobals.push_back(NGV);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001497
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001498 unsigned TypeSize = TD->getTypeAllocSize(FieldTy);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001499 if (StructType *ST = dyn_cast<StructType>(FieldTy))
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001500 TypeSize = TD->getStructLayout(ST)->getSizeInBytes();
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001501 Type *IntPtrTy = TD->getIntPtrType(CI->getContext());
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001502 Value *NMI = CallInst::CreateMalloc(CI, IntPtrTy, FieldTy,
1503 ConstantInt::get(IntPtrTy, TypeSize),
Chris Lattner5a30a852010-07-12 00:57:28 +00001504 NElems, 0,
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001505 CI->getName() + ".f" + Twine(FieldNo));
Chris Lattner3f5e0b82010-02-26 18:23:13 +00001506 FieldMallocs.push_back(NMI);
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001507 new StoreInst(NMI, NGV, CI);
Victor Hernandez83d63912009-09-18 22:35:49 +00001508 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001509
Victor Hernandez83d63912009-09-18 22:35:49 +00001510 // The tricky aspect of this transformation is handling the case when malloc
1511 // fails. In the original code, malloc failing would set the result pointer
1512 // of malloc to null. In this case, some mallocs could succeed and others
1513 // could fail. As such, we emit code that looks like this:
1514 // F0 = malloc(field0)
1515 // F1 = malloc(field1)
1516 // F2 = malloc(field2)
1517 // if (F0 == 0 || F1 == 0 || F2 == 0) {
1518 // if (F0) { free(F0); F0 = 0; }
1519 // if (F1) { free(F1); F1 = 0; }
1520 // if (F2) { free(F2); F2 = 0; }
1521 // }
Victor Hernandez8e345a12009-11-10 08:32:25 +00001522 // The malloc can also fail if its argument is too large.
Gabor Greif9e4f2432010-06-24 14:42:01 +00001523 Constant *ConstantZero = ConstantInt::get(CI->getArgOperand(0)->getType(), 0);
1524 Value *RunningOr = new ICmpInst(CI, ICmpInst::ICMP_SLT, CI->getArgOperand(0),
Victor Hernandez8e345a12009-11-10 08:32:25 +00001525 ConstantZero, "isneg");
Victor Hernandez83d63912009-09-18 22:35:49 +00001526 for (unsigned i = 0, e = FieldMallocs.size(); i != e; ++i) {
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001527 Value *Cond = new ICmpInst(CI, ICmpInst::ICMP_EQ, FieldMallocs[i],
1528 Constant::getNullValue(FieldMallocs[i]->getType()),
1529 "isnull");
Victor Hernandez8e345a12009-11-10 08:32:25 +00001530 RunningOr = BinaryOperator::CreateOr(RunningOr, Cond, "tmp", CI);
Victor Hernandez83d63912009-09-18 22:35:49 +00001531 }
1532
1533 // Split the basic block at the old malloc.
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001534 BasicBlock *OrigBB = CI->getParent();
1535 BasicBlock *ContBB = OrigBB->splitBasicBlock(CI, "malloc_cont");
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001536
Victor Hernandez83d63912009-09-18 22:35:49 +00001537 // Create the block to check the first condition. Put all these blocks at the
1538 // end of the function as they are unlikely to be executed.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001539 BasicBlock *NullPtrBlock = BasicBlock::Create(OrigBB->getContext(),
1540 "malloc_ret_null",
Victor Hernandez83d63912009-09-18 22:35:49 +00001541 OrigBB->getParent());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001542
Victor Hernandez83d63912009-09-18 22:35:49 +00001543 // Remove the uncond branch from OrigBB to ContBB, turning it into a cond
1544 // branch on RunningOr.
1545 OrigBB->getTerminator()->eraseFromParent();
1546 BranchInst::Create(NullPtrBlock, ContBB, RunningOr, OrigBB);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001547
Victor Hernandez83d63912009-09-18 22:35:49 +00001548 // Within the NullPtrBlock, we need to emit a comparison and branch for each
1549 // pointer, because some may be null while others are not.
1550 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
1551 Value *GVVal = new LoadInst(FieldGlobals[i], "tmp", NullPtrBlock);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001552 Value *Cmp = new ICmpInst(*NullPtrBlock, ICmpInst::ICMP_NE, GVVal,
Benjamin Kramera9390a42011-09-27 20:39:19 +00001553 Constant::getNullValue(GVVal->getType()));
Chris Lattner7b550cc2009-11-06 04:27:31 +00001554 BasicBlock *FreeBlock = BasicBlock::Create(Cmp->getContext(), "free_it",
Victor Hernandez83d63912009-09-18 22:35:49 +00001555 OrigBB->getParent());
Chris Lattner7b550cc2009-11-06 04:27:31 +00001556 BasicBlock *NextBlock = BasicBlock::Create(Cmp->getContext(), "next",
Victor Hernandez83d63912009-09-18 22:35:49 +00001557 OrigBB->getParent());
Victor Hernandez66284e02009-10-24 04:23:03 +00001558 Instruction *BI = BranchInst::Create(FreeBlock, NextBlock,
1559 Cmp, NullPtrBlock);
Victor Hernandez83d63912009-09-18 22:35:49 +00001560
1561 // Fill in FreeBlock.
Victor Hernandez66284e02009-10-24 04:23:03 +00001562 CallInst::CreateFree(GVVal, BI);
Victor Hernandez83d63912009-09-18 22:35:49 +00001563 new StoreInst(Constant::getNullValue(GVVal->getType()), FieldGlobals[i],
1564 FreeBlock);
1565 BranchInst::Create(NextBlock, FreeBlock);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001566
Victor Hernandez83d63912009-09-18 22:35:49 +00001567 NullPtrBlock = NextBlock;
1568 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001569
Victor Hernandez83d63912009-09-18 22:35:49 +00001570 BranchInst::Create(ContBB, NullPtrBlock);
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001571
1572 // CI is no longer needed, remove it.
Victor Hernandez83d63912009-09-18 22:35:49 +00001573 CI->eraseFromParent();
1574
1575 /// InsertedScalarizedLoads - As we process loads, if we can't immediately
1576 /// update all uses of the load, keep track of what scalarized loads are
1577 /// inserted for a given load.
1578 DenseMap<Value*, std::vector<Value*> > InsertedScalarizedValues;
1579 InsertedScalarizedValues[GV] = FieldGlobals;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001580
Victor Hernandez83d63912009-09-18 22:35:49 +00001581 std::vector<std::pair<PHINode*, unsigned> > PHIsToRewrite;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001582
Victor Hernandez83d63912009-09-18 22:35:49 +00001583 // Okay, the malloc site is completely handled. All of the uses of GV are now
1584 // loads, and all uses of those loads are simple. Rewrite them to use loads
1585 // of the per-field globals instead.
1586 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI != E;) {
1587 Instruction *User = cast<Instruction>(*UI++);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001588
Victor Hernandez83d63912009-09-18 22:35:49 +00001589 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Chris Lattner7b550cc2009-11-06 04:27:31 +00001590 RewriteUsesOfLoadForHeapSRoA(LI, InsertedScalarizedValues, PHIsToRewrite);
Victor Hernandez83d63912009-09-18 22:35:49 +00001591 continue;
1592 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001593
Victor Hernandez83d63912009-09-18 22:35:49 +00001594 // Must be a store of null.
1595 StoreInst *SI = cast<StoreInst>(User);
1596 assert(isa<ConstantPointerNull>(SI->getOperand(0)) &&
1597 "Unexpected heap-sra user!");
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001598
Victor Hernandez83d63912009-09-18 22:35:49 +00001599 // Insert a store of null into each global.
1600 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001601 PointerType *PT = cast<PointerType>(FieldGlobals[i]->getType());
Victor Hernandez83d63912009-09-18 22:35:49 +00001602 Constant *Null = Constant::getNullValue(PT->getElementType());
1603 new StoreInst(Null, FieldGlobals[i], SI);
1604 }
1605 // Erase the original store.
1606 SI->eraseFromParent();
1607 }
1608
1609 // While we have PHIs that are interesting to rewrite, do it.
1610 while (!PHIsToRewrite.empty()) {
1611 PHINode *PN = PHIsToRewrite.back().first;
1612 unsigned FieldNo = PHIsToRewrite.back().second;
1613 PHIsToRewrite.pop_back();
1614 PHINode *FieldPN = cast<PHINode>(InsertedScalarizedValues[PN][FieldNo]);
1615 assert(FieldPN->getNumIncomingValues() == 0 &&"Already processed this phi");
1616
1617 // Add all the incoming values. This can materialize more phis.
1618 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1619 Value *InVal = PN->getIncomingValue(i);
1620 InVal = GetHeapSROAValue(InVal, FieldNo, InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001621 PHIsToRewrite);
Victor Hernandez83d63912009-09-18 22:35:49 +00001622 FieldPN->addIncoming(InVal, PN->getIncomingBlock(i));
1623 }
1624 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001625
Victor Hernandez83d63912009-09-18 22:35:49 +00001626 // Drop all inter-phi links and any loads that made it this far.
1627 for (DenseMap<Value*, std::vector<Value*> >::iterator
1628 I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
1629 I != E; ++I) {
1630 if (PHINode *PN = dyn_cast<PHINode>(I->first))
1631 PN->dropAllReferences();
1632 else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
1633 LI->dropAllReferences();
1634 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001635
Victor Hernandez83d63912009-09-18 22:35:49 +00001636 // Delete all the phis and loads now that inter-references are dead.
1637 for (DenseMap<Value*, std::vector<Value*> >::iterator
1638 I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
1639 I != E; ++I) {
1640 if (PHINode *PN = dyn_cast<PHINode>(I->first))
1641 PN->eraseFromParent();
1642 else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
1643 LI->eraseFromParent();
1644 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001645
Victor Hernandez83d63912009-09-18 22:35:49 +00001646 // The old global is now dead, remove it.
1647 GV->eraseFromParent();
1648
1649 ++NumHeapSRA;
1650 return cast<GlobalVariable>(FieldGlobals[0]);
1651}
1652
Chris Lattnere61d0a62008-12-15 21:02:25 +00001653/// TryToOptimizeStoreOfMallocToGlobal - This function is called when we see a
1654/// pointer global variable with a single value stored it that is a malloc or
1655/// cast of malloc.
1656static bool TryToOptimizeStoreOfMallocToGlobal(GlobalVariable *GV,
Victor Hernandez83d63912009-09-18 22:35:49 +00001657 CallInst *CI,
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001658 Type *AllocTy,
Nick Lewyckyfad4d402012-02-05 19:56:38 +00001659 AtomicOrdering Ordering,
Victor Hernandez83d63912009-09-18 22:35:49 +00001660 Module::global_iterator &GVI,
Nick Lewycky6a577f82012-02-12 01:13:18 +00001661 TargetData *TD,
1662 TargetLibraryInfo *TLI) {
Evan Cheng86cd4452010-04-14 20:52:55 +00001663 if (!TD)
1664 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001665
Victor Hernandez83d63912009-09-18 22:35:49 +00001666 // If this is a malloc of an abstract type, don't touch it.
1667 if (!AllocTy->isSized())
1668 return false;
1669
1670 // We can't optimize this global unless all uses of it are *known* to be
1671 // of the malloc value, not of the null initializer value (consider a use
1672 // that compares the global's value against zero to see if the malloc has
1673 // been reached). To do this, we check to see if all uses of the global
1674 // would trap if the global were null: this proves that they must all
1675 // happen after the malloc.
1676 if (!AllUsesOfLoadedValueWillTrapIfNull(GV))
1677 return false;
1678
1679 // We can't optimize this if the malloc itself is used in a complex way,
1680 // for example, being stored into multiple globals. This allows the
Nick Lewyckybc384a12012-02-05 19:48:37 +00001681 // malloc to be stored into the specified global, loaded icmp'd, and
Victor Hernandez83d63912009-09-18 22:35:49 +00001682 // GEP'd. These are all things we could transform to using the global
1683 // for.
Evan Cheng86cd4452010-04-14 20:52:55 +00001684 SmallPtrSet<const PHINode*, 8> PHIs;
1685 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(CI, GV, PHIs))
1686 return false;
Victor Hernandez83d63912009-09-18 22:35:49 +00001687
1688 // If we have a global that is only initialized with a fixed size malloc,
1689 // transform the program to use global memory instead of malloc'd memory.
1690 // This eliminates dynamic allocation, avoids an indirection accessing the
1691 // data, and exposes the resultant global to further GlobalOpt.
Victor Hernandez8db42d22009-10-16 23:12:25 +00001692 // We cannot optimize the malloc if we cannot determine malloc array size.
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +00001693 Value *NElems = getMallocArraySize(CI, TD, TLI, true);
Evan Cheng86cd4452010-04-14 20:52:55 +00001694 if (!NElems)
1695 return false;
Victor Hernandez83d63912009-09-18 22:35:49 +00001696
Evan Cheng86cd4452010-04-14 20:52:55 +00001697 if (ConstantInt *NElements = dyn_cast<ConstantInt>(NElems))
1698 // Restrict this transformation to only working on small allocations
1699 // (2048 bytes currently), as we don't want to introduce a 16M global or
1700 // something.
1701 if (NElements->getZExtValue() * TD->getTypeAllocSize(AllocTy) < 2048) {
Nick Lewycky6a577f82012-02-12 01:13:18 +00001702 GVI = OptimizeGlobalAddressOfMalloc(GV, CI, AllocTy, NElements, TD, TLI);
Evan Cheng86cd4452010-04-14 20:52:55 +00001703 return true;
Victor Hernandez83d63912009-09-18 22:35:49 +00001704 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001705
Evan Cheng86cd4452010-04-14 20:52:55 +00001706 // If the allocation is an array of structures, consider transforming this
1707 // into multiple malloc'd arrays, one for each field. This is basically
1708 // SRoA for malloc'd memory.
1709
Nick Lewyckyfad4d402012-02-05 19:56:38 +00001710 if (Ordering != NotAtomic)
1711 return false;
1712
Evan Cheng86cd4452010-04-14 20:52:55 +00001713 // If this is an allocation of a fixed size array of structs, analyze as a
1714 // variable size array. malloc [100 x struct],1 -> malloc struct, 100
Gabor Greif9e4f2432010-06-24 14:42:01 +00001715 if (NElems == ConstantInt::get(CI->getArgOperand(0)->getType(), 1))
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001716 if (ArrayType *AT = dyn_cast<ArrayType>(AllocTy))
Evan Cheng86cd4452010-04-14 20:52:55 +00001717 AllocTy = AT->getElementType();
Gabor Greif9e4f2432010-06-24 14:42:01 +00001718
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001719 StructType *AllocSTy = dyn_cast<StructType>(AllocTy);
Evan Cheng86cd4452010-04-14 20:52:55 +00001720 if (!AllocSTy)
1721 return false;
1722
1723 // This the structure has an unreasonable number of fields, leave it
1724 // alone.
1725 if (AllocSTy->getNumElements() <= 16 && AllocSTy->getNumElements() != 0 &&
1726 AllGlobalLoadUsesSimpleEnoughForHeapSRA(GV, CI)) {
1727
1728 // If this is a fixed size array, transform the Malloc to be an alloc of
1729 // structs. malloc [100 x struct],1 -> malloc struct, 100
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +00001730 if (ArrayType *AT = dyn_cast<ArrayType>(getMallocAllocatedType(CI, TLI))) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001731 Type *IntPtrTy = TD->getIntPtrType(CI->getContext());
Evan Cheng86cd4452010-04-14 20:52:55 +00001732 unsigned TypeSize = TD->getStructLayout(AllocSTy)->getSizeInBytes();
1733 Value *AllocSize = ConstantInt::get(IntPtrTy, TypeSize);
1734 Value *NumElements = ConstantInt::get(IntPtrTy, AT->getNumElements());
1735 Instruction *Malloc = CallInst::CreateMalloc(CI, IntPtrTy, AllocSTy,
1736 AllocSize, NumElements,
Chris Lattner5a30a852010-07-12 00:57:28 +00001737 0, CI->getName());
Evan Cheng86cd4452010-04-14 20:52:55 +00001738 Instruction *Cast = new BitCastInst(Malloc, CI->getType(), "tmp", CI);
1739 CI->replaceAllUsesWith(Cast);
1740 CI->eraseFromParent();
Nuno Lopeseb7c6862012-06-22 00:25:01 +00001741 if (BitCastInst *BCI = dyn_cast<BitCastInst>(Malloc))
1742 CI = cast<CallInst>(BCI->getOperand(0));
1743 else
Nuno Lopescd88efe2012-06-22 00:29:58 +00001744 CI = cast<CallInst>(Malloc);
Evan Cheng86cd4452010-04-14 20:52:55 +00001745 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001746
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +00001747 GVI = PerformHeapAllocSRoA(GV, CI, getMallocArraySize(CI, TD, TLI, true),
1748 TD, TLI);
Evan Cheng86cd4452010-04-14 20:52:55 +00001749 return true;
Victor Hernandez83d63912009-09-18 22:35:49 +00001750 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001751
Victor Hernandez83d63912009-09-18 22:35:49 +00001752 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001753}
Victor Hernandez83d63912009-09-18 22:35:49 +00001754
Chris Lattner9b34a612004-10-09 21:48:45 +00001755// OptimizeOnceStoredGlobal - Try to optimize globals based on the knowledge
1756// that only one value (besides its initializer) is ever stored to the global.
Chris Lattner30ba5692004-10-11 05:54:41 +00001757static bool OptimizeOnceStoredGlobal(GlobalVariable *GV, Value *StoredOnceVal,
Nick Lewyckyfad4d402012-02-05 19:56:38 +00001758 AtomicOrdering Ordering,
Chris Lattner7f8897f2006-08-27 22:42:52 +00001759 Module::global_iterator &GVI,
Nick Lewycky6a577f82012-02-12 01:13:18 +00001760 TargetData *TD, TargetLibraryInfo *TLI) {
Chris Lattner344b41c2008-12-15 21:20:32 +00001761 // Ignore no-op GEPs and bitcasts.
1762 StoredOnceVal = StoredOnceVal->stripPointerCasts();
Chris Lattner9b34a612004-10-09 21:48:45 +00001763
Chris Lattner708148e2004-10-10 23:14:11 +00001764 // If we are dealing with a pointer global that is initialized to null and
1765 // only has one (non-null) value stored into it, then we can optimize any
1766 // users of the loaded value (often calls and loads) that would trap if the
1767 // value was null.
Duncan Sands1df98592010-02-16 11:11:14 +00001768 if (GV->getInitializer()->getType()->isPointerTy() &&
Chris Lattner9b34a612004-10-09 21:48:45 +00001769 GV->getInitializer()->isNullValue()) {
Chris Lattner708148e2004-10-10 23:14:11 +00001770 if (Constant *SOVC = dyn_cast<Constant>(StoredOnceVal)) {
1771 if (GV->getInitializer()->getType() != SOVC->getType())
Chris Lattner98a42b22011-05-22 07:15:13 +00001772 SOVC = ConstantExpr::getBitCast(SOVC, GV->getInitializer()->getType());
Misha Brukmanfd939082005-04-21 23:48:37 +00001773
Chris Lattner708148e2004-10-10 23:14:11 +00001774 // Optimize away any trapping uses of the loaded value.
Nick Lewycky6a577f82012-02-12 01:13:18 +00001775 if (OptimizeAwayTrappingUsesOfLoads(GV, SOVC, TD, TLI))
Chris Lattner8be80122004-10-10 17:07:12 +00001776 return true;
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +00001777 } else if (CallInst *CI = extractMallocCall(StoredOnceVal, TLI)) {
1778 Type *MallocType = getMallocAllocatedType(CI, TLI);
Nick Lewycky6a577f82012-02-12 01:13:18 +00001779 if (MallocType &&
1780 TryToOptimizeStoreOfMallocToGlobal(GV, CI, MallocType, Ordering, GVI,
1781 TD, TLI))
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001782 return true;
Chris Lattner708148e2004-10-10 23:14:11 +00001783 }
Chris Lattner9b34a612004-10-09 21:48:45 +00001784 }
Chris Lattner30ba5692004-10-11 05:54:41 +00001785
Chris Lattner9b34a612004-10-09 21:48:45 +00001786 return false;
1787}
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001788
Chris Lattner58e44f42008-01-14 01:17:44 +00001789/// TryToShrinkGlobalToBoolean - At this point, we have learned that the only
1790/// two values ever stored into GV are its initializer and OtherVal. See if we
1791/// can shrink the global into a boolean and select between the two values
1792/// whenever it is used. This exposes the values to other scalar optimizations.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001793static bool TryToShrinkGlobalToBoolean(GlobalVariable *GV, Constant *OtherVal) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001794 Type *GVElType = GV->getType()->getElementType();
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001795
Chris Lattner58e44f42008-01-14 01:17:44 +00001796 // If GVElType is already i1, it is already shrunk. If the type of the GV is
Chris Lattner6f6923f2009-03-07 23:32:02 +00001797 // an FP value, pointer or vector, don't do this optimization because a select
1798 // between them is very expensive and unlikely to lead to later
1799 // simplification. In these cases, we typically end up with "cond ? v1 : v2"
1800 // where v1 and v2 both require constant pool loads, a big loss.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001801 if (GVElType == Type::getInt1Ty(GV->getContext()) ||
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001802 GVElType->isFloatingPointTy() ||
Duncan Sands1df98592010-02-16 11:11:14 +00001803 GVElType->isPointerTy() || GVElType->isVectorTy())
Chris Lattner58e44f42008-01-14 01:17:44 +00001804 return false;
Gabor Greifaaaaa022010-07-12 14:13:15 +00001805
Chris Lattner58e44f42008-01-14 01:17:44 +00001806 // Walk the use list of the global seeing if all the uses are load or store.
1807 // If there is anything else, bail out.
Gabor Greifaaaaa022010-07-12 14:13:15 +00001808 for (Value::use_iterator I = GV->use_begin(), E = GV->use_end(); I != E; ++I){
1809 User *U = *I;
1810 if (!isa<LoadInst>(U) && !isa<StoreInst>(U))
Chris Lattner58e44f42008-01-14 01:17:44 +00001811 return false;
Gabor Greifaaaaa022010-07-12 14:13:15 +00001812 }
1813
David Greene3215b0e2010-01-05 01:28:05 +00001814 DEBUG(dbgs() << " *** SHRINKING TO BOOL: " << *GV);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001815
Chris Lattner96a86b22004-12-12 05:53:50 +00001816 // Create the new global, initializing it to false.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001817 GlobalVariable *NewGV = new GlobalVariable(Type::getInt1Ty(GV->getContext()),
1818 false,
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001819 GlobalValue::InternalLinkage,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001820 ConstantInt::getFalse(GV->getContext()),
Nick Lewycky0e670df2009-05-03 03:49:08 +00001821 GV->getName()+".b",
Hans Wennborgce718ff2012-06-23 11:37:03 +00001822 GV->getThreadLocalMode());
Chris Lattner96a86b22004-12-12 05:53:50 +00001823 GV->getParent()->getGlobalList().insert(GV, NewGV);
1824
1825 Constant *InitVal = GV->getInitializer();
Chris Lattner7b550cc2009-11-06 04:27:31 +00001826 assert(InitVal->getType() != Type::getInt1Ty(GV->getContext()) &&
Owen Anderson1d0be152009-08-13 21:58:54 +00001827 "No reason to shrink to bool!");
Chris Lattner96a86b22004-12-12 05:53:50 +00001828
1829 // If initialized to zero and storing one into the global, we can use a cast
1830 // instead of a select to synthesize the desired value.
1831 bool IsOneZero = false;
1832 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal))
Reid Spencercae57542007-03-02 00:28:52 +00001833 IsOneZero = InitVal->isNullValue() && CI->isOne();
Chris Lattner96a86b22004-12-12 05:53:50 +00001834
1835 while (!GV->use_empty()) {
Devang Patel771281f2009-03-06 01:39:36 +00001836 Instruction *UI = cast<Instruction>(GV->use_back());
1837 if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
Chris Lattner96a86b22004-12-12 05:53:50 +00001838 // Change the store into a boolean store.
1839 bool StoringOther = SI->getOperand(0) == OtherVal;
1840 // Only do this if we weren't storing a loaded value.
Chris Lattner38c25562004-12-12 19:34:41 +00001841 Value *StoreVal;
Chris Lattner96a86b22004-12-12 05:53:50 +00001842 if (StoringOther || SI->getOperand(0) == InitVal)
Chris Lattner7b550cc2009-11-06 04:27:31 +00001843 StoreVal = ConstantInt::get(Type::getInt1Ty(GV->getContext()),
1844 StoringOther);
Chris Lattner38c25562004-12-12 19:34:41 +00001845 else {
1846 // Otherwise, we are storing a previously loaded copy. To do this,
1847 // change the copy from copying the original value to just copying the
1848 // bool.
1849 Instruction *StoredVal = cast<Instruction>(SI->getOperand(0));
1850
Gabor Greif9e4f2432010-06-24 14:42:01 +00001851 // If we've already replaced the input, StoredVal will be a cast or
Chris Lattner38c25562004-12-12 19:34:41 +00001852 // select instruction. If not, it will be a load of the original
1853 // global.
1854 if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
1855 assert(LI->getOperand(0) == GV && "Not a copy!");
1856 // Insert a new load, to preserve the saved value.
Nick Lewyckyfad4d402012-02-05 19:56:38 +00001857 StoreVal = new LoadInst(NewGV, LI->getName()+".b", false, 0,
1858 LI->getOrdering(), LI->getSynchScope(), LI);
Chris Lattner38c25562004-12-12 19:34:41 +00001859 } else {
1860 assert((isa<CastInst>(StoredVal) || isa<SelectInst>(StoredVal)) &&
1861 "This is not a form that we understand!");
1862 StoreVal = StoredVal->getOperand(0);
1863 assert(isa<LoadInst>(StoreVal) && "Not a load of NewGV!");
1864 }
1865 }
Nick Lewyckyfad4d402012-02-05 19:56:38 +00001866 new StoreInst(StoreVal, NewGV, false, 0,
1867 SI->getOrdering(), SI->getSynchScope(), SI);
Devang Patel771281f2009-03-06 01:39:36 +00001868 } else {
Chris Lattner96a86b22004-12-12 05:53:50 +00001869 // Change the load into a load of bool then a select.
Devang Patel771281f2009-03-06 01:39:36 +00001870 LoadInst *LI = cast<LoadInst>(UI);
Nick Lewyckyfad4d402012-02-05 19:56:38 +00001871 LoadInst *NLI = new LoadInst(NewGV, LI->getName()+".b", false, 0,
1872 LI->getOrdering(), LI->getSynchScope(), LI);
Chris Lattner96a86b22004-12-12 05:53:50 +00001873 Value *NSI;
1874 if (IsOneZero)
Chris Lattner046800a2007-02-11 01:08:35 +00001875 NSI = new ZExtInst(NLI, LI->getType(), "", LI);
Misha Brukmanfd939082005-04-21 23:48:37 +00001876 else
Gabor Greif051a9502008-04-06 20:25:17 +00001877 NSI = SelectInst::Create(NLI, OtherVal, InitVal, "", LI);
Chris Lattner046800a2007-02-11 01:08:35 +00001878 NSI->takeName(LI);
Chris Lattner96a86b22004-12-12 05:53:50 +00001879 LI->replaceAllUsesWith(NSI);
Devang Patel771281f2009-03-06 01:39:36 +00001880 }
1881 UI->eraseFromParent();
Chris Lattner96a86b22004-12-12 05:53:50 +00001882 }
1883
1884 GV->eraseFromParent();
Chris Lattner58e44f42008-01-14 01:17:44 +00001885 return true;
Chris Lattner96a86b22004-12-12 05:53:50 +00001886}
1887
1888
Nick Lewyckydb292a62012-02-12 00:52:26 +00001889/// ProcessGlobal - Analyze the specified global variable and optimize it if
1890/// possible. If we make a change, return true.
Rafael Espindolac4440e32011-01-19 16:32:21 +00001891bool GlobalOpt::ProcessGlobal(GlobalVariable *GV,
1892 Module::global_iterator &GVI) {
Rafael Espindola03977292012-06-14 22:48:13 +00001893 if (!GV->isDiscardableIfUnused())
Rafael Espindolac4440e32011-01-19 16:32:21 +00001894 return false;
1895
1896 // Do more involved optimizations if the global is internal.
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001897 GV->removeDeadConstantUsers();
1898
1899 if (GV->use_empty()) {
David Greene3215b0e2010-01-05 01:28:05 +00001900 DEBUG(dbgs() << "GLOBAL DEAD: " << *GV);
Chris Lattner7a7ed022004-10-16 18:09:00 +00001901 GV->eraseFromParent();
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001902 ++NumDeleted;
1903 return true;
1904 }
1905
Rafael Espindola2f135d42012-06-15 18:00:24 +00001906 if (!GV->hasLocalLinkage())
1907 return false;
1908
Rafael Espindolac4440e32011-01-19 16:32:21 +00001909 SmallPtrSet<const PHINode*, 16> PHIUsers;
1910 GlobalStatus GS;
1911
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001912 if (AnalyzeGlobal(GV, GS, PHIUsers))
1913 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001914
Rafael Espindolac4440e32011-01-19 16:32:21 +00001915 if (!GS.isCompared && !GV->hasUnnamedAddr()) {
1916 GV->setUnnamedAddr(true);
1917 NumUnnamed++;
1918 }
1919
1920 if (GV->isConstant() || !GV->hasInitializer())
1921 return false;
1922
1923 return ProcessInternalGlobal(GV, GVI, PHIUsers, GS);
1924}
1925
1926/// ProcessInternalGlobal - Analyze the specified global variable and optimize
1927/// it if possible. If we make a change, return true.
1928bool GlobalOpt::ProcessInternalGlobal(GlobalVariable *GV,
1929 Module::global_iterator &GVI,
Nick Lewyckydb292a62012-02-12 00:52:26 +00001930 const SmallPtrSet<const PHINode*, 16> &PHIUsers,
Rafael Espindolac4440e32011-01-19 16:32:21 +00001931 const GlobalStatus &GS) {
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001932 // If this is a first class global and has only one accessing function
1933 // and this function is main (which we know is not recursive we can make
1934 // this global a local variable) we replace the global with a local alloca
1935 // in this function.
1936 //
1937 // NOTE: It doesn't make sense to promote non single-value types since we
1938 // are just replacing static memory to stack memory.
1939 //
1940 // If the global is in different address space, don't bring it to stack.
1941 if (!GS.HasMultipleAccessingFunctions &&
1942 GS.AccessingFunction && !GS.HasNonInstructionUser &&
1943 GV->getType()->getElementType()->isSingleValueType() &&
1944 GS.AccessingFunction->getName() == "main" &&
1945 GS.AccessingFunction->hasExternalLinkage() &&
1946 GV->getType()->getAddressSpace() == 0) {
1947 DEBUG(dbgs() << "LOCALIZING GLOBAL: " << *GV);
Nick Lewyckybc384a12012-02-05 19:48:37 +00001948 Instruction &FirstI = const_cast<Instruction&>(*GS.AccessingFunction
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001949 ->getEntryBlock().begin());
Nick Lewyckybc384a12012-02-05 19:48:37 +00001950 Type *ElemTy = GV->getType()->getElementType();
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001951 // FIXME: Pass Global's alignment when globals have alignment
Nick Lewyckybc384a12012-02-05 19:48:37 +00001952 AllocaInst *Alloca = new AllocaInst(ElemTy, NULL, GV->getName(), &FirstI);
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001953 if (!isa<UndefValue>(GV->getInitializer()))
1954 new StoreInst(GV->getInitializer(), Alloca, &FirstI);
Misha Brukmanfd939082005-04-21 23:48:37 +00001955
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001956 GV->replaceAllUsesWith(Alloca);
1957 GV->eraseFromParent();
1958 ++NumLocalized;
1959 return true;
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001960 }
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001961
1962 // If the global is never loaded (but may be stored to), it is dead.
1963 // Delete it now.
1964 if (!GS.isLoaded) {
1965 DEBUG(dbgs() << "GLOBAL NEVER LOADED: " << *GV);
1966
Nick Lewycky8899d5c2012-07-24 07:21:08 +00001967 bool Changed;
1968 if (isLeakCheckerRoot(GV)) {
1969 // Delete any constant stores to the global.
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +00001970 Changed = CleanupPointerRootUsers(GV, TLI);
Nick Lewycky8899d5c2012-07-24 07:21:08 +00001971 } else {
1972 // Delete any stores we can find to the global. We may not be able to
1973 // make it completely dead though.
1974 Changed = CleanupConstantGlobalUsers(GV, GV->getInitializer(), TD, TLI);
1975 }
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001976
1977 // If the global is dead now, delete it.
1978 if (GV->use_empty()) {
1979 GV->eraseFromParent();
1980 ++NumDeleted;
1981 Changed = true;
1982 }
1983 return Changed;
1984
1985 } else if (GS.StoredType <= GlobalStatus::isInitializerStored) {
1986 DEBUG(dbgs() << "MARKING CONSTANT: " << *GV);
1987 GV->setConstant(true);
1988
1989 // Clean up any obviously simplifiable users now.
Nick Lewycky6a577f82012-02-12 01:13:18 +00001990 CleanupConstantGlobalUsers(GV, GV->getInitializer(), TD, TLI);
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001991
1992 // If the global is dead now, just nuke it.
1993 if (GV->use_empty()) {
1994 DEBUG(dbgs() << " *** Marking constant allowed us to simplify "
1995 << "all users and delete global!\n");
1996 GV->eraseFromParent();
1997 ++NumDeleted;
1998 }
1999
2000 ++NumMarked;
2001 return true;
2002 } else if (!GV->getInitializer()->getType()->isSingleValueType()) {
2003 if (TargetData *TD = getAnalysisIfAvailable<TargetData>())
2004 if (GlobalVariable *FirstNewGV = SRAGlobal(GV, *TD)) {
2005 GVI = FirstNewGV; // Don't skip the newly produced globals!
2006 return true;
2007 }
2008 } else if (GS.StoredType == GlobalStatus::isStoredOnce) {
2009 // If the initial value for the global was an undef value, and if only
2010 // one other value was stored into it, we can just change the
2011 // initializer to be the stored value, then delete all stores to the
2012 // global. This allows us to mark it constant.
2013 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
2014 if (isa<UndefValue>(GV->getInitializer())) {
2015 // Change the initial value here.
2016 GV->setInitializer(SOVConstant);
2017
2018 // Clean up any obviously simplifiable users now.
Nick Lewycky6a577f82012-02-12 01:13:18 +00002019 CleanupConstantGlobalUsers(GV, GV->getInitializer(), TD, TLI);
Rafael Espindoladaad56a2011-01-18 04:36:06 +00002020
2021 if (GV->use_empty()) {
2022 DEBUG(dbgs() << " *** Substituting initializer allowed us to "
Nick Lewycky8899d5c2012-07-24 07:21:08 +00002023 << "simplify all users and delete global!\n");
Rafael Espindoladaad56a2011-01-18 04:36:06 +00002024 GV->eraseFromParent();
2025 ++NumDeleted;
2026 } else {
2027 GVI = GV;
2028 }
2029 ++NumSubstitute;
2030 return true;
2031 }
2032
2033 // Try to optimize globals based on the knowledge that only one value
2034 // (besides its initializer) is ever stored to the global.
Nick Lewyckyfad4d402012-02-05 19:56:38 +00002035 if (OptimizeOnceStoredGlobal(GV, GS.StoredOnceValue, GS.Ordering, GVI,
Nick Lewycky6a577f82012-02-12 01:13:18 +00002036 TD, TLI))
Rafael Espindoladaad56a2011-01-18 04:36:06 +00002037 return true;
2038
2039 // Otherwise, if the global was not a boolean, we can shrink it to be a
2040 // boolean.
2041 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
2042 if (TryToShrinkGlobalToBoolean(GV, SOVConstant)) {
2043 ++NumShrunkToBool;
2044 return true;
2045 }
2046 }
2047
Chris Lattnera4be1dc2004-10-08 20:59:28 +00002048 return false;
2049}
2050
Chris Lattnerfb217ad2005-05-08 22:18:06 +00002051/// ChangeCalleesToFastCall - Walk all of the direct calls of the specified
2052/// function, changing them to FastCC.
2053static void ChangeCalleesToFastCall(Function *F) {
2054 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
Jay Foadb7454fd2012-05-12 08:30:16 +00002055 if (isa<BlockAddress>(*UI))
2056 continue;
Duncan Sands548448a2008-02-18 17:32:13 +00002057 CallSite User(cast<Instruction>(*UI));
2058 User.setCallingConv(CallingConv::Fast);
Chris Lattnerfb217ad2005-05-08 22:18:06 +00002059 }
2060}
Chris Lattnera4be1dc2004-10-08 20:59:28 +00002061
Devang Patel05988662008-09-25 21:00:45 +00002062static AttrListPtr StripNest(const AttrListPtr &Attrs) {
Chris Lattner58d74912008-03-12 17:45:29 +00002063 for (unsigned i = 0, e = Attrs.getNumSlots(); i != e; ++i) {
Devang Patel05988662008-09-25 21:00:45 +00002064 if ((Attrs.getSlot(i).Attrs & Attribute::Nest) == 0)
Duncan Sands548448a2008-02-18 17:32:13 +00002065 continue;
2066
Duncan Sands548448a2008-02-18 17:32:13 +00002067 // There can be only one.
Devang Patel05988662008-09-25 21:00:45 +00002068 return Attrs.removeAttr(Attrs.getSlot(i).Index, Attribute::Nest);
Duncan Sands3d5378f2008-02-16 20:56:04 +00002069 }
2070
2071 return Attrs;
2072}
2073
2074static void RemoveNestAttribute(Function *F) {
Devang Patel05988662008-09-25 21:00:45 +00002075 F->setAttributes(StripNest(F->getAttributes()));
Duncan Sands3d5378f2008-02-16 20:56:04 +00002076 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
Jay Foadb7454fd2012-05-12 08:30:16 +00002077 if (isa<BlockAddress>(*UI))
2078 continue;
Duncan Sands548448a2008-02-18 17:32:13 +00002079 CallSite User(cast<Instruction>(*UI));
Devang Patel05988662008-09-25 21:00:45 +00002080 User.setAttributes(StripNest(User.getAttributes()));
Duncan Sands3d5378f2008-02-16 20:56:04 +00002081 }
2082}
2083
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002084bool GlobalOpt::OptimizeFunctions(Module &M) {
2085 bool Changed = false;
2086 // Optimize functions.
2087 for (Module::iterator FI = M.begin(), E = M.end(); FI != E; ) {
2088 Function *F = FI++;
Duncan Sandsfc5940d2009-03-06 10:21:56 +00002089 // Functions without names cannot be referenced outside this module.
2090 if (!F->hasName() && !F->isDeclaration())
2091 F->setLinkage(GlobalValue::InternalLinkage);
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002092 F->removeDeadConstantUsers();
Eli Friedmanc6633052011-10-20 05:23:42 +00002093 if (F->isDefTriviallyDead()) {
Chris Lattnerec4c7b92009-11-01 19:03:42 +00002094 F->eraseFromParent();
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002095 Changed = true;
2096 ++NumFnDeleted;
Rafael Espindolabb46f522009-01-15 20:18:42 +00002097 } else if (F->hasLocalLinkage()) {
Duncan Sands3d5378f2008-02-16 20:56:04 +00002098 if (F->getCallingConv() == CallingConv::C && !F->isVarArg() &&
Jay Foad757068f2009-06-10 08:41:11 +00002099 !F->hasAddressTaken()) {
Duncan Sands3d5378f2008-02-16 20:56:04 +00002100 // If this function has C calling conventions, is not a varargs
2101 // function, and is only called directly, promote it to use the Fast
2102 // calling convention.
2103 F->setCallingConv(CallingConv::Fast);
2104 ChangeCalleesToFastCall(F);
2105 ++NumFastCallFns;
2106 Changed = true;
2107 }
2108
Devang Patel05988662008-09-25 21:00:45 +00002109 if (F->getAttributes().hasAttrSomewhere(Attribute::Nest) &&
Jay Foad757068f2009-06-10 08:41:11 +00002110 !F->hasAddressTaken()) {
Duncan Sands3d5378f2008-02-16 20:56:04 +00002111 // The function is not used by a trampoline intrinsic, so it is safe
2112 // to remove the 'nest' attribute.
2113 RemoveNestAttribute(F);
2114 ++NumNestRemoved;
2115 Changed = true;
2116 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002117 }
2118 }
2119 return Changed;
2120}
2121
2122bool GlobalOpt::OptimizeGlobalVars(Module &M) {
2123 bool Changed = false;
2124 for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
2125 GVI != E; ) {
2126 GlobalVariable *GV = GVI++;
Duncan Sandsfc5940d2009-03-06 10:21:56 +00002127 // Global variables without names cannot be referenced outside this module.
2128 if (!GV->hasName() && !GV->isDeclaration())
2129 GV->setLinkage(GlobalValue::InternalLinkage);
Dan Gohman01b97dd2009-11-23 16:22:21 +00002130 // Simplify the initializer.
2131 if (GV->hasInitializer())
2132 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GV->getInitializer())) {
Chad Rosieraab8e282011-12-02 01:26:24 +00002133 Constant *New = ConstantFoldConstantExpression(CE, TD, TLI);
Dan Gohman01b97dd2009-11-23 16:22:21 +00002134 if (New && New != CE)
2135 GV->setInitializer(New);
2136 }
Rafael Espindolac4440e32011-01-19 16:32:21 +00002137
2138 Changed |= ProcessGlobal(GV, GVI);
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002139 }
2140 return Changed;
2141}
2142
Nick Lewycky2c44a802011-04-08 07:30:21 +00002143/// FindGlobalCtors - Find the llvm.global_ctors list, verifying that all
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002144/// initializers have an init priority of 65535.
2145GlobalVariable *GlobalOpt::FindGlobalCtors(Module &M) {
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00002146 GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
2147 if (GV == 0) return 0;
2148
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00002149 // Verify that the initializer is simple enough for us to handle. We are
2150 // only allowed to optimize the initializer if it is unique.
2151 if (!GV->hasUniqueInitializer()) return 0;
Nick Lewycky5ea5c612011-04-11 22:11:20 +00002152
2153 if (isa<ConstantAggregateZero>(GV->getInitializer()))
2154 return GV;
2155 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
Eli Friedman18a2e502011-04-09 09:11:09 +00002156
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00002157 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i) {
Nick Lewycky5ea5c612011-04-11 22:11:20 +00002158 if (isa<ConstantAggregateZero>(*i))
2159 continue;
2160 ConstantStruct *CS = cast<ConstantStruct>(*i);
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00002161 if (isa<ConstantPointerNull>(CS->getOperand(1)))
2162 continue;
Chris Lattner7d8e58f2005-09-26 02:19:27 +00002163
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00002164 // Must have a function or null ptr.
2165 if (!isa<Function>(CS->getOperand(1)))
2166 return 0;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002167
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00002168 // Init priority must be standard.
Nick Lewycky2c44a802011-04-08 07:30:21 +00002169 ConstantInt *CI = cast<ConstantInt>(CS->getOperand(0));
2170 if (CI->getZExtValue() != 65535)
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00002171 return 0;
2172 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002173
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00002174 return GV;
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002175}
2176
Chris Lattnerdb973e62005-09-26 02:31:18 +00002177/// ParseGlobalCtors - Given a llvm.global_ctors list that we can understand,
2178/// return a list of the functions and null terminator as a vector.
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002179static std::vector<Function*> ParseGlobalCtors(GlobalVariable *GV) {
Nick Lewycky5ea5c612011-04-11 22:11:20 +00002180 if (GV->getInitializer()->isNullValue())
2181 return std::vector<Function*>();
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002182 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
2183 std::vector<Function*> Result;
2184 Result.reserve(CA->getNumOperands());
Gabor Greif5e463212008-05-29 01:59:18 +00002185 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i) {
2186 ConstantStruct *CS = cast<ConstantStruct>(*i);
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002187 Result.push_back(dyn_cast<Function>(CS->getOperand(1)));
2188 }
2189 return Result;
2190}
2191
Chris Lattnerdb973e62005-09-26 02:31:18 +00002192/// InstallGlobalCtors - Given a specified llvm.global_ctors list, install the
2193/// specified array, returning the new global to use.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002194static GlobalVariable *InstallGlobalCtors(GlobalVariable *GCL,
Chris Lattner7b550cc2009-11-06 04:27:31 +00002195 const std::vector<Function*> &Ctors) {
Chris Lattnerdb973e62005-09-26 02:31:18 +00002196 // If we made a change, reassemble the initializer list.
Chris Lattnerb065b062011-06-20 04:01:31 +00002197 Constant *CSVals[2];
2198 CSVals[0] = ConstantInt::get(Type::getInt32Ty(GCL->getContext()), 65535);
2199 CSVals[1] = 0;
2200
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002201 StructType *StructTy =
Chris Lattnerb065b062011-06-20 04:01:31 +00002202 cast <StructType>(
2203 cast<ArrayType>(GCL->getType()->getElementType())->getElementType());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002204
Chris Lattnerdb973e62005-09-26 02:31:18 +00002205 // Create the new init list.
2206 std::vector<Constant*> CAList;
2207 for (unsigned i = 0, e = Ctors.size(); i != e; ++i) {
Chris Lattner79c11012005-09-26 04:44:35 +00002208 if (Ctors[i]) {
Chris Lattnerdb973e62005-09-26 02:31:18 +00002209 CSVals[1] = Ctors[i];
Chris Lattner79c11012005-09-26 04:44:35 +00002210 } else {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002211 Type *FTy = FunctionType::get(Type::getVoidTy(GCL->getContext()),
Chris Lattner7b550cc2009-11-06 04:27:31 +00002212 false);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002213 PointerType *PFTy = PointerType::getUnqual(FTy);
Owen Andersona7235ea2009-07-31 20:28:14 +00002214 CSVals[1] = Constant::getNullValue(PFTy);
Chris Lattner7b550cc2009-11-06 04:27:31 +00002215 CSVals[0] = ConstantInt::get(Type::getInt32Ty(GCL->getContext()),
Nick Lewycky5ea5c612011-04-11 22:11:20 +00002216 0x7fffffff);
Chris Lattnerdb973e62005-09-26 02:31:18 +00002217 }
Chris Lattnerb065b062011-06-20 04:01:31 +00002218 CAList.push_back(ConstantStruct::get(StructTy, CSVals));
Chris Lattnerdb973e62005-09-26 02:31:18 +00002219 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002220
Chris Lattnerdb973e62005-09-26 02:31:18 +00002221 // Create the array initializer.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002222 Constant *CA = ConstantArray::get(ArrayType::get(StructTy,
Nick Lewyckyc332fba2009-09-19 20:30:26 +00002223 CAList.size()), CAList);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002224
Chris Lattnerdb973e62005-09-26 02:31:18 +00002225 // If we didn't change the number of elements, don't create a new GV.
2226 if (CA->getType() == GCL->getInitializer()->getType()) {
2227 GCL->setInitializer(CA);
2228 return GCL;
2229 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002230
Chris Lattnerdb973e62005-09-26 02:31:18 +00002231 // Create the new global and insert it next to the existing list.
Chris Lattner7b550cc2009-11-06 04:27:31 +00002232 GlobalVariable *NGV = new GlobalVariable(CA->getType(), GCL->isConstant(),
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +00002233 GCL->getLinkage(), CA, "",
Hans Wennborgce718ff2012-06-23 11:37:03 +00002234 GCL->getThreadLocalMode());
Chris Lattnerdb973e62005-09-26 02:31:18 +00002235 GCL->getParent()->getGlobalList().insert(GCL, NGV);
Chris Lattner046800a2007-02-11 01:08:35 +00002236 NGV->takeName(GCL);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002237
Chris Lattnerdb973e62005-09-26 02:31:18 +00002238 // Nuke the old list, replacing any uses with the new one.
2239 if (!GCL->use_empty()) {
2240 Constant *V = NGV;
2241 if (V->getType() != GCL->getType())
Owen Andersonbaf3c402009-07-29 18:55:55 +00002242 V = ConstantExpr::getBitCast(V, GCL->getType());
Chris Lattnerdb973e62005-09-26 02:31:18 +00002243 GCL->replaceAllUsesWith(V);
2244 }
2245 GCL->eraseFromParent();
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002246
Chris Lattnerdb973e62005-09-26 02:31:18 +00002247 if (Ctors.size())
2248 return NGV;
2249 else
2250 return 0;
2251}
Chris Lattner79c11012005-09-26 04:44:35 +00002252
2253
Chris Lattner1945d582010-12-07 04:33:29 +00002254static inline bool
2255isSimpleEnoughValueToCommit(Constant *C,
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002256 SmallPtrSet<Constant*, 8> &SimpleConstants,
2257 const TargetData *TD);
Chris Lattner1945d582010-12-07 04:33:29 +00002258
2259
2260/// isSimpleEnoughValueToCommit - Return true if the specified constant can be
2261/// handled by the code generator. We don't want to generate something like:
2262/// void *X = &X/42;
2263/// because the code generator doesn't have a relocation that can handle that.
2264///
2265/// This function should be called if C was not found (but just got inserted)
2266/// in SimpleConstants to avoid having to rescan the same constants all the
2267/// time.
2268static bool isSimpleEnoughValueToCommitHelper(Constant *C,
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002269 SmallPtrSet<Constant*, 8> &SimpleConstants,
2270 const TargetData *TD) {
Chris Lattner1945d582010-12-07 04:33:29 +00002271 // Simple integer, undef, constant aggregate zero, global addresses, etc are
2272 // all supported.
2273 if (C->getNumOperands() == 0 || isa<BlockAddress>(C) ||
2274 isa<GlobalValue>(C))
2275 return true;
2276
2277 // Aggregate values are safe if all their elements are.
2278 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C) ||
2279 isa<ConstantVector>(C)) {
2280 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i) {
2281 Constant *Op = cast<Constant>(C->getOperand(i));
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002282 if (!isSimpleEnoughValueToCommit(Op, SimpleConstants, TD))
Chris Lattner1945d582010-12-07 04:33:29 +00002283 return false;
2284 }
2285 return true;
2286 }
2287
2288 // We don't know exactly what relocations are allowed in constant expressions,
2289 // so we allow &global+constantoffset, which is safe and uniformly supported
2290 // across targets.
2291 ConstantExpr *CE = cast<ConstantExpr>(C);
2292 switch (CE->getOpcode()) {
2293 case Instruction::BitCast:
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002294 // Bitcast is fine if the casted value is fine.
2295 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, TD);
2296
Chris Lattner1945d582010-12-07 04:33:29 +00002297 case Instruction::IntToPtr:
2298 case Instruction::PtrToInt:
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002299 // int <=> ptr is fine if the int type is the same size as the
2300 // pointer type.
2301 if (!TD || TD->getTypeSizeInBits(CE->getType()) !=
2302 TD->getTypeSizeInBits(CE->getOperand(0)->getType()))
2303 return false;
2304 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, TD);
Chris Lattner1945d582010-12-07 04:33:29 +00002305
2306 // GEP is fine if it is simple + constant offset.
2307 case Instruction::GetElementPtr:
2308 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
2309 if (!isa<ConstantInt>(CE->getOperand(i)))
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 case Instruction::Add:
2314 // We allow simple+cst.
2315 if (!isa<ConstantInt>(CE->getOperand(1)))
2316 return false;
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002317 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, TD);
Chris Lattner1945d582010-12-07 04:33:29 +00002318 }
2319 return false;
2320}
2321
2322static inline bool
2323isSimpleEnoughValueToCommit(Constant *C,
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002324 SmallPtrSet<Constant*, 8> &SimpleConstants,
2325 const TargetData *TD) {
Chris Lattner1945d582010-12-07 04:33:29 +00002326 // If we already checked this constant, we win.
2327 if (!SimpleConstants.insert(C)) return true;
2328 // Check the constant.
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002329 return isSimpleEnoughValueToCommitHelper(C, SimpleConstants, TD);
Chris Lattner1945d582010-12-07 04:33:29 +00002330}
2331
2332
Chris Lattner79c11012005-09-26 04:44:35 +00002333/// isSimpleEnoughPointerToCommit - Return true if this constant is simple
Owen Andersoncff6b372011-01-14 22:19:20 +00002334/// enough for us to understand. In particular, if it is a cast to anything
2335/// other than from one pointer type to another pointer type, we punt.
2336/// We basically just support direct accesses to globals and GEP's of
Chris Lattner79c11012005-09-26 04:44:35 +00002337/// globals. This should be kept up to date with CommitValueTo.
Chris Lattner7b550cc2009-11-06 04:27:31 +00002338static bool isSimpleEnoughPointerToCommit(Constant *C) {
Dan Gohmance5de5b2009-09-07 22:42:05 +00002339 // Conservatively, avoid aggregate types. This is because we don't
2340 // want to worry about them partially overlapping other stores.
2341 if (!cast<PointerType>(C->getType())->getElementType()->isSingleValueType())
2342 return false;
2343
Dan Gohmanfd54a892009-09-07 22:31:26 +00002344 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
Mikhail Glushenkov99fca5d2010-10-19 16:47:23 +00002345 // Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or
Dan Gohmanfd54a892009-09-07 22:31:26 +00002346 // external globals.
Mikhail Glushenkov99fca5d2010-10-19 16:47:23 +00002347 return GV->hasUniqueInitializer();
Dan Gohmanfd54a892009-09-07 22:31:26 +00002348
Owen Andersone95a32c2011-01-14 22:31:13 +00002349 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002350 // Handle a constantexpr gep.
2351 if (CE->getOpcode() == Instruction::GetElementPtr &&
Dan Gohmanc62482d2009-09-07 22:40:13 +00002352 isa<GlobalVariable>(CE->getOperand(0)) &&
2353 cast<GEPOperator>(CE)->isInBounds()) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002354 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
Mikhail Glushenkov99fca5d2010-10-19 16:47:23 +00002355 // Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or
Dan Gohmanfd54a892009-09-07 22:31:26 +00002356 // external globals.
Mikhail Glushenkov99fca5d2010-10-19 16:47:23 +00002357 if (!GV->hasUniqueInitializer())
Dan Gohmanfd54a892009-09-07 22:31:26 +00002358 return false;
Dan Gohman80bdc962009-09-07 22:44:55 +00002359
Dan Gohman80bdc962009-09-07 22:44:55 +00002360 // The first index must be zero.
Oscar Fuentesee56c422010-08-02 06:00:15 +00002361 ConstantInt *CI = dyn_cast<ConstantInt>(*llvm::next(CE->op_begin()));
Dan Gohman80bdc962009-09-07 22:44:55 +00002362 if (!CI || !CI->isZero()) return false;
Dan Gohman80bdc962009-09-07 22:44:55 +00002363
2364 // The remaining indices must be compile-time known integers within the
Dan Gohmane6992f72009-09-10 23:37:55 +00002365 // notional bounds of the corresponding static array types.
2366 if (!CE->isGEPWithNoNotionalOverIndexing())
2367 return false;
Dan Gohman80bdc962009-09-07 22:44:55 +00002368
Dan Gohmanc6f69e92009-10-05 16:36:26 +00002369 return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
Owen Andersoncff6b372011-01-14 22:19:20 +00002370
2371 // A constantexpr bitcast from a pointer to another pointer is a no-op,
2372 // and we know how to evaluate it by moving the bitcast from the pointer
2373 // operand to the value operand.
2374 } else if (CE->getOpcode() == Instruction::BitCast &&
Chris Lattnerd5f656f2011-01-16 02:05:10 +00002375 isa<GlobalVariable>(CE->getOperand(0))) {
Owen Andersoncff6b372011-01-14 22:19:20 +00002376 // Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or
2377 // external globals.
Chris Lattnerd5f656f2011-01-16 02:05:10 +00002378 return cast<GlobalVariable>(CE->getOperand(0))->hasUniqueInitializer();
Chris Lattner798b4d52005-09-26 06:52:44 +00002379 }
Owen Andersone95a32c2011-01-14 22:31:13 +00002380 }
2381
Chris Lattner79c11012005-09-26 04:44:35 +00002382 return false;
2383}
2384
Chris Lattner798b4d52005-09-26 06:52:44 +00002385/// EvaluateStoreInto - Evaluate a piece of a constantexpr store into a global
2386/// initializer. This returns 'Init' modified to reflect 'Val' stored into it.
2387/// At this point, the GEP operands of Addr [0, OpNo) have been stepped into.
2388static Constant *EvaluateStoreInto(Constant *Init, Constant *Val,
Chris Lattner7b550cc2009-11-06 04:27:31 +00002389 ConstantExpr *Addr, unsigned OpNo) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002390 // Base case of the recursion.
2391 if (OpNo == Addr->getNumOperands()) {
2392 assert(Val->getType() == Init->getType() && "Type mismatch!");
2393 return Val;
2394 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002395
Chris Lattnera78fa8c2012-01-27 03:08:05 +00002396 SmallVector<Constant*, 32> Elts;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002397 if (StructType *STy = dyn_cast<StructType>(Init->getType())) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002398 // Break up the constant into its elements.
Chris Lattnerd59ae902012-01-26 02:32:04 +00002399 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
2400 Elts.push_back(Init->getAggregateElement(i));
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002401
Chris Lattner798b4d52005-09-26 06:52:44 +00002402 // Replace the element that we are supposed to.
Reid Spencerb83eb642006-10-20 07:07:24 +00002403 ConstantInt *CU = cast<ConstantInt>(Addr->getOperand(OpNo));
2404 unsigned Idx = CU->getZExtValue();
2405 assert(Idx < STy->getNumElements() && "Struct index out of range!");
Chris Lattner7b550cc2009-11-06 04:27:31 +00002406 Elts[Idx] = EvaluateStoreInto(Elts[Idx], Val, Addr, OpNo+1);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002407
Chris Lattner798b4d52005-09-26 06:52:44 +00002408 // Return the modified struct.
Chris Lattnerb065b062011-06-20 04:01:31 +00002409 return ConstantStruct::get(STy, Elts);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002410 }
Chris Lattnerb065b062011-06-20 04:01:31 +00002411
2412 ConstantInt *CI = cast<ConstantInt>(Addr->getOperand(OpNo));
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002413 SequentialType *InitTy = cast<SequentialType>(Init->getType());
Chris Lattnerb065b062011-06-20 04:01:31 +00002414
2415 uint64_t NumElts;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002416 if (ArrayType *ATy = dyn_cast<ArrayType>(InitTy))
Chris Lattnerb065b062011-06-20 04:01:31 +00002417 NumElts = ATy->getNumElements();
2418 else
Chris Lattnerd59ae902012-01-26 02:32:04 +00002419 NumElts = InitTy->getVectorNumElements();
Chris Lattnerb065b062011-06-20 04:01:31 +00002420
2421 // Break up the array into elements.
Chris Lattnerd59ae902012-01-26 02:32:04 +00002422 for (uint64_t i = 0, e = NumElts; i != e; ++i)
2423 Elts.push_back(Init->getAggregateElement(i));
Chris Lattnerb065b062011-06-20 04:01:31 +00002424
2425 assert(CI->getZExtValue() < NumElts);
2426 Elts[CI->getZExtValue()] =
2427 EvaluateStoreInto(Elts[CI->getZExtValue()], Val, Addr, OpNo+1);
2428
2429 if (Init->getType()->isArrayTy())
2430 return ConstantArray::get(cast<ArrayType>(InitTy), Elts);
2431 return ConstantVector::get(Elts);
Chris Lattner798b4d52005-09-26 06:52:44 +00002432}
2433
Chris Lattner79c11012005-09-26 04:44:35 +00002434/// CommitValueTo - We have decided that Addr (which satisfies the predicate
2435/// isSimpleEnoughPointerToCommit) should get Val as its value. Make it happen.
Chris Lattner7b550cc2009-11-06 04:27:31 +00002436static void CommitValueTo(Constant *Val, Constant *Addr) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002437 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Addr)) {
2438 assert(GV->hasInitializer());
2439 GV->setInitializer(Val);
2440 return;
2441 }
Chris Lattnera0e9a242010-01-07 01:16:21 +00002442
Chris Lattner798b4d52005-09-26 06:52:44 +00002443 ConstantExpr *CE = cast<ConstantExpr>(Addr);
2444 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
Chris Lattnera0e9a242010-01-07 01:16:21 +00002445 GV->setInitializer(EvaluateStoreInto(GV->getInitializer(), Val, CE, 2));
Chris Lattner79c11012005-09-26 04:44:35 +00002446}
2447
Nick Lewycky7fa76772012-02-20 03:25:59 +00002448namespace {
2449
2450/// Evaluator - This class evaluates LLVM IR, producing the Constant
2451/// representing each SSA instruction. Changes to global variables are stored
2452/// in a mapping that can be iterated over after the evaluation is complete.
2453/// Once an evaluation call fails, the evaluation object should not be reused.
2454class Evaluator {
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002455public:
Nick Lewycky7fa76772012-02-20 03:25:59 +00002456 Evaluator(const TargetData *TD, const TargetLibraryInfo *TLI)
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002457 : TD(TD), TLI(TLI) {
2458 ValueStack.push_back(new DenseMap<Value*, Constant*>);
2459 }
2460
Nick Lewycky7fa76772012-02-20 03:25:59 +00002461 ~Evaluator() {
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002462 DeleteContainerPointers(ValueStack);
2463 while (!AllocaTmps.empty()) {
2464 GlobalVariable *Tmp = AllocaTmps.back();
2465 AllocaTmps.pop_back();
2466
2467 // If there are still users of the alloca, the program is doing something
2468 // silly, e.g. storing the address of the alloca somewhere and using it
2469 // later. Since this is undefined, we'll just make it be null.
2470 if (!Tmp->use_empty())
2471 Tmp->replaceAllUsesWith(Constant::getNullValue(Tmp->getType()));
2472 delete Tmp;
2473 }
2474 }
2475
2476 /// EvaluateFunction - Evaluate a call to function F, returning true if
2477 /// successful, false if we can't evaluate it. ActualArgs contains the formal
2478 /// arguments for the function.
2479 bool EvaluateFunction(Function *F, Constant *&RetVal,
2480 const SmallVectorImpl<Constant*> &ActualArgs);
2481
2482 /// EvaluateBlock - Evaluate all instructions in block BB, returning true if
2483 /// successful, false if we can't evaluate it. NewBB returns the next BB that
2484 /// control flows into, or null upon return.
2485 bool EvaluateBlock(BasicBlock::iterator CurInst, BasicBlock *&NextBB);
2486
2487 Constant *getVal(Value *V) {
2488 if (Constant *CV = dyn_cast<Constant>(V)) return CV;
2489 Constant *R = ValueStack.back()->lookup(V);
2490 assert(R && "Reference to an uncomputed value!");
2491 return R;
2492 }
2493
2494 void setVal(Value *V, Constant *C) {
2495 ValueStack.back()->operator[](V) = C;
2496 }
2497
2498 const DenseMap<Constant*, Constant*> &getMutatedMemory() const {
2499 return MutatedMemory;
2500 }
2501
2502 const SmallPtrSet<GlobalVariable*, 8> &getInvariants() const {
2503 return Invariants;
2504 }
2505
2506private:
2507 Constant *ComputeLoadResult(Constant *P);
2508
2509 /// ValueStack - As we compute SSA register values, we store their contents
2510 /// here. The back of the vector contains the current function and the stack
2511 /// contains the values in the calling frames.
2512 SmallVector<DenseMap<Value*, Constant*>*, 4> ValueStack;
2513
2514 /// CallStack - This is used to detect recursion. In pathological situations
2515 /// we could hit exponential behavior, but at least there is nothing
2516 /// unbounded.
2517 SmallVector<Function*, 4> CallStack;
2518
2519 /// MutatedMemory - For each store we execute, we update this map. Loads
2520 /// check this to get the most up-to-date value. If evaluation is successful,
2521 /// this state is committed to the process.
2522 DenseMap<Constant*, Constant*> MutatedMemory;
2523
2524 /// AllocaTmps - To 'execute' an alloca, we create a temporary global variable
2525 /// to represent its body. This vector is needed so we can delete the
2526 /// temporary globals when we are done.
2527 SmallVector<GlobalVariable*, 32> AllocaTmps;
2528
2529 /// Invariants - These global variables have been marked invariant by the
2530 /// static constructor.
2531 SmallPtrSet<GlobalVariable*, 8> Invariants;
2532
2533 /// SimpleConstants - These are constants we have checked and know to be
2534 /// simple enough to live in a static initializer of a global.
2535 SmallPtrSet<Constant*, 8> SimpleConstants;
2536
2537 const TargetData *TD;
2538 const TargetLibraryInfo *TLI;
2539};
2540
Nick Lewycky7fa76772012-02-20 03:25:59 +00002541} // anonymous namespace
2542
Chris Lattner562a0552005-09-26 05:16:34 +00002543/// ComputeLoadResult - Return the value that would be computed by a load from
2544/// P after the stores reflected by 'memory' have been performed. If we can't
2545/// decide, return null.
Nick Lewycky7fa76772012-02-20 03:25:59 +00002546Constant *Evaluator::ComputeLoadResult(Constant *P) {
Chris Lattner04de1cf2005-09-26 05:15:37 +00002547 // If this memory location has been recently stored, use the stored value: it
2548 // is the most up-to-date.
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002549 DenseMap<Constant*, Constant*>::const_iterator I = MutatedMemory.find(P);
2550 if (I != MutatedMemory.end()) return I->second;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002551
Chris Lattner04de1cf2005-09-26 05:15:37 +00002552 // Access it.
2553 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(P)) {
Dan Gohman82555732009-08-19 18:20:44 +00002554 if (GV->hasDefinitiveInitializer())
Chris Lattner04de1cf2005-09-26 05:15:37 +00002555 return GV->getInitializer();
2556 return 0;
Chris Lattner04de1cf2005-09-26 05:15:37 +00002557 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002558
Chris Lattner798b4d52005-09-26 06:52:44 +00002559 // Handle a constantexpr getelementptr.
2560 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(P))
2561 if (CE->getOpcode() == Instruction::GetElementPtr &&
2562 isa<GlobalVariable>(CE->getOperand(0))) {
2563 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
Dan Gohman82555732009-08-19 18:20:44 +00002564 if (GV->hasDefinitiveInitializer())
Dan Gohmanc6f69e92009-10-05 16:36:26 +00002565 return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
Chris Lattner798b4d52005-09-26 06:52:44 +00002566 }
2567
2568 return 0; // don't know how to evaluate.
Chris Lattner04de1cf2005-09-26 05:15:37 +00002569}
2570
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002571/// EvaluateBlock - Evaluate all instructions in block BB, returning true if
2572/// successful, false if we can't evaluate it. NewBB returns the next BB that
2573/// control flows into, or null upon return.
Nick Lewycky7fa76772012-02-20 03:25:59 +00002574bool Evaluator::EvaluateBlock(BasicBlock::iterator CurInst,
2575 BasicBlock *&NextBB) {
Chris Lattner79c11012005-09-26 04:44:35 +00002576 // This is the main evaluation loop.
2577 while (1) {
2578 Constant *InstResult = 0;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002579
Chris Lattner79c11012005-09-26 04:44:35 +00002580 if (StoreInst *SI = dyn_cast<StoreInst>(CurInst)) {
Eli Friedman33cb4452011-08-16 00:20:11 +00002581 if (!SI->isSimple()) return false; // no volatile/atomic accesses.
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002582 Constant *Ptr = getVal(SI->getOperand(1));
Nick Lewyckya641c072012-02-21 22:08:06 +00002583 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
2584 Ptr = ConstantFoldConstantExpression(CE, TD, TLI);
Chris Lattner7b550cc2009-11-06 04:27:31 +00002585 if (!isSimpleEnoughPointerToCommit(Ptr))
Chris Lattner79c11012005-09-26 04:44:35 +00002586 // If this is too complex for us to commit, reject it.
Chris Lattnercd271422005-09-27 04:45:34 +00002587 return false;
Chris Lattner1945d582010-12-07 04:33:29 +00002588
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002589 Constant *Val = getVal(SI->getOperand(0));
Chris Lattner1945d582010-12-07 04:33:29 +00002590
2591 // If this might be too difficult for the backend to handle (e.g. the addr
2592 // of one global variable divided by another) then we can't commit it.
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002593 if (!isSimpleEnoughValueToCommit(Val, SimpleConstants, TD))
Chris Lattner1945d582010-12-07 04:33:29 +00002594 return false;
Owen Andersoncff6b372011-01-14 22:19:20 +00002595
2596 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
2597 if (CE->getOpcode() == Instruction::BitCast) {
2598 // If we're evaluating a store through a bitcast, then we need
2599 // to pull the bitcast off the pointer type and push it onto the
2600 // stored value.
Chris Lattnerd5f656f2011-01-16 02:05:10 +00002601 Ptr = CE->getOperand(0);
Owen Andersoncff6b372011-01-14 22:19:20 +00002602
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002603 Type *NewTy = cast<PointerType>(Ptr->getType())->getElementType();
Owen Andersoncff6b372011-01-14 22:19:20 +00002604
Owen Anderson66f708f2011-01-16 04:33:33 +00002605 // In order to push the bitcast onto the stored value, a bitcast
2606 // from NewTy to Val's type must be legal. If it's not, we can try
2607 // introspecting NewTy to find a legal conversion.
2608 while (!Val->getType()->canLosslesslyBitCastTo(NewTy)) {
2609 // If NewTy is a struct, we can convert the pointer to the struct
2610 // into a pointer to its first member.
2611 // FIXME: This could be extended to support arrays as well.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002612 if (StructType *STy = dyn_cast<StructType>(NewTy)) {
Owen Anderson66f708f2011-01-16 04:33:33 +00002613 NewTy = STy->getTypeAtIndex(0U);
2614
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002615 IntegerType *IdxTy = IntegerType::get(NewTy->getContext(), 32);
Owen Anderson66f708f2011-01-16 04:33:33 +00002616 Constant *IdxZero = ConstantInt::get(IdxTy, 0, false);
2617 Constant * const IdxList[] = {IdxZero, IdxZero};
2618
Jay Foadb4263a62011-07-22 08:52:50 +00002619 Ptr = ConstantExpr::getGetElementPtr(Ptr, IdxList);
Nick Lewyckya641c072012-02-21 22:08:06 +00002620 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
2621 Ptr = ConstantFoldConstantExpression(CE, TD, TLI);
2622
Owen Anderson66f708f2011-01-16 04:33:33 +00002623 // If we can't improve the situation by introspecting NewTy,
2624 // we have to give up.
2625 } else {
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002626 return false;
Owen Anderson66f708f2011-01-16 04:33:33 +00002627 }
Owen Andersoncff6b372011-01-14 22:19:20 +00002628 }
2629
Owen Anderson66f708f2011-01-16 04:33:33 +00002630 // If we found compatible types, go ahead and push the bitcast
2631 // onto the stored value.
Owen Andersoncff6b372011-01-14 22:19:20 +00002632 Val = ConstantExpr::getBitCast(Val, NewTy);
2633 }
2634
Chris Lattner79c11012005-09-26 04:44:35 +00002635 MutatedMemory[Ptr] = Val;
2636 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CurInst)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002637 InstResult = ConstantExpr::get(BO->getOpcode(),
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002638 getVal(BO->getOperand(0)),
2639 getVal(BO->getOperand(1)));
Reid Spencere4d87aa2006-12-23 06:05:41 +00002640 } else if (CmpInst *CI = dyn_cast<CmpInst>(CurInst)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002641 InstResult = ConstantExpr::getCompare(CI->getPredicate(),
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002642 getVal(CI->getOperand(0)),
2643 getVal(CI->getOperand(1)));
Chris Lattner79c11012005-09-26 04:44:35 +00002644 } else if (CastInst *CI = dyn_cast<CastInst>(CurInst)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002645 InstResult = ConstantExpr::getCast(CI->getOpcode(),
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002646 getVal(CI->getOperand(0)),
Chris Lattner79c11012005-09-26 04:44:35 +00002647 CI->getType());
2648 } else if (SelectInst *SI = dyn_cast<SelectInst>(CurInst)) {
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002649 InstResult = ConstantExpr::getSelect(getVal(SI->getOperand(0)),
2650 getVal(SI->getOperand(1)),
2651 getVal(SI->getOperand(2)));
Chris Lattner04de1cf2005-09-26 05:15:37 +00002652 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurInst)) {
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002653 Constant *P = getVal(GEP->getOperand(0));
Chris Lattner55eb1c42007-01-31 04:40:53 +00002654 SmallVector<Constant*, 8> GEPOps;
Gabor Greif5e463212008-05-29 01:59:18 +00002655 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end();
2656 i != e; ++i)
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002657 GEPOps.push_back(getVal(*i));
Jay Foad4b5e2072011-07-21 15:15:37 +00002658 InstResult =
2659 ConstantExpr::getGetElementPtr(P, GEPOps,
2660 cast<GEPOperator>(GEP)->isInBounds());
Chris Lattner04de1cf2005-09-26 05:15:37 +00002661 } else if (LoadInst *LI = dyn_cast<LoadInst>(CurInst)) {
Eli Friedman33cb4452011-08-16 00:20:11 +00002662 if (!LI->isSimple()) return false; // no volatile/atomic accesses.
Nick Lewyckya641c072012-02-21 22:08:06 +00002663 Constant *Ptr = getVal(LI->getOperand(0));
2664 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
2665 Ptr = ConstantFoldConstantExpression(CE, TD, TLI);
2666 InstResult = ComputeLoadResult(Ptr);
Chris Lattnercd271422005-09-27 04:45:34 +00002667 if (InstResult == 0) return false; // Could not evaluate load.
Chris Lattnera22fdb02005-09-26 17:07:09 +00002668 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(CurInst)) {
Chris Lattnercd271422005-09-27 04:45:34 +00002669 if (AI->isArrayAllocation()) return false; // Cannot handle array allocs.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002670 Type *Ty = AI->getType()->getElementType();
Chris Lattner7b550cc2009-11-06 04:27:31 +00002671 AllocaTmps.push_back(new GlobalVariable(Ty, false,
Chris Lattnera22fdb02005-09-26 17:07:09 +00002672 GlobalValue::InternalLinkage,
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002673 UndefValue::get(Ty),
Chris Lattnera22fdb02005-09-26 17:07:09 +00002674 AI->getName()));
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002675 InstResult = AllocaTmps.back();
Nick Lewycky132bd9c2012-02-12 05:09:35 +00002676 } else if (isa<CallInst>(CurInst) || isa<InvokeInst>(CurInst)) {
2677 CallSite CS(CurInst);
Devang Patel412a4462009-03-09 23:04:12 +00002678
2679 // Debug info can safely be ignored here.
Nick Lewycky132bd9c2012-02-12 05:09:35 +00002680 if (isa<DbgInfoIntrinsic>(CS.getInstruction())) {
Devang Patel412a4462009-03-09 23:04:12 +00002681 ++CurInst;
2682 continue;
2683 }
2684
Chris Lattner7cd580f2006-07-07 21:37:01 +00002685 // Cannot handle inline asm.
Nick Lewycky132bd9c2012-02-12 05:09:35 +00002686 if (isa<InlineAsm>(CS.getCalledValue())) return false;
Chris Lattner7cd580f2006-07-07 21:37:01 +00002687
Nick Lewycky81266c52012-02-17 06:59:21 +00002688 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CS.getInstruction())) {
2689 if (MemSetInst *MSI = dyn_cast<MemSetInst>(II)) {
2690 if (MSI->isVolatile()) return false;
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002691 Constant *Ptr = getVal(MSI->getDest());
2692 Constant *Val = getVal(MSI->getValue());
2693 Constant *DestVal = ComputeLoadResult(getVal(Ptr));
Nick Lewycky81266c52012-02-17 06:59:21 +00002694 if (Val->isNullValue() && DestVal && DestVal->isNullValue()) {
2695 // This memset is a no-op.
2696 ++CurInst;
2697 continue;
2698 }
2699 }
2700
2701 if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
2702 II->getIntrinsicID() == Intrinsic::lifetime_end) {
2703 ++CurInst;
2704 continue;
2705 }
2706
2707 if (II->getIntrinsicID() == Intrinsic::invariant_start) {
2708 // We don't insert an entry into Values, as it doesn't have a
2709 // meaningful return value.
2710 if (!II->use_empty())
2711 return false;
2712 ConstantInt *Size = cast<ConstantInt>(II->getArgOperand(0));
Nick Lewycky0ef05572012-02-20 23:32:26 +00002713 Value *PtrArg = getVal(II->getArgOperand(1));
2714 Value *Ptr = PtrArg->stripPointerCasts();
2715 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr)) {
2716 Type *ElemTy = cast<PointerType>(GV->getType())->getElementType();
2717 if (!Size->isAllOnesValue() &&
2718 Size->getValue().getLimitedValue() >=
2719 TD->getTypeStoreSize(ElemTy))
Nick Lewycky81266c52012-02-17 06:59:21 +00002720 Invariants.insert(GV);
2721 }
2722 // Continue even if we do nothing.
Nick Lewycky1f237b02011-05-29 18:41:56 +00002723 ++CurInst;
2724 continue;
2725 }
2726 return false;
2727 }
2728
Chris Lattnercd271422005-09-27 04:45:34 +00002729 // Resolve function pointers.
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002730 Function *Callee = dyn_cast<Function>(getVal(CS.getCalledValue()));
Nick Lewycky132bd9c2012-02-12 05:09:35 +00002731 if (!Callee || Callee->mayBeOverridden())
2732 return false; // Cannot resolve.
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002733
Duncan Sandsfa6a1cf2009-08-17 14:33:27 +00002734 SmallVector<Constant*, 8> Formals;
Nick Lewycky132bd9c2012-02-12 05:09:35 +00002735 for (User::op_iterator i = CS.arg_begin(), e = CS.arg_end(); i != e; ++i)
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002736 Formals.push_back(getVal(*i));
Duncan Sandsfa6a1cf2009-08-17 14:33:27 +00002737
Reid Spencer5cbf9852007-01-30 20:08:39 +00002738 if (Callee->isDeclaration()) {
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002739 // If this is a function we can constant fold, do it.
Chad Rosier00737bd2011-12-01 21:29:16 +00002740 if (Constant *C = ConstantFoldCall(Callee, Formals, TLI)) {
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002741 InstResult = C;
2742 } else {
2743 return false;
2744 }
2745 } else {
2746 if (Callee->getFunctionType()->isVarArg())
2747 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002748
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002749 Constant *RetVal;
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002750 // Execute the call, if successful, use the return value.
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002751 ValueStack.push_back(new DenseMap<Value*, Constant*>);
2752 if (!EvaluateFunction(Callee, RetVal, Formals))
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002753 return false;
Benjamin Kramer3bbf2b62012-02-27 12:48:24 +00002754 delete ValueStack.pop_back_val();
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002755 InstResult = RetVal;
2756 }
Reid Spencer3ed469c2006-11-02 20:25:50 +00002757 } else if (isa<TerminatorInst>(CurInst)) {
Chris Lattnercdf98be2005-09-26 04:57:38 +00002758 if (BranchInst *BI = dyn_cast<BranchInst>(CurInst)) {
2759 if (BI->isUnconditional()) {
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002760 NextBB = BI->getSuccessor(0);
Chris Lattnercdf98be2005-09-26 04:57:38 +00002761 } else {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002762 ConstantInt *Cond =
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002763 dyn_cast<ConstantInt>(getVal(BI->getCondition()));
Chris Lattner97d1fad2007-01-12 18:30:11 +00002764 if (!Cond) return false; // Cannot determine.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002765
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002766 NextBB = BI->getSuccessor(!Cond->getZExtValue());
Chris Lattnercdf98be2005-09-26 04:57:38 +00002767 }
2768 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(CurInst)) {
2769 ConstantInt *Val =
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002770 dyn_cast<ConstantInt>(getVal(SI->getCondition()));
Chris Lattnercd271422005-09-27 04:45:34 +00002771 if (!Val) return false; // Cannot determine.
Stepan Dyatkovskiyc10fa6c2012-03-08 07:06:20 +00002772 NextBB = SI->findCaseValue(Val).getCaseSuccessor();
Chris Lattnerb3d5a652009-10-29 05:51:50 +00002773 } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(CurInst)) {
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002774 Value *Val = getVal(IBI->getAddress())->stripPointerCasts();
Chris Lattnerb3d5a652009-10-29 05:51:50 +00002775 if (BlockAddress *BA = dyn_cast<BlockAddress>(Val))
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002776 NextBB = BA->getBasicBlock();
Chris Lattnercdfc9402009-11-01 01:27:45 +00002777 else
2778 return false; // Cannot determine.
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002779 } else if (isa<ReturnInst>(CurInst)) {
2780 NextBB = 0;
Chris Lattnercdf98be2005-09-26 04:57:38 +00002781 } else {
Bill Wendlingdccc03b2011-07-31 06:30:59 +00002782 // invoke, unwind, resume, unreachable.
Chris Lattnercd271422005-09-27 04:45:34 +00002783 return false; // Cannot handle this terminator.
Chris Lattnercdf98be2005-09-26 04:57:38 +00002784 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002785
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002786 // We succeeded at evaluating this block!
2787 return true;
Chris Lattner79c11012005-09-26 04:44:35 +00002788 } else {
Chris Lattner79c11012005-09-26 04:44:35 +00002789 // Did not know how to evaluate this!
Chris Lattnercd271422005-09-27 04:45:34 +00002790 return false;
Chris Lattner79c11012005-09-26 04:44:35 +00002791 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002792
Chris Lattner1945d582010-12-07 04:33:29 +00002793 if (!CurInst->use_empty()) {
2794 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(InstResult))
Chad Rosieraab8e282011-12-02 01:26:24 +00002795 InstResult = ConstantFoldConstantExpression(CE, TD, TLI);
Chris Lattner1945d582010-12-07 04:33:29 +00002796
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002797 setVal(CurInst, InstResult);
Chris Lattner1945d582010-12-07 04:33:29 +00002798 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002799
Dan Gohmanf1ce79f2012-03-13 18:01:37 +00002800 // If we just processed an invoke, we finished evaluating the block.
2801 if (InvokeInst *II = dyn_cast<InvokeInst>(CurInst)) {
2802 NextBB = II->getNormalDest();
2803 return true;
2804 }
2805
Chris Lattner79c11012005-09-26 04:44:35 +00002806 // Advance program counter.
2807 ++CurInst;
2808 }
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002809}
2810
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002811/// EvaluateFunction - Evaluate a call to function F, returning true if
2812/// successful, false if we can't evaluate it. ActualArgs contains the formal
2813/// arguments for the function.
Nick Lewycky7fa76772012-02-20 03:25:59 +00002814bool Evaluator::EvaluateFunction(Function *F, Constant *&RetVal,
2815 const SmallVectorImpl<Constant*> &ActualArgs) {
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002816 // Check to see if this function is already executing (recursion). If so,
2817 // bail out. TODO: we might want to accept limited recursion.
2818 if (std::find(CallStack.begin(), CallStack.end(), F) != CallStack.end())
2819 return false;
2820
2821 CallStack.push_back(F);
2822
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002823 // Initialize arguments to the incoming values specified.
2824 unsigned ArgNo = 0;
2825 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); AI != E;
2826 ++AI, ++ArgNo)
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002827 setVal(AI, ActualArgs[ArgNo]);
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002828
2829 // ExecutedBlocks - We only handle non-looping, non-recursive code. As such,
2830 // we can only evaluate any one basic block at most once. This set keeps
2831 // track of what we have executed so we can detect recursive cases etc.
2832 SmallPtrSet<BasicBlock*, 32> ExecutedBlocks;
2833
2834 // CurBB - The current basic block we're evaluating.
2835 BasicBlock *CurBB = F->begin();
2836
Nick Lewycky8e4ba6b2012-02-12 00:47:24 +00002837 BasicBlock::iterator CurInst = CurBB->begin();
2838
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002839 while (1) {
Duncan Sands4b794f82012-02-23 08:23:06 +00002840 BasicBlock *NextBB = 0; // Initialized to avoid compiler warnings.
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002841 if (!EvaluateBlock(CurInst, NextBB))
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002842 return false;
2843
2844 if (NextBB == 0) {
2845 // Successfully running until there's no next block means that we found
2846 // the return. Fill it the return value and pop the call stack.
2847 ReturnInst *RI = cast<ReturnInst>(CurBB->getTerminator());
2848 if (RI->getNumOperands())
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002849 RetVal = getVal(RI->getOperand(0));
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002850 CallStack.pop_back();
2851 return true;
2852 }
2853
2854 // Okay, we succeeded in evaluating this control flow. See if we have
2855 // executed the new block before. If so, we have a looping function,
2856 // which we cannot evaluate in reasonable time.
2857 if (!ExecutedBlocks.insert(NextBB))
2858 return false; // looped!
2859
2860 // Okay, we have never been in this block before. Check to see if there
2861 // are any PHI nodes. If so, evaluate them with information about where
2862 // we came from.
2863 PHINode *PN = 0;
Nick Lewycky8e4ba6b2012-02-12 00:47:24 +00002864 for (CurInst = NextBB->begin();
2865 (PN = dyn_cast<PHINode>(CurInst)); ++CurInst)
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002866 setVal(PN, getVal(PN->getIncomingValueForBlock(CurBB)));
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002867
2868 // Advance to the next block.
2869 CurBB = NextBB;
2870 }
2871}
2872
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002873/// EvaluateStaticConstructor - Evaluate static constructors in the function, if
2874/// we can. Return true if we can, false otherwise.
Chad Rosier00737bd2011-12-01 21:29:16 +00002875static bool EvaluateStaticConstructor(Function *F, const TargetData *TD,
2876 const TargetLibraryInfo *TLI) {
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002877 // Call the function.
Nick Lewycky7fa76772012-02-20 03:25:59 +00002878 Evaluator Eval(TD, TLI);
Chris Lattnercd271422005-09-27 04:45:34 +00002879 Constant *RetValDummy;
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002880 bool EvalSuccess = Eval.EvaluateFunction(F, RetValDummy,
2881 SmallVector<Constant*, 0>());
Chris Lattner1945d582010-12-07 04:33:29 +00002882
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002883 if (EvalSuccess) {
Chris Lattnera22fdb02005-09-26 17:07:09 +00002884 // We succeeded at evaluation: commit the result.
David Greene3215b0e2010-01-05 01:28:05 +00002885 DEBUG(dbgs() << "FULLY EVALUATED GLOBAL CTOR FUNCTION '"
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002886 << F->getName() << "' to " << Eval.getMutatedMemory().size()
Daniel Dunbarce63ffb2009-07-25 00:23:56 +00002887 << " stores.\n");
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002888 for (DenseMap<Constant*, Constant*>::const_iterator I =
2889 Eval.getMutatedMemory().begin(), E = Eval.getMutatedMemory().end();
Nick Lewycky3eab3c42012-06-24 04:07:14 +00002890 I != E; ++I)
Chris Lattner7b550cc2009-11-06 04:27:31 +00002891 CommitValueTo(I->second, I->first);
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002892 for (SmallPtrSet<GlobalVariable*, 8>::const_iterator I =
2893 Eval.getInvariants().begin(), E = Eval.getInvariants().end();
2894 I != E; ++I)
Nick Lewycky81266c52012-02-17 06:59:21 +00002895 (*I)->setConstant(true);
Chris Lattnera22fdb02005-09-26 17:07:09 +00002896 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002897
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002898 return EvalSuccess;
Chris Lattner79c11012005-09-26 04:44:35 +00002899}
2900
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002901/// OptimizeGlobalCtorsList - Simplify and evaluation global ctors if possible.
2902/// Return true if anything changed.
2903bool GlobalOpt::OptimizeGlobalCtorsList(GlobalVariable *&GCL) {
2904 std::vector<Function*> Ctors = ParseGlobalCtors(GCL);
2905 bool MadeChange = false;
2906 if (Ctors.empty()) return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002907
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002908 // Loop over global ctors, optimizing them when we can.
2909 for (unsigned i = 0; i != Ctors.size(); ++i) {
2910 Function *F = Ctors[i];
2911 // Found a null terminator in the middle of the list, prune off the rest of
2912 // the list.
Chris Lattner7d8e58f2005-09-26 02:19:27 +00002913 if (F == 0) {
2914 if (i != Ctors.size()-1) {
2915 Ctors.resize(i+1);
2916 MadeChange = true;
2917 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002918 break;
2919 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002920
Chris Lattner79c11012005-09-26 04:44:35 +00002921 // We cannot simplify external ctor functions.
2922 if (F->empty()) continue;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002923
Chris Lattner79c11012005-09-26 04:44:35 +00002924 // If we can evaluate the ctor at compile time, do.
Chad Rosier00737bd2011-12-01 21:29:16 +00002925 if (EvaluateStaticConstructor(F, TD, TLI)) {
Chris Lattner79c11012005-09-26 04:44:35 +00002926 Ctors.erase(Ctors.begin()+i);
2927 MadeChange = true;
2928 --i;
2929 ++NumCtorsEvaluated;
2930 continue;
2931 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002932 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002933
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002934 if (!MadeChange) return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002935
Chris Lattner7b550cc2009-11-06 04:27:31 +00002936 GCL = InstallGlobalCtors(GCL, Ctors);
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002937 return true;
2938}
2939
Duncan Sandsfc5940d2009-03-06 10:21:56 +00002940bool GlobalOpt::OptimizeGlobalAliases(Module &M) {
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002941 bool Changed = false;
2942
Duncan Sands177d84e2009-01-07 20:01:06 +00002943 for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end();
Duncan Sands4782b302009-02-15 09:56:08 +00002944 I != E;) {
2945 Module::alias_iterator J = I++;
Duncan Sandsfc5940d2009-03-06 10:21:56 +00002946 // Aliases without names cannot be referenced outside this module.
2947 if (!J->hasName() && !J->isDeclaration())
2948 J->setLinkage(GlobalValue::InternalLinkage);
Duncan Sands4782b302009-02-15 09:56:08 +00002949 // If the aliasee may change at link time, nothing can be done - bail out.
2950 if (J->mayBeOverridden())
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002951 continue;
2952
Duncan Sands4782b302009-02-15 09:56:08 +00002953 Constant *Aliasee = J->getAliasee();
2954 GlobalValue *Target = cast<GlobalValue>(Aliasee->stripPointerCasts());
Duncan Sands95c5d0f2009-02-18 17:55:38 +00002955 Target->removeDeadConstantUsers();
Duncan Sands4782b302009-02-15 09:56:08 +00002956 bool hasOneUse = Target->hasOneUse() && Aliasee->hasOneUse();
2957
2958 // Make all users of the alias use the aliasee instead.
2959 if (!J->use_empty()) {
2960 J->replaceAllUsesWith(Aliasee);
2961 ++NumAliasesResolved;
2962 Changed = true;
2963 }
2964
Duncan Sands7a154cf2009-12-08 10:10:20 +00002965 // If the alias is externally visible, we may still be able to simplify it.
2966 if (!J->hasLocalLinkage()) {
2967 // If the aliasee has internal linkage, give it the name and linkage
2968 // of the alias, and delete the alias. This turns:
2969 // define internal ... @f(...)
2970 // @a = alias ... @f
2971 // into:
2972 // define ... @a(...)
2973 if (!Target->hasLocalLinkage())
2974 continue;
Duncan Sands4782b302009-02-15 09:56:08 +00002975
Duncan Sands7a154cf2009-12-08 10:10:20 +00002976 // Do not perform the transform if multiple aliases potentially target the
Gabor Greif27236912010-04-07 18:59:26 +00002977 // aliasee. This check also ensures that it is safe to replace the section
Duncan Sands7a154cf2009-12-08 10:10:20 +00002978 // and other attributes of the aliasee with those of the alias.
2979 if (!hasOneUse)
2980 continue;
Duncan Sands4782b302009-02-15 09:56:08 +00002981
Duncan Sands7a154cf2009-12-08 10:10:20 +00002982 // Give the aliasee the name, linkage and other attributes of the alias.
2983 Target->takeName(J);
2984 Target->setLinkage(J->getLinkage());
2985 Target->GlobalValue::copyAttributesFrom(J);
2986 }
Duncan Sands4782b302009-02-15 09:56:08 +00002987
2988 // Delete the alias.
2989 M.getAliasList().erase(J);
2990 ++NumAliasesRemoved;
2991 Changed = true;
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002992 }
2993
2994 return Changed;
2995}
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002996
Nick Lewycky6a7df9a2012-02-12 02:15:20 +00002997static Function *FindCXAAtExit(Module &M, TargetLibraryInfo *TLI) {
2998 if (!TLI->has(LibFunc::cxa_atexit))
Nick Lewycky6f160d32012-02-12 02:17:18 +00002999 return 0;
Nick Lewycky6a7df9a2012-02-12 02:15:20 +00003000
3001 Function *Fn = M.getFunction(TLI->getName(LibFunc::cxa_atexit));
Anders Carlssona201c4c2011-03-20 17:59:11 +00003002
3003 if (!Fn)
3004 return 0;
Nick Lewycky6a7df9a2012-02-12 02:15:20 +00003005
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003006 FunctionType *FTy = Fn->getFunctionType();
Anders Carlssona201c4c2011-03-20 17:59:11 +00003007
Anders Carlsson1f7c7ba2011-03-20 19:51:13 +00003008 // Checking that the function has the right return type, the right number of
3009 // parameters and that they all have pointer types should be enough.
3010 if (!FTy->getReturnType()->isIntegerTy() ||
3011 FTy->getNumParams() != 3 ||
Anders Carlssona201c4c2011-03-20 17:59:11 +00003012 !FTy->getParamType(0)->isPointerTy() ||
3013 !FTy->getParamType(1)->isPointerTy() ||
3014 !FTy->getParamType(2)->isPointerTy())
3015 return 0;
3016
3017 return Fn;
3018}
3019
3020/// cxxDtorIsEmpty - Returns whether the given function is an empty C++
3021/// destructor and can therefore be eliminated.
3022/// Note that we assume that other optimization passes have already simplified
3023/// the code so we only look for a function with a single basic block, where
Benjamin Kramerc1322a12012-02-09 16:28:15 +00003024/// the only allowed instructions are 'ret', 'call' to an empty C++ dtor and
3025/// other side-effect free instructions.
Anders Carlsson372ec6a2011-03-20 20:16:43 +00003026static bool cxxDtorIsEmpty(const Function &Fn,
3027 SmallPtrSet<const Function *, 8> &CalledFunctions) {
Anders Carlsson1f7c7ba2011-03-20 19:51:13 +00003028 // FIXME: We could eliminate C++ destructors if they're readonly/readnone and
Nick Lewycky35ee1c92011-03-21 02:26:01 +00003029 // nounwind, but that doesn't seem worth doing.
Anders Carlsson1f7c7ba2011-03-20 19:51:13 +00003030 if (Fn.isDeclaration())
3031 return false;
Anders Carlssona201c4c2011-03-20 17:59:11 +00003032
3033 if (++Fn.begin() != Fn.end())
3034 return false;
3035
3036 const BasicBlock &EntryBlock = Fn.getEntryBlock();
3037 for (BasicBlock::const_iterator I = EntryBlock.begin(), E = EntryBlock.end();
3038 I != E; ++I) {
3039 if (const CallInst *CI = dyn_cast<CallInst>(I)) {
Anders Carlssonb12caf32011-03-21 14:54:40 +00003040 // Ignore debug intrinsics.
3041 if (isa<DbgInfoIntrinsic>(CI))
3042 continue;
3043
Anders Carlssona201c4c2011-03-20 17:59:11 +00003044 const Function *CalledFn = CI->getCalledFunction();
3045
3046 if (!CalledFn)
3047 return false;
3048
Anders Carlsson807bc2a2011-03-22 03:21:01 +00003049 SmallPtrSet<const Function *, 8> NewCalledFunctions(CalledFunctions);
3050
Anders Carlsson1f7c7ba2011-03-20 19:51:13 +00003051 // Don't treat recursive functions as empty.
Anders Carlsson807bc2a2011-03-22 03:21:01 +00003052 if (!NewCalledFunctions.insert(CalledFn))
Anders Carlsson1f7c7ba2011-03-20 19:51:13 +00003053 return false;
3054
Anders Carlsson807bc2a2011-03-22 03:21:01 +00003055 if (!cxxDtorIsEmpty(*CalledFn, NewCalledFunctions))
Anders Carlssona201c4c2011-03-20 17:59:11 +00003056 return false;
3057 } else if (isa<ReturnInst>(*I))
Benjamin Kramerd4692742012-02-09 14:26:06 +00003058 return true; // We're done.
3059 else if (I->mayHaveSideEffects())
3060 return false; // Destructor with side effects, bail.
Anders Carlssona201c4c2011-03-20 17:59:11 +00003061 }
3062
3063 return false;
3064}
3065
3066bool GlobalOpt::OptimizeEmptyGlobalCXXDtors(Function *CXAAtExitFn) {
3067 /// Itanium C++ ABI p3.3.5:
3068 ///
3069 /// After constructing a global (or local static) object, that will require
3070 /// destruction on exit, a termination function is registered as follows:
3071 ///
3072 /// extern "C" int __cxa_atexit ( void (*f)(void *), void *p, void *d );
3073 ///
3074 /// This registration, e.g. __cxa_atexit(f,p,d), is intended to cause the
3075 /// call f(p) when DSO d is unloaded, before all such termination calls
3076 /// registered before this one. It returns zero if registration is
Nick Lewycky35ee1c92011-03-21 02:26:01 +00003077 /// successful, nonzero on failure.
Anders Carlssona201c4c2011-03-20 17:59:11 +00003078
3079 // This pass will look for calls to __cxa_atexit where the function is trivial
3080 // and remove them.
3081 bool Changed = false;
3082
3083 for (Function::use_iterator I = CXAAtExitFn->use_begin(),
3084 E = CXAAtExitFn->use_end(); I != E;) {
Anders Carlsson4f735ca2011-03-20 20:21:33 +00003085 // We're only interested in calls. Theoretically, we could handle invoke
3086 // instructions as well, but neither llvm-gcc nor clang generate invokes
3087 // to __cxa_atexit.
Anders Carlssonb12caf32011-03-21 14:54:40 +00003088 CallInst *CI = dyn_cast<CallInst>(*I++);
3089 if (!CI)
Anders Carlsson4f735ca2011-03-20 20:21:33 +00003090 continue;
3091
Anders Carlssona201c4c2011-03-20 17:59:11 +00003092 Function *DtorFn =
Anders Carlssonb12caf32011-03-21 14:54:40 +00003093 dyn_cast<Function>(CI->getArgOperand(0)->stripPointerCasts());
Anders Carlssona201c4c2011-03-20 17:59:11 +00003094 if (!DtorFn)
3095 continue;
3096
Anders Carlsson372ec6a2011-03-20 20:16:43 +00003097 SmallPtrSet<const Function *, 8> CalledFunctions;
3098 if (!cxxDtorIsEmpty(*DtorFn, CalledFunctions))
Anders Carlssona201c4c2011-03-20 17:59:11 +00003099 continue;
3100
3101 // Just remove the call.
Anders Carlssonb12caf32011-03-21 14:54:40 +00003102 CI->replaceAllUsesWith(Constant::getNullValue(CI->getType()));
3103 CI->eraseFromParent();
Anders Carlsson1f7c7ba2011-03-20 19:51:13 +00003104
Anders Carlssona201c4c2011-03-20 17:59:11 +00003105 ++NumCXXDtorsRemoved;
3106
3107 Changed |= true;
3108 }
3109
3110 return Changed;
3111}
3112
Chris Lattner7a90b682004-10-07 04:16:33 +00003113bool GlobalOpt::runOnModule(Module &M) {
Chris Lattner079236d2004-02-25 21:34:36 +00003114 bool Changed = false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00003115
Nick Lewycky6a577f82012-02-12 01:13:18 +00003116 TD = getAnalysisIfAvailable<TargetData>();
Nick Lewycky6a7df9a2012-02-12 02:15:20 +00003117 TLI = &getAnalysis<TargetLibraryInfo>();
Nick Lewycky6a577f82012-02-12 01:13:18 +00003118
Chris Lattnerb1ab4582005-09-26 01:43:45 +00003119 // Try to find the llvm.globalctors list.
3120 GlobalVariable *GlobalCtors = FindGlobalCtors(M);
Chris Lattner7a90b682004-10-07 04:16:33 +00003121
Nick Lewycky6a7df9a2012-02-12 02:15:20 +00003122 Function *CXAAtExitFn = FindCXAAtExit(M, TLI);
Anders Carlssona201c4c2011-03-20 17:59:11 +00003123
Chris Lattner7a90b682004-10-07 04:16:33 +00003124 bool LocalChange = true;
3125 while (LocalChange) {
3126 LocalChange = false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00003127
Chris Lattnerb1ab4582005-09-26 01:43:45 +00003128 // Delete functions that are trivially dead, ccc -> fastcc
3129 LocalChange |= OptimizeFunctions(M);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00003130
Chris Lattnerb1ab4582005-09-26 01:43:45 +00003131 // Optimize global_ctors list.
3132 if (GlobalCtors)
3133 LocalChange |= OptimizeGlobalCtorsList(GlobalCtors);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00003134
Chris Lattnerb1ab4582005-09-26 01:43:45 +00003135 // Optimize non-address-taken globals.
3136 LocalChange |= OptimizeGlobalVars(M);
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00003137
3138 // Resolve aliases, when possible.
Duncan Sandsfc5940d2009-03-06 10:21:56 +00003139 LocalChange |= OptimizeGlobalAliases(M);
Anders Carlssona201c4c2011-03-20 17:59:11 +00003140
3141 // Try to remove trivial global destructors.
3142 if (CXAAtExitFn)
3143 LocalChange |= OptimizeEmptyGlobalCXXDtors(CXAAtExitFn);
3144
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00003145 Changed |= LocalChange;
Chris Lattner7a90b682004-10-07 04:16:33 +00003146 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00003147
Chris Lattnerb1ab4582005-09-26 01:43:45 +00003148 // TODO: Move all global ctors functions to the end of the module for code
3149 // layout.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00003150
Chris Lattner079236d2004-02-25 21:34:36 +00003151 return Changed;
3152}