blob: 6468ff3276ed82acb46e4ded35701d0b09eae4f4 [file] [log] [blame]
Chris Lattner7a90b682004-10-07 04:16:33 +00001//===- GlobalOpt.cpp - Optimize Global Variables --------------------------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
Chris Lattner079236d2004-02-25 21:34:36 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
Chris Lattner079236d2004-02-25 21:34:36 +00008//===----------------------------------------------------------------------===//
9//
Chris Lattner7a90b682004-10-07 04:16:33 +000010// This pass transforms simple global variables that never have their address
11// taken. If obviously true, it marks read/write globals as constant, deletes
12// variables only stored to, etc.
Chris Lattner079236d2004-02-25 21:34:36 +000013//
14//===----------------------------------------------------------------------===//
15
Chris Lattner7a90b682004-10-07 04:16:33 +000016#define DEBUG_TYPE "globalopt"
Chris Lattner079236d2004-02-25 21:34:36 +000017#include "llvm/Transforms/IPO.h"
Chris Lattnerfb217ad2005-05-08 22:18:06 +000018#include "llvm/CallingConv.h"
Chris Lattner079236d2004-02-25 21:34:36 +000019#include "llvm/Constants.h"
Chris Lattner7a90b682004-10-07 04:16:33 +000020#include "llvm/DerivedTypes.h"
Chris Lattner7d90a272004-02-27 18:09:25 +000021#include "llvm/Instructions.h"
Chris Lattner35c81b02005-02-27 18:58:52 +000022#include "llvm/IntrinsicInst.h"
Chris Lattner079236d2004-02-25 21:34:36 +000023#include "llvm/Module.h"
Jay Foad562b84b2011-04-11 09:35:34 +000024#include "llvm/Operator.h"
Chris Lattner079236d2004-02-25 21:34:36 +000025#include "llvm/Pass.h"
Chris Lattner79066fa2007-01-30 23:46:24 +000026#include "llvm/Analysis/ConstantFolding.h"
Victor Hernandezf006b182009-10-27 20:05:49 +000027#include "llvm/Analysis/MemoryBuiltins.h"
Micah Villmow3574eca2012-10-08 16:38:25 +000028#include "llvm/DataLayout.h"
Chad Rosier00737bd2011-12-01 21:29:16 +000029#include "llvm/Target/TargetLibraryInfo.h"
Duncan Sands548448a2008-02-18 17:32:13 +000030#include "llvm/Support/CallSite.h"
Chris Lattner79066fa2007-01-30 23:46:24 +000031#include "llvm/Support/Debug.h"
Torok Edwinc25e7582009-07-11 20:10:48 +000032#include "llvm/Support/ErrorHandling.h"
Chris Lattner941db492008-01-14 02:09:12 +000033#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner998182b2008-04-26 07:40:11 +000034#include "llvm/Support/MathExtras.h"
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000035#include "llvm/Support/raw_ostream.h"
Chris Lattner5a6bb6a2008-12-16 07:34:30 +000036#include "llvm/ADT/DenseMap.h"
Chris Lattner81686182007-09-13 16:30:19 +000037#include "llvm/ADT/SmallPtrSet.h"
Chris Lattner55eb1c42007-01-31 04:40:53 +000038#include "llvm/ADT/SmallVector.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000039#include "llvm/ADT/Statistic.h"
Chris Lattnerbce4afe2008-12-17 05:28:49 +000040#include "llvm/ADT/STLExtras.h"
Chris Lattnere47ba742004-10-06 20:57:02 +000041#include <algorithm>
Chris Lattner079236d2004-02-25 21:34:36 +000042using namespace llvm;
43
Chris Lattner86453c52006-12-19 22:09:18 +000044STATISTIC(NumMarked , "Number of globals marked constant");
Rafael Espindolac4440e32011-01-19 16:32:21 +000045STATISTIC(NumUnnamed , "Number of globals marked unnamed_addr");
Chris Lattner86453c52006-12-19 22:09:18 +000046STATISTIC(NumSRA , "Number of aggregate globals broken into scalars");
47STATISTIC(NumHeapSRA , "Number of heap objects SRA'd");
48STATISTIC(NumSubstitute,"Number of globals with initializers stored into them");
49STATISTIC(NumDeleted , "Number of globals deleted");
50STATISTIC(NumFnDeleted , "Number of functions deleted");
51STATISTIC(NumGlobUses , "Number of global uses devirtualized");
52STATISTIC(NumLocalized , "Number of globals localized");
53STATISTIC(NumShrunkToBool , "Number of global vars shrunk to booleans");
54STATISTIC(NumFastCallFns , "Number of functions converted to fastcc");
55STATISTIC(NumCtorsEvaluated, "Number of static ctors evaluated");
Duncan Sands3d5378f2008-02-16 20:56:04 +000056STATISTIC(NumNestRemoved , "Number of nest attributes removed");
Duncan Sands4782b302009-02-15 09:56:08 +000057STATISTIC(NumAliasesResolved, "Number of global aliases resolved");
58STATISTIC(NumAliasesRemoved, "Number of global aliases eliminated");
Anders Carlssona201c4c2011-03-20 17:59:11 +000059STATISTIC(NumCXXDtorsRemoved, "Number of global C++ destructors removed");
Chris Lattner079236d2004-02-25 21:34:36 +000060
Chris Lattner86453c52006-12-19 22:09:18 +000061namespace {
Rafael Espindolac4440e32011-01-19 16:32:21 +000062 struct GlobalStatus;
Nick Lewycky6726b6d2009-10-25 06:33:48 +000063 struct GlobalOpt : public ModulePass {
Chris Lattner30ba5692004-10-11 05:54:41 +000064 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chad Rosier00737bd2011-12-01 21:29:16 +000065 AU.addRequired<TargetLibraryInfo>();
Chris Lattner30ba5692004-10-11 05:54:41 +000066 }
Nick Lewyckyecd94c82007-05-06 13:37:16 +000067 static char ID; // Pass identification, replacement for typeid
Owen Anderson081c34b2010-10-19 17:21:58 +000068 GlobalOpt() : ModulePass(ID) {
69 initializeGlobalOptPass(*PassRegistry::getPassRegistry());
70 }
Misha Brukmanfd939082005-04-21 23:48:37 +000071
Chris Lattnerb12914b2004-09-20 04:48:05 +000072 bool runOnModule(Module &M);
Chris Lattner30ba5692004-10-11 05:54:41 +000073
74 private:
Chris Lattnerb1ab4582005-09-26 01:43:45 +000075 GlobalVariable *FindGlobalCtors(Module &M);
76 bool OptimizeFunctions(Module &M);
77 bool OptimizeGlobalVars(Module &M);
Duncan Sandsfc5940d2009-03-06 10:21:56 +000078 bool OptimizeGlobalAliases(Module &M);
Chris Lattnerb1ab4582005-09-26 01:43:45 +000079 bool OptimizeGlobalCtorsList(GlobalVariable *&GCL);
Rafael Espindolac4440e32011-01-19 16:32:21 +000080 bool ProcessGlobal(GlobalVariable *GV,Module::global_iterator &GVI);
81 bool ProcessInternalGlobal(GlobalVariable *GV,Module::global_iterator &GVI,
82 const SmallPtrSet<const PHINode*, 16> &PHIUsers,
83 const GlobalStatus &GS);
Anders Carlssona201c4c2011-03-20 17:59:11 +000084 bool OptimizeEmptyGlobalCXXDtors(Function *CXAAtExitFn);
Nick Lewycky6a577f82012-02-12 01:13:18 +000085
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;
Chris Lattnerd91ed102011-01-01 22:31:46 +0000203
204 // If the result of the constantexpr isn't pointer type, then we won't
205 // know to expect it in various places. Just reject early.
206 if (!isa<PointerType>(CE->getType())) return true;
207
Chris Lattner7a90b682004-10-07 04:16:33 +0000208 if (AnalyzeGlobal(CE, GS, PHIUsers)) return true;
Gabor Greife6642672010-07-09 16:51:20 +0000209 } else if (const Instruction *I = dyn_cast<Instruction>(U)) {
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +0000210 if (!GS.HasMultipleAccessingFunctions) {
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000211 const Function *F = I->getParent()->getParent();
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +0000212 if (GS.AccessingFunction == 0)
213 GS.AccessingFunction = F;
214 else if (GS.AccessingFunction != F)
215 GS.HasMultipleAccessingFunctions = true;
216 }
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000217 if (const LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattner7a90b682004-10-07 04:16:33 +0000218 GS.isLoaded = true;
Nick Lewyckyfad4d402012-02-05 19:56:38 +0000219 // Don't hack on volatile loads.
220 if (LI->isVolatile()) return true;
221 GS.Ordering = StrongerOrdering(GS.Ordering, LI->getOrdering());
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000222 } else if (const StoreInst *SI = dyn_cast<StoreInst>(I)) {
Chris Lattner36025492004-10-07 06:01:25 +0000223 // Don't allow a store OF the address, only stores TO the address.
224 if (SI->getOperand(0) == V) return true;
225
Nick Lewyckyfad4d402012-02-05 19:56:38 +0000226 // Don't hack on volatile stores.
227 if (SI->isVolatile()) return true;
228 GS.Ordering = StrongerOrdering(GS.Ordering, SI->getOrdering());
Chris Lattnerc69d3c92008-01-29 19:01:37 +0000229
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000230 // If this is a direct store to the global (i.e., the global is a scalar
231 // value, not an aggregate), keep more specific information about
232 // stores.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000233 if (GS.StoredType != GlobalStatus::isStored) {
Gabor Greif27236912010-04-07 18:59:26 +0000234 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(
235 SI->getOperand(1))) {
Chris Lattnerbd38edf2004-11-14 20:50:30 +0000236 Value *StoredVal = SI->getOperand(0);
237 if (StoredVal == GV->getInitializer()) {
238 if (GS.StoredType < GlobalStatus::isInitializerStored)
239 GS.StoredType = GlobalStatus::isInitializerStored;
240 } else if (isa<LoadInst>(StoredVal) &&
241 cast<LoadInst>(StoredVal)->getOperand(0) == GV) {
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000242 if (GS.StoredType < GlobalStatus::isInitializerStored)
243 GS.StoredType = GlobalStatus::isInitializerStored;
244 } else if (GS.StoredType < GlobalStatus::isStoredOnce) {
245 GS.StoredType = GlobalStatus::isStoredOnce;
Chris Lattnerbd38edf2004-11-14 20:50:30 +0000246 GS.StoredOnceValue = StoredVal;
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000247 } else if (GS.StoredType == GlobalStatus::isStoredOnce &&
Chris Lattnerbd38edf2004-11-14 20:50:30 +0000248 GS.StoredOnceValue == StoredVal) {
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000249 // noop.
250 } else {
251 GS.StoredType = GlobalStatus::isStored;
252 }
253 } else {
Chris Lattner7a90b682004-10-07 04:16:33 +0000254 GS.StoredType = GlobalStatus::isStored;
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000255 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000256 }
Duncan Sandsb2fe7f12012-07-02 18:55:39 +0000257 } else if (isa<BitCastInst>(I)) {
258 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Chris Lattner35c81b02005-02-27 18:58:52 +0000259 } else if (isa<GetElementPtrInst>(I)) {
Chris Lattner7a90b682004-10-07 04:16:33 +0000260 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Chris Lattner35c81b02005-02-27 18:58:52 +0000261 } else if (isa<SelectInst>(I)) {
Chris Lattner7a90b682004-10-07 04:16:33 +0000262 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000263 } else if (const PHINode *PN = dyn_cast<PHINode>(I)) {
Chris Lattner7a90b682004-10-07 04:16:33 +0000264 // PHI nodes we can check just like select or GEP instructions, but we
265 // have to be careful about infinite recursion.
Chris Lattner5a6bb6a2008-12-16 07:34:30 +0000266 if (PHIUsers.insert(PN)) // Not already visited.
Chris Lattner7a90b682004-10-07 04:16:33 +0000267 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Chris Lattner25de4e52006-11-01 18:03:33 +0000268 GS.HasPHIUser = true;
Reid Spencere4d87aa2006-12-23 06:05:41 +0000269 } else if (isa<CmpInst>(I)) {
Rafael Espindolac4440e32011-01-19 16:32:21 +0000270 GS.isCompared = true;
Nick Lewycky1f237b02011-05-29 18:41:56 +0000271 } else if (const MemTransferInst *MTI = dyn_cast<MemTransferInst>(I)) {
272 if (MTI->isVolatile()) return true;
Gabor Greif9e4f2432010-06-24 14:42:01 +0000273 if (MTI->getArgOperand(0) == V)
Eric Christopher551754c2010-04-16 23:37:20 +0000274 GS.StoredType = GlobalStatus::isStored;
Gabor Greif9e4f2432010-06-24 14:42:01 +0000275 if (MTI->getArgOperand(1) == V)
Chris Lattner35c81b02005-02-27 18:58:52 +0000276 GS.isLoaded = true;
Nick Lewycky1f237b02011-05-29 18:41:56 +0000277 } else if (const MemSetInst *MSI = dyn_cast<MemSetInst>(I)) {
278 assert(MSI->getArgOperand(0) == V && "Memset only takes one pointer!");
279 if (MSI->isVolatile()) return true;
Chris Lattner35c81b02005-02-27 18:58:52 +0000280 GS.StoredType = GlobalStatus::isStored;
Chris Lattner7a90b682004-10-07 04:16:33 +0000281 } else {
282 return true; // Any other non-load instruction might take address!
Chris Lattner9ce30002004-07-20 03:58:07 +0000283 }
Gabor Greife6642672010-07-09 16:51:20 +0000284 } else if (const Constant *C = dyn_cast<Constant>(U)) {
Chris Lattner553ca522005-06-15 21:11:48 +0000285 GS.HasNonInstructionUser = true;
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000286 // We might have a dead and dangling constant hanging off of here.
Jay Foade3acf152009-06-09 21:37:11 +0000287 if (!SafeToDestroyConstant(C))
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000288 return true;
Chris Lattner079236d2004-02-25 21:34:36 +0000289 } else {
Chris Lattner553ca522005-06-15 21:11:48 +0000290 GS.HasNonInstructionUser = true;
291 // Otherwise must be some other user.
Chris Lattner079236d2004-02-25 21:34:36 +0000292 return true;
293 }
Gabor Greife6642672010-07-09 16:51:20 +0000294 }
Chris Lattner079236d2004-02-25 21:34:36 +0000295
296 return false;
297}
298
Nick Lewycky8899d5c2012-07-24 07:21:08 +0000299/// isLeakCheckerRoot - Is this global variable possibly used by a leak checker
300/// as a root? If so, we might not really want to eliminate the stores to it.
301static bool isLeakCheckerRoot(GlobalVariable *GV) {
302 // A global variable is a root if it is a pointer, or could plausibly contain
303 // a pointer. There are two challenges; one is that we could have a struct
304 // the has an inner member which is a pointer. We recurse through the type to
305 // detect these (up to a point). The other is that we may actually be a union
306 // of a pointer and another type, and so our LLVM type is an integer which
307 // gets converted into a pointer, or our type is an [i8 x #] with a pointer
308 // potentially contained here.
309
310 if (GV->hasPrivateLinkage())
311 return false;
312
313 SmallVector<Type *, 4> Types;
314 Types.push_back(cast<PointerType>(GV->getType())->getElementType());
315
316 unsigned Limit = 20;
317 do {
318 Type *Ty = Types.pop_back_val();
319 switch (Ty->getTypeID()) {
320 default: break;
321 case Type::PointerTyID: return true;
322 case Type::ArrayTyID:
323 case Type::VectorTyID: {
324 SequentialType *STy = cast<SequentialType>(Ty);
325 Types.push_back(STy->getElementType());
326 break;
327 }
328 case Type::StructTyID: {
329 StructType *STy = cast<StructType>(Ty);
330 if (STy->isOpaque()) return true;
331 for (StructType::element_iterator I = STy->element_begin(),
332 E = STy->element_end(); I != E; ++I) {
333 Type *InnerTy = *I;
334 if (isa<PointerType>(InnerTy)) return true;
335 if (isa<CompositeType>(InnerTy))
336 Types.push_back(InnerTy);
337 }
338 break;
339 }
340 }
341 if (--Limit == 0) return true;
342 } while (!Types.empty());
343 return false;
344}
345
346/// Given a value that is stored to a global but never read, determine whether
347/// it's safe to remove the store and the chain of computation that feeds the
348/// store.
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000349static bool IsSafeComputationToRemove(Value *V, const TargetLibraryInfo *TLI) {
Nick Lewycky8899d5c2012-07-24 07:21:08 +0000350 do {
351 if (isa<Constant>(V))
352 return true;
353 if (!V->hasOneUse())
354 return false;
Nick Lewyckyb8cd66b2012-07-25 21:19:40 +0000355 if (isa<LoadInst>(V) || isa<InvokeInst>(V) || isa<Argument>(V) ||
356 isa<GlobalValue>(V))
Nick Lewycky8899d5c2012-07-24 07:21:08 +0000357 return false;
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000358 if (isAllocationFn(V, TLI))
Nick Lewycky8899d5c2012-07-24 07:21:08 +0000359 return true;
360
361 Instruction *I = cast<Instruction>(V);
362 if (I->mayHaveSideEffects())
363 return false;
364 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
365 if (!GEP->hasAllConstantIndices())
366 return false;
367 } else if (I->getNumOperands() != 1) {
368 return false;
369 }
370
371 V = I->getOperand(0);
372 } while (1);
373}
374
375/// CleanupPointerRootUsers - This GV is a pointer root. Loop over all users
376/// of the global and clean up any that obviously don't assign the global a
377/// value that isn't dynamically allocated.
378///
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000379static bool CleanupPointerRootUsers(GlobalVariable *GV,
380 const TargetLibraryInfo *TLI) {
Nick Lewycky8899d5c2012-07-24 07:21:08 +0000381 // A brief explanation of leak checkers. The goal is to find bugs where
382 // pointers are forgotten, causing an accumulating growth in memory
383 // usage over time. The common strategy for leak checkers is to whitelist the
384 // memory pointed to by globals at exit. This is popular because it also
385 // solves another problem where the main thread of a C++ program may shut down
386 // before other threads that are still expecting to use those globals. To
387 // handle that case, we expect the program may create a singleton and never
388 // destroy it.
389
390 bool Changed = false;
391
392 // If Dead[n].first is the only use of a malloc result, we can delete its
393 // chain of computation and the store to the global in Dead[n].second.
394 SmallVector<std::pair<Instruction *, Instruction *>, 32> Dead;
395
396 // Constants can't be pointers to dynamically allocated memory.
397 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end();
398 UI != E;) {
399 User *U = *UI++;
400 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
401 Value *V = SI->getValueOperand();
402 if (isa<Constant>(V)) {
403 Changed = true;
404 SI->eraseFromParent();
405 } else if (Instruction *I = dyn_cast<Instruction>(V)) {
406 if (I->hasOneUse())
407 Dead.push_back(std::make_pair(I, SI));
408 }
409 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(U)) {
410 if (isa<Constant>(MSI->getValue())) {
411 Changed = true;
412 MSI->eraseFromParent();
413 } else if (Instruction *I = dyn_cast<Instruction>(MSI->getValue())) {
414 if (I->hasOneUse())
415 Dead.push_back(std::make_pair(I, MSI));
416 }
417 } else if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(U)) {
418 GlobalVariable *MemSrc = dyn_cast<GlobalVariable>(MTI->getSource());
419 if (MemSrc && MemSrc->isConstant()) {
420 Changed = true;
421 MTI->eraseFromParent();
422 } else if (Instruction *I = dyn_cast<Instruction>(MemSrc)) {
423 if (I->hasOneUse())
424 Dead.push_back(std::make_pair(I, MTI));
425 }
426 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
427 if (CE->use_empty()) {
428 CE->destroyConstant();
429 Changed = true;
430 }
431 } else if (Constant *C = dyn_cast<Constant>(U)) {
432 if (SafeToDestroyConstant(C)) {
433 C->destroyConstant();
434 // This could have invalidated UI, start over from scratch.
435 Dead.clear();
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000436 CleanupPointerRootUsers(GV, TLI);
Nick Lewycky8899d5c2012-07-24 07:21:08 +0000437 return true;
438 }
439 }
440 }
441
442 for (int i = 0, e = Dead.size(); i != e; ++i) {
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000443 if (IsSafeComputationToRemove(Dead[i].first, TLI)) {
Nick Lewycky8899d5c2012-07-24 07:21:08 +0000444 Dead[i].second->eraseFromParent();
445 Instruction *I = Dead[i].first;
446 do {
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000447 if (isAllocationFn(I, TLI))
Nick Lewycky952f5d52012-07-24 21:33:00 +0000448 break;
Nick Lewycky8899d5c2012-07-24 07:21:08 +0000449 Instruction *J = dyn_cast<Instruction>(I->getOperand(0));
450 if (!J)
451 break;
452 I->eraseFromParent();
453 I = J;
Nick Lewycky952f5d52012-07-24 21:33:00 +0000454 } while (1);
Nick Lewycky8899d5c2012-07-24 07:21:08 +0000455 I->eraseFromParent();
456 }
457 }
458
459 return Changed;
460}
461
Chris Lattnere47ba742004-10-06 20:57:02 +0000462/// CleanupConstantGlobalUsers - We just marked GV constant. Loop over all
463/// users of the global, cleaning up the obvious ones. This is largely just a
Chris Lattner031955d2004-10-10 16:43:46 +0000464/// quick scan over the use list to clean up the easy and obvious cruft. This
465/// returns true if it made a change.
Nick Lewycky6a577f82012-02-12 01:13:18 +0000466static bool CleanupConstantGlobalUsers(Value *V, Constant *Init,
Micah Villmow3574eca2012-10-08 16:38:25 +0000467 DataLayout *TD, TargetLibraryInfo *TLI) {
Chris Lattner031955d2004-10-10 16:43:46 +0000468 bool Changed = false;
Chris Lattner7a90b682004-10-07 04:16:33 +0000469 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;) {
470 User *U = *UI++;
Misha Brukmanfd939082005-04-21 23:48:37 +0000471
Chris Lattner7a90b682004-10-07 04:16:33 +0000472 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
Chris Lattner35c81b02005-02-27 18:58:52 +0000473 if (Init) {
474 // Replace the load with the initializer.
475 LI->replaceAllUsesWith(Init);
476 LI->eraseFromParent();
477 Changed = true;
478 }
Chris Lattner7a90b682004-10-07 04:16:33 +0000479 } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
Chris Lattnere47ba742004-10-06 20:57:02 +0000480 // Store must be unreachable or storing Init into the global.
Chris Lattner7a7ed022004-10-16 18:09:00 +0000481 SI->eraseFromParent();
Chris Lattner031955d2004-10-10 16:43:46 +0000482 Changed = true;
Chris Lattner7a90b682004-10-07 04:16:33 +0000483 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
484 if (CE->getOpcode() == Instruction::GetElementPtr) {
Chris Lattneraae4a1c2005-09-26 07:34:35 +0000485 Constant *SubInit = 0;
486 if (Init)
Dan Gohmanc6f69e92009-10-05 16:36:26 +0000487 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
Nick Lewycky6a577f82012-02-12 01:13:18 +0000488 Changed |= CleanupConstantGlobalUsers(CE, SubInit, TD, TLI);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000489 } else if (CE->getOpcode() == Instruction::BitCast &&
Duncan Sands1df98592010-02-16 11:11:14 +0000490 CE->getType()->isPointerTy()) {
Chris Lattner35c81b02005-02-27 18:58:52 +0000491 // Pointer cast, delete any stores and memsets to the global.
Nick Lewycky6a577f82012-02-12 01:13:18 +0000492 Changed |= CleanupConstantGlobalUsers(CE, 0, TD, TLI);
Chris Lattner35c81b02005-02-27 18:58:52 +0000493 }
494
495 if (CE->use_empty()) {
496 CE->destroyConstant();
497 Changed = true;
Chris Lattner7a90b682004-10-07 04:16:33 +0000498 }
499 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
Chris Lattner7b52fe72007-11-09 17:33:02 +0000500 // Do not transform "gepinst (gep constexpr (GV))" here, because forming
501 // "gepconstexpr (gep constexpr (GV))" will cause the two gep's to fold
502 // and will invalidate our notion of what Init is.
Chris Lattner19450242007-11-13 21:46:23 +0000503 Constant *SubInit = 0;
Chris Lattner7b52fe72007-11-09 17:33:02 +0000504 if (!isa<ConstantExpr>(GEP->getOperand(0))) {
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000505 ConstantExpr *CE =
Nick Lewycky6a577f82012-02-12 01:13:18 +0000506 dyn_cast_or_null<ConstantExpr>(ConstantFoldInstruction(GEP, TD, TLI));
Chris Lattner7b52fe72007-11-09 17:33:02 +0000507 if (Init && CE && CE->getOpcode() == Instruction::GetElementPtr)
Dan Gohmanc6f69e92009-10-05 16:36:26 +0000508 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
Benjamin Kramerc1ea16e2012-03-28 14:50:09 +0000509
510 // If the initializer is an all-null value and we have an inbounds GEP,
511 // we already know what the result of any load from that GEP is.
512 // TODO: Handle splats.
513 if (Init && isa<ConstantAggregateZero>(Init) && GEP->isInBounds())
514 SubInit = Constant::getNullValue(GEP->getType()->getElementType());
Chris Lattner7b52fe72007-11-09 17:33:02 +0000515 }
Nick Lewycky6a577f82012-02-12 01:13:18 +0000516 Changed |= CleanupConstantGlobalUsers(GEP, SubInit, TD, TLI);
Chris Lattnerc4d81b02004-10-10 16:47:33 +0000517
Chris Lattner031955d2004-10-10 16:43:46 +0000518 if (GEP->use_empty()) {
Chris Lattner7a7ed022004-10-16 18:09:00 +0000519 GEP->eraseFromParent();
Chris Lattner031955d2004-10-10 16:43:46 +0000520 Changed = true;
521 }
Chris Lattner35c81b02005-02-27 18:58:52 +0000522 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U)) { // memset/cpy/mv
523 if (MI->getRawDest() == V) {
524 MI->eraseFromParent();
525 Changed = true;
526 }
527
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000528 } else if (Constant *C = dyn_cast<Constant>(U)) {
529 // If we have a chain of dead constantexprs or other things dangling from
530 // us, and if they are all dead, nuke them without remorse.
Jay Foade3acf152009-06-09 21:37:11 +0000531 if (SafeToDestroyConstant(C)) {
Devang Patel743cdf82009-03-06 01:37:41 +0000532 C->destroyConstant();
Chris Lattner35c81b02005-02-27 18:58:52 +0000533 // This could have invalidated UI, start over from scratch.
Nick Lewycky6a577f82012-02-12 01:13:18 +0000534 CleanupConstantGlobalUsers(V, Init, TD, TLI);
Chris Lattner031955d2004-10-10 16:43:46 +0000535 return true;
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000536 }
Chris Lattnere47ba742004-10-06 20:57:02 +0000537 }
538 }
Chris Lattner031955d2004-10-10 16:43:46 +0000539 return Changed;
Chris Lattnere47ba742004-10-06 20:57:02 +0000540}
541
Chris Lattner941db492008-01-14 02:09:12 +0000542/// isSafeSROAElementUse - Return true if the specified instruction is a safe
543/// user of a derived expression from a global that we want to SROA.
544static bool isSafeSROAElementUse(Value *V) {
545 // We might have a dead and dangling constant hanging off of here.
546 if (Constant *C = dyn_cast<Constant>(V))
Jay Foade3acf152009-06-09 21:37:11 +0000547 return SafeToDestroyConstant(C);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000548
Chris Lattner941db492008-01-14 02:09:12 +0000549 Instruction *I = dyn_cast<Instruction>(V);
550 if (!I) return false;
551
552 // Loads are ok.
553 if (isa<LoadInst>(I)) return true;
554
555 // Stores *to* the pointer are ok.
556 if (StoreInst *SI = dyn_cast<StoreInst>(I))
557 return SI->getOperand(0) != V;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000558
Chris Lattner941db492008-01-14 02:09:12 +0000559 // Otherwise, it must be a GEP.
560 GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I);
561 if (GEPI == 0) return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000562
Chris Lattner941db492008-01-14 02:09:12 +0000563 if (GEPI->getNumOperands() < 3 || !isa<Constant>(GEPI->getOperand(1)) ||
564 !cast<Constant>(GEPI->getOperand(1))->isNullValue())
565 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000566
Chris Lattner941db492008-01-14 02:09:12 +0000567 for (Value::use_iterator I = GEPI->use_begin(), E = GEPI->use_end();
568 I != E; ++I)
569 if (!isSafeSROAElementUse(*I))
570 return false;
Chris Lattner727c2102008-01-14 01:31:05 +0000571 return true;
572}
573
Chris Lattner941db492008-01-14 02:09:12 +0000574
575/// IsUserOfGlobalSafeForSRA - U is a direct user of the specified global value.
576/// Look at it and its uses and decide whether it is safe to SROA this global.
577///
578static bool IsUserOfGlobalSafeForSRA(User *U, GlobalValue *GV) {
579 // The user of the global must be a GEP Inst or a ConstantExpr GEP.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000580 if (!isa<GetElementPtrInst>(U) &&
581 (!isa<ConstantExpr>(U) ||
Chris Lattner941db492008-01-14 02:09:12 +0000582 cast<ConstantExpr>(U)->getOpcode() != Instruction::GetElementPtr))
583 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000584
Chris Lattner941db492008-01-14 02:09:12 +0000585 // Check to see if this ConstantExpr GEP is SRA'able. In particular, we
586 // don't like < 3 operand CE's, and we don't like non-constant integer
587 // indices. This enforces that all uses are 'gep GV, 0, C, ...' for some
588 // value of C.
589 if (U->getNumOperands() < 3 || !isa<Constant>(U->getOperand(1)) ||
590 !cast<Constant>(U->getOperand(1))->isNullValue() ||
591 !isa<ConstantInt>(U->getOperand(2)))
592 return false;
593
594 gep_type_iterator GEPI = gep_type_begin(U), E = gep_type_end(U);
595 ++GEPI; // Skip over the pointer index.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000596
Chris Lattner941db492008-01-14 02:09:12 +0000597 // If this is a use of an array allocation, do a bit more checking for sanity.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000598 if (ArrayType *AT = dyn_cast<ArrayType>(*GEPI)) {
Chris Lattner941db492008-01-14 02:09:12 +0000599 uint64_t NumElements = AT->getNumElements();
600 ConstantInt *Idx = cast<ConstantInt>(U->getOperand(2));
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000601
Chris Lattner941db492008-01-14 02:09:12 +0000602 // Check to make sure that index falls within the array. If not,
603 // something funny is going on, so we won't do the optimization.
604 //
605 if (Idx->getZExtValue() >= NumElements)
606 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000607
Chris Lattner941db492008-01-14 02:09:12 +0000608 // We cannot scalar repl this level of the array unless any array
609 // sub-indices are in-range constants. In particular, consider:
610 // A[0][i]. We cannot know that the user isn't doing invalid things like
611 // allowing i to index an out-of-range subscript that accesses A[1].
612 //
613 // Scalar replacing *just* the outer index of the array is probably not
614 // going to be a win anyway, so just give up.
615 for (++GEPI; // Skip array index.
Dan Gohman6874a2a2009-08-18 14:58:19 +0000616 GEPI != E;
Chris Lattner941db492008-01-14 02:09:12 +0000617 ++GEPI) {
618 uint64_t NumElements;
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000619 if (ArrayType *SubArrayTy = dyn_cast<ArrayType>(*GEPI))
Chris Lattner941db492008-01-14 02:09:12 +0000620 NumElements = SubArrayTy->getNumElements();
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000621 else if (VectorType *SubVectorTy = dyn_cast<VectorType>(*GEPI))
Dan Gohman6874a2a2009-08-18 14:58:19 +0000622 NumElements = SubVectorTy->getNumElements();
623 else {
Duncan Sands1df98592010-02-16 11:11:14 +0000624 assert((*GEPI)->isStructTy() &&
Dan Gohman6874a2a2009-08-18 14:58:19 +0000625 "Indexed GEP type is not array, vector, or struct!");
626 continue;
627 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000628
Chris Lattner941db492008-01-14 02:09:12 +0000629 ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPI.getOperand());
630 if (!IdxVal || IdxVal->getZExtValue() >= NumElements)
631 return false;
632 }
633 }
634
635 for (Value::use_iterator I = U->use_begin(), E = U->use_end(); I != E; ++I)
636 if (!isSafeSROAElementUse(*I))
637 return false;
638 return true;
639}
640
641/// GlobalUsersSafeToSRA - Look at all uses of the global and decide whether it
642/// is safe for us to perform this transformation.
643///
644static bool GlobalUsersSafeToSRA(GlobalValue *GV) {
645 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end();
646 UI != E; ++UI) {
647 if (!IsUserOfGlobalSafeForSRA(*UI, GV))
648 return false;
649 }
650 return true;
651}
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000652
Chris Lattner941db492008-01-14 02:09:12 +0000653
Chris Lattner670c8892004-10-08 17:32:09 +0000654/// SRAGlobal - Perform scalar replacement of aggregates on the specified global
655/// variable. This opens the door for other optimizations by exposing the
656/// behavior of the program in a more fine-grained way. We have determined that
657/// this transformation is safe already. We return the first global variable we
658/// insert so that the caller can reprocess it.
Micah Villmow3574eca2012-10-08 16:38:25 +0000659static GlobalVariable *SRAGlobal(GlobalVariable *GV, const DataLayout &TD) {
Chris Lattner727c2102008-01-14 01:31:05 +0000660 // Make sure this global only has simple uses that we can SRA.
Chris Lattner941db492008-01-14 02:09:12 +0000661 if (!GlobalUsersSafeToSRA(GV))
Chris Lattner727c2102008-01-14 01:31:05 +0000662 return 0;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000663
Rafael Espindolabb46f522009-01-15 20:18:42 +0000664 assert(GV->hasLocalLinkage() && !GV->isConstant());
Chris Lattner670c8892004-10-08 17:32:09 +0000665 Constant *Init = GV->getInitializer();
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000666 Type *Ty = Init->getType();
Misha Brukmanfd939082005-04-21 23:48:37 +0000667
Chris Lattner670c8892004-10-08 17:32:09 +0000668 std::vector<GlobalVariable*> NewGlobals;
669 Module::GlobalListType &Globals = GV->getParent()->getGlobalList();
670
Chris Lattner998182b2008-04-26 07:40:11 +0000671 // Get the alignment of the global, either explicit or target-specific.
672 unsigned StartAlignment = GV->getAlignment();
673 if (StartAlignment == 0)
674 StartAlignment = TD.getABITypeAlignment(GV->getType());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000675
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000676 if (StructType *STy = dyn_cast<StructType>(Ty)) {
Chris Lattner670c8892004-10-08 17:32:09 +0000677 NewGlobals.reserve(STy->getNumElements());
Chris Lattner998182b2008-04-26 07:40:11 +0000678 const StructLayout &Layout = *TD.getStructLayout(STy);
Chris Lattner670c8892004-10-08 17:32:09 +0000679 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
Chris Lattnera1f00f42012-01-25 06:48:06 +0000680 Constant *In = Init->getAggregateElement(i);
Chris Lattner670c8892004-10-08 17:32:09 +0000681 assert(In && "Couldn't get element of initializer?");
Chris Lattner7b550cc2009-11-06 04:27:31 +0000682 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(i), false,
Chris Lattner670c8892004-10-08 17:32:09 +0000683 GlobalVariable::InternalLinkage,
Daniel Dunbarfe09b202009-07-30 17:37:43 +0000684 In, GV->getName()+"."+Twine(i),
Hans Wennborgce718ff2012-06-23 11:37:03 +0000685 GV->getThreadLocalMode(),
Owen Anderson3d29df32009-07-08 01:26:06 +0000686 GV->getType()->getAddressSpace());
Chris Lattner670c8892004-10-08 17:32:09 +0000687 Globals.insert(GV, NGV);
688 NewGlobals.push_back(NGV);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000689
Chris Lattner998182b2008-04-26 07:40:11 +0000690 // Calculate the known alignment of the field. If the original aggregate
691 // had 256 byte alignment for example, something might depend on that:
692 // propagate info to each field.
693 uint64_t FieldOffset = Layout.getElementOffset(i);
694 unsigned NewAlign = (unsigned)MinAlign(StartAlignment, FieldOffset);
695 if (NewAlign > TD.getABITypeAlignment(STy->getElementType(i)))
696 NGV->setAlignment(NewAlign);
Chris Lattner670c8892004-10-08 17:32:09 +0000697 }
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000698 } else if (SequentialType *STy = dyn_cast<SequentialType>(Ty)) {
Chris Lattner670c8892004-10-08 17:32:09 +0000699 unsigned NumElements = 0;
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000700 if (ArrayType *ATy = dyn_cast<ArrayType>(STy))
Chris Lattner670c8892004-10-08 17:32:09 +0000701 NumElements = ATy->getNumElements();
Chris Lattner670c8892004-10-08 17:32:09 +0000702 else
Chris Lattner998182b2008-04-26 07:40:11 +0000703 NumElements = cast<VectorType>(STy)->getNumElements();
Chris Lattner670c8892004-10-08 17:32:09 +0000704
Chris Lattner1f21ef12005-02-23 16:53:04 +0000705 if (NumElements > 16 && GV->hasNUsesOrMore(16))
Chris Lattnerd514d822005-02-01 01:23:31 +0000706 return 0; // It's not worth it.
Chris Lattner670c8892004-10-08 17:32:09 +0000707 NewGlobals.reserve(NumElements);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000708
Duncan Sands777d2302009-05-09 07:06:46 +0000709 uint64_t EltSize = TD.getTypeAllocSize(STy->getElementType());
Chris Lattner998182b2008-04-26 07:40:11 +0000710 unsigned EltAlign = TD.getABITypeAlignment(STy->getElementType());
Chris Lattner670c8892004-10-08 17:32:09 +0000711 for (unsigned i = 0, e = NumElements; i != e; ++i) {
Chris Lattnera1f00f42012-01-25 06:48:06 +0000712 Constant *In = Init->getAggregateElement(i);
Chris Lattner670c8892004-10-08 17:32:09 +0000713 assert(In && "Couldn't get element of initializer?");
714
Chris Lattner7b550cc2009-11-06 04:27:31 +0000715 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(), false,
Chris Lattner670c8892004-10-08 17:32:09 +0000716 GlobalVariable::InternalLinkage,
Daniel Dunbarfe09b202009-07-30 17:37:43 +0000717 In, GV->getName()+"."+Twine(i),
Hans Wennborgce718ff2012-06-23 11:37:03 +0000718 GV->getThreadLocalMode(),
Owen Andersone9b11b42009-07-08 19:03:57 +0000719 GV->getType()->getAddressSpace());
Chris Lattner670c8892004-10-08 17:32:09 +0000720 Globals.insert(GV, NGV);
721 NewGlobals.push_back(NGV);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000722
Chris Lattner998182b2008-04-26 07:40:11 +0000723 // Calculate the known alignment of the field. If the original aggregate
724 // had 256 byte alignment for example, something might depend on that:
725 // propagate info to each field.
726 unsigned NewAlign = (unsigned)MinAlign(StartAlignment, EltSize*i);
727 if (NewAlign > EltAlign)
728 NGV->setAlignment(NewAlign);
Chris Lattner670c8892004-10-08 17:32:09 +0000729 }
730 }
731
732 if (NewGlobals.empty())
733 return 0;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000734
David Greene3215b0e2010-01-05 01:28:05 +0000735 DEBUG(dbgs() << "PERFORMING GLOBAL SRA ON: " << *GV);
Chris Lattner30ba5692004-10-11 05:54:41 +0000736
Chris Lattner7b550cc2009-11-06 04:27:31 +0000737 Constant *NullInt =Constant::getNullValue(Type::getInt32Ty(GV->getContext()));
Chris Lattner670c8892004-10-08 17:32:09 +0000738
739 // Loop over all of the uses of the global, replacing the constantexpr geps,
740 // with smaller constantexpr geps or direct references.
741 while (!GV->use_empty()) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000742 User *GEP = GV->use_back();
743 assert(((isa<ConstantExpr>(GEP) &&
744 cast<ConstantExpr>(GEP)->getOpcode()==Instruction::GetElementPtr)||
745 isa<GetElementPtrInst>(GEP)) && "NonGEP CE's are not SRAable!");
Misha Brukmanfd939082005-04-21 23:48:37 +0000746
Chris Lattner670c8892004-10-08 17:32:09 +0000747 // Ignore the 1th operand, which has to be zero or else the program is quite
748 // broken (undefined). Get the 2nd operand, which is the structure or array
749 // index.
Reid Spencerb83eb642006-10-20 07:07:24 +0000750 unsigned Val = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
Chris Lattner670c8892004-10-08 17:32:09 +0000751 if (Val >= NewGlobals.size()) Val = 0; // Out of bound array access.
752
Chris Lattner30ba5692004-10-11 05:54:41 +0000753 Value *NewPtr = NewGlobals[Val];
Chris Lattner670c8892004-10-08 17:32:09 +0000754
755 // Form a shorter GEP if needed.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000756 if (GEP->getNumOperands() > 3) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000757 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEP)) {
Chris Lattner55eb1c42007-01-31 04:40:53 +0000758 SmallVector<Constant*, 8> Idxs;
Chris Lattner30ba5692004-10-11 05:54:41 +0000759 Idxs.push_back(NullInt);
760 for (unsigned i = 3, e = CE->getNumOperands(); i != e; ++i)
761 Idxs.push_back(CE->getOperand(i));
Jay Foaddab3d292011-07-21 14:31:17 +0000762 NewPtr = ConstantExpr::getGetElementPtr(cast<Constant>(NewPtr), Idxs);
Chris Lattner30ba5692004-10-11 05:54:41 +0000763 } else {
764 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(GEP);
Chris Lattner699d1442007-01-31 19:59:55 +0000765 SmallVector<Value*, 8> Idxs;
Chris Lattner30ba5692004-10-11 05:54:41 +0000766 Idxs.push_back(NullInt);
767 for (unsigned i = 3, e = GEPI->getNumOperands(); i != e; ++i)
768 Idxs.push_back(GEPI->getOperand(i));
Jay Foada9203102011-07-25 09:48:08 +0000769 NewPtr = GetElementPtrInst::Create(NewPtr, Idxs,
Daniel Dunbarfe09b202009-07-30 17:37:43 +0000770 GEPI->getName()+"."+Twine(Val),GEPI);
Chris Lattner30ba5692004-10-11 05:54:41 +0000771 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000772 }
Chris Lattner30ba5692004-10-11 05:54:41 +0000773 GEP->replaceAllUsesWith(NewPtr);
774
775 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(GEP))
Chris Lattner7a7ed022004-10-16 18:09:00 +0000776 GEPI->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +0000777 else
778 cast<ConstantExpr>(GEP)->destroyConstant();
Chris Lattner670c8892004-10-08 17:32:09 +0000779 }
780
Chris Lattnere40e2d12004-10-08 20:25:55 +0000781 // Delete the old global, now that it is dead.
782 Globals.erase(GV);
Chris Lattner670c8892004-10-08 17:32:09 +0000783 ++NumSRA;
Chris Lattner30ba5692004-10-11 05:54:41 +0000784
785 // Loop over the new globals array deleting any globals that are obviously
786 // dead. This can arise due to scalarization of a structure or an array that
787 // has elements that are dead.
788 unsigned FirstGlobal = 0;
789 for (unsigned i = 0, e = NewGlobals.size(); i != e; ++i)
790 if (NewGlobals[i]->use_empty()) {
791 Globals.erase(NewGlobals[i]);
792 if (FirstGlobal == i) ++FirstGlobal;
793 }
794
795 return FirstGlobal != NewGlobals.size() ? NewGlobals[FirstGlobal] : 0;
Chris Lattner670c8892004-10-08 17:32:09 +0000796}
797
Chris Lattner9b34a612004-10-09 21:48:45 +0000798/// AllUsesOfValueWillTrapIfNull - Return true if all users of the specified
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000799/// value will trap if the value is dynamically null. PHIs keeps track of any
Chris Lattner81686182007-09-13 16:30:19 +0000800/// phi nodes we've seen to avoid reprocessing them.
Gabor Greif6ce02b52010-04-06 19:24:18 +0000801static bool AllUsesOfValueWillTrapIfNull(const Value *V,
802 SmallPtrSet<const PHINode*, 8> &PHIs) {
803 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;
Gabor Greifa01d6db2010-04-06 19:14:05 +0000804 ++UI) {
Gabor Greif6ce02b52010-04-06 19:24:18 +0000805 const User *U = *UI;
Gabor Greifa01d6db2010-04-06 19:14:05 +0000806
807 if (isa<LoadInst>(U)) {
Chris Lattner9b34a612004-10-09 21:48:45 +0000808 // Will trap.
Gabor Greif6ce02b52010-04-06 19:24:18 +0000809 } else if (const StoreInst *SI = dyn_cast<StoreInst>(U)) {
Chris Lattner9b34a612004-10-09 21:48:45 +0000810 if (SI->getOperand(0) == V) {
Gabor Greifa01d6db2010-04-06 19:14:05 +0000811 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner9b34a612004-10-09 21:48:45 +0000812 return false; // Storing the value.
813 }
Gabor Greif6ce02b52010-04-06 19:24:18 +0000814 } else if (const CallInst *CI = dyn_cast<CallInst>(U)) {
Gabor Greif654c06f2010-03-20 21:00:25 +0000815 if (CI->getCalledValue() != V) {
Gabor Greifa01d6db2010-04-06 19:14:05 +0000816 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner9b34a612004-10-09 21:48:45 +0000817 return false; // Not calling the ptr
818 }
Gabor Greif6ce02b52010-04-06 19:24:18 +0000819 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(U)) {
Gabor Greif654c06f2010-03-20 21:00:25 +0000820 if (II->getCalledValue() != V) {
Gabor Greifa01d6db2010-04-06 19:14:05 +0000821 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner9b34a612004-10-09 21:48:45 +0000822 return false; // Not calling the ptr
823 }
Gabor Greif6ce02b52010-04-06 19:24:18 +0000824 } else if (const BitCastInst *CI = dyn_cast<BitCastInst>(U)) {
Chris Lattner81686182007-09-13 16:30:19 +0000825 if (!AllUsesOfValueWillTrapIfNull(CI, PHIs)) return false;
Gabor Greif6ce02b52010-04-06 19:24:18 +0000826 } else if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
Chris Lattner81686182007-09-13 16:30:19 +0000827 if (!AllUsesOfValueWillTrapIfNull(GEPI, PHIs)) return false;
Gabor Greif6ce02b52010-04-06 19:24:18 +0000828 } else if (const PHINode *PN = dyn_cast<PHINode>(U)) {
Chris Lattner81686182007-09-13 16:30:19 +0000829 // If we've already seen this phi node, ignore it, it has already been
830 // checked.
Jakob Stoklund Olesenb489d0f2010-01-29 23:54:14 +0000831 if (PHIs.insert(PN) && !AllUsesOfValueWillTrapIfNull(PN, PHIs))
832 return false;
Gabor Greifa01d6db2010-04-06 19:14:05 +0000833 } else if (isa<ICmpInst>(U) &&
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000834 isa<ConstantPointerNull>(UI->getOperand(1))) {
Nick Lewyckye7ee59b2010-02-25 06:39:10 +0000835 // Ignore icmp X, null
Chris Lattner9b34a612004-10-09 21:48:45 +0000836 } else {
Gabor Greifa01d6db2010-04-06 19:14:05 +0000837 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner9b34a612004-10-09 21:48:45 +0000838 return false;
839 }
Gabor Greifa01d6db2010-04-06 19:14:05 +0000840 }
Chris Lattner9b34a612004-10-09 21:48:45 +0000841 return true;
842}
843
844/// AllUsesOfLoadedValueWillTrapIfNull - Return true if all uses of any loads
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000845/// from GV will trap if the loaded value is null. Note that this also permits
846/// comparisons of the loaded value against null, as a special case.
Gabor Greif6ce02b52010-04-06 19:24:18 +0000847static bool AllUsesOfLoadedValueWillTrapIfNull(const GlobalVariable *GV) {
848 for (Value::const_use_iterator UI = GV->use_begin(), E = GV->use_end();
Gabor Greifa01d6db2010-04-06 19:14:05 +0000849 UI != E; ++UI) {
Gabor Greif6ce02b52010-04-06 19:24:18 +0000850 const User *U = *UI;
Gabor Greifa01d6db2010-04-06 19:14:05 +0000851
Gabor Greif6ce02b52010-04-06 19:24:18 +0000852 if (const LoadInst *LI = dyn_cast<LoadInst>(U)) {
853 SmallPtrSet<const PHINode*, 8> PHIs;
Chris Lattner81686182007-09-13 16:30:19 +0000854 if (!AllUsesOfValueWillTrapIfNull(LI, PHIs))
Chris Lattner9b34a612004-10-09 21:48:45 +0000855 return false;
Gabor Greifa01d6db2010-04-06 19:14:05 +0000856 } else if (isa<StoreInst>(U)) {
Chris Lattner9b34a612004-10-09 21:48:45 +0000857 // Ignore stores to the global.
858 } else {
859 // We don't know or understand this user, bail out.
Gabor Greifa01d6db2010-04-06 19:14:05 +0000860 //cerr << "UNKNOWN USER OF GLOBAL!: " << *U;
Chris Lattner9b34a612004-10-09 21:48:45 +0000861 return false;
862 }
Gabor Greifa01d6db2010-04-06 19:14:05 +0000863 }
Chris Lattner9b34a612004-10-09 21:48:45 +0000864 return true;
865}
866
Chris Lattner7b550cc2009-11-06 04:27:31 +0000867static bool OptimizeAwayTrappingUsesOfValue(Value *V, Constant *NewV) {
Chris Lattner708148e2004-10-10 23:14:11 +0000868 bool Changed = false;
869 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ) {
870 Instruction *I = cast<Instruction>(*UI++);
871 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
872 LI->setOperand(0, NewV);
873 Changed = true;
874 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
875 if (SI->getOperand(1) == V) {
876 SI->setOperand(1, NewV);
877 Changed = true;
878 }
879 } else if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
Gabor Greiffa1f5c22010-04-06 18:45:08 +0000880 CallSite CS(I);
881 if (CS.getCalledValue() == V) {
Chris Lattner708148e2004-10-10 23:14:11 +0000882 // Calling through the pointer! Turn into a direct call, but be careful
883 // that the pointer is not also being passed as an argument.
Gabor Greiffa1f5c22010-04-06 18:45:08 +0000884 CS.setCalledFunction(NewV);
Chris Lattner708148e2004-10-10 23:14:11 +0000885 Changed = true;
886 bool PassedAsArg = false;
Gabor Greiffa1f5c22010-04-06 18:45:08 +0000887 for (unsigned i = 0, e = CS.arg_size(); i != e; ++i)
888 if (CS.getArgument(i) == V) {
Chris Lattner708148e2004-10-10 23:14:11 +0000889 PassedAsArg = true;
Gabor Greiffa1f5c22010-04-06 18:45:08 +0000890 CS.setArgument(i, NewV);
Chris Lattner708148e2004-10-10 23:14:11 +0000891 }
892
893 if (PassedAsArg) {
894 // Being passed as an argument also. Be careful to not invalidate UI!
895 UI = V->use_begin();
896 }
897 }
898 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
899 Changed |= OptimizeAwayTrappingUsesOfValue(CI,
Owen Andersonbaf3c402009-07-29 18:55:55 +0000900 ConstantExpr::getCast(CI->getOpcode(),
Chris Lattner7b550cc2009-11-06 04:27:31 +0000901 NewV, CI->getType()));
Chris Lattner708148e2004-10-10 23:14:11 +0000902 if (CI->use_empty()) {
903 Changed = true;
Chris Lattner7a7ed022004-10-16 18:09:00 +0000904 CI->eraseFromParent();
Chris Lattner708148e2004-10-10 23:14:11 +0000905 }
906 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
907 // Should handle GEP here.
Chris Lattner55eb1c42007-01-31 04:40:53 +0000908 SmallVector<Constant*, 8> Idxs;
909 Idxs.reserve(GEPI->getNumOperands()-1);
Gabor Greif5e463212008-05-29 01:59:18 +0000910 for (User::op_iterator i = GEPI->op_begin() + 1, e = GEPI->op_end();
911 i != e; ++i)
912 if (Constant *C = dyn_cast<Constant>(*i))
Chris Lattner55eb1c42007-01-31 04:40:53 +0000913 Idxs.push_back(C);
Chris Lattner708148e2004-10-10 23:14:11 +0000914 else
915 break;
Chris Lattner55eb1c42007-01-31 04:40:53 +0000916 if (Idxs.size() == GEPI->getNumOperands()-1)
Chris Lattner708148e2004-10-10 23:14:11 +0000917 Changed |= OptimizeAwayTrappingUsesOfValue(GEPI,
Jay Foaddab3d292011-07-21 14:31:17 +0000918 ConstantExpr::getGetElementPtr(NewV, Idxs));
Chris Lattner708148e2004-10-10 23:14:11 +0000919 if (GEPI->use_empty()) {
920 Changed = true;
Chris Lattner7a7ed022004-10-16 18:09:00 +0000921 GEPI->eraseFromParent();
Chris Lattner708148e2004-10-10 23:14:11 +0000922 }
923 }
924 }
925
926 return Changed;
927}
928
929
930/// OptimizeAwayTrappingUsesOfLoads - The specified global has only one non-null
931/// value stored into it. If there are uses of the loaded value that would trap
932/// if the loaded value is dynamically null, then we know that they cannot be
933/// reachable with a null optimize away the load.
Nick Lewycky6a577f82012-02-12 01:13:18 +0000934static bool OptimizeAwayTrappingUsesOfLoads(GlobalVariable *GV, Constant *LV,
Micah Villmow3574eca2012-10-08 16:38:25 +0000935 DataLayout *TD,
Nick Lewycky6a577f82012-02-12 01:13:18 +0000936 TargetLibraryInfo *TLI) {
Chris Lattner708148e2004-10-10 23:14:11 +0000937 bool Changed = false;
938
Chris Lattner92c6bd22009-01-14 00:12:58 +0000939 // Keep track of whether we are able to remove all the uses of the global
940 // other than the store that defines it.
941 bool AllNonStoreUsesGone = true;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000942
Chris Lattner708148e2004-10-10 23:14:11 +0000943 // Replace all uses of loads with uses of uses of the stored value.
Chris Lattner92c6bd22009-01-14 00:12:58 +0000944 for (Value::use_iterator GUI = GV->use_begin(), E = GV->use_end(); GUI != E;){
945 User *GlobalUser = *GUI++;
946 if (LoadInst *LI = dyn_cast<LoadInst>(GlobalUser)) {
Chris Lattner7b550cc2009-11-06 04:27:31 +0000947 Changed |= OptimizeAwayTrappingUsesOfValue(LI, LV);
Chris Lattner92c6bd22009-01-14 00:12:58 +0000948 // If we were able to delete all uses of the loads
949 if (LI->use_empty()) {
950 LI->eraseFromParent();
951 Changed = true;
952 } else {
953 AllNonStoreUsesGone = false;
954 }
955 } else if (isa<StoreInst>(GlobalUser)) {
956 // Ignore the store that stores "LV" to the global.
957 assert(GlobalUser->getOperand(1) == GV &&
958 "Must be storing *to* the global");
Chris Lattner708148e2004-10-10 23:14:11 +0000959 } else {
Chris Lattner92c6bd22009-01-14 00:12:58 +0000960 AllNonStoreUsesGone = false;
961
962 // If we get here we could have other crazy uses that are transitively
963 // loaded.
964 assert((isa<PHINode>(GlobalUser) || isa<SelectInst>(GlobalUser) ||
Benjamin Kramerab164232012-09-28 10:01:27 +0000965 isa<ConstantExpr>(GlobalUser) || isa<CmpInst>(GlobalUser) ||
966 isa<BitCastInst>(GlobalUser) ||
967 isa<GetElementPtrInst>(GlobalUser)) &&
Chris Lattner98a42b22011-05-22 07:15:13 +0000968 "Only expect load and stores!");
Chris Lattner708148e2004-10-10 23:14:11 +0000969 }
Chris Lattner92c6bd22009-01-14 00:12:58 +0000970 }
Chris Lattner708148e2004-10-10 23:14:11 +0000971
972 if (Changed) {
David Greene3215b0e2010-01-05 01:28:05 +0000973 DEBUG(dbgs() << "OPTIMIZED LOADS FROM STORED ONCE POINTER: " << *GV);
Chris Lattner708148e2004-10-10 23:14:11 +0000974 ++NumGlobUses;
975 }
976
Chris Lattner708148e2004-10-10 23:14:11 +0000977 // If we nuked all of the loads, then none of the stores are needed either,
978 // nor is the global.
Chris Lattner92c6bd22009-01-14 00:12:58 +0000979 if (AllNonStoreUsesGone) {
Nick Lewycky8899d5c2012-07-24 07:21:08 +0000980 if (isLeakCheckerRoot(GV)) {
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000981 Changed |= CleanupPointerRootUsers(GV, TLI);
Nick Lewycky8899d5c2012-07-24 07:21:08 +0000982 } else {
983 Changed = true;
984 CleanupConstantGlobalUsers(GV, 0, TD, TLI);
985 }
Chris Lattner708148e2004-10-10 23:14:11 +0000986 if (GV->use_empty()) {
Nick Lewycky8899d5c2012-07-24 07:21:08 +0000987 DEBUG(dbgs() << " *** GLOBAL NOW DEAD!\n");
988 Changed = true;
Chris Lattner7a7ed022004-10-16 18:09:00 +0000989 GV->eraseFromParent();
Chris Lattner708148e2004-10-10 23:14:11 +0000990 ++NumDeleted;
991 }
Chris Lattner708148e2004-10-10 23:14:11 +0000992 }
993 return Changed;
994}
995
Chris Lattner30ba5692004-10-11 05:54:41 +0000996/// ConstantPropUsersOf - Walk the use list of V, constant folding all of the
997/// instructions that are foldable.
Nick Lewycky6a577f82012-02-12 01:13:18 +0000998static void ConstantPropUsersOf(Value *V,
Micah Villmow3574eca2012-10-08 16:38:25 +0000999 DataLayout *TD, TargetLibraryInfo *TLI) {
Chris Lattner30ba5692004-10-11 05:54:41 +00001000 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; )
1001 if (Instruction *I = dyn_cast<Instruction>(*UI++))
Nick Lewycky6a577f82012-02-12 01:13:18 +00001002 if (Constant *NewC = ConstantFoldInstruction(I, TD, TLI)) {
Chris Lattner30ba5692004-10-11 05:54:41 +00001003 I->replaceAllUsesWith(NewC);
1004
Chris Lattnerd514d822005-02-01 01:23:31 +00001005 // Advance UI to the next non-I use to avoid invalidating it!
1006 // Instructions could multiply use V.
1007 while (UI != E && *UI == I)
Chris Lattner30ba5692004-10-11 05:54:41 +00001008 ++UI;
Chris Lattnerd514d822005-02-01 01:23:31 +00001009 I->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +00001010 }
1011}
1012
1013/// OptimizeGlobalAddressOfMalloc - This function takes the specified global
1014/// variable, and transforms the program as if it always contained the result of
1015/// the specified malloc. Because it is always the result of the specified
1016/// malloc, there is no reason to actually DO the malloc. Instead, turn the
Chris Lattner6e8fbad2006-11-30 17:32:29 +00001017/// malloc into a global, and any loads of GV as uses of the new global.
Chris Lattner30ba5692004-10-11 05:54:41 +00001018static GlobalVariable *OptimizeGlobalAddressOfMalloc(GlobalVariable *GV,
Victor Hernandez83d63912009-09-18 22:35:49 +00001019 CallInst *CI,
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001020 Type *AllocTy,
Chris Lattnera6874652010-02-25 22:33:52 +00001021 ConstantInt *NElements,
Micah Villmow3574eca2012-10-08 16:38:25 +00001022 DataLayout *TD,
Nick Lewycky6a577f82012-02-12 01:13:18 +00001023 TargetLibraryInfo *TLI) {
Chris Lattnera6874652010-02-25 22:33:52 +00001024 DEBUG(errs() << "PROMOTING GLOBAL: " << *GV << " CALL = " << *CI << '\n');
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001025
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001026 Type *GlobalType;
Chris Lattnera6874652010-02-25 22:33:52 +00001027 if (NElements->getZExtValue() == 1)
1028 GlobalType = AllocTy;
1029 else
1030 // If we have an array allocation, the global variable is of an array.
1031 GlobalType = ArrayType::get(AllocTy, NElements->getZExtValue());
Victor Hernandez83d63912009-09-18 22:35:49 +00001032
1033 // Create the new global variable. The contents of the malloc'd memory is
1034 // undefined, so initialize with an undef value.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001035 GlobalVariable *NewGV = new GlobalVariable(*GV->getParent(),
Chris Lattnere9fd4442010-02-26 23:42:13 +00001036 GlobalType, false,
Chris Lattnera6874652010-02-25 22:33:52 +00001037 GlobalValue::InternalLinkage,
Chris Lattnere9fd4442010-02-26 23:42:13 +00001038 UndefValue::get(GlobalType),
Victor Hernandez83d63912009-09-18 22:35:49 +00001039 GV->getName()+".body",
1040 GV,
Hans Wennborgce718ff2012-06-23 11:37:03 +00001041 GV->getThreadLocalMode());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001042
Chris Lattnera6874652010-02-25 22:33:52 +00001043 // If there are bitcast users of the malloc (which is typical, usually we have
1044 // a malloc + bitcast) then replace them with uses of the new global. Update
1045 // other users to use the global as well.
1046 BitCastInst *TheBC = 0;
1047 while (!CI->use_empty()) {
1048 Instruction *User = cast<Instruction>(CI->use_back());
1049 if (BitCastInst *BCI = dyn_cast<BitCastInst>(User)) {
1050 if (BCI->getType() == NewGV->getType()) {
1051 BCI->replaceAllUsesWith(NewGV);
1052 BCI->eraseFromParent();
1053 } else {
1054 BCI->setOperand(0, NewGV);
1055 }
1056 } else {
1057 if (TheBC == 0)
1058 TheBC = new BitCastInst(NewGV, CI->getType(), "newgv", CI);
1059 User->replaceUsesOfWith(CI, TheBC);
1060 }
1061 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001062
Victor Hernandez83d63912009-09-18 22:35:49 +00001063 Constant *RepValue = NewGV;
1064 if (NewGV->getType() != GV->getType()->getElementType())
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001065 RepValue = ConstantExpr::getBitCast(RepValue,
Victor Hernandez83d63912009-09-18 22:35:49 +00001066 GV->getType()->getElementType());
1067
1068 // If there is a comparison against null, we will insert a global bool to
1069 // keep track of whether the global was initialized yet or not.
1070 GlobalVariable *InitBool =
Chris Lattner7b550cc2009-11-06 04:27:31 +00001071 new GlobalVariable(Type::getInt1Ty(GV->getContext()), false,
Victor Hernandez83d63912009-09-18 22:35:49 +00001072 GlobalValue::InternalLinkage,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001073 ConstantInt::getFalse(GV->getContext()),
Hans Wennborgce718ff2012-06-23 11:37:03 +00001074 GV->getName()+".init", GV->getThreadLocalMode());
Victor Hernandez83d63912009-09-18 22:35:49 +00001075 bool InitBoolUsed = false;
1076
1077 // Loop over all uses of GV, processing them in turn.
Chris Lattnera6874652010-02-25 22:33:52 +00001078 while (!GV->use_empty()) {
1079 if (StoreInst *SI = dyn_cast<StoreInst>(GV->use_back())) {
Victor Hernandez83d63912009-09-18 22:35:49 +00001080 // The global is initialized when the store to it occurs.
Nick Lewyckyfad4d402012-02-05 19:56:38 +00001081 new StoreInst(ConstantInt::getTrue(GV->getContext()), InitBool, false, 0,
1082 SI->getOrdering(), SI->getSynchScope(), SI);
Victor Hernandez83d63912009-09-18 22:35:49 +00001083 SI->eraseFromParent();
Chris Lattnera6874652010-02-25 22:33:52 +00001084 continue;
Victor Hernandez83d63912009-09-18 22:35:49 +00001085 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001086
Chris Lattnera6874652010-02-25 22:33:52 +00001087 LoadInst *LI = cast<LoadInst>(GV->use_back());
1088 while (!LI->use_empty()) {
1089 Use &LoadUse = LI->use_begin().getUse();
1090 if (!isa<ICmpInst>(LoadUse.getUser())) {
1091 LoadUse = RepValue;
1092 continue;
1093 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001094
Chris Lattnera6874652010-02-25 22:33:52 +00001095 ICmpInst *ICI = cast<ICmpInst>(LoadUse.getUser());
1096 // Replace the cmp X, 0 with a use of the bool value.
Nick Lewyckyfad4d402012-02-05 19:56:38 +00001097 // Sink the load to where the compare was, if atomic rules allow us to.
1098 Value *LV = new LoadInst(InitBool, InitBool->getName()+".val", false, 0,
1099 LI->getOrdering(), LI->getSynchScope(),
1100 LI->isUnordered() ? (Instruction*)ICI : LI);
Chris Lattnera6874652010-02-25 22:33:52 +00001101 InitBoolUsed = true;
1102 switch (ICI->getPredicate()) {
1103 default: llvm_unreachable("Unknown ICmp Predicate!");
1104 case ICmpInst::ICMP_ULT:
1105 case ICmpInst::ICMP_SLT: // X < null -> always false
1106 LV = ConstantInt::getFalse(GV->getContext());
1107 break;
1108 case ICmpInst::ICMP_ULE:
1109 case ICmpInst::ICMP_SLE:
1110 case ICmpInst::ICMP_EQ:
1111 LV = BinaryOperator::CreateNot(LV, "notinit", ICI);
1112 break;
1113 case ICmpInst::ICMP_NE:
1114 case ICmpInst::ICMP_UGE:
1115 case ICmpInst::ICMP_SGE:
1116 case ICmpInst::ICMP_UGT:
1117 case ICmpInst::ICMP_SGT:
1118 break; // no change.
1119 }
1120 ICI->replaceAllUsesWith(LV);
1121 ICI->eraseFromParent();
1122 }
1123 LI->eraseFromParent();
1124 }
Victor Hernandez83d63912009-09-18 22:35:49 +00001125
1126 // If the initialization boolean was used, insert it, otherwise delete it.
1127 if (!InitBoolUsed) {
1128 while (!InitBool->use_empty()) // Delete initializations
Chris Lattnera6874652010-02-25 22:33:52 +00001129 cast<StoreInst>(InitBool->use_back())->eraseFromParent();
Victor Hernandez83d63912009-09-18 22:35:49 +00001130 delete InitBool;
1131 } else
1132 GV->getParent()->getGlobalList().insert(GV, InitBool);
1133
Chris Lattnera6874652010-02-25 22:33:52 +00001134 // Now the GV is dead, nuke it and the malloc..
Victor Hernandez83d63912009-09-18 22:35:49 +00001135 GV->eraseFromParent();
Victor Hernandez83d63912009-09-18 22:35:49 +00001136 CI->eraseFromParent();
1137
1138 // To further other optimizations, loop over all users of NewGV and try to
1139 // constant prop them. This will promote GEP instructions with constant
1140 // indices into GEP constant-exprs, which will allow global-opt to hack on it.
Nick Lewycky6a577f82012-02-12 01:13:18 +00001141 ConstantPropUsersOf(NewGV, TD, TLI);
Victor Hernandez83d63912009-09-18 22:35:49 +00001142 if (RepValue != NewGV)
Nick Lewycky6a577f82012-02-12 01:13:18 +00001143 ConstantPropUsersOf(RepValue, TD, TLI);
Victor Hernandez83d63912009-09-18 22:35:49 +00001144
1145 return NewGV;
1146}
1147
Chris Lattnerfa07e4f2004-12-02 07:11:07 +00001148/// ValueIsOnlyUsedLocallyOrStoredToOneGlobal - Scan the use-list of V checking
1149/// to make sure that there are no complex uses of V. We permit simple things
1150/// like dereferencing the pointer, but not storing through the address, unless
1151/// it is to the specified global.
Gabor Greif0b520db2010-04-06 18:58:22 +00001152static bool ValueIsOnlyUsedLocallyOrStoredToOneGlobal(const Instruction *V,
1153 const GlobalVariable *GV,
Gabor Greifa01d6db2010-04-06 19:14:05 +00001154 SmallPtrSet<const PHINode*, 8> &PHIs) {
Gabor Greif0b520db2010-04-06 18:58:22 +00001155 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end();
Gabor Greifa01d6db2010-04-06 19:14:05 +00001156 UI != E; ++UI) {
Gabor Greif0b520db2010-04-06 18:58:22 +00001157 const Instruction *Inst = cast<Instruction>(*UI);
Gabor Greifa01d6db2010-04-06 19:14:05 +00001158
Chris Lattner49b6d4a2008-12-15 21:08:54 +00001159 if (isa<LoadInst>(Inst) || isa<CmpInst>(Inst)) {
1160 continue; // Fine, ignore.
1161 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001162
Gabor Greif0b520db2010-04-06 18:58:22 +00001163 if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
Chris Lattnerfa07e4f2004-12-02 07:11:07 +00001164 if (SI->getOperand(0) == V && SI->getOperand(1) != GV)
1165 return false; // Storing the pointer itself... bad.
Chris Lattner49b6d4a2008-12-15 21:08:54 +00001166 continue; // Otherwise, storing through it, or storing into GV... fine.
1167 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001168
Chris Lattnera2fb2342010-04-10 18:19:22 +00001169 // Must index into the array and into the struct.
1170 if (isa<GetElementPtrInst>(Inst) && Inst->getNumOperands() >= 3) {
Chris Lattner49b6d4a2008-12-15 21:08:54 +00001171 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(Inst, GV, PHIs))
Chris Lattnerfa07e4f2004-12-02 07:11:07 +00001172 return false;
Chris Lattner49b6d4a2008-12-15 21:08:54 +00001173 continue;
1174 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001175
Gabor Greif0b520db2010-04-06 18:58:22 +00001176 if (const PHINode *PN = dyn_cast<PHINode>(Inst)) {
Chris Lattnerc451f9c2007-09-13 16:37:20 +00001177 // PHIs are ok if all uses are ok. Don't infinitely recurse through PHI
1178 // cycles.
1179 if (PHIs.insert(PN))
Chris Lattner5e6e4942007-09-14 03:41:21 +00001180 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(PN, GV, PHIs))
1181 return false;
Chris Lattner49b6d4a2008-12-15 21:08:54 +00001182 continue;
Chris Lattnerfa07e4f2004-12-02 07:11:07 +00001183 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001184
Gabor Greif0b520db2010-04-06 18:58:22 +00001185 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Inst)) {
Chris Lattner49b6d4a2008-12-15 21:08:54 +00001186 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(BCI, GV, PHIs))
1187 return false;
1188 continue;
1189 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001190
Chris Lattner49b6d4a2008-12-15 21:08:54 +00001191 return false;
1192 }
Chris Lattnerfa07e4f2004-12-02 07:11:07 +00001193 return true;
Chris Lattnerfa07e4f2004-12-02 07:11:07 +00001194}
1195
Chris Lattner86395032006-09-30 23:32:09 +00001196/// ReplaceUsesOfMallocWithGlobal - The Alloc pointer is stored into GV
1197/// somewhere. Transform all uses of the allocation into loads from the
1198/// global and uses of the resultant pointer. Further, delete the store into
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001199/// GV. This assumes that these value pass the
Chris Lattner86395032006-09-30 23:32:09 +00001200/// 'ValueIsOnlyUsedLocallyOrStoredToOneGlobal' predicate.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001201static void ReplaceUsesOfMallocWithGlobal(Instruction *Alloc,
Chris Lattner86395032006-09-30 23:32:09 +00001202 GlobalVariable *GV) {
1203 while (!Alloc->use_empty()) {
Chris Lattnera637a8b2007-09-13 18:00:31 +00001204 Instruction *U = cast<Instruction>(*Alloc->use_begin());
1205 Instruction *InsertPt = U;
Chris Lattner86395032006-09-30 23:32:09 +00001206 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
1207 // If this is the store of the allocation into the global, remove it.
1208 if (SI->getOperand(1) == GV) {
1209 SI->eraseFromParent();
1210 continue;
1211 }
Chris Lattnera637a8b2007-09-13 18:00:31 +00001212 } else if (PHINode *PN = dyn_cast<PHINode>(U)) {
1213 // Insert the load in the corresponding predecessor, not right before the
1214 // PHI.
Gabor Greifa36791d2009-01-23 19:40:15 +00001215 InsertPt = PN->getIncomingBlock(Alloc->use_begin())->getTerminator();
Chris Lattner101f44e2008-12-15 21:44:34 +00001216 } else if (isa<BitCastInst>(U)) {
1217 // Must be bitcast between the malloc and store to initialize the global.
1218 ReplaceUsesOfMallocWithGlobal(U, GV);
1219 U->eraseFromParent();
1220 continue;
1221 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
1222 // If this is a "GEP bitcast" and the user is a store to the global, then
1223 // just process it as a bitcast.
1224 if (GEPI->hasAllZeroIndices() && GEPI->hasOneUse())
1225 if (StoreInst *SI = dyn_cast<StoreInst>(GEPI->use_back()))
1226 if (SI->getOperand(1) == GV) {
1227 // Must be bitcast GEP between the malloc and store to initialize
1228 // the global.
1229 ReplaceUsesOfMallocWithGlobal(GEPI, GV);
1230 GEPI->eraseFromParent();
1231 continue;
1232 }
Chris Lattner86395032006-09-30 23:32:09 +00001233 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001234
Chris Lattner86395032006-09-30 23:32:09 +00001235 // Insert a load from the global, and use it instead of the malloc.
Chris Lattnera637a8b2007-09-13 18:00:31 +00001236 Value *NL = new LoadInst(GV, GV->getName()+".val", InsertPt);
Chris Lattner86395032006-09-30 23:32:09 +00001237 U->replaceUsesOfWith(Alloc, NL);
1238 }
1239}
1240
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001241/// LoadUsesSimpleEnoughForHeapSRA - Verify that all uses of V (a load, or a phi
1242/// of a load) are simple enough to perform heap SRA on. This permits GEP's
1243/// that index through the array and struct field, icmps of null, and PHIs.
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001244static bool LoadUsesSimpleEnoughForHeapSRA(const Value *V,
Gabor Greif27236912010-04-07 18:59:26 +00001245 SmallPtrSet<const PHINode*, 32> &LoadUsingPHIs,
1246 SmallPtrSet<const PHINode*, 32> &LoadUsingPHIsPerLoad) {
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001247 // We permit two users of the load: setcc comparing against the null
1248 // pointer, and a getelementptr of a specific form.
Gabor Greif27236912010-04-07 18:59:26 +00001249 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;
1250 ++UI) {
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001251 const Instruction *User = cast<Instruction>(*UI);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001252
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001253 // Comparison against null is ok.
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001254 if (const ICmpInst *ICI = dyn_cast<ICmpInst>(User)) {
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001255 if (!isa<ConstantPointerNull>(ICI->getOperand(1)))
1256 return false;
1257 continue;
1258 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001259
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001260 // getelementptr is also ok, but only a simple form.
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001261 if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001262 // Must index into the array and into the struct.
1263 if (GEPI->getNumOperands() < 3)
1264 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001265
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001266 // Otherwise the GEP is ok.
1267 continue;
1268 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001269
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001270 if (const PHINode *PN = dyn_cast<PHINode>(User)) {
Evan Cheng5d163962009-06-02 00:56:07 +00001271 if (!LoadUsingPHIsPerLoad.insert(PN))
1272 // This means some phi nodes are dependent on each other.
1273 // Avoid infinite looping!
1274 return false;
1275 if (!LoadUsingPHIs.insert(PN))
1276 // If we have already analyzed this PHI, then it is safe.
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001277 continue;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001278
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001279 // Make sure all uses of the PHI are simple enough to transform.
Evan Cheng5d163962009-06-02 00:56:07 +00001280 if (!LoadUsesSimpleEnoughForHeapSRA(PN,
1281 LoadUsingPHIs, LoadUsingPHIsPerLoad))
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001282 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001283
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001284 continue;
Chris Lattner86395032006-09-30 23:32:09 +00001285 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001286
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001287 // Otherwise we don't know what this is, not ok.
1288 return false;
1289 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001290
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001291 return true;
1292}
1293
1294
1295/// AllGlobalLoadUsesSimpleEnoughForHeapSRA - If all users of values loaded from
1296/// GV are simple enough to perform HeapSRA, return true.
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001297static bool AllGlobalLoadUsesSimpleEnoughForHeapSRA(const GlobalVariable *GV,
Victor Hernandez83d63912009-09-18 22:35:49 +00001298 Instruction *StoredVal) {
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001299 SmallPtrSet<const PHINode*, 32> LoadUsingPHIs;
1300 SmallPtrSet<const PHINode*, 32> LoadUsingPHIsPerLoad;
Gabor Greif27236912010-04-07 18:59:26 +00001301 for (Value::const_use_iterator UI = GV->use_begin(), E = GV->use_end();
1302 UI != E; ++UI)
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001303 if (const LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
Evan Cheng5d163962009-06-02 00:56:07 +00001304 if (!LoadUsesSimpleEnoughForHeapSRA(LI, LoadUsingPHIs,
1305 LoadUsingPHIsPerLoad))
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001306 return false;
Evan Cheng5d163962009-06-02 00:56:07 +00001307 LoadUsingPHIsPerLoad.clear();
1308 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001309
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001310 // If we reach here, we know that all uses of the loads and transitive uses
1311 // (through PHI nodes) are simple enough to transform. However, we don't know
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001312 // that all inputs the to the PHI nodes are in the same equivalence sets.
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001313 // Check to verify that all operands of the PHIs are either PHIS that can be
1314 // transformed, loads from GV, or MI itself.
Gabor Greif27236912010-04-07 18:59:26 +00001315 for (SmallPtrSet<const PHINode*, 32>::const_iterator I = LoadUsingPHIs.begin()
1316 , E = LoadUsingPHIs.end(); I != E; ++I) {
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001317 const PHINode *PN = *I;
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001318 for (unsigned op = 0, e = PN->getNumIncomingValues(); op != e; ++op) {
1319 Value *InVal = PN->getIncomingValue(op);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001320
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001321 // PHI of the stored value itself is ok.
Victor Hernandez83d63912009-09-18 22:35:49 +00001322 if (InVal == StoredVal) continue;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001323
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001324 if (const PHINode *InPN = dyn_cast<PHINode>(InVal)) {
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001325 // One of the PHIs in our set is (optimistically) ok.
1326 if (LoadUsingPHIs.count(InPN))
1327 continue;
1328 return false;
1329 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001330
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001331 // Load from GV is ok.
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001332 if (const LoadInst *LI = dyn_cast<LoadInst>(InVal))
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001333 if (LI->getOperand(0) == GV)
1334 continue;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001335
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001336 // UNDEF? NULL?
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001337
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001338 // Anything else is rejected.
1339 return false;
1340 }
1341 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001342
Chris Lattner86395032006-09-30 23:32:09 +00001343 return true;
1344}
1345
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001346static Value *GetHeapSROAValue(Value *V, unsigned FieldNo,
1347 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001348 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001349 std::vector<Value*> &FieldVals = InsertedScalarizedValues[V];
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001350
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001351 if (FieldNo >= FieldVals.size())
1352 FieldVals.resize(FieldNo+1);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001353
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001354 // If we already have this value, just reuse the previously scalarized
1355 // version.
1356 if (Value *FieldVal = FieldVals[FieldNo])
1357 return FieldVal;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001358
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001359 // Depending on what instruction this is, we have several cases.
1360 Value *Result;
1361 if (LoadInst *LI = dyn_cast<LoadInst>(V)) {
1362 // This is a scalarized version of the load from the global. Just create
1363 // a new Load of the scalarized global.
1364 Result = new LoadInst(GetHeapSROAValue(LI->getOperand(0), FieldNo,
1365 InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001366 PHIsToRewrite),
Daniel Dunbarfe09b202009-07-30 17:37:43 +00001367 LI->getName()+".f"+Twine(FieldNo), LI);
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001368 } else if (PHINode *PN = dyn_cast<PHINode>(V)) {
1369 // PN's type is pointer to struct. Make a new PHI of pointer to struct
1370 // field.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001371 StructType *ST =
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001372 cast<StructType>(cast<PointerType>(PN->getType())->getElementType());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001373
Jay Foadd8b4fb42011-03-30 11:19:20 +00001374 PHINode *NewPN =
Owen Andersondebcb012009-07-29 22:17:13 +00001375 PHINode::Create(PointerType::getUnqual(ST->getElementType(FieldNo)),
Jay Foad3ecfc862011-03-30 11:28:46 +00001376 PN->getNumIncomingValues(),
Daniel Dunbarfe09b202009-07-30 17:37:43 +00001377 PN->getName()+".f"+Twine(FieldNo), PN);
Jay Foadd8b4fb42011-03-30 11:19:20 +00001378 Result = NewPN;
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001379 PHIsToRewrite.push_back(std::make_pair(PN, FieldNo));
1380 } else {
Torok Edwinc23197a2009-07-14 16:55:14 +00001381 llvm_unreachable("Unknown usable value");
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001382 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001383
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001384 return FieldVals[FieldNo] = Result;
Chris Lattnera637a8b2007-09-13 18:00:31 +00001385}
1386
Chris Lattner330245e2007-09-13 17:29:05 +00001387/// RewriteHeapSROALoadUser - Given a load instruction and a value derived from
1388/// the load, rewrite the derived value to use the HeapSRoA'd load.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001389static void RewriteHeapSROALoadUser(Instruction *LoadUser,
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001390 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001391 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
Chris Lattner330245e2007-09-13 17:29:05 +00001392 // If this is a comparison against null, handle it.
1393 if (ICmpInst *SCI = dyn_cast<ICmpInst>(LoadUser)) {
1394 assert(isa<ConstantPointerNull>(SCI->getOperand(1)));
1395 // If we have a setcc of the loaded pointer, we can use a setcc of any
1396 // field.
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001397 Value *NPtr = GetHeapSROAValue(SCI->getOperand(0), 0,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001398 InsertedScalarizedValues, PHIsToRewrite);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001399
Owen Anderson333c4002009-07-09 23:48:35 +00001400 Value *New = new ICmpInst(SCI, SCI->getPredicate(), NPtr,
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001401 Constant::getNullValue(NPtr->getType()),
Owen Anderson333c4002009-07-09 23:48:35 +00001402 SCI->getName());
Chris Lattner330245e2007-09-13 17:29:05 +00001403 SCI->replaceAllUsesWith(New);
1404 SCI->eraseFromParent();
1405 return;
1406 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001407
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001408 // Handle 'getelementptr Ptr, Idx, i32 FieldNo ...'
Chris Lattnera637a8b2007-09-13 18:00:31 +00001409 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(LoadUser)) {
1410 assert(GEPI->getNumOperands() >= 3 && isa<ConstantInt>(GEPI->getOperand(2))
1411 && "Unexpected GEPI!");
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001412
Chris Lattnera637a8b2007-09-13 18:00:31 +00001413 // Load the pointer for this field.
1414 unsigned FieldNo = cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue();
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001415 Value *NewPtr = GetHeapSROAValue(GEPI->getOperand(0), FieldNo,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001416 InsertedScalarizedValues, PHIsToRewrite);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001417
Chris Lattnera637a8b2007-09-13 18:00:31 +00001418 // Create the new GEP idx vector.
1419 SmallVector<Value*, 8> GEPIdx;
1420 GEPIdx.push_back(GEPI->getOperand(1));
1421 GEPIdx.append(GEPI->op_begin()+3, GEPI->op_end());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001422
Jay Foada9203102011-07-25 09:48:08 +00001423 Value *NGEPI = GetElementPtrInst::Create(NewPtr, GEPIdx,
Gabor Greif051a9502008-04-06 20:25:17 +00001424 GEPI->getName(), GEPI);
Chris Lattnera637a8b2007-09-13 18:00:31 +00001425 GEPI->replaceAllUsesWith(NGEPI);
1426 GEPI->eraseFromParent();
1427 return;
1428 }
Chris Lattner309f20f2007-09-13 21:31:36 +00001429
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001430 // Recursively transform the users of PHI nodes. This will lazily create the
1431 // PHIs that are needed for individual elements. Keep track of what PHIs we
1432 // see in InsertedScalarizedValues so that we don't get infinite loops (very
1433 // antisocial). If the PHI is already in InsertedScalarizedValues, it has
1434 // already been seen first by another load, so its uses have already been
1435 // processed.
1436 PHINode *PN = cast<PHINode>(LoadUser);
Chris Lattnerc30a38f2011-07-21 06:21:31 +00001437 if (!InsertedScalarizedValues.insert(std::make_pair(PN,
1438 std::vector<Value*>())).second)
1439 return;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001440
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001441 // If this is the first time we've seen this PHI, recursively process all
1442 // users.
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001443 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end(); UI != E; ) {
1444 Instruction *User = cast<Instruction>(*UI++);
Chris Lattner7b550cc2009-11-06 04:27:31 +00001445 RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite);
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001446 }
Chris Lattner330245e2007-09-13 17:29:05 +00001447}
1448
Chris Lattner86395032006-09-30 23:32:09 +00001449/// RewriteUsesOfLoadForHeapSRoA - We are performing Heap SRoA on a global. Ptr
1450/// is a value loaded from the global. Eliminate all uses of Ptr, making them
1451/// use FieldGlobals instead. All uses of loaded values satisfy
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001452/// AllGlobalLoadUsesSimpleEnoughForHeapSRA.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001453static void RewriteUsesOfLoadForHeapSRoA(LoadInst *Load,
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001454 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001455 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001456 for (Value::use_iterator UI = Load->use_begin(), E = Load->use_end();
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001457 UI != E; ) {
1458 Instruction *User = cast<Instruction>(*UI++);
Chris Lattner7b550cc2009-11-06 04:27:31 +00001459 RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite);
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001460 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001461
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001462 if (Load->use_empty()) {
1463 Load->eraseFromParent();
1464 InsertedScalarizedValues.erase(Load);
1465 }
Chris Lattner86395032006-09-30 23:32:09 +00001466}
1467
Victor Hernandez83d63912009-09-18 22:35:49 +00001468/// PerformHeapAllocSRoA - CI is an allocation of an array of structures. Break
1469/// it up into multiple allocations of arrays of the fields.
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001470static GlobalVariable *PerformHeapAllocSRoA(GlobalVariable *GV, CallInst *CI,
Micah Villmow3574eca2012-10-08 16:38:25 +00001471 Value *NElems, DataLayout *TD,
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +00001472 const TargetLibraryInfo *TLI) {
David Greene3215b0e2010-01-05 01:28:05 +00001473 DEBUG(dbgs() << "SROA HEAP ALLOC: " << *GV << " MALLOC = " << *CI << '\n');
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +00001474 Type *MAT = getMallocAllocatedType(CI, TLI);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001475 StructType *STy = cast<StructType>(MAT);
Victor Hernandez83d63912009-09-18 22:35:49 +00001476
1477 // There is guaranteed to be at least one use of the malloc (storing
1478 // it into GV). If there are other uses, change them to be uses of
1479 // the global to simplify later code. This also deletes the store
1480 // into GV.
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001481 ReplaceUsesOfMallocWithGlobal(CI, GV);
1482
Victor Hernandez83d63912009-09-18 22:35:49 +00001483 // Okay, at this point, there are no users of the malloc. Insert N
1484 // new mallocs at the same place as CI, and N globals.
1485 std::vector<Value*> FieldGlobals;
1486 std::vector<Value*> FieldMallocs;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001487
Victor Hernandez83d63912009-09-18 22:35:49 +00001488 for (unsigned FieldNo = 0, e = STy->getNumElements(); FieldNo != e;++FieldNo){
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001489 Type *FieldTy = STy->getElementType(FieldNo);
1490 PointerType *PFieldTy = PointerType::getUnqual(FieldTy);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001491
Victor Hernandez83d63912009-09-18 22:35:49 +00001492 GlobalVariable *NGV =
1493 new GlobalVariable(*GV->getParent(),
1494 PFieldTy, false, GlobalValue::InternalLinkage,
1495 Constant::getNullValue(PFieldTy),
1496 GV->getName() + ".f" + Twine(FieldNo), GV,
Hans Wennborgce718ff2012-06-23 11:37:03 +00001497 GV->getThreadLocalMode());
Victor Hernandez83d63912009-09-18 22:35:49 +00001498 FieldGlobals.push_back(NGV);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001499
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001500 unsigned TypeSize = TD->getTypeAllocSize(FieldTy);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001501 if (StructType *ST = dyn_cast<StructType>(FieldTy))
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001502 TypeSize = TD->getStructLayout(ST)->getSizeInBytes();
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001503 Type *IntPtrTy = TD->getIntPtrType(CI->getContext());
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001504 Value *NMI = CallInst::CreateMalloc(CI, IntPtrTy, FieldTy,
1505 ConstantInt::get(IntPtrTy, TypeSize),
Chris Lattner5a30a852010-07-12 00:57:28 +00001506 NElems, 0,
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001507 CI->getName() + ".f" + Twine(FieldNo));
Chris Lattner3f5e0b82010-02-26 18:23:13 +00001508 FieldMallocs.push_back(NMI);
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001509 new StoreInst(NMI, NGV, CI);
Victor Hernandez83d63912009-09-18 22:35:49 +00001510 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001511
Victor Hernandez83d63912009-09-18 22:35:49 +00001512 // The tricky aspect of this transformation is handling the case when malloc
1513 // fails. In the original code, malloc failing would set the result pointer
1514 // of malloc to null. In this case, some mallocs could succeed and others
1515 // could fail. As such, we emit code that looks like this:
1516 // F0 = malloc(field0)
1517 // F1 = malloc(field1)
1518 // F2 = malloc(field2)
1519 // if (F0 == 0 || F1 == 0 || F2 == 0) {
1520 // if (F0) { free(F0); F0 = 0; }
1521 // if (F1) { free(F1); F1 = 0; }
1522 // if (F2) { free(F2); F2 = 0; }
1523 // }
Victor Hernandez8e345a12009-11-10 08:32:25 +00001524 // The malloc can also fail if its argument is too large.
Gabor Greif9e4f2432010-06-24 14:42:01 +00001525 Constant *ConstantZero = ConstantInt::get(CI->getArgOperand(0)->getType(), 0);
1526 Value *RunningOr = new ICmpInst(CI, ICmpInst::ICMP_SLT, CI->getArgOperand(0),
Victor Hernandez8e345a12009-11-10 08:32:25 +00001527 ConstantZero, "isneg");
Victor Hernandez83d63912009-09-18 22:35:49 +00001528 for (unsigned i = 0, e = FieldMallocs.size(); i != e; ++i) {
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001529 Value *Cond = new ICmpInst(CI, ICmpInst::ICMP_EQ, FieldMallocs[i],
1530 Constant::getNullValue(FieldMallocs[i]->getType()),
1531 "isnull");
Victor Hernandez8e345a12009-11-10 08:32:25 +00001532 RunningOr = BinaryOperator::CreateOr(RunningOr, Cond, "tmp", CI);
Victor Hernandez83d63912009-09-18 22:35:49 +00001533 }
1534
1535 // Split the basic block at the old malloc.
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001536 BasicBlock *OrigBB = CI->getParent();
1537 BasicBlock *ContBB = OrigBB->splitBasicBlock(CI, "malloc_cont");
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001538
Victor Hernandez83d63912009-09-18 22:35:49 +00001539 // Create the block to check the first condition. Put all these blocks at the
1540 // end of the function as they are unlikely to be executed.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001541 BasicBlock *NullPtrBlock = BasicBlock::Create(OrigBB->getContext(),
1542 "malloc_ret_null",
Victor Hernandez83d63912009-09-18 22:35:49 +00001543 OrigBB->getParent());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001544
Victor Hernandez83d63912009-09-18 22:35:49 +00001545 // Remove the uncond branch from OrigBB to ContBB, turning it into a cond
1546 // branch on RunningOr.
1547 OrigBB->getTerminator()->eraseFromParent();
1548 BranchInst::Create(NullPtrBlock, ContBB, RunningOr, OrigBB);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001549
Victor Hernandez83d63912009-09-18 22:35:49 +00001550 // Within the NullPtrBlock, we need to emit a comparison and branch for each
1551 // pointer, because some may be null while others are not.
1552 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
1553 Value *GVVal = new LoadInst(FieldGlobals[i], "tmp", NullPtrBlock);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001554 Value *Cmp = new ICmpInst(*NullPtrBlock, ICmpInst::ICMP_NE, GVVal,
Benjamin Kramera9390a42011-09-27 20:39:19 +00001555 Constant::getNullValue(GVVal->getType()));
Chris Lattner7b550cc2009-11-06 04:27:31 +00001556 BasicBlock *FreeBlock = BasicBlock::Create(Cmp->getContext(), "free_it",
Victor Hernandez83d63912009-09-18 22:35:49 +00001557 OrigBB->getParent());
Chris Lattner7b550cc2009-11-06 04:27:31 +00001558 BasicBlock *NextBlock = BasicBlock::Create(Cmp->getContext(), "next",
Victor Hernandez83d63912009-09-18 22:35:49 +00001559 OrigBB->getParent());
Victor Hernandez66284e02009-10-24 04:23:03 +00001560 Instruction *BI = BranchInst::Create(FreeBlock, NextBlock,
1561 Cmp, NullPtrBlock);
Victor Hernandez83d63912009-09-18 22:35:49 +00001562
1563 // Fill in FreeBlock.
Victor Hernandez66284e02009-10-24 04:23:03 +00001564 CallInst::CreateFree(GVVal, BI);
Victor Hernandez83d63912009-09-18 22:35:49 +00001565 new StoreInst(Constant::getNullValue(GVVal->getType()), FieldGlobals[i],
1566 FreeBlock);
1567 BranchInst::Create(NextBlock, FreeBlock);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001568
Victor Hernandez83d63912009-09-18 22:35:49 +00001569 NullPtrBlock = NextBlock;
1570 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001571
Victor Hernandez83d63912009-09-18 22:35:49 +00001572 BranchInst::Create(ContBB, NullPtrBlock);
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001573
1574 // CI is no longer needed, remove it.
Victor Hernandez83d63912009-09-18 22:35:49 +00001575 CI->eraseFromParent();
1576
1577 /// InsertedScalarizedLoads - As we process loads, if we can't immediately
1578 /// update all uses of the load, keep track of what scalarized loads are
1579 /// inserted for a given load.
1580 DenseMap<Value*, std::vector<Value*> > InsertedScalarizedValues;
1581 InsertedScalarizedValues[GV] = FieldGlobals;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001582
Victor Hernandez83d63912009-09-18 22:35:49 +00001583 std::vector<std::pair<PHINode*, unsigned> > PHIsToRewrite;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001584
Victor Hernandez83d63912009-09-18 22:35:49 +00001585 // Okay, the malloc site is completely handled. All of the uses of GV are now
1586 // loads, and all uses of those loads are simple. Rewrite them to use loads
1587 // of the per-field globals instead.
1588 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI != E;) {
1589 Instruction *User = cast<Instruction>(*UI++);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001590
Victor Hernandez83d63912009-09-18 22:35:49 +00001591 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Chris Lattner7b550cc2009-11-06 04:27:31 +00001592 RewriteUsesOfLoadForHeapSRoA(LI, InsertedScalarizedValues, PHIsToRewrite);
Victor Hernandez83d63912009-09-18 22:35:49 +00001593 continue;
1594 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001595
Victor Hernandez83d63912009-09-18 22:35:49 +00001596 // Must be a store of null.
1597 StoreInst *SI = cast<StoreInst>(User);
1598 assert(isa<ConstantPointerNull>(SI->getOperand(0)) &&
1599 "Unexpected heap-sra user!");
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001600
Victor Hernandez83d63912009-09-18 22:35:49 +00001601 // Insert a store of null into each global.
1602 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001603 PointerType *PT = cast<PointerType>(FieldGlobals[i]->getType());
Victor Hernandez83d63912009-09-18 22:35:49 +00001604 Constant *Null = Constant::getNullValue(PT->getElementType());
1605 new StoreInst(Null, FieldGlobals[i], SI);
1606 }
1607 // Erase the original store.
1608 SI->eraseFromParent();
1609 }
1610
1611 // While we have PHIs that are interesting to rewrite, do it.
1612 while (!PHIsToRewrite.empty()) {
1613 PHINode *PN = PHIsToRewrite.back().first;
1614 unsigned FieldNo = PHIsToRewrite.back().second;
1615 PHIsToRewrite.pop_back();
1616 PHINode *FieldPN = cast<PHINode>(InsertedScalarizedValues[PN][FieldNo]);
1617 assert(FieldPN->getNumIncomingValues() == 0 &&"Already processed this phi");
1618
1619 // Add all the incoming values. This can materialize more phis.
1620 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1621 Value *InVal = PN->getIncomingValue(i);
1622 InVal = GetHeapSROAValue(InVal, FieldNo, InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001623 PHIsToRewrite);
Victor Hernandez83d63912009-09-18 22:35:49 +00001624 FieldPN->addIncoming(InVal, PN->getIncomingBlock(i));
1625 }
1626 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001627
Victor Hernandez83d63912009-09-18 22:35:49 +00001628 // Drop all inter-phi links and any loads that made it this far.
1629 for (DenseMap<Value*, std::vector<Value*> >::iterator
1630 I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
1631 I != E; ++I) {
1632 if (PHINode *PN = dyn_cast<PHINode>(I->first))
1633 PN->dropAllReferences();
1634 else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
1635 LI->dropAllReferences();
1636 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001637
Victor Hernandez83d63912009-09-18 22:35:49 +00001638 // Delete all the phis and loads now that inter-references are dead.
1639 for (DenseMap<Value*, std::vector<Value*> >::iterator
1640 I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
1641 I != E; ++I) {
1642 if (PHINode *PN = dyn_cast<PHINode>(I->first))
1643 PN->eraseFromParent();
1644 else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
1645 LI->eraseFromParent();
1646 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001647
Victor Hernandez83d63912009-09-18 22:35:49 +00001648 // The old global is now dead, remove it.
1649 GV->eraseFromParent();
1650
1651 ++NumHeapSRA;
1652 return cast<GlobalVariable>(FieldGlobals[0]);
1653}
1654
Chris Lattnere61d0a62008-12-15 21:02:25 +00001655/// TryToOptimizeStoreOfMallocToGlobal - This function is called when we see a
1656/// pointer global variable with a single value stored it that is a malloc or
1657/// cast of malloc.
1658static bool TryToOptimizeStoreOfMallocToGlobal(GlobalVariable *GV,
Victor Hernandez83d63912009-09-18 22:35:49 +00001659 CallInst *CI,
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001660 Type *AllocTy,
Nick Lewyckyfad4d402012-02-05 19:56:38 +00001661 AtomicOrdering Ordering,
Victor Hernandez83d63912009-09-18 22:35:49 +00001662 Module::global_iterator &GVI,
Micah Villmow3574eca2012-10-08 16:38:25 +00001663 DataLayout *TD,
Nick Lewycky6a577f82012-02-12 01:13:18 +00001664 TargetLibraryInfo *TLI) {
Evan Cheng86cd4452010-04-14 20:52:55 +00001665 if (!TD)
1666 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001667
Victor Hernandez83d63912009-09-18 22:35:49 +00001668 // If this is a malloc of an abstract type, don't touch it.
1669 if (!AllocTy->isSized())
1670 return false;
1671
1672 // We can't optimize this global unless all uses of it are *known* to be
1673 // of the malloc value, not of the null initializer value (consider a use
1674 // that compares the global's value against zero to see if the malloc has
1675 // been reached). To do this, we check to see if all uses of the global
1676 // would trap if the global were null: this proves that they must all
1677 // happen after the malloc.
1678 if (!AllUsesOfLoadedValueWillTrapIfNull(GV))
1679 return false;
1680
1681 // We can't optimize this if the malloc itself is used in a complex way,
1682 // for example, being stored into multiple globals. This allows the
Nick Lewyckybc384a12012-02-05 19:48:37 +00001683 // malloc to be stored into the specified global, loaded icmp'd, and
Victor Hernandez83d63912009-09-18 22:35:49 +00001684 // GEP'd. These are all things we could transform to using the global
1685 // for.
Evan Cheng86cd4452010-04-14 20:52:55 +00001686 SmallPtrSet<const PHINode*, 8> PHIs;
1687 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(CI, GV, PHIs))
1688 return false;
Victor Hernandez83d63912009-09-18 22:35:49 +00001689
1690 // If we have a global that is only initialized with a fixed size malloc,
1691 // transform the program to use global memory instead of malloc'd memory.
1692 // This eliminates dynamic allocation, avoids an indirection accessing the
1693 // data, and exposes the resultant global to further GlobalOpt.
Victor Hernandez8db42d22009-10-16 23:12:25 +00001694 // We cannot optimize the malloc if we cannot determine malloc array size.
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +00001695 Value *NElems = getMallocArraySize(CI, TD, TLI, true);
Evan Cheng86cd4452010-04-14 20:52:55 +00001696 if (!NElems)
1697 return false;
Victor Hernandez83d63912009-09-18 22:35:49 +00001698
Evan Cheng86cd4452010-04-14 20:52:55 +00001699 if (ConstantInt *NElements = dyn_cast<ConstantInt>(NElems))
1700 // Restrict this transformation to only working on small allocations
1701 // (2048 bytes currently), as we don't want to introduce a 16M global or
1702 // something.
1703 if (NElements->getZExtValue() * TD->getTypeAllocSize(AllocTy) < 2048) {
Nick Lewycky6a577f82012-02-12 01:13:18 +00001704 GVI = OptimizeGlobalAddressOfMalloc(GV, CI, AllocTy, NElements, TD, TLI);
Evan Cheng86cd4452010-04-14 20:52:55 +00001705 return true;
Victor Hernandez83d63912009-09-18 22:35:49 +00001706 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001707
Evan Cheng86cd4452010-04-14 20:52:55 +00001708 // If the allocation is an array of structures, consider transforming this
1709 // into multiple malloc'd arrays, one for each field. This is basically
1710 // SRoA for malloc'd memory.
1711
Nick Lewyckyfad4d402012-02-05 19:56:38 +00001712 if (Ordering != NotAtomic)
1713 return false;
1714
Evan Cheng86cd4452010-04-14 20:52:55 +00001715 // If this is an allocation of a fixed size array of structs, analyze as a
1716 // variable size array. malloc [100 x struct],1 -> malloc struct, 100
Gabor Greif9e4f2432010-06-24 14:42:01 +00001717 if (NElems == ConstantInt::get(CI->getArgOperand(0)->getType(), 1))
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001718 if (ArrayType *AT = dyn_cast<ArrayType>(AllocTy))
Evan Cheng86cd4452010-04-14 20:52:55 +00001719 AllocTy = AT->getElementType();
Gabor Greif9e4f2432010-06-24 14:42:01 +00001720
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001721 StructType *AllocSTy = dyn_cast<StructType>(AllocTy);
Evan Cheng86cd4452010-04-14 20:52:55 +00001722 if (!AllocSTy)
1723 return false;
1724
1725 // This the structure has an unreasonable number of fields, leave it
1726 // alone.
1727 if (AllocSTy->getNumElements() <= 16 && AllocSTy->getNumElements() != 0 &&
1728 AllGlobalLoadUsesSimpleEnoughForHeapSRA(GV, CI)) {
1729
1730 // If this is a fixed size array, transform the Malloc to be an alloc of
1731 // structs. malloc [100 x struct],1 -> malloc struct, 100
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +00001732 if (ArrayType *AT = dyn_cast<ArrayType>(getMallocAllocatedType(CI, TLI))) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001733 Type *IntPtrTy = TD->getIntPtrType(CI->getContext());
Evan Cheng86cd4452010-04-14 20:52:55 +00001734 unsigned TypeSize = TD->getStructLayout(AllocSTy)->getSizeInBytes();
1735 Value *AllocSize = ConstantInt::get(IntPtrTy, TypeSize);
1736 Value *NumElements = ConstantInt::get(IntPtrTy, AT->getNumElements());
1737 Instruction *Malloc = CallInst::CreateMalloc(CI, IntPtrTy, AllocSTy,
1738 AllocSize, NumElements,
Chris Lattner5a30a852010-07-12 00:57:28 +00001739 0, CI->getName());
Evan Cheng86cd4452010-04-14 20:52:55 +00001740 Instruction *Cast = new BitCastInst(Malloc, CI->getType(), "tmp", CI);
1741 CI->replaceAllUsesWith(Cast);
1742 CI->eraseFromParent();
Nuno Lopeseb7c6862012-06-22 00:25:01 +00001743 if (BitCastInst *BCI = dyn_cast<BitCastInst>(Malloc))
1744 CI = cast<CallInst>(BCI->getOperand(0));
1745 else
Nuno Lopescd88efe2012-06-22 00:29:58 +00001746 CI = cast<CallInst>(Malloc);
Evan Cheng86cd4452010-04-14 20:52:55 +00001747 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001748
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +00001749 GVI = PerformHeapAllocSRoA(GV, CI, getMallocArraySize(CI, TD, TLI, true),
1750 TD, TLI);
Evan Cheng86cd4452010-04-14 20:52:55 +00001751 return true;
Victor Hernandez83d63912009-09-18 22:35:49 +00001752 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001753
Victor Hernandez83d63912009-09-18 22:35:49 +00001754 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001755}
Victor Hernandez83d63912009-09-18 22:35:49 +00001756
Chris Lattner9b34a612004-10-09 21:48:45 +00001757// OptimizeOnceStoredGlobal - Try to optimize globals based on the knowledge
1758// that only one value (besides its initializer) is ever stored to the global.
Chris Lattner30ba5692004-10-11 05:54:41 +00001759static bool OptimizeOnceStoredGlobal(GlobalVariable *GV, Value *StoredOnceVal,
Nick Lewyckyfad4d402012-02-05 19:56:38 +00001760 AtomicOrdering Ordering,
Chris Lattner7f8897f2006-08-27 22:42:52 +00001761 Module::global_iterator &GVI,
Micah Villmow3574eca2012-10-08 16:38:25 +00001762 DataLayout *TD, TargetLibraryInfo *TLI) {
Chris Lattner344b41c2008-12-15 21:20:32 +00001763 // Ignore no-op GEPs and bitcasts.
1764 StoredOnceVal = StoredOnceVal->stripPointerCasts();
Chris Lattner9b34a612004-10-09 21:48:45 +00001765
Chris Lattner708148e2004-10-10 23:14:11 +00001766 // If we are dealing with a pointer global that is initialized to null and
1767 // only has one (non-null) value stored into it, then we can optimize any
1768 // users of the loaded value (often calls and loads) that would trap if the
1769 // value was null.
Duncan Sands1df98592010-02-16 11:11:14 +00001770 if (GV->getInitializer()->getType()->isPointerTy() &&
Chris Lattner9b34a612004-10-09 21:48:45 +00001771 GV->getInitializer()->isNullValue()) {
Chris Lattner708148e2004-10-10 23:14:11 +00001772 if (Constant *SOVC = dyn_cast<Constant>(StoredOnceVal)) {
1773 if (GV->getInitializer()->getType() != SOVC->getType())
Chris Lattner98a42b22011-05-22 07:15:13 +00001774 SOVC = ConstantExpr::getBitCast(SOVC, GV->getInitializer()->getType());
Misha Brukmanfd939082005-04-21 23:48:37 +00001775
Chris Lattner708148e2004-10-10 23:14:11 +00001776 // Optimize away any trapping uses of the loaded value.
Nick Lewycky6a577f82012-02-12 01:13:18 +00001777 if (OptimizeAwayTrappingUsesOfLoads(GV, SOVC, TD, TLI))
Chris Lattner8be80122004-10-10 17:07:12 +00001778 return true;
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +00001779 } else if (CallInst *CI = extractMallocCall(StoredOnceVal, TLI)) {
1780 Type *MallocType = getMallocAllocatedType(CI, TLI);
Nick Lewycky6a577f82012-02-12 01:13:18 +00001781 if (MallocType &&
1782 TryToOptimizeStoreOfMallocToGlobal(GV, CI, MallocType, Ordering, GVI,
1783 TD, TLI))
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001784 return true;
Chris Lattner708148e2004-10-10 23:14:11 +00001785 }
Chris Lattner9b34a612004-10-09 21:48:45 +00001786 }
Chris Lattner30ba5692004-10-11 05:54:41 +00001787
Chris Lattner9b34a612004-10-09 21:48:45 +00001788 return false;
1789}
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001790
Chris Lattner58e44f42008-01-14 01:17:44 +00001791/// TryToShrinkGlobalToBoolean - At this point, we have learned that the only
1792/// two values ever stored into GV are its initializer and OtherVal. See if we
1793/// can shrink the global into a boolean and select between the two values
1794/// whenever it is used. This exposes the values to other scalar optimizations.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001795static bool TryToShrinkGlobalToBoolean(GlobalVariable *GV, Constant *OtherVal) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001796 Type *GVElType = GV->getType()->getElementType();
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001797
Chris Lattner58e44f42008-01-14 01:17:44 +00001798 // If GVElType is already i1, it is already shrunk. If the type of the GV is
Chris Lattner6f6923f2009-03-07 23:32:02 +00001799 // an FP value, pointer or vector, don't do this optimization because a select
1800 // between them is very expensive and unlikely to lead to later
1801 // simplification. In these cases, we typically end up with "cond ? v1 : v2"
1802 // where v1 and v2 both require constant pool loads, a big loss.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001803 if (GVElType == Type::getInt1Ty(GV->getContext()) ||
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001804 GVElType->isFloatingPointTy() ||
Duncan Sands1df98592010-02-16 11:11:14 +00001805 GVElType->isPointerTy() || GVElType->isVectorTy())
Chris Lattner58e44f42008-01-14 01:17:44 +00001806 return false;
Gabor Greifaaaaa022010-07-12 14:13:15 +00001807
Chris Lattner58e44f42008-01-14 01:17:44 +00001808 // Walk the use list of the global seeing if all the uses are load or store.
1809 // If there is anything else, bail out.
Gabor Greifaaaaa022010-07-12 14:13:15 +00001810 for (Value::use_iterator I = GV->use_begin(), E = GV->use_end(); I != E; ++I){
1811 User *U = *I;
1812 if (!isa<LoadInst>(U) && !isa<StoreInst>(U))
Chris Lattner58e44f42008-01-14 01:17:44 +00001813 return false;
Gabor Greifaaaaa022010-07-12 14:13:15 +00001814 }
1815
David Greene3215b0e2010-01-05 01:28:05 +00001816 DEBUG(dbgs() << " *** SHRINKING TO BOOL: " << *GV);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001817
Chris Lattner96a86b22004-12-12 05:53:50 +00001818 // Create the new global, initializing it to false.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001819 GlobalVariable *NewGV = new GlobalVariable(Type::getInt1Ty(GV->getContext()),
1820 false,
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001821 GlobalValue::InternalLinkage,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001822 ConstantInt::getFalse(GV->getContext()),
Nick Lewycky0e670df2009-05-03 03:49:08 +00001823 GV->getName()+".b",
Hans Wennborgce718ff2012-06-23 11:37:03 +00001824 GV->getThreadLocalMode());
Chris Lattner96a86b22004-12-12 05:53:50 +00001825 GV->getParent()->getGlobalList().insert(GV, NewGV);
1826
1827 Constant *InitVal = GV->getInitializer();
Chris Lattner7b550cc2009-11-06 04:27:31 +00001828 assert(InitVal->getType() != Type::getInt1Ty(GV->getContext()) &&
Owen Anderson1d0be152009-08-13 21:58:54 +00001829 "No reason to shrink to bool!");
Chris Lattner96a86b22004-12-12 05:53:50 +00001830
1831 // If initialized to zero and storing one into the global, we can use a cast
1832 // instead of a select to synthesize the desired value.
1833 bool IsOneZero = false;
1834 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal))
Reid Spencercae57542007-03-02 00:28:52 +00001835 IsOneZero = InitVal->isNullValue() && CI->isOne();
Chris Lattner96a86b22004-12-12 05:53:50 +00001836
1837 while (!GV->use_empty()) {
Devang Patel771281f2009-03-06 01:39:36 +00001838 Instruction *UI = cast<Instruction>(GV->use_back());
1839 if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
Chris Lattner96a86b22004-12-12 05:53:50 +00001840 // Change the store into a boolean store.
1841 bool StoringOther = SI->getOperand(0) == OtherVal;
1842 // Only do this if we weren't storing a loaded value.
Chris Lattner38c25562004-12-12 19:34:41 +00001843 Value *StoreVal;
Chris Lattner96a86b22004-12-12 05:53:50 +00001844 if (StoringOther || SI->getOperand(0) == InitVal)
Chris Lattner7b550cc2009-11-06 04:27:31 +00001845 StoreVal = ConstantInt::get(Type::getInt1Ty(GV->getContext()),
1846 StoringOther);
Chris Lattner38c25562004-12-12 19:34:41 +00001847 else {
1848 // Otherwise, we are storing a previously loaded copy. To do this,
1849 // change the copy from copying the original value to just copying the
1850 // bool.
1851 Instruction *StoredVal = cast<Instruction>(SI->getOperand(0));
1852
Gabor Greif9e4f2432010-06-24 14:42:01 +00001853 // If we've already replaced the input, StoredVal will be a cast or
Chris Lattner38c25562004-12-12 19:34:41 +00001854 // select instruction. If not, it will be a load of the original
1855 // global.
1856 if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
1857 assert(LI->getOperand(0) == GV && "Not a copy!");
1858 // Insert a new load, to preserve the saved value.
Nick Lewyckyfad4d402012-02-05 19:56:38 +00001859 StoreVal = new LoadInst(NewGV, LI->getName()+".b", false, 0,
1860 LI->getOrdering(), LI->getSynchScope(), LI);
Chris Lattner38c25562004-12-12 19:34:41 +00001861 } else {
1862 assert((isa<CastInst>(StoredVal) || isa<SelectInst>(StoredVal)) &&
1863 "This is not a form that we understand!");
1864 StoreVal = StoredVal->getOperand(0);
1865 assert(isa<LoadInst>(StoreVal) && "Not a load of NewGV!");
1866 }
1867 }
Nick Lewyckyfad4d402012-02-05 19:56:38 +00001868 new StoreInst(StoreVal, NewGV, false, 0,
1869 SI->getOrdering(), SI->getSynchScope(), SI);
Devang Patel771281f2009-03-06 01:39:36 +00001870 } else {
Chris Lattner96a86b22004-12-12 05:53:50 +00001871 // Change the load into a load of bool then a select.
Devang Patel771281f2009-03-06 01:39:36 +00001872 LoadInst *LI = cast<LoadInst>(UI);
Nick Lewyckyfad4d402012-02-05 19:56:38 +00001873 LoadInst *NLI = new LoadInst(NewGV, LI->getName()+".b", false, 0,
1874 LI->getOrdering(), LI->getSynchScope(), LI);
Chris Lattner96a86b22004-12-12 05:53:50 +00001875 Value *NSI;
1876 if (IsOneZero)
Chris Lattner046800a2007-02-11 01:08:35 +00001877 NSI = new ZExtInst(NLI, LI->getType(), "", LI);
Misha Brukmanfd939082005-04-21 23:48:37 +00001878 else
Gabor Greif051a9502008-04-06 20:25:17 +00001879 NSI = SelectInst::Create(NLI, OtherVal, InitVal, "", LI);
Chris Lattner046800a2007-02-11 01:08:35 +00001880 NSI->takeName(LI);
Chris Lattner96a86b22004-12-12 05:53:50 +00001881 LI->replaceAllUsesWith(NSI);
Devang Patel771281f2009-03-06 01:39:36 +00001882 }
1883 UI->eraseFromParent();
Chris Lattner96a86b22004-12-12 05:53:50 +00001884 }
1885
1886 GV->eraseFromParent();
Chris Lattner58e44f42008-01-14 01:17:44 +00001887 return true;
Chris Lattner96a86b22004-12-12 05:53:50 +00001888}
1889
1890
Nick Lewyckydb292a62012-02-12 00:52:26 +00001891/// ProcessGlobal - Analyze the specified global variable and optimize it if
1892/// possible. If we make a change, return true.
Rafael Espindolac4440e32011-01-19 16:32:21 +00001893bool GlobalOpt::ProcessGlobal(GlobalVariable *GV,
1894 Module::global_iterator &GVI) {
Rafael Espindola03977292012-06-14 22:48:13 +00001895 if (!GV->isDiscardableIfUnused())
Rafael Espindolac4440e32011-01-19 16:32:21 +00001896 return false;
1897
1898 // Do more involved optimizations if the global is internal.
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001899 GV->removeDeadConstantUsers();
1900
1901 if (GV->use_empty()) {
David Greene3215b0e2010-01-05 01:28:05 +00001902 DEBUG(dbgs() << "GLOBAL DEAD: " << *GV);
Chris Lattner7a7ed022004-10-16 18:09:00 +00001903 GV->eraseFromParent();
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001904 ++NumDeleted;
1905 return true;
1906 }
1907
Rafael Espindola2f135d42012-06-15 18:00:24 +00001908 if (!GV->hasLocalLinkage())
1909 return false;
1910
Rafael Espindolac4440e32011-01-19 16:32:21 +00001911 SmallPtrSet<const PHINode*, 16> PHIUsers;
1912 GlobalStatus GS;
1913
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001914 if (AnalyzeGlobal(GV, GS, PHIUsers))
1915 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001916
Rafael Espindolac4440e32011-01-19 16:32:21 +00001917 if (!GS.isCompared && !GV->hasUnnamedAddr()) {
1918 GV->setUnnamedAddr(true);
1919 NumUnnamed++;
1920 }
1921
1922 if (GV->isConstant() || !GV->hasInitializer())
1923 return false;
1924
1925 return ProcessInternalGlobal(GV, GVI, PHIUsers, GS);
1926}
1927
1928/// ProcessInternalGlobal - Analyze the specified global variable and optimize
1929/// it if possible. If we make a change, return true.
1930bool GlobalOpt::ProcessInternalGlobal(GlobalVariable *GV,
1931 Module::global_iterator &GVI,
Nick Lewyckydb292a62012-02-12 00:52:26 +00001932 const SmallPtrSet<const PHINode*, 16> &PHIUsers,
Rafael Espindolac4440e32011-01-19 16:32:21 +00001933 const GlobalStatus &GS) {
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001934 // If this is a first class global and has only one accessing function
1935 // and this function is main (which we know is not recursive we can make
1936 // this global a local variable) we replace the global with a local alloca
1937 // in this function.
1938 //
1939 // NOTE: It doesn't make sense to promote non single-value types since we
1940 // are just replacing static memory to stack memory.
1941 //
1942 // If the global is in different address space, don't bring it to stack.
1943 if (!GS.HasMultipleAccessingFunctions &&
1944 GS.AccessingFunction && !GS.HasNonInstructionUser &&
1945 GV->getType()->getElementType()->isSingleValueType() &&
1946 GS.AccessingFunction->getName() == "main" &&
1947 GS.AccessingFunction->hasExternalLinkage() &&
1948 GV->getType()->getAddressSpace() == 0) {
1949 DEBUG(dbgs() << "LOCALIZING GLOBAL: " << *GV);
Nick Lewyckybc384a12012-02-05 19:48:37 +00001950 Instruction &FirstI = const_cast<Instruction&>(*GS.AccessingFunction
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001951 ->getEntryBlock().begin());
Nick Lewyckybc384a12012-02-05 19:48:37 +00001952 Type *ElemTy = GV->getType()->getElementType();
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001953 // FIXME: Pass Global's alignment when globals have alignment
Nick Lewyckybc384a12012-02-05 19:48:37 +00001954 AllocaInst *Alloca = new AllocaInst(ElemTy, NULL, GV->getName(), &FirstI);
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001955 if (!isa<UndefValue>(GV->getInitializer()))
1956 new StoreInst(GV->getInitializer(), Alloca, &FirstI);
Misha Brukmanfd939082005-04-21 23:48:37 +00001957
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001958 GV->replaceAllUsesWith(Alloca);
1959 GV->eraseFromParent();
1960 ++NumLocalized;
1961 return true;
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001962 }
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001963
1964 // If the global is never loaded (but may be stored to), it is dead.
1965 // Delete it now.
1966 if (!GS.isLoaded) {
1967 DEBUG(dbgs() << "GLOBAL NEVER LOADED: " << *GV);
1968
Nick Lewycky8899d5c2012-07-24 07:21:08 +00001969 bool Changed;
1970 if (isLeakCheckerRoot(GV)) {
1971 // Delete any constant stores to the global.
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +00001972 Changed = CleanupPointerRootUsers(GV, TLI);
Nick Lewycky8899d5c2012-07-24 07:21:08 +00001973 } else {
1974 // Delete any stores we can find to the global. We may not be able to
1975 // make it completely dead though.
1976 Changed = CleanupConstantGlobalUsers(GV, GV->getInitializer(), TD, TLI);
1977 }
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001978
1979 // If the global is dead now, delete it.
1980 if (GV->use_empty()) {
1981 GV->eraseFromParent();
1982 ++NumDeleted;
1983 Changed = true;
1984 }
1985 return Changed;
1986
1987 } else if (GS.StoredType <= GlobalStatus::isInitializerStored) {
1988 DEBUG(dbgs() << "MARKING CONSTANT: " << *GV);
1989 GV->setConstant(true);
1990
1991 // Clean up any obviously simplifiable users now.
Nick Lewycky6a577f82012-02-12 01:13:18 +00001992 CleanupConstantGlobalUsers(GV, GV->getInitializer(), TD, TLI);
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001993
1994 // If the global is dead now, just nuke it.
1995 if (GV->use_empty()) {
1996 DEBUG(dbgs() << " *** Marking constant allowed us to simplify "
1997 << "all users and delete global!\n");
1998 GV->eraseFromParent();
1999 ++NumDeleted;
2000 }
2001
2002 ++NumMarked;
2003 return true;
2004 } else if (!GV->getInitializer()->getType()->isSingleValueType()) {
Micah Villmow3574eca2012-10-08 16:38:25 +00002005 if (DataLayout *TD = getAnalysisIfAvailable<DataLayout>())
Rafael Espindoladaad56a2011-01-18 04:36:06 +00002006 if (GlobalVariable *FirstNewGV = SRAGlobal(GV, *TD)) {
2007 GVI = FirstNewGV; // Don't skip the newly produced globals!
2008 return true;
2009 }
2010 } else if (GS.StoredType == GlobalStatus::isStoredOnce) {
2011 // If the initial value for the global was an undef value, and if only
2012 // one other value was stored into it, we can just change the
2013 // initializer to be the stored value, then delete all stores to the
2014 // global. This allows us to mark it constant.
2015 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
2016 if (isa<UndefValue>(GV->getInitializer())) {
2017 // Change the initial value here.
2018 GV->setInitializer(SOVConstant);
2019
2020 // Clean up any obviously simplifiable users now.
Nick Lewycky6a577f82012-02-12 01:13:18 +00002021 CleanupConstantGlobalUsers(GV, GV->getInitializer(), TD, TLI);
Rafael Espindoladaad56a2011-01-18 04:36:06 +00002022
2023 if (GV->use_empty()) {
2024 DEBUG(dbgs() << " *** Substituting initializer allowed us to "
Nick Lewycky8899d5c2012-07-24 07:21:08 +00002025 << "simplify all users and delete global!\n");
Rafael Espindoladaad56a2011-01-18 04:36:06 +00002026 GV->eraseFromParent();
2027 ++NumDeleted;
2028 } else {
2029 GVI = GV;
2030 }
2031 ++NumSubstitute;
2032 return true;
2033 }
2034
2035 // Try to optimize globals based on the knowledge that only one value
2036 // (besides its initializer) is ever stored to the global.
Nick Lewyckyfad4d402012-02-05 19:56:38 +00002037 if (OptimizeOnceStoredGlobal(GV, GS.StoredOnceValue, GS.Ordering, GVI,
Nick Lewycky6a577f82012-02-12 01:13:18 +00002038 TD, TLI))
Rafael Espindoladaad56a2011-01-18 04:36:06 +00002039 return true;
2040
2041 // Otherwise, if the global was not a boolean, we can shrink it to be a
2042 // boolean.
2043 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
2044 if (TryToShrinkGlobalToBoolean(GV, SOVConstant)) {
2045 ++NumShrunkToBool;
2046 return true;
2047 }
2048 }
2049
Chris Lattnera4be1dc2004-10-08 20:59:28 +00002050 return false;
2051}
2052
Chris Lattnerfb217ad2005-05-08 22:18:06 +00002053/// ChangeCalleesToFastCall - Walk all of the direct calls of the specified
2054/// function, changing them to FastCC.
2055static void ChangeCalleesToFastCall(Function *F) {
2056 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
Jay Foadb7454fd2012-05-12 08:30:16 +00002057 if (isa<BlockAddress>(*UI))
2058 continue;
Duncan Sands548448a2008-02-18 17:32:13 +00002059 CallSite User(cast<Instruction>(*UI));
2060 User.setCallingConv(CallingConv::Fast);
Chris Lattnerfb217ad2005-05-08 22:18:06 +00002061 }
2062}
Chris Lattnera4be1dc2004-10-08 20:59:28 +00002063
Bill Wendling5886b7b2012-10-14 06:39:53 +00002064static AttrListPtr StripNest(LLVMContext &C, const AttrListPtr &Attrs) {
Bill Wendling702cc912012-10-15 20:35:56 +00002065 AttrBuilder B;
Bill Wendling7d2f2492012-10-10 07:36:45 +00002066 B.addAttribute(Attributes::Nest);
2067
Chris Lattner58d74912008-03-12 17:45:29 +00002068 for (unsigned i = 0, e = Attrs.getNumSlots(); i != e; ++i) {
Bill Wendling67658342012-10-09 07:45:08 +00002069 if (!Attrs.getSlot(i).Attrs.hasAttribute(Attributes::Nest))
Duncan Sands548448a2008-02-18 17:32:13 +00002070 continue;
2071
Duncan Sands548448a2008-02-18 17:32:13 +00002072 // There can be only one.
Bill Wendlingcb3de0b2012-10-15 04:46:55 +00002073 return Attrs.removeAttr(C, Attrs.getSlot(i).Index, Attributes::get(C, B));
Duncan Sands3d5378f2008-02-16 20:56:04 +00002074 }
2075
2076 return Attrs;
2077}
2078
2079static void RemoveNestAttribute(Function *F) {
Bill Wendling5886b7b2012-10-14 06:39:53 +00002080 F->setAttributes(StripNest(F->getContext(), F->getAttributes()));
Duncan Sands3d5378f2008-02-16 20:56:04 +00002081 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
Jay Foadb7454fd2012-05-12 08:30:16 +00002082 if (isa<BlockAddress>(*UI))
2083 continue;
Duncan Sands548448a2008-02-18 17:32:13 +00002084 CallSite User(cast<Instruction>(*UI));
Bill Wendling5886b7b2012-10-14 06:39:53 +00002085 User.setAttributes(StripNest(F->getContext(), User.getAttributes()));
Duncan Sands3d5378f2008-02-16 20:56:04 +00002086 }
2087}
2088
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002089bool GlobalOpt::OptimizeFunctions(Module &M) {
2090 bool Changed = false;
2091 // Optimize functions.
2092 for (Module::iterator FI = M.begin(), E = M.end(); FI != E; ) {
2093 Function *F = FI++;
Duncan Sandsfc5940d2009-03-06 10:21:56 +00002094 // Functions without names cannot be referenced outside this module.
2095 if (!F->hasName() && !F->isDeclaration())
2096 F->setLinkage(GlobalValue::InternalLinkage);
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002097 F->removeDeadConstantUsers();
Eli Friedmanc6633052011-10-20 05:23:42 +00002098 if (F->isDefTriviallyDead()) {
Chris Lattnerec4c7b92009-11-01 19:03:42 +00002099 F->eraseFromParent();
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002100 Changed = true;
2101 ++NumFnDeleted;
Rafael Espindolabb46f522009-01-15 20:18:42 +00002102 } else if (F->hasLocalLinkage()) {
Duncan Sands3d5378f2008-02-16 20:56:04 +00002103 if (F->getCallingConv() == CallingConv::C && !F->isVarArg() &&
Jay Foad757068f2009-06-10 08:41:11 +00002104 !F->hasAddressTaken()) {
Duncan Sands3d5378f2008-02-16 20:56:04 +00002105 // If this function has C calling conventions, is not a varargs
2106 // function, and is only called directly, promote it to use the Fast
2107 // calling convention.
2108 F->setCallingConv(CallingConv::Fast);
2109 ChangeCalleesToFastCall(F);
2110 ++NumFastCallFns;
2111 Changed = true;
2112 }
2113
Bill Wendling7d2f2492012-10-10 07:36:45 +00002114 if (F->getAttributes().hasAttrSomewhere(Attributes::Nest) &&
Jay Foad757068f2009-06-10 08:41:11 +00002115 !F->hasAddressTaken()) {
Duncan Sands3d5378f2008-02-16 20:56:04 +00002116 // The function is not used by a trampoline intrinsic, so it is safe
2117 // to remove the 'nest' attribute.
2118 RemoveNestAttribute(F);
2119 ++NumNestRemoved;
2120 Changed = true;
2121 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002122 }
2123 }
2124 return Changed;
2125}
2126
2127bool GlobalOpt::OptimizeGlobalVars(Module &M) {
2128 bool Changed = false;
2129 for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
2130 GVI != E; ) {
2131 GlobalVariable *GV = GVI++;
Duncan Sandsfc5940d2009-03-06 10:21:56 +00002132 // Global variables without names cannot be referenced outside this module.
2133 if (!GV->hasName() && !GV->isDeclaration())
2134 GV->setLinkage(GlobalValue::InternalLinkage);
Dan Gohman01b97dd2009-11-23 16:22:21 +00002135 // Simplify the initializer.
2136 if (GV->hasInitializer())
2137 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GV->getInitializer())) {
Chad Rosieraab8e282011-12-02 01:26:24 +00002138 Constant *New = ConstantFoldConstantExpression(CE, TD, TLI);
Dan Gohman01b97dd2009-11-23 16:22:21 +00002139 if (New && New != CE)
2140 GV->setInitializer(New);
2141 }
Rafael Espindolac4440e32011-01-19 16:32:21 +00002142
2143 Changed |= ProcessGlobal(GV, GVI);
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002144 }
2145 return Changed;
2146}
2147
Nick Lewycky2c44a802011-04-08 07:30:21 +00002148/// FindGlobalCtors - Find the llvm.global_ctors list, verifying that all
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002149/// initializers have an init priority of 65535.
2150GlobalVariable *GlobalOpt::FindGlobalCtors(Module &M) {
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00002151 GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
2152 if (GV == 0) return 0;
2153
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00002154 // Verify that the initializer is simple enough for us to handle. We are
2155 // only allowed to optimize the initializer if it is unique.
2156 if (!GV->hasUniqueInitializer()) return 0;
Nick Lewycky5ea5c612011-04-11 22:11:20 +00002157
2158 if (isa<ConstantAggregateZero>(GV->getInitializer()))
2159 return GV;
2160 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
Eli Friedman18a2e502011-04-09 09:11:09 +00002161
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00002162 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i) {
Nick Lewycky5ea5c612011-04-11 22:11:20 +00002163 if (isa<ConstantAggregateZero>(*i))
2164 continue;
2165 ConstantStruct *CS = cast<ConstantStruct>(*i);
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00002166 if (isa<ConstantPointerNull>(CS->getOperand(1)))
2167 continue;
Chris Lattner7d8e58f2005-09-26 02:19:27 +00002168
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00002169 // Must have a function or null ptr.
2170 if (!isa<Function>(CS->getOperand(1)))
2171 return 0;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002172
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00002173 // Init priority must be standard.
Nick Lewycky2c44a802011-04-08 07:30:21 +00002174 ConstantInt *CI = cast<ConstantInt>(CS->getOperand(0));
2175 if (CI->getZExtValue() != 65535)
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00002176 return 0;
2177 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002178
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00002179 return GV;
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002180}
2181
Chris Lattnerdb973e62005-09-26 02:31:18 +00002182/// ParseGlobalCtors - Given a llvm.global_ctors list that we can understand,
2183/// return a list of the functions and null terminator as a vector.
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002184static std::vector<Function*> ParseGlobalCtors(GlobalVariable *GV) {
Nick Lewycky5ea5c612011-04-11 22:11:20 +00002185 if (GV->getInitializer()->isNullValue())
2186 return std::vector<Function*>();
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002187 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
2188 std::vector<Function*> Result;
2189 Result.reserve(CA->getNumOperands());
Gabor Greif5e463212008-05-29 01:59:18 +00002190 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i) {
2191 ConstantStruct *CS = cast<ConstantStruct>(*i);
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002192 Result.push_back(dyn_cast<Function>(CS->getOperand(1)));
2193 }
2194 return Result;
2195}
2196
Chris Lattnerdb973e62005-09-26 02:31:18 +00002197/// InstallGlobalCtors - Given a specified llvm.global_ctors list, install the
2198/// specified array, returning the new global to use.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002199static GlobalVariable *InstallGlobalCtors(GlobalVariable *GCL,
Chris Lattner7b550cc2009-11-06 04:27:31 +00002200 const std::vector<Function*> &Ctors) {
Chris Lattnerdb973e62005-09-26 02:31:18 +00002201 // If we made a change, reassemble the initializer list.
Chris Lattnerb065b062011-06-20 04:01:31 +00002202 Constant *CSVals[2];
2203 CSVals[0] = ConstantInt::get(Type::getInt32Ty(GCL->getContext()), 65535);
2204 CSVals[1] = 0;
2205
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002206 StructType *StructTy =
Chris Lattnerb065b062011-06-20 04:01:31 +00002207 cast <StructType>(
2208 cast<ArrayType>(GCL->getType()->getElementType())->getElementType());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002209
Chris Lattnerdb973e62005-09-26 02:31:18 +00002210 // Create the new init list.
2211 std::vector<Constant*> CAList;
2212 for (unsigned i = 0, e = Ctors.size(); i != e; ++i) {
Chris Lattner79c11012005-09-26 04:44:35 +00002213 if (Ctors[i]) {
Chris Lattnerdb973e62005-09-26 02:31:18 +00002214 CSVals[1] = Ctors[i];
Chris Lattner79c11012005-09-26 04:44:35 +00002215 } else {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002216 Type *FTy = FunctionType::get(Type::getVoidTy(GCL->getContext()),
Chris Lattner7b550cc2009-11-06 04:27:31 +00002217 false);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002218 PointerType *PFTy = PointerType::getUnqual(FTy);
Owen Andersona7235ea2009-07-31 20:28:14 +00002219 CSVals[1] = Constant::getNullValue(PFTy);
Chris Lattner7b550cc2009-11-06 04:27:31 +00002220 CSVals[0] = ConstantInt::get(Type::getInt32Ty(GCL->getContext()),
Nick Lewycky5ea5c612011-04-11 22:11:20 +00002221 0x7fffffff);
Chris Lattnerdb973e62005-09-26 02:31:18 +00002222 }
Chris Lattnerb065b062011-06-20 04:01:31 +00002223 CAList.push_back(ConstantStruct::get(StructTy, CSVals));
Chris Lattnerdb973e62005-09-26 02:31:18 +00002224 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002225
Chris Lattnerdb973e62005-09-26 02:31:18 +00002226 // Create the array initializer.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002227 Constant *CA = ConstantArray::get(ArrayType::get(StructTy,
Nick Lewyckyc332fba2009-09-19 20:30:26 +00002228 CAList.size()), CAList);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002229
Chris Lattnerdb973e62005-09-26 02:31:18 +00002230 // If we didn't change the number of elements, don't create a new GV.
2231 if (CA->getType() == GCL->getInitializer()->getType()) {
2232 GCL->setInitializer(CA);
2233 return GCL;
2234 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002235
Chris Lattnerdb973e62005-09-26 02:31:18 +00002236 // Create the new global and insert it next to the existing list.
Chris Lattner7b550cc2009-11-06 04:27:31 +00002237 GlobalVariable *NGV = new GlobalVariable(CA->getType(), GCL->isConstant(),
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +00002238 GCL->getLinkage(), CA, "",
Hans Wennborgce718ff2012-06-23 11:37:03 +00002239 GCL->getThreadLocalMode());
Chris Lattnerdb973e62005-09-26 02:31:18 +00002240 GCL->getParent()->getGlobalList().insert(GCL, NGV);
Chris Lattner046800a2007-02-11 01:08:35 +00002241 NGV->takeName(GCL);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002242
Chris Lattnerdb973e62005-09-26 02:31:18 +00002243 // Nuke the old list, replacing any uses with the new one.
2244 if (!GCL->use_empty()) {
2245 Constant *V = NGV;
2246 if (V->getType() != GCL->getType())
Owen Andersonbaf3c402009-07-29 18:55:55 +00002247 V = ConstantExpr::getBitCast(V, GCL->getType());
Chris Lattnerdb973e62005-09-26 02:31:18 +00002248 GCL->replaceAllUsesWith(V);
2249 }
2250 GCL->eraseFromParent();
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002251
Chris Lattnerdb973e62005-09-26 02:31:18 +00002252 if (Ctors.size())
2253 return NGV;
2254 else
2255 return 0;
2256}
Chris Lattner79c11012005-09-26 04:44:35 +00002257
2258
Chris Lattner1945d582010-12-07 04:33:29 +00002259static inline bool
2260isSimpleEnoughValueToCommit(Constant *C,
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002261 SmallPtrSet<Constant*, 8> &SimpleConstants,
Micah Villmow3574eca2012-10-08 16:38:25 +00002262 const DataLayout *TD);
Chris Lattner1945d582010-12-07 04:33:29 +00002263
2264
2265/// isSimpleEnoughValueToCommit - Return true if the specified constant can be
2266/// handled by the code generator. We don't want to generate something like:
2267/// void *X = &X/42;
2268/// because the code generator doesn't have a relocation that can handle that.
2269///
2270/// This function should be called if C was not found (but just got inserted)
2271/// in SimpleConstants to avoid having to rescan the same constants all the
2272/// time.
2273static bool isSimpleEnoughValueToCommitHelper(Constant *C,
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002274 SmallPtrSet<Constant*, 8> &SimpleConstants,
Micah Villmow3574eca2012-10-08 16:38:25 +00002275 const DataLayout *TD) {
Chris Lattner1945d582010-12-07 04:33:29 +00002276 // Simple integer, undef, constant aggregate zero, global addresses, etc are
2277 // all supported.
2278 if (C->getNumOperands() == 0 || isa<BlockAddress>(C) ||
2279 isa<GlobalValue>(C))
2280 return true;
2281
2282 // Aggregate values are safe if all their elements are.
2283 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C) ||
2284 isa<ConstantVector>(C)) {
2285 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i) {
2286 Constant *Op = cast<Constant>(C->getOperand(i));
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002287 if (!isSimpleEnoughValueToCommit(Op, SimpleConstants, TD))
Chris Lattner1945d582010-12-07 04:33:29 +00002288 return false;
2289 }
2290 return true;
2291 }
2292
2293 // We don't know exactly what relocations are allowed in constant expressions,
2294 // so we allow &global+constantoffset, which is safe and uniformly supported
2295 // across targets.
2296 ConstantExpr *CE = cast<ConstantExpr>(C);
2297 switch (CE->getOpcode()) {
2298 case Instruction::BitCast:
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002299 // Bitcast is fine if the casted value is fine.
2300 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, TD);
2301
Chris Lattner1945d582010-12-07 04:33:29 +00002302 case Instruction::IntToPtr:
2303 case Instruction::PtrToInt:
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002304 // int <=> ptr is fine if the int type is the same size as the
2305 // pointer type.
2306 if (!TD || TD->getTypeSizeInBits(CE->getType()) !=
2307 TD->getTypeSizeInBits(CE->getOperand(0)->getType()))
2308 return false;
2309 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, TD);
Chris Lattner1945d582010-12-07 04:33:29 +00002310
2311 // GEP is fine if it is simple + constant offset.
2312 case Instruction::GetElementPtr:
2313 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
2314 if (!isa<ConstantInt>(CE->getOperand(i)))
2315 return false;
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002316 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, TD);
Chris Lattner1945d582010-12-07 04:33:29 +00002317
2318 case Instruction::Add:
2319 // We allow simple+cst.
2320 if (!isa<ConstantInt>(CE->getOperand(1)))
2321 return false;
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002322 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, TD);
Chris Lattner1945d582010-12-07 04:33:29 +00002323 }
2324 return false;
2325}
2326
2327static inline bool
2328isSimpleEnoughValueToCommit(Constant *C,
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002329 SmallPtrSet<Constant*, 8> &SimpleConstants,
Micah Villmow3574eca2012-10-08 16:38:25 +00002330 const DataLayout *TD) {
Chris Lattner1945d582010-12-07 04:33:29 +00002331 // If we already checked this constant, we win.
2332 if (!SimpleConstants.insert(C)) return true;
2333 // Check the constant.
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002334 return isSimpleEnoughValueToCommitHelper(C, SimpleConstants, TD);
Chris Lattner1945d582010-12-07 04:33:29 +00002335}
2336
2337
Chris Lattner79c11012005-09-26 04:44:35 +00002338/// isSimpleEnoughPointerToCommit - Return true if this constant is simple
Owen Andersoncff6b372011-01-14 22:19:20 +00002339/// enough for us to understand. In particular, if it is a cast to anything
2340/// other than from one pointer type to another pointer type, we punt.
2341/// We basically just support direct accesses to globals and GEP's of
Chris Lattner79c11012005-09-26 04:44:35 +00002342/// globals. This should be kept up to date with CommitValueTo.
Chris Lattner7b550cc2009-11-06 04:27:31 +00002343static bool isSimpleEnoughPointerToCommit(Constant *C) {
Dan Gohmance5de5b2009-09-07 22:42:05 +00002344 // Conservatively, avoid aggregate types. This is because we don't
2345 // want to worry about them partially overlapping other stores.
2346 if (!cast<PointerType>(C->getType())->getElementType()->isSingleValueType())
2347 return false;
2348
Dan Gohmanfd54a892009-09-07 22:31:26 +00002349 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
Mikhail Glushenkov99fca5d2010-10-19 16:47:23 +00002350 // Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or
Dan Gohmanfd54a892009-09-07 22:31:26 +00002351 // external globals.
Mikhail Glushenkov99fca5d2010-10-19 16:47:23 +00002352 return GV->hasUniqueInitializer();
Dan Gohmanfd54a892009-09-07 22:31:26 +00002353
Owen Andersone95a32c2011-01-14 22:31:13 +00002354 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002355 // Handle a constantexpr gep.
2356 if (CE->getOpcode() == Instruction::GetElementPtr &&
Dan Gohmanc62482d2009-09-07 22:40:13 +00002357 isa<GlobalVariable>(CE->getOperand(0)) &&
2358 cast<GEPOperator>(CE)->isInBounds()) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002359 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
Mikhail Glushenkov99fca5d2010-10-19 16:47:23 +00002360 // Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or
Dan Gohmanfd54a892009-09-07 22:31:26 +00002361 // external globals.
Mikhail Glushenkov99fca5d2010-10-19 16:47:23 +00002362 if (!GV->hasUniqueInitializer())
Dan Gohmanfd54a892009-09-07 22:31:26 +00002363 return false;
Dan Gohman80bdc962009-09-07 22:44:55 +00002364
Dan Gohman80bdc962009-09-07 22:44:55 +00002365 // The first index must be zero.
Oscar Fuentesee56c422010-08-02 06:00:15 +00002366 ConstantInt *CI = dyn_cast<ConstantInt>(*llvm::next(CE->op_begin()));
Dan Gohman80bdc962009-09-07 22:44:55 +00002367 if (!CI || !CI->isZero()) return false;
Dan Gohman80bdc962009-09-07 22:44:55 +00002368
2369 // The remaining indices must be compile-time known integers within the
Dan Gohmane6992f72009-09-10 23:37:55 +00002370 // notional bounds of the corresponding static array types.
2371 if (!CE->isGEPWithNoNotionalOverIndexing())
2372 return false;
Dan Gohman80bdc962009-09-07 22:44:55 +00002373
Dan Gohmanc6f69e92009-10-05 16:36:26 +00002374 return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
Owen Andersoncff6b372011-01-14 22:19:20 +00002375
2376 // A constantexpr bitcast from a pointer to another pointer is a no-op,
2377 // and we know how to evaluate it by moving the bitcast from the pointer
2378 // operand to the value operand.
2379 } else if (CE->getOpcode() == Instruction::BitCast &&
Chris Lattnerd5f656f2011-01-16 02:05:10 +00002380 isa<GlobalVariable>(CE->getOperand(0))) {
Owen Andersoncff6b372011-01-14 22:19:20 +00002381 // Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or
2382 // external globals.
Chris Lattnerd5f656f2011-01-16 02:05:10 +00002383 return cast<GlobalVariable>(CE->getOperand(0))->hasUniqueInitializer();
Chris Lattner798b4d52005-09-26 06:52:44 +00002384 }
Owen Andersone95a32c2011-01-14 22:31:13 +00002385 }
2386
Chris Lattner79c11012005-09-26 04:44:35 +00002387 return false;
2388}
2389
Chris Lattner798b4d52005-09-26 06:52:44 +00002390/// EvaluateStoreInto - Evaluate a piece of a constantexpr store into a global
2391/// initializer. This returns 'Init' modified to reflect 'Val' stored into it.
2392/// At this point, the GEP operands of Addr [0, OpNo) have been stepped into.
2393static Constant *EvaluateStoreInto(Constant *Init, Constant *Val,
Chris Lattner7b550cc2009-11-06 04:27:31 +00002394 ConstantExpr *Addr, unsigned OpNo) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002395 // Base case of the recursion.
2396 if (OpNo == Addr->getNumOperands()) {
2397 assert(Val->getType() == Init->getType() && "Type mismatch!");
2398 return Val;
2399 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002400
Chris Lattnera78fa8c2012-01-27 03:08:05 +00002401 SmallVector<Constant*, 32> Elts;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002402 if (StructType *STy = dyn_cast<StructType>(Init->getType())) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002403 // Break up the constant into its elements.
Chris Lattnerd59ae902012-01-26 02:32:04 +00002404 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
2405 Elts.push_back(Init->getAggregateElement(i));
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002406
Chris Lattner798b4d52005-09-26 06:52:44 +00002407 // Replace the element that we are supposed to.
Reid Spencerb83eb642006-10-20 07:07:24 +00002408 ConstantInt *CU = cast<ConstantInt>(Addr->getOperand(OpNo));
2409 unsigned Idx = CU->getZExtValue();
2410 assert(Idx < STy->getNumElements() && "Struct index out of range!");
Chris Lattner7b550cc2009-11-06 04:27:31 +00002411 Elts[Idx] = EvaluateStoreInto(Elts[Idx], Val, Addr, OpNo+1);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002412
Chris Lattner798b4d52005-09-26 06:52:44 +00002413 // Return the modified struct.
Chris Lattnerb065b062011-06-20 04:01:31 +00002414 return ConstantStruct::get(STy, Elts);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002415 }
Chris Lattnerb065b062011-06-20 04:01:31 +00002416
2417 ConstantInt *CI = cast<ConstantInt>(Addr->getOperand(OpNo));
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002418 SequentialType *InitTy = cast<SequentialType>(Init->getType());
Chris Lattnerb065b062011-06-20 04:01:31 +00002419
2420 uint64_t NumElts;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002421 if (ArrayType *ATy = dyn_cast<ArrayType>(InitTy))
Chris Lattnerb065b062011-06-20 04:01:31 +00002422 NumElts = ATy->getNumElements();
2423 else
Chris Lattnerd59ae902012-01-26 02:32:04 +00002424 NumElts = InitTy->getVectorNumElements();
Chris Lattnerb065b062011-06-20 04:01:31 +00002425
2426 // Break up the array into elements.
Chris Lattnerd59ae902012-01-26 02:32:04 +00002427 for (uint64_t i = 0, e = NumElts; i != e; ++i)
2428 Elts.push_back(Init->getAggregateElement(i));
Chris Lattnerb065b062011-06-20 04:01:31 +00002429
2430 assert(CI->getZExtValue() < NumElts);
2431 Elts[CI->getZExtValue()] =
2432 EvaluateStoreInto(Elts[CI->getZExtValue()], Val, Addr, OpNo+1);
2433
2434 if (Init->getType()->isArrayTy())
2435 return ConstantArray::get(cast<ArrayType>(InitTy), Elts);
2436 return ConstantVector::get(Elts);
Chris Lattner798b4d52005-09-26 06:52:44 +00002437}
2438
Chris Lattner79c11012005-09-26 04:44:35 +00002439/// CommitValueTo - We have decided that Addr (which satisfies the predicate
2440/// isSimpleEnoughPointerToCommit) should get Val as its value. Make it happen.
Chris Lattner7b550cc2009-11-06 04:27:31 +00002441static void CommitValueTo(Constant *Val, Constant *Addr) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002442 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Addr)) {
2443 assert(GV->hasInitializer());
2444 GV->setInitializer(Val);
2445 return;
2446 }
Chris Lattnera0e9a242010-01-07 01:16:21 +00002447
Chris Lattner798b4d52005-09-26 06:52:44 +00002448 ConstantExpr *CE = cast<ConstantExpr>(Addr);
2449 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
Chris Lattnera0e9a242010-01-07 01:16:21 +00002450 GV->setInitializer(EvaluateStoreInto(GV->getInitializer(), Val, CE, 2));
Chris Lattner79c11012005-09-26 04:44:35 +00002451}
2452
Nick Lewycky7fa76772012-02-20 03:25:59 +00002453namespace {
2454
2455/// Evaluator - This class evaluates LLVM IR, producing the Constant
2456/// representing each SSA instruction. Changes to global variables are stored
2457/// in a mapping that can be iterated over after the evaluation is complete.
2458/// Once an evaluation call fails, the evaluation object should not be reused.
2459class Evaluator {
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002460public:
Micah Villmow3574eca2012-10-08 16:38:25 +00002461 Evaluator(const DataLayout *TD, const TargetLibraryInfo *TLI)
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002462 : TD(TD), TLI(TLI) {
2463 ValueStack.push_back(new DenseMap<Value*, Constant*>);
2464 }
2465
Nick Lewycky7fa76772012-02-20 03:25:59 +00002466 ~Evaluator() {
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002467 DeleteContainerPointers(ValueStack);
2468 while (!AllocaTmps.empty()) {
2469 GlobalVariable *Tmp = AllocaTmps.back();
2470 AllocaTmps.pop_back();
2471
2472 // If there are still users of the alloca, the program is doing something
2473 // silly, e.g. storing the address of the alloca somewhere and using it
2474 // later. Since this is undefined, we'll just make it be null.
2475 if (!Tmp->use_empty())
2476 Tmp->replaceAllUsesWith(Constant::getNullValue(Tmp->getType()));
2477 delete Tmp;
2478 }
2479 }
2480
2481 /// EvaluateFunction - Evaluate a call to function F, returning true if
2482 /// successful, false if we can't evaluate it. ActualArgs contains the formal
2483 /// arguments for the function.
2484 bool EvaluateFunction(Function *F, Constant *&RetVal,
2485 const SmallVectorImpl<Constant*> &ActualArgs);
2486
2487 /// EvaluateBlock - Evaluate all instructions in block BB, returning true if
2488 /// successful, false if we can't evaluate it. NewBB returns the next BB that
2489 /// control flows into, or null upon return.
2490 bool EvaluateBlock(BasicBlock::iterator CurInst, BasicBlock *&NextBB);
2491
2492 Constant *getVal(Value *V) {
2493 if (Constant *CV = dyn_cast<Constant>(V)) return CV;
2494 Constant *R = ValueStack.back()->lookup(V);
2495 assert(R && "Reference to an uncomputed value!");
2496 return R;
2497 }
2498
2499 void setVal(Value *V, Constant *C) {
2500 ValueStack.back()->operator[](V) = C;
2501 }
2502
2503 const DenseMap<Constant*, Constant*> &getMutatedMemory() const {
2504 return MutatedMemory;
2505 }
2506
2507 const SmallPtrSet<GlobalVariable*, 8> &getInvariants() const {
2508 return Invariants;
2509 }
2510
2511private:
2512 Constant *ComputeLoadResult(Constant *P);
2513
2514 /// ValueStack - As we compute SSA register values, we store their contents
2515 /// here. The back of the vector contains the current function and the stack
2516 /// contains the values in the calling frames.
2517 SmallVector<DenseMap<Value*, Constant*>*, 4> ValueStack;
2518
2519 /// CallStack - This is used to detect recursion. In pathological situations
2520 /// we could hit exponential behavior, but at least there is nothing
2521 /// unbounded.
2522 SmallVector<Function*, 4> CallStack;
2523
2524 /// MutatedMemory - For each store we execute, we update this map. Loads
2525 /// check this to get the most up-to-date value. If evaluation is successful,
2526 /// this state is committed to the process.
2527 DenseMap<Constant*, Constant*> MutatedMemory;
2528
2529 /// AllocaTmps - To 'execute' an alloca, we create a temporary global variable
2530 /// to represent its body. This vector is needed so we can delete the
2531 /// temporary globals when we are done.
2532 SmallVector<GlobalVariable*, 32> AllocaTmps;
2533
2534 /// Invariants - These global variables have been marked invariant by the
2535 /// static constructor.
2536 SmallPtrSet<GlobalVariable*, 8> Invariants;
2537
2538 /// SimpleConstants - These are constants we have checked and know to be
2539 /// simple enough to live in a static initializer of a global.
2540 SmallPtrSet<Constant*, 8> SimpleConstants;
2541
Micah Villmow3574eca2012-10-08 16:38:25 +00002542 const DataLayout *TD;
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002543 const TargetLibraryInfo *TLI;
2544};
2545
Nick Lewycky7fa76772012-02-20 03:25:59 +00002546} // anonymous namespace
2547
Chris Lattner562a0552005-09-26 05:16:34 +00002548/// ComputeLoadResult - Return the value that would be computed by a load from
2549/// P after the stores reflected by 'memory' have been performed. If we can't
2550/// decide, return null.
Nick Lewycky7fa76772012-02-20 03:25:59 +00002551Constant *Evaluator::ComputeLoadResult(Constant *P) {
Chris Lattner04de1cf2005-09-26 05:15:37 +00002552 // If this memory location has been recently stored, use the stored value: it
2553 // is the most up-to-date.
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002554 DenseMap<Constant*, Constant*>::const_iterator I = MutatedMemory.find(P);
2555 if (I != MutatedMemory.end()) return I->second;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002556
Chris Lattner04de1cf2005-09-26 05:15:37 +00002557 // Access it.
2558 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(P)) {
Dan Gohman82555732009-08-19 18:20:44 +00002559 if (GV->hasDefinitiveInitializer())
Chris Lattner04de1cf2005-09-26 05:15:37 +00002560 return GV->getInitializer();
2561 return 0;
Chris Lattner04de1cf2005-09-26 05:15:37 +00002562 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002563
Chris Lattner798b4d52005-09-26 06:52:44 +00002564 // Handle a constantexpr getelementptr.
2565 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(P))
2566 if (CE->getOpcode() == Instruction::GetElementPtr &&
2567 isa<GlobalVariable>(CE->getOperand(0))) {
2568 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
Dan Gohman82555732009-08-19 18:20:44 +00002569 if (GV->hasDefinitiveInitializer())
Dan Gohmanc6f69e92009-10-05 16:36:26 +00002570 return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
Chris Lattner798b4d52005-09-26 06:52:44 +00002571 }
2572
2573 return 0; // don't know how to evaluate.
Chris Lattner04de1cf2005-09-26 05:15:37 +00002574}
2575
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002576/// EvaluateBlock - Evaluate all instructions in block BB, returning true if
2577/// successful, false if we can't evaluate it. NewBB returns the next BB that
2578/// control flows into, or null upon return.
Nick Lewycky7fa76772012-02-20 03:25:59 +00002579bool Evaluator::EvaluateBlock(BasicBlock::iterator CurInst,
2580 BasicBlock *&NextBB) {
Chris Lattner79c11012005-09-26 04:44:35 +00002581 // This is the main evaluation loop.
2582 while (1) {
2583 Constant *InstResult = 0;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002584
Chris Lattner79c11012005-09-26 04:44:35 +00002585 if (StoreInst *SI = dyn_cast<StoreInst>(CurInst)) {
Eli Friedman33cb4452011-08-16 00:20:11 +00002586 if (!SI->isSimple()) return false; // no volatile/atomic accesses.
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002587 Constant *Ptr = getVal(SI->getOperand(1));
Nick Lewyckya641c072012-02-21 22:08:06 +00002588 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
2589 Ptr = ConstantFoldConstantExpression(CE, TD, TLI);
Chris Lattner7b550cc2009-11-06 04:27:31 +00002590 if (!isSimpleEnoughPointerToCommit(Ptr))
Chris Lattner79c11012005-09-26 04:44:35 +00002591 // If this is too complex for us to commit, reject it.
Chris Lattnercd271422005-09-27 04:45:34 +00002592 return false;
Chris Lattner1945d582010-12-07 04:33:29 +00002593
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002594 Constant *Val = getVal(SI->getOperand(0));
Chris Lattner1945d582010-12-07 04:33:29 +00002595
2596 // If this might be too difficult for the backend to handle (e.g. the addr
2597 // of one global variable divided by another) then we can't commit it.
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002598 if (!isSimpleEnoughValueToCommit(Val, SimpleConstants, TD))
Chris Lattner1945d582010-12-07 04:33:29 +00002599 return false;
Owen Andersoncff6b372011-01-14 22:19:20 +00002600
2601 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
2602 if (CE->getOpcode() == Instruction::BitCast) {
2603 // If we're evaluating a store through a bitcast, then we need
2604 // to pull the bitcast off the pointer type and push it onto the
2605 // stored value.
Chris Lattnerd5f656f2011-01-16 02:05:10 +00002606 Ptr = CE->getOperand(0);
Owen Andersoncff6b372011-01-14 22:19:20 +00002607
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002608 Type *NewTy = cast<PointerType>(Ptr->getType())->getElementType();
Owen Andersoncff6b372011-01-14 22:19:20 +00002609
Owen Anderson66f708f2011-01-16 04:33:33 +00002610 // In order to push the bitcast onto the stored value, a bitcast
2611 // from NewTy to Val's type must be legal. If it's not, we can try
2612 // introspecting NewTy to find a legal conversion.
2613 while (!Val->getType()->canLosslesslyBitCastTo(NewTy)) {
2614 // If NewTy is a struct, we can convert the pointer to the struct
2615 // into a pointer to its first member.
2616 // FIXME: This could be extended to support arrays as well.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002617 if (StructType *STy = dyn_cast<StructType>(NewTy)) {
Owen Anderson66f708f2011-01-16 04:33:33 +00002618 NewTy = STy->getTypeAtIndex(0U);
2619
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002620 IntegerType *IdxTy = IntegerType::get(NewTy->getContext(), 32);
Owen Anderson66f708f2011-01-16 04:33:33 +00002621 Constant *IdxZero = ConstantInt::get(IdxTy, 0, false);
2622 Constant * const IdxList[] = {IdxZero, IdxZero};
2623
Jay Foadb4263a62011-07-22 08:52:50 +00002624 Ptr = ConstantExpr::getGetElementPtr(Ptr, IdxList);
Nick Lewyckya641c072012-02-21 22:08:06 +00002625 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
2626 Ptr = ConstantFoldConstantExpression(CE, TD, TLI);
2627
Owen Anderson66f708f2011-01-16 04:33:33 +00002628 // If we can't improve the situation by introspecting NewTy,
2629 // we have to give up.
2630 } else {
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002631 return false;
Owen Anderson66f708f2011-01-16 04:33:33 +00002632 }
Owen Andersoncff6b372011-01-14 22:19:20 +00002633 }
2634
Owen Anderson66f708f2011-01-16 04:33:33 +00002635 // If we found compatible types, go ahead and push the bitcast
2636 // onto the stored value.
Owen Andersoncff6b372011-01-14 22:19:20 +00002637 Val = ConstantExpr::getBitCast(Val, NewTy);
2638 }
2639
Chris Lattner79c11012005-09-26 04:44:35 +00002640 MutatedMemory[Ptr] = Val;
2641 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CurInst)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002642 InstResult = ConstantExpr::get(BO->getOpcode(),
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002643 getVal(BO->getOperand(0)),
2644 getVal(BO->getOperand(1)));
Reid Spencere4d87aa2006-12-23 06:05:41 +00002645 } else if (CmpInst *CI = dyn_cast<CmpInst>(CurInst)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002646 InstResult = ConstantExpr::getCompare(CI->getPredicate(),
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002647 getVal(CI->getOperand(0)),
2648 getVal(CI->getOperand(1)));
Chris Lattner79c11012005-09-26 04:44:35 +00002649 } else if (CastInst *CI = dyn_cast<CastInst>(CurInst)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002650 InstResult = ConstantExpr::getCast(CI->getOpcode(),
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002651 getVal(CI->getOperand(0)),
Chris Lattner79c11012005-09-26 04:44:35 +00002652 CI->getType());
2653 } else if (SelectInst *SI = dyn_cast<SelectInst>(CurInst)) {
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002654 InstResult = ConstantExpr::getSelect(getVal(SI->getOperand(0)),
2655 getVal(SI->getOperand(1)),
2656 getVal(SI->getOperand(2)));
Chris Lattner04de1cf2005-09-26 05:15:37 +00002657 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurInst)) {
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002658 Constant *P = getVal(GEP->getOperand(0));
Chris Lattner55eb1c42007-01-31 04:40:53 +00002659 SmallVector<Constant*, 8> GEPOps;
Gabor Greif5e463212008-05-29 01:59:18 +00002660 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end();
2661 i != e; ++i)
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002662 GEPOps.push_back(getVal(*i));
Jay Foad4b5e2072011-07-21 15:15:37 +00002663 InstResult =
2664 ConstantExpr::getGetElementPtr(P, GEPOps,
2665 cast<GEPOperator>(GEP)->isInBounds());
Chris Lattner04de1cf2005-09-26 05:15:37 +00002666 } else if (LoadInst *LI = dyn_cast<LoadInst>(CurInst)) {
Eli Friedman33cb4452011-08-16 00:20:11 +00002667 if (!LI->isSimple()) return false; // no volatile/atomic accesses.
Nick Lewyckya641c072012-02-21 22:08:06 +00002668 Constant *Ptr = getVal(LI->getOperand(0));
2669 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
2670 Ptr = ConstantFoldConstantExpression(CE, TD, TLI);
2671 InstResult = ComputeLoadResult(Ptr);
Chris Lattnercd271422005-09-27 04:45:34 +00002672 if (InstResult == 0) return false; // Could not evaluate load.
Chris Lattnera22fdb02005-09-26 17:07:09 +00002673 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(CurInst)) {
Chris Lattnercd271422005-09-27 04:45:34 +00002674 if (AI->isArrayAllocation()) return false; // Cannot handle array allocs.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002675 Type *Ty = AI->getType()->getElementType();
Chris Lattner7b550cc2009-11-06 04:27:31 +00002676 AllocaTmps.push_back(new GlobalVariable(Ty, false,
Chris Lattnera22fdb02005-09-26 17:07:09 +00002677 GlobalValue::InternalLinkage,
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002678 UndefValue::get(Ty),
Chris Lattnera22fdb02005-09-26 17:07:09 +00002679 AI->getName()));
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002680 InstResult = AllocaTmps.back();
Nick Lewycky132bd9c2012-02-12 05:09:35 +00002681 } else if (isa<CallInst>(CurInst) || isa<InvokeInst>(CurInst)) {
2682 CallSite CS(CurInst);
Devang Patel412a4462009-03-09 23:04:12 +00002683
2684 // Debug info can safely be ignored here.
Nick Lewycky132bd9c2012-02-12 05:09:35 +00002685 if (isa<DbgInfoIntrinsic>(CS.getInstruction())) {
Devang Patel412a4462009-03-09 23:04:12 +00002686 ++CurInst;
2687 continue;
2688 }
2689
Chris Lattner7cd580f2006-07-07 21:37:01 +00002690 // Cannot handle inline asm.
Nick Lewycky132bd9c2012-02-12 05:09:35 +00002691 if (isa<InlineAsm>(CS.getCalledValue())) return false;
Chris Lattner7cd580f2006-07-07 21:37:01 +00002692
Nick Lewycky81266c52012-02-17 06:59:21 +00002693 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CS.getInstruction())) {
2694 if (MemSetInst *MSI = dyn_cast<MemSetInst>(II)) {
2695 if (MSI->isVolatile()) return false;
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002696 Constant *Ptr = getVal(MSI->getDest());
2697 Constant *Val = getVal(MSI->getValue());
2698 Constant *DestVal = ComputeLoadResult(getVal(Ptr));
Nick Lewycky81266c52012-02-17 06:59:21 +00002699 if (Val->isNullValue() && DestVal && DestVal->isNullValue()) {
2700 // This memset is a no-op.
2701 ++CurInst;
2702 continue;
2703 }
2704 }
2705
2706 if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
2707 II->getIntrinsicID() == Intrinsic::lifetime_end) {
2708 ++CurInst;
2709 continue;
2710 }
2711
2712 if (II->getIntrinsicID() == Intrinsic::invariant_start) {
2713 // We don't insert an entry into Values, as it doesn't have a
2714 // meaningful return value.
2715 if (!II->use_empty())
2716 return false;
2717 ConstantInt *Size = cast<ConstantInt>(II->getArgOperand(0));
Nick Lewycky0ef05572012-02-20 23:32:26 +00002718 Value *PtrArg = getVal(II->getArgOperand(1));
2719 Value *Ptr = PtrArg->stripPointerCasts();
2720 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr)) {
2721 Type *ElemTy = cast<PointerType>(GV->getType())->getElementType();
2722 if (!Size->isAllOnesValue() &&
2723 Size->getValue().getLimitedValue() >=
2724 TD->getTypeStoreSize(ElemTy))
Nick Lewycky81266c52012-02-17 06:59:21 +00002725 Invariants.insert(GV);
2726 }
2727 // Continue even if we do nothing.
Nick Lewycky1f237b02011-05-29 18:41:56 +00002728 ++CurInst;
2729 continue;
2730 }
2731 return false;
2732 }
2733
Chris Lattnercd271422005-09-27 04:45:34 +00002734 // Resolve function pointers.
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002735 Function *Callee = dyn_cast<Function>(getVal(CS.getCalledValue()));
Nick Lewycky132bd9c2012-02-12 05:09:35 +00002736 if (!Callee || Callee->mayBeOverridden())
2737 return false; // Cannot resolve.
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002738
Duncan Sandsfa6a1cf2009-08-17 14:33:27 +00002739 SmallVector<Constant*, 8> Formals;
Nick Lewycky132bd9c2012-02-12 05:09:35 +00002740 for (User::op_iterator i = CS.arg_begin(), e = CS.arg_end(); i != e; ++i)
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002741 Formals.push_back(getVal(*i));
Duncan Sandsfa6a1cf2009-08-17 14:33:27 +00002742
Reid Spencer5cbf9852007-01-30 20:08:39 +00002743 if (Callee->isDeclaration()) {
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002744 // If this is a function we can constant fold, do it.
Chad Rosier00737bd2011-12-01 21:29:16 +00002745 if (Constant *C = ConstantFoldCall(Callee, Formals, TLI)) {
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002746 InstResult = C;
2747 } else {
2748 return false;
2749 }
2750 } else {
2751 if (Callee->getFunctionType()->isVarArg())
2752 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002753
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002754 Constant *RetVal;
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002755 // Execute the call, if successful, use the return value.
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002756 ValueStack.push_back(new DenseMap<Value*, Constant*>);
2757 if (!EvaluateFunction(Callee, RetVal, Formals))
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002758 return false;
Benjamin Kramer3bbf2b62012-02-27 12:48:24 +00002759 delete ValueStack.pop_back_val();
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002760 InstResult = RetVal;
2761 }
Reid Spencer3ed469c2006-11-02 20:25:50 +00002762 } else if (isa<TerminatorInst>(CurInst)) {
Chris Lattnercdf98be2005-09-26 04:57:38 +00002763 if (BranchInst *BI = dyn_cast<BranchInst>(CurInst)) {
2764 if (BI->isUnconditional()) {
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002765 NextBB = BI->getSuccessor(0);
Chris Lattnercdf98be2005-09-26 04:57:38 +00002766 } else {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002767 ConstantInt *Cond =
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002768 dyn_cast<ConstantInt>(getVal(BI->getCondition()));
Chris Lattner97d1fad2007-01-12 18:30:11 +00002769 if (!Cond) return false; // Cannot determine.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002770
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002771 NextBB = BI->getSuccessor(!Cond->getZExtValue());
Chris Lattnercdf98be2005-09-26 04:57:38 +00002772 }
2773 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(CurInst)) {
2774 ConstantInt *Val =
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002775 dyn_cast<ConstantInt>(getVal(SI->getCondition()));
Chris Lattnercd271422005-09-27 04:45:34 +00002776 if (!Val) return false; // Cannot determine.
Stepan Dyatkovskiyc10fa6c2012-03-08 07:06:20 +00002777 NextBB = SI->findCaseValue(Val).getCaseSuccessor();
Chris Lattnerb3d5a652009-10-29 05:51:50 +00002778 } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(CurInst)) {
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002779 Value *Val = getVal(IBI->getAddress())->stripPointerCasts();
Chris Lattnerb3d5a652009-10-29 05:51:50 +00002780 if (BlockAddress *BA = dyn_cast<BlockAddress>(Val))
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002781 NextBB = BA->getBasicBlock();
Chris Lattnercdfc9402009-11-01 01:27:45 +00002782 else
2783 return false; // Cannot determine.
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002784 } else if (isa<ReturnInst>(CurInst)) {
2785 NextBB = 0;
Chris Lattnercdf98be2005-09-26 04:57:38 +00002786 } else {
Bill Wendlingdccc03b2011-07-31 06:30:59 +00002787 // invoke, unwind, resume, unreachable.
Chris Lattnercd271422005-09-27 04:45:34 +00002788 return false; // Cannot handle this terminator.
Chris Lattnercdf98be2005-09-26 04:57:38 +00002789 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002790
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002791 // We succeeded at evaluating this block!
2792 return true;
Chris Lattner79c11012005-09-26 04:44:35 +00002793 } else {
Chris Lattner79c11012005-09-26 04:44:35 +00002794 // Did not know how to evaluate this!
Chris Lattnercd271422005-09-27 04:45:34 +00002795 return false;
Chris Lattner79c11012005-09-26 04:44:35 +00002796 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002797
Chris Lattner1945d582010-12-07 04:33:29 +00002798 if (!CurInst->use_empty()) {
2799 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(InstResult))
Chad Rosieraab8e282011-12-02 01:26:24 +00002800 InstResult = ConstantFoldConstantExpression(CE, TD, TLI);
Chris Lattner1945d582010-12-07 04:33:29 +00002801
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002802 setVal(CurInst, InstResult);
Chris Lattner1945d582010-12-07 04:33:29 +00002803 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002804
Dan Gohmanf1ce79f2012-03-13 18:01:37 +00002805 // If we just processed an invoke, we finished evaluating the block.
2806 if (InvokeInst *II = dyn_cast<InvokeInst>(CurInst)) {
2807 NextBB = II->getNormalDest();
2808 return true;
2809 }
2810
Chris Lattner79c11012005-09-26 04:44:35 +00002811 // Advance program counter.
2812 ++CurInst;
2813 }
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002814}
2815
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002816/// EvaluateFunction - Evaluate a call to function F, returning true if
2817/// successful, false if we can't evaluate it. ActualArgs contains the formal
2818/// arguments for the function.
Nick Lewycky7fa76772012-02-20 03:25:59 +00002819bool Evaluator::EvaluateFunction(Function *F, Constant *&RetVal,
2820 const SmallVectorImpl<Constant*> &ActualArgs) {
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002821 // Check to see if this function is already executing (recursion). If so,
2822 // bail out. TODO: we might want to accept limited recursion.
2823 if (std::find(CallStack.begin(), CallStack.end(), F) != CallStack.end())
2824 return false;
2825
2826 CallStack.push_back(F);
2827
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002828 // Initialize arguments to the incoming values specified.
2829 unsigned ArgNo = 0;
2830 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); AI != E;
2831 ++AI, ++ArgNo)
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002832 setVal(AI, ActualArgs[ArgNo]);
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002833
2834 // ExecutedBlocks - We only handle non-looping, non-recursive code. As such,
2835 // we can only evaluate any one basic block at most once. This set keeps
2836 // track of what we have executed so we can detect recursive cases etc.
2837 SmallPtrSet<BasicBlock*, 32> ExecutedBlocks;
2838
2839 // CurBB - The current basic block we're evaluating.
2840 BasicBlock *CurBB = F->begin();
2841
Nick Lewycky8e4ba6b2012-02-12 00:47:24 +00002842 BasicBlock::iterator CurInst = CurBB->begin();
2843
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002844 while (1) {
Duncan Sands4b794f82012-02-23 08:23:06 +00002845 BasicBlock *NextBB = 0; // Initialized to avoid compiler warnings.
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002846 if (!EvaluateBlock(CurInst, NextBB))
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002847 return false;
2848
2849 if (NextBB == 0) {
2850 // Successfully running until there's no next block means that we found
2851 // the return. Fill it the return value and pop the call stack.
2852 ReturnInst *RI = cast<ReturnInst>(CurBB->getTerminator());
2853 if (RI->getNumOperands())
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002854 RetVal = getVal(RI->getOperand(0));
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002855 CallStack.pop_back();
2856 return true;
2857 }
2858
2859 // Okay, we succeeded in evaluating this control flow. See if we have
2860 // executed the new block before. If so, we have a looping function,
2861 // which we cannot evaluate in reasonable time.
2862 if (!ExecutedBlocks.insert(NextBB))
2863 return false; // looped!
2864
2865 // Okay, we have never been in this block before. Check to see if there
2866 // are any PHI nodes. If so, evaluate them with information about where
2867 // we came from.
2868 PHINode *PN = 0;
Nick Lewycky8e4ba6b2012-02-12 00:47:24 +00002869 for (CurInst = NextBB->begin();
2870 (PN = dyn_cast<PHINode>(CurInst)); ++CurInst)
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002871 setVal(PN, getVal(PN->getIncomingValueForBlock(CurBB)));
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002872
2873 // Advance to the next block.
2874 CurBB = NextBB;
2875 }
2876}
2877
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002878/// EvaluateStaticConstructor - Evaluate static constructors in the function, if
2879/// we can. Return true if we can, false otherwise.
Micah Villmow3574eca2012-10-08 16:38:25 +00002880static bool EvaluateStaticConstructor(Function *F, const DataLayout *TD,
Chad Rosier00737bd2011-12-01 21:29:16 +00002881 const TargetLibraryInfo *TLI) {
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002882 // Call the function.
Nick Lewycky7fa76772012-02-20 03:25:59 +00002883 Evaluator Eval(TD, TLI);
Chris Lattnercd271422005-09-27 04:45:34 +00002884 Constant *RetValDummy;
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002885 bool EvalSuccess = Eval.EvaluateFunction(F, RetValDummy,
2886 SmallVector<Constant*, 0>());
Chris Lattner1945d582010-12-07 04:33:29 +00002887
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002888 if (EvalSuccess) {
Chris Lattnera22fdb02005-09-26 17:07:09 +00002889 // We succeeded at evaluation: commit the result.
David Greene3215b0e2010-01-05 01:28:05 +00002890 DEBUG(dbgs() << "FULLY EVALUATED GLOBAL CTOR FUNCTION '"
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002891 << F->getName() << "' to " << Eval.getMutatedMemory().size()
Daniel Dunbarce63ffb2009-07-25 00:23:56 +00002892 << " stores.\n");
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002893 for (DenseMap<Constant*, Constant*>::const_iterator I =
2894 Eval.getMutatedMemory().begin(), E = Eval.getMutatedMemory().end();
Nick Lewycky3eab3c42012-06-24 04:07:14 +00002895 I != E; ++I)
Chris Lattner7b550cc2009-11-06 04:27:31 +00002896 CommitValueTo(I->second, I->first);
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002897 for (SmallPtrSet<GlobalVariable*, 8>::const_iterator I =
2898 Eval.getInvariants().begin(), E = Eval.getInvariants().end();
2899 I != E; ++I)
Nick Lewycky81266c52012-02-17 06:59:21 +00002900 (*I)->setConstant(true);
Chris Lattnera22fdb02005-09-26 17:07:09 +00002901 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002902
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002903 return EvalSuccess;
Chris Lattner79c11012005-09-26 04:44:35 +00002904}
2905
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002906/// OptimizeGlobalCtorsList - Simplify and evaluation global ctors if possible.
2907/// Return true if anything changed.
2908bool GlobalOpt::OptimizeGlobalCtorsList(GlobalVariable *&GCL) {
2909 std::vector<Function*> Ctors = ParseGlobalCtors(GCL);
2910 bool MadeChange = false;
2911 if (Ctors.empty()) return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002912
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002913 // Loop over global ctors, optimizing them when we can.
2914 for (unsigned i = 0; i != Ctors.size(); ++i) {
2915 Function *F = Ctors[i];
2916 // Found a null terminator in the middle of the list, prune off the rest of
2917 // the list.
Chris Lattner7d8e58f2005-09-26 02:19:27 +00002918 if (F == 0) {
2919 if (i != Ctors.size()-1) {
2920 Ctors.resize(i+1);
2921 MadeChange = true;
2922 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002923 break;
2924 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002925
Chris Lattner79c11012005-09-26 04:44:35 +00002926 // We cannot simplify external ctor functions.
2927 if (F->empty()) continue;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002928
Chris Lattner79c11012005-09-26 04:44:35 +00002929 // If we can evaluate the ctor at compile time, do.
Chad Rosier00737bd2011-12-01 21:29:16 +00002930 if (EvaluateStaticConstructor(F, TD, TLI)) {
Chris Lattner79c11012005-09-26 04:44:35 +00002931 Ctors.erase(Ctors.begin()+i);
2932 MadeChange = true;
2933 --i;
2934 ++NumCtorsEvaluated;
2935 continue;
2936 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002937 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002938
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002939 if (!MadeChange) return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002940
Chris Lattner7b550cc2009-11-06 04:27:31 +00002941 GCL = InstallGlobalCtors(GCL, Ctors);
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002942 return true;
2943}
2944
Duncan Sandsfc5940d2009-03-06 10:21:56 +00002945bool GlobalOpt::OptimizeGlobalAliases(Module &M) {
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002946 bool Changed = false;
2947
Duncan Sands177d84e2009-01-07 20:01:06 +00002948 for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end();
Duncan Sands4782b302009-02-15 09:56:08 +00002949 I != E;) {
2950 Module::alias_iterator J = I++;
Duncan Sandsfc5940d2009-03-06 10:21:56 +00002951 // Aliases without names cannot be referenced outside this module.
2952 if (!J->hasName() && !J->isDeclaration())
2953 J->setLinkage(GlobalValue::InternalLinkage);
Duncan Sands4782b302009-02-15 09:56:08 +00002954 // If the aliasee may change at link time, nothing can be done - bail out.
2955 if (J->mayBeOverridden())
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002956 continue;
2957
Duncan Sands4782b302009-02-15 09:56:08 +00002958 Constant *Aliasee = J->getAliasee();
2959 GlobalValue *Target = cast<GlobalValue>(Aliasee->stripPointerCasts());
Duncan Sands95c5d0f2009-02-18 17:55:38 +00002960 Target->removeDeadConstantUsers();
Duncan Sands4782b302009-02-15 09:56:08 +00002961 bool hasOneUse = Target->hasOneUse() && Aliasee->hasOneUse();
2962
2963 // Make all users of the alias use the aliasee instead.
2964 if (!J->use_empty()) {
2965 J->replaceAllUsesWith(Aliasee);
2966 ++NumAliasesResolved;
2967 Changed = true;
2968 }
2969
Duncan Sands7a154cf2009-12-08 10:10:20 +00002970 // If the alias is externally visible, we may still be able to simplify it.
2971 if (!J->hasLocalLinkage()) {
2972 // If the aliasee has internal linkage, give it the name and linkage
2973 // of the alias, and delete the alias. This turns:
2974 // define internal ... @f(...)
2975 // @a = alias ... @f
2976 // into:
2977 // define ... @a(...)
2978 if (!Target->hasLocalLinkage())
2979 continue;
Duncan Sands4782b302009-02-15 09:56:08 +00002980
Duncan Sands7a154cf2009-12-08 10:10:20 +00002981 // Do not perform the transform if multiple aliases potentially target the
Gabor Greif27236912010-04-07 18:59:26 +00002982 // aliasee. This check also ensures that it is safe to replace the section
Duncan Sands7a154cf2009-12-08 10:10:20 +00002983 // and other attributes of the aliasee with those of the alias.
2984 if (!hasOneUse)
2985 continue;
Duncan Sands4782b302009-02-15 09:56:08 +00002986
Duncan Sands7a154cf2009-12-08 10:10:20 +00002987 // Give the aliasee the name, linkage and other attributes of the alias.
2988 Target->takeName(J);
2989 Target->setLinkage(J->getLinkage());
2990 Target->GlobalValue::copyAttributesFrom(J);
2991 }
Duncan Sands4782b302009-02-15 09:56:08 +00002992
2993 // Delete the alias.
2994 M.getAliasList().erase(J);
2995 ++NumAliasesRemoved;
2996 Changed = true;
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002997 }
2998
2999 return Changed;
3000}
Chris Lattnerb1ab4582005-09-26 01:43:45 +00003001
Nick Lewycky6a7df9a2012-02-12 02:15:20 +00003002static Function *FindCXAAtExit(Module &M, TargetLibraryInfo *TLI) {
3003 if (!TLI->has(LibFunc::cxa_atexit))
Nick Lewycky6f160d32012-02-12 02:17:18 +00003004 return 0;
Nick Lewycky6a7df9a2012-02-12 02:15:20 +00003005
3006 Function *Fn = M.getFunction(TLI->getName(LibFunc::cxa_atexit));
Anders Carlssona201c4c2011-03-20 17:59:11 +00003007
3008 if (!Fn)
3009 return 0;
Nick Lewycky6a7df9a2012-02-12 02:15:20 +00003010
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003011 FunctionType *FTy = Fn->getFunctionType();
Anders Carlssona201c4c2011-03-20 17:59:11 +00003012
Anders Carlsson1f7c7ba2011-03-20 19:51:13 +00003013 // Checking that the function has the right return type, the right number of
3014 // parameters and that they all have pointer types should be enough.
3015 if (!FTy->getReturnType()->isIntegerTy() ||
3016 FTy->getNumParams() != 3 ||
Anders Carlssona201c4c2011-03-20 17:59:11 +00003017 !FTy->getParamType(0)->isPointerTy() ||
3018 !FTy->getParamType(1)->isPointerTy() ||
3019 !FTy->getParamType(2)->isPointerTy())
3020 return 0;
3021
3022 return Fn;
3023}
3024
3025/// cxxDtorIsEmpty - Returns whether the given function is an empty C++
3026/// destructor and can therefore be eliminated.
3027/// Note that we assume that other optimization passes have already simplified
3028/// the code so we only look for a function with a single basic block, where
Benjamin Kramerc1322a12012-02-09 16:28:15 +00003029/// the only allowed instructions are 'ret', 'call' to an empty C++ dtor and
3030/// other side-effect free instructions.
Anders Carlsson372ec6a2011-03-20 20:16:43 +00003031static bool cxxDtorIsEmpty(const Function &Fn,
3032 SmallPtrSet<const Function *, 8> &CalledFunctions) {
Anders Carlsson1f7c7ba2011-03-20 19:51:13 +00003033 // FIXME: We could eliminate C++ destructors if they're readonly/readnone and
Nick Lewycky35ee1c92011-03-21 02:26:01 +00003034 // nounwind, but that doesn't seem worth doing.
Anders Carlsson1f7c7ba2011-03-20 19:51:13 +00003035 if (Fn.isDeclaration())
3036 return false;
Anders Carlssona201c4c2011-03-20 17:59:11 +00003037
3038 if (++Fn.begin() != Fn.end())
3039 return false;
3040
3041 const BasicBlock &EntryBlock = Fn.getEntryBlock();
3042 for (BasicBlock::const_iterator I = EntryBlock.begin(), E = EntryBlock.end();
3043 I != E; ++I) {
3044 if (const CallInst *CI = dyn_cast<CallInst>(I)) {
Anders Carlssonb12caf32011-03-21 14:54:40 +00003045 // Ignore debug intrinsics.
3046 if (isa<DbgInfoIntrinsic>(CI))
3047 continue;
3048
Anders Carlssona201c4c2011-03-20 17:59:11 +00003049 const Function *CalledFn = CI->getCalledFunction();
3050
3051 if (!CalledFn)
3052 return false;
3053
Anders Carlsson807bc2a2011-03-22 03:21:01 +00003054 SmallPtrSet<const Function *, 8> NewCalledFunctions(CalledFunctions);
3055
Anders Carlsson1f7c7ba2011-03-20 19:51:13 +00003056 // Don't treat recursive functions as empty.
Anders Carlsson807bc2a2011-03-22 03:21:01 +00003057 if (!NewCalledFunctions.insert(CalledFn))
Anders Carlsson1f7c7ba2011-03-20 19:51:13 +00003058 return false;
3059
Anders Carlsson807bc2a2011-03-22 03:21:01 +00003060 if (!cxxDtorIsEmpty(*CalledFn, NewCalledFunctions))
Anders Carlssona201c4c2011-03-20 17:59:11 +00003061 return false;
3062 } else if (isa<ReturnInst>(*I))
Benjamin Kramerd4692742012-02-09 14:26:06 +00003063 return true; // We're done.
3064 else if (I->mayHaveSideEffects())
3065 return false; // Destructor with side effects, bail.
Anders Carlssona201c4c2011-03-20 17:59:11 +00003066 }
3067
3068 return false;
3069}
3070
3071bool GlobalOpt::OptimizeEmptyGlobalCXXDtors(Function *CXAAtExitFn) {
3072 /// Itanium C++ ABI p3.3.5:
3073 ///
3074 /// After constructing a global (or local static) object, that will require
3075 /// destruction on exit, a termination function is registered as follows:
3076 ///
3077 /// extern "C" int __cxa_atexit ( void (*f)(void *), void *p, void *d );
3078 ///
3079 /// This registration, e.g. __cxa_atexit(f,p,d), is intended to cause the
3080 /// call f(p) when DSO d is unloaded, before all such termination calls
3081 /// registered before this one. It returns zero if registration is
Nick Lewycky35ee1c92011-03-21 02:26:01 +00003082 /// successful, nonzero on failure.
Anders Carlssona201c4c2011-03-20 17:59:11 +00003083
3084 // This pass will look for calls to __cxa_atexit where the function is trivial
3085 // and remove them.
3086 bool Changed = false;
3087
3088 for (Function::use_iterator I = CXAAtExitFn->use_begin(),
3089 E = CXAAtExitFn->use_end(); I != E;) {
Anders Carlsson4f735ca2011-03-20 20:21:33 +00003090 // We're only interested in calls. Theoretically, we could handle invoke
3091 // instructions as well, but neither llvm-gcc nor clang generate invokes
3092 // to __cxa_atexit.
Anders Carlssonb12caf32011-03-21 14:54:40 +00003093 CallInst *CI = dyn_cast<CallInst>(*I++);
3094 if (!CI)
Anders Carlsson4f735ca2011-03-20 20:21:33 +00003095 continue;
3096
Anders Carlssona201c4c2011-03-20 17:59:11 +00003097 Function *DtorFn =
Anders Carlssonb12caf32011-03-21 14:54:40 +00003098 dyn_cast<Function>(CI->getArgOperand(0)->stripPointerCasts());
Anders Carlssona201c4c2011-03-20 17:59:11 +00003099 if (!DtorFn)
3100 continue;
3101
Anders Carlsson372ec6a2011-03-20 20:16:43 +00003102 SmallPtrSet<const Function *, 8> CalledFunctions;
3103 if (!cxxDtorIsEmpty(*DtorFn, CalledFunctions))
Anders Carlssona201c4c2011-03-20 17:59:11 +00003104 continue;
3105
3106 // Just remove the call.
Anders Carlssonb12caf32011-03-21 14:54:40 +00003107 CI->replaceAllUsesWith(Constant::getNullValue(CI->getType()));
3108 CI->eraseFromParent();
Anders Carlsson1f7c7ba2011-03-20 19:51:13 +00003109
Anders Carlssona201c4c2011-03-20 17:59:11 +00003110 ++NumCXXDtorsRemoved;
3111
3112 Changed |= true;
3113 }
3114
3115 return Changed;
3116}
3117
Chris Lattner7a90b682004-10-07 04:16:33 +00003118bool GlobalOpt::runOnModule(Module &M) {
Chris Lattner079236d2004-02-25 21:34:36 +00003119 bool Changed = false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00003120
Micah Villmow3574eca2012-10-08 16:38:25 +00003121 TD = getAnalysisIfAvailable<DataLayout>();
Nick Lewycky6a7df9a2012-02-12 02:15:20 +00003122 TLI = &getAnalysis<TargetLibraryInfo>();
Nick Lewycky6a577f82012-02-12 01:13:18 +00003123
Chris Lattnerb1ab4582005-09-26 01:43:45 +00003124 // Try to find the llvm.globalctors list.
3125 GlobalVariable *GlobalCtors = FindGlobalCtors(M);
Chris Lattner7a90b682004-10-07 04:16:33 +00003126
Nick Lewycky6a7df9a2012-02-12 02:15:20 +00003127 Function *CXAAtExitFn = FindCXAAtExit(M, TLI);
Anders Carlssona201c4c2011-03-20 17:59:11 +00003128
Chris Lattner7a90b682004-10-07 04:16:33 +00003129 bool LocalChange = true;
3130 while (LocalChange) {
3131 LocalChange = false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00003132
Chris Lattnerb1ab4582005-09-26 01:43:45 +00003133 // Delete functions that are trivially dead, ccc -> fastcc
3134 LocalChange |= OptimizeFunctions(M);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00003135
Chris Lattnerb1ab4582005-09-26 01:43:45 +00003136 // Optimize global_ctors list.
3137 if (GlobalCtors)
3138 LocalChange |= OptimizeGlobalCtorsList(GlobalCtors);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00003139
Chris Lattnerb1ab4582005-09-26 01:43:45 +00003140 // Optimize non-address-taken globals.
3141 LocalChange |= OptimizeGlobalVars(M);
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00003142
3143 // Resolve aliases, when possible.
Duncan Sandsfc5940d2009-03-06 10:21:56 +00003144 LocalChange |= OptimizeGlobalAliases(M);
Anders Carlssona201c4c2011-03-20 17:59:11 +00003145
3146 // Try to remove trivial global destructors.
3147 if (CXAAtExitFn)
3148 LocalChange |= OptimizeEmptyGlobalCXXDtors(CXAAtExitFn);
3149
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00003150 Changed |= LocalChange;
Chris Lattner7a90b682004-10-07 04:16:33 +00003151 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00003152
Chris Lattnerb1ab4582005-09-26 01:43:45 +00003153 // TODO: Move all global ctors functions to the end of the module for code
3154 // layout.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00003155
Chris Lattner079236d2004-02-25 21:34:36 +00003156 return Changed;
3157}