blob: 1344ab64c7133ba4aa6752505e0ac56b78e65aa2 [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"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000018#include "llvm/ADT/DenseMap.h"
19#include "llvm/ADT/STLExtras.h"
20#include "llvm/ADT/SmallPtrSet.h"
21#include "llvm/ADT/SmallVector.h"
22#include "llvm/ADT/Statistic.h"
23#include "llvm/Analysis/ConstantFolding.h"
24#include "llvm/Analysis/MemoryBuiltins.h"
Chris Lattnerfb217ad2005-05-08 22:18:06 +000025#include "llvm/CallingConv.h"
Chris Lattner079236d2004-02-25 21:34:36 +000026#include "llvm/Constants.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000027#include "llvm/DataLayout.h"
Chris Lattner7a90b682004-10-07 04:16:33 +000028#include "llvm/DerivedTypes.h"
Chris Lattner7d90a272004-02-27 18:09:25 +000029#include "llvm/Instructions.h"
Chris Lattner35c81b02005-02-27 18:58:52 +000030#include "llvm/IntrinsicInst.h"
Chris Lattner079236d2004-02-25 21:34:36 +000031#include "llvm/Module.h"
Jay Foad562b84b2011-04-11 09:35:34 +000032#include "llvm/Operator.h"
Chris Lattner079236d2004-02-25 21:34:36 +000033#include "llvm/Pass.h"
Duncan Sands548448a2008-02-18 17:32:13 +000034#include "llvm/Support/CallSite.h"
Chris Lattner79066fa2007-01-30 23:46:24 +000035#include "llvm/Support/Debug.h"
Torok Edwinc25e7582009-07-11 20:10:48 +000036#include "llvm/Support/ErrorHandling.h"
Chris Lattner941db492008-01-14 02:09:12 +000037#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner998182b2008-04-26 07:40:11 +000038#include "llvm/Support/MathExtras.h"
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000039#include "llvm/Support/raw_ostream.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000040#include "llvm/Target/TargetLibraryInfo.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
Micah Villmow3574eca2012-10-08 16:38:25 +000086 DataLayout *TD;
Nick Lewycky6a577f82012-02-12 01:13:18 +000087 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
Sylvestre Ledru94c22712012-09-27 10:14:43 +0000175/// SafeToDestroyConstant - It is safe to destroy a constant iff it is only used
Nick Lewyckybc384a12012-02-05 19:48:37 +0000176/// 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;
Jakub Staszak582088c2012-12-06 21:57:16 +0000203
Chris Lattnerd91ed102011-01-01 22:31:46 +0000204 // 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;
Jakub Staszak582088c2012-12-06 21:57:16 +0000207
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;
Hans Wennborg18398582012-11-15 11:40:00 +0000228
Nick Lewyckyfad4d402012-02-05 19:56:38 +0000229 GS.Ordering = StrongerOrdering(GS.Ordering, SI->getOrdering());
Chris Lattnerc69d3c92008-01-29 19:01:37 +0000230
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000231 // If this is a direct store to the global (i.e., the global is a scalar
232 // value, not an aggregate), keep more specific information about
233 // stores.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000234 if (GS.StoredType != GlobalStatus::isStored) {
Gabor Greif27236912010-04-07 18:59:26 +0000235 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(
236 SI->getOperand(1))) {
Chris Lattnerbd38edf2004-11-14 20:50:30 +0000237 Value *StoredVal = SI->getOperand(0);
Hans Wennborg18398582012-11-15 11:40:00 +0000238
239 if (Constant *C = dyn_cast<Constant>(StoredVal)) {
240 if (C->isThreadDependent()) {
241 // The stored value changes between threads; don't track it.
242 return true;
243 }
244 }
245
Chris Lattnerbd38edf2004-11-14 20:50:30 +0000246 if (StoredVal == GV->getInitializer()) {
247 if (GS.StoredType < GlobalStatus::isInitializerStored)
248 GS.StoredType = GlobalStatus::isInitializerStored;
249 } else if (isa<LoadInst>(StoredVal) &&
250 cast<LoadInst>(StoredVal)->getOperand(0) == GV) {
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000251 if (GS.StoredType < GlobalStatus::isInitializerStored)
252 GS.StoredType = GlobalStatus::isInitializerStored;
253 } else if (GS.StoredType < GlobalStatus::isStoredOnce) {
254 GS.StoredType = GlobalStatus::isStoredOnce;
Chris Lattnerbd38edf2004-11-14 20:50:30 +0000255 GS.StoredOnceValue = StoredVal;
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000256 } else if (GS.StoredType == GlobalStatus::isStoredOnce &&
Chris Lattnerbd38edf2004-11-14 20:50:30 +0000257 GS.StoredOnceValue == StoredVal) {
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000258 // noop.
259 } else {
260 GS.StoredType = GlobalStatus::isStored;
261 }
262 } else {
Chris Lattner7a90b682004-10-07 04:16:33 +0000263 GS.StoredType = GlobalStatus::isStored;
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000264 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000265 }
Duncan Sandsb2fe7f12012-07-02 18:55:39 +0000266 } else if (isa<BitCastInst>(I)) {
267 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Chris Lattner35c81b02005-02-27 18:58:52 +0000268 } else if (isa<GetElementPtrInst>(I)) {
Chris Lattner7a90b682004-10-07 04:16:33 +0000269 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Chris Lattner35c81b02005-02-27 18:58:52 +0000270 } else if (isa<SelectInst>(I)) {
Chris Lattner7a90b682004-10-07 04:16:33 +0000271 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000272 } else if (const PHINode *PN = dyn_cast<PHINode>(I)) {
Chris Lattner7a90b682004-10-07 04:16:33 +0000273 // PHI nodes we can check just like select or GEP instructions, but we
274 // have to be careful about infinite recursion.
Chris Lattner5a6bb6a2008-12-16 07:34:30 +0000275 if (PHIUsers.insert(PN)) // Not already visited.
Chris Lattner7a90b682004-10-07 04:16:33 +0000276 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Chris Lattner25de4e52006-11-01 18:03:33 +0000277 GS.HasPHIUser = true;
Reid Spencere4d87aa2006-12-23 06:05:41 +0000278 } else if (isa<CmpInst>(I)) {
Rafael Espindolac4440e32011-01-19 16:32:21 +0000279 GS.isCompared = true;
Nick Lewycky1f237b02011-05-29 18:41:56 +0000280 } else if (const MemTransferInst *MTI = dyn_cast<MemTransferInst>(I)) {
281 if (MTI->isVolatile()) return true;
Gabor Greif9e4f2432010-06-24 14:42:01 +0000282 if (MTI->getArgOperand(0) == V)
Eric Christopher551754c2010-04-16 23:37:20 +0000283 GS.StoredType = GlobalStatus::isStored;
Gabor Greif9e4f2432010-06-24 14:42:01 +0000284 if (MTI->getArgOperand(1) == V)
Chris Lattner35c81b02005-02-27 18:58:52 +0000285 GS.isLoaded = true;
Nick Lewycky1f237b02011-05-29 18:41:56 +0000286 } else if (const MemSetInst *MSI = dyn_cast<MemSetInst>(I)) {
287 assert(MSI->getArgOperand(0) == V && "Memset only takes one pointer!");
288 if (MSI->isVolatile()) return true;
Chris Lattner35c81b02005-02-27 18:58:52 +0000289 GS.StoredType = GlobalStatus::isStored;
Chris Lattner7a90b682004-10-07 04:16:33 +0000290 } else {
291 return true; // Any other non-load instruction might take address!
Chris Lattner9ce30002004-07-20 03:58:07 +0000292 }
Gabor Greife6642672010-07-09 16:51:20 +0000293 } else if (const Constant *C = dyn_cast<Constant>(U)) {
Chris Lattner553ca522005-06-15 21:11:48 +0000294 GS.HasNonInstructionUser = true;
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000295 // We might have a dead and dangling constant hanging off of here.
Jay Foade3acf152009-06-09 21:37:11 +0000296 if (!SafeToDestroyConstant(C))
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000297 return true;
Chris Lattner079236d2004-02-25 21:34:36 +0000298 } else {
Chris Lattner553ca522005-06-15 21:11:48 +0000299 GS.HasNonInstructionUser = true;
300 // Otherwise must be some other user.
Chris Lattner079236d2004-02-25 21:34:36 +0000301 return true;
302 }
Gabor Greife6642672010-07-09 16:51:20 +0000303 }
Chris Lattner079236d2004-02-25 21:34:36 +0000304
305 return false;
306}
307
Nick Lewycky8899d5c2012-07-24 07:21:08 +0000308/// isLeakCheckerRoot - Is this global variable possibly used by a leak checker
309/// as a root? If so, we might not really want to eliminate the stores to it.
310static bool isLeakCheckerRoot(GlobalVariable *GV) {
311 // A global variable is a root if it is a pointer, or could plausibly contain
312 // a pointer. There are two challenges; one is that we could have a struct
313 // the has an inner member which is a pointer. We recurse through the type to
314 // detect these (up to a point). The other is that we may actually be a union
315 // of a pointer and another type, and so our LLVM type is an integer which
316 // gets converted into a pointer, or our type is an [i8 x #] with a pointer
317 // potentially contained here.
318
319 if (GV->hasPrivateLinkage())
320 return false;
321
322 SmallVector<Type *, 4> Types;
323 Types.push_back(cast<PointerType>(GV->getType())->getElementType());
324
325 unsigned Limit = 20;
326 do {
327 Type *Ty = Types.pop_back_val();
328 switch (Ty->getTypeID()) {
329 default: break;
330 case Type::PointerTyID: return true;
331 case Type::ArrayTyID:
332 case Type::VectorTyID: {
333 SequentialType *STy = cast<SequentialType>(Ty);
334 Types.push_back(STy->getElementType());
335 break;
336 }
337 case Type::StructTyID: {
338 StructType *STy = cast<StructType>(Ty);
339 if (STy->isOpaque()) return true;
340 for (StructType::element_iterator I = STy->element_begin(),
341 E = STy->element_end(); I != E; ++I) {
342 Type *InnerTy = *I;
343 if (isa<PointerType>(InnerTy)) return true;
344 if (isa<CompositeType>(InnerTy))
345 Types.push_back(InnerTy);
346 }
347 break;
348 }
349 }
350 if (--Limit == 0) return true;
351 } while (!Types.empty());
352 return false;
353}
354
355/// Given a value that is stored to a global but never read, determine whether
356/// it's safe to remove the store and the chain of computation that feeds the
357/// store.
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000358static bool IsSafeComputationToRemove(Value *V, const TargetLibraryInfo *TLI) {
Nick Lewycky8899d5c2012-07-24 07:21:08 +0000359 do {
360 if (isa<Constant>(V))
361 return true;
362 if (!V->hasOneUse())
363 return false;
Nick Lewyckyb8cd66b2012-07-25 21:19:40 +0000364 if (isa<LoadInst>(V) || isa<InvokeInst>(V) || isa<Argument>(V) ||
365 isa<GlobalValue>(V))
Nick Lewycky8899d5c2012-07-24 07:21:08 +0000366 return false;
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000367 if (isAllocationFn(V, TLI))
Nick Lewycky8899d5c2012-07-24 07:21:08 +0000368 return true;
369
370 Instruction *I = cast<Instruction>(V);
371 if (I->mayHaveSideEffects())
372 return false;
373 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
374 if (!GEP->hasAllConstantIndices())
375 return false;
376 } else if (I->getNumOperands() != 1) {
377 return false;
378 }
379
380 V = I->getOperand(0);
381 } while (1);
382}
383
384/// CleanupPointerRootUsers - This GV is a pointer root. Loop over all users
385/// of the global and clean up any that obviously don't assign the global a
386/// value that isn't dynamically allocated.
387///
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000388static bool CleanupPointerRootUsers(GlobalVariable *GV,
389 const TargetLibraryInfo *TLI) {
Nick Lewycky8899d5c2012-07-24 07:21:08 +0000390 // A brief explanation of leak checkers. The goal is to find bugs where
391 // pointers are forgotten, causing an accumulating growth in memory
392 // usage over time. The common strategy for leak checkers is to whitelist the
393 // memory pointed to by globals at exit. This is popular because it also
394 // solves another problem where the main thread of a C++ program may shut down
395 // before other threads that are still expecting to use those globals. To
396 // handle that case, we expect the program may create a singleton and never
397 // destroy it.
398
399 bool Changed = false;
400
401 // If Dead[n].first is the only use of a malloc result, we can delete its
402 // chain of computation and the store to the global in Dead[n].second.
403 SmallVector<std::pair<Instruction *, Instruction *>, 32> Dead;
404
405 // Constants can't be pointers to dynamically allocated memory.
406 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end();
407 UI != E;) {
408 User *U = *UI++;
409 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
410 Value *V = SI->getValueOperand();
411 if (isa<Constant>(V)) {
412 Changed = true;
413 SI->eraseFromParent();
414 } else if (Instruction *I = dyn_cast<Instruction>(V)) {
415 if (I->hasOneUse())
416 Dead.push_back(std::make_pair(I, SI));
417 }
418 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(U)) {
419 if (isa<Constant>(MSI->getValue())) {
420 Changed = true;
421 MSI->eraseFromParent();
422 } else if (Instruction *I = dyn_cast<Instruction>(MSI->getValue())) {
423 if (I->hasOneUse())
424 Dead.push_back(std::make_pair(I, MSI));
425 }
426 } else if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(U)) {
427 GlobalVariable *MemSrc = dyn_cast<GlobalVariable>(MTI->getSource());
428 if (MemSrc && MemSrc->isConstant()) {
429 Changed = true;
430 MTI->eraseFromParent();
431 } else if (Instruction *I = dyn_cast<Instruction>(MemSrc)) {
432 if (I->hasOneUse())
433 Dead.push_back(std::make_pair(I, MTI));
434 }
435 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
436 if (CE->use_empty()) {
437 CE->destroyConstant();
438 Changed = true;
439 }
440 } else if (Constant *C = dyn_cast<Constant>(U)) {
441 if (SafeToDestroyConstant(C)) {
442 C->destroyConstant();
443 // This could have invalidated UI, start over from scratch.
444 Dead.clear();
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000445 CleanupPointerRootUsers(GV, TLI);
Nick Lewycky8899d5c2012-07-24 07:21:08 +0000446 return true;
447 }
448 }
449 }
450
451 for (int i = 0, e = Dead.size(); i != e; ++i) {
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000452 if (IsSafeComputationToRemove(Dead[i].first, TLI)) {
Nick Lewycky8899d5c2012-07-24 07:21:08 +0000453 Dead[i].second->eraseFromParent();
454 Instruction *I = Dead[i].first;
455 do {
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000456 if (isAllocationFn(I, TLI))
Nick Lewycky952f5d52012-07-24 21:33:00 +0000457 break;
Nick Lewycky8899d5c2012-07-24 07:21:08 +0000458 Instruction *J = dyn_cast<Instruction>(I->getOperand(0));
459 if (!J)
460 break;
461 I->eraseFromParent();
462 I = J;
Nick Lewycky952f5d52012-07-24 21:33:00 +0000463 } while (1);
Nick Lewycky8899d5c2012-07-24 07:21:08 +0000464 I->eraseFromParent();
465 }
466 }
467
468 return Changed;
469}
470
Chris Lattnere47ba742004-10-06 20:57:02 +0000471/// CleanupConstantGlobalUsers - We just marked GV constant. Loop over all
472/// users of the global, cleaning up the obvious ones. This is largely just a
Chris Lattner031955d2004-10-10 16:43:46 +0000473/// quick scan over the use list to clean up the easy and obvious cruft. This
474/// returns true if it made a change.
Nick Lewycky6a577f82012-02-12 01:13:18 +0000475static bool CleanupConstantGlobalUsers(Value *V, Constant *Init,
Micah Villmow3574eca2012-10-08 16:38:25 +0000476 DataLayout *TD, TargetLibraryInfo *TLI) {
Chris Lattner031955d2004-10-10 16:43:46 +0000477 bool Changed = false;
Chris Lattner7a90b682004-10-07 04:16:33 +0000478 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;) {
479 User *U = *UI++;
Misha Brukmanfd939082005-04-21 23:48:37 +0000480
Chris Lattner7a90b682004-10-07 04:16:33 +0000481 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
Chris Lattner35c81b02005-02-27 18:58:52 +0000482 if (Init) {
483 // Replace the load with the initializer.
484 LI->replaceAllUsesWith(Init);
485 LI->eraseFromParent();
486 Changed = true;
487 }
Chris Lattner7a90b682004-10-07 04:16:33 +0000488 } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
Chris Lattnere47ba742004-10-06 20:57:02 +0000489 // Store must be unreachable or storing Init into the global.
Chris Lattner7a7ed022004-10-16 18:09:00 +0000490 SI->eraseFromParent();
Chris Lattner031955d2004-10-10 16:43:46 +0000491 Changed = true;
Chris Lattner7a90b682004-10-07 04:16:33 +0000492 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
493 if (CE->getOpcode() == Instruction::GetElementPtr) {
Chris Lattneraae4a1c2005-09-26 07:34:35 +0000494 Constant *SubInit = 0;
495 if (Init)
Dan Gohmanc6f69e92009-10-05 16:36:26 +0000496 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
Nick Lewycky6a577f82012-02-12 01:13:18 +0000497 Changed |= CleanupConstantGlobalUsers(CE, SubInit, TD, TLI);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000498 } else if (CE->getOpcode() == Instruction::BitCast &&
Duncan Sands1df98592010-02-16 11:11:14 +0000499 CE->getType()->isPointerTy()) {
Chris Lattner35c81b02005-02-27 18:58:52 +0000500 // Pointer cast, delete any stores and memsets to the global.
Nick Lewycky6a577f82012-02-12 01:13:18 +0000501 Changed |= CleanupConstantGlobalUsers(CE, 0, TD, TLI);
Chris Lattner35c81b02005-02-27 18:58:52 +0000502 }
503
504 if (CE->use_empty()) {
505 CE->destroyConstant();
506 Changed = true;
Chris Lattner7a90b682004-10-07 04:16:33 +0000507 }
508 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
Chris Lattner7b52fe72007-11-09 17:33:02 +0000509 // Do not transform "gepinst (gep constexpr (GV))" here, because forming
510 // "gepconstexpr (gep constexpr (GV))" will cause the two gep's to fold
511 // and will invalidate our notion of what Init is.
Chris Lattner19450242007-11-13 21:46:23 +0000512 Constant *SubInit = 0;
Chris Lattner7b52fe72007-11-09 17:33:02 +0000513 if (!isa<ConstantExpr>(GEP->getOperand(0))) {
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000514 ConstantExpr *CE =
Nick Lewycky6a577f82012-02-12 01:13:18 +0000515 dyn_cast_or_null<ConstantExpr>(ConstantFoldInstruction(GEP, TD, TLI));
Chris Lattner7b52fe72007-11-09 17:33:02 +0000516 if (Init && CE && CE->getOpcode() == Instruction::GetElementPtr)
Dan Gohmanc6f69e92009-10-05 16:36:26 +0000517 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
Benjamin Kramerc1ea16e2012-03-28 14:50:09 +0000518
519 // If the initializer is an all-null value and we have an inbounds GEP,
520 // we already know what the result of any load from that GEP is.
521 // TODO: Handle splats.
522 if (Init && isa<ConstantAggregateZero>(Init) && GEP->isInBounds())
523 SubInit = Constant::getNullValue(GEP->getType()->getElementType());
Chris Lattner7b52fe72007-11-09 17:33:02 +0000524 }
Nick Lewycky6a577f82012-02-12 01:13:18 +0000525 Changed |= CleanupConstantGlobalUsers(GEP, SubInit, TD, TLI);
Chris Lattnerc4d81b02004-10-10 16:47:33 +0000526
Chris Lattner031955d2004-10-10 16:43:46 +0000527 if (GEP->use_empty()) {
Chris Lattner7a7ed022004-10-16 18:09:00 +0000528 GEP->eraseFromParent();
Chris Lattner031955d2004-10-10 16:43:46 +0000529 Changed = true;
530 }
Chris Lattner35c81b02005-02-27 18:58:52 +0000531 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U)) { // memset/cpy/mv
532 if (MI->getRawDest() == V) {
533 MI->eraseFromParent();
534 Changed = true;
535 }
536
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000537 } else if (Constant *C = dyn_cast<Constant>(U)) {
538 // If we have a chain of dead constantexprs or other things dangling from
539 // us, and if they are all dead, nuke them without remorse.
Jay Foade3acf152009-06-09 21:37:11 +0000540 if (SafeToDestroyConstant(C)) {
Devang Patel743cdf82009-03-06 01:37:41 +0000541 C->destroyConstant();
Chris Lattner35c81b02005-02-27 18:58:52 +0000542 // This could have invalidated UI, start over from scratch.
Nick Lewycky6a577f82012-02-12 01:13:18 +0000543 CleanupConstantGlobalUsers(V, Init, TD, TLI);
Chris Lattner031955d2004-10-10 16:43:46 +0000544 return true;
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000545 }
Chris Lattnere47ba742004-10-06 20:57:02 +0000546 }
547 }
Chris Lattner031955d2004-10-10 16:43:46 +0000548 return Changed;
Chris Lattnere47ba742004-10-06 20:57:02 +0000549}
550
Chris Lattner941db492008-01-14 02:09:12 +0000551/// isSafeSROAElementUse - Return true if the specified instruction is a safe
552/// user of a derived expression from a global that we want to SROA.
553static bool isSafeSROAElementUse(Value *V) {
554 // We might have a dead and dangling constant hanging off of here.
555 if (Constant *C = dyn_cast<Constant>(V))
Jay Foade3acf152009-06-09 21:37:11 +0000556 return SafeToDestroyConstant(C);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000557
Chris Lattner941db492008-01-14 02:09:12 +0000558 Instruction *I = dyn_cast<Instruction>(V);
559 if (!I) return false;
560
561 // Loads are ok.
562 if (isa<LoadInst>(I)) return true;
563
564 // Stores *to* the pointer are ok.
565 if (StoreInst *SI = dyn_cast<StoreInst>(I))
566 return SI->getOperand(0) != V;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000567
Chris Lattner941db492008-01-14 02:09:12 +0000568 // Otherwise, it must be a GEP.
569 GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I);
570 if (GEPI == 0) return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000571
Chris Lattner941db492008-01-14 02:09:12 +0000572 if (GEPI->getNumOperands() < 3 || !isa<Constant>(GEPI->getOperand(1)) ||
573 !cast<Constant>(GEPI->getOperand(1))->isNullValue())
574 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000575
Chris Lattner941db492008-01-14 02:09:12 +0000576 for (Value::use_iterator I = GEPI->use_begin(), E = GEPI->use_end();
577 I != E; ++I)
578 if (!isSafeSROAElementUse(*I))
579 return false;
Chris Lattner727c2102008-01-14 01:31:05 +0000580 return true;
581}
582
Chris Lattner941db492008-01-14 02:09:12 +0000583
584/// IsUserOfGlobalSafeForSRA - U is a direct user of the specified global value.
585/// Look at it and its uses and decide whether it is safe to SROA this global.
586///
587static bool IsUserOfGlobalSafeForSRA(User *U, GlobalValue *GV) {
588 // The user of the global must be a GEP Inst or a ConstantExpr GEP.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000589 if (!isa<GetElementPtrInst>(U) &&
590 (!isa<ConstantExpr>(U) ||
Chris Lattner941db492008-01-14 02:09:12 +0000591 cast<ConstantExpr>(U)->getOpcode() != Instruction::GetElementPtr))
592 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000593
Chris Lattner941db492008-01-14 02:09:12 +0000594 // Check to see if this ConstantExpr GEP is SRA'able. In particular, we
595 // don't like < 3 operand CE's, and we don't like non-constant integer
596 // indices. This enforces that all uses are 'gep GV, 0, C, ...' for some
597 // value of C.
598 if (U->getNumOperands() < 3 || !isa<Constant>(U->getOperand(1)) ||
599 !cast<Constant>(U->getOperand(1))->isNullValue() ||
600 !isa<ConstantInt>(U->getOperand(2)))
601 return false;
602
603 gep_type_iterator GEPI = gep_type_begin(U), E = gep_type_end(U);
604 ++GEPI; // Skip over the pointer index.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000605
Chris Lattner941db492008-01-14 02:09:12 +0000606 // If this is a use of an array allocation, do a bit more checking for sanity.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000607 if (ArrayType *AT = dyn_cast<ArrayType>(*GEPI)) {
Chris Lattner941db492008-01-14 02:09:12 +0000608 uint64_t NumElements = AT->getNumElements();
609 ConstantInt *Idx = cast<ConstantInt>(U->getOperand(2));
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000610
Chris Lattner941db492008-01-14 02:09:12 +0000611 // Check to make sure that index falls within the array. If not,
612 // something funny is going on, so we won't do the optimization.
613 //
614 if (Idx->getZExtValue() >= NumElements)
615 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000616
Chris Lattner941db492008-01-14 02:09:12 +0000617 // We cannot scalar repl this level of the array unless any array
618 // sub-indices are in-range constants. In particular, consider:
619 // A[0][i]. We cannot know that the user isn't doing invalid things like
620 // allowing i to index an out-of-range subscript that accesses A[1].
621 //
622 // Scalar replacing *just* the outer index of the array is probably not
623 // going to be a win anyway, so just give up.
624 for (++GEPI; // Skip array index.
Dan Gohman6874a2a2009-08-18 14:58:19 +0000625 GEPI != E;
Chris Lattner941db492008-01-14 02:09:12 +0000626 ++GEPI) {
627 uint64_t NumElements;
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000628 if (ArrayType *SubArrayTy = dyn_cast<ArrayType>(*GEPI))
Chris Lattner941db492008-01-14 02:09:12 +0000629 NumElements = SubArrayTy->getNumElements();
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000630 else if (VectorType *SubVectorTy = dyn_cast<VectorType>(*GEPI))
Dan Gohman6874a2a2009-08-18 14:58:19 +0000631 NumElements = SubVectorTy->getNumElements();
632 else {
Duncan Sands1df98592010-02-16 11:11:14 +0000633 assert((*GEPI)->isStructTy() &&
Dan Gohman6874a2a2009-08-18 14:58:19 +0000634 "Indexed GEP type is not array, vector, or struct!");
635 continue;
636 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000637
Chris Lattner941db492008-01-14 02:09:12 +0000638 ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPI.getOperand());
639 if (!IdxVal || IdxVal->getZExtValue() >= NumElements)
640 return false;
641 }
642 }
643
644 for (Value::use_iterator I = U->use_begin(), E = U->use_end(); I != E; ++I)
645 if (!isSafeSROAElementUse(*I))
646 return false;
647 return true;
648}
649
650/// GlobalUsersSafeToSRA - Look at all uses of the global and decide whether it
651/// is safe for us to perform this transformation.
652///
653static bool GlobalUsersSafeToSRA(GlobalValue *GV) {
654 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end();
655 UI != E; ++UI) {
656 if (!IsUserOfGlobalSafeForSRA(*UI, GV))
657 return false;
658 }
659 return true;
660}
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000661
Chris Lattner941db492008-01-14 02:09:12 +0000662
Chris Lattner670c8892004-10-08 17:32:09 +0000663/// SRAGlobal - Perform scalar replacement of aggregates on the specified global
664/// variable. This opens the door for other optimizations by exposing the
665/// behavior of the program in a more fine-grained way. We have determined that
666/// this transformation is safe already. We return the first global variable we
667/// insert so that the caller can reprocess it.
Micah Villmow3574eca2012-10-08 16:38:25 +0000668static GlobalVariable *SRAGlobal(GlobalVariable *GV, const DataLayout &TD) {
Chris Lattner727c2102008-01-14 01:31:05 +0000669 // Make sure this global only has simple uses that we can SRA.
Chris Lattner941db492008-01-14 02:09:12 +0000670 if (!GlobalUsersSafeToSRA(GV))
Chris Lattner727c2102008-01-14 01:31:05 +0000671 return 0;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000672
Rafael Espindolabb46f522009-01-15 20:18:42 +0000673 assert(GV->hasLocalLinkage() && !GV->isConstant());
Chris Lattner670c8892004-10-08 17:32:09 +0000674 Constant *Init = GV->getInitializer();
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000675 Type *Ty = Init->getType();
Misha Brukmanfd939082005-04-21 23:48:37 +0000676
Chris Lattner670c8892004-10-08 17:32:09 +0000677 std::vector<GlobalVariable*> NewGlobals;
678 Module::GlobalListType &Globals = GV->getParent()->getGlobalList();
679
Chris Lattner998182b2008-04-26 07:40:11 +0000680 // Get the alignment of the global, either explicit or target-specific.
681 unsigned StartAlignment = GV->getAlignment();
682 if (StartAlignment == 0)
683 StartAlignment = TD.getABITypeAlignment(GV->getType());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000684
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000685 if (StructType *STy = dyn_cast<StructType>(Ty)) {
Chris Lattner670c8892004-10-08 17:32:09 +0000686 NewGlobals.reserve(STy->getNumElements());
Chris Lattner998182b2008-04-26 07:40:11 +0000687 const StructLayout &Layout = *TD.getStructLayout(STy);
Chris Lattner670c8892004-10-08 17:32:09 +0000688 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
Chris Lattnera1f00f42012-01-25 06:48:06 +0000689 Constant *In = Init->getAggregateElement(i);
Chris Lattner670c8892004-10-08 17:32:09 +0000690 assert(In && "Couldn't get element of initializer?");
Chris Lattner7b550cc2009-11-06 04:27:31 +0000691 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(i), false,
Chris Lattner670c8892004-10-08 17:32:09 +0000692 GlobalVariable::InternalLinkage,
Daniel Dunbarfe09b202009-07-30 17:37:43 +0000693 In, GV->getName()+"."+Twine(i),
Hans Wennborgce718ff2012-06-23 11:37:03 +0000694 GV->getThreadLocalMode(),
Owen Anderson3d29df32009-07-08 01:26:06 +0000695 GV->getType()->getAddressSpace());
Chris Lattner670c8892004-10-08 17:32:09 +0000696 Globals.insert(GV, NGV);
697 NewGlobals.push_back(NGV);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000698
Chris Lattner998182b2008-04-26 07:40:11 +0000699 // Calculate the known alignment of the field. If the original aggregate
700 // had 256 byte alignment for example, something might depend on that:
701 // propagate info to each field.
702 uint64_t FieldOffset = Layout.getElementOffset(i);
703 unsigned NewAlign = (unsigned)MinAlign(StartAlignment, FieldOffset);
704 if (NewAlign > TD.getABITypeAlignment(STy->getElementType(i)))
705 NGV->setAlignment(NewAlign);
Chris Lattner670c8892004-10-08 17:32:09 +0000706 }
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000707 } else if (SequentialType *STy = dyn_cast<SequentialType>(Ty)) {
Chris Lattner670c8892004-10-08 17:32:09 +0000708 unsigned NumElements = 0;
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000709 if (ArrayType *ATy = dyn_cast<ArrayType>(STy))
Chris Lattner670c8892004-10-08 17:32:09 +0000710 NumElements = ATy->getNumElements();
Chris Lattner670c8892004-10-08 17:32:09 +0000711 else
Chris Lattner998182b2008-04-26 07:40:11 +0000712 NumElements = cast<VectorType>(STy)->getNumElements();
Chris Lattner670c8892004-10-08 17:32:09 +0000713
Chris Lattner1f21ef12005-02-23 16:53:04 +0000714 if (NumElements > 16 && GV->hasNUsesOrMore(16))
Chris Lattnerd514d822005-02-01 01:23:31 +0000715 return 0; // It's not worth it.
Chris Lattner670c8892004-10-08 17:32:09 +0000716 NewGlobals.reserve(NumElements);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000717
Duncan Sands777d2302009-05-09 07:06:46 +0000718 uint64_t EltSize = TD.getTypeAllocSize(STy->getElementType());
Chris Lattner998182b2008-04-26 07:40:11 +0000719 unsigned EltAlign = TD.getABITypeAlignment(STy->getElementType());
Chris Lattner670c8892004-10-08 17:32:09 +0000720 for (unsigned i = 0, e = NumElements; i != e; ++i) {
Chris Lattnera1f00f42012-01-25 06:48:06 +0000721 Constant *In = Init->getAggregateElement(i);
Chris Lattner670c8892004-10-08 17:32:09 +0000722 assert(In && "Couldn't get element of initializer?");
723
Chris Lattner7b550cc2009-11-06 04:27:31 +0000724 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(), false,
Chris Lattner670c8892004-10-08 17:32:09 +0000725 GlobalVariable::InternalLinkage,
Daniel Dunbarfe09b202009-07-30 17:37:43 +0000726 In, GV->getName()+"."+Twine(i),
Hans Wennborgce718ff2012-06-23 11:37:03 +0000727 GV->getThreadLocalMode(),
Owen Andersone9b11b42009-07-08 19:03:57 +0000728 GV->getType()->getAddressSpace());
Chris Lattner670c8892004-10-08 17:32:09 +0000729 Globals.insert(GV, NGV);
730 NewGlobals.push_back(NGV);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000731
Chris Lattner998182b2008-04-26 07:40:11 +0000732 // Calculate the known alignment of the field. If the original aggregate
733 // had 256 byte alignment for example, something might depend on that:
734 // propagate info to each field.
735 unsigned NewAlign = (unsigned)MinAlign(StartAlignment, EltSize*i);
736 if (NewAlign > EltAlign)
737 NGV->setAlignment(NewAlign);
Chris Lattner670c8892004-10-08 17:32:09 +0000738 }
739 }
740
741 if (NewGlobals.empty())
742 return 0;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000743
David Greene3215b0e2010-01-05 01:28:05 +0000744 DEBUG(dbgs() << "PERFORMING GLOBAL SRA ON: " << *GV);
Chris Lattner30ba5692004-10-11 05:54:41 +0000745
Chris Lattner7b550cc2009-11-06 04:27:31 +0000746 Constant *NullInt =Constant::getNullValue(Type::getInt32Ty(GV->getContext()));
Chris Lattner670c8892004-10-08 17:32:09 +0000747
748 // Loop over all of the uses of the global, replacing the constantexpr geps,
749 // with smaller constantexpr geps or direct references.
750 while (!GV->use_empty()) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000751 User *GEP = GV->use_back();
752 assert(((isa<ConstantExpr>(GEP) &&
753 cast<ConstantExpr>(GEP)->getOpcode()==Instruction::GetElementPtr)||
754 isa<GetElementPtrInst>(GEP)) && "NonGEP CE's are not SRAable!");
Misha Brukmanfd939082005-04-21 23:48:37 +0000755
Chris Lattner670c8892004-10-08 17:32:09 +0000756 // Ignore the 1th operand, which has to be zero or else the program is quite
757 // broken (undefined). Get the 2nd operand, which is the structure or array
758 // index.
Reid Spencerb83eb642006-10-20 07:07:24 +0000759 unsigned Val = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
Chris Lattner670c8892004-10-08 17:32:09 +0000760 if (Val >= NewGlobals.size()) Val = 0; // Out of bound array access.
761
Chris Lattner30ba5692004-10-11 05:54:41 +0000762 Value *NewPtr = NewGlobals[Val];
Chris Lattner670c8892004-10-08 17:32:09 +0000763
764 // Form a shorter GEP if needed.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000765 if (GEP->getNumOperands() > 3) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000766 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEP)) {
Chris Lattner55eb1c42007-01-31 04:40:53 +0000767 SmallVector<Constant*, 8> Idxs;
Chris Lattner30ba5692004-10-11 05:54:41 +0000768 Idxs.push_back(NullInt);
769 for (unsigned i = 3, e = CE->getNumOperands(); i != e; ++i)
770 Idxs.push_back(CE->getOperand(i));
Jay Foaddab3d292011-07-21 14:31:17 +0000771 NewPtr = ConstantExpr::getGetElementPtr(cast<Constant>(NewPtr), Idxs);
Chris Lattner30ba5692004-10-11 05:54:41 +0000772 } else {
773 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(GEP);
Chris Lattner699d1442007-01-31 19:59:55 +0000774 SmallVector<Value*, 8> Idxs;
Chris Lattner30ba5692004-10-11 05:54:41 +0000775 Idxs.push_back(NullInt);
776 for (unsigned i = 3, e = GEPI->getNumOperands(); i != e; ++i)
777 Idxs.push_back(GEPI->getOperand(i));
Jay Foada9203102011-07-25 09:48:08 +0000778 NewPtr = GetElementPtrInst::Create(NewPtr, Idxs,
Daniel Dunbarfe09b202009-07-30 17:37:43 +0000779 GEPI->getName()+"."+Twine(Val),GEPI);
Chris Lattner30ba5692004-10-11 05:54:41 +0000780 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000781 }
Chris Lattner30ba5692004-10-11 05:54:41 +0000782 GEP->replaceAllUsesWith(NewPtr);
783
784 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(GEP))
Chris Lattner7a7ed022004-10-16 18:09:00 +0000785 GEPI->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +0000786 else
787 cast<ConstantExpr>(GEP)->destroyConstant();
Chris Lattner670c8892004-10-08 17:32:09 +0000788 }
789
Chris Lattnere40e2d12004-10-08 20:25:55 +0000790 // Delete the old global, now that it is dead.
791 Globals.erase(GV);
Chris Lattner670c8892004-10-08 17:32:09 +0000792 ++NumSRA;
Chris Lattner30ba5692004-10-11 05:54:41 +0000793
794 // Loop over the new globals array deleting any globals that are obviously
795 // dead. This can arise due to scalarization of a structure or an array that
796 // has elements that are dead.
797 unsigned FirstGlobal = 0;
798 for (unsigned i = 0, e = NewGlobals.size(); i != e; ++i)
799 if (NewGlobals[i]->use_empty()) {
800 Globals.erase(NewGlobals[i]);
801 if (FirstGlobal == i) ++FirstGlobal;
802 }
803
804 return FirstGlobal != NewGlobals.size() ? NewGlobals[FirstGlobal] : 0;
Chris Lattner670c8892004-10-08 17:32:09 +0000805}
806
Chris Lattner9b34a612004-10-09 21:48:45 +0000807/// AllUsesOfValueWillTrapIfNull - Return true if all users of the specified
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000808/// value will trap if the value is dynamically null. PHIs keeps track of any
Chris Lattner81686182007-09-13 16:30:19 +0000809/// phi nodes we've seen to avoid reprocessing them.
Gabor Greif6ce02b52010-04-06 19:24:18 +0000810static bool AllUsesOfValueWillTrapIfNull(const Value *V,
811 SmallPtrSet<const PHINode*, 8> &PHIs) {
812 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;
Gabor Greifa01d6db2010-04-06 19:14:05 +0000813 ++UI) {
Gabor Greif6ce02b52010-04-06 19:24:18 +0000814 const User *U = *UI;
Gabor Greifa01d6db2010-04-06 19:14:05 +0000815
816 if (isa<LoadInst>(U)) {
Chris Lattner9b34a612004-10-09 21:48:45 +0000817 // Will trap.
Gabor Greif6ce02b52010-04-06 19:24:18 +0000818 } else if (const StoreInst *SI = dyn_cast<StoreInst>(U)) {
Chris Lattner9b34a612004-10-09 21:48:45 +0000819 if (SI->getOperand(0) == V) {
Gabor Greifa01d6db2010-04-06 19:14:05 +0000820 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner9b34a612004-10-09 21:48:45 +0000821 return false; // Storing the value.
822 }
Gabor Greif6ce02b52010-04-06 19:24:18 +0000823 } else if (const CallInst *CI = dyn_cast<CallInst>(U)) {
Gabor Greif654c06f2010-03-20 21:00:25 +0000824 if (CI->getCalledValue() != V) {
Gabor Greifa01d6db2010-04-06 19:14:05 +0000825 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner9b34a612004-10-09 21:48:45 +0000826 return false; // Not calling the ptr
827 }
Gabor Greif6ce02b52010-04-06 19:24:18 +0000828 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(U)) {
Gabor Greif654c06f2010-03-20 21:00:25 +0000829 if (II->getCalledValue() != V) {
Gabor Greifa01d6db2010-04-06 19:14:05 +0000830 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner9b34a612004-10-09 21:48:45 +0000831 return false; // Not calling the ptr
832 }
Gabor Greif6ce02b52010-04-06 19:24:18 +0000833 } else if (const BitCastInst *CI = dyn_cast<BitCastInst>(U)) {
Chris Lattner81686182007-09-13 16:30:19 +0000834 if (!AllUsesOfValueWillTrapIfNull(CI, PHIs)) return false;
Gabor Greif6ce02b52010-04-06 19:24:18 +0000835 } else if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
Chris Lattner81686182007-09-13 16:30:19 +0000836 if (!AllUsesOfValueWillTrapIfNull(GEPI, PHIs)) return false;
Gabor Greif6ce02b52010-04-06 19:24:18 +0000837 } else if (const PHINode *PN = dyn_cast<PHINode>(U)) {
Chris Lattner81686182007-09-13 16:30:19 +0000838 // If we've already seen this phi node, ignore it, it has already been
839 // checked.
Jakob Stoklund Olesenb489d0f2010-01-29 23:54:14 +0000840 if (PHIs.insert(PN) && !AllUsesOfValueWillTrapIfNull(PN, PHIs))
841 return false;
Gabor Greifa01d6db2010-04-06 19:14:05 +0000842 } else if (isa<ICmpInst>(U) &&
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000843 isa<ConstantPointerNull>(UI->getOperand(1))) {
Nick Lewyckye7ee59b2010-02-25 06:39:10 +0000844 // Ignore icmp X, null
Chris Lattner9b34a612004-10-09 21:48:45 +0000845 } else {
Gabor Greifa01d6db2010-04-06 19:14:05 +0000846 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner9b34a612004-10-09 21:48:45 +0000847 return false;
848 }
Gabor Greifa01d6db2010-04-06 19:14:05 +0000849 }
Chris Lattner9b34a612004-10-09 21:48:45 +0000850 return true;
851}
852
853/// AllUsesOfLoadedValueWillTrapIfNull - Return true if all uses of any loads
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000854/// from GV will trap if the loaded value is null. Note that this also permits
855/// comparisons of the loaded value against null, as a special case.
Gabor Greif6ce02b52010-04-06 19:24:18 +0000856static bool AllUsesOfLoadedValueWillTrapIfNull(const GlobalVariable *GV) {
857 for (Value::const_use_iterator UI = GV->use_begin(), E = GV->use_end();
Gabor Greifa01d6db2010-04-06 19:14:05 +0000858 UI != E; ++UI) {
Gabor Greif6ce02b52010-04-06 19:24:18 +0000859 const User *U = *UI;
Gabor Greifa01d6db2010-04-06 19:14:05 +0000860
Gabor Greif6ce02b52010-04-06 19:24:18 +0000861 if (const LoadInst *LI = dyn_cast<LoadInst>(U)) {
862 SmallPtrSet<const PHINode*, 8> PHIs;
Chris Lattner81686182007-09-13 16:30:19 +0000863 if (!AllUsesOfValueWillTrapIfNull(LI, PHIs))
Chris Lattner9b34a612004-10-09 21:48:45 +0000864 return false;
Gabor Greifa01d6db2010-04-06 19:14:05 +0000865 } else if (isa<StoreInst>(U)) {
Chris Lattner9b34a612004-10-09 21:48:45 +0000866 // Ignore stores to the global.
867 } else {
868 // We don't know or understand this user, bail out.
Gabor Greifa01d6db2010-04-06 19:14:05 +0000869 //cerr << "UNKNOWN USER OF GLOBAL!: " << *U;
Chris Lattner9b34a612004-10-09 21:48:45 +0000870 return false;
871 }
Gabor Greifa01d6db2010-04-06 19:14:05 +0000872 }
Chris Lattner9b34a612004-10-09 21:48:45 +0000873 return true;
874}
875
Chris Lattner7b550cc2009-11-06 04:27:31 +0000876static bool OptimizeAwayTrappingUsesOfValue(Value *V, Constant *NewV) {
Chris Lattner708148e2004-10-10 23:14:11 +0000877 bool Changed = false;
878 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ) {
879 Instruction *I = cast<Instruction>(*UI++);
880 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
881 LI->setOperand(0, NewV);
882 Changed = true;
883 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
884 if (SI->getOperand(1) == V) {
885 SI->setOperand(1, NewV);
886 Changed = true;
887 }
888 } else if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
Gabor Greiffa1f5c22010-04-06 18:45:08 +0000889 CallSite CS(I);
890 if (CS.getCalledValue() == V) {
Chris Lattner708148e2004-10-10 23:14:11 +0000891 // Calling through the pointer! Turn into a direct call, but be careful
892 // that the pointer is not also being passed as an argument.
Gabor Greiffa1f5c22010-04-06 18:45:08 +0000893 CS.setCalledFunction(NewV);
Chris Lattner708148e2004-10-10 23:14:11 +0000894 Changed = true;
895 bool PassedAsArg = false;
Gabor Greiffa1f5c22010-04-06 18:45:08 +0000896 for (unsigned i = 0, e = CS.arg_size(); i != e; ++i)
897 if (CS.getArgument(i) == V) {
Chris Lattner708148e2004-10-10 23:14:11 +0000898 PassedAsArg = true;
Gabor Greiffa1f5c22010-04-06 18:45:08 +0000899 CS.setArgument(i, NewV);
Chris Lattner708148e2004-10-10 23:14:11 +0000900 }
901
902 if (PassedAsArg) {
903 // Being passed as an argument also. Be careful to not invalidate UI!
904 UI = V->use_begin();
905 }
906 }
907 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
908 Changed |= OptimizeAwayTrappingUsesOfValue(CI,
Owen Andersonbaf3c402009-07-29 18:55:55 +0000909 ConstantExpr::getCast(CI->getOpcode(),
Chris Lattner7b550cc2009-11-06 04:27:31 +0000910 NewV, CI->getType()));
Chris Lattner708148e2004-10-10 23:14:11 +0000911 if (CI->use_empty()) {
912 Changed = true;
Chris Lattner7a7ed022004-10-16 18:09:00 +0000913 CI->eraseFromParent();
Chris Lattner708148e2004-10-10 23:14:11 +0000914 }
915 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
916 // Should handle GEP here.
Chris Lattner55eb1c42007-01-31 04:40:53 +0000917 SmallVector<Constant*, 8> Idxs;
918 Idxs.reserve(GEPI->getNumOperands()-1);
Gabor Greif5e463212008-05-29 01:59:18 +0000919 for (User::op_iterator i = GEPI->op_begin() + 1, e = GEPI->op_end();
920 i != e; ++i)
921 if (Constant *C = dyn_cast<Constant>(*i))
Chris Lattner55eb1c42007-01-31 04:40:53 +0000922 Idxs.push_back(C);
Chris Lattner708148e2004-10-10 23:14:11 +0000923 else
924 break;
Chris Lattner55eb1c42007-01-31 04:40:53 +0000925 if (Idxs.size() == GEPI->getNumOperands()-1)
Chris Lattner708148e2004-10-10 23:14:11 +0000926 Changed |= OptimizeAwayTrappingUsesOfValue(GEPI,
Jay Foaddab3d292011-07-21 14:31:17 +0000927 ConstantExpr::getGetElementPtr(NewV, Idxs));
Chris Lattner708148e2004-10-10 23:14:11 +0000928 if (GEPI->use_empty()) {
929 Changed = true;
Chris Lattner7a7ed022004-10-16 18:09:00 +0000930 GEPI->eraseFromParent();
Chris Lattner708148e2004-10-10 23:14:11 +0000931 }
932 }
933 }
934
935 return Changed;
936}
937
938
939/// OptimizeAwayTrappingUsesOfLoads - The specified global has only one non-null
940/// value stored into it. If there are uses of the loaded value that would trap
941/// if the loaded value is dynamically null, then we know that they cannot be
942/// reachable with a null optimize away the load.
Nick Lewycky6a577f82012-02-12 01:13:18 +0000943static bool OptimizeAwayTrappingUsesOfLoads(GlobalVariable *GV, Constant *LV,
Micah Villmow3574eca2012-10-08 16:38:25 +0000944 DataLayout *TD,
Nick Lewycky6a577f82012-02-12 01:13:18 +0000945 TargetLibraryInfo *TLI) {
Chris Lattner708148e2004-10-10 23:14:11 +0000946 bool Changed = false;
947
Chris Lattner92c6bd22009-01-14 00:12:58 +0000948 // Keep track of whether we are able to remove all the uses of the global
949 // other than the store that defines it.
950 bool AllNonStoreUsesGone = true;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000951
Chris Lattner708148e2004-10-10 23:14:11 +0000952 // Replace all uses of loads with uses of uses of the stored value.
Chris Lattner92c6bd22009-01-14 00:12:58 +0000953 for (Value::use_iterator GUI = GV->use_begin(), E = GV->use_end(); GUI != E;){
954 User *GlobalUser = *GUI++;
955 if (LoadInst *LI = dyn_cast<LoadInst>(GlobalUser)) {
Chris Lattner7b550cc2009-11-06 04:27:31 +0000956 Changed |= OptimizeAwayTrappingUsesOfValue(LI, LV);
Chris Lattner92c6bd22009-01-14 00:12:58 +0000957 // If we were able to delete all uses of the loads
958 if (LI->use_empty()) {
959 LI->eraseFromParent();
960 Changed = true;
961 } else {
962 AllNonStoreUsesGone = false;
963 }
964 } else if (isa<StoreInst>(GlobalUser)) {
965 // Ignore the store that stores "LV" to the global.
966 assert(GlobalUser->getOperand(1) == GV &&
967 "Must be storing *to* the global");
Chris Lattner708148e2004-10-10 23:14:11 +0000968 } else {
Chris Lattner92c6bd22009-01-14 00:12:58 +0000969 AllNonStoreUsesGone = false;
970
971 // If we get here we could have other crazy uses that are transitively
972 // loaded.
973 assert((isa<PHINode>(GlobalUser) || isa<SelectInst>(GlobalUser) ||
Benjamin Kramerab164232012-09-28 10:01:27 +0000974 isa<ConstantExpr>(GlobalUser) || isa<CmpInst>(GlobalUser) ||
975 isa<BitCastInst>(GlobalUser) ||
976 isa<GetElementPtrInst>(GlobalUser)) &&
Chris Lattner98a42b22011-05-22 07:15:13 +0000977 "Only expect load and stores!");
Chris Lattner708148e2004-10-10 23:14:11 +0000978 }
Chris Lattner92c6bd22009-01-14 00:12:58 +0000979 }
Chris Lattner708148e2004-10-10 23:14:11 +0000980
981 if (Changed) {
David Greene3215b0e2010-01-05 01:28:05 +0000982 DEBUG(dbgs() << "OPTIMIZED LOADS FROM STORED ONCE POINTER: " << *GV);
Chris Lattner708148e2004-10-10 23:14:11 +0000983 ++NumGlobUses;
984 }
985
Chris Lattner708148e2004-10-10 23:14:11 +0000986 // If we nuked all of the loads, then none of the stores are needed either,
987 // nor is the global.
Chris Lattner92c6bd22009-01-14 00:12:58 +0000988 if (AllNonStoreUsesGone) {
Nick Lewycky8899d5c2012-07-24 07:21:08 +0000989 if (isLeakCheckerRoot(GV)) {
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000990 Changed |= CleanupPointerRootUsers(GV, TLI);
Nick Lewycky8899d5c2012-07-24 07:21:08 +0000991 } else {
992 Changed = true;
993 CleanupConstantGlobalUsers(GV, 0, TD, TLI);
994 }
Chris Lattner708148e2004-10-10 23:14:11 +0000995 if (GV->use_empty()) {
Nick Lewycky8899d5c2012-07-24 07:21:08 +0000996 DEBUG(dbgs() << " *** GLOBAL NOW DEAD!\n");
997 Changed = true;
Chris Lattner7a7ed022004-10-16 18:09:00 +0000998 GV->eraseFromParent();
Chris Lattner708148e2004-10-10 23:14:11 +0000999 ++NumDeleted;
1000 }
Chris Lattner708148e2004-10-10 23:14:11 +00001001 }
1002 return Changed;
1003}
1004
Chris Lattner30ba5692004-10-11 05:54:41 +00001005/// ConstantPropUsersOf - Walk the use list of V, constant folding all of the
1006/// instructions that are foldable.
Nick Lewycky6a577f82012-02-12 01:13:18 +00001007static void ConstantPropUsersOf(Value *V,
Micah Villmow3574eca2012-10-08 16:38:25 +00001008 DataLayout *TD, TargetLibraryInfo *TLI) {
Chris Lattner30ba5692004-10-11 05:54:41 +00001009 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; )
1010 if (Instruction *I = dyn_cast<Instruction>(*UI++))
Nick Lewycky6a577f82012-02-12 01:13:18 +00001011 if (Constant *NewC = ConstantFoldInstruction(I, TD, TLI)) {
Chris Lattner30ba5692004-10-11 05:54:41 +00001012 I->replaceAllUsesWith(NewC);
1013
Chris Lattnerd514d822005-02-01 01:23:31 +00001014 // Advance UI to the next non-I use to avoid invalidating it!
1015 // Instructions could multiply use V.
1016 while (UI != E && *UI == I)
Chris Lattner30ba5692004-10-11 05:54:41 +00001017 ++UI;
Chris Lattnerd514d822005-02-01 01:23:31 +00001018 I->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +00001019 }
1020}
1021
1022/// OptimizeGlobalAddressOfMalloc - This function takes the specified global
1023/// variable, and transforms the program as if it always contained the result of
1024/// the specified malloc. Because it is always the result of the specified
1025/// malloc, there is no reason to actually DO the malloc. Instead, turn the
Chris Lattner6e8fbad2006-11-30 17:32:29 +00001026/// malloc into a global, and any loads of GV as uses of the new global.
Chris Lattner30ba5692004-10-11 05:54:41 +00001027static GlobalVariable *OptimizeGlobalAddressOfMalloc(GlobalVariable *GV,
Victor Hernandez83d63912009-09-18 22:35:49 +00001028 CallInst *CI,
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001029 Type *AllocTy,
Chris Lattnera6874652010-02-25 22:33:52 +00001030 ConstantInt *NElements,
Micah Villmow3574eca2012-10-08 16:38:25 +00001031 DataLayout *TD,
Nick Lewycky6a577f82012-02-12 01:13:18 +00001032 TargetLibraryInfo *TLI) {
Chris Lattnera6874652010-02-25 22:33:52 +00001033 DEBUG(errs() << "PROMOTING GLOBAL: " << *GV << " CALL = " << *CI << '\n');
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001034
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001035 Type *GlobalType;
Chris Lattnera6874652010-02-25 22:33:52 +00001036 if (NElements->getZExtValue() == 1)
1037 GlobalType = AllocTy;
1038 else
1039 // If we have an array allocation, the global variable is of an array.
1040 GlobalType = ArrayType::get(AllocTy, NElements->getZExtValue());
Victor Hernandez83d63912009-09-18 22:35:49 +00001041
1042 // Create the new global variable. The contents of the malloc'd memory is
1043 // undefined, so initialize with an undef value.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001044 GlobalVariable *NewGV = new GlobalVariable(*GV->getParent(),
Chris Lattnere9fd4442010-02-26 23:42:13 +00001045 GlobalType, false,
Chris Lattnera6874652010-02-25 22:33:52 +00001046 GlobalValue::InternalLinkage,
Chris Lattnere9fd4442010-02-26 23:42:13 +00001047 UndefValue::get(GlobalType),
Victor Hernandez83d63912009-09-18 22:35:49 +00001048 GV->getName()+".body",
1049 GV,
Hans Wennborgce718ff2012-06-23 11:37:03 +00001050 GV->getThreadLocalMode());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001051
Chris Lattnera6874652010-02-25 22:33:52 +00001052 // If there are bitcast users of the malloc (which is typical, usually we have
1053 // a malloc + bitcast) then replace them with uses of the new global. Update
1054 // other users to use the global as well.
1055 BitCastInst *TheBC = 0;
1056 while (!CI->use_empty()) {
1057 Instruction *User = cast<Instruction>(CI->use_back());
1058 if (BitCastInst *BCI = dyn_cast<BitCastInst>(User)) {
1059 if (BCI->getType() == NewGV->getType()) {
1060 BCI->replaceAllUsesWith(NewGV);
1061 BCI->eraseFromParent();
1062 } else {
1063 BCI->setOperand(0, NewGV);
1064 }
1065 } else {
1066 if (TheBC == 0)
1067 TheBC = new BitCastInst(NewGV, CI->getType(), "newgv", CI);
1068 User->replaceUsesOfWith(CI, TheBC);
1069 }
1070 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001071
Victor Hernandez83d63912009-09-18 22:35:49 +00001072 Constant *RepValue = NewGV;
1073 if (NewGV->getType() != GV->getType()->getElementType())
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001074 RepValue = ConstantExpr::getBitCast(RepValue,
Victor Hernandez83d63912009-09-18 22:35:49 +00001075 GV->getType()->getElementType());
1076
1077 // If there is a comparison against null, we will insert a global bool to
1078 // keep track of whether the global was initialized yet or not.
1079 GlobalVariable *InitBool =
Chris Lattner7b550cc2009-11-06 04:27:31 +00001080 new GlobalVariable(Type::getInt1Ty(GV->getContext()), false,
Victor Hernandez83d63912009-09-18 22:35:49 +00001081 GlobalValue::InternalLinkage,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001082 ConstantInt::getFalse(GV->getContext()),
Hans Wennborgce718ff2012-06-23 11:37:03 +00001083 GV->getName()+".init", GV->getThreadLocalMode());
Victor Hernandez83d63912009-09-18 22:35:49 +00001084 bool InitBoolUsed = false;
1085
1086 // Loop over all uses of GV, processing them in turn.
Chris Lattnera6874652010-02-25 22:33:52 +00001087 while (!GV->use_empty()) {
1088 if (StoreInst *SI = dyn_cast<StoreInst>(GV->use_back())) {
Victor Hernandez83d63912009-09-18 22:35:49 +00001089 // The global is initialized when the store to it occurs.
Nick Lewyckyfad4d402012-02-05 19:56:38 +00001090 new StoreInst(ConstantInt::getTrue(GV->getContext()), InitBool, false, 0,
1091 SI->getOrdering(), SI->getSynchScope(), SI);
Victor Hernandez83d63912009-09-18 22:35:49 +00001092 SI->eraseFromParent();
Chris Lattnera6874652010-02-25 22:33:52 +00001093 continue;
Victor Hernandez83d63912009-09-18 22:35:49 +00001094 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001095
Chris Lattnera6874652010-02-25 22:33:52 +00001096 LoadInst *LI = cast<LoadInst>(GV->use_back());
1097 while (!LI->use_empty()) {
1098 Use &LoadUse = LI->use_begin().getUse();
1099 if (!isa<ICmpInst>(LoadUse.getUser())) {
1100 LoadUse = RepValue;
1101 continue;
1102 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001103
Chris Lattnera6874652010-02-25 22:33:52 +00001104 ICmpInst *ICI = cast<ICmpInst>(LoadUse.getUser());
1105 // Replace the cmp X, 0 with a use of the bool value.
Nick Lewyckyfad4d402012-02-05 19:56:38 +00001106 // Sink the load to where the compare was, if atomic rules allow us to.
1107 Value *LV = new LoadInst(InitBool, InitBool->getName()+".val", false, 0,
1108 LI->getOrdering(), LI->getSynchScope(),
1109 LI->isUnordered() ? (Instruction*)ICI : LI);
Chris Lattnera6874652010-02-25 22:33:52 +00001110 InitBoolUsed = true;
1111 switch (ICI->getPredicate()) {
1112 default: llvm_unreachable("Unknown ICmp Predicate!");
1113 case ICmpInst::ICMP_ULT:
1114 case ICmpInst::ICMP_SLT: // X < null -> always false
1115 LV = ConstantInt::getFalse(GV->getContext());
1116 break;
1117 case ICmpInst::ICMP_ULE:
1118 case ICmpInst::ICMP_SLE:
1119 case ICmpInst::ICMP_EQ:
1120 LV = BinaryOperator::CreateNot(LV, "notinit", ICI);
1121 break;
1122 case ICmpInst::ICMP_NE:
1123 case ICmpInst::ICMP_UGE:
1124 case ICmpInst::ICMP_SGE:
1125 case ICmpInst::ICMP_UGT:
1126 case ICmpInst::ICMP_SGT:
1127 break; // no change.
1128 }
1129 ICI->replaceAllUsesWith(LV);
1130 ICI->eraseFromParent();
1131 }
1132 LI->eraseFromParent();
1133 }
Victor Hernandez83d63912009-09-18 22:35:49 +00001134
1135 // If the initialization boolean was used, insert it, otherwise delete it.
1136 if (!InitBoolUsed) {
1137 while (!InitBool->use_empty()) // Delete initializations
Chris Lattnera6874652010-02-25 22:33:52 +00001138 cast<StoreInst>(InitBool->use_back())->eraseFromParent();
Victor Hernandez83d63912009-09-18 22:35:49 +00001139 delete InitBool;
1140 } else
1141 GV->getParent()->getGlobalList().insert(GV, InitBool);
1142
Chris Lattnera6874652010-02-25 22:33:52 +00001143 // Now the GV is dead, nuke it and the malloc..
Victor Hernandez83d63912009-09-18 22:35:49 +00001144 GV->eraseFromParent();
Victor Hernandez83d63912009-09-18 22:35:49 +00001145 CI->eraseFromParent();
1146
1147 // To further other optimizations, loop over all users of NewGV and try to
1148 // constant prop them. This will promote GEP instructions with constant
1149 // indices into GEP constant-exprs, which will allow global-opt to hack on it.
Nick Lewycky6a577f82012-02-12 01:13:18 +00001150 ConstantPropUsersOf(NewGV, TD, TLI);
Victor Hernandez83d63912009-09-18 22:35:49 +00001151 if (RepValue != NewGV)
Nick Lewycky6a577f82012-02-12 01:13:18 +00001152 ConstantPropUsersOf(RepValue, TD, TLI);
Victor Hernandez83d63912009-09-18 22:35:49 +00001153
1154 return NewGV;
1155}
1156
Chris Lattnerfa07e4f2004-12-02 07:11:07 +00001157/// ValueIsOnlyUsedLocallyOrStoredToOneGlobal - Scan the use-list of V checking
1158/// to make sure that there are no complex uses of V. We permit simple things
1159/// like dereferencing the pointer, but not storing through the address, unless
1160/// it is to the specified global.
Gabor Greif0b520db2010-04-06 18:58:22 +00001161static bool ValueIsOnlyUsedLocallyOrStoredToOneGlobal(const Instruction *V,
1162 const GlobalVariable *GV,
Gabor Greifa01d6db2010-04-06 19:14:05 +00001163 SmallPtrSet<const PHINode*, 8> &PHIs) {
Gabor Greif0b520db2010-04-06 18:58:22 +00001164 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end();
Gabor Greifa01d6db2010-04-06 19:14:05 +00001165 UI != E; ++UI) {
Gabor Greif0b520db2010-04-06 18:58:22 +00001166 const Instruction *Inst = cast<Instruction>(*UI);
Gabor Greifa01d6db2010-04-06 19:14:05 +00001167
Chris Lattner49b6d4a2008-12-15 21:08:54 +00001168 if (isa<LoadInst>(Inst) || isa<CmpInst>(Inst)) {
1169 continue; // Fine, ignore.
1170 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001171
Gabor Greif0b520db2010-04-06 18:58:22 +00001172 if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
Chris Lattnerfa07e4f2004-12-02 07:11:07 +00001173 if (SI->getOperand(0) == V && SI->getOperand(1) != GV)
1174 return false; // Storing the pointer itself... bad.
Chris Lattner49b6d4a2008-12-15 21:08:54 +00001175 continue; // Otherwise, storing through it, or storing into GV... fine.
1176 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001177
Chris Lattnera2fb2342010-04-10 18:19:22 +00001178 // Must index into the array and into the struct.
1179 if (isa<GetElementPtrInst>(Inst) && Inst->getNumOperands() >= 3) {
Chris Lattner49b6d4a2008-12-15 21:08:54 +00001180 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(Inst, GV, PHIs))
Chris Lattnerfa07e4f2004-12-02 07:11:07 +00001181 return false;
Chris Lattner49b6d4a2008-12-15 21:08:54 +00001182 continue;
1183 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001184
Gabor Greif0b520db2010-04-06 18:58:22 +00001185 if (const PHINode *PN = dyn_cast<PHINode>(Inst)) {
Chris Lattnerc451f9c2007-09-13 16:37:20 +00001186 // PHIs are ok if all uses are ok. Don't infinitely recurse through PHI
1187 // cycles.
1188 if (PHIs.insert(PN))
Chris Lattner5e6e4942007-09-14 03:41:21 +00001189 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(PN, GV, PHIs))
1190 return false;
Chris Lattner49b6d4a2008-12-15 21:08:54 +00001191 continue;
Chris Lattnerfa07e4f2004-12-02 07:11:07 +00001192 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001193
Gabor Greif0b520db2010-04-06 18:58:22 +00001194 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Inst)) {
Chris Lattner49b6d4a2008-12-15 21:08:54 +00001195 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(BCI, GV, PHIs))
1196 return false;
1197 continue;
1198 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001199
Chris Lattner49b6d4a2008-12-15 21:08:54 +00001200 return false;
1201 }
Chris Lattnerfa07e4f2004-12-02 07:11:07 +00001202 return true;
Chris Lattnerfa07e4f2004-12-02 07:11:07 +00001203}
1204
Chris Lattner86395032006-09-30 23:32:09 +00001205/// ReplaceUsesOfMallocWithGlobal - The Alloc pointer is stored into GV
1206/// somewhere. Transform all uses of the allocation into loads from the
1207/// global and uses of the resultant pointer. Further, delete the store into
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001208/// GV. This assumes that these value pass the
Chris Lattner86395032006-09-30 23:32:09 +00001209/// 'ValueIsOnlyUsedLocallyOrStoredToOneGlobal' predicate.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001210static void ReplaceUsesOfMallocWithGlobal(Instruction *Alloc,
Chris Lattner86395032006-09-30 23:32:09 +00001211 GlobalVariable *GV) {
1212 while (!Alloc->use_empty()) {
Chris Lattnera637a8b2007-09-13 18:00:31 +00001213 Instruction *U = cast<Instruction>(*Alloc->use_begin());
1214 Instruction *InsertPt = U;
Chris Lattner86395032006-09-30 23:32:09 +00001215 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
1216 // If this is the store of the allocation into the global, remove it.
1217 if (SI->getOperand(1) == GV) {
1218 SI->eraseFromParent();
1219 continue;
1220 }
Chris Lattnera637a8b2007-09-13 18:00:31 +00001221 } else if (PHINode *PN = dyn_cast<PHINode>(U)) {
1222 // Insert the load in the corresponding predecessor, not right before the
1223 // PHI.
Gabor Greifa36791d2009-01-23 19:40:15 +00001224 InsertPt = PN->getIncomingBlock(Alloc->use_begin())->getTerminator();
Chris Lattner101f44e2008-12-15 21:44:34 +00001225 } else if (isa<BitCastInst>(U)) {
1226 // Must be bitcast between the malloc and store to initialize the global.
1227 ReplaceUsesOfMallocWithGlobal(U, GV);
1228 U->eraseFromParent();
1229 continue;
1230 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
1231 // If this is a "GEP bitcast" and the user is a store to the global, then
1232 // just process it as a bitcast.
1233 if (GEPI->hasAllZeroIndices() && GEPI->hasOneUse())
1234 if (StoreInst *SI = dyn_cast<StoreInst>(GEPI->use_back()))
1235 if (SI->getOperand(1) == GV) {
1236 // Must be bitcast GEP between the malloc and store to initialize
1237 // the global.
1238 ReplaceUsesOfMallocWithGlobal(GEPI, GV);
1239 GEPI->eraseFromParent();
1240 continue;
1241 }
Chris Lattner86395032006-09-30 23:32:09 +00001242 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001243
Chris Lattner86395032006-09-30 23:32:09 +00001244 // Insert a load from the global, and use it instead of the malloc.
Chris Lattnera637a8b2007-09-13 18:00:31 +00001245 Value *NL = new LoadInst(GV, GV->getName()+".val", InsertPt);
Chris Lattner86395032006-09-30 23:32:09 +00001246 U->replaceUsesOfWith(Alloc, NL);
1247 }
1248}
1249
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001250/// LoadUsesSimpleEnoughForHeapSRA - Verify that all uses of V (a load, or a phi
1251/// of a load) are simple enough to perform heap SRA on. This permits GEP's
1252/// that index through the array and struct field, icmps of null, and PHIs.
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001253static bool LoadUsesSimpleEnoughForHeapSRA(const Value *V,
Gabor Greif27236912010-04-07 18:59:26 +00001254 SmallPtrSet<const PHINode*, 32> &LoadUsingPHIs,
1255 SmallPtrSet<const PHINode*, 32> &LoadUsingPHIsPerLoad) {
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001256 // We permit two users of the load: setcc comparing against the null
1257 // pointer, and a getelementptr of a specific form.
Gabor Greif27236912010-04-07 18:59:26 +00001258 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;
1259 ++UI) {
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001260 const Instruction *User = cast<Instruction>(*UI);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001261
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001262 // Comparison against null is ok.
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001263 if (const ICmpInst *ICI = dyn_cast<ICmpInst>(User)) {
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001264 if (!isa<ConstantPointerNull>(ICI->getOperand(1)))
1265 return false;
1266 continue;
1267 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001268
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001269 // getelementptr is also ok, but only a simple form.
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001270 if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001271 // Must index into the array and into the struct.
1272 if (GEPI->getNumOperands() < 3)
1273 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001274
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001275 // Otherwise the GEP is ok.
1276 continue;
1277 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001278
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001279 if (const PHINode *PN = dyn_cast<PHINode>(User)) {
Evan Cheng5d163962009-06-02 00:56:07 +00001280 if (!LoadUsingPHIsPerLoad.insert(PN))
1281 // This means some phi nodes are dependent on each other.
1282 // Avoid infinite looping!
1283 return false;
1284 if (!LoadUsingPHIs.insert(PN))
1285 // If we have already analyzed this PHI, then it is safe.
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001286 continue;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001287
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001288 // Make sure all uses of the PHI are simple enough to transform.
Evan Cheng5d163962009-06-02 00:56:07 +00001289 if (!LoadUsesSimpleEnoughForHeapSRA(PN,
1290 LoadUsingPHIs, LoadUsingPHIsPerLoad))
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001291 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001292
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001293 continue;
Chris Lattner86395032006-09-30 23:32:09 +00001294 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001295
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001296 // Otherwise we don't know what this is, not ok.
1297 return false;
1298 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001299
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001300 return true;
1301}
1302
1303
1304/// AllGlobalLoadUsesSimpleEnoughForHeapSRA - If all users of values loaded from
1305/// GV are simple enough to perform HeapSRA, return true.
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001306static bool AllGlobalLoadUsesSimpleEnoughForHeapSRA(const GlobalVariable *GV,
Victor Hernandez83d63912009-09-18 22:35:49 +00001307 Instruction *StoredVal) {
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001308 SmallPtrSet<const PHINode*, 32> LoadUsingPHIs;
1309 SmallPtrSet<const PHINode*, 32> LoadUsingPHIsPerLoad;
Gabor Greif27236912010-04-07 18:59:26 +00001310 for (Value::const_use_iterator UI = GV->use_begin(), E = GV->use_end();
1311 UI != E; ++UI)
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001312 if (const LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
Evan Cheng5d163962009-06-02 00:56:07 +00001313 if (!LoadUsesSimpleEnoughForHeapSRA(LI, LoadUsingPHIs,
1314 LoadUsingPHIsPerLoad))
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001315 return false;
Evan Cheng5d163962009-06-02 00:56:07 +00001316 LoadUsingPHIsPerLoad.clear();
1317 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001318
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001319 // If we reach here, we know that all uses of the loads and transitive uses
1320 // (through PHI nodes) are simple enough to transform. However, we don't know
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001321 // that all inputs the to the PHI nodes are in the same equivalence sets.
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001322 // Check to verify that all operands of the PHIs are either PHIS that can be
1323 // transformed, loads from GV, or MI itself.
Gabor Greif27236912010-04-07 18:59:26 +00001324 for (SmallPtrSet<const PHINode*, 32>::const_iterator I = LoadUsingPHIs.begin()
1325 , E = LoadUsingPHIs.end(); I != E; ++I) {
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001326 const PHINode *PN = *I;
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001327 for (unsigned op = 0, e = PN->getNumIncomingValues(); op != e; ++op) {
1328 Value *InVal = PN->getIncomingValue(op);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001329
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001330 // PHI of the stored value itself is ok.
Victor Hernandez83d63912009-09-18 22:35:49 +00001331 if (InVal == StoredVal) continue;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001332
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001333 if (const PHINode *InPN = dyn_cast<PHINode>(InVal)) {
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001334 // One of the PHIs in our set is (optimistically) ok.
1335 if (LoadUsingPHIs.count(InPN))
1336 continue;
1337 return false;
1338 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001339
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001340 // Load from GV is ok.
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001341 if (const LoadInst *LI = dyn_cast<LoadInst>(InVal))
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001342 if (LI->getOperand(0) == GV)
1343 continue;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001344
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001345 // UNDEF? NULL?
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001346
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001347 // Anything else is rejected.
1348 return false;
1349 }
1350 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001351
Chris Lattner86395032006-09-30 23:32:09 +00001352 return true;
1353}
1354
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001355static Value *GetHeapSROAValue(Value *V, unsigned FieldNo,
1356 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001357 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001358 std::vector<Value*> &FieldVals = InsertedScalarizedValues[V];
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001359
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001360 if (FieldNo >= FieldVals.size())
1361 FieldVals.resize(FieldNo+1);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001362
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001363 // If we already have this value, just reuse the previously scalarized
1364 // version.
1365 if (Value *FieldVal = FieldVals[FieldNo])
1366 return FieldVal;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001367
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001368 // Depending on what instruction this is, we have several cases.
1369 Value *Result;
1370 if (LoadInst *LI = dyn_cast<LoadInst>(V)) {
1371 // This is a scalarized version of the load from the global. Just create
1372 // a new Load of the scalarized global.
1373 Result = new LoadInst(GetHeapSROAValue(LI->getOperand(0), FieldNo,
1374 InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001375 PHIsToRewrite),
Daniel Dunbarfe09b202009-07-30 17:37:43 +00001376 LI->getName()+".f"+Twine(FieldNo), LI);
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001377 } else if (PHINode *PN = dyn_cast<PHINode>(V)) {
1378 // PN's type is pointer to struct. Make a new PHI of pointer to struct
1379 // field.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001380 StructType *ST =
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001381 cast<StructType>(cast<PointerType>(PN->getType())->getElementType());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001382
Jay Foadd8b4fb42011-03-30 11:19:20 +00001383 PHINode *NewPN =
Owen Andersondebcb012009-07-29 22:17:13 +00001384 PHINode::Create(PointerType::getUnqual(ST->getElementType(FieldNo)),
Jay Foad3ecfc862011-03-30 11:28:46 +00001385 PN->getNumIncomingValues(),
Daniel Dunbarfe09b202009-07-30 17:37:43 +00001386 PN->getName()+".f"+Twine(FieldNo), PN);
Jay Foadd8b4fb42011-03-30 11:19:20 +00001387 Result = NewPN;
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001388 PHIsToRewrite.push_back(std::make_pair(PN, FieldNo));
1389 } else {
Torok Edwinc23197a2009-07-14 16:55:14 +00001390 llvm_unreachable("Unknown usable value");
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001391 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001392
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001393 return FieldVals[FieldNo] = Result;
Chris Lattnera637a8b2007-09-13 18:00:31 +00001394}
1395
Chris Lattner330245e2007-09-13 17:29:05 +00001396/// RewriteHeapSROALoadUser - Given a load instruction and a value derived from
1397/// the load, rewrite the derived value to use the HeapSRoA'd load.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001398static void RewriteHeapSROALoadUser(Instruction *LoadUser,
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001399 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001400 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
Chris Lattner330245e2007-09-13 17:29:05 +00001401 // If this is a comparison against null, handle it.
1402 if (ICmpInst *SCI = dyn_cast<ICmpInst>(LoadUser)) {
1403 assert(isa<ConstantPointerNull>(SCI->getOperand(1)));
1404 // If we have a setcc of the loaded pointer, we can use a setcc of any
1405 // field.
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001406 Value *NPtr = GetHeapSROAValue(SCI->getOperand(0), 0,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001407 InsertedScalarizedValues, PHIsToRewrite);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001408
Owen Anderson333c4002009-07-09 23:48:35 +00001409 Value *New = new ICmpInst(SCI, SCI->getPredicate(), NPtr,
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001410 Constant::getNullValue(NPtr->getType()),
Owen Anderson333c4002009-07-09 23:48:35 +00001411 SCI->getName());
Chris Lattner330245e2007-09-13 17:29:05 +00001412 SCI->replaceAllUsesWith(New);
1413 SCI->eraseFromParent();
1414 return;
1415 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001416
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001417 // Handle 'getelementptr Ptr, Idx, i32 FieldNo ...'
Chris Lattnera637a8b2007-09-13 18:00:31 +00001418 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(LoadUser)) {
1419 assert(GEPI->getNumOperands() >= 3 && isa<ConstantInt>(GEPI->getOperand(2))
1420 && "Unexpected GEPI!");
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001421
Chris Lattnera637a8b2007-09-13 18:00:31 +00001422 // Load the pointer for this field.
1423 unsigned FieldNo = cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue();
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001424 Value *NewPtr = GetHeapSROAValue(GEPI->getOperand(0), FieldNo,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001425 InsertedScalarizedValues, PHIsToRewrite);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001426
Chris Lattnera637a8b2007-09-13 18:00:31 +00001427 // Create the new GEP idx vector.
1428 SmallVector<Value*, 8> GEPIdx;
1429 GEPIdx.push_back(GEPI->getOperand(1));
1430 GEPIdx.append(GEPI->op_begin()+3, GEPI->op_end());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001431
Jay Foada9203102011-07-25 09:48:08 +00001432 Value *NGEPI = GetElementPtrInst::Create(NewPtr, GEPIdx,
Gabor Greif051a9502008-04-06 20:25:17 +00001433 GEPI->getName(), GEPI);
Chris Lattnera637a8b2007-09-13 18:00:31 +00001434 GEPI->replaceAllUsesWith(NGEPI);
1435 GEPI->eraseFromParent();
1436 return;
1437 }
Chris Lattner309f20f2007-09-13 21:31:36 +00001438
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001439 // Recursively transform the users of PHI nodes. This will lazily create the
1440 // PHIs that are needed for individual elements. Keep track of what PHIs we
1441 // see in InsertedScalarizedValues so that we don't get infinite loops (very
1442 // antisocial). If the PHI is already in InsertedScalarizedValues, it has
1443 // already been seen first by another load, so its uses have already been
1444 // processed.
1445 PHINode *PN = cast<PHINode>(LoadUser);
Chris Lattnerc30a38f2011-07-21 06:21:31 +00001446 if (!InsertedScalarizedValues.insert(std::make_pair(PN,
1447 std::vector<Value*>())).second)
1448 return;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001449
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001450 // If this is the first time we've seen this PHI, recursively process all
1451 // users.
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001452 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end(); UI != E; ) {
1453 Instruction *User = cast<Instruction>(*UI++);
Chris Lattner7b550cc2009-11-06 04:27:31 +00001454 RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite);
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001455 }
Chris Lattner330245e2007-09-13 17:29:05 +00001456}
1457
Chris Lattner86395032006-09-30 23:32:09 +00001458/// RewriteUsesOfLoadForHeapSRoA - We are performing Heap SRoA on a global. Ptr
1459/// is a value loaded from the global. Eliminate all uses of Ptr, making them
1460/// use FieldGlobals instead. All uses of loaded values satisfy
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001461/// AllGlobalLoadUsesSimpleEnoughForHeapSRA.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001462static void RewriteUsesOfLoadForHeapSRoA(LoadInst *Load,
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001463 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001464 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001465 for (Value::use_iterator UI = Load->use_begin(), E = Load->use_end();
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001466 UI != E; ) {
1467 Instruction *User = cast<Instruction>(*UI++);
Chris Lattner7b550cc2009-11-06 04:27:31 +00001468 RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite);
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001469 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001470
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001471 if (Load->use_empty()) {
1472 Load->eraseFromParent();
1473 InsertedScalarizedValues.erase(Load);
1474 }
Chris Lattner86395032006-09-30 23:32:09 +00001475}
1476
Victor Hernandez83d63912009-09-18 22:35:49 +00001477/// PerformHeapAllocSRoA - CI is an allocation of an array of structures. Break
1478/// it up into multiple allocations of arrays of the fields.
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001479static GlobalVariable *PerformHeapAllocSRoA(GlobalVariable *GV, CallInst *CI,
Micah Villmow3574eca2012-10-08 16:38:25 +00001480 Value *NElems, DataLayout *TD,
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +00001481 const TargetLibraryInfo *TLI) {
David Greene3215b0e2010-01-05 01:28:05 +00001482 DEBUG(dbgs() << "SROA HEAP ALLOC: " << *GV << " MALLOC = " << *CI << '\n');
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +00001483 Type *MAT = getMallocAllocatedType(CI, TLI);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001484 StructType *STy = cast<StructType>(MAT);
Victor Hernandez83d63912009-09-18 22:35:49 +00001485
1486 // There is guaranteed to be at least one use of the malloc (storing
1487 // it into GV). If there are other uses, change them to be uses of
1488 // the global to simplify later code. This also deletes the store
1489 // into GV.
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001490 ReplaceUsesOfMallocWithGlobal(CI, GV);
1491
Victor Hernandez83d63912009-09-18 22:35:49 +00001492 // Okay, at this point, there are no users of the malloc. Insert N
1493 // new mallocs at the same place as CI, and N globals.
1494 std::vector<Value*> FieldGlobals;
1495 std::vector<Value*> FieldMallocs;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001496
Victor Hernandez83d63912009-09-18 22:35:49 +00001497 for (unsigned FieldNo = 0, e = STy->getNumElements(); FieldNo != e;++FieldNo){
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001498 Type *FieldTy = STy->getElementType(FieldNo);
1499 PointerType *PFieldTy = PointerType::getUnqual(FieldTy);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001500
Victor Hernandez83d63912009-09-18 22:35:49 +00001501 GlobalVariable *NGV =
1502 new GlobalVariable(*GV->getParent(),
1503 PFieldTy, false, GlobalValue::InternalLinkage,
1504 Constant::getNullValue(PFieldTy),
1505 GV->getName() + ".f" + Twine(FieldNo), GV,
Hans Wennborgce718ff2012-06-23 11:37:03 +00001506 GV->getThreadLocalMode());
Victor Hernandez83d63912009-09-18 22:35:49 +00001507 FieldGlobals.push_back(NGV);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001508
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001509 unsigned TypeSize = TD->getTypeAllocSize(FieldTy);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001510 if (StructType *ST = dyn_cast<StructType>(FieldTy))
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001511 TypeSize = TD->getStructLayout(ST)->getSizeInBytes();
Chandler Carruthece6c6b2012-11-01 08:07:29 +00001512 Type *IntPtrTy = TD->getIntPtrType(CI->getContext());
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001513 Value *NMI = CallInst::CreateMalloc(CI, IntPtrTy, FieldTy,
1514 ConstantInt::get(IntPtrTy, TypeSize),
Chris Lattner5a30a852010-07-12 00:57:28 +00001515 NElems, 0,
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001516 CI->getName() + ".f" + Twine(FieldNo));
Chris Lattner3f5e0b82010-02-26 18:23:13 +00001517 FieldMallocs.push_back(NMI);
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001518 new StoreInst(NMI, NGV, CI);
Victor Hernandez83d63912009-09-18 22:35:49 +00001519 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001520
Victor Hernandez83d63912009-09-18 22:35:49 +00001521 // The tricky aspect of this transformation is handling the case when malloc
1522 // fails. In the original code, malloc failing would set the result pointer
1523 // of malloc to null. In this case, some mallocs could succeed and others
1524 // could fail. As such, we emit code that looks like this:
1525 // F0 = malloc(field0)
1526 // F1 = malloc(field1)
1527 // F2 = malloc(field2)
1528 // if (F0 == 0 || F1 == 0 || F2 == 0) {
1529 // if (F0) { free(F0); F0 = 0; }
1530 // if (F1) { free(F1); F1 = 0; }
1531 // if (F2) { free(F2); F2 = 0; }
1532 // }
Victor Hernandez8e345a12009-11-10 08:32:25 +00001533 // The malloc can also fail if its argument is too large.
Gabor Greif9e4f2432010-06-24 14:42:01 +00001534 Constant *ConstantZero = ConstantInt::get(CI->getArgOperand(0)->getType(), 0);
1535 Value *RunningOr = new ICmpInst(CI, ICmpInst::ICMP_SLT, CI->getArgOperand(0),
Victor Hernandez8e345a12009-11-10 08:32:25 +00001536 ConstantZero, "isneg");
Victor Hernandez83d63912009-09-18 22:35:49 +00001537 for (unsigned i = 0, e = FieldMallocs.size(); i != e; ++i) {
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001538 Value *Cond = new ICmpInst(CI, ICmpInst::ICMP_EQ, FieldMallocs[i],
1539 Constant::getNullValue(FieldMallocs[i]->getType()),
1540 "isnull");
Victor Hernandez8e345a12009-11-10 08:32:25 +00001541 RunningOr = BinaryOperator::CreateOr(RunningOr, Cond, "tmp", CI);
Victor Hernandez83d63912009-09-18 22:35:49 +00001542 }
1543
1544 // Split the basic block at the old malloc.
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001545 BasicBlock *OrigBB = CI->getParent();
1546 BasicBlock *ContBB = OrigBB->splitBasicBlock(CI, "malloc_cont");
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001547
Victor Hernandez83d63912009-09-18 22:35:49 +00001548 // Create the block to check the first condition. Put all these blocks at the
1549 // end of the function as they are unlikely to be executed.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001550 BasicBlock *NullPtrBlock = BasicBlock::Create(OrigBB->getContext(),
1551 "malloc_ret_null",
Victor Hernandez83d63912009-09-18 22:35:49 +00001552 OrigBB->getParent());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001553
Victor Hernandez83d63912009-09-18 22:35:49 +00001554 // Remove the uncond branch from OrigBB to ContBB, turning it into a cond
1555 // branch on RunningOr.
1556 OrigBB->getTerminator()->eraseFromParent();
1557 BranchInst::Create(NullPtrBlock, ContBB, RunningOr, OrigBB);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001558
Victor Hernandez83d63912009-09-18 22:35:49 +00001559 // Within the NullPtrBlock, we need to emit a comparison and branch for each
1560 // pointer, because some may be null while others are not.
1561 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
1562 Value *GVVal = new LoadInst(FieldGlobals[i], "tmp", NullPtrBlock);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001563 Value *Cmp = new ICmpInst(*NullPtrBlock, ICmpInst::ICMP_NE, GVVal,
Benjamin Kramera9390a42011-09-27 20:39:19 +00001564 Constant::getNullValue(GVVal->getType()));
Chris Lattner7b550cc2009-11-06 04:27:31 +00001565 BasicBlock *FreeBlock = BasicBlock::Create(Cmp->getContext(), "free_it",
Victor Hernandez83d63912009-09-18 22:35:49 +00001566 OrigBB->getParent());
Chris Lattner7b550cc2009-11-06 04:27:31 +00001567 BasicBlock *NextBlock = BasicBlock::Create(Cmp->getContext(), "next",
Victor Hernandez83d63912009-09-18 22:35:49 +00001568 OrigBB->getParent());
Victor Hernandez66284e02009-10-24 04:23:03 +00001569 Instruction *BI = BranchInst::Create(FreeBlock, NextBlock,
1570 Cmp, NullPtrBlock);
Victor Hernandez83d63912009-09-18 22:35:49 +00001571
1572 // Fill in FreeBlock.
Victor Hernandez66284e02009-10-24 04:23:03 +00001573 CallInst::CreateFree(GVVal, BI);
Victor Hernandez83d63912009-09-18 22:35:49 +00001574 new StoreInst(Constant::getNullValue(GVVal->getType()), FieldGlobals[i],
1575 FreeBlock);
1576 BranchInst::Create(NextBlock, FreeBlock);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001577
Victor Hernandez83d63912009-09-18 22:35:49 +00001578 NullPtrBlock = NextBlock;
1579 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001580
Victor Hernandez83d63912009-09-18 22:35:49 +00001581 BranchInst::Create(ContBB, NullPtrBlock);
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001582
1583 // CI is no longer needed, remove it.
Victor Hernandez83d63912009-09-18 22:35:49 +00001584 CI->eraseFromParent();
1585
1586 /// InsertedScalarizedLoads - As we process loads, if we can't immediately
1587 /// update all uses of the load, keep track of what scalarized loads are
1588 /// inserted for a given load.
1589 DenseMap<Value*, std::vector<Value*> > InsertedScalarizedValues;
1590 InsertedScalarizedValues[GV] = FieldGlobals;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001591
Victor Hernandez83d63912009-09-18 22:35:49 +00001592 std::vector<std::pair<PHINode*, unsigned> > PHIsToRewrite;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001593
Victor Hernandez83d63912009-09-18 22:35:49 +00001594 // Okay, the malloc site is completely handled. All of the uses of GV are now
1595 // loads, and all uses of those loads are simple. Rewrite them to use loads
1596 // of the per-field globals instead.
1597 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI != E;) {
1598 Instruction *User = cast<Instruction>(*UI++);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001599
Victor Hernandez83d63912009-09-18 22:35:49 +00001600 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Chris Lattner7b550cc2009-11-06 04:27:31 +00001601 RewriteUsesOfLoadForHeapSRoA(LI, InsertedScalarizedValues, PHIsToRewrite);
Victor Hernandez83d63912009-09-18 22:35:49 +00001602 continue;
1603 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001604
Victor Hernandez83d63912009-09-18 22:35:49 +00001605 // Must be a store of null.
1606 StoreInst *SI = cast<StoreInst>(User);
1607 assert(isa<ConstantPointerNull>(SI->getOperand(0)) &&
1608 "Unexpected heap-sra user!");
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001609
Victor Hernandez83d63912009-09-18 22:35:49 +00001610 // Insert a store of null into each global.
1611 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001612 PointerType *PT = cast<PointerType>(FieldGlobals[i]->getType());
Victor Hernandez83d63912009-09-18 22:35:49 +00001613 Constant *Null = Constant::getNullValue(PT->getElementType());
1614 new StoreInst(Null, FieldGlobals[i], SI);
1615 }
1616 // Erase the original store.
1617 SI->eraseFromParent();
1618 }
1619
1620 // While we have PHIs that are interesting to rewrite, do it.
1621 while (!PHIsToRewrite.empty()) {
1622 PHINode *PN = PHIsToRewrite.back().first;
1623 unsigned FieldNo = PHIsToRewrite.back().second;
1624 PHIsToRewrite.pop_back();
1625 PHINode *FieldPN = cast<PHINode>(InsertedScalarizedValues[PN][FieldNo]);
1626 assert(FieldPN->getNumIncomingValues() == 0 &&"Already processed this phi");
1627
1628 // Add all the incoming values. This can materialize more phis.
1629 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1630 Value *InVal = PN->getIncomingValue(i);
1631 InVal = GetHeapSROAValue(InVal, FieldNo, InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001632 PHIsToRewrite);
Victor Hernandez83d63912009-09-18 22:35:49 +00001633 FieldPN->addIncoming(InVal, PN->getIncomingBlock(i));
1634 }
1635 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001636
Victor Hernandez83d63912009-09-18 22:35:49 +00001637 // Drop all inter-phi links and any loads that made it this far.
1638 for (DenseMap<Value*, std::vector<Value*> >::iterator
1639 I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
1640 I != E; ++I) {
1641 if (PHINode *PN = dyn_cast<PHINode>(I->first))
1642 PN->dropAllReferences();
1643 else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
1644 LI->dropAllReferences();
1645 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001646
Victor Hernandez83d63912009-09-18 22:35:49 +00001647 // Delete all the phis and loads now that inter-references are dead.
1648 for (DenseMap<Value*, std::vector<Value*> >::iterator
1649 I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
1650 I != E; ++I) {
1651 if (PHINode *PN = dyn_cast<PHINode>(I->first))
1652 PN->eraseFromParent();
1653 else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
1654 LI->eraseFromParent();
1655 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001656
Victor Hernandez83d63912009-09-18 22:35:49 +00001657 // The old global is now dead, remove it.
1658 GV->eraseFromParent();
1659
1660 ++NumHeapSRA;
1661 return cast<GlobalVariable>(FieldGlobals[0]);
1662}
1663
Chris Lattnere61d0a62008-12-15 21:02:25 +00001664/// TryToOptimizeStoreOfMallocToGlobal - This function is called when we see a
1665/// pointer global variable with a single value stored it that is a malloc or
1666/// cast of malloc.
1667static bool TryToOptimizeStoreOfMallocToGlobal(GlobalVariable *GV,
Victor Hernandez83d63912009-09-18 22:35:49 +00001668 CallInst *CI,
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001669 Type *AllocTy,
Nick Lewyckyfad4d402012-02-05 19:56:38 +00001670 AtomicOrdering Ordering,
Victor Hernandez83d63912009-09-18 22:35:49 +00001671 Module::global_iterator &GVI,
Micah Villmow3574eca2012-10-08 16:38:25 +00001672 DataLayout *TD,
Nick Lewycky6a577f82012-02-12 01:13:18 +00001673 TargetLibraryInfo *TLI) {
Evan Cheng86cd4452010-04-14 20:52:55 +00001674 if (!TD)
1675 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001676
Victor Hernandez83d63912009-09-18 22:35:49 +00001677 // If this is a malloc of an abstract type, don't touch it.
1678 if (!AllocTy->isSized())
1679 return false;
1680
1681 // We can't optimize this global unless all uses of it are *known* to be
1682 // of the malloc value, not of the null initializer value (consider a use
1683 // that compares the global's value against zero to see if the malloc has
1684 // been reached). To do this, we check to see if all uses of the global
1685 // would trap if the global were null: this proves that they must all
1686 // happen after the malloc.
1687 if (!AllUsesOfLoadedValueWillTrapIfNull(GV))
1688 return false;
1689
1690 // We can't optimize this if the malloc itself is used in a complex way,
1691 // for example, being stored into multiple globals. This allows the
Nick Lewyckybc384a12012-02-05 19:48:37 +00001692 // malloc to be stored into the specified global, loaded icmp'd, and
Victor Hernandez83d63912009-09-18 22:35:49 +00001693 // GEP'd. These are all things we could transform to using the global
1694 // for.
Evan Cheng86cd4452010-04-14 20:52:55 +00001695 SmallPtrSet<const PHINode*, 8> PHIs;
1696 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(CI, GV, PHIs))
1697 return false;
Victor Hernandez83d63912009-09-18 22:35:49 +00001698
1699 // If we have a global that is only initialized with a fixed size malloc,
1700 // transform the program to use global memory instead of malloc'd memory.
1701 // This eliminates dynamic allocation, avoids an indirection accessing the
1702 // data, and exposes the resultant global to further GlobalOpt.
Victor Hernandez8db42d22009-10-16 23:12:25 +00001703 // We cannot optimize the malloc if we cannot determine malloc array size.
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +00001704 Value *NElems = getMallocArraySize(CI, TD, TLI, true);
Evan Cheng86cd4452010-04-14 20:52:55 +00001705 if (!NElems)
1706 return false;
Victor Hernandez83d63912009-09-18 22:35:49 +00001707
Evan Cheng86cd4452010-04-14 20:52:55 +00001708 if (ConstantInt *NElements = dyn_cast<ConstantInt>(NElems))
1709 // Restrict this transformation to only working on small allocations
1710 // (2048 bytes currently), as we don't want to introduce a 16M global or
1711 // something.
1712 if (NElements->getZExtValue() * TD->getTypeAllocSize(AllocTy) < 2048) {
Nick Lewycky6a577f82012-02-12 01:13:18 +00001713 GVI = OptimizeGlobalAddressOfMalloc(GV, CI, AllocTy, NElements, TD, TLI);
Evan Cheng86cd4452010-04-14 20:52:55 +00001714 return true;
Victor Hernandez83d63912009-09-18 22:35:49 +00001715 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001716
Evan Cheng86cd4452010-04-14 20:52:55 +00001717 // If the allocation is an array of structures, consider transforming this
1718 // into multiple malloc'd arrays, one for each field. This is basically
1719 // SRoA for malloc'd memory.
1720
Nick Lewyckyfad4d402012-02-05 19:56:38 +00001721 if (Ordering != NotAtomic)
1722 return false;
1723
Evan Cheng86cd4452010-04-14 20:52:55 +00001724 // If this is an allocation of a fixed size array of structs, analyze as a
1725 // variable size array. malloc [100 x struct],1 -> malloc struct, 100
Gabor Greif9e4f2432010-06-24 14:42:01 +00001726 if (NElems == ConstantInt::get(CI->getArgOperand(0)->getType(), 1))
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001727 if (ArrayType *AT = dyn_cast<ArrayType>(AllocTy))
Evan Cheng86cd4452010-04-14 20:52:55 +00001728 AllocTy = AT->getElementType();
Gabor Greif9e4f2432010-06-24 14:42:01 +00001729
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001730 StructType *AllocSTy = dyn_cast<StructType>(AllocTy);
Evan Cheng86cd4452010-04-14 20:52:55 +00001731 if (!AllocSTy)
1732 return false;
1733
1734 // This the structure has an unreasonable number of fields, leave it
1735 // alone.
1736 if (AllocSTy->getNumElements() <= 16 && AllocSTy->getNumElements() != 0 &&
1737 AllGlobalLoadUsesSimpleEnoughForHeapSRA(GV, CI)) {
1738
1739 // If this is a fixed size array, transform the Malloc to be an alloc of
1740 // structs. malloc [100 x struct],1 -> malloc struct, 100
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +00001741 if (ArrayType *AT = dyn_cast<ArrayType>(getMallocAllocatedType(CI, TLI))) {
Chandler Carruthece6c6b2012-11-01 08:07:29 +00001742 Type *IntPtrTy = TD->getIntPtrType(CI->getContext());
Evan Cheng86cd4452010-04-14 20:52:55 +00001743 unsigned TypeSize = TD->getStructLayout(AllocSTy)->getSizeInBytes();
1744 Value *AllocSize = ConstantInt::get(IntPtrTy, TypeSize);
1745 Value *NumElements = ConstantInt::get(IntPtrTy, AT->getNumElements());
1746 Instruction *Malloc = CallInst::CreateMalloc(CI, IntPtrTy, AllocSTy,
1747 AllocSize, NumElements,
Chris Lattner5a30a852010-07-12 00:57:28 +00001748 0, CI->getName());
Evan Cheng86cd4452010-04-14 20:52:55 +00001749 Instruction *Cast = new BitCastInst(Malloc, CI->getType(), "tmp", CI);
1750 CI->replaceAllUsesWith(Cast);
1751 CI->eraseFromParent();
Nuno Lopeseb7c6862012-06-22 00:25:01 +00001752 if (BitCastInst *BCI = dyn_cast<BitCastInst>(Malloc))
1753 CI = cast<CallInst>(BCI->getOperand(0));
1754 else
Nuno Lopescd88efe2012-06-22 00:29:58 +00001755 CI = cast<CallInst>(Malloc);
Evan Cheng86cd4452010-04-14 20:52:55 +00001756 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001757
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +00001758 GVI = PerformHeapAllocSRoA(GV, CI, getMallocArraySize(CI, TD, TLI, true),
1759 TD, TLI);
Evan Cheng86cd4452010-04-14 20:52:55 +00001760 return true;
Victor Hernandez83d63912009-09-18 22:35:49 +00001761 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001762
Victor Hernandez83d63912009-09-18 22:35:49 +00001763 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001764}
Victor Hernandez83d63912009-09-18 22:35:49 +00001765
Chris Lattner9b34a612004-10-09 21:48:45 +00001766// OptimizeOnceStoredGlobal - Try to optimize globals based on the knowledge
1767// that only one value (besides its initializer) is ever stored to the global.
Chris Lattner30ba5692004-10-11 05:54:41 +00001768static bool OptimizeOnceStoredGlobal(GlobalVariable *GV, Value *StoredOnceVal,
Nick Lewyckyfad4d402012-02-05 19:56:38 +00001769 AtomicOrdering Ordering,
Chris Lattner7f8897f2006-08-27 22:42:52 +00001770 Module::global_iterator &GVI,
Micah Villmow3574eca2012-10-08 16:38:25 +00001771 DataLayout *TD, TargetLibraryInfo *TLI) {
Chris Lattner344b41c2008-12-15 21:20:32 +00001772 // Ignore no-op GEPs and bitcasts.
1773 StoredOnceVal = StoredOnceVal->stripPointerCasts();
Chris Lattner9b34a612004-10-09 21:48:45 +00001774
Chris Lattner708148e2004-10-10 23:14:11 +00001775 // If we are dealing with a pointer global that is initialized to null and
1776 // only has one (non-null) value stored into it, then we can optimize any
1777 // users of the loaded value (often calls and loads) that would trap if the
1778 // value was null.
Duncan Sands1df98592010-02-16 11:11:14 +00001779 if (GV->getInitializer()->getType()->isPointerTy() &&
Chris Lattner9b34a612004-10-09 21:48:45 +00001780 GV->getInitializer()->isNullValue()) {
Chris Lattner708148e2004-10-10 23:14:11 +00001781 if (Constant *SOVC = dyn_cast<Constant>(StoredOnceVal)) {
1782 if (GV->getInitializer()->getType() != SOVC->getType())
Chris Lattner98a42b22011-05-22 07:15:13 +00001783 SOVC = ConstantExpr::getBitCast(SOVC, GV->getInitializer()->getType());
Misha Brukmanfd939082005-04-21 23:48:37 +00001784
Chris Lattner708148e2004-10-10 23:14:11 +00001785 // Optimize away any trapping uses of the loaded value.
Nick Lewycky6a577f82012-02-12 01:13:18 +00001786 if (OptimizeAwayTrappingUsesOfLoads(GV, SOVC, TD, TLI))
Chris Lattner8be80122004-10-10 17:07:12 +00001787 return true;
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +00001788 } else if (CallInst *CI = extractMallocCall(StoredOnceVal, TLI)) {
1789 Type *MallocType = getMallocAllocatedType(CI, TLI);
Nick Lewycky6a577f82012-02-12 01:13:18 +00001790 if (MallocType &&
1791 TryToOptimizeStoreOfMallocToGlobal(GV, CI, MallocType, Ordering, GVI,
1792 TD, TLI))
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001793 return true;
Chris Lattner708148e2004-10-10 23:14:11 +00001794 }
Chris Lattner9b34a612004-10-09 21:48:45 +00001795 }
Chris Lattner30ba5692004-10-11 05:54:41 +00001796
Chris Lattner9b34a612004-10-09 21:48:45 +00001797 return false;
1798}
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001799
Chris Lattner58e44f42008-01-14 01:17:44 +00001800/// TryToShrinkGlobalToBoolean - At this point, we have learned that the only
1801/// two values ever stored into GV are its initializer and OtherVal. See if we
1802/// can shrink the global into a boolean and select between the two values
1803/// whenever it is used. This exposes the values to other scalar optimizations.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001804static bool TryToShrinkGlobalToBoolean(GlobalVariable *GV, Constant *OtherVal) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001805 Type *GVElType = GV->getType()->getElementType();
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001806
Chris Lattner58e44f42008-01-14 01:17:44 +00001807 // If GVElType is already i1, it is already shrunk. If the type of the GV is
Chris Lattner6f6923f2009-03-07 23:32:02 +00001808 // an FP value, pointer or vector, don't do this optimization because a select
1809 // between them is very expensive and unlikely to lead to later
1810 // simplification. In these cases, we typically end up with "cond ? v1 : v2"
1811 // where v1 and v2 both require constant pool loads, a big loss.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001812 if (GVElType == Type::getInt1Ty(GV->getContext()) ||
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001813 GVElType->isFloatingPointTy() ||
Duncan Sands1df98592010-02-16 11:11:14 +00001814 GVElType->isPointerTy() || GVElType->isVectorTy())
Chris Lattner58e44f42008-01-14 01:17:44 +00001815 return false;
Gabor Greifaaaaa022010-07-12 14:13:15 +00001816
Chris Lattner58e44f42008-01-14 01:17:44 +00001817 // Walk the use list of the global seeing if all the uses are load or store.
1818 // If there is anything else, bail out.
Gabor Greifaaaaa022010-07-12 14:13:15 +00001819 for (Value::use_iterator I = GV->use_begin(), E = GV->use_end(); I != E; ++I){
1820 User *U = *I;
1821 if (!isa<LoadInst>(U) && !isa<StoreInst>(U))
Chris Lattner58e44f42008-01-14 01:17:44 +00001822 return false;
Gabor Greifaaaaa022010-07-12 14:13:15 +00001823 }
1824
David Greene3215b0e2010-01-05 01:28:05 +00001825 DEBUG(dbgs() << " *** SHRINKING TO BOOL: " << *GV);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001826
Chris Lattner96a86b22004-12-12 05:53:50 +00001827 // Create the new global, initializing it to false.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001828 GlobalVariable *NewGV = new GlobalVariable(Type::getInt1Ty(GV->getContext()),
1829 false,
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001830 GlobalValue::InternalLinkage,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001831 ConstantInt::getFalse(GV->getContext()),
Nick Lewycky0e670df2009-05-03 03:49:08 +00001832 GV->getName()+".b",
Hans Wennborgce718ff2012-06-23 11:37:03 +00001833 GV->getThreadLocalMode());
Chris Lattner96a86b22004-12-12 05:53:50 +00001834 GV->getParent()->getGlobalList().insert(GV, NewGV);
1835
1836 Constant *InitVal = GV->getInitializer();
Chris Lattner7b550cc2009-11-06 04:27:31 +00001837 assert(InitVal->getType() != Type::getInt1Ty(GV->getContext()) &&
Owen Anderson1d0be152009-08-13 21:58:54 +00001838 "No reason to shrink to bool!");
Chris Lattner96a86b22004-12-12 05:53:50 +00001839
1840 // If initialized to zero and storing one into the global, we can use a cast
1841 // instead of a select to synthesize the desired value.
1842 bool IsOneZero = false;
1843 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal))
Reid Spencercae57542007-03-02 00:28:52 +00001844 IsOneZero = InitVal->isNullValue() && CI->isOne();
Chris Lattner96a86b22004-12-12 05:53:50 +00001845
1846 while (!GV->use_empty()) {
Devang Patel771281f2009-03-06 01:39:36 +00001847 Instruction *UI = cast<Instruction>(GV->use_back());
1848 if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
Chris Lattner96a86b22004-12-12 05:53:50 +00001849 // Change the store into a boolean store.
1850 bool StoringOther = SI->getOperand(0) == OtherVal;
1851 // Only do this if we weren't storing a loaded value.
Chris Lattner38c25562004-12-12 19:34:41 +00001852 Value *StoreVal;
Chris Lattner96a86b22004-12-12 05:53:50 +00001853 if (StoringOther || SI->getOperand(0) == InitVal)
Chris Lattner7b550cc2009-11-06 04:27:31 +00001854 StoreVal = ConstantInt::get(Type::getInt1Ty(GV->getContext()),
1855 StoringOther);
Chris Lattner38c25562004-12-12 19:34:41 +00001856 else {
1857 // Otherwise, we are storing a previously loaded copy. To do this,
1858 // change the copy from copying the original value to just copying the
1859 // bool.
1860 Instruction *StoredVal = cast<Instruction>(SI->getOperand(0));
1861
Gabor Greif9e4f2432010-06-24 14:42:01 +00001862 // If we've already replaced the input, StoredVal will be a cast or
Chris Lattner38c25562004-12-12 19:34:41 +00001863 // select instruction. If not, it will be a load of the original
1864 // global.
1865 if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
1866 assert(LI->getOperand(0) == GV && "Not a copy!");
1867 // Insert a new load, to preserve the saved value.
Nick Lewyckyfad4d402012-02-05 19:56:38 +00001868 StoreVal = new LoadInst(NewGV, LI->getName()+".b", false, 0,
1869 LI->getOrdering(), LI->getSynchScope(), LI);
Chris Lattner38c25562004-12-12 19:34:41 +00001870 } else {
1871 assert((isa<CastInst>(StoredVal) || isa<SelectInst>(StoredVal)) &&
1872 "This is not a form that we understand!");
1873 StoreVal = StoredVal->getOperand(0);
1874 assert(isa<LoadInst>(StoreVal) && "Not a load of NewGV!");
1875 }
1876 }
Nick Lewyckyfad4d402012-02-05 19:56:38 +00001877 new StoreInst(StoreVal, NewGV, false, 0,
1878 SI->getOrdering(), SI->getSynchScope(), SI);
Devang Patel771281f2009-03-06 01:39:36 +00001879 } else {
Chris Lattner96a86b22004-12-12 05:53:50 +00001880 // Change the load into a load of bool then a select.
Devang Patel771281f2009-03-06 01:39:36 +00001881 LoadInst *LI = cast<LoadInst>(UI);
Nick Lewyckyfad4d402012-02-05 19:56:38 +00001882 LoadInst *NLI = new LoadInst(NewGV, LI->getName()+".b", false, 0,
1883 LI->getOrdering(), LI->getSynchScope(), LI);
Chris Lattner96a86b22004-12-12 05:53:50 +00001884 Value *NSI;
1885 if (IsOneZero)
Chris Lattner046800a2007-02-11 01:08:35 +00001886 NSI = new ZExtInst(NLI, LI->getType(), "", LI);
Misha Brukmanfd939082005-04-21 23:48:37 +00001887 else
Gabor Greif051a9502008-04-06 20:25:17 +00001888 NSI = SelectInst::Create(NLI, OtherVal, InitVal, "", LI);
Chris Lattner046800a2007-02-11 01:08:35 +00001889 NSI->takeName(LI);
Chris Lattner96a86b22004-12-12 05:53:50 +00001890 LI->replaceAllUsesWith(NSI);
Devang Patel771281f2009-03-06 01:39:36 +00001891 }
1892 UI->eraseFromParent();
Chris Lattner96a86b22004-12-12 05:53:50 +00001893 }
1894
1895 GV->eraseFromParent();
Chris Lattner58e44f42008-01-14 01:17:44 +00001896 return true;
Chris Lattner96a86b22004-12-12 05:53:50 +00001897}
1898
1899
Nick Lewyckydb292a62012-02-12 00:52:26 +00001900/// ProcessGlobal - Analyze the specified global variable and optimize it if
1901/// possible. If we make a change, return true.
Rafael Espindolac4440e32011-01-19 16:32:21 +00001902bool GlobalOpt::ProcessGlobal(GlobalVariable *GV,
1903 Module::global_iterator &GVI) {
Rafael Espindola03977292012-06-14 22:48:13 +00001904 if (!GV->isDiscardableIfUnused())
Rafael Espindolac4440e32011-01-19 16:32:21 +00001905 return false;
1906
1907 // Do more involved optimizations if the global is internal.
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001908 GV->removeDeadConstantUsers();
1909
1910 if (GV->use_empty()) {
David Greene3215b0e2010-01-05 01:28:05 +00001911 DEBUG(dbgs() << "GLOBAL DEAD: " << *GV);
Chris Lattner7a7ed022004-10-16 18:09:00 +00001912 GV->eraseFromParent();
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001913 ++NumDeleted;
1914 return true;
1915 }
1916
Rafael Espindola2f135d42012-06-15 18:00:24 +00001917 if (!GV->hasLocalLinkage())
1918 return false;
1919
Rafael Espindolac4440e32011-01-19 16:32:21 +00001920 SmallPtrSet<const PHINode*, 16> PHIUsers;
1921 GlobalStatus GS;
1922
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001923 if (AnalyzeGlobal(GV, GS, PHIUsers))
1924 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001925
Rafael Espindolac4440e32011-01-19 16:32:21 +00001926 if (!GS.isCompared && !GV->hasUnnamedAddr()) {
1927 GV->setUnnamedAddr(true);
1928 NumUnnamed++;
1929 }
1930
1931 if (GV->isConstant() || !GV->hasInitializer())
1932 return false;
1933
1934 return ProcessInternalGlobal(GV, GVI, PHIUsers, GS);
1935}
1936
1937/// ProcessInternalGlobal - Analyze the specified global variable and optimize
1938/// it if possible. If we make a change, return true.
1939bool GlobalOpt::ProcessInternalGlobal(GlobalVariable *GV,
1940 Module::global_iterator &GVI,
Nick Lewyckydb292a62012-02-12 00:52:26 +00001941 const SmallPtrSet<const PHINode*, 16> &PHIUsers,
Rafael Espindolac4440e32011-01-19 16:32:21 +00001942 const GlobalStatus &GS) {
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001943 // If this is a first class global and has only one accessing function
1944 // and this function is main (which we know is not recursive we can make
1945 // this global a local variable) we replace the global with a local alloca
1946 // in this function.
1947 //
1948 // NOTE: It doesn't make sense to promote non single-value types since we
1949 // are just replacing static memory to stack memory.
1950 //
1951 // If the global is in different address space, don't bring it to stack.
1952 if (!GS.HasMultipleAccessingFunctions &&
1953 GS.AccessingFunction && !GS.HasNonInstructionUser &&
1954 GV->getType()->getElementType()->isSingleValueType() &&
1955 GS.AccessingFunction->getName() == "main" &&
1956 GS.AccessingFunction->hasExternalLinkage() &&
1957 GV->getType()->getAddressSpace() == 0) {
1958 DEBUG(dbgs() << "LOCALIZING GLOBAL: " << *GV);
Nick Lewyckybc384a12012-02-05 19:48:37 +00001959 Instruction &FirstI = const_cast<Instruction&>(*GS.AccessingFunction
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001960 ->getEntryBlock().begin());
Nick Lewyckybc384a12012-02-05 19:48:37 +00001961 Type *ElemTy = GV->getType()->getElementType();
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001962 // FIXME: Pass Global's alignment when globals have alignment
Nick Lewyckybc384a12012-02-05 19:48:37 +00001963 AllocaInst *Alloca = new AllocaInst(ElemTy, NULL, GV->getName(), &FirstI);
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001964 if (!isa<UndefValue>(GV->getInitializer()))
1965 new StoreInst(GV->getInitializer(), Alloca, &FirstI);
Misha Brukmanfd939082005-04-21 23:48:37 +00001966
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001967 GV->replaceAllUsesWith(Alloca);
1968 GV->eraseFromParent();
1969 ++NumLocalized;
1970 return true;
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001971 }
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001972
1973 // If the global is never loaded (but may be stored to), it is dead.
1974 // Delete it now.
1975 if (!GS.isLoaded) {
1976 DEBUG(dbgs() << "GLOBAL NEVER LOADED: " << *GV);
1977
Nick Lewycky8899d5c2012-07-24 07:21:08 +00001978 bool Changed;
1979 if (isLeakCheckerRoot(GV)) {
1980 // Delete any constant stores to the global.
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +00001981 Changed = CleanupPointerRootUsers(GV, TLI);
Nick Lewycky8899d5c2012-07-24 07:21:08 +00001982 } else {
1983 // Delete any stores we can find to the global. We may not be able to
1984 // make it completely dead though.
1985 Changed = CleanupConstantGlobalUsers(GV, GV->getInitializer(), TD, TLI);
1986 }
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001987
1988 // If the global is dead now, delete it.
1989 if (GV->use_empty()) {
1990 GV->eraseFromParent();
1991 ++NumDeleted;
1992 Changed = true;
1993 }
1994 return Changed;
1995
1996 } else if (GS.StoredType <= GlobalStatus::isInitializerStored) {
1997 DEBUG(dbgs() << "MARKING CONSTANT: " << *GV);
1998 GV->setConstant(true);
1999
2000 // Clean up any obviously simplifiable users now.
Nick Lewycky6a577f82012-02-12 01:13:18 +00002001 CleanupConstantGlobalUsers(GV, GV->getInitializer(), TD, TLI);
Rafael Espindoladaad56a2011-01-18 04:36:06 +00002002
2003 // If the global is dead now, just nuke it.
2004 if (GV->use_empty()) {
2005 DEBUG(dbgs() << " *** Marking constant allowed us to simplify "
2006 << "all users and delete global!\n");
2007 GV->eraseFromParent();
2008 ++NumDeleted;
2009 }
2010
2011 ++NumMarked;
2012 return true;
2013 } else if (!GV->getInitializer()->getType()->isSingleValueType()) {
Micah Villmow3574eca2012-10-08 16:38:25 +00002014 if (DataLayout *TD = getAnalysisIfAvailable<DataLayout>())
Rafael Espindoladaad56a2011-01-18 04:36:06 +00002015 if (GlobalVariable *FirstNewGV = SRAGlobal(GV, *TD)) {
2016 GVI = FirstNewGV; // Don't skip the newly produced globals!
2017 return true;
2018 }
2019 } else if (GS.StoredType == GlobalStatus::isStoredOnce) {
2020 // If the initial value for the global was an undef value, and if only
2021 // one other value was stored into it, we can just change the
2022 // initializer to be the stored value, then delete all stores to the
2023 // global. This allows us to mark it constant.
2024 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
2025 if (isa<UndefValue>(GV->getInitializer())) {
2026 // Change the initial value here.
2027 GV->setInitializer(SOVConstant);
2028
2029 // Clean up any obviously simplifiable users now.
Nick Lewycky6a577f82012-02-12 01:13:18 +00002030 CleanupConstantGlobalUsers(GV, GV->getInitializer(), TD, TLI);
Rafael Espindoladaad56a2011-01-18 04:36:06 +00002031
2032 if (GV->use_empty()) {
2033 DEBUG(dbgs() << " *** Substituting initializer allowed us to "
Nick Lewycky8899d5c2012-07-24 07:21:08 +00002034 << "simplify all users and delete global!\n");
Rafael Espindoladaad56a2011-01-18 04:36:06 +00002035 GV->eraseFromParent();
2036 ++NumDeleted;
2037 } else {
2038 GVI = GV;
2039 }
2040 ++NumSubstitute;
2041 return true;
2042 }
2043
2044 // Try to optimize globals based on the knowledge that only one value
2045 // (besides its initializer) is ever stored to the global.
Nick Lewyckyfad4d402012-02-05 19:56:38 +00002046 if (OptimizeOnceStoredGlobal(GV, GS.StoredOnceValue, GS.Ordering, GVI,
Nick Lewycky6a577f82012-02-12 01:13:18 +00002047 TD, TLI))
Rafael Espindoladaad56a2011-01-18 04:36:06 +00002048 return true;
2049
2050 // Otherwise, if the global was not a boolean, we can shrink it to be a
2051 // boolean.
2052 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
2053 if (TryToShrinkGlobalToBoolean(GV, SOVConstant)) {
2054 ++NumShrunkToBool;
2055 return true;
2056 }
2057 }
2058
Chris Lattnera4be1dc2004-10-08 20:59:28 +00002059 return false;
2060}
2061
Chris Lattnerfb217ad2005-05-08 22:18:06 +00002062/// ChangeCalleesToFastCall - Walk all of the direct calls of the specified
2063/// function, changing them to FastCC.
2064static void ChangeCalleesToFastCall(Function *F) {
2065 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
Jay Foadb7454fd2012-05-12 08:30:16 +00002066 if (isa<BlockAddress>(*UI))
2067 continue;
Duncan Sands548448a2008-02-18 17:32:13 +00002068 CallSite User(cast<Instruction>(*UI));
2069 User.setCallingConv(CallingConv::Fast);
Chris Lattnerfb217ad2005-05-08 22:18:06 +00002070 }
2071}
Chris Lattnera4be1dc2004-10-08 20:59:28 +00002072
Bill Wendling5886b7b2012-10-14 06:39:53 +00002073static AttrListPtr StripNest(LLVMContext &C, const AttrListPtr &Attrs) {
Chris Lattner58d74912008-03-12 17:45:29 +00002074 for (unsigned i = 0, e = Attrs.getNumSlots(); i != e; ++i) {
Bill Wendling67658342012-10-09 07:45:08 +00002075 if (!Attrs.getSlot(i).Attrs.hasAttribute(Attributes::Nest))
Duncan Sands548448a2008-02-18 17:32:13 +00002076 continue;
2077
Duncan Sands548448a2008-02-18 17:32:13 +00002078 // There can be only one.
Bill Wendling46d5dd92012-10-16 05:23:31 +00002079 return Attrs.removeAttr(C, Attrs.getSlot(i).Index,
2080 Attributes::get(C, Attributes::Nest));
Duncan Sands3d5378f2008-02-16 20:56:04 +00002081 }
2082
2083 return Attrs;
2084}
2085
2086static void RemoveNestAttribute(Function *F) {
Bill Wendling5886b7b2012-10-14 06:39:53 +00002087 F->setAttributes(StripNest(F->getContext(), F->getAttributes()));
Duncan Sands3d5378f2008-02-16 20:56:04 +00002088 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
Jay Foadb7454fd2012-05-12 08:30:16 +00002089 if (isa<BlockAddress>(*UI))
2090 continue;
Duncan Sands548448a2008-02-18 17:32:13 +00002091 CallSite User(cast<Instruction>(*UI));
Bill Wendling5886b7b2012-10-14 06:39:53 +00002092 User.setAttributes(StripNest(F->getContext(), User.getAttributes()));
Duncan Sands3d5378f2008-02-16 20:56:04 +00002093 }
2094}
2095
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002096bool GlobalOpt::OptimizeFunctions(Module &M) {
2097 bool Changed = false;
2098 // Optimize functions.
2099 for (Module::iterator FI = M.begin(), E = M.end(); FI != E; ) {
2100 Function *F = FI++;
Duncan Sandsfc5940d2009-03-06 10:21:56 +00002101 // Functions without names cannot be referenced outside this module.
2102 if (!F->hasName() && !F->isDeclaration())
2103 F->setLinkage(GlobalValue::InternalLinkage);
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002104 F->removeDeadConstantUsers();
Eli Friedmanc6633052011-10-20 05:23:42 +00002105 if (F->isDefTriviallyDead()) {
Chris Lattnerec4c7b92009-11-01 19:03:42 +00002106 F->eraseFromParent();
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002107 Changed = true;
2108 ++NumFnDeleted;
Rafael Espindolabb46f522009-01-15 20:18:42 +00002109 } else if (F->hasLocalLinkage()) {
Duncan Sands3d5378f2008-02-16 20:56:04 +00002110 if (F->getCallingConv() == CallingConv::C && !F->isVarArg() &&
Jay Foad757068f2009-06-10 08:41:11 +00002111 !F->hasAddressTaken()) {
Duncan Sands3d5378f2008-02-16 20:56:04 +00002112 // If this function has C calling conventions, is not a varargs
2113 // function, and is only called directly, promote it to use the Fast
2114 // calling convention.
2115 F->setCallingConv(CallingConv::Fast);
2116 ChangeCalleesToFastCall(F);
2117 ++NumFastCallFns;
2118 Changed = true;
2119 }
2120
Bill Wendling7d2f2492012-10-10 07:36:45 +00002121 if (F->getAttributes().hasAttrSomewhere(Attributes::Nest) &&
Jay Foad757068f2009-06-10 08:41:11 +00002122 !F->hasAddressTaken()) {
Duncan Sands3d5378f2008-02-16 20:56:04 +00002123 // The function is not used by a trampoline intrinsic, so it is safe
2124 // to remove the 'nest' attribute.
2125 RemoveNestAttribute(F);
2126 ++NumNestRemoved;
2127 Changed = true;
2128 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002129 }
2130 }
2131 return Changed;
2132}
2133
2134bool GlobalOpt::OptimizeGlobalVars(Module &M) {
2135 bool Changed = false;
2136 for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
2137 GVI != E; ) {
2138 GlobalVariable *GV = GVI++;
Duncan Sandsfc5940d2009-03-06 10:21:56 +00002139 // Global variables without names cannot be referenced outside this module.
2140 if (!GV->hasName() && !GV->isDeclaration())
2141 GV->setLinkage(GlobalValue::InternalLinkage);
Dan Gohman01b97dd2009-11-23 16:22:21 +00002142 // Simplify the initializer.
2143 if (GV->hasInitializer())
2144 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GV->getInitializer())) {
Chad Rosieraab8e282011-12-02 01:26:24 +00002145 Constant *New = ConstantFoldConstantExpression(CE, TD, TLI);
Dan Gohman01b97dd2009-11-23 16:22:21 +00002146 if (New && New != CE)
2147 GV->setInitializer(New);
2148 }
Rafael Espindolac4440e32011-01-19 16:32:21 +00002149
2150 Changed |= ProcessGlobal(GV, GVI);
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002151 }
2152 return Changed;
2153}
2154
Nick Lewycky2c44a802011-04-08 07:30:21 +00002155/// FindGlobalCtors - Find the llvm.global_ctors list, verifying that all
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002156/// initializers have an init priority of 65535.
2157GlobalVariable *GlobalOpt::FindGlobalCtors(Module &M) {
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00002158 GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
2159 if (GV == 0) return 0;
Jakub Staszak582088c2012-12-06 21:57:16 +00002160
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00002161 // Verify that the initializer is simple enough for us to handle. We are
2162 // only allowed to optimize the initializer if it is unique.
2163 if (!GV->hasUniqueInitializer()) return 0;
Nick Lewycky5ea5c612011-04-11 22:11:20 +00002164
2165 if (isa<ConstantAggregateZero>(GV->getInitializer()))
2166 return GV;
2167 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
Eli Friedman18a2e502011-04-09 09:11:09 +00002168
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00002169 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i) {
Nick Lewycky5ea5c612011-04-11 22:11:20 +00002170 if (isa<ConstantAggregateZero>(*i))
2171 continue;
2172 ConstantStruct *CS = cast<ConstantStruct>(*i);
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00002173 if (isa<ConstantPointerNull>(CS->getOperand(1)))
2174 continue;
Chris Lattner7d8e58f2005-09-26 02:19:27 +00002175
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00002176 // Must have a function or null ptr.
2177 if (!isa<Function>(CS->getOperand(1)))
2178 return 0;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002179
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00002180 // Init priority must be standard.
Nick Lewycky2c44a802011-04-08 07:30:21 +00002181 ConstantInt *CI = cast<ConstantInt>(CS->getOperand(0));
2182 if (CI->getZExtValue() != 65535)
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00002183 return 0;
2184 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002185
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00002186 return GV;
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002187}
2188
Chris Lattnerdb973e62005-09-26 02:31:18 +00002189/// ParseGlobalCtors - Given a llvm.global_ctors list that we can understand,
2190/// return a list of the functions and null terminator as a vector.
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002191static std::vector<Function*> ParseGlobalCtors(GlobalVariable *GV) {
Nick Lewycky5ea5c612011-04-11 22:11:20 +00002192 if (GV->getInitializer()->isNullValue())
2193 return std::vector<Function*>();
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002194 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
2195 std::vector<Function*> Result;
2196 Result.reserve(CA->getNumOperands());
Gabor Greif5e463212008-05-29 01:59:18 +00002197 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i) {
2198 ConstantStruct *CS = cast<ConstantStruct>(*i);
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002199 Result.push_back(dyn_cast<Function>(CS->getOperand(1)));
2200 }
2201 return Result;
2202}
2203
Chris Lattnerdb973e62005-09-26 02:31:18 +00002204/// InstallGlobalCtors - Given a specified llvm.global_ctors list, install the
2205/// specified array, returning the new global to use.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002206static GlobalVariable *InstallGlobalCtors(GlobalVariable *GCL,
Chris Lattner7b550cc2009-11-06 04:27:31 +00002207 const std::vector<Function*> &Ctors) {
Chris Lattnerdb973e62005-09-26 02:31:18 +00002208 // If we made a change, reassemble the initializer list.
Chris Lattnerb065b062011-06-20 04:01:31 +00002209 Constant *CSVals[2];
2210 CSVals[0] = ConstantInt::get(Type::getInt32Ty(GCL->getContext()), 65535);
2211 CSVals[1] = 0;
2212
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002213 StructType *StructTy =
Chris Lattnerb065b062011-06-20 04:01:31 +00002214 cast <StructType>(
2215 cast<ArrayType>(GCL->getType()->getElementType())->getElementType());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002216
Chris Lattnerdb973e62005-09-26 02:31:18 +00002217 // Create the new init list.
2218 std::vector<Constant*> CAList;
2219 for (unsigned i = 0, e = Ctors.size(); i != e; ++i) {
Chris Lattner79c11012005-09-26 04:44:35 +00002220 if (Ctors[i]) {
Chris Lattnerdb973e62005-09-26 02:31:18 +00002221 CSVals[1] = Ctors[i];
Chris Lattner79c11012005-09-26 04:44:35 +00002222 } else {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002223 Type *FTy = FunctionType::get(Type::getVoidTy(GCL->getContext()),
Chris Lattner7b550cc2009-11-06 04:27:31 +00002224 false);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002225 PointerType *PFTy = PointerType::getUnqual(FTy);
Owen Andersona7235ea2009-07-31 20:28:14 +00002226 CSVals[1] = Constant::getNullValue(PFTy);
Chris Lattner7b550cc2009-11-06 04:27:31 +00002227 CSVals[0] = ConstantInt::get(Type::getInt32Ty(GCL->getContext()),
Nick Lewycky5ea5c612011-04-11 22:11:20 +00002228 0x7fffffff);
Chris Lattnerdb973e62005-09-26 02:31:18 +00002229 }
Chris Lattnerb065b062011-06-20 04:01:31 +00002230 CAList.push_back(ConstantStruct::get(StructTy, CSVals));
Chris Lattnerdb973e62005-09-26 02:31:18 +00002231 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002232
Chris Lattnerdb973e62005-09-26 02:31:18 +00002233 // Create the array initializer.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002234 Constant *CA = ConstantArray::get(ArrayType::get(StructTy,
Nick Lewyckyc332fba2009-09-19 20:30:26 +00002235 CAList.size()), CAList);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002236
Chris Lattnerdb973e62005-09-26 02:31:18 +00002237 // If we didn't change the number of elements, don't create a new GV.
2238 if (CA->getType() == GCL->getInitializer()->getType()) {
2239 GCL->setInitializer(CA);
2240 return GCL;
2241 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002242
Chris Lattnerdb973e62005-09-26 02:31:18 +00002243 // Create the new global and insert it next to the existing list.
Chris Lattner7b550cc2009-11-06 04:27:31 +00002244 GlobalVariable *NGV = new GlobalVariable(CA->getType(), GCL->isConstant(),
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +00002245 GCL->getLinkage(), CA, "",
Hans Wennborgce718ff2012-06-23 11:37:03 +00002246 GCL->getThreadLocalMode());
Chris Lattnerdb973e62005-09-26 02:31:18 +00002247 GCL->getParent()->getGlobalList().insert(GCL, NGV);
Chris Lattner046800a2007-02-11 01:08:35 +00002248 NGV->takeName(GCL);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002249
Chris Lattnerdb973e62005-09-26 02:31:18 +00002250 // Nuke the old list, replacing any uses with the new one.
2251 if (!GCL->use_empty()) {
2252 Constant *V = NGV;
2253 if (V->getType() != GCL->getType())
Owen Andersonbaf3c402009-07-29 18:55:55 +00002254 V = ConstantExpr::getBitCast(V, GCL->getType());
Chris Lattnerdb973e62005-09-26 02:31:18 +00002255 GCL->replaceAllUsesWith(V);
2256 }
2257 GCL->eraseFromParent();
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002258
Chris Lattnerdb973e62005-09-26 02:31:18 +00002259 if (Ctors.size())
2260 return NGV;
2261 else
2262 return 0;
2263}
Chris Lattner79c11012005-09-26 04:44:35 +00002264
2265
Jakub Staszak582088c2012-12-06 21:57:16 +00002266static inline bool
Chris Lattner1945d582010-12-07 04:33:29 +00002267isSimpleEnoughValueToCommit(Constant *C,
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002268 SmallPtrSet<Constant*, 8> &SimpleConstants,
Micah Villmow3574eca2012-10-08 16:38:25 +00002269 const DataLayout *TD);
Chris Lattner1945d582010-12-07 04:33:29 +00002270
2271
2272/// isSimpleEnoughValueToCommit - Return true if the specified constant can be
2273/// handled by the code generator. We don't want to generate something like:
2274/// void *X = &X/42;
2275/// because the code generator doesn't have a relocation that can handle that.
2276///
2277/// This function should be called if C was not found (but just got inserted)
2278/// in SimpleConstants to avoid having to rescan the same constants all the
2279/// time.
2280static bool isSimpleEnoughValueToCommitHelper(Constant *C,
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002281 SmallPtrSet<Constant*, 8> &SimpleConstants,
Micah Villmow3574eca2012-10-08 16:38:25 +00002282 const DataLayout *TD) {
Chris Lattner1945d582010-12-07 04:33:29 +00002283 // Simple integer, undef, constant aggregate zero, global addresses, etc are
2284 // all supported.
2285 if (C->getNumOperands() == 0 || isa<BlockAddress>(C) ||
2286 isa<GlobalValue>(C))
2287 return true;
Jakub Staszak582088c2012-12-06 21:57:16 +00002288
Chris Lattner1945d582010-12-07 04:33:29 +00002289 // Aggregate values are safe if all their elements are.
2290 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C) ||
2291 isa<ConstantVector>(C)) {
2292 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i) {
2293 Constant *Op = cast<Constant>(C->getOperand(i));
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002294 if (!isSimpleEnoughValueToCommit(Op, SimpleConstants, TD))
Chris Lattner1945d582010-12-07 04:33:29 +00002295 return false;
2296 }
2297 return true;
2298 }
Jakub Staszak582088c2012-12-06 21:57:16 +00002299
Chris Lattner1945d582010-12-07 04:33:29 +00002300 // We don't know exactly what relocations are allowed in constant expressions,
2301 // so we allow &global+constantoffset, which is safe and uniformly supported
2302 // across targets.
2303 ConstantExpr *CE = cast<ConstantExpr>(C);
2304 switch (CE->getOpcode()) {
2305 case Instruction::BitCast:
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002306 // Bitcast is fine if the casted value is fine.
2307 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, TD);
2308
Chris Lattner1945d582010-12-07 04:33:29 +00002309 case Instruction::IntToPtr:
2310 case Instruction::PtrToInt:
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002311 // int <=> ptr is fine if the int type is the same size as the
2312 // pointer type.
2313 if (!TD || TD->getTypeSizeInBits(CE->getType()) !=
2314 TD->getTypeSizeInBits(CE->getOperand(0)->getType()))
2315 return false;
2316 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, TD);
Jakub Staszak582088c2012-12-06 21:57:16 +00002317
Chris Lattner1945d582010-12-07 04:33:29 +00002318 // GEP is fine if it is simple + constant offset.
2319 case Instruction::GetElementPtr:
2320 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
2321 if (!isa<ConstantInt>(CE->getOperand(i)))
2322 return false;
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002323 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, TD);
Jakub Staszak582088c2012-12-06 21:57:16 +00002324
Chris Lattner1945d582010-12-07 04:33:29 +00002325 case Instruction::Add:
2326 // We allow simple+cst.
2327 if (!isa<ConstantInt>(CE->getOperand(1)))
2328 return false;
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002329 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, TD);
Chris Lattner1945d582010-12-07 04:33:29 +00002330 }
2331 return false;
2332}
2333
Jakub Staszak582088c2012-12-06 21:57:16 +00002334static inline bool
Chris Lattner1945d582010-12-07 04:33:29 +00002335isSimpleEnoughValueToCommit(Constant *C,
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002336 SmallPtrSet<Constant*, 8> &SimpleConstants,
Micah Villmow3574eca2012-10-08 16:38:25 +00002337 const DataLayout *TD) {
Chris Lattner1945d582010-12-07 04:33:29 +00002338 // If we already checked this constant, we win.
2339 if (!SimpleConstants.insert(C)) return true;
2340 // Check the constant.
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002341 return isSimpleEnoughValueToCommitHelper(C, SimpleConstants, TD);
Chris Lattner1945d582010-12-07 04:33:29 +00002342}
2343
2344
Chris Lattner79c11012005-09-26 04:44:35 +00002345/// isSimpleEnoughPointerToCommit - Return true if this constant is simple
Owen Andersoncff6b372011-01-14 22:19:20 +00002346/// enough for us to understand. In particular, if it is a cast to anything
2347/// other than from one pointer type to another pointer type, we punt.
2348/// We basically just support direct accesses to globals and GEP's of
Chris Lattner79c11012005-09-26 04:44:35 +00002349/// globals. This should be kept up to date with CommitValueTo.
Chris Lattner7b550cc2009-11-06 04:27:31 +00002350static bool isSimpleEnoughPointerToCommit(Constant *C) {
Dan Gohmance5de5b2009-09-07 22:42:05 +00002351 // Conservatively, avoid aggregate types. This is because we don't
2352 // want to worry about them partially overlapping other stores.
2353 if (!cast<PointerType>(C->getType())->getElementType()->isSingleValueType())
2354 return false;
2355
Dan Gohmanfd54a892009-09-07 22:31:26 +00002356 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
Mikhail Glushenkov99fca5d2010-10-19 16:47:23 +00002357 // Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or
Dan Gohmanfd54a892009-09-07 22:31:26 +00002358 // external globals.
Mikhail Glushenkov99fca5d2010-10-19 16:47:23 +00002359 return GV->hasUniqueInitializer();
Dan Gohmanfd54a892009-09-07 22:31:26 +00002360
Owen Andersone95a32c2011-01-14 22:31:13 +00002361 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002362 // Handle a constantexpr gep.
2363 if (CE->getOpcode() == Instruction::GetElementPtr &&
Dan Gohmanc62482d2009-09-07 22:40:13 +00002364 isa<GlobalVariable>(CE->getOperand(0)) &&
2365 cast<GEPOperator>(CE)->isInBounds()) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002366 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
Mikhail Glushenkov99fca5d2010-10-19 16:47:23 +00002367 // Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or
Dan Gohmanfd54a892009-09-07 22:31:26 +00002368 // external globals.
Mikhail Glushenkov99fca5d2010-10-19 16:47:23 +00002369 if (!GV->hasUniqueInitializer())
Dan Gohmanfd54a892009-09-07 22:31:26 +00002370 return false;
Dan Gohman80bdc962009-09-07 22:44:55 +00002371
Dan Gohman80bdc962009-09-07 22:44:55 +00002372 // The first index must be zero.
Oscar Fuentesee56c422010-08-02 06:00:15 +00002373 ConstantInt *CI = dyn_cast<ConstantInt>(*llvm::next(CE->op_begin()));
Dan Gohman80bdc962009-09-07 22:44:55 +00002374 if (!CI || !CI->isZero()) return false;
Dan Gohman80bdc962009-09-07 22:44:55 +00002375
2376 // The remaining indices must be compile-time known integers within the
Dan Gohmane6992f72009-09-10 23:37:55 +00002377 // notional bounds of the corresponding static array types.
2378 if (!CE->isGEPWithNoNotionalOverIndexing())
2379 return false;
Dan Gohman80bdc962009-09-07 22:44:55 +00002380
Dan Gohmanc6f69e92009-10-05 16:36:26 +00002381 return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
Jakub Staszak582088c2012-12-06 21:57:16 +00002382
Owen Andersoncff6b372011-01-14 22:19:20 +00002383 // A constantexpr bitcast from a pointer to another pointer is a no-op,
2384 // and we know how to evaluate it by moving the bitcast from the pointer
2385 // operand to the value operand.
2386 } else if (CE->getOpcode() == Instruction::BitCast &&
Chris Lattnerd5f656f2011-01-16 02:05:10 +00002387 isa<GlobalVariable>(CE->getOperand(0))) {
Owen Andersoncff6b372011-01-14 22:19:20 +00002388 // Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or
2389 // external globals.
Chris Lattnerd5f656f2011-01-16 02:05:10 +00002390 return cast<GlobalVariable>(CE->getOperand(0))->hasUniqueInitializer();
Chris Lattner798b4d52005-09-26 06:52:44 +00002391 }
Owen Andersone95a32c2011-01-14 22:31:13 +00002392 }
Jakub Staszak582088c2012-12-06 21:57:16 +00002393
Chris Lattner79c11012005-09-26 04:44:35 +00002394 return false;
2395}
2396
Chris Lattner798b4d52005-09-26 06:52:44 +00002397/// EvaluateStoreInto - Evaluate a piece of a constantexpr store into a global
2398/// initializer. This returns 'Init' modified to reflect 'Val' stored into it.
2399/// At this point, the GEP operands of Addr [0, OpNo) have been stepped into.
2400static Constant *EvaluateStoreInto(Constant *Init, Constant *Val,
Zhou Shengefcdb292012-12-01 10:54:28 +00002401 ConstantExpr *Addr, unsigned OpNo) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002402 // Base case of the recursion.
2403 if (OpNo == Addr->getNumOperands()) {
2404 assert(Val->getType() == Init->getType() && "Type mismatch!");
2405 return Val;
2406 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002407
Chris Lattnera78fa8c2012-01-27 03:08:05 +00002408 SmallVector<Constant*, 32> Elts;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002409 if (StructType *STy = dyn_cast<StructType>(Init->getType())) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002410 // Break up the constant into its elements.
Chris Lattnerd59ae902012-01-26 02:32:04 +00002411 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
2412 Elts.push_back(Init->getAggregateElement(i));
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002413
Chris Lattner798b4d52005-09-26 06:52:44 +00002414 // Replace the element that we are supposed to.
Reid Spencerb83eb642006-10-20 07:07:24 +00002415 ConstantInt *CU = cast<ConstantInt>(Addr->getOperand(OpNo));
2416 unsigned Idx = CU->getZExtValue();
2417 assert(Idx < STy->getNumElements() && "Struct index out of range!");
Zhou Shengefcdb292012-12-01 10:54:28 +00002418 Elts[Idx] = EvaluateStoreInto(Elts[Idx], Val, Addr, OpNo+1);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002419
Chris Lattner798b4d52005-09-26 06:52:44 +00002420 // Return the modified struct.
Chris Lattnerb065b062011-06-20 04:01:31 +00002421 return ConstantStruct::get(STy, Elts);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002422 }
Jakub Staszak582088c2012-12-06 21:57:16 +00002423
Chris Lattnerb065b062011-06-20 04:01:31 +00002424 ConstantInt *CI = cast<ConstantInt>(Addr->getOperand(OpNo));
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002425 SequentialType *InitTy = cast<SequentialType>(Init->getType());
Chris Lattnerb065b062011-06-20 04:01:31 +00002426
2427 uint64_t NumElts;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002428 if (ArrayType *ATy = dyn_cast<ArrayType>(InitTy))
Chris Lattnerb065b062011-06-20 04:01:31 +00002429 NumElts = ATy->getNumElements();
2430 else
Chris Lattnerd59ae902012-01-26 02:32:04 +00002431 NumElts = InitTy->getVectorNumElements();
Chris Lattnerb065b062011-06-20 04:01:31 +00002432
2433 // Break up the array into elements.
Chris Lattnerd59ae902012-01-26 02:32:04 +00002434 for (uint64_t i = 0, e = NumElts; i != e; ++i)
2435 Elts.push_back(Init->getAggregateElement(i));
Chris Lattnerb065b062011-06-20 04:01:31 +00002436
2437 assert(CI->getZExtValue() < NumElts);
2438 Elts[CI->getZExtValue()] =
Zhou Shengefcdb292012-12-01 10:54:28 +00002439 EvaluateStoreInto(Elts[CI->getZExtValue()], Val, Addr, OpNo+1);
Chris Lattnerb065b062011-06-20 04:01:31 +00002440
2441 if (Init->getType()->isArrayTy())
2442 return ConstantArray::get(cast<ArrayType>(InitTy), Elts);
2443 return ConstantVector::get(Elts);
Chris Lattner798b4d52005-09-26 06:52:44 +00002444}
2445
Chris Lattner79c11012005-09-26 04:44:35 +00002446/// CommitValueTo - We have decided that Addr (which satisfies the predicate
2447/// isSimpleEnoughPointerToCommit) should get Val as its value. Make it happen.
Chris Lattner7b550cc2009-11-06 04:27:31 +00002448static void CommitValueTo(Constant *Val, Constant *Addr) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002449 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Addr)) {
2450 assert(GV->hasInitializer());
2451 GV->setInitializer(Val);
2452 return;
2453 }
Chris Lattnera0e9a242010-01-07 01:16:21 +00002454
Chris Lattner798b4d52005-09-26 06:52:44 +00002455 ConstantExpr *CE = cast<ConstantExpr>(Addr);
2456 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
Zhou Shengefcdb292012-12-01 10:54:28 +00002457 GV->setInitializer(EvaluateStoreInto(GV->getInitializer(), Val, CE, 2));
Chris Lattner79c11012005-09-26 04:44:35 +00002458}
2459
Nick Lewycky7fa76772012-02-20 03:25:59 +00002460namespace {
2461
2462/// Evaluator - This class evaluates LLVM IR, producing the Constant
2463/// representing each SSA instruction. Changes to global variables are stored
2464/// in a mapping that can be iterated over after the evaluation is complete.
2465/// Once an evaluation call fails, the evaluation object should not be reused.
2466class Evaluator {
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002467public:
Micah Villmow3574eca2012-10-08 16:38:25 +00002468 Evaluator(const DataLayout *TD, const TargetLibraryInfo *TLI)
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002469 : TD(TD), TLI(TLI) {
2470 ValueStack.push_back(new DenseMap<Value*, Constant*>);
2471 }
2472
Nick Lewycky7fa76772012-02-20 03:25:59 +00002473 ~Evaluator() {
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002474 DeleteContainerPointers(ValueStack);
2475 while (!AllocaTmps.empty()) {
2476 GlobalVariable *Tmp = AllocaTmps.back();
2477 AllocaTmps.pop_back();
2478
2479 // If there are still users of the alloca, the program is doing something
2480 // silly, e.g. storing the address of the alloca somewhere and using it
2481 // later. Since this is undefined, we'll just make it be null.
2482 if (!Tmp->use_empty())
2483 Tmp->replaceAllUsesWith(Constant::getNullValue(Tmp->getType()));
2484 delete Tmp;
2485 }
2486 }
2487
2488 /// EvaluateFunction - Evaluate a call to function F, returning true if
2489 /// successful, false if we can't evaluate it. ActualArgs contains the formal
2490 /// arguments for the function.
2491 bool EvaluateFunction(Function *F, Constant *&RetVal,
2492 const SmallVectorImpl<Constant*> &ActualArgs);
2493
2494 /// EvaluateBlock - Evaluate all instructions in block BB, returning true if
2495 /// successful, false if we can't evaluate it. NewBB returns the next BB that
2496 /// control flows into, or null upon return.
2497 bool EvaluateBlock(BasicBlock::iterator CurInst, BasicBlock *&NextBB);
2498
2499 Constant *getVal(Value *V) {
2500 if (Constant *CV = dyn_cast<Constant>(V)) return CV;
2501 Constant *R = ValueStack.back()->lookup(V);
2502 assert(R && "Reference to an uncomputed value!");
2503 return R;
2504 }
2505
2506 void setVal(Value *V, Constant *C) {
2507 ValueStack.back()->operator[](V) = C;
2508 }
2509
2510 const DenseMap<Constant*, Constant*> &getMutatedMemory() const {
2511 return MutatedMemory;
2512 }
2513
2514 const SmallPtrSet<GlobalVariable*, 8> &getInvariants() const {
2515 return Invariants;
2516 }
2517
2518private:
2519 Constant *ComputeLoadResult(Constant *P);
2520
2521 /// ValueStack - As we compute SSA register values, we store their contents
2522 /// here. The back of the vector contains the current function and the stack
2523 /// contains the values in the calling frames.
2524 SmallVector<DenseMap<Value*, Constant*>*, 4> ValueStack;
2525
2526 /// CallStack - This is used to detect recursion. In pathological situations
2527 /// we could hit exponential behavior, but at least there is nothing
2528 /// unbounded.
2529 SmallVector<Function*, 4> CallStack;
2530
2531 /// MutatedMemory - For each store we execute, we update this map. Loads
2532 /// check this to get the most up-to-date value. If evaluation is successful,
2533 /// this state is committed to the process.
2534 DenseMap<Constant*, Constant*> MutatedMemory;
2535
2536 /// AllocaTmps - To 'execute' an alloca, we create a temporary global variable
2537 /// to represent its body. This vector is needed so we can delete the
2538 /// temporary globals when we are done.
2539 SmallVector<GlobalVariable*, 32> AllocaTmps;
2540
2541 /// Invariants - These global variables have been marked invariant by the
2542 /// static constructor.
2543 SmallPtrSet<GlobalVariable*, 8> Invariants;
2544
2545 /// SimpleConstants - These are constants we have checked and know to be
2546 /// simple enough to live in a static initializer of a global.
2547 SmallPtrSet<Constant*, 8> SimpleConstants;
2548
Micah Villmow3574eca2012-10-08 16:38:25 +00002549 const DataLayout *TD;
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002550 const TargetLibraryInfo *TLI;
2551};
2552
Nick Lewycky7fa76772012-02-20 03:25:59 +00002553} // anonymous namespace
2554
Chris Lattner562a0552005-09-26 05:16:34 +00002555/// ComputeLoadResult - Return the value that would be computed by a load from
2556/// P after the stores reflected by 'memory' have been performed. If we can't
2557/// decide, return null.
Nick Lewycky7fa76772012-02-20 03:25:59 +00002558Constant *Evaluator::ComputeLoadResult(Constant *P) {
Chris Lattner04de1cf2005-09-26 05:15:37 +00002559 // If this memory location has been recently stored, use the stored value: it
2560 // is the most up-to-date.
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002561 DenseMap<Constant*, Constant*>::const_iterator I = MutatedMemory.find(P);
2562 if (I != MutatedMemory.end()) return I->second;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002563
Chris Lattner04de1cf2005-09-26 05:15:37 +00002564 // Access it.
2565 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(P)) {
Dan Gohman82555732009-08-19 18:20:44 +00002566 if (GV->hasDefinitiveInitializer())
Chris Lattner04de1cf2005-09-26 05:15:37 +00002567 return GV->getInitializer();
2568 return 0;
Chris Lattner04de1cf2005-09-26 05:15:37 +00002569 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002570
Chris Lattner798b4d52005-09-26 06:52:44 +00002571 // Handle a constantexpr getelementptr.
2572 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(P))
2573 if (CE->getOpcode() == Instruction::GetElementPtr &&
2574 isa<GlobalVariable>(CE->getOperand(0))) {
2575 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
Dan Gohman82555732009-08-19 18:20:44 +00002576 if (GV->hasDefinitiveInitializer())
Dan Gohmanc6f69e92009-10-05 16:36:26 +00002577 return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
Chris Lattner798b4d52005-09-26 06:52:44 +00002578 }
2579
2580 return 0; // don't know how to evaluate.
Chris Lattner04de1cf2005-09-26 05:15:37 +00002581}
2582
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002583/// EvaluateBlock - Evaluate all instructions in block BB, returning true if
2584/// successful, false if we can't evaluate it. NewBB returns the next BB that
2585/// control flows into, or null upon return.
Nick Lewycky7fa76772012-02-20 03:25:59 +00002586bool Evaluator::EvaluateBlock(BasicBlock::iterator CurInst,
2587 BasicBlock *&NextBB) {
Chris Lattner79c11012005-09-26 04:44:35 +00002588 // This is the main evaluation loop.
2589 while (1) {
2590 Constant *InstResult = 0;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002591
Chris Lattner79c11012005-09-26 04:44:35 +00002592 if (StoreInst *SI = dyn_cast<StoreInst>(CurInst)) {
Eli Friedman33cb4452011-08-16 00:20:11 +00002593 if (!SI->isSimple()) return false; // no volatile/atomic accesses.
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002594 Constant *Ptr = getVal(SI->getOperand(1));
Nick Lewyckya641c072012-02-21 22:08:06 +00002595 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
2596 Ptr = ConstantFoldConstantExpression(CE, TD, TLI);
Chris Lattner7b550cc2009-11-06 04:27:31 +00002597 if (!isSimpleEnoughPointerToCommit(Ptr))
Chris Lattner79c11012005-09-26 04:44:35 +00002598 // If this is too complex for us to commit, reject it.
Chris Lattnercd271422005-09-27 04:45:34 +00002599 return false;
Jakub Staszak582088c2012-12-06 21:57:16 +00002600
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002601 Constant *Val = getVal(SI->getOperand(0));
Chris Lattner1945d582010-12-07 04:33:29 +00002602
2603 // If this might be too difficult for the backend to handle (e.g. the addr
2604 // of one global variable divided by another) then we can't commit it.
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002605 if (!isSimpleEnoughValueToCommit(Val, SimpleConstants, TD))
Chris Lattner1945d582010-12-07 04:33:29 +00002606 return false;
Jakub Staszak582088c2012-12-06 21:57:16 +00002607
Owen Andersoncff6b372011-01-14 22:19:20 +00002608 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
2609 if (CE->getOpcode() == Instruction::BitCast) {
2610 // If we're evaluating a store through a bitcast, then we need
2611 // to pull the bitcast off the pointer type and push it onto the
2612 // stored value.
Chris Lattnerd5f656f2011-01-16 02:05:10 +00002613 Ptr = CE->getOperand(0);
Jakub Staszak582088c2012-12-06 21:57:16 +00002614
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002615 Type *NewTy = cast<PointerType>(Ptr->getType())->getElementType();
Jakub Staszak582088c2012-12-06 21:57:16 +00002616
Owen Anderson66f708f2011-01-16 04:33:33 +00002617 // In order to push the bitcast onto the stored value, a bitcast
2618 // from NewTy to Val's type must be legal. If it's not, we can try
2619 // introspecting NewTy to find a legal conversion.
2620 while (!Val->getType()->canLosslesslyBitCastTo(NewTy)) {
2621 // If NewTy is a struct, we can convert the pointer to the struct
2622 // into a pointer to its first member.
2623 // FIXME: This could be extended to support arrays as well.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002624 if (StructType *STy = dyn_cast<StructType>(NewTy)) {
Owen Anderson66f708f2011-01-16 04:33:33 +00002625 NewTy = STy->getTypeAtIndex(0U);
2626
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002627 IntegerType *IdxTy = IntegerType::get(NewTy->getContext(), 32);
Owen Anderson66f708f2011-01-16 04:33:33 +00002628 Constant *IdxZero = ConstantInt::get(IdxTy, 0, false);
2629 Constant * const IdxList[] = {IdxZero, IdxZero};
2630
Jay Foadb4263a62011-07-22 08:52:50 +00002631 Ptr = ConstantExpr::getGetElementPtr(Ptr, IdxList);
Nick Lewyckya641c072012-02-21 22:08:06 +00002632 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
2633 Ptr = ConstantFoldConstantExpression(CE, TD, TLI);
2634
Owen Anderson66f708f2011-01-16 04:33:33 +00002635 // If we can't improve the situation by introspecting NewTy,
2636 // we have to give up.
2637 } else {
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002638 return false;
Owen Anderson66f708f2011-01-16 04:33:33 +00002639 }
Owen Andersoncff6b372011-01-14 22:19:20 +00002640 }
Jakub Staszak582088c2012-12-06 21:57:16 +00002641
Owen Anderson66f708f2011-01-16 04:33:33 +00002642 // If we found compatible types, go ahead and push the bitcast
2643 // onto the stored value.
Owen Andersoncff6b372011-01-14 22:19:20 +00002644 Val = ConstantExpr::getBitCast(Val, NewTy);
2645 }
Jakub Staszak582088c2012-12-06 21:57:16 +00002646
Chris Lattner79c11012005-09-26 04:44:35 +00002647 MutatedMemory[Ptr] = Val;
2648 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CurInst)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002649 InstResult = ConstantExpr::get(BO->getOpcode(),
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002650 getVal(BO->getOperand(0)),
2651 getVal(BO->getOperand(1)));
Reid Spencere4d87aa2006-12-23 06:05:41 +00002652 } else if (CmpInst *CI = dyn_cast<CmpInst>(CurInst)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002653 InstResult = ConstantExpr::getCompare(CI->getPredicate(),
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002654 getVal(CI->getOperand(0)),
2655 getVal(CI->getOperand(1)));
Chris Lattner79c11012005-09-26 04:44:35 +00002656 } else if (CastInst *CI = dyn_cast<CastInst>(CurInst)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002657 InstResult = ConstantExpr::getCast(CI->getOpcode(),
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002658 getVal(CI->getOperand(0)),
Chris Lattner79c11012005-09-26 04:44:35 +00002659 CI->getType());
2660 } else if (SelectInst *SI = dyn_cast<SelectInst>(CurInst)) {
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002661 InstResult = ConstantExpr::getSelect(getVal(SI->getOperand(0)),
2662 getVal(SI->getOperand(1)),
2663 getVal(SI->getOperand(2)));
Chris Lattner04de1cf2005-09-26 05:15:37 +00002664 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurInst)) {
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002665 Constant *P = getVal(GEP->getOperand(0));
Chris Lattner55eb1c42007-01-31 04:40:53 +00002666 SmallVector<Constant*, 8> GEPOps;
Gabor Greif5e463212008-05-29 01:59:18 +00002667 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end();
2668 i != e; ++i)
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002669 GEPOps.push_back(getVal(*i));
Jay Foad4b5e2072011-07-21 15:15:37 +00002670 InstResult =
2671 ConstantExpr::getGetElementPtr(P, GEPOps,
2672 cast<GEPOperator>(GEP)->isInBounds());
Chris Lattner04de1cf2005-09-26 05:15:37 +00002673 } else if (LoadInst *LI = dyn_cast<LoadInst>(CurInst)) {
Eli Friedman33cb4452011-08-16 00:20:11 +00002674 if (!LI->isSimple()) return false; // no volatile/atomic accesses.
Nick Lewyckya641c072012-02-21 22:08:06 +00002675 Constant *Ptr = getVal(LI->getOperand(0));
2676 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
2677 Ptr = ConstantFoldConstantExpression(CE, TD, TLI);
2678 InstResult = ComputeLoadResult(Ptr);
Chris Lattnercd271422005-09-27 04:45:34 +00002679 if (InstResult == 0) return false; // Could not evaluate load.
Chris Lattnera22fdb02005-09-26 17:07:09 +00002680 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(CurInst)) {
Chris Lattnercd271422005-09-27 04:45:34 +00002681 if (AI->isArrayAllocation()) return false; // Cannot handle array allocs.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002682 Type *Ty = AI->getType()->getElementType();
Chris Lattner7b550cc2009-11-06 04:27:31 +00002683 AllocaTmps.push_back(new GlobalVariable(Ty, false,
Chris Lattnera22fdb02005-09-26 17:07:09 +00002684 GlobalValue::InternalLinkage,
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002685 UndefValue::get(Ty),
Chris Lattnera22fdb02005-09-26 17:07:09 +00002686 AI->getName()));
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002687 InstResult = AllocaTmps.back();
Nick Lewycky132bd9c2012-02-12 05:09:35 +00002688 } else if (isa<CallInst>(CurInst) || isa<InvokeInst>(CurInst)) {
2689 CallSite CS(CurInst);
Devang Patel412a4462009-03-09 23:04:12 +00002690
2691 // Debug info can safely be ignored here.
Nick Lewycky132bd9c2012-02-12 05:09:35 +00002692 if (isa<DbgInfoIntrinsic>(CS.getInstruction())) {
Devang Patel412a4462009-03-09 23:04:12 +00002693 ++CurInst;
2694 continue;
2695 }
2696
Chris Lattner7cd580f2006-07-07 21:37:01 +00002697 // Cannot handle inline asm.
Nick Lewycky132bd9c2012-02-12 05:09:35 +00002698 if (isa<InlineAsm>(CS.getCalledValue())) return false;
Chris Lattner7cd580f2006-07-07 21:37:01 +00002699
Nick Lewycky81266c52012-02-17 06:59:21 +00002700 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CS.getInstruction())) {
2701 if (MemSetInst *MSI = dyn_cast<MemSetInst>(II)) {
2702 if (MSI->isVolatile()) return false;
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002703 Constant *Ptr = getVal(MSI->getDest());
2704 Constant *Val = getVal(MSI->getValue());
2705 Constant *DestVal = ComputeLoadResult(getVal(Ptr));
Nick Lewycky81266c52012-02-17 06:59:21 +00002706 if (Val->isNullValue() && DestVal && DestVal->isNullValue()) {
2707 // This memset is a no-op.
2708 ++CurInst;
2709 continue;
2710 }
2711 }
2712
2713 if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
2714 II->getIntrinsicID() == Intrinsic::lifetime_end) {
2715 ++CurInst;
2716 continue;
2717 }
2718
2719 if (II->getIntrinsicID() == Intrinsic::invariant_start) {
2720 // We don't insert an entry into Values, as it doesn't have a
2721 // meaningful return value.
2722 if (!II->use_empty())
2723 return false;
2724 ConstantInt *Size = cast<ConstantInt>(II->getArgOperand(0));
Nick Lewycky0ef05572012-02-20 23:32:26 +00002725 Value *PtrArg = getVal(II->getArgOperand(1));
2726 Value *Ptr = PtrArg->stripPointerCasts();
2727 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr)) {
2728 Type *ElemTy = cast<PointerType>(GV->getType())->getElementType();
2729 if (!Size->isAllOnesValue() &&
2730 Size->getValue().getLimitedValue() >=
2731 TD->getTypeStoreSize(ElemTy))
Nick Lewycky81266c52012-02-17 06:59:21 +00002732 Invariants.insert(GV);
2733 }
2734 // Continue even if we do nothing.
Nick Lewycky1f237b02011-05-29 18:41:56 +00002735 ++CurInst;
2736 continue;
2737 }
2738 return false;
2739 }
2740
Chris Lattnercd271422005-09-27 04:45:34 +00002741 // Resolve function pointers.
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002742 Function *Callee = dyn_cast<Function>(getVal(CS.getCalledValue()));
Nick Lewycky132bd9c2012-02-12 05:09:35 +00002743 if (!Callee || Callee->mayBeOverridden())
2744 return false; // Cannot resolve.
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002745
Duncan Sandsfa6a1cf2009-08-17 14:33:27 +00002746 SmallVector<Constant*, 8> Formals;
Nick Lewycky132bd9c2012-02-12 05:09:35 +00002747 for (User::op_iterator i = CS.arg_begin(), e = CS.arg_end(); i != e; ++i)
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002748 Formals.push_back(getVal(*i));
Duncan Sandsfa6a1cf2009-08-17 14:33:27 +00002749
Reid Spencer5cbf9852007-01-30 20:08:39 +00002750 if (Callee->isDeclaration()) {
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002751 // If this is a function we can constant fold, do it.
Chad Rosier00737bd2011-12-01 21:29:16 +00002752 if (Constant *C = ConstantFoldCall(Callee, Formals, TLI)) {
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002753 InstResult = C;
2754 } else {
2755 return false;
2756 }
2757 } else {
2758 if (Callee->getFunctionType()->isVarArg())
2759 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002760
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002761 Constant *RetVal;
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002762 // Execute the call, if successful, use the return value.
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002763 ValueStack.push_back(new DenseMap<Value*, Constant*>);
2764 if (!EvaluateFunction(Callee, RetVal, Formals))
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002765 return false;
Benjamin Kramer3bbf2b62012-02-27 12:48:24 +00002766 delete ValueStack.pop_back_val();
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002767 InstResult = RetVal;
2768 }
Reid Spencer3ed469c2006-11-02 20:25:50 +00002769 } else if (isa<TerminatorInst>(CurInst)) {
Chris Lattnercdf98be2005-09-26 04:57:38 +00002770 if (BranchInst *BI = dyn_cast<BranchInst>(CurInst)) {
2771 if (BI->isUnconditional()) {
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002772 NextBB = BI->getSuccessor(0);
Chris Lattnercdf98be2005-09-26 04:57:38 +00002773 } else {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002774 ConstantInt *Cond =
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002775 dyn_cast<ConstantInt>(getVal(BI->getCondition()));
Chris Lattner97d1fad2007-01-12 18:30:11 +00002776 if (!Cond) return false; // Cannot determine.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002777
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002778 NextBB = BI->getSuccessor(!Cond->getZExtValue());
Chris Lattnercdf98be2005-09-26 04:57:38 +00002779 }
2780 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(CurInst)) {
2781 ConstantInt *Val =
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002782 dyn_cast<ConstantInt>(getVal(SI->getCondition()));
Chris Lattnercd271422005-09-27 04:45:34 +00002783 if (!Val) return false; // Cannot determine.
Stepan Dyatkovskiyc10fa6c2012-03-08 07:06:20 +00002784 NextBB = SI->findCaseValue(Val).getCaseSuccessor();
Chris Lattnerb3d5a652009-10-29 05:51:50 +00002785 } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(CurInst)) {
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002786 Value *Val = getVal(IBI->getAddress())->stripPointerCasts();
Chris Lattnerb3d5a652009-10-29 05:51:50 +00002787 if (BlockAddress *BA = dyn_cast<BlockAddress>(Val))
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002788 NextBB = BA->getBasicBlock();
Chris Lattnercdfc9402009-11-01 01:27:45 +00002789 else
2790 return false; // Cannot determine.
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002791 } else if (isa<ReturnInst>(CurInst)) {
2792 NextBB = 0;
Chris Lattnercdf98be2005-09-26 04:57:38 +00002793 } else {
Bill Wendlingdccc03b2011-07-31 06:30:59 +00002794 // invoke, unwind, resume, unreachable.
Chris Lattnercd271422005-09-27 04:45:34 +00002795 return false; // Cannot handle this terminator.
Chris Lattnercdf98be2005-09-26 04:57:38 +00002796 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002797
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002798 // We succeeded at evaluating this block!
2799 return true;
Chris Lattner79c11012005-09-26 04:44:35 +00002800 } else {
Chris Lattner79c11012005-09-26 04:44:35 +00002801 // Did not know how to evaluate this!
Chris Lattnercd271422005-09-27 04:45:34 +00002802 return false;
Chris Lattner79c11012005-09-26 04:44:35 +00002803 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002804
Chris Lattner1945d582010-12-07 04:33:29 +00002805 if (!CurInst->use_empty()) {
2806 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(InstResult))
Chad Rosieraab8e282011-12-02 01:26:24 +00002807 InstResult = ConstantFoldConstantExpression(CE, TD, TLI);
Jakub Staszak582088c2012-12-06 21:57:16 +00002808
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002809 setVal(CurInst, InstResult);
Chris Lattner1945d582010-12-07 04:33:29 +00002810 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002811
Dan Gohmanf1ce79f2012-03-13 18:01:37 +00002812 // If we just processed an invoke, we finished evaluating the block.
2813 if (InvokeInst *II = dyn_cast<InvokeInst>(CurInst)) {
2814 NextBB = II->getNormalDest();
2815 return true;
2816 }
2817
Chris Lattner79c11012005-09-26 04:44:35 +00002818 // Advance program counter.
2819 ++CurInst;
2820 }
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002821}
2822
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002823/// EvaluateFunction - Evaluate a call to function F, returning true if
2824/// successful, false if we can't evaluate it. ActualArgs contains the formal
2825/// arguments for the function.
Nick Lewycky7fa76772012-02-20 03:25:59 +00002826bool Evaluator::EvaluateFunction(Function *F, Constant *&RetVal,
2827 const SmallVectorImpl<Constant*> &ActualArgs) {
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002828 // Check to see if this function is already executing (recursion). If so,
2829 // bail out. TODO: we might want to accept limited recursion.
2830 if (std::find(CallStack.begin(), CallStack.end(), F) != CallStack.end())
2831 return false;
2832
2833 CallStack.push_back(F);
2834
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002835 // Initialize arguments to the incoming values specified.
2836 unsigned ArgNo = 0;
2837 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); AI != E;
2838 ++AI, ++ArgNo)
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002839 setVal(AI, ActualArgs[ArgNo]);
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002840
2841 // ExecutedBlocks - We only handle non-looping, non-recursive code. As such,
2842 // we can only evaluate any one basic block at most once. This set keeps
2843 // track of what we have executed so we can detect recursive cases etc.
2844 SmallPtrSet<BasicBlock*, 32> ExecutedBlocks;
2845
2846 // CurBB - The current basic block we're evaluating.
2847 BasicBlock *CurBB = F->begin();
2848
Nick Lewycky8e4ba6b2012-02-12 00:47:24 +00002849 BasicBlock::iterator CurInst = CurBB->begin();
2850
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002851 while (1) {
Duncan Sands4b794f82012-02-23 08:23:06 +00002852 BasicBlock *NextBB = 0; // Initialized to avoid compiler warnings.
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002853 if (!EvaluateBlock(CurInst, NextBB))
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002854 return false;
2855
2856 if (NextBB == 0) {
2857 // Successfully running until there's no next block means that we found
2858 // the return. Fill it the return value and pop the call stack.
2859 ReturnInst *RI = cast<ReturnInst>(CurBB->getTerminator());
2860 if (RI->getNumOperands())
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002861 RetVal = getVal(RI->getOperand(0));
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002862 CallStack.pop_back();
2863 return true;
2864 }
2865
2866 // Okay, we succeeded in evaluating this control flow. See if we have
2867 // executed the new block before. If so, we have a looping function,
2868 // which we cannot evaluate in reasonable time.
2869 if (!ExecutedBlocks.insert(NextBB))
2870 return false; // looped!
2871
2872 // Okay, we have never been in this block before. Check to see if there
2873 // are any PHI nodes. If so, evaluate them with information about where
2874 // we came from.
2875 PHINode *PN = 0;
Nick Lewycky8e4ba6b2012-02-12 00:47:24 +00002876 for (CurInst = NextBB->begin();
2877 (PN = dyn_cast<PHINode>(CurInst)); ++CurInst)
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002878 setVal(PN, getVal(PN->getIncomingValueForBlock(CurBB)));
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002879
2880 // Advance to the next block.
2881 CurBB = NextBB;
2882 }
2883}
2884
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002885/// EvaluateStaticConstructor - Evaluate static constructors in the function, if
2886/// we can. Return true if we can, false otherwise.
Micah Villmow3574eca2012-10-08 16:38:25 +00002887static bool EvaluateStaticConstructor(Function *F, const DataLayout *TD,
Chad Rosier00737bd2011-12-01 21:29:16 +00002888 const TargetLibraryInfo *TLI) {
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002889 // Call the function.
Nick Lewycky7fa76772012-02-20 03:25:59 +00002890 Evaluator Eval(TD, TLI);
Chris Lattnercd271422005-09-27 04:45:34 +00002891 Constant *RetValDummy;
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002892 bool EvalSuccess = Eval.EvaluateFunction(F, RetValDummy,
2893 SmallVector<Constant*, 0>());
Jakub Staszak582088c2012-12-06 21:57:16 +00002894
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002895 if (EvalSuccess) {
Chris Lattnera22fdb02005-09-26 17:07:09 +00002896 // We succeeded at evaluation: commit the result.
David Greene3215b0e2010-01-05 01:28:05 +00002897 DEBUG(dbgs() << "FULLY EVALUATED GLOBAL CTOR FUNCTION '"
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002898 << F->getName() << "' to " << Eval.getMutatedMemory().size()
Daniel Dunbarce63ffb2009-07-25 00:23:56 +00002899 << " stores.\n");
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002900 for (DenseMap<Constant*, Constant*>::const_iterator I =
2901 Eval.getMutatedMemory().begin(), E = Eval.getMutatedMemory().end();
Nick Lewycky3eab3c42012-06-24 04:07:14 +00002902 I != E; ++I)
Chris Lattner7b550cc2009-11-06 04:27:31 +00002903 CommitValueTo(I->second, I->first);
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002904 for (SmallPtrSet<GlobalVariable*, 8>::const_iterator I =
2905 Eval.getInvariants().begin(), E = Eval.getInvariants().end();
2906 I != E; ++I)
Nick Lewycky81266c52012-02-17 06:59:21 +00002907 (*I)->setConstant(true);
Chris Lattnera22fdb02005-09-26 17:07:09 +00002908 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002909
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002910 return EvalSuccess;
Chris Lattner79c11012005-09-26 04:44:35 +00002911}
2912
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002913/// OptimizeGlobalCtorsList - Simplify and evaluation global ctors if possible.
2914/// Return true if anything changed.
2915bool GlobalOpt::OptimizeGlobalCtorsList(GlobalVariable *&GCL) {
2916 std::vector<Function*> Ctors = ParseGlobalCtors(GCL);
2917 bool MadeChange = false;
2918 if (Ctors.empty()) return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002919
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002920 // Loop over global ctors, optimizing them when we can.
2921 for (unsigned i = 0; i != Ctors.size(); ++i) {
2922 Function *F = Ctors[i];
2923 // Found a null terminator in the middle of the list, prune off the rest of
2924 // the list.
Chris Lattner7d8e58f2005-09-26 02:19:27 +00002925 if (F == 0) {
2926 if (i != Ctors.size()-1) {
2927 Ctors.resize(i+1);
2928 MadeChange = true;
2929 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002930 break;
2931 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002932
Chris Lattner79c11012005-09-26 04:44:35 +00002933 // We cannot simplify external ctor functions.
2934 if (F->empty()) continue;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002935
Chris Lattner79c11012005-09-26 04:44:35 +00002936 // If we can evaluate the ctor at compile time, do.
Chad Rosier00737bd2011-12-01 21:29:16 +00002937 if (EvaluateStaticConstructor(F, TD, TLI)) {
Chris Lattner79c11012005-09-26 04:44:35 +00002938 Ctors.erase(Ctors.begin()+i);
2939 MadeChange = true;
2940 --i;
2941 ++NumCtorsEvaluated;
2942 continue;
2943 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002944 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002945
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002946 if (!MadeChange) return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002947
Chris Lattner7b550cc2009-11-06 04:27:31 +00002948 GCL = InstallGlobalCtors(GCL, Ctors);
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002949 return true;
2950}
2951
Duncan Sandsfc5940d2009-03-06 10:21:56 +00002952bool GlobalOpt::OptimizeGlobalAliases(Module &M) {
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002953 bool Changed = false;
2954
Duncan Sands177d84e2009-01-07 20:01:06 +00002955 for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end();
Duncan Sands4782b302009-02-15 09:56:08 +00002956 I != E;) {
2957 Module::alias_iterator J = I++;
Duncan Sandsfc5940d2009-03-06 10:21:56 +00002958 // Aliases without names cannot be referenced outside this module.
2959 if (!J->hasName() && !J->isDeclaration())
2960 J->setLinkage(GlobalValue::InternalLinkage);
Duncan Sands4782b302009-02-15 09:56:08 +00002961 // If the aliasee may change at link time, nothing can be done - bail out.
2962 if (J->mayBeOverridden())
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002963 continue;
2964
Duncan Sands4782b302009-02-15 09:56:08 +00002965 Constant *Aliasee = J->getAliasee();
2966 GlobalValue *Target = cast<GlobalValue>(Aliasee->stripPointerCasts());
Duncan Sands95c5d0f2009-02-18 17:55:38 +00002967 Target->removeDeadConstantUsers();
Duncan Sands4782b302009-02-15 09:56:08 +00002968 bool hasOneUse = Target->hasOneUse() && Aliasee->hasOneUse();
2969
2970 // Make all users of the alias use the aliasee instead.
2971 if (!J->use_empty()) {
2972 J->replaceAllUsesWith(Aliasee);
2973 ++NumAliasesResolved;
2974 Changed = true;
2975 }
2976
Duncan Sands7a154cf2009-12-08 10:10:20 +00002977 // If the alias is externally visible, we may still be able to simplify it.
2978 if (!J->hasLocalLinkage()) {
2979 // If the aliasee has internal linkage, give it the name and linkage
2980 // of the alias, and delete the alias. This turns:
2981 // define internal ... @f(...)
2982 // @a = alias ... @f
2983 // into:
2984 // define ... @a(...)
2985 if (!Target->hasLocalLinkage())
2986 continue;
Duncan Sands4782b302009-02-15 09:56:08 +00002987
Duncan Sands7a154cf2009-12-08 10:10:20 +00002988 // Do not perform the transform if multiple aliases potentially target the
Gabor Greif27236912010-04-07 18:59:26 +00002989 // aliasee. This check also ensures that it is safe to replace the section
Duncan Sands7a154cf2009-12-08 10:10:20 +00002990 // and other attributes of the aliasee with those of the alias.
2991 if (!hasOneUse)
2992 continue;
Duncan Sands4782b302009-02-15 09:56:08 +00002993
Duncan Sands7a154cf2009-12-08 10:10:20 +00002994 // Give the aliasee the name, linkage and other attributes of the alias.
2995 Target->takeName(J);
2996 Target->setLinkage(J->getLinkage());
2997 Target->GlobalValue::copyAttributesFrom(J);
2998 }
Duncan Sands4782b302009-02-15 09:56:08 +00002999
3000 // Delete the alias.
3001 M.getAliasList().erase(J);
3002 ++NumAliasesRemoved;
3003 Changed = true;
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00003004 }
3005
3006 return Changed;
3007}
Chris Lattnerb1ab4582005-09-26 01:43:45 +00003008
Nick Lewycky6a7df9a2012-02-12 02:15:20 +00003009static Function *FindCXAAtExit(Module &M, TargetLibraryInfo *TLI) {
3010 if (!TLI->has(LibFunc::cxa_atexit))
Nick Lewycky6f160d32012-02-12 02:17:18 +00003011 return 0;
Nick Lewycky6a7df9a2012-02-12 02:15:20 +00003012
3013 Function *Fn = M.getFunction(TLI->getName(LibFunc::cxa_atexit));
Jakub Staszak582088c2012-12-06 21:57:16 +00003014
Anders Carlssona201c4c2011-03-20 17:59:11 +00003015 if (!Fn)
3016 return 0;
Nick Lewycky6a7df9a2012-02-12 02:15:20 +00003017
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003018 FunctionType *FTy = Fn->getFunctionType();
Jakub Staszak582088c2012-12-06 21:57:16 +00003019
3020 // Checking that the function has the right return type, the right number of
Anders Carlsson1f7c7ba2011-03-20 19:51:13 +00003021 // parameters and that they all have pointer types should be enough.
3022 if (!FTy->getReturnType()->isIntegerTy() ||
3023 FTy->getNumParams() != 3 ||
Anders Carlssona201c4c2011-03-20 17:59:11 +00003024 !FTy->getParamType(0)->isPointerTy() ||
3025 !FTy->getParamType(1)->isPointerTy() ||
3026 !FTy->getParamType(2)->isPointerTy())
3027 return 0;
3028
3029 return Fn;
3030}
3031
3032/// cxxDtorIsEmpty - Returns whether the given function is an empty C++
3033/// destructor and can therefore be eliminated.
3034/// Note that we assume that other optimization passes have already simplified
3035/// the code so we only look for a function with a single basic block, where
Benjamin Kramerc1322a12012-02-09 16:28:15 +00003036/// the only allowed instructions are 'ret', 'call' to an empty C++ dtor and
3037/// other side-effect free instructions.
Anders Carlsson372ec6a2011-03-20 20:16:43 +00003038static bool cxxDtorIsEmpty(const Function &Fn,
3039 SmallPtrSet<const Function *, 8> &CalledFunctions) {
Anders Carlsson1f7c7ba2011-03-20 19:51:13 +00003040 // FIXME: We could eliminate C++ destructors if they're readonly/readnone and
Nick Lewycky35ee1c92011-03-21 02:26:01 +00003041 // nounwind, but that doesn't seem worth doing.
Anders Carlsson1f7c7ba2011-03-20 19:51:13 +00003042 if (Fn.isDeclaration())
3043 return false;
Anders Carlssona201c4c2011-03-20 17:59:11 +00003044
3045 if (++Fn.begin() != Fn.end())
3046 return false;
3047
3048 const BasicBlock &EntryBlock = Fn.getEntryBlock();
3049 for (BasicBlock::const_iterator I = EntryBlock.begin(), E = EntryBlock.end();
3050 I != E; ++I) {
3051 if (const CallInst *CI = dyn_cast<CallInst>(I)) {
Anders Carlssonb12caf32011-03-21 14:54:40 +00003052 // Ignore debug intrinsics.
3053 if (isa<DbgInfoIntrinsic>(CI))
3054 continue;
3055
Anders Carlssona201c4c2011-03-20 17:59:11 +00003056 const Function *CalledFn = CI->getCalledFunction();
3057
3058 if (!CalledFn)
3059 return false;
3060
Anders Carlsson807bc2a2011-03-22 03:21:01 +00003061 SmallPtrSet<const Function *, 8> NewCalledFunctions(CalledFunctions);
3062
Anders Carlsson1f7c7ba2011-03-20 19:51:13 +00003063 // Don't treat recursive functions as empty.
Anders Carlsson807bc2a2011-03-22 03:21:01 +00003064 if (!NewCalledFunctions.insert(CalledFn))
Anders Carlsson1f7c7ba2011-03-20 19:51:13 +00003065 return false;
3066
Anders Carlsson807bc2a2011-03-22 03:21:01 +00003067 if (!cxxDtorIsEmpty(*CalledFn, NewCalledFunctions))
Anders Carlssona201c4c2011-03-20 17:59:11 +00003068 return false;
3069 } else if (isa<ReturnInst>(*I))
Benjamin Kramerd4692742012-02-09 14:26:06 +00003070 return true; // We're done.
3071 else if (I->mayHaveSideEffects())
3072 return false; // Destructor with side effects, bail.
Anders Carlssona201c4c2011-03-20 17:59:11 +00003073 }
3074
3075 return false;
3076}
3077
3078bool GlobalOpt::OptimizeEmptyGlobalCXXDtors(Function *CXAAtExitFn) {
3079 /// Itanium C++ ABI p3.3.5:
3080 ///
3081 /// After constructing a global (or local static) object, that will require
3082 /// destruction on exit, a termination function is registered as follows:
3083 ///
3084 /// extern "C" int __cxa_atexit ( void (*f)(void *), void *p, void *d );
3085 ///
3086 /// This registration, e.g. __cxa_atexit(f,p,d), is intended to cause the
3087 /// call f(p) when DSO d is unloaded, before all such termination calls
3088 /// registered before this one. It returns zero if registration is
Nick Lewycky35ee1c92011-03-21 02:26:01 +00003089 /// successful, nonzero on failure.
Anders Carlssona201c4c2011-03-20 17:59:11 +00003090
3091 // This pass will look for calls to __cxa_atexit where the function is trivial
3092 // and remove them.
3093 bool Changed = false;
3094
Jakub Staszak582088c2012-12-06 21:57:16 +00003095 for (Function::use_iterator I = CXAAtExitFn->use_begin(),
Anders Carlssona201c4c2011-03-20 17:59:11 +00003096 E = CXAAtExitFn->use_end(); I != E;) {
Anders Carlsson4f735ca2011-03-20 20:21:33 +00003097 // We're only interested in calls. Theoretically, we could handle invoke
3098 // instructions as well, but neither llvm-gcc nor clang generate invokes
3099 // to __cxa_atexit.
Anders Carlssonb12caf32011-03-21 14:54:40 +00003100 CallInst *CI = dyn_cast<CallInst>(*I++);
3101 if (!CI)
Anders Carlsson4f735ca2011-03-20 20:21:33 +00003102 continue;
3103
Jakub Staszak582088c2012-12-06 21:57:16 +00003104 Function *DtorFn =
Anders Carlssonb12caf32011-03-21 14:54:40 +00003105 dyn_cast<Function>(CI->getArgOperand(0)->stripPointerCasts());
Anders Carlssona201c4c2011-03-20 17:59:11 +00003106 if (!DtorFn)
3107 continue;
3108
Anders Carlsson372ec6a2011-03-20 20:16:43 +00003109 SmallPtrSet<const Function *, 8> CalledFunctions;
3110 if (!cxxDtorIsEmpty(*DtorFn, CalledFunctions))
Anders Carlssona201c4c2011-03-20 17:59:11 +00003111 continue;
3112
3113 // Just remove the call.
Anders Carlssonb12caf32011-03-21 14:54:40 +00003114 CI->replaceAllUsesWith(Constant::getNullValue(CI->getType()));
3115 CI->eraseFromParent();
Anders Carlsson1f7c7ba2011-03-20 19:51:13 +00003116
Anders Carlssona201c4c2011-03-20 17:59:11 +00003117 ++NumCXXDtorsRemoved;
3118
3119 Changed |= true;
3120 }
3121
3122 return Changed;
3123}
3124
Chris Lattner7a90b682004-10-07 04:16:33 +00003125bool GlobalOpt::runOnModule(Module &M) {
Chris Lattner079236d2004-02-25 21:34:36 +00003126 bool Changed = false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00003127
Micah Villmow3574eca2012-10-08 16:38:25 +00003128 TD = getAnalysisIfAvailable<DataLayout>();
Nick Lewycky6a7df9a2012-02-12 02:15:20 +00003129 TLI = &getAnalysis<TargetLibraryInfo>();
Nick Lewycky6a577f82012-02-12 01:13:18 +00003130
Chris Lattnerb1ab4582005-09-26 01:43:45 +00003131 // Try to find the llvm.globalctors list.
3132 GlobalVariable *GlobalCtors = FindGlobalCtors(M);
Chris Lattner7a90b682004-10-07 04:16:33 +00003133
Nick Lewycky6a7df9a2012-02-12 02:15:20 +00003134 Function *CXAAtExitFn = FindCXAAtExit(M, TLI);
Anders Carlssona201c4c2011-03-20 17:59:11 +00003135
Chris Lattner7a90b682004-10-07 04:16:33 +00003136 bool LocalChange = true;
3137 while (LocalChange) {
3138 LocalChange = false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00003139
Chris Lattnerb1ab4582005-09-26 01:43:45 +00003140 // Delete functions that are trivially dead, ccc -> fastcc
3141 LocalChange |= OptimizeFunctions(M);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00003142
Chris Lattnerb1ab4582005-09-26 01:43:45 +00003143 // Optimize global_ctors list.
3144 if (GlobalCtors)
3145 LocalChange |= OptimizeGlobalCtorsList(GlobalCtors);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00003146
Chris Lattnerb1ab4582005-09-26 01:43:45 +00003147 // Optimize non-address-taken globals.
3148 LocalChange |= OptimizeGlobalVars(M);
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00003149
3150 // Resolve aliases, when possible.
Duncan Sandsfc5940d2009-03-06 10:21:56 +00003151 LocalChange |= OptimizeGlobalAliases(M);
Anders Carlssona201c4c2011-03-20 17:59:11 +00003152
3153 // Try to remove trivial global destructors.
3154 if (CXAAtExitFn)
3155 LocalChange |= OptimizeEmptyGlobalCXXDtors(CXAAtExitFn);
3156
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00003157 Changed |= LocalChange;
Chris Lattner7a90b682004-10-07 04:16:33 +00003158 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00003159
Chris Lattnerb1ab4582005-09-26 01:43:45 +00003160 // TODO: Move all global ctors functions to the end of the module for code
3161 // layout.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00003162
Chris Lattner079236d2004-02-25 21:34:36 +00003163 return Changed;
3164}