blob: 4e1c23c1980c0f74670709c03576f58884a7eda3 [file] [log] [blame]
Chris Lattner7a90b682004-10-07 04:16:33 +00001//===- GlobalOpt.cpp - Optimize Global Variables --------------------------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
Chris Lattner079236d2004-02-25 21:34:36 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
Chris Lattner079236d2004-02-25 21:34:36 +00008//===----------------------------------------------------------------------===//
9//
Chris Lattner7a90b682004-10-07 04:16:33 +000010// This pass transforms simple global variables that never have their address
11// taken. If obviously true, it marks read/write globals as constant, deletes
12// variables only stored to, etc.
Chris Lattner079236d2004-02-25 21:34:36 +000013//
14//===----------------------------------------------------------------------===//
15
Chris Lattner7a90b682004-10-07 04:16:33 +000016#define DEBUG_TYPE "globalopt"
Chris Lattner079236d2004-02-25 21:34:36 +000017#include "llvm/Transforms/IPO.h"
Chris Lattnerfb217ad2005-05-08 22:18:06 +000018#include "llvm/CallingConv.h"
Chris Lattner079236d2004-02-25 21:34:36 +000019#include "llvm/Constants.h"
Chris Lattner7a90b682004-10-07 04:16:33 +000020#include "llvm/DerivedTypes.h"
Chris Lattner7d90a272004-02-27 18:09:25 +000021#include "llvm/Instructions.h"
Chris Lattner35c81b02005-02-27 18:58:52 +000022#include "llvm/IntrinsicInst.h"
Chris Lattner079236d2004-02-25 21:34:36 +000023#include "llvm/Module.h"
Jay Foad562b84b2011-04-11 09:35:34 +000024#include "llvm/Operator.h"
Chris Lattner079236d2004-02-25 21:34:36 +000025#include "llvm/Pass.h"
Chris Lattner79066fa2007-01-30 23:46:24 +000026#include "llvm/Analysis/ConstantFolding.h"
Victor Hernandezf006b182009-10-27 20:05:49 +000027#include "llvm/Analysis/MemoryBuiltins.h"
Chris Lattner30ba5692004-10-11 05:54:41 +000028#include "llvm/Target/TargetData.h"
Chad Rosier00737bd2011-12-01 21:29:16 +000029#include "llvm/Target/TargetLibraryInfo.h"
Duncan Sands548448a2008-02-18 17:32:13 +000030#include "llvm/Support/CallSite.h"
Chris Lattner79066fa2007-01-30 23:46:24 +000031#include "llvm/Support/Debug.h"
Torok Edwinc25e7582009-07-11 20:10:48 +000032#include "llvm/Support/ErrorHandling.h"
Chris Lattner941db492008-01-14 02:09:12 +000033#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner998182b2008-04-26 07:40:11 +000034#include "llvm/Support/MathExtras.h"
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000035#include "llvm/Support/raw_ostream.h"
Chris Lattner5a6bb6a2008-12-16 07:34:30 +000036#include "llvm/ADT/DenseMap.h"
Chris Lattner81686182007-09-13 16:30:19 +000037#include "llvm/ADT/SmallPtrSet.h"
Chris Lattner55eb1c42007-01-31 04:40:53 +000038#include "llvm/ADT/SmallVector.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000039#include "llvm/ADT/Statistic.h"
Chris Lattnerbce4afe2008-12-17 05:28:49 +000040#include "llvm/ADT/STLExtras.h"
Chris Lattnere47ba742004-10-06 20:57:02 +000041#include <algorithm>
Chris Lattner079236d2004-02-25 21:34:36 +000042using namespace llvm;
43
Chris Lattner86453c52006-12-19 22:09:18 +000044STATISTIC(NumMarked , "Number of globals marked constant");
Rafael Espindolac4440e32011-01-19 16:32:21 +000045STATISTIC(NumUnnamed , "Number of globals marked unnamed_addr");
Chris Lattner86453c52006-12-19 22:09:18 +000046STATISTIC(NumSRA , "Number of aggregate globals broken into scalars");
47STATISTIC(NumHeapSRA , "Number of heap objects SRA'd");
48STATISTIC(NumSubstitute,"Number of globals with initializers stored into them");
49STATISTIC(NumDeleted , "Number of globals deleted");
50STATISTIC(NumFnDeleted , "Number of functions deleted");
51STATISTIC(NumGlobUses , "Number of global uses devirtualized");
52STATISTIC(NumLocalized , "Number of globals localized");
53STATISTIC(NumShrunkToBool , "Number of global vars shrunk to booleans");
54STATISTIC(NumFastCallFns , "Number of functions converted to fastcc");
55STATISTIC(NumCtorsEvaluated, "Number of static ctors evaluated");
Duncan Sands3d5378f2008-02-16 20:56:04 +000056STATISTIC(NumNestRemoved , "Number of nest attributes removed");
Duncan Sands4782b302009-02-15 09:56:08 +000057STATISTIC(NumAliasesResolved, "Number of global aliases resolved");
58STATISTIC(NumAliasesRemoved, "Number of global aliases eliminated");
Anders Carlssona201c4c2011-03-20 17:59:11 +000059STATISTIC(NumCXXDtorsRemoved, "Number of global C++ destructors removed");
Chris Lattner079236d2004-02-25 21:34:36 +000060
Chris Lattner86453c52006-12-19 22:09:18 +000061namespace {
Rafael Espindolac4440e32011-01-19 16:32:21 +000062 struct GlobalStatus;
Nick Lewycky6726b6d2009-10-25 06:33:48 +000063 struct GlobalOpt : public ModulePass {
Chris Lattner30ba5692004-10-11 05:54:41 +000064 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chad Rosier00737bd2011-12-01 21:29:16 +000065 AU.addRequired<TargetLibraryInfo>();
Chris Lattner30ba5692004-10-11 05:54:41 +000066 }
Nick Lewyckyecd94c82007-05-06 13:37:16 +000067 static char ID; // Pass identification, replacement for typeid
Owen Anderson081c34b2010-10-19 17:21:58 +000068 GlobalOpt() : ModulePass(ID) {
69 initializeGlobalOptPass(*PassRegistry::getPassRegistry());
70 }
Misha Brukmanfd939082005-04-21 23:48:37 +000071
Chris Lattnerb12914b2004-09-20 04:48:05 +000072 bool runOnModule(Module &M);
Chris Lattner30ba5692004-10-11 05:54:41 +000073
74 private:
Chris Lattnerb1ab4582005-09-26 01:43:45 +000075 GlobalVariable *FindGlobalCtors(Module &M);
76 bool OptimizeFunctions(Module &M);
77 bool OptimizeGlobalVars(Module &M);
Duncan Sandsfc5940d2009-03-06 10:21:56 +000078 bool OptimizeGlobalAliases(Module &M);
Chris Lattnerb1ab4582005-09-26 01:43:45 +000079 bool OptimizeGlobalCtorsList(GlobalVariable *&GCL);
Rafael Espindolac4440e32011-01-19 16:32:21 +000080 bool ProcessGlobal(GlobalVariable *GV,Module::global_iterator &GVI);
81 bool ProcessInternalGlobal(GlobalVariable *GV,Module::global_iterator &GVI,
82 const SmallPtrSet<const PHINode*, 16> &PHIUsers,
83 const GlobalStatus &GS);
Anders Carlssona201c4c2011-03-20 17:59:11 +000084 bool OptimizeEmptyGlobalCXXDtors(Function *CXAAtExitFn);
Nick Lewycky6a577f82012-02-12 01:13:18 +000085
86 TargetData *TD;
87 TargetLibraryInfo *TLI;
Chris Lattner079236d2004-02-25 21:34:36 +000088 };
Chris Lattner079236d2004-02-25 21:34:36 +000089}
90
Dan Gohman844731a2008-05-13 00:00:25 +000091char GlobalOpt::ID = 0;
Chad Rosier00737bd2011-12-01 21:29:16 +000092INITIALIZE_PASS_BEGIN(GlobalOpt, "globalopt",
93 "Global Variable Optimizer", false, false)
94INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
95INITIALIZE_PASS_END(GlobalOpt, "globalopt",
Owen Andersonce665bd2010-10-07 22:25:06 +000096 "Global Variable Optimizer", false, false)
Dan Gohman844731a2008-05-13 00:00:25 +000097
Chris Lattner7a90b682004-10-07 04:16:33 +000098ModulePass *llvm::createGlobalOptimizerPass() { return new GlobalOpt(); }
Chris Lattner079236d2004-02-25 21:34:36 +000099
Dan Gohman844731a2008-05-13 00:00:25 +0000100namespace {
101
Chris Lattner7a90b682004-10-07 04:16:33 +0000102/// GlobalStatus - As we analyze each global, keep track of some information
103/// about it. If we find out that the address of the global is taken, none of
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000104/// this info will be accurate.
Nick Lewycky6726b6d2009-10-25 06:33:48 +0000105struct GlobalStatus {
Rafael Espindolac4440e32011-01-19 16:32:21 +0000106 /// isCompared - True if the global's address is used in a comparison.
107 bool isCompared;
108
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000109 /// isLoaded - True if the global is ever loaded. If the global isn't ever
110 /// loaded it can be deleted.
Chris Lattner7a90b682004-10-07 04:16:33 +0000111 bool isLoaded;
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000112
113 /// StoredType - Keep track of what stores to the global look like.
114 ///
Chris Lattner7a90b682004-10-07 04:16:33 +0000115 enum StoredType {
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000116 /// NotStored - There is no store to this global. It can thus be marked
117 /// constant.
118 NotStored,
119
120 /// isInitializerStored - This global is stored to, but the only thing
121 /// stored is the constant it was initialized with. This is only tracked
122 /// for scalar globals.
123 isInitializerStored,
124
125 /// isStoredOnce - This global is stored to, but only its initializer and
126 /// one other value is ever stored to it. If this global isStoredOnce, we
127 /// track the value stored to it in StoredOnceValue below. This is only
128 /// tracked for scalar globals.
129 isStoredOnce,
130
131 /// isStored - This global is stored to by multiple values or something else
132 /// that we cannot track.
133 isStored
Chris Lattner7a90b682004-10-07 04:16:33 +0000134 } StoredType;
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000135
136 /// StoredOnceValue - If only one value (besides the initializer constant) is
137 /// ever stored to this global, keep track of what value it is.
138 Value *StoredOnceValue;
139
Chris Lattner25de4e52006-11-01 18:03:33 +0000140 /// AccessingFunction/HasMultipleAccessingFunctions - These start out
141 /// null/false. When the first accessing function is noticed, it is recorded.
142 /// When a second different accessing function is noticed,
143 /// HasMultipleAccessingFunctions is set to true.
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000144 const Function *AccessingFunction;
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +0000145 bool HasMultipleAccessingFunctions;
146
Chris Lattner25de4e52006-11-01 18:03:33 +0000147 /// HasNonInstructionUser - Set to true if this global has a user that is not
148 /// an instruction (e.g. a constant expr or GV initializer).
Chris Lattner553ca522005-06-15 21:11:48 +0000149 bool HasNonInstructionUser;
150
Chris Lattner25de4e52006-11-01 18:03:33 +0000151 /// HasPHIUser - Set to true if this global has a user that is a PHI node.
152 bool HasPHIUser;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000153
Nick Lewyckyfad4d402012-02-05 19:56:38 +0000154 /// AtomicOrdering - Set to the strongest atomic ordering requirement.
155 AtomicOrdering Ordering;
156
Rafael Espindolac4440e32011-01-19 16:32:21 +0000157 GlobalStatus() : isCompared(false), isLoaded(false), StoredType(NotStored),
158 StoredOnceValue(0), AccessingFunction(0),
Nick Lewyckyfad4d402012-02-05 19:56:38 +0000159 HasMultipleAccessingFunctions(false),
160 HasNonInstructionUser(false), HasPHIUser(false),
161 Ordering(NotAtomic) {}
Chris Lattner7a90b682004-10-07 04:16:33 +0000162};
Chris Lattnere47ba742004-10-06 20:57:02 +0000163
Dan Gohman844731a2008-05-13 00:00:25 +0000164}
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000165
Nick Lewyckyfad4d402012-02-05 19:56:38 +0000166/// StrongerOrdering - Return the stronger of the two ordering. If the two
167/// orderings are acquire and release, then return AcquireRelease.
168///
169static AtomicOrdering StrongerOrdering(AtomicOrdering X, AtomicOrdering Y) {
170 if (X == Acquire && Y == Release) return AcquireRelease;
171 if (Y == Acquire && X == Release) return AcquireRelease;
172 return (AtomicOrdering)std::max(X, Y);
173}
174
Nick Lewyckybc384a12012-02-05 19:48:37 +0000175/// SafeToDestroyConstant - It is safe to destroy a constant iff it is only used
176/// by constants itself. Note that constants cannot be cyclic, so this test is
177/// pretty easy to implement recursively.
178///
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000179static bool SafeToDestroyConstant(const Constant *C) {
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000180 if (isa<GlobalValue>(C)) return false;
181
Gabor Greif27236912010-04-07 18:59:26 +0000182 for (Value::const_use_iterator UI = C->use_begin(), E = C->use_end(); UI != E;
183 ++UI)
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000184 if (const Constant *CU = dyn_cast<Constant>(*UI)) {
Jay Foade3acf152009-06-09 21:37:11 +0000185 if (!SafeToDestroyConstant(CU)) return false;
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000186 } else
187 return false;
188 return true;
189}
190
191
Chris Lattner7a90b682004-10-07 04:16:33 +0000192/// AnalyzeGlobal - Look at all uses of the global and fill in the GlobalStatus
193/// structure. If the global has its address taken, return true to indicate we
194/// can't do anything with it.
Chris Lattner079236d2004-02-25 21:34:36 +0000195///
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000196static bool AnalyzeGlobal(const Value *V, GlobalStatus &GS,
197 SmallPtrSet<const PHINode*, 16> &PHIUsers) {
Gabor Greif27236912010-04-07 18:59:26 +0000198 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;
Gabor Greife6642672010-07-09 16:51:20 +0000199 ++UI) {
200 const User *U = *UI;
201 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
Chris Lattner553ca522005-06-15 21:11:48 +0000202 GS.HasNonInstructionUser = true;
Chris Lattnerd91ed102011-01-01 22:31:46 +0000203
204 // If the result of the constantexpr isn't pointer type, then we won't
205 // know to expect it in various places. Just reject early.
206 if (!isa<PointerType>(CE->getType())) return true;
207
Chris Lattner7a90b682004-10-07 04:16:33 +0000208 if (AnalyzeGlobal(CE, GS, PHIUsers)) return true;
Gabor Greife6642672010-07-09 16:51:20 +0000209 } else if (const Instruction *I = dyn_cast<Instruction>(U)) {
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +0000210 if (!GS.HasMultipleAccessingFunctions) {
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000211 const Function *F = I->getParent()->getParent();
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +0000212 if (GS.AccessingFunction == 0)
213 GS.AccessingFunction = F;
214 else if (GS.AccessingFunction != F)
215 GS.HasMultipleAccessingFunctions = true;
216 }
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000217 if (const LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattner7a90b682004-10-07 04:16:33 +0000218 GS.isLoaded = true;
Nick Lewyckyfad4d402012-02-05 19:56:38 +0000219 // Don't hack on volatile loads.
220 if (LI->isVolatile()) return true;
221 GS.Ordering = StrongerOrdering(GS.Ordering, LI->getOrdering());
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000222 } else if (const StoreInst *SI = dyn_cast<StoreInst>(I)) {
Chris Lattner36025492004-10-07 06:01:25 +0000223 // Don't allow a store OF the address, only stores TO the address.
224 if (SI->getOperand(0) == V) return true;
225
Nick Lewyckyfad4d402012-02-05 19:56:38 +0000226 // Don't hack on volatile stores.
227 if (SI->isVolatile()) return true;
228 GS.Ordering = StrongerOrdering(GS.Ordering, SI->getOrdering());
Chris Lattnerc69d3c92008-01-29 19:01:37 +0000229
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000230 // If this is a direct store to the global (i.e., the global is a scalar
231 // value, not an aggregate), keep more specific information about
232 // stores.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000233 if (GS.StoredType != GlobalStatus::isStored) {
Gabor Greif27236912010-04-07 18:59:26 +0000234 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(
235 SI->getOperand(1))) {
Chris Lattnerbd38edf2004-11-14 20:50:30 +0000236 Value *StoredVal = SI->getOperand(0);
237 if (StoredVal == GV->getInitializer()) {
238 if (GS.StoredType < GlobalStatus::isInitializerStored)
239 GS.StoredType = GlobalStatus::isInitializerStored;
240 } else if (isa<LoadInst>(StoredVal) &&
241 cast<LoadInst>(StoredVal)->getOperand(0) == GV) {
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000242 if (GS.StoredType < GlobalStatus::isInitializerStored)
243 GS.StoredType = GlobalStatus::isInitializerStored;
244 } else if (GS.StoredType < GlobalStatus::isStoredOnce) {
245 GS.StoredType = GlobalStatus::isStoredOnce;
Chris Lattnerbd38edf2004-11-14 20:50:30 +0000246 GS.StoredOnceValue = StoredVal;
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000247 } else if (GS.StoredType == GlobalStatus::isStoredOnce &&
Chris Lattnerbd38edf2004-11-14 20:50:30 +0000248 GS.StoredOnceValue == StoredVal) {
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000249 // noop.
250 } else {
251 GS.StoredType = GlobalStatus::isStored;
252 }
253 } else {
Chris Lattner7a90b682004-10-07 04:16:33 +0000254 GS.StoredType = GlobalStatus::isStored;
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000255 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000256 }
Duncan Sandsb2fe7f12012-07-02 18:55:39 +0000257 } else if (isa<BitCastInst>(I)) {
258 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Chris Lattner35c81b02005-02-27 18:58:52 +0000259 } else if (isa<GetElementPtrInst>(I)) {
Chris Lattner7a90b682004-10-07 04:16:33 +0000260 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Chris Lattner35c81b02005-02-27 18:58:52 +0000261 } else if (isa<SelectInst>(I)) {
Chris Lattner7a90b682004-10-07 04:16:33 +0000262 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000263 } else if (const PHINode *PN = dyn_cast<PHINode>(I)) {
Chris Lattner7a90b682004-10-07 04:16:33 +0000264 // PHI nodes we can check just like select or GEP instructions, but we
265 // have to be careful about infinite recursion.
Chris Lattner5a6bb6a2008-12-16 07:34:30 +0000266 if (PHIUsers.insert(PN)) // Not already visited.
Chris Lattner7a90b682004-10-07 04:16:33 +0000267 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Chris Lattner25de4e52006-11-01 18:03:33 +0000268 GS.HasPHIUser = true;
Reid Spencere4d87aa2006-12-23 06:05:41 +0000269 } else if (isa<CmpInst>(I)) {
Rafael Espindolac4440e32011-01-19 16:32:21 +0000270 GS.isCompared = true;
Nick Lewycky1f237b02011-05-29 18:41:56 +0000271 } else if (const MemTransferInst *MTI = dyn_cast<MemTransferInst>(I)) {
272 if (MTI->isVolatile()) return true;
Gabor Greif9e4f2432010-06-24 14:42:01 +0000273 if (MTI->getArgOperand(0) == V)
Eric Christopher551754c2010-04-16 23:37:20 +0000274 GS.StoredType = GlobalStatus::isStored;
Gabor Greif9e4f2432010-06-24 14:42:01 +0000275 if (MTI->getArgOperand(1) == V)
Chris Lattner35c81b02005-02-27 18:58:52 +0000276 GS.isLoaded = true;
Nick Lewycky1f237b02011-05-29 18:41:56 +0000277 } else if (const MemSetInst *MSI = dyn_cast<MemSetInst>(I)) {
278 assert(MSI->getArgOperand(0) == V && "Memset only takes one pointer!");
279 if (MSI->isVolatile()) return true;
Chris Lattner35c81b02005-02-27 18:58:52 +0000280 GS.StoredType = GlobalStatus::isStored;
Chris Lattner7a90b682004-10-07 04:16:33 +0000281 } else {
282 return true; // Any other non-load instruction might take address!
Chris Lattner9ce30002004-07-20 03:58:07 +0000283 }
Gabor Greife6642672010-07-09 16:51:20 +0000284 } else if (const Constant *C = dyn_cast<Constant>(U)) {
Chris Lattner553ca522005-06-15 21:11:48 +0000285 GS.HasNonInstructionUser = true;
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000286 // We might have a dead and dangling constant hanging off of here.
Jay Foade3acf152009-06-09 21:37:11 +0000287 if (!SafeToDestroyConstant(C))
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000288 return true;
Chris Lattner079236d2004-02-25 21:34:36 +0000289 } else {
Chris Lattner553ca522005-06-15 21:11:48 +0000290 GS.HasNonInstructionUser = true;
291 // Otherwise must be some other user.
Chris Lattner079236d2004-02-25 21:34:36 +0000292 return true;
293 }
Gabor Greife6642672010-07-09 16:51:20 +0000294 }
Chris Lattner079236d2004-02-25 21:34:36 +0000295
296 return false;
297}
298
Chris Lattnere47ba742004-10-06 20:57:02 +0000299/// CleanupConstantGlobalUsers - We just marked GV constant. Loop over all
300/// users of the global, cleaning up the obvious ones. This is largely just a
Chris Lattner031955d2004-10-10 16:43:46 +0000301/// quick scan over the use list to clean up the easy and obvious cruft. This
302/// returns true if it made a change.
Nick Lewycky6a577f82012-02-12 01:13:18 +0000303static bool CleanupConstantGlobalUsers(Value *V, Constant *Init,
304 TargetData *TD, TargetLibraryInfo *TLI) {
Chris Lattner031955d2004-10-10 16:43:46 +0000305 bool Changed = false;
Chris Lattner7a90b682004-10-07 04:16:33 +0000306 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;) {
307 User *U = *UI++;
Misha Brukmanfd939082005-04-21 23:48:37 +0000308
Chris Lattner7a90b682004-10-07 04:16:33 +0000309 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
Chris Lattner35c81b02005-02-27 18:58:52 +0000310 if (Init) {
311 // Replace the load with the initializer.
312 LI->replaceAllUsesWith(Init);
313 LI->eraseFromParent();
314 Changed = true;
315 }
Chris Lattner7a90b682004-10-07 04:16:33 +0000316 } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
Chris Lattnere47ba742004-10-06 20:57:02 +0000317 // Store must be unreachable or storing Init into the global.
Chris Lattner7a7ed022004-10-16 18:09:00 +0000318 SI->eraseFromParent();
Chris Lattner031955d2004-10-10 16:43:46 +0000319 Changed = true;
Chris Lattner7a90b682004-10-07 04:16:33 +0000320 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
321 if (CE->getOpcode() == Instruction::GetElementPtr) {
Chris Lattneraae4a1c2005-09-26 07:34:35 +0000322 Constant *SubInit = 0;
323 if (Init)
Dan Gohmanc6f69e92009-10-05 16:36:26 +0000324 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
Nick Lewycky6a577f82012-02-12 01:13:18 +0000325 Changed |= CleanupConstantGlobalUsers(CE, SubInit, TD, TLI);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000326 } else if (CE->getOpcode() == Instruction::BitCast &&
Duncan Sands1df98592010-02-16 11:11:14 +0000327 CE->getType()->isPointerTy()) {
Chris Lattner35c81b02005-02-27 18:58:52 +0000328 // Pointer cast, delete any stores and memsets to the global.
Nick Lewycky6a577f82012-02-12 01:13:18 +0000329 Changed |= CleanupConstantGlobalUsers(CE, 0, TD, TLI);
Chris Lattner35c81b02005-02-27 18:58:52 +0000330 }
331
332 if (CE->use_empty()) {
333 CE->destroyConstant();
334 Changed = true;
Chris Lattner7a90b682004-10-07 04:16:33 +0000335 }
336 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
Chris Lattner7b52fe72007-11-09 17:33:02 +0000337 // Do not transform "gepinst (gep constexpr (GV))" here, because forming
338 // "gepconstexpr (gep constexpr (GV))" will cause the two gep's to fold
339 // and will invalidate our notion of what Init is.
Chris Lattner19450242007-11-13 21:46:23 +0000340 Constant *SubInit = 0;
Chris Lattner7b52fe72007-11-09 17:33:02 +0000341 if (!isa<ConstantExpr>(GEP->getOperand(0))) {
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000342 ConstantExpr *CE =
Nick Lewycky6a577f82012-02-12 01:13:18 +0000343 dyn_cast_or_null<ConstantExpr>(ConstantFoldInstruction(GEP, TD, TLI));
Chris Lattner7b52fe72007-11-09 17:33:02 +0000344 if (Init && CE && CE->getOpcode() == Instruction::GetElementPtr)
Dan Gohmanc6f69e92009-10-05 16:36:26 +0000345 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
Benjamin Kramerc1ea16e2012-03-28 14:50:09 +0000346
347 // If the initializer is an all-null value and we have an inbounds GEP,
348 // we already know what the result of any load from that GEP is.
349 // TODO: Handle splats.
350 if (Init && isa<ConstantAggregateZero>(Init) && GEP->isInBounds())
351 SubInit = Constant::getNullValue(GEP->getType()->getElementType());
Chris Lattner7b52fe72007-11-09 17:33:02 +0000352 }
Nick Lewycky6a577f82012-02-12 01:13:18 +0000353 Changed |= CleanupConstantGlobalUsers(GEP, SubInit, TD, TLI);
Chris Lattnerc4d81b02004-10-10 16:47:33 +0000354
Chris Lattner031955d2004-10-10 16:43:46 +0000355 if (GEP->use_empty()) {
Chris Lattner7a7ed022004-10-16 18:09:00 +0000356 GEP->eraseFromParent();
Chris Lattner031955d2004-10-10 16:43:46 +0000357 Changed = true;
358 }
Chris Lattner35c81b02005-02-27 18:58:52 +0000359 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U)) { // memset/cpy/mv
360 if (MI->getRawDest() == V) {
361 MI->eraseFromParent();
362 Changed = true;
363 }
364
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000365 } else if (Constant *C = dyn_cast<Constant>(U)) {
366 // If we have a chain of dead constantexprs or other things dangling from
367 // us, and if they are all dead, nuke them without remorse.
Jay Foade3acf152009-06-09 21:37:11 +0000368 if (SafeToDestroyConstant(C)) {
Devang Patel743cdf82009-03-06 01:37:41 +0000369 C->destroyConstant();
Chris Lattner35c81b02005-02-27 18:58:52 +0000370 // This could have invalidated UI, start over from scratch.
Nick Lewycky6a577f82012-02-12 01:13:18 +0000371 CleanupConstantGlobalUsers(V, Init, TD, TLI);
Chris Lattner031955d2004-10-10 16:43:46 +0000372 return true;
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000373 }
Chris Lattnere47ba742004-10-06 20:57:02 +0000374 }
375 }
Chris Lattner031955d2004-10-10 16:43:46 +0000376 return Changed;
Chris Lattnere47ba742004-10-06 20:57:02 +0000377}
378
Chris Lattner941db492008-01-14 02:09:12 +0000379/// isSafeSROAElementUse - Return true if the specified instruction is a safe
380/// user of a derived expression from a global that we want to SROA.
381static bool isSafeSROAElementUse(Value *V) {
382 // We might have a dead and dangling constant hanging off of here.
383 if (Constant *C = dyn_cast<Constant>(V))
Jay Foade3acf152009-06-09 21:37:11 +0000384 return SafeToDestroyConstant(C);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000385
Chris Lattner941db492008-01-14 02:09:12 +0000386 Instruction *I = dyn_cast<Instruction>(V);
387 if (!I) return false;
388
389 // Loads are ok.
390 if (isa<LoadInst>(I)) return true;
391
392 // Stores *to* the pointer are ok.
393 if (StoreInst *SI = dyn_cast<StoreInst>(I))
394 return SI->getOperand(0) != V;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000395
Chris Lattner941db492008-01-14 02:09:12 +0000396 // Otherwise, it must be a GEP.
397 GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I);
398 if (GEPI == 0) return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000399
Chris Lattner941db492008-01-14 02:09:12 +0000400 if (GEPI->getNumOperands() < 3 || !isa<Constant>(GEPI->getOperand(1)) ||
401 !cast<Constant>(GEPI->getOperand(1))->isNullValue())
402 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000403
Chris Lattner941db492008-01-14 02:09:12 +0000404 for (Value::use_iterator I = GEPI->use_begin(), E = GEPI->use_end();
405 I != E; ++I)
406 if (!isSafeSROAElementUse(*I))
407 return false;
Chris Lattner727c2102008-01-14 01:31:05 +0000408 return true;
409}
410
Chris Lattner941db492008-01-14 02:09:12 +0000411
412/// IsUserOfGlobalSafeForSRA - U is a direct user of the specified global value.
413/// Look at it and its uses and decide whether it is safe to SROA this global.
414///
415static bool IsUserOfGlobalSafeForSRA(User *U, GlobalValue *GV) {
416 // The user of the global must be a GEP Inst or a ConstantExpr GEP.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000417 if (!isa<GetElementPtrInst>(U) &&
418 (!isa<ConstantExpr>(U) ||
Chris Lattner941db492008-01-14 02:09:12 +0000419 cast<ConstantExpr>(U)->getOpcode() != Instruction::GetElementPtr))
420 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000421
Chris Lattner941db492008-01-14 02:09:12 +0000422 // Check to see if this ConstantExpr GEP is SRA'able. In particular, we
423 // don't like < 3 operand CE's, and we don't like non-constant integer
424 // indices. This enforces that all uses are 'gep GV, 0, C, ...' for some
425 // value of C.
426 if (U->getNumOperands() < 3 || !isa<Constant>(U->getOperand(1)) ||
427 !cast<Constant>(U->getOperand(1))->isNullValue() ||
428 !isa<ConstantInt>(U->getOperand(2)))
429 return false;
430
431 gep_type_iterator GEPI = gep_type_begin(U), E = gep_type_end(U);
432 ++GEPI; // Skip over the pointer index.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000433
Chris Lattner941db492008-01-14 02:09:12 +0000434 // If this is a use of an array allocation, do a bit more checking for sanity.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000435 if (ArrayType *AT = dyn_cast<ArrayType>(*GEPI)) {
Chris Lattner941db492008-01-14 02:09:12 +0000436 uint64_t NumElements = AT->getNumElements();
437 ConstantInt *Idx = cast<ConstantInt>(U->getOperand(2));
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000438
Chris Lattner941db492008-01-14 02:09:12 +0000439 // Check to make sure that index falls within the array. If not,
440 // something funny is going on, so we won't do the optimization.
441 //
442 if (Idx->getZExtValue() >= NumElements)
443 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000444
Chris Lattner941db492008-01-14 02:09:12 +0000445 // We cannot scalar repl this level of the array unless any array
446 // sub-indices are in-range constants. In particular, consider:
447 // A[0][i]. We cannot know that the user isn't doing invalid things like
448 // allowing i to index an out-of-range subscript that accesses A[1].
449 //
450 // Scalar replacing *just* the outer index of the array is probably not
451 // going to be a win anyway, so just give up.
452 for (++GEPI; // Skip array index.
Dan Gohman6874a2a2009-08-18 14:58:19 +0000453 GEPI != E;
Chris Lattner941db492008-01-14 02:09:12 +0000454 ++GEPI) {
455 uint64_t NumElements;
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000456 if (ArrayType *SubArrayTy = dyn_cast<ArrayType>(*GEPI))
Chris Lattner941db492008-01-14 02:09:12 +0000457 NumElements = SubArrayTy->getNumElements();
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000458 else if (VectorType *SubVectorTy = dyn_cast<VectorType>(*GEPI))
Dan Gohman6874a2a2009-08-18 14:58:19 +0000459 NumElements = SubVectorTy->getNumElements();
460 else {
Duncan Sands1df98592010-02-16 11:11:14 +0000461 assert((*GEPI)->isStructTy() &&
Dan Gohman6874a2a2009-08-18 14:58:19 +0000462 "Indexed GEP type is not array, vector, or struct!");
463 continue;
464 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000465
Chris Lattner941db492008-01-14 02:09:12 +0000466 ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPI.getOperand());
467 if (!IdxVal || IdxVal->getZExtValue() >= NumElements)
468 return false;
469 }
470 }
471
472 for (Value::use_iterator I = U->use_begin(), E = U->use_end(); I != E; ++I)
473 if (!isSafeSROAElementUse(*I))
474 return false;
475 return true;
476}
477
478/// GlobalUsersSafeToSRA - Look at all uses of the global and decide whether it
479/// is safe for us to perform this transformation.
480///
481static bool GlobalUsersSafeToSRA(GlobalValue *GV) {
482 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end();
483 UI != E; ++UI) {
484 if (!IsUserOfGlobalSafeForSRA(*UI, GV))
485 return false;
486 }
487 return true;
488}
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000489
Chris Lattner941db492008-01-14 02:09:12 +0000490
Chris Lattner670c8892004-10-08 17:32:09 +0000491/// SRAGlobal - Perform scalar replacement of aggregates on the specified global
492/// variable. This opens the door for other optimizations by exposing the
493/// behavior of the program in a more fine-grained way. We have determined that
494/// this transformation is safe already. We return the first global variable we
495/// insert so that the caller can reprocess it.
Chris Lattner7b550cc2009-11-06 04:27:31 +0000496static GlobalVariable *SRAGlobal(GlobalVariable *GV, const TargetData &TD) {
Chris Lattner727c2102008-01-14 01:31:05 +0000497 // Make sure this global only has simple uses that we can SRA.
Chris Lattner941db492008-01-14 02:09:12 +0000498 if (!GlobalUsersSafeToSRA(GV))
Chris Lattner727c2102008-01-14 01:31:05 +0000499 return 0;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000500
Rafael Espindolabb46f522009-01-15 20:18:42 +0000501 assert(GV->hasLocalLinkage() && !GV->isConstant());
Chris Lattner670c8892004-10-08 17:32:09 +0000502 Constant *Init = GV->getInitializer();
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000503 Type *Ty = Init->getType();
Misha Brukmanfd939082005-04-21 23:48:37 +0000504
Chris Lattner670c8892004-10-08 17:32:09 +0000505 std::vector<GlobalVariable*> NewGlobals;
506 Module::GlobalListType &Globals = GV->getParent()->getGlobalList();
507
Chris Lattner998182b2008-04-26 07:40:11 +0000508 // Get the alignment of the global, either explicit or target-specific.
509 unsigned StartAlignment = GV->getAlignment();
510 if (StartAlignment == 0)
511 StartAlignment = TD.getABITypeAlignment(GV->getType());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000512
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000513 if (StructType *STy = dyn_cast<StructType>(Ty)) {
Chris Lattner670c8892004-10-08 17:32:09 +0000514 NewGlobals.reserve(STy->getNumElements());
Chris Lattner998182b2008-04-26 07:40:11 +0000515 const StructLayout &Layout = *TD.getStructLayout(STy);
Chris Lattner670c8892004-10-08 17:32:09 +0000516 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
Chris Lattnera1f00f42012-01-25 06:48:06 +0000517 Constant *In = Init->getAggregateElement(i);
Chris Lattner670c8892004-10-08 17:32:09 +0000518 assert(In && "Couldn't get element of initializer?");
Chris Lattner7b550cc2009-11-06 04:27:31 +0000519 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(i), false,
Chris Lattner670c8892004-10-08 17:32:09 +0000520 GlobalVariable::InternalLinkage,
Daniel Dunbarfe09b202009-07-30 17:37:43 +0000521 In, GV->getName()+"."+Twine(i),
Hans Wennborgce718ff2012-06-23 11:37:03 +0000522 GV->getThreadLocalMode(),
Owen Anderson3d29df32009-07-08 01:26:06 +0000523 GV->getType()->getAddressSpace());
Chris Lattner670c8892004-10-08 17:32:09 +0000524 Globals.insert(GV, NGV);
525 NewGlobals.push_back(NGV);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000526
Chris Lattner998182b2008-04-26 07:40:11 +0000527 // Calculate the known alignment of the field. If the original aggregate
528 // had 256 byte alignment for example, something might depend on that:
529 // propagate info to each field.
530 uint64_t FieldOffset = Layout.getElementOffset(i);
531 unsigned NewAlign = (unsigned)MinAlign(StartAlignment, FieldOffset);
532 if (NewAlign > TD.getABITypeAlignment(STy->getElementType(i)))
533 NGV->setAlignment(NewAlign);
Chris Lattner670c8892004-10-08 17:32:09 +0000534 }
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000535 } else if (SequentialType *STy = dyn_cast<SequentialType>(Ty)) {
Chris Lattner670c8892004-10-08 17:32:09 +0000536 unsigned NumElements = 0;
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000537 if (ArrayType *ATy = dyn_cast<ArrayType>(STy))
Chris Lattner670c8892004-10-08 17:32:09 +0000538 NumElements = ATy->getNumElements();
Chris Lattner670c8892004-10-08 17:32:09 +0000539 else
Chris Lattner998182b2008-04-26 07:40:11 +0000540 NumElements = cast<VectorType>(STy)->getNumElements();
Chris Lattner670c8892004-10-08 17:32:09 +0000541
Chris Lattner1f21ef12005-02-23 16:53:04 +0000542 if (NumElements > 16 && GV->hasNUsesOrMore(16))
Chris Lattnerd514d822005-02-01 01:23:31 +0000543 return 0; // It's not worth it.
Chris Lattner670c8892004-10-08 17:32:09 +0000544 NewGlobals.reserve(NumElements);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000545
Duncan Sands777d2302009-05-09 07:06:46 +0000546 uint64_t EltSize = TD.getTypeAllocSize(STy->getElementType());
Chris Lattner998182b2008-04-26 07:40:11 +0000547 unsigned EltAlign = TD.getABITypeAlignment(STy->getElementType());
Chris Lattner670c8892004-10-08 17:32:09 +0000548 for (unsigned i = 0, e = NumElements; i != e; ++i) {
Chris Lattnera1f00f42012-01-25 06:48:06 +0000549 Constant *In = Init->getAggregateElement(i);
Chris Lattner670c8892004-10-08 17:32:09 +0000550 assert(In && "Couldn't get element of initializer?");
551
Chris Lattner7b550cc2009-11-06 04:27:31 +0000552 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(), false,
Chris Lattner670c8892004-10-08 17:32:09 +0000553 GlobalVariable::InternalLinkage,
Daniel Dunbarfe09b202009-07-30 17:37:43 +0000554 In, GV->getName()+"."+Twine(i),
Hans Wennborgce718ff2012-06-23 11:37:03 +0000555 GV->getThreadLocalMode(),
Owen Andersone9b11b42009-07-08 19:03:57 +0000556 GV->getType()->getAddressSpace());
Chris Lattner670c8892004-10-08 17:32:09 +0000557 Globals.insert(GV, NGV);
558 NewGlobals.push_back(NGV);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000559
Chris Lattner998182b2008-04-26 07:40:11 +0000560 // Calculate the known alignment of the field. If the original aggregate
561 // had 256 byte alignment for example, something might depend on that:
562 // propagate info to each field.
563 unsigned NewAlign = (unsigned)MinAlign(StartAlignment, EltSize*i);
564 if (NewAlign > EltAlign)
565 NGV->setAlignment(NewAlign);
Chris Lattner670c8892004-10-08 17:32:09 +0000566 }
567 }
568
569 if (NewGlobals.empty())
570 return 0;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000571
David Greene3215b0e2010-01-05 01:28:05 +0000572 DEBUG(dbgs() << "PERFORMING GLOBAL SRA ON: " << *GV);
Chris Lattner30ba5692004-10-11 05:54:41 +0000573
Chris Lattner7b550cc2009-11-06 04:27:31 +0000574 Constant *NullInt =Constant::getNullValue(Type::getInt32Ty(GV->getContext()));
Chris Lattner670c8892004-10-08 17:32:09 +0000575
576 // Loop over all of the uses of the global, replacing the constantexpr geps,
577 // with smaller constantexpr geps or direct references.
578 while (!GV->use_empty()) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000579 User *GEP = GV->use_back();
580 assert(((isa<ConstantExpr>(GEP) &&
581 cast<ConstantExpr>(GEP)->getOpcode()==Instruction::GetElementPtr)||
582 isa<GetElementPtrInst>(GEP)) && "NonGEP CE's are not SRAable!");
Misha Brukmanfd939082005-04-21 23:48:37 +0000583
Chris Lattner670c8892004-10-08 17:32:09 +0000584 // Ignore the 1th operand, which has to be zero or else the program is quite
585 // broken (undefined). Get the 2nd operand, which is the structure or array
586 // index.
Reid Spencerb83eb642006-10-20 07:07:24 +0000587 unsigned Val = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
Chris Lattner670c8892004-10-08 17:32:09 +0000588 if (Val >= NewGlobals.size()) Val = 0; // Out of bound array access.
589
Chris Lattner30ba5692004-10-11 05:54:41 +0000590 Value *NewPtr = NewGlobals[Val];
Chris Lattner670c8892004-10-08 17:32:09 +0000591
592 // Form a shorter GEP if needed.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000593 if (GEP->getNumOperands() > 3) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000594 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEP)) {
Chris Lattner55eb1c42007-01-31 04:40:53 +0000595 SmallVector<Constant*, 8> Idxs;
Chris Lattner30ba5692004-10-11 05:54:41 +0000596 Idxs.push_back(NullInt);
597 for (unsigned i = 3, e = CE->getNumOperands(); i != e; ++i)
598 Idxs.push_back(CE->getOperand(i));
Jay Foaddab3d292011-07-21 14:31:17 +0000599 NewPtr = ConstantExpr::getGetElementPtr(cast<Constant>(NewPtr), Idxs);
Chris Lattner30ba5692004-10-11 05:54:41 +0000600 } else {
601 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(GEP);
Chris Lattner699d1442007-01-31 19:59:55 +0000602 SmallVector<Value*, 8> Idxs;
Chris Lattner30ba5692004-10-11 05:54:41 +0000603 Idxs.push_back(NullInt);
604 for (unsigned i = 3, e = GEPI->getNumOperands(); i != e; ++i)
605 Idxs.push_back(GEPI->getOperand(i));
Jay Foada9203102011-07-25 09:48:08 +0000606 NewPtr = GetElementPtrInst::Create(NewPtr, Idxs,
Daniel Dunbarfe09b202009-07-30 17:37:43 +0000607 GEPI->getName()+"."+Twine(Val),GEPI);
Chris Lattner30ba5692004-10-11 05:54:41 +0000608 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000609 }
Chris Lattner30ba5692004-10-11 05:54:41 +0000610 GEP->replaceAllUsesWith(NewPtr);
611
612 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(GEP))
Chris Lattner7a7ed022004-10-16 18:09:00 +0000613 GEPI->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +0000614 else
615 cast<ConstantExpr>(GEP)->destroyConstant();
Chris Lattner670c8892004-10-08 17:32:09 +0000616 }
617
Chris Lattnere40e2d12004-10-08 20:25:55 +0000618 // Delete the old global, now that it is dead.
619 Globals.erase(GV);
Chris Lattner670c8892004-10-08 17:32:09 +0000620 ++NumSRA;
Chris Lattner30ba5692004-10-11 05:54:41 +0000621
622 // Loop over the new globals array deleting any globals that are obviously
623 // dead. This can arise due to scalarization of a structure or an array that
624 // has elements that are dead.
625 unsigned FirstGlobal = 0;
626 for (unsigned i = 0, e = NewGlobals.size(); i != e; ++i)
627 if (NewGlobals[i]->use_empty()) {
628 Globals.erase(NewGlobals[i]);
629 if (FirstGlobal == i) ++FirstGlobal;
630 }
631
632 return FirstGlobal != NewGlobals.size() ? NewGlobals[FirstGlobal] : 0;
Chris Lattner670c8892004-10-08 17:32:09 +0000633}
634
Chris Lattner9b34a612004-10-09 21:48:45 +0000635/// AllUsesOfValueWillTrapIfNull - Return true if all users of the specified
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000636/// value will trap if the value is dynamically null. PHIs keeps track of any
Chris Lattner81686182007-09-13 16:30:19 +0000637/// phi nodes we've seen to avoid reprocessing them.
Gabor Greif6ce02b52010-04-06 19:24:18 +0000638static bool AllUsesOfValueWillTrapIfNull(const Value *V,
639 SmallPtrSet<const PHINode*, 8> &PHIs) {
640 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;
Gabor Greifa01d6db2010-04-06 19:14:05 +0000641 ++UI) {
Gabor Greif6ce02b52010-04-06 19:24:18 +0000642 const User *U = *UI;
Gabor Greifa01d6db2010-04-06 19:14:05 +0000643
644 if (isa<LoadInst>(U)) {
Chris Lattner9b34a612004-10-09 21:48:45 +0000645 // Will trap.
Gabor Greif6ce02b52010-04-06 19:24:18 +0000646 } else if (const StoreInst *SI = dyn_cast<StoreInst>(U)) {
Chris Lattner9b34a612004-10-09 21:48:45 +0000647 if (SI->getOperand(0) == V) {
Gabor Greifa01d6db2010-04-06 19:14:05 +0000648 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner9b34a612004-10-09 21:48:45 +0000649 return false; // Storing the value.
650 }
Gabor Greif6ce02b52010-04-06 19:24:18 +0000651 } else if (const CallInst *CI = dyn_cast<CallInst>(U)) {
Gabor Greif654c06f2010-03-20 21:00:25 +0000652 if (CI->getCalledValue() != V) {
Gabor Greifa01d6db2010-04-06 19:14:05 +0000653 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner9b34a612004-10-09 21:48:45 +0000654 return false; // Not calling the ptr
655 }
Gabor Greif6ce02b52010-04-06 19:24:18 +0000656 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(U)) {
Gabor Greif654c06f2010-03-20 21:00:25 +0000657 if (II->getCalledValue() != V) {
Gabor Greifa01d6db2010-04-06 19:14:05 +0000658 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner9b34a612004-10-09 21:48:45 +0000659 return false; // Not calling the ptr
660 }
Gabor Greif6ce02b52010-04-06 19:24:18 +0000661 } else if (const BitCastInst *CI = dyn_cast<BitCastInst>(U)) {
Chris Lattner81686182007-09-13 16:30:19 +0000662 if (!AllUsesOfValueWillTrapIfNull(CI, PHIs)) return false;
Gabor Greif6ce02b52010-04-06 19:24:18 +0000663 } else if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
Chris Lattner81686182007-09-13 16:30:19 +0000664 if (!AllUsesOfValueWillTrapIfNull(GEPI, PHIs)) return false;
Gabor Greif6ce02b52010-04-06 19:24:18 +0000665 } else if (const PHINode *PN = dyn_cast<PHINode>(U)) {
Chris Lattner81686182007-09-13 16:30:19 +0000666 // If we've already seen this phi node, ignore it, it has already been
667 // checked.
Jakob Stoklund Olesenb489d0f2010-01-29 23:54:14 +0000668 if (PHIs.insert(PN) && !AllUsesOfValueWillTrapIfNull(PN, PHIs))
669 return false;
Gabor Greifa01d6db2010-04-06 19:14:05 +0000670 } else if (isa<ICmpInst>(U) &&
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000671 isa<ConstantPointerNull>(UI->getOperand(1))) {
Nick Lewyckye7ee59b2010-02-25 06:39:10 +0000672 // Ignore icmp X, null
Chris Lattner9b34a612004-10-09 21:48:45 +0000673 } else {
Gabor Greifa01d6db2010-04-06 19:14:05 +0000674 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner9b34a612004-10-09 21:48:45 +0000675 return false;
676 }
Gabor Greifa01d6db2010-04-06 19:14:05 +0000677 }
Chris Lattner9b34a612004-10-09 21:48:45 +0000678 return true;
679}
680
681/// AllUsesOfLoadedValueWillTrapIfNull - Return true if all uses of any loads
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000682/// from GV will trap if the loaded value is null. Note that this also permits
683/// comparisons of the loaded value against null, as a special case.
Gabor Greif6ce02b52010-04-06 19:24:18 +0000684static bool AllUsesOfLoadedValueWillTrapIfNull(const GlobalVariable *GV) {
685 for (Value::const_use_iterator UI = GV->use_begin(), E = GV->use_end();
Gabor Greifa01d6db2010-04-06 19:14:05 +0000686 UI != E; ++UI) {
Gabor Greif6ce02b52010-04-06 19:24:18 +0000687 const User *U = *UI;
Gabor Greifa01d6db2010-04-06 19:14:05 +0000688
Gabor Greif6ce02b52010-04-06 19:24:18 +0000689 if (const LoadInst *LI = dyn_cast<LoadInst>(U)) {
690 SmallPtrSet<const PHINode*, 8> PHIs;
Chris Lattner81686182007-09-13 16:30:19 +0000691 if (!AllUsesOfValueWillTrapIfNull(LI, PHIs))
Chris Lattner9b34a612004-10-09 21:48:45 +0000692 return false;
Gabor Greifa01d6db2010-04-06 19:14:05 +0000693 } else if (isa<StoreInst>(U)) {
Chris Lattner9b34a612004-10-09 21:48:45 +0000694 // Ignore stores to the global.
695 } else {
696 // We don't know or understand this user, bail out.
Gabor Greifa01d6db2010-04-06 19:14:05 +0000697 //cerr << "UNKNOWN USER OF GLOBAL!: " << *U;
Chris Lattner9b34a612004-10-09 21:48:45 +0000698 return false;
699 }
Gabor Greifa01d6db2010-04-06 19:14:05 +0000700 }
Chris Lattner9b34a612004-10-09 21:48:45 +0000701 return true;
702}
703
Chris Lattner7b550cc2009-11-06 04:27:31 +0000704static bool OptimizeAwayTrappingUsesOfValue(Value *V, Constant *NewV) {
Chris Lattner708148e2004-10-10 23:14:11 +0000705 bool Changed = false;
706 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ) {
707 Instruction *I = cast<Instruction>(*UI++);
708 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
709 LI->setOperand(0, NewV);
710 Changed = true;
711 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
712 if (SI->getOperand(1) == V) {
713 SI->setOperand(1, NewV);
714 Changed = true;
715 }
716 } else if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
Gabor Greiffa1f5c22010-04-06 18:45:08 +0000717 CallSite CS(I);
718 if (CS.getCalledValue() == V) {
Chris Lattner708148e2004-10-10 23:14:11 +0000719 // Calling through the pointer! Turn into a direct call, but be careful
720 // that the pointer is not also being passed as an argument.
Gabor Greiffa1f5c22010-04-06 18:45:08 +0000721 CS.setCalledFunction(NewV);
Chris Lattner708148e2004-10-10 23:14:11 +0000722 Changed = true;
723 bool PassedAsArg = false;
Gabor Greiffa1f5c22010-04-06 18:45:08 +0000724 for (unsigned i = 0, e = CS.arg_size(); i != e; ++i)
725 if (CS.getArgument(i) == V) {
Chris Lattner708148e2004-10-10 23:14:11 +0000726 PassedAsArg = true;
Gabor Greiffa1f5c22010-04-06 18:45:08 +0000727 CS.setArgument(i, NewV);
Chris Lattner708148e2004-10-10 23:14:11 +0000728 }
729
730 if (PassedAsArg) {
731 // Being passed as an argument also. Be careful to not invalidate UI!
732 UI = V->use_begin();
733 }
734 }
735 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
736 Changed |= OptimizeAwayTrappingUsesOfValue(CI,
Owen Andersonbaf3c402009-07-29 18:55:55 +0000737 ConstantExpr::getCast(CI->getOpcode(),
Chris Lattner7b550cc2009-11-06 04:27:31 +0000738 NewV, CI->getType()));
Chris Lattner708148e2004-10-10 23:14:11 +0000739 if (CI->use_empty()) {
740 Changed = true;
Chris Lattner7a7ed022004-10-16 18:09:00 +0000741 CI->eraseFromParent();
Chris Lattner708148e2004-10-10 23:14:11 +0000742 }
743 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
744 // Should handle GEP here.
Chris Lattner55eb1c42007-01-31 04:40:53 +0000745 SmallVector<Constant*, 8> Idxs;
746 Idxs.reserve(GEPI->getNumOperands()-1);
Gabor Greif5e463212008-05-29 01:59:18 +0000747 for (User::op_iterator i = GEPI->op_begin() + 1, e = GEPI->op_end();
748 i != e; ++i)
749 if (Constant *C = dyn_cast<Constant>(*i))
Chris Lattner55eb1c42007-01-31 04:40:53 +0000750 Idxs.push_back(C);
Chris Lattner708148e2004-10-10 23:14:11 +0000751 else
752 break;
Chris Lattner55eb1c42007-01-31 04:40:53 +0000753 if (Idxs.size() == GEPI->getNumOperands()-1)
Chris Lattner708148e2004-10-10 23:14:11 +0000754 Changed |= OptimizeAwayTrappingUsesOfValue(GEPI,
Jay Foaddab3d292011-07-21 14:31:17 +0000755 ConstantExpr::getGetElementPtr(NewV, Idxs));
Chris Lattner708148e2004-10-10 23:14:11 +0000756 if (GEPI->use_empty()) {
757 Changed = true;
Chris Lattner7a7ed022004-10-16 18:09:00 +0000758 GEPI->eraseFromParent();
Chris Lattner708148e2004-10-10 23:14:11 +0000759 }
760 }
761 }
762
763 return Changed;
764}
765
766
767/// OptimizeAwayTrappingUsesOfLoads - The specified global has only one non-null
768/// value stored into it. If there are uses of the loaded value that would trap
769/// if the loaded value is dynamically null, then we know that they cannot be
770/// reachable with a null optimize away the load.
Nick Lewycky6a577f82012-02-12 01:13:18 +0000771static bool OptimizeAwayTrappingUsesOfLoads(GlobalVariable *GV, Constant *LV,
772 TargetData *TD,
773 TargetLibraryInfo *TLI) {
Chris Lattner708148e2004-10-10 23:14:11 +0000774 bool Changed = false;
775
Chris Lattner92c6bd22009-01-14 00:12:58 +0000776 // Keep track of whether we are able to remove all the uses of the global
777 // other than the store that defines it.
778 bool AllNonStoreUsesGone = true;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000779
Chris Lattner708148e2004-10-10 23:14:11 +0000780 // Replace all uses of loads with uses of uses of the stored value.
Chris Lattner92c6bd22009-01-14 00:12:58 +0000781 for (Value::use_iterator GUI = GV->use_begin(), E = GV->use_end(); GUI != E;){
782 User *GlobalUser = *GUI++;
783 if (LoadInst *LI = dyn_cast<LoadInst>(GlobalUser)) {
Chris Lattner7b550cc2009-11-06 04:27:31 +0000784 Changed |= OptimizeAwayTrappingUsesOfValue(LI, LV);
Chris Lattner92c6bd22009-01-14 00:12:58 +0000785 // If we were able to delete all uses of the loads
786 if (LI->use_empty()) {
787 LI->eraseFromParent();
788 Changed = true;
789 } else {
790 AllNonStoreUsesGone = false;
791 }
792 } else if (isa<StoreInst>(GlobalUser)) {
793 // Ignore the store that stores "LV" to the global.
794 assert(GlobalUser->getOperand(1) == GV &&
795 "Must be storing *to* the global");
Chris Lattner708148e2004-10-10 23:14:11 +0000796 } else {
Chris Lattner92c6bd22009-01-14 00:12:58 +0000797 AllNonStoreUsesGone = false;
798
799 // If we get here we could have other crazy uses that are transitively
800 // loaded.
801 assert((isa<PHINode>(GlobalUser) || isa<SelectInst>(GlobalUser) ||
Chris Lattner98a42b22011-05-22 07:15:13 +0000802 isa<ConstantExpr>(GlobalUser) || isa<CmpInst>(GlobalUser)) &&
803 "Only expect load and stores!");
Chris Lattner708148e2004-10-10 23:14:11 +0000804 }
Chris Lattner92c6bd22009-01-14 00:12:58 +0000805 }
Chris Lattner708148e2004-10-10 23:14:11 +0000806
807 if (Changed) {
David Greene3215b0e2010-01-05 01:28:05 +0000808 DEBUG(dbgs() << "OPTIMIZED LOADS FROM STORED ONCE POINTER: " << *GV);
Chris Lattner708148e2004-10-10 23:14:11 +0000809 ++NumGlobUses;
810 }
811
Chris Lattner708148e2004-10-10 23:14:11 +0000812 // If we nuked all of the loads, then none of the stores are needed either,
813 // nor is the global.
Chris Lattner92c6bd22009-01-14 00:12:58 +0000814 if (AllNonStoreUsesGone) {
Nick Lewyckyc7088c92012-07-21 09:03:15 +0000815 DEBUG(dbgs() << " *** GLOBAL NOW DEAD!\n");
816 CleanupConstantGlobalUsers(GV, 0, TD, TLI);
Chris Lattner708148e2004-10-10 23:14:11 +0000817 if (GV->use_empty()) {
Chris Lattner7a7ed022004-10-16 18:09:00 +0000818 GV->eraseFromParent();
Chris Lattner708148e2004-10-10 23:14:11 +0000819 ++NumDeleted;
820 }
Nick Lewyckyc7088c92012-07-21 09:03:15 +0000821 Changed = true;
Chris Lattner708148e2004-10-10 23:14:11 +0000822 }
823 return Changed;
824}
825
Chris Lattner30ba5692004-10-11 05:54:41 +0000826/// ConstantPropUsersOf - Walk the use list of V, constant folding all of the
827/// instructions that are foldable.
Nick Lewycky6a577f82012-02-12 01:13:18 +0000828static void ConstantPropUsersOf(Value *V,
829 TargetData *TD, TargetLibraryInfo *TLI) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000830 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; )
831 if (Instruction *I = dyn_cast<Instruction>(*UI++))
Nick Lewycky6a577f82012-02-12 01:13:18 +0000832 if (Constant *NewC = ConstantFoldInstruction(I, TD, TLI)) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000833 I->replaceAllUsesWith(NewC);
834
Chris Lattnerd514d822005-02-01 01:23:31 +0000835 // Advance UI to the next non-I use to avoid invalidating it!
836 // Instructions could multiply use V.
837 while (UI != E && *UI == I)
Chris Lattner30ba5692004-10-11 05:54:41 +0000838 ++UI;
Chris Lattnerd514d822005-02-01 01:23:31 +0000839 I->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +0000840 }
841}
842
843/// OptimizeGlobalAddressOfMalloc - This function takes the specified global
844/// variable, and transforms the program as if it always contained the result of
845/// the specified malloc. Because it is always the result of the specified
846/// malloc, there is no reason to actually DO the malloc. Instead, turn the
Chris Lattner6e8fbad2006-11-30 17:32:29 +0000847/// malloc into a global, and any loads of GV as uses of the new global.
Chris Lattner30ba5692004-10-11 05:54:41 +0000848static GlobalVariable *OptimizeGlobalAddressOfMalloc(GlobalVariable *GV,
Victor Hernandez83d63912009-09-18 22:35:49 +0000849 CallInst *CI,
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000850 Type *AllocTy,
Chris Lattnera6874652010-02-25 22:33:52 +0000851 ConstantInt *NElements,
Nick Lewycky6a577f82012-02-12 01:13:18 +0000852 TargetData *TD,
853 TargetLibraryInfo *TLI) {
Chris Lattnera6874652010-02-25 22:33:52 +0000854 DEBUG(errs() << "PROMOTING GLOBAL: " << *GV << " CALL = " << *CI << '\n');
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000855
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000856 Type *GlobalType;
Chris Lattnera6874652010-02-25 22:33:52 +0000857 if (NElements->getZExtValue() == 1)
858 GlobalType = AllocTy;
859 else
860 // If we have an array allocation, the global variable is of an array.
861 GlobalType = ArrayType::get(AllocTy, NElements->getZExtValue());
Victor Hernandez83d63912009-09-18 22:35:49 +0000862
863 // Create the new global variable. The contents of the malloc'd memory is
864 // undefined, so initialize with an undef value.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000865 GlobalVariable *NewGV = new GlobalVariable(*GV->getParent(),
Chris Lattnere9fd4442010-02-26 23:42:13 +0000866 GlobalType, false,
Chris Lattnera6874652010-02-25 22:33:52 +0000867 GlobalValue::InternalLinkage,
Chris Lattnere9fd4442010-02-26 23:42:13 +0000868 UndefValue::get(GlobalType),
Victor Hernandez83d63912009-09-18 22:35:49 +0000869 GV->getName()+".body",
870 GV,
Hans Wennborgce718ff2012-06-23 11:37:03 +0000871 GV->getThreadLocalMode());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000872
Chris Lattnera6874652010-02-25 22:33:52 +0000873 // If there are bitcast users of the malloc (which is typical, usually we have
874 // a malloc + bitcast) then replace them with uses of the new global. Update
875 // other users to use the global as well.
876 BitCastInst *TheBC = 0;
877 while (!CI->use_empty()) {
878 Instruction *User = cast<Instruction>(CI->use_back());
879 if (BitCastInst *BCI = dyn_cast<BitCastInst>(User)) {
880 if (BCI->getType() == NewGV->getType()) {
881 BCI->replaceAllUsesWith(NewGV);
882 BCI->eraseFromParent();
883 } else {
884 BCI->setOperand(0, NewGV);
885 }
886 } else {
887 if (TheBC == 0)
888 TheBC = new BitCastInst(NewGV, CI->getType(), "newgv", CI);
889 User->replaceUsesOfWith(CI, TheBC);
890 }
891 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000892
Victor Hernandez83d63912009-09-18 22:35:49 +0000893 Constant *RepValue = NewGV;
894 if (NewGV->getType() != GV->getType()->getElementType())
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000895 RepValue = ConstantExpr::getBitCast(RepValue,
Victor Hernandez83d63912009-09-18 22:35:49 +0000896 GV->getType()->getElementType());
897
898 // If there is a comparison against null, we will insert a global bool to
899 // keep track of whether the global was initialized yet or not.
900 GlobalVariable *InitBool =
Chris Lattner7b550cc2009-11-06 04:27:31 +0000901 new GlobalVariable(Type::getInt1Ty(GV->getContext()), false,
Victor Hernandez83d63912009-09-18 22:35:49 +0000902 GlobalValue::InternalLinkage,
Chris Lattner7b550cc2009-11-06 04:27:31 +0000903 ConstantInt::getFalse(GV->getContext()),
Hans Wennborgce718ff2012-06-23 11:37:03 +0000904 GV->getName()+".init", GV->getThreadLocalMode());
Victor Hernandez83d63912009-09-18 22:35:49 +0000905 bool InitBoolUsed = false;
906
907 // Loop over all uses of GV, processing them in turn.
Chris Lattnera6874652010-02-25 22:33:52 +0000908 while (!GV->use_empty()) {
909 if (StoreInst *SI = dyn_cast<StoreInst>(GV->use_back())) {
Victor Hernandez83d63912009-09-18 22:35:49 +0000910 // The global is initialized when the store to it occurs.
Nick Lewyckyfad4d402012-02-05 19:56:38 +0000911 new StoreInst(ConstantInt::getTrue(GV->getContext()), InitBool, false, 0,
912 SI->getOrdering(), SI->getSynchScope(), SI);
Victor Hernandez83d63912009-09-18 22:35:49 +0000913 SI->eraseFromParent();
Chris Lattnera6874652010-02-25 22:33:52 +0000914 continue;
Victor Hernandez83d63912009-09-18 22:35:49 +0000915 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000916
Chris Lattnera6874652010-02-25 22:33:52 +0000917 LoadInst *LI = cast<LoadInst>(GV->use_back());
918 while (!LI->use_empty()) {
919 Use &LoadUse = LI->use_begin().getUse();
920 if (!isa<ICmpInst>(LoadUse.getUser())) {
921 LoadUse = RepValue;
922 continue;
923 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000924
Chris Lattnera6874652010-02-25 22:33:52 +0000925 ICmpInst *ICI = cast<ICmpInst>(LoadUse.getUser());
926 // Replace the cmp X, 0 with a use of the bool value.
Nick Lewyckyfad4d402012-02-05 19:56:38 +0000927 // Sink the load to where the compare was, if atomic rules allow us to.
928 Value *LV = new LoadInst(InitBool, InitBool->getName()+".val", false, 0,
929 LI->getOrdering(), LI->getSynchScope(),
930 LI->isUnordered() ? (Instruction*)ICI : LI);
Chris Lattnera6874652010-02-25 22:33:52 +0000931 InitBoolUsed = true;
932 switch (ICI->getPredicate()) {
933 default: llvm_unreachable("Unknown ICmp Predicate!");
934 case ICmpInst::ICMP_ULT:
935 case ICmpInst::ICMP_SLT: // X < null -> always false
936 LV = ConstantInt::getFalse(GV->getContext());
937 break;
938 case ICmpInst::ICMP_ULE:
939 case ICmpInst::ICMP_SLE:
940 case ICmpInst::ICMP_EQ:
941 LV = BinaryOperator::CreateNot(LV, "notinit", ICI);
942 break;
943 case ICmpInst::ICMP_NE:
944 case ICmpInst::ICMP_UGE:
945 case ICmpInst::ICMP_SGE:
946 case ICmpInst::ICMP_UGT:
947 case ICmpInst::ICMP_SGT:
948 break; // no change.
949 }
950 ICI->replaceAllUsesWith(LV);
951 ICI->eraseFromParent();
952 }
953 LI->eraseFromParent();
954 }
Victor Hernandez83d63912009-09-18 22:35:49 +0000955
956 // If the initialization boolean was used, insert it, otherwise delete it.
957 if (!InitBoolUsed) {
958 while (!InitBool->use_empty()) // Delete initializations
Chris Lattnera6874652010-02-25 22:33:52 +0000959 cast<StoreInst>(InitBool->use_back())->eraseFromParent();
Victor Hernandez83d63912009-09-18 22:35:49 +0000960 delete InitBool;
961 } else
962 GV->getParent()->getGlobalList().insert(GV, InitBool);
963
Chris Lattnera6874652010-02-25 22:33:52 +0000964 // Now the GV is dead, nuke it and the malloc..
Victor Hernandez83d63912009-09-18 22:35:49 +0000965 GV->eraseFromParent();
Victor Hernandez83d63912009-09-18 22:35:49 +0000966 CI->eraseFromParent();
967
968 // To further other optimizations, loop over all users of NewGV and try to
969 // constant prop them. This will promote GEP instructions with constant
970 // indices into GEP constant-exprs, which will allow global-opt to hack on it.
Nick Lewycky6a577f82012-02-12 01:13:18 +0000971 ConstantPropUsersOf(NewGV, TD, TLI);
Victor Hernandez83d63912009-09-18 22:35:49 +0000972 if (RepValue != NewGV)
Nick Lewycky6a577f82012-02-12 01:13:18 +0000973 ConstantPropUsersOf(RepValue, TD, TLI);
Victor Hernandez83d63912009-09-18 22:35:49 +0000974
975 return NewGV;
976}
977
Chris Lattnerfa07e4f2004-12-02 07:11:07 +0000978/// ValueIsOnlyUsedLocallyOrStoredToOneGlobal - Scan the use-list of V checking
979/// to make sure that there are no complex uses of V. We permit simple things
980/// like dereferencing the pointer, but not storing through the address, unless
981/// it is to the specified global.
Gabor Greif0b520db2010-04-06 18:58:22 +0000982static bool ValueIsOnlyUsedLocallyOrStoredToOneGlobal(const Instruction *V,
983 const GlobalVariable *GV,
Gabor Greifa01d6db2010-04-06 19:14:05 +0000984 SmallPtrSet<const PHINode*, 8> &PHIs) {
Gabor Greif0b520db2010-04-06 18:58:22 +0000985 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end();
Gabor Greifa01d6db2010-04-06 19:14:05 +0000986 UI != E; ++UI) {
Gabor Greif0b520db2010-04-06 18:58:22 +0000987 const Instruction *Inst = cast<Instruction>(*UI);
Gabor Greifa01d6db2010-04-06 19:14:05 +0000988
Chris Lattner49b6d4a2008-12-15 21:08:54 +0000989 if (isa<LoadInst>(Inst) || isa<CmpInst>(Inst)) {
990 continue; // Fine, ignore.
991 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000992
Gabor Greif0b520db2010-04-06 18:58:22 +0000993 if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
Chris Lattnerfa07e4f2004-12-02 07:11:07 +0000994 if (SI->getOperand(0) == V && SI->getOperand(1) != GV)
995 return false; // Storing the pointer itself... bad.
Chris Lattner49b6d4a2008-12-15 21:08:54 +0000996 continue; // Otherwise, storing through it, or storing into GV... fine.
997 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000998
Chris Lattnera2fb2342010-04-10 18:19:22 +0000999 // Must index into the array and into the struct.
1000 if (isa<GetElementPtrInst>(Inst) && Inst->getNumOperands() >= 3) {
Chris Lattner49b6d4a2008-12-15 21:08:54 +00001001 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(Inst, GV, PHIs))
Chris Lattnerfa07e4f2004-12-02 07:11:07 +00001002 return false;
Chris Lattner49b6d4a2008-12-15 21:08:54 +00001003 continue;
1004 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001005
Gabor Greif0b520db2010-04-06 18:58:22 +00001006 if (const PHINode *PN = dyn_cast<PHINode>(Inst)) {
Chris Lattnerc451f9c2007-09-13 16:37:20 +00001007 // PHIs are ok if all uses are ok. Don't infinitely recurse through PHI
1008 // cycles.
1009 if (PHIs.insert(PN))
Chris Lattner5e6e4942007-09-14 03:41:21 +00001010 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(PN, GV, PHIs))
1011 return false;
Chris Lattner49b6d4a2008-12-15 21:08:54 +00001012 continue;
Chris Lattnerfa07e4f2004-12-02 07:11:07 +00001013 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001014
Gabor Greif0b520db2010-04-06 18:58:22 +00001015 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Inst)) {
Chris Lattner49b6d4a2008-12-15 21:08:54 +00001016 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(BCI, GV, PHIs))
1017 return false;
1018 continue;
1019 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001020
Chris Lattner49b6d4a2008-12-15 21:08:54 +00001021 return false;
1022 }
Chris Lattnerfa07e4f2004-12-02 07:11:07 +00001023 return true;
Chris Lattnerfa07e4f2004-12-02 07:11:07 +00001024}
1025
Chris Lattner86395032006-09-30 23:32:09 +00001026/// ReplaceUsesOfMallocWithGlobal - The Alloc pointer is stored into GV
1027/// somewhere. Transform all uses of the allocation into loads from the
1028/// global and uses of the resultant pointer. Further, delete the store into
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001029/// GV. This assumes that these value pass the
Chris Lattner86395032006-09-30 23:32:09 +00001030/// 'ValueIsOnlyUsedLocallyOrStoredToOneGlobal' predicate.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001031static void ReplaceUsesOfMallocWithGlobal(Instruction *Alloc,
Chris Lattner86395032006-09-30 23:32:09 +00001032 GlobalVariable *GV) {
1033 while (!Alloc->use_empty()) {
Chris Lattnera637a8b2007-09-13 18:00:31 +00001034 Instruction *U = cast<Instruction>(*Alloc->use_begin());
1035 Instruction *InsertPt = U;
Chris Lattner86395032006-09-30 23:32:09 +00001036 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
1037 // If this is the store of the allocation into the global, remove it.
1038 if (SI->getOperand(1) == GV) {
1039 SI->eraseFromParent();
1040 continue;
1041 }
Chris Lattnera637a8b2007-09-13 18:00:31 +00001042 } else if (PHINode *PN = dyn_cast<PHINode>(U)) {
1043 // Insert the load in the corresponding predecessor, not right before the
1044 // PHI.
Gabor Greifa36791d2009-01-23 19:40:15 +00001045 InsertPt = PN->getIncomingBlock(Alloc->use_begin())->getTerminator();
Chris Lattner101f44e2008-12-15 21:44:34 +00001046 } else if (isa<BitCastInst>(U)) {
1047 // Must be bitcast between the malloc and store to initialize the global.
1048 ReplaceUsesOfMallocWithGlobal(U, GV);
1049 U->eraseFromParent();
1050 continue;
1051 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
1052 // If this is a "GEP bitcast" and the user is a store to the global, then
1053 // just process it as a bitcast.
1054 if (GEPI->hasAllZeroIndices() && GEPI->hasOneUse())
1055 if (StoreInst *SI = dyn_cast<StoreInst>(GEPI->use_back()))
1056 if (SI->getOperand(1) == GV) {
1057 // Must be bitcast GEP between the malloc and store to initialize
1058 // the global.
1059 ReplaceUsesOfMallocWithGlobal(GEPI, GV);
1060 GEPI->eraseFromParent();
1061 continue;
1062 }
Chris Lattner86395032006-09-30 23:32:09 +00001063 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001064
Chris Lattner86395032006-09-30 23:32:09 +00001065 // Insert a load from the global, and use it instead of the malloc.
Chris Lattnera637a8b2007-09-13 18:00:31 +00001066 Value *NL = new LoadInst(GV, GV->getName()+".val", InsertPt);
Chris Lattner86395032006-09-30 23:32:09 +00001067 U->replaceUsesOfWith(Alloc, NL);
1068 }
1069}
1070
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001071/// LoadUsesSimpleEnoughForHeapSRA - Verify that all uses of V (a load, or a phi
1072/// of a load) are simple enough to perform heap SRA on. This permits GEP's
1073/// that index through the array and struct field, icmps of null, and PHIs.
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001074static bool LoadUsesSimpleEnoughForHeapSRA(const Value *V,
Gabor Greif27236912010-04-07 18:59:26 +00001075 SmallPtrSet<const PHINode*, 32> &LoadUsingPHIs,
1076 SmallPtrSet<const PHINode*, 32> &LoadUsingPHIsPerLoad) {
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001077 // We permit two users of the load: setcc comparing against the null
1078 // pointer, and a getelementptr of a specific form.
Gabor Greif27236912010-04-07 18:59:26 +00001079 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;
1080 ++UI) {
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001081 const Instruction *User = cast<Instruction>(*UI);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001082
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001083 // Comparison against null is ok.
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001084 if (const ICmpInst *ICI = dyn_cast<ICmpInst>(User)) {
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001085 if (!isa<ConstantPointerNull>(ICI->getOperand(1)))
1086 return false;
1087 continue;
1088 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001089
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001090 // getelementptr is also ok, but only a simple form.
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001091 if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001092 // Must index into the array and into the struct.
1093 if (GEPI->getNumOperands() < 3)
1094 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001095
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001096 // Otherwise the GEP is ok.
1097 continue;
1098 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001099
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001100 if (const PHINode *PN = dyn_cast<PHINode>(User)) {
Evan Cheng5d163962009-06-02 00:56:07 +00001101 if (!LoadUsingPHIsPerLoad.insert(PN))
1102 // This means some phi nodes are dependent on each other.
1103 // Avoid infinite looping!
1104 return false;
1105 if (!LoadUsingPHIs.insert(PN))
1106 // If we have already analyzed this PHI, then it is safe.
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001107 continue;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001108
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001109 // Make sure all uses of the PHI are simple enough to transform.
Evan Cheng5d163962009-06-02 00:56:07 +00001110 if (!LoadUsesSimpleEnoughForHeapSRA(PN,
1111 LoadUsingPHIs, LoadUsingPHIsPerLoad))
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001112 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001113
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001114 continue;
Chris Lattner86395032006-09-30 23:32:09 +00001115 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001116
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001117 // Otherwise we don't know what this is, not ok.
1118 return false;
1119 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001120
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001121 return true;
1122}
1123
1124
1125/// AllGlobalLoadUsesSimpleEnoughForHeapSRA - If all users of values loaded from
1126/// GV are simple enough to perform HeapSRA, return true.
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001127static bool AllGlobalLoadUsesSimpleEnoughForHeapSRA(const GlobalVariable *GV,
Victor Hernandez83d63912009-09-18 22:35:49 +00001128 Instruction *StoredVal) {
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001129 SmallPtrSet<const PHINode*, 32> LoadUsingPHIs;
1130 SmallPtrSet<const PHINode*, 32> LoadUsingPHIsPerLoad;
Gabor Greif27236912010-04-07 18:59:26 +00001131 for (Value::const_use_iterator UI = GV->use_begin(), E = GV->use_end();
1132 UI != E; ++UI)
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001133 if (const LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
Evan Cheng5d163962009-06-02 00:56:07 +00001134 if (!LoadUsesSimpleEnoughForHeapSRA(LI, LoadUsingPHIs,
1135 LoadUsingPHIsPerLoad))
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001136 return false;
Evan Cheng5d163962009-06-02 00:56:07 +00001137 LoadUsingPHIsPerLoad.clear();
1138 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001139
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001140 // If we reach here, we know that all uses of the loads and transitive uses
1141 // (through PHI nodes) are simple enough to transform. However, we don't know
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001142 // that all inputs the to the PHI nodes are in the same equivalence sets.
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001143 // Check to verify that all operands of the PHIs are either PHIS that can be
1144 // transformed, loads from GV, or MI itself.
Gabor Greif27236912010-04-07 18:59:26 +00001145 for (SmallPtrSet<const PHINode*, 32>::const_iterator I = LoadUsingPHIs.begin()
1146 , E = LoadUsingPHIs.end(); I != E; ++I) {
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001147 const PHINode *PN = *I;
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001148 for (unsigned op = 0, e = PN->getNumIncomingValues(); op != e; ++op) {
1149 Value *InVal = PN->getIncomingValue(op);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001150
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001151 // PHI of the stored value itself is ok.
Victor Hernandez83d63912009-09-18 22:35:49 +00001152 if (InVal == StoredVal) continue;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001153
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001154 if (const PHINode *InPN = dyn_cast<PHINode>(InVal)) {
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001155 // One of the PHIs in our set is (optimistically) ok.
1156 if (LoadUsingPHIs.count(InPN))
1157 continue;
1158 return false;
1159 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001160
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001161 // Load from GV is ok.
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001162 if (const LoadInst *LI = dyn_cast<LoadInst>(InVal))
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001163 if (LI->getOperand(0) == GV)
1164 continue;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001165
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001166 // UNDEF? NULL?
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001167
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001168 // Anything else is rejected.
1169 return false;
1170 }
1171 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001172
Chris Lattner86395032006-09-30 23:32:09 +00001173 return true;
1174}
1175
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001176static Value *GetHeapSROAValue(Value *V, unsigned FieldNo,
1177 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001178 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001179 std::vector<Value*> &FieldVals = InsertedScalarizedValues[V];
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001180
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001181 if (FieldNo >= FieldVals.size())
1182 FieldVals.resize(FieldNo+1);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001183
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001184 // If we already have this value, just reuse the previously scalarized
1185 // version.
1186 if (Value *FieldVal = FieldVals[FieldNo])
1187 return FieldVal;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001188
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001189 // Depending on what instruction this is, we have several cases.
1190 Value *Result;
1191 if (LoadInst *LI = dyn_cast<LoadInst>(V)) {
1192 // This is a scalarized version of the load from the global. Just create
1193 // a new Load of the scalarized global.
1194 Result = new LoadInst(GetHeapSROAValue(LI->getOperand(0), FieldNo,
1195 InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001196 PHIsToRewrite),
Daniel Dunbarfe09b202009-07-30 17:37:43 +00001197 LI->getName()+".f"+Twine(FieldNo), LI);
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001198 } else if (PHINode *PN = dyn_cast<PHINode>(V)) {
1199 // PN's type is pointer to struct. Make a new PHI of pointer to struct
1200 // field.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001201 StructType *ST =
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001202 cast<StructType>(cast<PointerType>(PN->getType())->getElementType());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001203
Jay Foadd8b4fb42011-03-30 11:19:20 +00001204 PHINode *NewPN =
Owen Andersondebcb012009-07-29 22:17:13 +00001205 PHINode::Create(PointerType::getUnqual(ST->getElementType(FieldNo)),
Jay Foad3ecfc862011-03-30 11:28:46 +00001206 PN->getNumIncomingValues(),
Daniel Dunbarfe09b202009-07-30 17:37:43 +00001207 PN->getName()+".f"+Twine(FieldNo), PN);
Jay Foadd8b4fb42011-03-30 11:19:20 +00001208 Result = NewPN;
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001209 PHIsToRewrite.push_back(std::make_pair(PN, FieldNo));
1210 } else {
Torok Edwinc23197a2009-07-14 16:55:14 +00001211 llvm_unreachable("Unknown usable value");
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001212 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001213
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001214 return FieldVals[FieldNo] = Result;
Chris Lattnera637a8b2007-09-13 18:00:31 +00001215}
1216
Chris Lattner330245e2007-09-13 17:29:05 +00001217/// RewriteHeapSROALoadUser - Given a load instruction and a value derived from
1218/// the load, rewrite the derived value to use the HeapSRoA'd load.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001219static void RewriteHeapSROALoadUser(Instruction *LoadUser,
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001220 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001221 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
Chris Lattner330245e2007-09-13 17:29:05 +00001222 // If this is a comparison against null, handle it.
1223 if (ICmpInst *SCI = dyn_cast<ICmpInst>(LoadUser)) {
1224 assert(isa<ConstantPointerNull>(SCI->getOperand(1)));
1225 // If we have a setcc of the loaded pointer, we can use a setcc of any
1226 // field.
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001227 Value *NPtr = GetHeapSROAValue(SCI->getOperand(0), 0,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001228 InsertedScalarizedValues, PHIsToRewrite);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001229
Owen Anderson333c4002009-07-09 23:48:35 +00001230 Value *New = new ICmpInst(SCI, SCI->getPredicate(), NPtr,
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001231 Constant::getNullValue(NPtr->getType()),
Owen Anderson333c4002009-07-09 23:48:35 +00001232 SCI->getName());
Chris Lattner330245e2007-09-13 17:29:05 +00001233 SCI->replaceAllUsesWith(New);
1234 SCI->eraseFromParent();
1235 return;
1236 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001237
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001238 // Handle 'getelementptr Ptr, Idx, i32 FieldNo ...'
Chris Lattnera637a8b2007-09-13 18:00:31 +00001239 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(LoadUser)) {
1240 assert(GEPI->getNumOperands() >= 3 && isa<ConstantInt>(GEPI->getOperand(2))
1241 && "Unexpected GEPI!");
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001242
Chris Lattnera637a8b2007-09-13 18:00:31 +00001243 // Load the pointer for this field.
1244 unsigned FieldNo = cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue();
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001245 Value *NewPtr = GetHeapSROAValue(GEPI->getOperand(0), FieldNo,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001246 InsertedScalarizedValues, PHIsToRewrite);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001247
Chris Lattnera637a8b2007-09-13 18:00:31 +00001248 // Create the new GEP idx vector.
1249 SmallVector<Value*, 8> GEPIdx;
1250 GEPIdx.push_back(GEPI->getOperand(1));
1251 GEPIdx.append(GEPI->op_begin()+3, GEPI->op_end());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001252
Jay Foada9203102011-07-25 09:48:08 +00001253 Value *NGEPI = GetElementPtrInst::Create(NewPtr, GEPIdx,
Gabor Greif051a9502008-04-06 20:25:17 +00001254 GEPI->getName(), GEPI);
Chris Lattnera637a8b2007-09-13 18:00:31 +00001255 GEPI->replaceAllUsesWith(NGEPI);
1256 GEPI->eraseFromParent();
1257 return;
1258 }
Chris Lattner309f20f2007-09-13 21:31:36 +00001259
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001260 // Recursively transform the users of PHI nodes. This will lazily create the
1261 // PHIs that are needed for individual elements. Keep track of what PHIs we
1262 // see in InsertedScalarizedValues so that we don't get infinite loops (very
1263 // antisocial). If the PHI is already in InsertedScalarizedValues, it has
1264 // already been seen first by another load, so its uses have already been
1265 // processed.
1266 PHINode *PN = cast<PHINode>(LoadUser);
Chris Lattnerc30a38f2011-07-21 06:21:31 +00001267 if (!InsertedScalarizedValues.insert(std::make_pair(PN,
1268 std::vector<Value*>())).second)
1269 return;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001270
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001271 // If this is the first time we've seen this PHI, recursively process all
1272 // users.
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001273 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end(); UI != E; ) {
1274 Instruction *User = cast<Instruction>(*UI++);
Chris Lattner7b550cc2009-11-06 04:27:31 +00001275 RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite);
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001276 }
Chris Lattner330245e2007-09-13 17:29:05 +00001277}
1278
Chris Lattner86395032006-09-30 23:32:09 +00001279/// RewriteUsesOfLoadForHeapSRoA - We are performing Heap SRoA on a global. Ptr
1280/// is a value loaded from the global. Eliminate all uses of Ptr, making them
1281/// use FieldGlobals instead. All uses of loaded values satisfy
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001282/// AllGlobalLoadUsesSimpleEnoughForHeapSRA.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001283static void RewriteUsesOfLoadForHeapSRoA(LoadInst *Load,
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001284 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001285 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001286 for (Value::use_iterator UI = Load->use_begin(), E = Load->use_end();
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001287 UI != E; ) {
1288 Instruction *User = cast<Instruction>(*UI++);
Chris Lattner7b550cc2009-11-06 04:27:31 +00001289 RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite);
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001290 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001291
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001292 if (Load->use_empty()) {
1293 Load->eraseFromParent();
1294 InsertedScalarizedValues.erase(Load);
1295 }
Chris Lattner86395032006-09-30 23:32:09 +00001296}
1297
Victor Hernandez83d63912009-09-18 22:35:49 +00001298/// PerformHeapAllocSRoA - CI is an allocation of an array of structures. Break
1299/// it up into multiple allocations of arrays of the fields.
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001300static GlobalVariable *PerformHeapAllocSRoA(GlobalVariable *GV, CallInst *CI,
Nick Lewyckybc384a12012-02-05 19:48:37 +00001301 Value *NElems, TargetData *TD) {
David Greene3215b0e2010-01-05 01:28:05 +00001302 DEBUG(dbgs() << "SROA HEAP ALLOC: " << *GV << " MALLOC = " << *CI << '\n');
Nick Lewyckybc384a12012-02-05 19:48:37 +00001303 Type *MAT = getMallocAllocatedType(CI);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001304 StructType *STy = cast<StructType>(MAT);
Victor Hernandez83d63912009-09-18 22:35:49 +00001305
1306 // There is guaranteed to be at least one use of the malloc (storing
1307 // it into GV). If there are other uses, change them to be uses of
1308 // the global to simplify later code. This also deletes the store
1309 // into GV.
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001310 ReplaceUsesOfMallocWithGlobal(CI, GV);
1311
Victor Hernandez83d63912009-09-18 22:35:49 +00001312 // Okay, at this point, there are no users of the malloc. Insert N
1313 // new mallocs at the same place as CI, and N globals.
1314 std::vector<Value*> FieldGlobals;
1315 std::vector<Value*> FieldMallocs;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001316
Victor Hernandez83d63912009-09-18 22:35:49 +00001317 for (unsigned FieldNo = 0, e = STy->getNumElements(); FieldNo != e;++FieldNo){
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001318 Type *FieldTy = STy->getElementType(FieldNo);
1319 PointerType *PFieldTy = PointerType::getUnqual(FieldTy);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001320
Victor Hernandez83d63912009-09-18 22:35:49 +00001321 GlobalVariable *NGV =
1322 new GlobalVariable(*GV->getParent(),
1323 PFieldTy, false, GlobalValue::InternalLinkage,
1324 Constant::getNullValue(PFieldTy),
1325 GV->getName() + ".f" + Twine(FieldNo), GV,
Hans Wennborgce718ff2012-06-23 11:37:03 +00001326 GV->getThreadLocalMode());
Victor Hernandez83d63912009-09-18 22:35:49 +00001327 FieldGlobals.push_back(NGV);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001328
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001329 unsigned TypeSize = TD->getTypeAllocSize(FieldTy);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001330 if (StructType *ST = dyn_cast<StructType>(FieldTy))
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001331 TypeSize = TD->getStructLayout(ST)->getSizeInBytes();
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001332 Type *IntPtrTy = TD->getIntPtrType(CI->getContext());
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001333 Value *NMI = CallInst::CreateMalloc(CI, IntPtrTy, FieldTy,
1334 ConstantInt::get(IntPtrTy, TypeSize),
Chris Lattner5a30a852010-07-12 00:57:28 +00001335 NElems, 0,
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001336 CI->getName() + ".f" + Twine(FieldNo));
Chris Lattner3f5e0b82010-02-26 18:23:13 +00001337 FieldMallocs.push_back(NMI);
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001338 new StoreInst(NMI, NGV, CI);
Victor Hernandez83d63912009-09-18 22:35:49 +00001339 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001340
Victor Hernandez83d63912009-09-18 22:35:49 +00001341 // The tricky aspect of this transformation is handling the case when malloc
1342 // fails. In the original code, malloc failing would set the result pointer
1343 // of malloc to null. In this case, some mallocs could succeed and others
1344 // could fail. As such, we emit code that looks like this:
1345 // F0 = malloc(field0)
1346 // F1 = malloc(field1)
1347 // F2 = malloc(field2)
1348 // if (F0 == 0 || F1 == 0 || F2 == 0) {
1349 // if (F0) { free(F0); F0 = 0; }
1350 // if (F1) { free(F1); F1 = 0; }
1351 // if (F2) { free(F2); F2 = 0; }
1352 // }
Victor Hernandez8e345a12009-11-10 08:32:25 +00001353 // The malloc can also fail if its argument is too large.
Gabor Greif9e4f2432010-06-24 14:42:01 +00001354 Constant *ConstantZero = ConstantInt::get(CI->getArgOperand(0)->getType(), 0);
1355 Value *RunningOr = new ICmpInst(CI, ICmpInst::ICMP_SLT, CI->getArgOperand(0),
Victor Hernandez8e345a12009-11-10 08:32:25 +00001356 ConstantZero, "isneg");
Victor Hernandez83d63912009-09-18 22:35:49 +00001357 for (unsigned i = 0, e = FieldMallocs.size(); i != e; ++i) {
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001358 Value *Cond = new ICmpInst(CI, ICmpInst::ICMP_EQ, FieldMallocs[i],
1359 Constant::getNullValue(FieldMallocs[i]->getType()),
1360 "isnull");
Victor Hernandez8e345a12009-11-10 08:32:25 +00001361 RunningOr = BinaryOperator::CreateOr(RunningOr, Cond, "tmp", CI);
Victor Hernandez83d63912009-09-18 22:35:49 +00001362 }
1363
1364 // Split the basic block at the old malloc.
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001365 BasicBlock *OrigBB = CI->getParent();
1366 BasicBlock *ContBB = OrigBB->splitBasicBlock(CI, "malloc_cont");
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001367
Victor Hernandez83d63912009-09-18 22:35:49 +00001368 // Create the block to check the first condition. Put all these blocks at the
1369 // end of the function as they are unlikely to be executed.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001370 BasicBlock *NullPtrBlock = BasicBlock::Create(OrigBB->getContext(),
1371 "malloc_ret_null",
Victor Hernandez83d63912009-09-18 22:35:49 +00001372 OrigBB->getParent());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001373
Victor Hernandez83d63912009-09-18 22:35:49 +00001374 // Remove the uncond branch from OrigBB to ContBB, turning it into a cond
1375 // branch on RunningOr.
1376 OrigBB->getTerminator()->eraseFromParent();
1377 BranchInst::Create(NullPtrBlock, ContBB, RunningOr, OrigBB);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001378
Victor Hernandez83d63912009-09-18 22:35:49 +00001379 // Within the NullPtrBlock, we need to emit a comparison and branch for each
1380 // pointer, because some may be null while others are not.
1381 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
1382 Value *GVVal = new LoadInst(FieldGlobals[i], "tmp", NullPtrBlock);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001383 Value *Cmp = new ICmpInst(*NullPtrBlock, ICmpInst::ICMP_NE, GVVal,
Benjamin Kramera9390a42011-09-27 20:39:19 +00001384 Constant::getNullValue(GVVal->getType()));
Chris Lattner7b550cc2009-11-06 04:27:31 +00001385 BasicBlock *FreeBlock = BasicBlock::Create(Cmp->getContext(), "free_it",
Victor Hernandez83d63912009-09-18 22:35:49 +00001386 OrigBB->getParent());
Chris Lattner7b550cc2009-11-06 04:27:31 +00001387 BasicBlock *NextBlock = BasicBlock::Create(Cmp->getContext(), "next",
Victor Hernandez83d63912009-09-18 22:35:49 +00001388 OrigBB->getParent());
Victor Hernandez66284e02009-10-24 04:23:03 +00001389 Instruction *BI = BranchInst::Create(FreeBlock, NextBlock,
1390 Cmp, NullPtrBlock);
Victor Hernandez83d63912009-09-18 22:35:49 +00001391
1392 // Fill in FreeBlock.
Victor Hernandez66284e02009-10-24 04:23:03 +00001393 CallInst::CreateFree(GVVal, BI);
Victor Hernandez83d63912009-09-18 22:35:49 +00001394 new StoreInst(Constant::getNullValue(GVVal->getType()), FieldGlobals[i],
1395 FreeBlock);
1396 BranchInst::Create(NextBlock, FreeBlock);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001397
Victor Hernandez83d63912009-09-18 22:35:49 +00001398 NullPtrBlock = NextBlock;
1399 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001400
Victor Hernandez83d63912009-09-18 22:35:49 +00001401 BranchInst::Create(ContBB, NullPtrBlock);
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001402
1403 // CI is no longer needed, remove it.
Victor Hernandez83d63912009-09-18 22:35:49 +00001404 CI->eraseFromParent();
1405
1406 /// InsertedScalarizedLoads - As we process loads, if we can't immediately
1407 /// update all uses of the load, keep track of what scalarized loads are
1408 /// inserted for a given load.
1409 DenseMap<Value*, std::vector<Value*> > InsertedScalarizedValues;
1410 InsertedScalarizedValues[GV] = FieldGlobals;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001411
Victor Hernandez83d63912009-09-18 22:35:49 +00001412 std::vector<std::pair<PHINode*, unsigned> > PHIsToRewrite;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001413
Victor Hernandez83d63912009-09-18 22:35:49 +00001414 // Okay, the malloc site is completely handled. All of the uses of GV are now
1415 // loads, and all uses of those loads are simple. Rewrite them to use loads
1416 // of the per-field globals instead.
1417 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI != E;) {
1418 Instruction *User = cast<Instruction>(*UI++);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001419
Victor Hernandez83d63912009-09-18 22:35:49 +00001420 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Chris Lattner7b550cc2009-11-06 04:27:31 +00001421 RewriteUsesOfLoadForHeapSRoA(LI, InsertedScalarizedValues, PHIsToRewrite);
Victor Hernandez83d63912009-09-18 22:35:49 +00001422 continue;
1423 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001424
Victor Hernandez83d63912009-09-18 22:35:49 +00001425 // Must be a store of null.
1426 StoreInst *SI = cast<StoreInst>(User);
1427 assert(isa<ConstantPointerNull>(SI->getOperand(0)) &&
1428 "Unexpected heap-sra user!");
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001429
Victor Hernandez83d63912009-09-18 22:35:49 +00001430 // Insert a store of null into each global.
1431 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001432 PointerType *PT = cast<PointerType>(FieldGlobals[i]->getType());
Victor Hernandez83d63912009-09-18 22:35:49 +00001433 Constant *Null = Constant::getNullValue(PT->getElementType());
1434 new StoreInst(Null, FieldGlobals[i], SI);
1435 }
1436 // Erase the original store.
1437 SI->eraseFromParent();
1438 }
1439
1440 // While we have PHIs that are interesting to rewrite, do it.
1441 while (!PHIsToRewrite.empty()) {
1442 PHINode *PN = PHIsToRewrite.back().first;
1443 unsigned FieldNo = PHIsToRewrite.back().second;
1444 PHIsToRewrite.pop_back();
1445 PHINode *FieldPN = cast<PHINode>(InsertedScalarizedValues[PN][FieldNo]);
1446 assert(FieldPN->getNumIncomingValues() == 0 &&"Already processed this phi");
1447
1448 // Add all the incoming values. This can materialize more phis.
1449 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1450 Value *InVal = PN->getIncomingValue(i);
1451 InVal = GetHeapSROAValue(InVal, FieldNo, InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001452 PHIsToRewrite);
Victor Hernandez83d63912009-09-18 22:35:49 +00001453 FieldPN->addIncoming(InVal, PN->getIncomingBlock(i));
1454 }
1455 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001456
Victor Hernandez83d63912009-09-18 22:35:49 +00001457 // Drop all inter-phi links and any loads that made it this far.
1458 for (DenseMap<Value*, std::vector<Value*> >::iterator
1459 I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
1460 I != E; ++I) {
1461 if (PHINode *PN = dyn_cast<PHINode>(I->first))
1462 PN->dropAllReferences();
1463 else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
1464 LI->dropAllReferences();
1465 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001466
Victor Hernandez83d63912009-09-18 22:35:49 +00001467 // Delete all the phis and loads now that inter-references are dead.
1468 for (DenseMap<Value*, std::vector<Value*> >::iterator
1469 I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
1470 I != E; ++I) {
1471 if (PHINode *PN = dyn_cast<PHINode>(I->first))
1472 PN->eraseFromParent();
1473 else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
1474 LI->eraseFromParent();
1475 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001476
Victor Hernandez83d63912009-09-18 22:35:49 +00001477 // The old global is now dead, remove it.
1478 GV->eraseFromParent();
1479
1480 ++NumHeapSRA;
1481 return cast<GlobalVariable>(FieldGlobals[0]);
1482}
1483
Chris Lattnere61d0a62008-12-15 21:02:25 +00001484/// TryToOptimizeStoreOfMallocToGlobal - This function is called when we see a
1485/// pointer global variable with a single value stored it that is a malloc or
1486/// cast of malloc.
1487static bool TryToOptimizeStoreOfMallocToGlobal(GlobalVariable *GV,
Victor Hernandez83d63912009-09-18 22:35:49 +00001488 CallInst *CI,
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001489 Type *AllocTy,
Nick Lewyckyfad4d402012-02-05 19:56:38 +00001490 AtomicOrdering Ordering,
Victor Hernandez83d63912009-09-18 22:35:49 +00001491 Module::global_iterator &GVI,
Nick Lewycky6a577f82012-02-12 01:13:18 +00001492 TargetData *TD,
1493 TargetLibraryInfo *TLI) {
Evan Cheng86cd4452010-04-14 20:52:55 +00001494 if (!TD)
1495 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001496
Victor Hernandez83d63912009-09-18 22:35:49 +00001497 // If this is a malloc of an abstract type, don't touch it.
1498 if (!AllocTy->isSized())
1499 return false;
1500
1501 // We can't optimize this global unless all uses of it are *known* to be
1502 // of the malloc value, not of the null initializer value (consider a use
1503 // that compares the global's value against zero to see if the malloc has
1504 // been reached). To do this, we check to see if all uses of the global
1505 // would trap if the global were null: this proves that they must all
1506 // happen after the malloc.
1507 if (!AllUsesOfLoadedValueWillTrapIfNull(GV))
1508 return false;
1509
1510 // We can't optimize this if the malloc itself is used in a complex way,
1511 // for example, being stored into multiple globals. This allows the
Nick Lewyckybc384a12012-02-05 19:48:37 +00001512 // malloc to be stored into the specified global, loaded icmp'd, and
Victor Hernandez83d63912009-09-18 22:35:49 +00001513 // GEP'd. These are all things we could transform to using the global
1514 // for.
Evan Cheng86cd4452010-04-14 20:52:55 +00001515 SmallPtrSet<const PHINode*, 8> PHIs;
1516 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(CI, GV, PHIs))
1517 return false;
Victor Hernandez83d63912009-09-18 22:35:49 +00001518
1519 // If we have a global that is only initialized with a fixed size malloc,
1520 // transform the program to use global memory instead of malloc'd memory.
1521 // This eliminates dynamic allocation, avoids an indirection accessing the
1522 // data, and exposes the resultant global to further GlobalOpt.
Victor Hernandez8db42d22009-10-16 23:12:25 +00001523 // We cannot optimize the malloc if we cannot determine malloc array size.
Evan Cheng86cd4452010-04-14 20:52:55 +00001524 Value *NElems = getMallocArraySize(CI, TD, true);
1525 if (!NElems)
1526 return false;
Victor Hernandez83d63912009-09-18 22:35:49 +00001527
Evan Cheng86cd4452010-04-14 20:52:55 +00001528 if (ConstantInt *NElements = dyn_cast<ConstantInt>(NElems))
1529 // Restrict this transformation to only working on small allocations
1530 // (2048 bytes currently), as we don't want to introduce a 16M global or
1531 // something.
1532 if (NElements->getZExtValue() * TD->getTypeAllocSize(AllocTy) < 2048) {
Nick Lewycky6a577f82012-02-12 01:13:18 +00001533 GVI = OptimizeGlobalAddressOfMalloc(GV, CI, AllocTy, NElements, TD, TLI);
Evan Cheng86cd4452010-04-14 20:52:55 +00001534 return true;
Victor Hernandez83d63912009-09-18 22:35:49 +00001535 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001536
Evan Cheng86cd4452010-04-14 20:52:55 +00001537 // If the allocation is an array of structures, consider transforming this
1538 // into multiple malloc'd arrays, one for each field. This is basically
1539 // SRoA for malloc'd memory.
1540
Nick Lewyckyfad4d402012-02-05 19:56:38 +00001541 if (Ordering != NotAtomic)
1542 return false;
1543
Evan Cheng86cd4452010-04-14 20:52:55 +00001544 // If this is an allocation of a fixed size array of structs, analyze as a
1545 // variable size array. malloc [100 x struct],1 -> malloc struct, 100
Gabor Greif9e4f2432010-06-24 14:42:01 +00001546 if (NElems == ConstantInt::get(CI->getArgOperand(0)->getType(), 1))
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001547 if (ArrayType *AT = dyn_cast<ArrayType>(AllocTy))
Evan Cheng86cd4452010-04-14 20:52:55 +00001548 AllocTy = AT->getElementType();
Gabor Greif9e4f2432010-06-24 14:42:01 +00001549
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001550 StructType *AllocSTy = dyn_cast<StructType>(AllocTy);
Evan Cheng86cd4452010-04-14 20:52:55 +00001551 if (!AllocSTy)
1552 return false;
1553
1554 // This the structure has an unreasonable number of fields, leave it
1555 // alone.
1556 if (AllocSTy->getNumElements() <= 16 && AllocSTy->getNumElements() != 0 &&
1557 AllGlobalLoadUsesSimpleEnoughForHeapSRA(GV, CI)) {
1558
1559 // If this is a fixed size array, transform the Malloc to be an alloc of
1560 // structs. malloc [100 x struct],1 -> malloc struct, 100
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001561 if (ArrayType *AT = dyn_cast<ArrayType>(getMallocAllocatedType(CI))) {
1562 Type *IntPtrTy = TD->getIntPtrType(CI->getContext());
Evan Cheng86cd4452010-04-14 20:52:55 +00001563 unsigned TypeSize = TD->getStructLayout(AllocSTy)->getSizeInBytes();
1564 Value *AllocSize = ConstantInt::get(IntPtrTy, TypeSize);
1565 Value *NumElements = ConstantInt::get(IntPtrTy, AT->getNumElements());
1566 Instruction *Malloc = CallInst::CreateMalloc(CI, IntPtrTy, AllocSTy,
1567 AllocSize, NumElements,
Chris Lattner5a30a852010-07-12 00:57:28 +00001568 0, CI->getName());
Evan Cheng86cd4452010-04-14 20:52:55 +00001569 Instruction *Cast = new BitCastInst(Malloc, CI->getType(), "tmp", CI);
1570 CI->replaceAllUsesWith(Cast);
1571 CI->eraseFromParent();
Nuno Lopeseb7c6862012-06-22 00:25:01 +00001572 if (BitCastInst *BCI = dyn_cast<BitCastInst>(Malloc))
1573 CI = cast<CallInst>(BCI->getOperand(0));
1574 else
Nuno Lopescd88efe2012-06-22 00:29:58 +00001575 CI = cast<CallInst>(Malloc);
Evan Cheng86cd4452010-04-14 20:52:55 +00001576 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001577
Nick Lewyckybc384a12012-02-05 19:48:37 +00001578 GVI = PerformHeapAllocSRoA(GV, CI, getMallocArraySize(CI, TD, true), TD);
Evan Cheng86cd4452010-04-14 20:52:55 +00001579 return true;
Victor Hernandez83d63912009-09-18 22:35:49 +00001580 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001581
Victor Hernandez83d63912009-09-18 22:35:49 +00001582 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001583}
Victor Hernandez83d63912009-09-18 22:35:49 +00001584
Chris Lattner9b34a612004-10-09 21:48:45 +00001585// OptimizeOnceStoredGlobal - Try to optimize globals based on the knowledge
1586// that only one value (besides its initializer) is ever stored to the global.
Chris Lattner30ba5692004-10-11 05:54:41 +00001587static bool OptimizeOnceStoredGlobal(GlobalVariable *GV, Value *StoredOnceVal,
Nick Lewyckyfad4d402012-02-05 19:56:38 +00001588 AtomicOrdering Ordering,
Chris Lattner7f8897f2006-08-27 22:42:52 +00001589 Module::global_iterator &GVI,
Nick Lewycky6a577f82012-02-12 01:13:18 +00001590 TargetData *TD, TargetLibraryInfo *TLI) {
Chris Lattner344b41c2008-12-15 21:20:32 +00001591 // Ignore no-op GEPs and bitcasts.
1592 StoredOnceVal = StoredOnceVal->stripPointerCasts();
Chris Lattner9b34a612004-10-09 21:48:45 +00001593
Chris Lattner708148e2004-10-10 23:14:11 +00001594 // If we are dealing with a pointer global that is initialized to null and
1595 // only has one (non-null) value stored into it, then we can optimize any
1596 // users of the loaded value (often calls and loads) that would trap if the
1597 // value was null.
Duncan Sands1df98592010-02-16 11:11:14 +00001598 if (GV->getInitializer()->getType()->isPointerTy() &&
Chris Lattner9b34a612004-10-09 21:48:45 +00001599 GV->getInitializer()->isNullValue()) {
Chris Lattner708148e2004-10-10 23:14:11 +00001600 if (Constant *SOVC = dyn_cast<Constant>(StoredOnceVal)) {
1601 if (GV->getInitializer()->getType() != SOVC->getType())
Chris Lattner98a42b22011-05-22 07:15:13 +00001602 SOVC = ConstantExpr::getBitCast(SOVC, GV->getInitializer()->getType());
Misha Brukmanfd939082005-04-21 23:48:37 +00001603
Chris Lattner708148e2004-10-10 23:14:11 +00001604 // Optimize away any trapping uses of the loaded value.
Nick Lewycky6a577f82012-02-12 01:13:18 +00001605 if (OptimizeAwayTrappingUsesOfLoads(GV, SOVC, TD, TLI))
Chris Lattner8be80122004-10-10 17:07:12 +00001606 return true;
Victor Hernandez83d63912009-09-18 22:35:49 +00001607 } else if (CallInst *CI = extractMallocCall(StoredOnceVal)) {
Nick Lewyckybc384a12012-02-05 19:48:37 +00001608 Type *MallocType = getMallocAllocatedType(CI);
Nick Lewycky6a577f82012-02-12 01:13:18 +00001609 if (MallocType &&
1610 TryToOptimizeStoreOfMallocToGlobal(GV, CI, MallocType, Ordering, GVI,
1611 TD, TLI))
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001612 return true;
Chris Lattner708148e2004-10-10 23:14:11 +00001613 }
Chris Lattner9b34a612004-10-09 21:48:45 +00001614 }
Chris Lattner30ba5692004-10-11 05:54:41 +00001615
Chris Lattner9b34a612004-10-09 21:48:45 +00001616 return false;
1617}
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001618
Chris Lattner58e44f42008-01-14 01:17:44 +00001619/// TryToShrinkGlobalToBoolean - At this point, we have learned that the only
1620/// two values ever stored into GV are its initializer and OtherVal. See if we
1621/// can shrink the global into a boolean and select between the two values
1622/// whenever it is used. This exposes the values to other scalar optimizations.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001623static bool TryToShrinkGlobalToBoolean(GlobalVariable *GV, Constant *OtherVal) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001624 Type *GVElType = GV->getType()->getElementType();
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001625
Chris Lattner58e44f42008-01-14 01:17:44 +00001626 // If GVElType is already i1, it is already shrunk. If the type of the GV is
Chris Lattner6f6923f2009-03-07 23:32:02 +00001627 // an FP value, pointer or vector, don't do this optimization because a select
1628 // between them is very expensive and unlikely to lead to later
1629 // simplification. In these cases, we typically end up with "cond ? v1 : v2"
1630 // where v1 and v2 both require constant pool loads, a big loss.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001631 if (GVElType == Type::getInt1Ty(GV->getContext()) ||
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001632 GVElType->isFloatingPointTy() ||
Duncan Sands1df98592010-02-16 11:11:14 +00001633 GVElType->isPointerTy() || GVElType->isVectorTy())
Chris Lattner58e44f42008-01-14 01:17:44 +00001634 return false;
Gabor Greifaaaaa022010-07-12 14:13:15 +00001635
Chris Lattner58e44f42008-01-14 01:17:44 +00001636 // Walk the use list of the global seeing if all the uses are load or store.
1637 // If there is anything else, bail out.
Gabor Greifaaaaa022010-07-12 14:13:15 +00001638 for (Value::use_iterator I = GV->use_begin(), E = GV->use_end(); I != E; ++I){
1639 User *U = *I;
1640 if (!isa<LoadInst>(U) && !isa<StoreInst>(U))
Chris Lattner58e44f42008-01-14 01:17:44 +00001641 return false;
Gabor Greifaaaaa022010-07-12 14:13:15 +00001642 }
1643
David Greene3215b0e2010-01-05 01:28:05 +00001644 DEBUG(dbgs() << " *** SHRINKING TO BOOL: " << *GV);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001645
Chris Lattner96a86b22004-12-12 05:53:50 +00001646 // Create the new global, initializing it to false.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001647 GlobalVariable *NewGV = new GlobalVariable(Type::getInt1Ty(GV->getContext()),
1648 false,
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001649 GlobalValue::InternalLinkage,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001650 ConstantInt::getFalse(GV->getContext()),
Nick Lewycky0e670df2009-05-03 03:49:08 +00001651 GV->getName()+".b",
Hans Wennborgce718ff2012-06-23 11:37:03 +00001652 GV->getThreadLocalMode());
Chris Lattner96a86b22004-12-12 05:53:50 +00001653 GV->getParent()->getGlobalList().insert(GV, NewGV);
1654
1655 Constant *InitVal = GV->getInitializer();
Chris Lattner7b550cc2009-11-06 04:27:31 +00001656 assert(InitVal->getType() != Type::getInt1Ty(GV->getContext()) &&
Owen Anderson1d0be152009-08-13 21:58:54 +00001657 "No reason to shrink to bool!");
Chris Lattner96a86b22004-12-12 05:53:50 +00001658
1659 // If initialized to zero and storing one into the global, we can use a cast
1660 // instead of a select to synthesize the desired value.
1661 bool IsOneZero = false;
1662 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal))
Reid Spencercae57542007-03-02 00:28:52 +00001663 IsOneZero = InitVal->isNullValue() && CI->isOne();
Chris Lattner96a86b22004-12-12 05:53:50 +00001664
1665 while (!GV->use_empty()) {
Devang Patel771281f2009-03-06 01:39:36 +00001666 Instruction *UI = cast<Instruction>(GV->use_back());
1667 if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
Chris Lattner96a86b22004-12-12 05:53:50 +00001668 // Change the store into a boolean store.
1669 bool StoringOther = SI->getOperand(0) == OtherVal;
1670 // Only do this if we weren't storing a loaded value.
Chris Lattner38c25562004-12-12 19:34:41 +00001671 Value *StoreVal;
Chris Lattner96a86b22004-12-12 05:53:50 +00001672 if (StoringOther || SI->getOperand(0) == InitVal)
Chris Lattner7b550cc2009-11-06 04:27:31 +00001673 StoreVal = ConstantInt::get(Type::getInt1Ty(GV->getContext()),
1674 StoringOther);
Chris Lattner38c25562004-12-12 19:34:41 +00001675 else {
1676 // Otherwise, we are storing a previously loaded copy. To do this,
1677 // change the copy from copying the original value to just copying the
1678 // bool.
1679 Instruction *StoredVal = cast<Instruction>(SI->getOperand(0));
1680
Gabor Greif9e4f2432010-06-24 14:42:01 +00001681 // If we've already replaced the input, StoredVal will be a cast or
Chris Lattner38c25562004-12-12 19:34:41 +00001682 // select instruction. If not, it will be a load of the original
1683 // global.
1684 if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
1685 assert(LI->getOperand(0) == GV && "Not a copy!");
1686 // Insert a new load, to preserve the saved value.
Nick Lewyckyfad4d402012-02-05 19:56:38 +00001687 StoreVal = new LoadInst(NewGV, LI->getName()+".b", false, 0,
1688 LI->getOrdering(), LI->getSynchScope(), LI);
Chris Lattner38c25562004-12-12 19:34:41 +00001689 } else {
1690 assert((isa<CastInst>(StoredVal) || isa<SelectInst>(StoredVal)) &&
1691 "This is not a form that we understand!");
1692 StoreVal = StoredVal->getOperand(0);
1693 assert(isa<LoadInst>(StoreVal) && "Not a load of NewGV!");
1694 }
1695 }
Nick Lewyckyfad4d402012-02-05 19:56:38 +00001696 new StoreInst(StoreVal, NewGV, false, 0,
1697 SI->getOrdering(), SI->getSynchScope(), SI);
Devang Patel771281f2009-03-06 01:39:36 +00001698 } else {
Chris Lattner96a86b22004-12-12 05:53:50 +00001699 // Change the load into a load of bool then a select.
Devang Patel771281f2009-03-06 01:39:36 +00001700 LoadInst *LI = cast<LoadInst>(UI);
Nick Lewyckyfad4d402012-02-05 19:56:38 +00001701 LoadInst *NLI = new LoadInst(NewGV, LI->getName()+".b", false, 0,
1702 LI->getOrdering(), LI->getSynchScope(), LI);
Chris Lattner96a86b22004-12-12 05:53:50 +00001703 Value *NSI;
1704 if (IsOneZero)
Chris Lattner046800a2007-02-11 01:08:35 +00001705 NSI = new ZExtInst(NLI, LI->getType(), "", LI);
Misha Brukmanfd939082005-04-21 23:48:37 +00001706 else
Gabor Greif051a9502008-04-06 20:25:17 +00001707 NSI = SelectInst::Create(NLI, OtherVal, InitVal, "", LI);
Chris Lattner046800a2007-02-11 01:08:35 +00001708 NSI->takeName(LI);
Chris Lattner96a86b22004-12-12 05:53:50 +00001709 LI->replaceAllUsesWith(NSI);
Devang Patel771281f2009-03-06 01:39:36 +00001710 }
1711 UI->eraseFromParent();
Chris Lattner96a86b22004-12-12 05:53:50 +00001712 }
1713
1714 GV->eraseFromParent();
Chris Lattner58e44f42008-01-14 01:17:44 +00001715 return true;
Chris Lattner96a86b22004-12-12 05:53:50 +00001716}
1717
1718
Nick Lewyckydb292a62012-02-12 00:52:26 +00001719/// ProcessGlobal - Analyze the specified global variable and optimize it if
1720/// possible. If we make a change, return true.
Rafael Espindolac4440e32011-01-19 16:32:21 +00001721bool GlobalOpt::ProcessGlobal(GlobalVariable *GV,
1722 Module::global_iterator &GVI) {
Rafael Espindola03977292012-06-14 22:48:13 +00001723 if (!GV->isDiscardableIfUnused())
Rafael Espindolac4440e32011-01-19 16:32:21 +00001724 return false;
1725
1726 // Do more involved optimizations if the global is internal.
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001727 GV->removeDeadConstantUsers();
1728
1729 if (GV->use_empty()) {
David Greene3215b0e2010-01-05 01:28:05 +00001730 DEBUG(dbgs() << "GLOBAL DEAD: " << *GV);
Chris Lattner7a7ed022004-10-16 18:09:00 +00001731 GV->eraseFromParent();
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001732 ++NumDeleted;
1733 return true;
1734 }
1735
Rafael Espindola2f135d42012-06-15 18:00:24 +00001736 if (!GV->hasLocalLinkage())
1737 return false;
1738
Rafael Espindolac4440e32011-01-19 16:32:21 +00001739 SmallPtrSet<const PHINode*, 16> PHIUsers;
1740 GlobalStatus GS;
1741
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001742 if (AnalyzeGlobal(GV, GS, PHIUsers))
1743 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001744
Rafael Espindolac4440e32011-01-19 16:32:21 +00001745 if (!GS.isCompared && !GV->hasUnnamedAddr()) {
1746 GV->setUnnamedAddr(true);
1747 NumUnnamed++;
1748 }
1749
1750 if (GV->isConstant() || !GV->hasInitializer())
1751 return false;
1752
1753 return ProcessInternalGlobal(GV, GVI, PHIUsers, GS);
1754}
1755
1756/// ProcessInternalGlobal - Analyze the specified global variable and optimize
1757/// it if possible. If we make a change, return true.
1758bool GlobalOpt::ProcessInternalGlobal(GlobalVariable *GV,
1759 Module::global_iterator &GVI,
Nick Lewyckydb292a62012-02-12 00:52:26 +00001760 const SmallPtrSet<const PHINode*, 16> &PHIUsers,
Rafael Espindolac4440e32011-01-19 16:32:21 +00001761 const GlobalStatus &GS) {
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001762 // If this is a first class global and has only one accessing function
1763 // and this function is main (which we know is not recursive we can make
1764 // this global a local variable) we replace the global with a local alloca
1765 // in this function.
1766 //
1767 // NOTE: It doesn't make sense to promote non single-value types since we
1768 // are just replacing static memory to stack memory.
1769 //
1770 // If the global is in different address space, don't bring it to stack.
1771 if (!GS.HasMultipleAccessingFunctions &&
1772 GS.AccessingFunction && !GS.HasNonInstructionUser &&
1773 GV->getType()->getElementType()->isSingleValueType() &&
1774 GS.AccessingFunction->getName() == "main" &&
1775 GS.AccessingFunction->hasExternalLinkage() &&
1776 GV->getType()->getAddressSpace() == 0) {
1777 DEBUG(dbgs() << "LOCALIZING GLOBAL: " << *GV);
Nick Lewyckybc384a12012-02-05 19:48:37 +00001778 Instruction &FirstI = const_cast<Instruction&>(*GS.AccessingFunction
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001779 ->getEntryBlock().begin());
Nick Lewyckybc384a12012-02-05 19:48:37 +00001780 Type *ElemTy = GV->getType()->getElementType();
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001781 // FIXME: Pass Global's alignment when globals have alignment
Nick Lewyckybc384a12012-02-05 19:48:37 +00001782 AllocaInst *Alloca = new AllocaInst(ElemTy, NULL, GV->getName(), &FirstI);
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001783 if (!isa<UndefValue>(GV->getInitializer()))
1784 new StoreInst(GV->getInitializer(), Alloca, &FirstI);
Misha Brukmanfd939082005-04-21 23:48:37 +00001785
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001786 GV->replaceAllUsesWith(Alloca);
1787 GV->eraseFromParent();
1788 ++NumLocalized;
1789 return true;
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001790 }
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001791
1792 // If the global is never loaded (but may be stored to), it is dead.
1793 // Delete it now.
1794 if (!GS.isLoaded) {
1795 DEBUG(dbgs() << "GLOBAL NEVER LOADED: " << *GV);
1796
Nick Lewyckyc7088c92012-07-21 09:03:15 +00001797 // Delete any stores we can find to the global. We may not be able to
1798 // make it completely dead though.
1799 bool Changed = CleanupConstantGlobalUsers(GV, GV->getInitializer(),
1800 TD, TLI);
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001801
1802 // If the global is dead now, delete it.
1803 if (GV->use_empty()) {
1804 GV->eraseFromParent();
1805 ++NumDeleted;
1806 Changed = true;
1807 }
1808 return Changed;
1809
1810 } else if (GS.StoredType <= GlobalStatus::isInitializerStored) {
1811 DEBUG(dbgs() << "MARKING CONSTANT: " << *GV);
1812 GV->setConstant(true);
1813
1814 // Clean up any obviously simplifiable users now.
Nick Lewycky6a577f82012-02-12 01:13:18 +00001815 CleanupConstantGlobalUsers(GV, GV->getInitializer(), TD, TLI);
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001816
1817 // If the global is dead now, just nuke it.
1818 if (GV->use_empty()) {
1819 DEBUG(dbgs() << " *** Marking constant allowed us to simplify "
1820 << "all users and delete global!\n");
1821 GV->eraseFromParent();
1822 ++NumDeleted;
1823 }
1824
1825 ++NumMarked;
1826 return true;
1827 } else if (!GV->getInitializer()->getType()->isSingleValueType()) {
1828 if (TargetData *TD = getAnalysisIfAvailable<TargetData>())
1829 if (GlobalVariable *FirstNewGV = SRAGlobal(GV, *TD)) {
1830 GVI = FirstNewGV; // Don't skip the newly produced globals!
1831 return true;
1832 }
1833 } else if (GS.StoredType == GlobalStatus::isStoredOnce) {
1834 // If the initial value for the global was an undef value, and if only
1835 // one other value was stored into it, we can just change the
1836 // initializer to be the stored value, then delete all stores to the
1837 // global. This allows us to mark it constant.
1838 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
1839 if (isa<UndefValue>(GV->getInitializer())) {
1840 // Change the initial value here.
1841 GV->setInitializer(SOVConstant);
1842
1843 // Clean up any obviously simplifiable users now.
Nick Lewycky6a577f82012-02-12 01:13:18 +00001844 CleanupConstantGlobalUsers(GV, GV->getInitializer(), TD, TLI);
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001845
1846 if (GV->use_empty()) {
1847 DEBUG(dbgs() << " *** Substituting initializer allowed us to "
Nick Lewyckyc7088c92012-07-21 09:03:15 +00001848 << "simplify all users and delete global!\n");
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001849 GV->eraseFromParent();
1850 ++NumDeleted;
1851 } else {
1852 GVI = GV;
1853 }
1854 ++NumSubstitute;
1855 return true;
1856 }
1857
1858 // Try to optimize globals based on the knowledge that only one value
1859 // (besides its initializer) is ever stored to the global.
Nick Lewyckyfad4d402012-02-05 19:56:38 +00001860 if (OptimizeOnceStoredGlobal(GV, GS.StoredOnceValue, GS.Ordering, GVI,
Nick Lewycky6a577f82012-02-12 01:13:18 +00001861 TD, TLI))
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001862 return true;
1863
1864 // Otherwise, if the global was not a boolean, we can shrink it to be a
1865 // boolean.
1866 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
1867 if (TryToShrinkGlobalToBoolean(GV, SOVConstant)) {
1868 ++NumShrunkToBool;
1869 return true;
1870 }
1871 }
1872
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001873 return false;
1874}
1875
Chris Lattnerfb217ad2005-05-08 22:18:06 +00001876/// ChangeCalleesToFastCall - Walk all of the direct calls of the specified
1877/// function, changing them to FastCC.
1878static void ChangeCalleesToFastCall(Function *F) {
1879 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
Jay Foadb7454fd2012-05-12 08:30:16 +00001880 if (isa<BlockAddress>(*UI))
1881 continue;
Duncan Sands548448a2008-02-18 17:32:13 +00001882 CallSite User(cast<Instruction>(*UI));
1883 User.setCallingConv(CallingConv::Fast);
Chris Lattnerfb217ad2005-05-08 22:18:06 +00001884 }
1885}
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001886
Devang Patel05988662008-09-25 21:00:45 +00001887static AttrListPtr StripNest(const AttrListPtr &Attrs) {
Chris Lattner58d74912008-03-12 17:45:29 +00001888 for (unsigned i = 0, e = Attrs.getNumSlots(); i != e; ++i) {
Devang Patel05988662008-09-25 21:00:45 +00001889 if ((Attrs.getSlot(i).Attrs & Attribute::Nest) == 0)
Duncan Sands548448a2008-02-18 17:32:13 +00001890 continue;
1891
Duncan Sands548448a2008-02-18 17:32:13 +00001892 // There can be only one.
Devang Patel05988662008-09-25 21:00:45 +00001893 return Attrs.removeAttr(Attrs.getSlot(i).Index, Attribute::Nest);
Duncan Sands3d5378f2008-02-16 20:56:04 +00001894 }
1895
1896 return Attrs;
1897}
1898
1899static void RemoveNestAttribute(Function *F) {
Devang Patel05988662008-09-25 21:00:45 +00001900 F->setAttributes(StripNest(F->getAttributes()));
Duncan Sands3d5378f2008-02-16 20:56:04 +00001901 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
Jay Foadb7454fd2012-05-12 08:30:16 +00001902 if (isa<BlockAddress>(*UI))
1903 continue;
Duncan Sands548448a2008-02-18 17:32:13 +00001904 CallSite User(cast<Instruction>(*UI));
Devang Patel05988662008-09-25 21:00:45 +00001905 User.setAttributes(StripNest(User.getAttributes()));
Duncan Sands3d5378f2008-02-16 20:56:04 +00001906 }
1907}
1908
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001909bool GlobalOpt::OptimizeFunctions(Module &M) {
1910 bool Changed = false;
1911 // Optimize functions.
1912 for (Module::iterator FI = M.begin(), E = M.end(); FI != E; ) {
1913 Function *F = FI++;
Duncan Sandsfc5940d2009-03-06 10:21:56 +00001914 // Functions without names cannot be referenced outside this module.
1915 if (!F->hasName() && !F->isDeclaration())
1916 F->setLinkage(GlobalValue::InternalLinkage);
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001917 F->removeDeadConstantUsers();
Eli Friedmanc6633052011-10-20 05:23:42 +00001918 if (F->isDefTriviallyDead()) {
Chris Lattnerec4c7b92009-11-01 19:03:42 +00001919 F->eraseFromParent();
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001920 Changed = true;
1921 ++NumFnDeleted;
Rafael Espindolabb46f522009-01-15 20:18:42 +00001922 } else if (F->hasLocalLinkage()) {
Duncan Sands3d5378f2008-02-16 20:56:04 +00001923 if (F->getCallingConv() == CallingConv::C && !F->isVarArg() &&
Jay Foad757068f2009-06-10 08:41:11 +00001924 !F->hasAddressTaken()) {
Duncan Sands3d5378f2008-02-16 20:56:04 +00001925 // If this function has C calling conventions, is not a varargs
1926 // function, and is only called directly, promote it to use the Fast
1927 // calling convention.
1928 F->setCallingConv(CallingConv::Fast);
1929 ChangeCalleesToFastCall(F);
1930 ++NumFastCallFns;
1931 Changed = true;
1932 }
1933
Devang Patel05988662008-09-25 21:00:45 +00001934 if (F->getAttributes().hasAttrSomewhere(Attribute::Nest) &&
Jay Foad757068f2009-06-10 08:41:11 +00001935 !F->hasAddressTaken()) {
Duncan Sands3d5378f2008-02-16 20:56:04 +00001936 // The function is not used by a trampoline intrinsic, so it is safe
1937 // to remove the 'nest' attribute.
1938 RemoveNestAttribute(F);
1939 ++NumNestRemoved;
1940 Changed = true;
1941 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001942 }
1943 }
1944 return Changed;
1945}
1946
1947bool GlobalOpt::OptimizeGlobalVars(Module &M) {
1948 bool Changed = false;
1949 for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
1950 GVI != E; ) {
1951 GlobalVariable *GV = GVI++;
Duncan Sandsfc5940d2009-03-06 10:21:56 +00001952 // Global variables without names cannot be referenced outside this module.
1953 if (!GV->hasName() && !GV->isDeclaration())
1954 GV->setLinkage(GlobalValue::InternalLinkage);
Dan Gohman01b97dd2009-11-23 16:22:21 +00001955 // Simplify the initializer.
1956 if (GV->hasInitializer())
1957 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GV->getInitializer())) {
Chad Rosieraab8e282011-12-02 01:26:24 +00001958 Constant *New = ConstantFoldConstantExpression(CE, TD, TLI);
Dan Gohman01b97dd2009-11-23 16:22:21 +00001959 if (New && New != CE)
1960 GV->setInitializer(New);
1961 }
Rafael Espindolac4440e32011-01-19 16:32:21 +00001962
1963 Changed |= ProcessGlobal(GV, GVI);
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001964 }
1965 return Changed;
1966}
1967
Nick Lewycky2c44a802011-04-08 07:30:21 +00001968/// FindGlobalCtors - Find the llvm.global_ctors list, verifying that all
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001969/// initializers have an init priority of 65535.
1970GlobalVariable *GlobalOpt::FindGlobalCtors(Module &M) {
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00001971 GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
1972 if (GV == 0) return 0;
1973
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00001974 // Verify that the initializer is simple enough for us to handle. We are
1975 // only allowed to optimize the initializer if it is unique.
1976 if (!GV->hasUniqueInitializer()) return 0;
Nick Lewycky5ea5c612011-04-11 22:11:20 +00001977
1978 if (isa<ConstantAggregateZero>(GV->getInitializer()))
1979 return GV;
1980 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
Eli Friedman18a2e502011-04-09 09:11:09 +00001981
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00001982 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i) {
Nick Lewycky5ea5c612011-04-11 22:11:20 +00001983 if (isa<ConstantAggregateZero>(*i))
1984 continue;
1985 ConstantStruct *CS = cast<ConstantStruct>(*i);
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00001986 if (isa<ConstantPointerNull>(CS->getOperand(1)))
1987 continue;
Chris Lattner7d8e58f2005-09-26 02:19:27 +00001988
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00001989 // Must have a function or null ptr.
1990 if (!isa<Function>(CS->getOperand(1)))
1991 return 0;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001992
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00001993 // Init priority must be standard.
Nick Lewycky2c44a802011-04-08 07:30:21 +00001994 ConstantInt *CI = cast<ConstantInt>(CS->getOperand(0));
1995 if (CI->getZExtValue() != 65535)
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00001996 return 0;
1997 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001998
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00001999 return GV;
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002000}
2001
Chris Lattnerdb973e62005-09-26 02:31:18 +00002002/// ParseGlobalCtors - Given a llvm.global_ctors list that we can understand,
2003/// return a list of the functions and null terminator as a vector.
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002004static std::vector<Function*> ParseGlobalCtors(GlobalVariable *GV) {
Nick Lewycky5ea5c612011-04-11 22:11:20 +00002005 if (GV->getInitializer()->isNullValue())
2006 return std::vector<Function*>();
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002007 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
2008 std::vector<Function*> Result;
2009 Result.reserve(CA->getNumOperands());
Gabor Greif5e463212008-05-29 01:59:18 +00002010 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i) {
2011 ConstantStruct *CS = cast<ConstantStruct>(*i);
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002012 Result.push_back(dyn_cast<Function>(CS->getOperand(1)));
2013 }
2014 return Result;
2015}
2016
Chris Lattnerdb973e62005-09-26 02:31:18 +00002017/// InstallGlobalCtors - Given a specified llvm.global_ctors list, install the
2018/// specified array, returning the new global to use.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002019static GlobalVariable *InstallGlobalCtors(GlobalVariable *GCL,
Chris Lattner7b550cc2009-11-06 04:27:31 +00002020 const std::vector<Function*> &Ctors) {
Chris Lattnerdb973e62005-09-26 02:31:18 +00002021 // If we made a change, reassemble the initializer list.
Chris Lattnerb065b062011-06-20 04:01:31 +00002022 Constant *CSVals[2];
2023 CSVals[0] = ConstantInt::get(Type::getInt32Ty(GCL->getContext()), 65535);
2024 CSVals[1] = 0;
2025
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002026 StructType *StructTy =
Chris Lattnerb065b062011-06-20 04:01:31 +00002027 cast <StructType>(
2028 cast<ArrayType>(GCL->getType()->getElementType())->getElementType());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002029
Chris Lattnerdb973e62005-09-26 02:31:18 +00002030 // Create the new init list.
2031 std::vector<Constant*> CAList;
2032 for (unsigned i = 0, e = Ctors.size(); i != e; ++i) {
Chris Lattner79c11012005-09-26 04:44:35 +00002033 if (Ctors[i]) {
Chris Lattnerdb973e62005-09-26 02:31:18 +00002034 CSVals[1] = Ctors[i];
Chris Lattner79c11012005-09-26 04:44:35 +00002035 } else {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002036 Type *FTy = FunctionType::get(Type::getVoidTy(GCL->getContext()),
Chris Lattner7b550cc2009-11-06 04:27:31 +00002037 false);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002038 PointerType *PFTy = PointerType::getUnqual(FTy);
Owen Andersona7235ea2009-07-31 20:28:14 +00002039 CSVals[1] = Constant::getNullValue(PFTy);
Chris Lattner7b550cc2009-11-06 04:27:31 +00002040 CSVals[0] = ConstantInt::get(Type::getInt32Ty(GCL->getContext()),
Nick Lewycky5ea5c612011-04-11 22:11:20 +00002041 0x7fffffff);
Chris Lattnerdb973e62005-09-26 02:31:18 +00002042 }
Chris Lattnerb065b062011-06-20 04:01:31 +00002043 CAList.push_back(ConstantStruct::get(StructTy, CSVals));
Chris Lattnerdb973e62005-09-26 02:31:18 +00002044 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002045
Chris Lattnerdb973e62005-09-26 02:31:18 +00002046 // Create the array initializer.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002047 Constant *CA = ConstantArray::get(ArrayType::get(StructTy,
Nick Lewyckyc332fba2009-09-19 20:30:26 +00002048 CAList.size()), CAList);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002049
Chris Lattnerdb973e62005-09-26 02:31:18 +00002050 // If we didn't change the number of elements, don't create a new GV.
2051 if (CA->getType() == GCL->getInitializer()->getType()) {
2052 GCL->setInitializer(CA);
2053 return GCL;
2054 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002055
Chris Lattnerdb973e62005-09-26 02:31:18 +00002056 // Create the new global and insert it next to the existing list.
Chris Lattner7b550cc2009-11-06 04:27:31 +00002057 GlobalVariable *NGV = new GlobalVariable(CA->getType(), GCL->isConstant(),
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +00002058 GCL->getLinkage(), CA, "",
Hans Wennborgce718ff2012-06-23 11:37:03 +00002059 GCL->getThreadLocalMode());
Chris Lattnerdb973e62005-09-26 02:31:18 +00002060 GCL->getParent()->getGlobalList().insert(GCL, NGV);
Chris Lattner046800a2007-02-11 01:08:35 +00002061 NGV->takeName(GCL);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002062
Chris Lattnerdb973e62005-09-26 02:31:18 +00002063 // Nuke the old list, replacing any uses with the new one.
2064 if (!GCL->use_empty()) {
2065 Constant *V = NGV;
2066 if (V->getType() != GCL->getType())
Owen Andersonbaf3c402009-07-29 18:55:55 +00002067 V = ConstantExpr::getBitCast(V, GCL->getType());
Chris Lattnerdb973e62005-09-26 02:31:18 +00002068 GCL->replaceAllUsesWith(V);
2069 }
2070 GCL->eraseFromParent();
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002071
Chris Lattnerdb973e62005-09-26 02:31:18 +00002072 if (Ctors.size())
2073 return NGV;
2074 else
2075 return 0;
2076}
Chris Lattner79c11012005-09-26 04:44:35 +00002077
2078
Chris Lattner1945d582010-12-07 04:33:29 +00002079static inline bool
2080isSimpleEnoughValueToCommit(Constant *C,
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002081 SmallPtrSet<Constant*, 8> &SimpleConstants,
2082 const TargetData *TD);
Chris Lattner1945d582010-12-07 04:33:29 +00002083
2084
2085/// isSimpleEnoughValueToCommit - Return true if the specified constant can be
2086/// handled by the code generator. We don't want to generate something like:
2087/// void *X = &X/42;
2088/// because the code generator doesn't have a relocation that can handle that.
2089///
2090/// This function should be called if C was not found (but just got inserted)
2091/// in SimpleConstants to avoid having to rescan the same constants all the
2092/// time.
2093static bool isSimpleEnoughValueToCommitHelper(Constant *C,
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002094 SmallPtrSet<Constant*, 8> &SimpleConstants,
2095 const TargetData *TD) {
Chris Lattner1945d582010-12-07 04:33:29 +00002096 // Simple integer, undef, constant aggregate zero, global addresses, etc are
2097 // all supported.
2098 if (C->getNumOperands() == 0 || isa<BlockAddress>(C) ||
2099 isa<GlobalValue>(C))
2100 return true;
2101
2102 // Aggregate values are safe if all their elements are.
2103 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C) ||
2104 isa<ConstantVector>(C)) {
2105 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i) {
2106 Constant *Op = cast<Constant>(C->getOperand(i));
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002107 if (!isSimpleEnoughValueToCommit(Op, SimpleConstants, TD))
Chris Lattner1945d582010-12-07 04:33:29 +00002108 return false;
2109 }
2110 return true;
2111 }
2112
2113 // We don't know exactly what relocations are allowed in constant expressions,
2114 // so we allow &global+constantoffset, which is safe and uniformly supported
2115 // across targets.
2116 ConstantExpr *CE = cast<ConstantExpr>(C);
2117 switch (CE->getOpcode()) {
2118 case Instruction::BitCast:
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002119 // Bitcast is fine if the casted value is fine.
2120 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, TD);
2121
Chris Lattner1945d582010-12-07 04:33:29 +00002122 case Instruction::IntToPtr:
2123 case Instruction::PtrToInt:
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002124 // int <=> ptr is fine if the int type is the same size as the
2125 // pointer type.
2126 if (!TD || TD->getTypeSizeInBits(CE->getType()) !=
2127 TD->getTypeSizeInBits(CE->getOperand(0)->getType()))
2128 return false;
2129 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, TD);
Chris Lattner1945d582010-12-07 04:33:29 +00002130
2131 // GEP is fine if it is simple + constant offset.
2132 case Instruction::GetElementPtr:
2133 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
2134 if (!isa<ConstantInt>(CE->getOperand(i)))
2135 return false;
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002136 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, TD);
Chris Lattner1945d582010-12-07 04:33:29 +00002137
2138 case Instruction::Add:
2139 // We allow simple+cst.
2140 if (!isa<ConstantInt>(CE->getOperand(1)))
2141 return false;
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002142 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, TD);
Chris Lattner1945d582010-12-07 04:33:29 +00002143 }
2144 return false;
2145}
2146
2147static inline bool
2148isSimpleEnoughValueToCommit(Constant *C,
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002149 SmallPtrSet<Constant*, 8> &SimpleConstants,
2150 const TargetData *TD) {
Chris Lattner1945d582010-12-07 04:33:29 +00002151 // If we already checked this constant, we win.
2152 if (!SimpleConstants.insert(C)) return true;
2153 // Check the constant.
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002154 return isSimpleEnoughValueToCommitHelper(C, SimpleConstants, TD);
Chris Lattner1945d582010-12-07 04:33:29 +00002155}
2156
2157
Chris Lattner79c11012005-09-26 04:44:35 +00002158/// isSimpleEnoughPointerToCommit - Return true if this constant is simple
Owen Andersoncff6b372011-01-14 22:19:20 +00002159/// enough for us to understand. In particular, if it is a cast to anything
2160/// other than from one pointer type to another pointer type, we punt.
2161/// We basically just support direct accesses to globals and GEP's of
Chris Lattner79c11012005-09-26 04:44:35 +00002162/// globals. This should be kept up to date with CommitValueTo.
Chris Lattner7b550cc2009-11-06 04:27:31 +00002163static bool isSimpleEnoughPointerToCommit(Constant *C) {
Dan Gohmance5de5b2009-09-07 22:42:05 +00002164 // Conservatively, avoid aggregate types. This is because we don't
2165 // want to worry about them partially overlapping other stores.
2166 if (!cast<PointerType>(C->getType())->getElementType()->isSingleValueType())
2167 return false;
2168
Dan Gohmanfd54a892009-09-07 22:31:26 +00002169 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
Mikhail Glushenkov99fca5d2010-10-19 16:47:23 +00002170 // Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or
Dan Gohmanfd54a892009-09-07 22:31:26 +00002171 // external globals.
Mikhail Glushenkov99fca5d2010-10-19 16:47:23 +00002172 return GV->hasUniqueInitializer();
Dan Gohmanfd54a892009-09-07 22:31:26 +00002173
Owen Andersone95a32c2011-01-14 22:31:13 +00002174 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002175 // Handle a constantexpr gep.
2176 if (CE->getOpcode() == Instruction::GetElementPtr &&
Dan Gohmanc62482d2009-09-07 22:40:13 +00002177 isa<GlobalVariable>(CE->getOperand(0)) &&
2178 cast<GEPOperator>(CE)->isInBounds()) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002179 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
Mikhail Glushenkov99fca5d2010-10-19 16:47:23 +00002180 // Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or
Dan Gohmanfd54a892009-09-07 22:31:26 +00002181 // external globals.
Mikhail Glushenkov99fca5d2010-10-19 16:47:23 +00002182 if (!GV->hasUniqueInitializer())
Dan Gohmanfd54a892009-09-07 22:31:26 +00002183 return false;
Dan Gohman80bdc962009-09-07 22:44:55 +00002184
Dan Gohman80bdc962009-09-07 22:44:55 +00002185 // The first index must be zero.
Oscar Fuentesee56c422010-08-02 06:00:15 +00002186 ConstantInt *CI = dyn_cast<ConstantInt>(*llvm::next(CE->op_begin()));
Dan Gohman80bdc962009-09-07 22:44:55 +00002187 if (!CI || !CI->isZero()) return false;
Dan Gohman80bdc962009-09-07 22:44:55 +00002188
2189 // The remaining indices must be compile-time known integers within the
Dan Gohmane6992f72009-09-10 23:37:55 +00002190 // notional bounds of the corresponding static array types.
2191 if (!CE->isGEPWithNoNotionalOverIndexing())
2192 return false;
Dan Gohman80bdc962009-09-07 22:44:55 +00002193
Dan Gohmanc6f69e92009-10-05 16:36:26 +00002194 return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
Owen Andersoncff6b372011-01-14 22:19:20 +00002195
2196 // A constantexpr bitcast from a pointer to another pointer is a no-op,
2197 // and we know how to evaluate it by moving the bitcast from the pointer
2198 // operand to the value operand.
2199 } else if (CE->getOpcode() == Instruction::BitCast &&
Chris Lattnerd5f656f2011-01-16 02:05:10 +00002200 isa<GlobalVariable>(CE->getOperand(0))) {
Owen Andersoncff6b372011-01-14 22:19:20 +00002201 // Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or
2202 // external globals.
Chris Lattnerd5f656f2011-01-16 02:05:10 +00002203 return cast<GlobalVariable>(CE->getOperand(0))->hasUniqueInitializer();
Chris Lattner798b4d52005-09-26 06:52:44 +00002204 }
Owen Andersone95a32c2011-01-14 22:31:13 +00002205 }
2206
Chris Lattner79c11012005-09-26 04:44:35 +00002207 return false;
2208}
2209
Chris Lattner798b4d52005-09-26 06:52:44 +00002210/// EvaluateStoreInto - Evaluate a piece of a constantexpr store into a global
2211/// initializer. This returns 'Init' modified to reflect 'Val' stored into it.
2212/// At this point, the GEP operands of Addr [0, OpNo) have been stepped into.
2213static Constant *EvaluateStoreInto(Constant *Init, Constant *Val,
Chris Lattner7b550cc2009-11-06 04:27:31 +00002214 ConstantExpr *Addr, unsigned OpNo) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002215 // Base case of the recursion.
2216 if (OpNo == Addr->getNumOperands()) {
2217 assert(Val->getType() == Init->getType() && "Type mismatch!");
2218 return Val;
2219 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002220
Chris Lattnera78fa8c2012-01-27 03:08:05 +00002221 SmallVector<Constant*, 32> Elts;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002222 if (StructType *STy = dyn_cast<StructType>(Init->getType())) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002223 // Break up the constant into its elements.
Chris Lattnerd59ae902012-01-26 02:32:04 +00002224 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
2225 Elts.push_back(Init->getAggregateElement(i));
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002226
Chris Lattner798b4d52005-09-26 06:52:44 +00002227 // Replace the element that we are supposed to.
Reid Spencerb83eb642006-10-20 07:07:24 +00002228 ConstantInt *CU = cast<ConstantInt>(Addr->getOperand(OpNo));
2229 unsigned Idx = CU->getZExtValue();
2230 assert(Idx < STy->getNumElements() && "Struct index out of range!");
Chris Lattner7b550cc2009-11-06 04:27:31 +00002231 Elts[Idx] = EvaluateStoreInto(Elts[Idx], Val, Addr, OpNo+1);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002232
Chris Lattner798b4d52005-09-26 06:52:44 +00002233 // Return the modified struct.
Chris Lattnerb065b062011-06-20 04:01:31 +00002234 return ConstantStruct::get(STy, Elts);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002235 }
Chris Lattnerb065b062011-06-20 04:01:31 +00002236
2237 ConstantInt *CI = cast<ConstantInt>(Addr->getOperand(OpNo));
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002238 SequentialType *InitTy = cast<SequentialType>(Init->getType());
Chris Lattnerb065b062011-06-20 04:01:31 +00002239
2240 uint64_t NumElts;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002241 if (ArrayType *ATy = dyn_cast<ArrayType>(InitTy))
Chris Lattnerb065b062011-06-20 04:01:31 +00002242 NumElts = ATy->getNumElements();
2243 else
Chris Lattnerd59ae902012-01-26 02:32:04 +00002244 NumElts = InitTy->getVectorNumElements();
Chris Lattnerb065b062011-06-20 04:01:31 +00002245
2246 // Break up the array into elements.
Chris Lattnerd59ae902012-01-26 02:32:04 +00002247 for (uint64_t i = 0, e = NumElts; i != e; ++i)
2248 Elts.push_back(Init->getAggregateElement(i));
Chris Lattnerb065b062011-06-20 04:01:31 +00002249
2250 assert(CI->getZExtValue() < NumElts);
2251 Elts[CI->getZExtValue()] =
2252 EvaluateStoreInto(Elts[CI->getZExtValue()], Val, Addr, OpNo+1);
2253
2254 if (Init->getType()->isArrayTy())
2255 return ConstantArray::get(cast<ArrayType>(InitTy), Elts);
2256 return ConstantVector::get(Elts);
Chris Lattner798b4d52005-09-26 06:52:44 +00002257}
2258
Chris Lattner79c11012005-09-26 04:44:35 +00002259/// CommitValueTo - We have decided that Addr (which satisfies the predicate
2260/// isSimpleEnoughPointerToCommit) should get Val as its value. Make it happen.
Chris Lattner7b550cc2009-11-06 04:27:31 +00002261static void CommitValueTo(Constant *Val, Constant *Addr) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002262 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Addr)) {
2263 assert(GV->hasInitializer());
2264 GV->setInitializer(Val);
2265 return;
2266 }
Chris Lattnera0e9a242010-01-07 01:16:21 +00002267
Chris Lattner798b4d52005-09-26 06:52:44 +00002268 ConstantExpr *CE = cast<ConstantExpr>(Addr);
2269 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
Chris Lattnera0e9a242010-01-07 01:16:21 +00002270 GV->setInitializer(EvaluateStoreInto(GV->getInitializer(), Val, CE, 2));
Chris Lattner79c11012005-09-26 04:44:35 +00002271}
2272
Nick Lewycky7fa76772012-02-20 03:25:59 +00002273namespace {
2274
2275/// Evaluator - This class evaluates LLVM IR, producing the Constant
2276/// representing each SSA instruction. Changes to global variables are stored
2277/// in a mapping that can be iterated over after the evaluation is complete.
2278/// Once an evaluation call fails, the evaluation object should not be reused.
2279class Evaluator {
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002280public:
Nick Lewycky7fa76772012-02-20 03:25:59 +00002281 Evaluator(const TargetData *TD, const TargetLibraryInfo *TLI)
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002282 : TD(TD), TLI(TLI) {
2283 ValueStack.push_back(new DenseMap<Value*, Constant*>);
2284 }
2285
Nick Lewycky7fa76772012-02-20 03:25:59 +00002286 ~Evaluator() {
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002287 DeleteContainerPointers(ValueStack);
2288 while (!AllocaTmps.empty()) {
2289 GlobalVariable *Tmp = AllocaTmps.back();
2290 AllocaTmps.pop_back();
2291
2292 // If there are still users of the alloca, the program is doing something
2293 // silly, e.g. storing the address of the alloca somewhere and using it
2294 // later. Since this is undefined, we'll just make it be null.
2295 if (!Tmp->use_empty())
2296 Tmp->replaceAllUsesWith(Constant::getNullValue(Tmp->getType()));
2297 delete Tmp;
2298 }
2299 }
2300
2301 /// EvaluateFunction - Evaluate a call to function F, returning true if
2302 /// successful, false if we can't evaluate it. ActualArgs contains the formal
2303 /// arguments for the function.
2304 bool EvaluateFunction(Function *F, Constant *&RetVal,
2305 const SmallVectorImpl<Constant*> &ActualArgs);
2306
2307 /// EvaluateBlock - Evaluate all instructions in block BB, returning true if
2308 /// successful, false if we can't evaluate it. NewBB returns the next BB that
2309 /// control flows into, or null upon return.
2310 bool EvaluateBlock(BasicBlock::iterator CurInst, BasicBlock *&NextBB);
2311
2312 Constant *getVal(Value *V) {
2313 if (Constant *CV = dyn_cast<Constant>(V)) return CV;
2314 Constant *R = ValueStack.back()->lookup(V);
2315 assert(R && "Reference to an uncomputed value!");
2316 return R;
2317 }
2318
2319 void setVal(Value *V, Constant *C) {
2320 ValueStack.back()->operator[](V) = C;
2321 }
2322
2323 const DenseMap<Constant*, Constant*> &getMutatedMemory() const {
2324 return MutatedMemory;
2325 }
2326
2327 const SmallPtrSet<GlobalVariable*, 8> &getInvariants() const {
2328 return Invariants;
2329 }
2330
2331private:
2332 Constant *ComputeLoadResult(Constant *P);
2333
2334 /// ValueStack - As we compute SSA register values, we store their contents
2335 /// here. The back of the vector contains the current function and the stack
2336 /// contains the values in the calling frames.
2337 SmallVector<DenseMap<Value*, Constant*>*, 4> ValueStack;
2338
2339 /// CallStack - This is used to detect recursion. In pathological situations
2340 /// we could hit exponential behavior, but at least there is nothing
2341 /// unbounded.
2342 SmallVector<Function*, 4> CallStack;
2343
2344 /// MutatedMemory - For each store we execute, we update this map. Loads
2345 /// check this to get the most up-to-date value. If evaluation is successful,
2346 /// this state is committed to the process.
2347 DenseMap<Constant*, Constant*> MutatedMemory;
2348
2349 /// AllocaTmps - To 'execute' an alloca, we create a temporary global variable
2350 /// to represent its body. This vector is needed so we can delete the
2351 /// temporary globals when we are done.
2352 SmallVector<GlobalVariable*, 32> AllocaTmps;
2353
2354 /// Invariants - These global variables have been marked invariant by the
2355 /// static constructor.
2356 SmallPtrSet<GlobalVariable*, 8> Invariants;
2357
2358 /// SimpleConstants - These are constants we have checked and know to be
2359 /// simple enough to live in a static initializer of a global.
2360 SmallPtrSet<Constant*, 8> SimpleConstants;
2361
2362 const TargetData *TD;
2363 const TargetLibraryInfo *TLI;
2364};
2365
Nick Lewycky7fa76772012-02-20 03:25:59 +00002366} // anonymous namespace
2367
Chris Lattner562a0552005-09-26 05:16:34 +00002368/// ComputeLoadResult - Return the value that would be computed by a load from
2369/// P after the stores reflected by 'memory' have been performed. If we can't
2370/// decide, return null.
Nick Lewycky7fa76772012-02-20 03:25:59 +00002371Constant *Evaluator::ComputeLoadResult(Constant *P) {
Chris Lattner04de1cf2005-09-26 05:15:37 +00002372 // If this memory location has been recently stored, use the stored value: it
2373 // is the most up-to-date.
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002374 DenseMap<Constant*, Constant*>::const_iterator I = MutatedMemory.find(P);
2375 if (I != MutatedMemory.end()) return I->second;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002376
Chris Lattner04de1cf2005-09-26 05:15:37 +00002377 // Access it.
2378 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(P)) {
Dan Gohman82555732009-08-19 18:20:44 +00002379 if (GV->hasDefinitiveInitializer())
Chris Lattner04de1cf2005-09-26 05:15:37 +00002380 return GV->getInitializer();
2381 return 0;
Chris Lattner04de1cf2005-09-26 05:15:37 +00002382 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002383
Chris Lattner798b4d52005-09-26 06:52:44 +00002384 // Handle a constantexpr getelementptr.
2385 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(P))
2386 if (CE->getOpcode() == Instruction::GetElementPtr &&
2387 isa<GlobalVariable>(CE->getOperand(0))) {
2388 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
Dan Gohman82555732009-08-19 18:20:44 +00002389 if (GV->hasDefinitiveInitializer())
Dan Gohmanc6f69e92009-10-05 16:36:26 +00002390 return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
Chris Lattner798b4d52005-09-26 06:52:44 +00002391 }
2392
2393 return 0; // don't know how to evaluate.
Chris Lattner04de1cf2005-09-26 05:15:37 +00002394}
2395
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002396/// EvaluateBlock - Evaluate all instructions in block BB, returning true if
2397/// successful, false if we can't evaluate it. NewBB returns the next BB that
2398/// control flows into, or null upon return.
Nick Lewycky7fa76772012-02-20 03:25:59 +00002399bool Evaluator::EvaluateBlock(BasicBlock::iterator CurInst,
2400 BasicBlock *&NextBB) {
Chris Lattner79c11012005-09-26 04:44:35 +00002401 // This is the main evaluation loop.
2402 while (1) {
2403 Constant *InstResult = 0;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002404
Chris Lattner79c11012005-09-26 04:44:35 +00002405 if (StoreInst *SI = dyn_cast<StoreInst>(CurInst)) {
Eli Friedman33cb4452011-08-16 00:20:11 +00002406 if (!SI->isSimple()) return false; // no volatile/atomic accesses.
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002407 Constant *Ptr = getVal(SI->getOperand(1));
Nick Lewyckya641c072012-02-21 22:08:06 +00002408 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
2409 Ptr = ConstantFoldConstantExpression(CE, TD, TLI);
Chris Lattner7b550cc2009-11-06 04:27:31 +00002410 if (!isSimpleEnoughPointerToCommit(Ptr))
Chris Lattner79c11012005-09-26 04:44:35 +00002411 // If this is too complex for us to commit, reject it.
Chris Lattnercd271422005-09-27 04:45:34 +00002412 return false;
Chris Lattner1945d582010-12-07 04:33:29 +00002413
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002414 Constant *Val = getVal(SI->getOperand(0));
Chris Lattner1945d582010-12-07 04:33:29 +00002415
2416 // If this might be too difficult for the backend to handle (e.g. the addr
2417 // of one global variable divided by another) then we can't commit it.
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002418 if (!isSimpleEnoughValueToCommit(Val, SimpleConstants, TD))
Chris Lattner1945d582010-12-07 04:33:29 +00002419 return false;
Owen Andersoncff6b372011-01-14 22:19:20 +00002420
2421 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
2422 if (CE->getOpcode() == Instruction::BitCast) {
2423 // If we're evaluating a store through a bitcast, then we need
2424 // to pull the bitcast off the pointer type and push it onto the
2425 // stored value.
Chris Lattnerd5f656f2011-01-16 02:05:10 +00002426 Ptr = CE->getOperand(0);
Owen Andersoncff6b372011-01-14 22:19:20 +00002427
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002428 Type *NewTy = cast<PointerType>(Ptr->getType())->getElementType();
Owen Andersoncff6b372011-01-14 22:19:20 +00002429
Owen Anderson66f708f2011-01-16 04:33:33 +00002430 // In order to push the bitcast onto the stored value, a bitcast
2431 // from NewTy to Val's type must be legal. If it's not, we can try
2432 // introspecting NewTy to find a legal conversion.
2433 while (!Val->getType()->canLosslesslyBitCastTo(NewTy)) {
2434 // If NewTy is a struct, we can convert the pointer to the struct
2435 // into a pointer to its first member.
2436 // FIXME: This could be extended to support arrays as well.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002437 if (StructType *STy = dyn_cast<StructType>(NewTy)) {
Owen Anderson66f708f2011-01-16 04:33:33 +00002438 NewTy = STy->getTypeAtIndex(0U);
2439
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002440 IntegerType *IdxTy = IntegerType::get(NewTy->getContext(), 32);
Owen Anderson66f708f2011-01-16 04:33:33 +00002441 Constant *IdxZero = ConstantInt::get(IdxTy, 0, false);
2442 Constant * const IdxList[] = {IdxZero, IdxZero};
2443
Jay Foadb4263a62011-07-22 08:52:50 +00002444 Ptr = ConstantExpr::getGetElementPtr(Ptr, IdxList);
Nick Lewyckya641c072012-02-21 22:08:06 +00002445 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
2446 Ptr = ConstantFoldConstantExpression(CE, TD, TLI);
2447
Owen Anderson66f708f2011-01-16 04:33:33 +00002448 // If we can't improve the situation by introspecting NewTy,
2449 // we have to give up.
2450 } else {
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002451 return false;
Owen Anderson66f708f2011-01-16 04:33:33 +00002452 }
Owen Andersoncff6b372011-01-14 22:19:20 +00002453 }
2454
Owen Anderson66f708f2011-01-16 04:33:33 +00002455 // If we found compatible types, go ahead and push the bitcast
2456 // onto the stored value.
Owen Andersoncff6b372011-01-14 22:19:20 +00002457 Val = ConstantExpr::getBitCast(Val, NewTy);
2458 }
2459
Chris Lattner79c11012005-09-26 04:44:35 +00002460 MutatedMemory[Ptr] = Val;
2461 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CurInst)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002462 InstResult = ConstantExpr::get(BO->getOpcode(),
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002463 getVal(BO->getOperand(0)),
2464 getVal(BO->getOperand(1)));
Reid Spencere4d87aa2006-12-23 06:05:41 +00002465 } else if (CmpInst *CI = dyn_cast<CmpInst>(CurInst)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002466 InstResult = ConstantExpr::getCompare(CI->getPredicate(),
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002467 getVal(CI->getOperand(0)),
2468 getVal(CI->getOperand(1)));
Chris Lattner79c11012005-09-26 04:44:35 +00002469 } else if (CastInst *CI = dyn_cast<CastInst>(CurInst)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002470 InstResult = ConstantExpr::getCast(CI->getOpcode(),
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002471 getVal(CI->getOperand(0)),
Chris Lattner79c11012005-09-26 04:44:35 +00002472 CI->getType());
2473 } else if (SelectInst *SI = dyn_cast<SelectInst>(CurInst)) {
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002474 InstResult = ConstantExpr::getSelect(getVal(SI->getOperand(0)),
2475 getVal(SI->getOperand(1)),
2476 getVal(SI->getOperand(2)));
Chris Lattner04de1cf2005-09-26 05:15:37 +00002477 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurInst)) {
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002478 Constant *P = getVal(GEP->getOperand(0));
Chris Lattner55eb1c42007-01-31 04:40:53 +00002479 SmallVector<Constant*, 8> GEPOps;
Gabor Greif5e463212008-05-29 01:59:18 +00002480 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end();
2481 i != e; ++i)
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002482 GEPOps.push_back(getVal(*i));
Jay Foad4b5e2072011-07-21 15:15:37 +00002483 InstResult =
2484 ConstantExpr::getGetElementPtr(P, GEPOps,
2485 cast<GEPOperator>(GEP)->isInBounds());
Chris Lattner04de1cf2005-09-26 05:15:37 +00002486 } else if (LoadInst *LI = dyn_cast<LoadInst>(CurInst)) {
Eli Friedman33cb4452011-08-16 00:20:11 +00002487 if (!LI->isSimple()) return false; // no volatile/atomic accesses.
Nick Lewyckya641c072012-02-21 22:08:06 +00002488 Constant *Ptr = getVal(LI->getOperand(0));
2489 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
2490 Ptr = ConstantFoldConstantExpression(CE, TD, TLI);
2491 InstResult = ComputeLoadResult(Ptr);
Chris Lattnercd271422005-09-27 04:45:34 +00002492 if (InstResult == 0) return false; // Could not evaluate load.
Chris Lattnera22fdb02005-09-26 17:07:09 +00002493 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(CurInst)) {
Chris Lattnercd271422005-09-27 04:45:34 +00002494 if (AI->isArrayAllocation()) return false; // Cannot handle array allocs.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002495 Type *Ty = AI->getType()->getElementType();
Chris Lattner7b550cc2009-11-06 04:27:31 +00002496 AllocaTmps.push_back(new GlobalVariable(Ty, false,
Chris Lattnera22fdb02005-09-26 17:07:09 +00002497 GlobalValue::InternalLinkage,
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002498 UndefValue::get(Ty),
Chris Lattnera22fdb02005-09-26 17:07:09 +00002499 AI->getName()));
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002500 InstResult = AllocaTmps.back();
Nick Lewycky132bd9c2012-02-12 05:09:35 +00002501 } else if (isa<CallInst>(CurInst) || isa<InvokeInst>(CurInst)) {
2502 CallSite CS(CurInst);
Devang Patel412a4462009-03-09 23:04:12 +00002503
2504 // Debug info can safely be ignored here.
Nick Lewycky132bd9c2012-02-12 05:09:35 +00002505 if (isa<DbgInfoIntrinsic>(CS.getInstruction())) {
Devang Patel412a4462009-03-09 23:04:12 +00002506 ++CurInst;
2507 continue;
2508 }
2509
Chris Lattner7cd580f2006-07-07 21:37:01 +00002510 // Cannot handle inline asm.
Nick Lewycky132bd9c2012-02-12 05:09:35 +00002511 if (isa<InlineAsm>(CS.getCalledValue())) return false;
Chris Lattner7cd580f2006-07-07 21:37:01 +00002512
Nick Lewycky81266c52012-02-17 06:59:21 +00002513 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CS.getInstruction())) {
2514 if (MemSetInst *MSI = dyn_cast<MemSetInst>(II)) {
2515 if (MSI->isVolatile()) return false;
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002516 Constant *Ptr = getVal(MSI->getDest());
2517 Constant *Val = getVal(MSI->getValue());
2518 Constant *DestVal = ComputeLoadResult(getVal(Ptr));
Nick Lewycky81266c52012-02-17 06:59:21 +00002519 if (Val->isNullValue() && DestVal && DestVal->isNullValue()) {
2520 // This memset is a no-op.
2521 ++CurInst;
2522 continue;
2523 }
2524 }
2525
2526 if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
2527 II->getIntrinsicID() == Intrinsic::lifetime_end) {
2528 ++CurInst;
2529 continue;
2530 }
2531
2532 if (II->getIntrinsicID() == Intrinsic::invariant_start) {
2533 // We don't insert an entry into Values, as it doesn't have a
2534 // meaningful return value.
2535 if (!II->use_empty())
2536 return false;
2537 ConstantInt *Size = cast<ConstantInt>(II->getArgOperand(0));
Nick Lewycky0ef05572012-02-20 23:32:26 +00002538 Value *PtrArg = getVal(II->getArgOperand(1));
2539 Value *Ptr = PtrArg->stripPointerCasts();
2540 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr)) {
2541 Type *ElemTy = cast<PointerType>(GV->getType())->getElementType();
2542 if (!Size->isAllOnesValue() &&
2543 Size->getValue().getLimitedValue() >=
2544 TD->getTypeStoreSize(ElemTy))
Nick Lewycky81266c52012-02-17 06:59:21 +00002545 Invariants.insert(GV);
2546 }
2547 // Continue even if we do nothing.
Nick Lewycky1f237b02011-05-29 18:41:56 +00002548 ++CurInst;
2549 continue;
2550 }
2551 return false;
2552 }
2553
Chris Lattnercd271422005-09-27 04:45:34 +00002554 // Resolve function pointers.
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002555 Function *Callee = dyn_cast<Function>(getVal(CS.getCalledValue()));
Nick Lewycky132bd9c2012-02-12 05:09:35 +00002556 if (!Callee || Callee->mayBeOverridden())
2557 return false; // Cannot resolve.
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002558
Duncan Sandsfa6a1cf2009-08-17 14:33:27 +00002559 SmallVector<Constant*, 8> Formals;
Nick Lewycky132bd9c2012-02-12 05:09:35 +00002560 for (User::op_iterator i = CS.arg_begin(), e = CS.arg_end(); i != e; ++i)
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002561 Formals.push_back(getVal(*i));
Duncan Sandsfa6a1cf2009-08-17 14:33:27 +00002562
Reid Spencer5cbf9852007-01-30 20:08:39 +00002563 if (Callee->isDeclaration()) {
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002564 // If this is a function we can constant fold, do it.
Chad Rosier00737bd2011-12-01 21:29:16 +00002565 if (Constant *C = ConstantFoldCall(Callee, Formals, TLI)) {
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002566 InstResult = C;
2567 } else {
2568 return false;
2569 }
2570 } else {
2571 if (Callee->getFunctionType()->isVarArg())
2572 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002573
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002574 Constant *RetVal;
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002575 // Execute the call, if successful, use the return value.
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002576 ValueStack.push_back(new DenseMap<Value*, Constant*>);
2577 if (!EvaluateFunction(Callee, RetVal, Formals))
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002578 return false;
Benjamin Kramer3bbf2b62012-02-27 12:48:24 +00002579 delete ValueStack.pop_back_val();
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002580 InstResult = RetVal;
2581 }
Reid Spencer3ed469c2006-11-02 20:25:50 +00002582 } else if (isa<TerminatorInst>(CurInst)) {
Chris Lattnercdf98be2005-09-26 04:57:38 +00002583 if (BranchInst *BI = dyn_cast<BranchInst>(CurInst)) {
2584 if (BI->isUnconditional()) {
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002585 NextBB = BI->getSuccessor(0);
Chris Lattnercdf98be2005-09-26 04:57:38 +00002586 } else {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002587 ConstantInt *Cond =
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002588 dyn_cast<ConstantInt>(getVal(BI->getCondition()));
Chris Lattner97d1fad2007-01-12 18:30:11 +00002589 if (!Cond) return false; // Cannot determine.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002590
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002591 NextBB = BI->getSuccessor(!Cond->getZExtValue());
Chris Lattnercdf98be2005-09-26 04:57:38 +00002592 }
2593 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(CurInst)) {
2594 ConstantInt *Val =
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002595 dyn_cast<ConstantInt>(getVal(SI->getCondition()));
Chris Lattnercd271422005-09-27 04:45:34 +00002596 if (!Val) return false; // Cannot determine.
Stepan Dyatkovskiyc10fa6c2012-03-08 07:06:20 +00002597 NextBB = SI->findCaseValue(Val).getCaseSuccessor();
Chris Lattnerb3d5a652009-10-29 05:51:50 +00002598 } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(CurInst)) {
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002599 Value *Val = getVal(IBI->getAddress())->stripPointerCasts();
Chris Lattnerb3d5a652009-10-29 05:51:50 +00002600 if (BlockAddress *BA = dyn_cast<BlockAddress>(Val))
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002601 NextBB = BA->getBasicBlock();
Chris Lattnercdfc9402009-11-01 01:27:45 +00002602 else
2603 return false; // Cannot determine.
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002604 } else if (isa<ReturnInst>(CurInst)) {
2605 NextBB = 0;
Chris Lattnercdf98be2005-09-26 04:57:38 +00002606 } else {
Bill Wendlingdccc03b2011-07-31 06:30:59 +00002607 // invoke, unwind, resume, unreachable.
Chris Lattnercd271422005-09-27 04:45:34 +00002608 return false; // Cannot handle this terminator.
Chris Lattnercdf98be2005-09-26 04:57:38 +00002609 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002610
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002611 // We succeeded at evaluating this block!
2612 return true;
Chris Lattner79c11012005-09-26 04:44:35 +00002613 } else {
Chris Lattner79c11012005-09-26 04:44:35 +00002614 // Did not know how to evaluate this!
Chris Lattnercd271422005-09-27 04:45:34 +00002615 return false;
Chris Lattner79c11012005-09-26 04:44:35 +00002616 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002617
Chris Lattner1945d582010-12-07 04:33:29 +00002618 if (!CurInst->use_empty()) {
2619 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(InstResult))
Chad Rosieraab8e282011-12-02 01:26:24 +00002620 InstResult = ConstantFoldConstantExpression(CE, TD, TLI);
Chris Lattner1945d582010-12-07 04:33:29 +00002621
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002622 setVal(CurInst, InstResult);
Chris Lattner1945d582010-12-07 04:33:29 +00002623 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002624
Dan Gohmanf1ce79f2012-03-13 18:01:37 +00002625 // If we just processed an invoke, we finished evaluating the block.
2626 if (InvokeInst *II = dyn_cast<InvokeInst>(CurInst)) {
2627 NextBB = II->getNormalDest();
2628 return true;
2629 }
2630
Chris Lattner79c11012005-09-26 04:44:35 +00002631 // Advance program counter.
2632 ++CurInst;
2633 }
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002634}
2635
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002636/// EvaluateFunction - Evaluate a call to function F, returning true if
2637/// successful, false if we can't evaluate it. ActualArgs contains the formal
2638/// arguments for the function.
Nick Lewycky7fa76772012-02-20 03:25:59 +00002639bool Evaluator::EvaluateFunction(Function *F, Constant *&RetVal,
2640 const SmallVectorImpl<Constant*> &ActualArgs) {
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002641 // Check to see if this function is already executing (recursion). If so,
2642 // bail out. TODO: we might want to accept limited recursion.
2643 if (std::find(CallStack.begin(), CallStack.end(), F) != CallStack.end())
2644 return false;
2645
2646 CallStack.push_back(F);
2647
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002648 // Initialize arguments to the incoming values specified.
2649 unsigned ArgNo = 0;
2650 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); AI != E;
2651 ++AI, ++ArgNo)
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002652 setVal(AI, ActualArgs[ArgNo]);
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002653
2654 // ExecutedBlocks - We only handle non-looping, non-recursive code. As such,
2655 // we can only evaluate any one basic block at most once. This set keeps
2656 // track of what we have executed so we can detect recursive cases etc.
2657 SmallPtrSet<BasicBlock*, 32> ExecutedBlocks;
2658
2659 // CurBB - The current basic block we're evaluating.
2660 BasicBlock *CurBB = F->begin();
2661
Nick Lewycky8e4ba6b2012-02-12 00:47:24 +00002662 BasicBlock::iterator CurInst = CurBB->begin();
2663
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002664 while (1) {
Duncan Sands4b794f82012-02-23 08:23:06 +00002665 BasicBlock *NextBB = 0; // Initialized to avoid compiler warnings.
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002666 if (!EvaluateBlock(CurInst, NextBB))
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002667 return false;
2668
2669 if (NextBB == 0) {
2670 // Successfully running until there's no next block means that we found
2671 // the return. Fill it the return value and pop the call stack.
2672 ReturnInst *RI = cast<ReturnInst>(CurBB->getTerminator());
2673 if (RI->getNumOperands())
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002674 RetVal = getVal(RI->getOperand(0));
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002675 CallStack.pop_back();
2676 return true;
2677 }
2678
2679 // Okay, we succeeded in evaluating this control flow. See if we have
2680 // executed the new block before. If so, we have a looping function,
2681 // which we cannot evaluate in reasonable time.
2682 if (!ExecutedBlocks.insert(NextBB))
2683 return false; // looped!
2684
2685 // Okay, we have never been in this block before. Check to see if there
2686 // are any PHI nodes. If so, evaluate them with information about where
2687 // we came from.
2688 PHINode *PN = 0;
Nick Lewycky8e4ba6b2012-02-12 00:47:24 +00002689 for (CurInst = NextBB->begin();
2690 (PN = dyn_cast<PHINode>(CurInst)); ++CurInst)
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002691 setVal(PN, getVal(PN->getIncomingValueForBlock(CurBB)));
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002692
2693 // Advance to the next block.
2694 CurBB = NextBB;
2695 }
2696}
2697
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002698/// EvaluateStaticConstructor - Evaluate static constructors in the function, if
2699/// we can. Return true if we can, false otherwise.
Chad Rosier00737bd2011-12-01 21:29:16 +00002700static bool EvaluateStaticConstructor(Function *F, const TargetData *TD,
2701 const TargetLibraryInfo *TLI) {
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002702 // Call the function.
Nick Lewycky7fa76772012-02-20 03:25:59 +00002703 Evaluator Eval(TD, TLI);
Chris Lattnercd271422005-09-27 04:45:34 +00002704 Constant *RetValDummy;
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002705 bool EvalSuccess = Eval.EvaluateFunction(F, RetValDummy,
2706 SmallVector<Constant*, 0>());
Chris Lattner1945d582010-12-07 04:33:29 +00002707
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002708 if (EvalSuccess) {
Chris Lattnera22fdb02005-09-26 17:07:09 +00002709 // We succeeded at evaluation: commit the result.
David Greene3215b0e2010-01-05 01:28:05 +00002710 DEBUG(dbgs() << "FULLY EVALUATED GLOBAL CTOR FUNCTION '"
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002711 << F->getName() << "' to " << Eval.getMutatedMemory().size()
Daniel Dunbarce63ffb2009-07-25 00:23:56 +00002712 << " stores.\n");
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002713 for (DenseMap<Constant*, Constant*>::const_iterator I =
2714 Eval.getMutatedMemory().begin(), E = Eval.getMutatedMemory().end();
Nick Lewycky3eab3c42012-06-24 04:07:14 +00002715 I != E; ++I)
Chris Lattner7b550cc2009-11-06 04:27:31 +00002716 CommitValueTo(I->second, I->first);
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002717 for (SmallPtrSet<GlobalVariable*, 8>::const_iterator I =
2718 Eval.getInvariants().begin(), E = Eval.getInvariants().end();
2719 I != E; ++I)
Nick Lewycky81266c52012-02-17 06:59:21 +00002720 (*I)->setConstant(true);
Chris Lattnera22fdb02005-09-26 17:07:09 +00002721 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002722
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002723 return EvalSuccess;
Chris Lattner79c11012005-09-26 04:44:35 +00002724}
2725
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002726/// OptimizeGlobalCtorsList - Simplify and evaluation global ctors if possible.
2727/// Return true if anything changed.
2728bool GlobalOpt::OptimizeGlobalCtorsList(GlobalVariable *&GCL) {
2729 std::vector<Function*> Ctors = ParseGlobalCtors(GCL);
2730 bool MadeChange = false;
2731 if (Ctors.empty()) return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002732
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002733 // Loop over global ctors, optimizing them when we can.
2734 for (unsigned i = 0; i != Ctors.size(); ++i) {
2735 Function *F = Ctors[i];
2736 // Found a null terminator in the middle of the list, prune off the rest of
2737 // the list.
Chris Lattner7d8e58f2005-09-26 02:19:27 +00002738 if (F == 0) {
2739 if (i != Ctors.size()-1) {
2740 Ctors.resize(i+1);
2741 MadeChange = true;
2742 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002743 break;
2744 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002745
Chris Lattner79c11012005-09-26 04:44:35 +00002746 // We cannot simplify external ctor functions.
2747 if (F->empty()) continue;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002748
Chris Lattner79c11012005-09-26 04:44:35 +00002749 // If we can evaluate the ctor at compile time, do.
Chad Rosier00737bd2011-12-01 21:29:16 +00002750 if (EvaluateStaticConstructor(F, TD, TLI)) {
Chris Lattner79c11012005-09-26 04:44:35 +00002751 Ctors.erase(Ctors.begin()+i);
2752 MadeChange = true;
2753 --i;
2754 ++NumCtorsEvaluated;
2755 continue;
2756 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002757 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002758
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002759 if (!MadeChange) return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002760
Chris Lattner7b550cc2009-11-06 04:27:31 +00002761 GCL = InstallGlobalCtors(GCL, Ctors);
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002762 return true;
2763}
2764
Duncan Sandsfc5940d2009-03-06 10:21:56 +00002765bool GlobalOpt::OptimizeGlobalAliases(Module &M) {
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002766 bool Changed = false;
2767
Duncan Sands177d84e2009-01-07 20:01:06 +00002768 for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end();
Duncan Sands4782b302009-02-15 09:56:08 +00002769 I != E;) {
2770 Module::alias_iterator J = I++;
Duncan Sandsfc5940d2009-03-06 10:21:56 +00002771 // Aliases without names cannot be referenced outside this module.
2772 if (!J->hasName() && !J->isDeclaration())
2773 J->setLinkage(GlobalValue::InternalLinkage);
Duncan Sands4782b302009-02-15 09:56:08 +00002774 // If the aliasee may change at link time, nothing can be done - bail out.
2775 if (J->mayBeOverridden())
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002776 continue;
2777
Duncan Sands4782b302009-02-15 09:56:08 +00002778 Constant *Aliasee = J->getAliasee();
2779 GlobalValue *Target = cast<GlobalValue>(Aliasee->stripPointerCasts());
Duncan Sands95c5d0f2009-02-18 17:55:38 +00002780 Target->removeDeadConstantUsers();
Duncan Sands4782b302009-02-15 09:56:08 +00002781 bool hasOneUse = Target->hasOneUse() && Aliasee->hasOneUse();
2782
2783 // Make all users of the alias use the aliasee instead.
2784 if (!J->use_empty()) {
2785 J->replaceAllUsesWith(Aliasee);
2786 ++NumAliasesResolved;
2787 Changed = true;
2788 }
2789
Duncan Sands7a154cf2009-12-08 10:10:20 +00002790 // If the alias is externally visible, we may still be able to simplify it.
2791 if (!J->hasLocalLinkage()) {
2792 // If the aliasee has internal linkage, give it the name and linkage
2793 // of the alias, and delete the alias. This turns:
2794 // define internal ... @f(...)
2795 // @a = alias ... @f
2796 // into:
2797 // define ... @a(...)
2798 if (!Target->hasLocalLinkage())
2799 continue;
Duncan Sands4782b302009-02-15 09:56:08 +00002800
Duncan Sands7a154cf2009-12-08 10:10:20 +00002801 // Do not perform the transform if multiple aliases potentially target the
Gabor Greif27236912010-04-07 18:59:26 +00002802 // aliasee. This check also ensures that it is safe to replace the section
Duncan Sands7a154cf2009-12-08 10:10:20 +00002803 // and other attributes of the aliasee with those of the alias.
2804 if (!hasOneUse)
2805 continue;
Duncan Sands4782b302009-02-15 09:56:08 +00002806
Duncan Sands7a154cf2009-12-08 10:10:20 +00002807 // Give the aliasee the name, linkage and other attributes of the alias.
2808 Target->takeName(J);
2809 Target->setLinkage(J->getLinkage());
2810 Target->GlobalValue::copyAttributesFrom(J);
2811 }
Duncan Sands4782b302009-02-15 09:56:08 +00002812
2813 // Delete the alias.
2814 M.getAliasList().erase(J);
2815 ++NumAliasesRemoved;
2816 Changed = true;
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002817 }
2818
2819 return Changed;
2820}
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002821
Nick Lewycky6a7df9a2012-02-12 02:15:20 +00002822static Function *FindCXAAtExit(Module &M, TargetLibraryInfo *TLI) {
2823 if (!TLI->has(LibFunc::cxa_atexit))
Nick Lewycky6f160d32012-02-12 02:17:18 +00002824 return 0;
Nick Lewycky6a7df9a2012-02-12 02:15:20 +00002825
2826 Function *Fn = M.getFunction(TLI->getName(LibFunc::cxa_atexit));
Anders Carlssona201c4c2011-03-20 17:59:11 +00002827
2828 if (!Fn)
2829 return 0;
Nick Lewycky6a7df9a2012-02-12 02:15:20 +00002830
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002831 FunctionType *FTy = Fn->getFunctionType();
Anders Carlssona201c4c2011-03-20 17:59:11 +00002832
Anders Carlsson1f7c7ba2011-03-20 19:51:13 +00002833 // Checking that the function has the right return type, the right number of
2834 // parameters and that they all have pointer types should be enough.
2835 if (!FTy->getReturnType()->isIntegerTy() ||
2836 FTy->getNumParams() != 3 ||
Anders Carlssona201c4c2011-03-20 17:59:11 +00002837 !FTy->getParamType(0)->isPointerTy() ||
2838 !FTy->getParamType(1)->isPointerTy() ||
2839 !FTy->getParamType(2)->isPointerTy())
2840 return 0;
2841
2842 return Fn;
2843}
2844
2845/// cxxDtorIsEmpty - Returns whether the given function is an empty C++
2846/// destructor and can therefore be eliminated.
2847/// Note that we assume that other optimization passes have already simplified
2848/// the code so we only look for a function with a single basic block, where
Benjamin Kramerc1322a12012-02-09 16:28:15 +00002849/// the only allowed instructions are 'ret', 'call' to an empty C++ dtor and
2850/// other side-effect free instructions.
Anders Carlsson372ec6a2011-03-20 20:16:43 +00002851static bool cxxDtorIsEmpty(const Function &Fn,
2852 SmallPtrSet<const Function *, 8> &CalledFunctions) {
Anders Carlsson1f7c7ba2011-03-20 19:51:13 +00002853 // FIXME: We could eliminate C++ destructors if they're readonly/readnone and
Nick Lewycky35ee1c92011-03-21 02:26:01 +00002854 // nounwind, but that doesn't seem worth doing.
Anders Carlsson1f7c7ba2011-03-20 19:51:13 +00002855 if (Fn.isDeclaration())
2856 return false;
Anders Carlssona201c4c2011-03-20 17:59:11 +00002857
2858 if (++Fn.begin() != Fn.end())
2859 return false;
2860
2861 const BasicBlock &EntryBlock = Fn.getEntryBlock();
2862 for (BasicBlock::const_iterator I = EntryBlock.begin(), E = EntryBlock.end();
2863 I != E; ++I) {
2864 if (const CallInst *CI = dyn_cast<CallInst>(I)) {
Anders Carlssonb12caf32011-03-21 14:54:40 +00002865 // Ignore debug intrinsics.
2866 if (isa<DbgInfoIntrinsic>(CI))
2867 continue;
2868
Anders Carlssona201c4c2011-03-20 17:59:11 +00002869 const Function *CalledFn = CI->getCalledFunction();
2870
2871 if (!CalledFn)
2872 return false;
2873
Anders Carlsson807bc2a2011-03-22 03:21:01 +00002874 SmallPtrSet<const Function *, 8> NewCalledFunctions(CalledFunctions);
2875
Anders Carlsson1f7c7ba2011-03-20 19:51:13 +00002876 // Don't treat recursive functions as empty.
Anders Carlsson807bc2a2011-03-22 03:21:01 +00002877 if (!NewCalledFunctions.insert(CalledFn))
Anders Carlsson1f7c7ba2011-03-20 19:51:13 +00002878 return false;
2879
Anders Carlsson807bc2a2011-03-22 03:21:01 +00002880 if (!cxxDtorIsEmpty(*CalledFn, NewCalledFunctions))
Anders Carlssona201c4c2011-03-20 17:59:11 +00002881 return false;
2882 } else if (isa<ReturnInst>(*I))
Benjamin Kramerd4692742012-02-09 14:26:06 +00002883 return true; // We're done.
2884 else if (I->mayHaveSideEffects())
2885 return false; // Destructor with side effects, bail.
Anders Carlssona201c4c2011-03-20 17:59:11 +00002886 }
2887
2888 return false;
2889}
2890
2891bool GlobalOpt::OptimizeEmptyGlobalCXXDtors(Function *CXAAtExitFn) {
2892 /// Itanium C++ ABI p3.3.5:
2893 ///
2894 /// After constructing a global (or local static) object, that will require
2895 /// destruction on exit, a termination function is registered as follows:
2896 ///
2897 /// extern "C" int __cxa_atexit ( void (*f)(void *), void *p, void *d );
2898 ///
2899 /// This registration, e.g. __cxa_atexit(f,p,d), is intended to cause the
2900 /// call f(p) when DSO d is unloaded, before all such termination calls
2901 /// registered before this one. It returns zero if registration is
Nick Lewycky35ee1c92011-03-21 02:26:01 +00002902 /// successful, nonzero on failure.
Anders Carlssona201c4c2011-03-20 17:59:11 +00002903
2904 // This pass will look for calls to __cxa_atexit where the function is trivial
2905 // and remove them.
2906 bool Changed = false;
2907
2908 for (Function::use_iterator I = CXAAtExitFn->use_begin(),
2909 E = CXAAtExitFn->use_end(); I != E;) {
Anders Carlsson4f735ca2011-03-20 20:21:33 +00002910 // We're only interested in calls. Theoretically, we could handle invoke
2911 // instructions as well, but neither llvm-gcc nor clang generate invokes
2912 // to __cxa_atexit.
Anders Carlssonb12caf32011-03-21 14:54:40 +00002913 CallInst *CI = dyn_cast<CallInst>(*I++);
2914 if (!CI)
Anders Carlsson4f735ca2011-03-20 20:21:33 +00002915 continue;
2916
Anders Carlssona201c4c2011-03-20 17:59:11 +00002917 Function *DtorFn =
Anders Carlssonb12caf32011-03-21 14:54:40 +00002918 dyn_cast<Function>(CI->getArgOperand(0)->stripPointerCasts());
Anders Carlssona201c4c2011-03-20 17:59:11 +00002919 if (!DtorFn)
2920 continue;
2921
Anders Carlsson372ec6a2011-03-20 20:16:43 +00002922 SmallPtrSet<const Function *, 8> CalledFunctions;
2923 if (!cxxDtorIsEmpty(*DtorFn, CalledFunctions))
Anders Carlssona201c4c2011-03-20 17:59:11 +00002924 continue;
2925
2926 // Just remove the call.
Anders Carlssonb12caf32011-03-21 14:54:40 +00002927 CI->replaceAllUsesWith(Constant::getNullValue(CI->getType()));
2928 CI->eraseFromParent();
Anders Carlsson1f7c7ba2011-03-20 19:51:13 +00002929
Anders Carlssona201c4c2011-03-20 17:59:11 +00002930 ++NumCXXDtorsRemoved;
2931
2932 Changed |= true;
2933 }
2934
2935 return Changed;
2936}
2937
Chris Lattner7a90b682004-10-07 04:16:33 +00002938bool GlobalOpt::runOnModule(Module &M) {
Chris Lattner079236d2004-02-25 21:34:36 +00002939 bool Changed = false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002940
Nick Lewycky6a577f82012-02-12 01:13:18 +00002941 TD = getAnalysisIfAvailable<TargetData>();
Nick Lewycky6a7df9a2012-02-12 02:15:20 +00002942 TLI = &getAnalysis<TargetLibraryInfo>();
Nick Lewycky6a577f82012-02-12 01:13:18 +00002943
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002944 // Try to find the llvm.globalctors list.
2945 GlobalVariable *GlobalCtors = FindGlobalCtors(M);
Chris Lattner7a90b682004-10-07 04:16:33 +00002946
Nick Lewycky6a7df9a2012-02-12 02:15:20 +00002947 Function *CXAAtExitFn = FindCXAAtExit(M, TLI);
Anders Carlssona201c4c2011-03-20 17:59:11 +00002948
Chris Lattner7a90b682004-10-07 04:16:33 +00002949 bool LocalChange = true;
2950 while (LocalChange) {
2951 LocalChange = false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002952
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002953 // Delete functions that are trivially dead, ccc -> fastcc
2954 LocalChange |= OptimizeFunctions(M);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002955
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002956 // Optimize global_ctors list.
2957 if (GlobalCtors)
2958 LocalChange |= OptimizeGlobalCtorsList(GlobalCtors);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002959
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002960 // Optimize non-address-taken globals.
2961 LocalChange |= OptimizeGlobalVars(M);
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002962
2963 // Resolve aliases, when possible.
Duncan Sandsfc5940d2009-03-06 10:21:56 +00002964 LocalChange |= OptimizeGlobalAliases(M);
Anders Carlssona201c4c2011-03-20 17:59:11 +00002965
2966 // Try to remove trivial global destructors.
2967 if (CXAAtExitFn)
2968 LocalChange |= OptimizeEmptyGlobalCXXDtors(CXAAtExitFn);
2969
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002970 Changed |= LocalChange;
Chris Lattner7a90b682004-10-07 04:16:33 +00002971 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002972
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002973 // TODO: Move all global ctors functions to the end of the module for code
2974 // layout.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002975
Chris Lattner079236d2004-02-25 21:34:36 +00002976 return Changed;
2977}