blob: 35f98b226536f1886fb8e749c3526627f8ef4948 [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 }
Chris Lattner35c81b02005-02-27 18:58:52 +0000257 } else if (isa<GetElementPtrInst>(I)) {
Chris Lattner7a90b682004-10-07 04:16:33 +0000258 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Chris Lattner35c81b02005-02-27 18:58:52 +0000259 } else if (isa<SelectInst>(I)) {
Chris Lattner7a90b682004-10-07 04:16:33 +0000260 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000261 } else if (const PHINode *PN = dyn_cast<PHINode>(I)) {
Chris Lattner7a90b682004-10-07 04:16:33 +0000262 // PHI nodes we can check just like select or GEP instructions, but we
263 // have to be careful about infinite recursion.
Chris Lattner5a6bb6a2008-12-16 07:34:30 +0000264 if (PHIUsers.insert(PN)) // Not already visited.
Chris Lattner7a90b682004-10-07 04:16:33 +0000265 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Chris Lattner25de4e52006-11-01 18:03:33 +0000266 GS.HasPHIUser = true;
Reid Spencere4d87aa2006-12-23 06:05:41 +0000267 } else if (isa<CmpInst>(I)) {
Rafael Espindolac4440e32011-01-19 16:32:21 +0000268 GS.isCompared = true;
Nick Lewycky1f237b02011-05-29 18:41:56 +0000269 } else if (const MemTransferInst *MTI = dyn_cast<MemTransferInst>(I)) {
270 if (MTI->isVolatile()) return true;
Gabor Greif9e4f2432010-06-24 14:42:01 +0000271 if (MTI->getArgOperand(0) == V)
Eric Christopher551754c2010-04-16 23:37:20 +0000272 GS.StoredType = GlobalStatus::isStored;
Gabor Greif9e4f2432010-06-24 14:42:01 +0000273 if (MTI->getArgOperand(1) == V)
Chris Lattner35c81b02005-02-27 18:58:52 +0000274 GS.isLoaded = true;
Nick Lewycky1f237b02011-05-29 18:41:56 +0000275 } else if (const MemSetInst *MSI = dyn_cast<MemSetInst>(I)) {
276 assert(MSI->getArgOperand(0) == V && "Memset only takes one pointer!");
277 if (MSI->isVolatile()) return true;
Chris Lattner35c81b02005-02-27 18:58:52 +0000278 GS.StoredType = GlobalStatus::isStored;
Chris Lattner7a90b682004-10-07 04:16:33 +0000279 } else {
280 return true; // Any other non-load instruction might take address!
Chris Lattner9ce30002004-07-20 03:58:07 +0000281 }
Gabor Greife6642672010-07-09 16:51:20 +0000282 } else if (const Constant *C = dyn_cast<Constant>(U)) {
Chris Lattner553ca522005-06-15 21:11:48 +0000283 GS.HasNonInstructionUser = true;
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000284 // We might have a dead and dangling constant hanging off of here.
Jay Foade3acf152009-06-09 21:37:11 +0000285 if (!SafeToDestroyConstant(C))
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000286 return true;
Chris Lattner079236d2004-02-25 21:34:36 +0000287 } else {
Chris Lattner553ca522005-06-15 21:11:48 +0000288 GS.HasNonInstructionUser = true;
289 // Otherwise must be some other user.
Chris Lattner079236d2004-02-25 21:34:36 +0000290 return true;
291 }
Gabor Greife6642672010-07-09 16:51:20 +0000292 }
Chris Lattner079236d2004-02-25 21:34:36 +0000293
294 return false;
295}
296
Chris Lattnere47ba742004-10-06 20:57:02 +0000297/// CleanupConstantGlobalUsers - We just marked GV constant. Loop over all
298/// users of the global, cleaning up the obvious ones. This is largely just a
Chris Lattner031955d2004-10-10 16:43:46 +0000299/// quick scan over the use list to clean up the easy and obvious cruft. This
300/// returns true if it made a change.
Nick Lewycky6a577f82012-02-12 01:13:18 +0000301static bool CleanupConstantGlobalUsers(Value *V, Constant *Init,
302 TargetData *TD, TargetLibraryInfo *TLI) {
Chris Lattner031955d2004-10-10 16:43:46 +0000303 bool Changed = false;
Chris Lattner7a90b682004-10-07 04:16:33 +0000304 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;) {
305 User *U = *UI++;
Misha Brukmanfd939082005-04-21 23:48:37 +0000306
Chris Lattner7a90b682004-10-07 04:16:33 +0000307 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
Chris Lattner35c81b02005-02-27 18:58:52 +0000308 if (Init) {
309 // Replace the load with the initializer.
310 LI->replaceAllUsesWith(Init);
311 LI->eraseFromParent();
312 Changed = true;
313 }
Chris Lattner7a90b682004-10-07 04:16:33 +0000314 } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
Chris Lattnere47ba742004-10-06 20:57:02 +0000315 // Store must be unreachable or storing Init into the global.
Chris Lattner7a7ed022004-10-16 18:09:00 +0000316 SI->eraseFromParent();
Chris Lattner031955d2004-10-10 16:43:46 +0000317 Changed = true;
Chris Lattner7a90b682004-10-07 04:16:33 +0000318 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
319 if (CE->getOpcode() == Instruction::GetElementPtr) {
Chris Lattneraae4a1c2005-09-26 07:34:35 +0000320 Constant *SubInit = 0;
321 if (Init)
Dan Gohmanc6f69e92009-10-05 16:36:26 +0000322 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
Nick Lewycky6a577f82012-02-12 01:13:18 +0000323 Changed |= CleanupConstantGlobalUsers(CE, SubInit, TD, TLI);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000324 } else if (CE->getOpcode() == Instruction::BitCast &&
Duncan Sands1df98592010-02-16 11:11:14 +0000325 CE->getType()->isPointerTy()) {
Chris Lattner35c81b02005-02-27 18:58:52 +0000326 // Pointer cast, delete any stores and memsets to the global.
Nick Lewycky6a577f82012-02-12 01:13:18 +0000327 Changed |= CleanupConstantGlobalUsers(CE, 0, TD, TLI);
Chris Lattner35c81b02005-02-27 18:58:52 +0000328 }
329
330 if (CE->use_empty()) {
331 CE->destroyConstant();
332 Changed = true;
Chris Lattner7a90b682004-10-07 04:16:33 +0000333 }
334 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
Chris Lattner7b52fe72007-11-09 17:33:02 +0000335 // Do not transform "gepinst (gep constexpr (GV))" here, because forming
336 // "gepconstexpr (gep constexpr (GV))" will cause the two gep's to fold
337 // and will invalidate our notion of what Init is.
Chris Lattner19450242007-11-13 21:46:23 +0000338 Constant *SubInit = 0;
Chris Lattner7b52fe72007-11-09 17:33:02 +0000339 if (!isa<ConstantExpr>(GEP->getOperand(0))) {
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000340 ConstantExpr *CE =
Nick Lewycky6a577f82012-02-12 01:13:18 +0000341 dyn_cast_or_null<ConstantExpr>(ConstantFoldInstruction(GEP, TD, TLI));
Chris Lattner7b52fe72007-11-09 17:33:02 +0000342 if (Init && CE && CE->getOpcode() == Instruction::GetElementPtr)
Dan Gohmanc6f69e92009-10-05 16:36:26 +0000343 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
Benjamin Kramerc1ea16e2012-03-28 14:50:09 +0000344
345 // If the initializer is an all-null value and we have an inbounds GEP,
346 // we already know what the result of any load from that GEP is.
347 // TODO: Handle splats.
348 if (Init && isa<ConstantAggregateZero>(Init) && GEP->isInBounds())
349 SubInit = Constant::getNullValue(GEP->getType()->getElementType());
Chris Lattner7b52fe72007-11-09 17:33:02 +0000350 }
Nick Lewycky6a577f82012-02-12 01:13:18 +0000351 Changed |= CleanupConstantGlobalUsers(GEP, SubInit, TD, TLI);
Chris Lattnerc4d81b02004-10-10 16:47:33 +0000352
Chris Lattner031955d2004-10-10 16:43:46 +0000353 if (GEP->use_empty()) {
Chris Lattner7a7ed022004-10-16 18:09:00 +0000354 GEP->eraseFromParent();
Chris Lattner031955d2004-10-10 16:43:46 +0000355 Changed = true;
356 }
Chris Lattner35c81b02005-02-27 18:58:52 +0000357 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U)) { // memset/cpy/mv
358 if (MI->getRawDest() == V) {
359 MI->eraseFromParent();
360 Changed = true;
361 }
362
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000363 } else if (Constant *C = dyn_cast<Constant>(U)) {
364 // If we have a chain of dead constantexprs or other things dangling from
365 // us, and if they are all dead, nuke them without remorse.
Jay Foade3acf152009-06-09 21:37:11 +0000366 if (SafeToDestroyConstant(C)) {
Devang Patel743cdf82009-03-06 01:37:41 +0000367 C->destroyConstant();
Chris Lattner35c81b02005-02-27 18:58:52 +0000368 // This could have invalidated UI, start over from scratch.
Nick Lewycky6a577f82012-02-12 01:13:18 +0000369 CleanupConstantGlobalUsers(V, Init, TD, TLI);
Chris Lattner031955d2004-10-10 16:43:46 +0000370 return true;
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000371 }
Chris Lattnere47ba742004-10-06 20:57:02 +0000372 }
373 }
Chris Lattner031955d2004-10-10 16:43:46 +0000374 return Changed;
Chris Lattnere47ba742004-10-06 20:57:02 +0000375}
376
Chris Lattner941db492008-01-14 02:09:12 +0000377/// isSafeSROAElementUse - Return true if the specified instruction is a safe
378/// user of a derived expression from a global that we want to SROA.
379static bool isSafeSROAElementUse(Value *V) {
380 // We might have a dead and dangling constant hanging off of here.
381 if (Constant *C = dyn_cast<Constant>(V))
Jay Foade3acf152009-06-09 21:37:11 +0000382 return SafeToDestroyConstant(C);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000383
Chris Lattner941db492008-01-14 02:09:12 +0000384 Instruction *I = dyn_cast<Instruction>(V);
385 if (!I) return false;
386
387 // Loads are ok.
388 if (isa<LoadInst>(I)) return true;
389
390 // Stores *to* the pointer are ok.
391 if (StoreInst *SI = dyn_cast<StoreInst>(I))
392 return SI->getOperand(0) != V;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000393
Chris Lattner941db492008-01-14 02:09:12 +0000394 // Otherwise, it must be a GEP.
395 GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I);
396 if (GEPI == 0) return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000397
Chris Lattner941db492008-01-14 02:09:12 +0000398 if (GEPI->getNumOperands() < 3 || !isa<Constant>(GEPI->getOperand(1)) ||
399 !cast<Constant>(GEPI->getOperand(1))->isNullValue())
400 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000401
Chris Lattner941db492008-01-14 02:09:12 +0000402 for (Value::use_iterator I = GEPI->use_begin(), E = GEPI->use_end();
403 I != E; ++I)
404 if (!isSafeSROAElementUse(*I))
405 return false;
Chris Lattner727c2102008-01-14 01:31:05 +0000406 return true;
407}
408
Chris Lattner941db492008-01-14 02:09:12 +0000409
410/// IsUserOfGlobalSafeForSRA - U is a direct user of the specified global value.
411/// Look at it and its uses and decide whether it is safe to SROA this global.
412///
413static bool IsUserOfGlobalSafeForSRA(User *U, GlobalValue *GV) {
414 // The user of the global must be a GEP Inst or a ConstantExpr GEP.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000415 if (!isa<GetElementPtrInst>(U) &&
416 (!isa<ConstantExpr>(U) ||
Chris Lattner941db492008-01-14 02:09:12 +0000417 cast<ConstantExpr>(U)->getOpcode() != Instruction::GetElementPtr))
418 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000419
Chris Lattner941db492008-01-14 02:09:12 +0000420 // Check to see if this ConstantExpr GEP is SRA'able. In particular, we
421 // don't like < 3 operand CE's, and we don't like non-constant integer
422 // indices. This enforces that all uses are 'gep GV, 0, C, ...' for some
423 // value of C.
424 if (U->getNumOperands() < 3 || !isa<Constant>(U->getOperand(1)) ||
425 !cast<Constant>(U->getOperand(1))->isNullValue() ||
426 !isa<ConstantInt>(U->getOperand(2)))
427 return false;
428
429 gep_type_iterator GEPI = gep_type_begin(U), E = gep_type_end(U);
430 ++GEPI; // Skip over the pointer index.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000431
Chris Lattner941db492008-01-14 02:09:12 +0000432 // If this is a use of an array allocation, do a bit more checking for sanity.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000433 if (ArrayType *AT = dyn_cast<ArrayType>(*GEPI)) {
Chris Lattner941db492008-01-14 02:09:12 +0000434 uint64_t NumElements = AT->getNumElements();
435 ConstantInt *Idx = cast<ConstantInt>(U->getOperand(2));
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000436
Chris Lattner941db492008-01-14 02:09:12 +0000437 // Check to make sure that index falls within the array. If not,
438 // something funny is going on, so we won't do the optimization.
439 //
440 if (Idx->getZExtValue() >= NumElements)
441 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000442
Chris Lattner941db492008-01-14 02:09:12 +0000443 // We cannot scalar repl this level of the array unless any array
444 // sub-indices are in-range constants. In particular, consider:
445 // A[0][i]. We cannot know that the user isn't doing invalid things like
446 // allowing i to index an out-of-range subscript that accesses A[1].
447 //
448 // Scalar replacing *just* the outer index of the array is probably not
449 // going to be a win anyway, so just give up.
450 for (++GEPI; // Skip array index.
Dan Gohman6874a2a2009-08-18 14:58:19 +0000451 GEPI != E;
Chris Lattner941db492008-01-14 02:09:12 +0000452 ++GEPI) {
453 uint64_t NumElements;
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000454 if (ArrayType *SubArrayTy = dyn_cast<ArrayType>(*GEPI))
Chris Lattner941db492008-01-14 02:09:12 +0000455 NumElements = SubArrayTy->getNumElements();
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000456 else if (VectorType *SubVectorTy = dyn_cast<VectorType>(*GEPI))
Dan Gohman6874a2a2009-08-18 14:58:19 +0000457 NumElements = SubVectorTy->getNumElements();
458 else {
Duncan Sands1df98592010-02-16 11:11:14 +0000459 assert((*GEPI)->isStructTy() &&
Dan Gohman6874a2a2009-08-18 14:58:19 +0000460 "Indexed GEP type is not array, vector, or struct!");
461 continue;
462 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000463
Chris Lattner941db492008-01-14 02:09:12 +0000464 ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPI.getOperand());
465 if (!IdxVal || IdxVal->getZExtValue() >= NumElements)
466 return false;
467 }
468 }
469
470 for (Value::use_iterator I = U->use_begin(), E = U->use_end(); I != E; ++I)
471 if (!isSafeSROAElementUse(*I))
472 return false;
473 return true;
474}
475
476/// GlobalUsersSafeToSRA - Look at all uses of the global and decide whether it
477/// is safe for us to perform this transformation.
478///
479static bool GlobalUsersSafeToSRA(GlobalValue *GV) {
480 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end();
481 UI != E; ++UI) {
482 if (!IsUserOfGlobalSafeForSRA(*UI, GV))
483 return false;
484 }
485 return true;
486}
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000487
Chris Lattner941db492008-01-14 02:09:12 +0000488
Chris Lattner670c8892004-10-08 17:32:09 +0000489/// SRAGlobal - Perform scalar replacement of aggregates on the specified global
490/// variable. This opens the door for other optimizations by exposing the
491/// behavior of the program in a more fine-grained way. We have determined that
492/// this transformation is safe already. We return the first global variable we
493/// insert so that the caller can reprocess it.
Chris Lattner7b550cc2009-11-06 04:27:31 +0000494static GlobalVariable *SRAGlobal(GlobalVariable *GV, const TargetData &TD) {
Chris Lattner727c2102008-01-14 01:31:05 +0000495 // Make sure this global only has simple uses that we can SRA.
Chris Lattner941db492008-01-14 02:09:12 +0000496 if (!GlobalUsersSafeToSRA(GV))
Chris Lattner727c2102008-01-14 01:31:05 +0000497 return 0;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000498
Rafael Espindolabb46f522009-01-15 20:18:42 +0000499 assert(GV->hasLocalLinkage() && !GV->isConstant());
Chris Lattner670c8892004-10-08 17:32:09 +0000500 Constant *Init = GV->getInitializer();
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000501 Type *Ty = Init->getType();
Misha Brukmanfd939082005-04-21 23:48:37 +0000502
Chris Lattner670c8892004-10-08 17:32:09 +0000503 std::vector<GlobalVariable*> NewGlobals;
504 Module::GlobalListType &Globals = GV->getParent()->getGlobalList();
505
Chris Lattner998182b2008-04-26 07:40:11 +0000506 // Get the alignment of the global, either explicit or target-specific.
507 unsigned StartAlignment = GV->getAlignment();
508 if (StartAlignment == 0)
509 StartAlignment = TD.getABITypeAlignment(GV->getType());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000510
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000511 if (StructType *STy = dyn_cast<StructType>(Ty)) {
Chris Lattner670c8892004-10-08 17:32:09 +0000512 NewGlobals.reserve(STy->getNumElements());
Chris Lattner998182b2008-04-26 07:40:11 +0000513 const StructLayout &Layout = *TD.getStructLayout(STy);
Chris Lattner670c8892004-10-08 17:32:09 +0000514 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
Chris Lattnera1f00f42012-01-25 06:48:06 +0000515 Constant *In = Init->getAggregateElement(i);
Chris Lattner670c8892004-10-08 17:32:09 +0000516 assert(In && "Couldn't get element of initializer?");
Chris Lattner7b550cc2009-11-06 04:27:31 +0000517 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(i), false,
Chris Lattner670c8892004-10-08 17:32:09 +0000518 GlobalVariable::InternalLinkage,
Daniel Dunbarfe09b202009-07-30 17:37:43 +0000519 In, GV->getName()+"."+Twine(i),
Hans Wennborgce718ff2012-06-23 11:37:03 +0000520 GV->getThreadLocalMode(),
Owen Anderson3d29df32009-07-08 01:26:06 +0000521 GV->getType()->getAddressSpace());
Chris Lattner670c8892004-10-08 17:32:09 +0000522 Globals.insert(GV, NGV);
523 NewGlobals.push_back(NGV);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000524
Chris Lattner998182b2008-04-26 07:40:11 +0000525 // Calculate the known alignment of the field. If the original aggregate
526 // had 256 byte alignment for example, something might depend on that:
527 // propagate info to each field.
528 uint64_t FieldOffset = Layout.getElementOffset(i);
529 unsigned NewAlign = (unsigned)MinAlign(StartAlignment, FieldOffset);
530 if (NewAlign > TD.getABITypeAlignment(STy->getElementType(i)))
531 NGV->setAlignment(NewAlign);
Chris Lattner670c8892004-10-08 17:32:09 +0000532 }
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000533 } else if (SequentialType *STy = dyn_cast<SequentialType>(Ty)) {
Chris Lattner670c8892004-10-08 17:32:09 +0000534 unsigned NumElements = 0;
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000535 if (ArrayType *ATy = dyn_cast<ArrayType>(STy))
Chris Lattner670c8892004-10-08 17:32:09 +0000536 NumElements = ATy->getNumElements();
Chris Lattner670c8892004-10-08 17:32:09 +0000537 else
Chris Lattner998182b2008-04-26 07:40:11 +0000538 NumElements = cast<VectorType>(STy)->getNumElements();
Chris Lattner670c8892004-10-08 17:32:09 +0000539
Chris Lattner1f21ef12005-02-23 16:53:04 +0000540 if (NumElements > 16 && GV->hasNUsesOrMore(16))
Chris Lattnerd514d822005-02-01 01:23:31 +0000541 return 0; // It's not worth it.
Chris Lattner670c8892004-10-08 17:32:09 +0000542 NewGlobals.reserve(NumElements);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000543
Duncan Sands777d2302009-05-09 07:06:46 +0000544 uint64_t EltSize = TD.getTypeAllocSize(STy->getElementType());
Chris Lattner998182b2008-04-26 07:40:11 +0000545 unsigned EltAlign = TD.getABITypeAlignment(STy->getElementType());
Chris Lattner670c8892004-10-08 17:32:09 +0000546 for (unsigned i = 0, e = NumElements; i != e; ++i) {
Chris Lattnera1f00f42012-01-25 06:48:06 +0000547 Constant *In = Init->getAggregateElement(i);
Chris Lattner670c8892004-10-08 17:32:09 +0000548 assert(In && "Couldn't get element of initializer?");
549
Chris Lattner7b550cc2009-11-06 04:27:31 +0000550 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(), false,
Chris Lattner670c8892004-10-08 17:32:09 +0000551 GlobalVariable::InternalLinkage,
Daniel Dunbarfe09b202009-07-30 17:37:43 +0000552 In, GV->getName()+"."+Twine(i),
Hans Wennborgce718ff2012-06-23 11:37:03 +0000553 GV->getThreadLocalMode(),
Owen Andersone9b11b42009-07-08 19:03:57 +0000554 GV->getType()->getAddressSpace());
Chris Lattner670c8892004-10-08 17:32:09 +0000555 Globals.insert(GV, NGV);
556 NewGlobals.push_back(NGV);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000557
Chris Lattner998182b2008-04-26 07:40:11 +0000558 // Calculate the known alignment of the field. If the original aggregate
559 // had 256 byte alignment for example, something might depend on that:
560 // propagate info to each field.
561 unsigned NewAlign = (unsigned)MinAlign(StartAlignment, EltSize*i);
562 if (NewAlign > EltAlign)
563 NGV->setAlignment(NewAlign);
Chris Lattner670c8892004-10-08 17:32:09 +0000564 }
565 }
566
567 if (NewGlobals.empty())
568 return 0;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000569
David Greene3215b0e2010-01-05 01:28:05 +0000570 DEBUG(dbgs() << "PERFORMING GLOBAL SRA ON: " << *GV);
Chris Lattner30ba5692004-10-11 05:54:41 +0000571
Chris Lattner7b550cc2009-11-06 04:27:31 +0000572 Constant *NullInt =Constant::getNullValue(Type::getInt32Ty(GV->getContext()));
Chris Lattner670c8892004-10-08 17:32:09 +0000573
574 // Loop over all of the uses of the global, replacing the constantexpr geps,
575 // with smaller constantexpr geps or direct references.
576 while (!GV->use_empty()) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000577 User *GEP = GV->use_back();
578 assert(((isa<ConstantExpr>(GEP) &&
579 cast<ConstantExpr>(GEP)->getOpcode()==Instruction::GetElementPtr)||
580 isa<GetElementPtrInst>(GEP)) && "NonGEP CE's are not SRAable!");
Misha Brukmanfd939082005-04-21 23:48:37 +0000581
Chris Lattner670c8892004-10-08 17:32:09 +0000582 // Ignore the 1th operand, which has to be zero or else the program is quite
583 // broken (undefined). Get the 2nd operand, which is the structure or array
584 // index.
Reid Spencerb83eb642006-10-20 07:07:24 +0000585 unsigned Val = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
Chris Lattner670c8892004-10-08 17:32:09 +0000586 if (Val >= NewGlobals.size()) Val = 0; // Out of bound array access.
587
Chris Lattner30ba5692004-10-11 05:54:41 +0000588 Value *NewPtr = NewGlobals[Val];
Chris Lattner670c8892004-10-08 17:32:09 +0000589
590 // Form a shorter GEP if needed.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000591 if (GEP->getNumOperands() > 3) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000592 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEP)) {
Chris Lattner55eb1c42007-01-31 04:40:53 +0000593 SmallVector<Constant*, 8> Idxs;
Chris Lattner30ba5692004-10-11 05:54:41 +0000594 Idxs.push_back(NullInt);
595 for (unsigned i = 3, e = CE->getNumOperands(); i != e; ++i)
596 Idxs.push_back(CE->getOperand(i));
Jay Foaddab3d292011-07-21 14:31:17 +0000597 NewPtr = ConstantExpr::getGetElementPtr(cast<Constant>(NewPtr), Idxs);
Chris Lattner30ba5692004-10-11 05:54:41 +0000598 } else {
599 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(GEP);
Chris Lattner699d1442007-01-31 19:59:55 +0000600 SmallVector<Value*, 8> Idxs;
Chris Lattner30ba5692004-10-11 05:54:41 +0000601 Idxs.push_back(NullInt);
602 for (unsigned i = 3, e = GEPI->getNumOperands(); i != e; ++i)
603 Idxs.push_back(GEPI->getOperand(i));
Jay Foada9203102011-07-25 09:48:08 +0000604 NewPtr = GetElementPtrInst::Create(NewPtr, Idxs,
Daniel Dunbarfe09b202009-07-30 17:37:43 +0000605 GEPI->getName()+"."+Twine(Val),GEPI);
Chris Lattner30ba5692004-10-11 05:54:41 +0000606 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000607 }
Chris Lattner30ba5692004-10-11 05:54:41 +0000608 GEP->replaceAllUsesWith(NewPtr);
609
610 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(GEP))
Chris Lattner7a7ed022004-10-16 18:09:00 +0000611 GEPI->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +0000612 else
613 cast<ConstantExpr>(GEP)->destroyConstant();
Chris Lattner670c8892004-10-08 17:32:09 +0000614 }
615
Chris Lattnere40e2d12004-10-08 20:25:55 +0000616 // Delete the old global, now that it is dead.
617 Globals.erase(GV);
Chris Lattner670c8892004-10-08 17:32:09 +0000618 ++NumSRA;
Chris Lattner30ba5692004-10-11 05:54:41 +0000619
620 // Loop over the new globals array deleting any globals that are obviously
621 // dead. This can arise due to scalarization of a structure or an array that
622 // has elements that are dead.
623 unsigned FirstGlobal = 0;
624 for (unsigned i = 0, e = NewGlobals.size(); i != e; ++i)
625 if (NewGlobals[i]->use_empty()) {
626 Globals.erase(NewGlobals[i]);
627 if (FirstGlobal == i) ++FirstGlobal;
628 }
629
630 return FirstGlobal != NewGlobals.size() ? NewGlobals[FirstGlobal] : 0;
Chris Lattner670c8892004-10-08 17:32:09 +0000631}
632
Chris Lattner9b34a612004-10-09 21:48:45 +0000633/// AllUsesOfValueWillTrapIfNull - Return true if all users of the specified
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000634/// value will trap if the value is dynamically null. PHIs keeps track of any
Chris Lattner81686182007-09-13 16:30:19 +0000635/// phi nodes we've seen to avoid reprocessing them.
Gabor Greif6ce02b52010-04-06 19:24:18 +0000636static bool AllUsesOfValueWillTrapIfNull(const Value *V,
637 SmallPtrSet<const PHINode*, 8> &PHIs) {
638 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;
Gabor Greifa01d6db2010-04-06 19:14:05 +0000639 ++UI) {
Gabor Greif6ce02b52010-04-06 19:24:18 +0000640 const User *U = *UI;
Gabor Greifa01d6db2010-04-06 19:14:05 +0000641
642 if (isa<LoadInst>(U)) {
Chris Lattner9b34a612004-10-09 21:48:45 +0000643 // Will trap.
Gabor Greif6ce02b52010-04-06 19:24:18 +0000644 } else if (const StoreInst *SI = dyn_cast<StoreInst>(U)) {
Chris Lattner9b34a612004-10-09 21:48:45 +0000645 if (SI->getOperand(0) == V) {
Gabor Greifa01d6db2010-04-06 19:14:05 +0000646 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner9b34a612004-10-09 21:48:45 +0000647 return false; // Storing the value.
648 }
Gabor Greif6ce02b52010-04-06 19:24:18 +0000649 } else if (const CallInst *CI = dyn_cast<CallInst>(U)) {
Gabor Greif654c06f2010-03-20 21:00:25 +0000650 if (CI->getCalledValue() != V) {
Gabor Greifa01d6db2010-04-06 19:14:05 +0000651 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner9b34a612004-10-09 21:48:45 +0000652 return false; // Not calling the ptr
653 }
Gabor Greif6ce02b52010-04-06 19:24:18 +0000654 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(U)) {
Gabor Greif654c06f2010-03-20 21:00:25 +0000655 if (II->getCalledValue() != V) {
Gabor Greifa01d6db2010-04-06 19:14:05 +0000656 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner9b34a612004-10-09 21:48:45 +0000657 return false; // Not calling the ptr
658 }
Gabor Greif6ce02b52010-04-06 19:24:18 +0000659 } else if (const BitCastInst *CI = dyn_cast<BitCastInst>(U)) {
Chris Lattner81686182007-09-13 16:30:19 +0000660 if (!AllUsesOfValueWillTrapIfNull(CI, PHIs)) return false;
Gabor Greif6ce02b52010-04-06 19:24:18 +0000661 } else if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
Chris Lattner81686182007-09-13 16:30:19 +0000662 if (!AllUsesOfValueWillTrapIfNull(GEPI, PHIs)) return false;
Gabor Greif6ce02b52010-04-06 19:24:18 +0000663 } else if (const PHINode *PN = dyn_cast<PHINode>(U)) {
Chris Lattner81686182007-09-13 16:30:19 +0000664 // If we've already seen this phi node, ignore it, it has already been
665 // checked.
Jakob Stoklund Olesenb489d0f2010-01-29 23:54:14 +0000666 if (PHIs.insert(PN) && !AllUsesOfValueWillTrapIfNull(PN, PHIs))
667 return false;
Gabor Greifa01d6db2010-04-06 19:14:05 +0000668 } else if (isa<ICmpInst>(U) &&
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000669 isa<ConstantPointerNull>(UI->getOperand(1))) {
Nick Lewyckye7ee59b2010-02-25 06:39:10 +0000670 // Ignore icmp X, null
Chris Lattner9b34a612004-10-09 21:48:45 +0000671 } else {
Gabor Greifa01d6db2010-04-06 19:14:05 +0000672 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner9b34a612004-10-09 21:48:45 +0000673 return false;
674 }
Gabor Greifa01d6db2010-04-06 19:14:05 +0000675 }
Chris Lattner9b34a612004-10-09 21:48:45 +0000676 return true;
677}
678
679/// AllUsesOfLoadedValueWillTrapIfNull - Return true if all uses of any loads
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000680/// from GV will trap if the loaded value is null. Note that this also permits
681/// comparisons of the loaded value against null, as a special case.
Gabor Greif6ce02b52010-04-06 19:24:18 +0000682static bool AllUsesOfLoadedValueWillTrapIfNull(const GlobalVariable *GV) {
683 for (Value::const_use_iterator UI = GV->use_begin(), E = GV->use_end();
Gabor Greifa01d6db2010-04-06 19:14:05 +0000684 UI != E; ++UI) {
Gabor Greif6ce02b52010-04-06 19:24:18 +0000685 const User *U = *UI;
Gabor Greifa01d6db2010-04-06 19:14:05 +0000686
Gabor Greif6ce02b52010-04-06 19:24:18 +0000687 if (const LoadInst *LI = dyn_cast<LoadInst>(U)) {
688 SmallPtrSet<const PHINode*, 8> PHIs;
Chris Lattner81686182007-09-13 16:30:19 +0000689 if (!AllUsesOfValueWillTrapIfNull(LI, PHIs))
Chris Lattner9b34a612004-10-09 21:48:45 +0000690 return false;
Gabor Greifa01d6db2010-04-06 19:14:05 +0000691 } else if (isa<StoreInst>(U)) {
Chris Lattner9b34a612004-10-09 21:48:45 +0000692 // Ignore stores to the global.
693 } else {
694 // We don't know or understand this user, bail out.
Gabor Greifa01d6db2010-04-06 19:14:05 +0000695 //cerr << "UNKNOWN USER OF GLOBAL!: " << *U;
Chris Lattner9b34a612004-10-09 21:48:45 +0000696 return false;
697 }
Gabor Greifa01d6db2010-04-06 19:14:05 +0000698 }
Chris Lattner9b34a612004-10-09 21:48:45 +0000699 return true;
700}
701
Chris Lattner7b550cc2009-11-06 04:27:31 +0000702static bool OptimizeAwayTrappingUsesOfValue(Value *V, Constant *NewV) {
Chris Lattner708148e2004-10-10 23:14:11 +0000703 bool Changed = false;
704 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ) {
705 Instruction *I = cast<Instruction>(*UI++);
706 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
707 LI->setOperand(0, NewV);
708 Changed = true;
709 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
710 if (SI->getOperand(1) == V) {
711 SI->setOperand(1, NewV);
712 Changed = true;
713 }
714 } else if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
Gabor Greiffa1f5c22010-04-06 18:45:08 +0000715 CallSite CS(I);
716 if (CS.getCalledValue() == V) {
Chris Lattner708148e2004-10-10 23:14:11 +0000717 // Calling through the pointer! Turn into a direct call, but be careful
718 // that the pointer is not also being passed as an argument.
Gabor Greiffa1f5c22010-04-06 18:45:08 +0000719 CS.setCalledFunction(NewV);
Chris Lattner708148e2004-10-10 23:14:11 +0000720 Changed = true;
721 bool PassedAsArg = false;
Gabor Greiffa1f5c22010-04-06 18:45:08 +0000722 for (unsigned i = 0, e = CS.arg_size(); i != e; ++i)
723 if (CS.getArgument(i) == V) {
Chris Lattner708148e2004-10-10 23:14:11 +0000724 PassedAsArg = true;
Gabor Greiffa1f5c22010-04-06 18:45:08 +0000725 CS.setArgument(i, NewV);
Chris Lattner708148e2004-10-10 23:14:11 +0000726 }
727
728 if (PassedAsArg) {
729 // Being passed as an argument also. Be careful to not invalidate UI!
730 UI = V->use_begin();
731 }
732 }
733 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
734 Changed |= OptimizeAwayTrappingUsesOfValue(CI,
Owen Andersonbaf3c402009-07-29 18:55:55 +0000735 ConstantExpr::getCast(CI->getOpcode(),
Chris Lattner7b550cc2009-11-06 04:27:31 +0000736 NewV, CI->getType()));
Chris Lattner708148e2004-10-10 23:14:11 +0000737 if (CI->use_empty()) {
738 Changed = true;
Chris Lattner7a7ed022004-10-16 18:09:00 +0000739 CI->eraseFromParent();
Chris Lattner708148e2004-10-10 23:14:11 +0000740 }
741 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
742 // Should handle GEP here.
Chris Lattner55eb1c42007-01-31 04:40:53 +0000743 SmallVector<Constant*, 8> Idxs;
744 Idxs.reserve(GEPI->getNumOperands()-1);
Gabor Greif5e463212008-05-29 01:59:18 +0000745 for (User::op_iterator i = GEPI->op_begin() + 1, e = GEPI->op_end();
746 i != e; ++i)
747 if (Constant *C = dyn_cast<Constant>(*i))
Chris Lattner55eb1c42007-01-31 04:40:53 +0000748 Idxs.push_back(C);
Chris Lattner708148e2004-10-10 23:14:11 +0000749 else
750 break;
Chris Lattner55eb1c42007-01-31 04:40:53 +0000751 if (Idxs.size() == GEPI->getNumOperands()-1)
Chris Lattner708148e2004-10-10 23:14:11 +0000752 Changed |= OptimizeAwayTrappingUsesOfValue(GEPI,
Jay Foaddab3d292011-07-21 14:31:17 +0000753 ConstantExpr::getGetElementPtr(NewV, Idxs));
Chris Lattner708148e2004-10-10 23:14:11 +0000754 if (GEPI->use_empty()) {
755 Changed = true;
Chris Lattner7a7ed022004-10-16 18:09:00 +0000756 GEPI->eraseFromParent();
Chris Lattner708148e2004-10-10 23:14:11 +0000757 }
758 }
759 }
760
761 return Changed;
762}
763
764
765/// OptimizeAwayTrappingUsesOfLoads - The specified global has only one non-null
766/// value stored into it. If there are uses of the loaded value that would trap
767/// if the loaded value is dynamically null, then we know that they cannot be
768/// reachable with a null optimize away the load.
Nick Lewycky6a577f82012-02-12 01:13:18 +0000769static bool OptimizeAwayTrappingUsesOfLoads(GlobalVariable *GV, Constant *LV,
770 TargetData *TD,
771 TargetLibraryInfo *TLI) {
Chris Lattner708148e2004-10-10 23:14:11 +0000772 bool Changed = false;
773
Chris Lattner92c6bd22009-01-14 00:12:58 +0000774 // Keep track of whether we are able to remove all the uses of the global
775 // other than the store that defines it.
776 bool AllNonStoreUsesGone = true;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000777
Chris Lattner708148e2004-10-10 23:14:11 +0000778 // Replace all uses of loads with uses of uses of the stored value.
Chris Lattner92c6bd22009-01-14 00:12:58 +0000779 for (Value::use_iterator GUI = GV->use_begin(), E = GV->use_end(); GUI != E;){
780 User *GlobalUser = *GUI++;
781 if (LoadInst *LI = dyn_cast<LoadInst>(GlobalUser)) {
Chris Lattner7b550cc2009-11-06 04:27:31 +0000782 Changed |= OptimizeAwayTrappingUsesOfValue(LI, LV);
Chris Lattner92c6bd22009-01-14 00:12:58 +0000783 // If we were able to delete all uses of the loads
784 if (LI->use_empty()) {
785 LI->eraseFromParent();
786 Changed = true;
787 } else {
788 AllNonStoreUsesGone = false;
789 }
790 } else if (isa<StoreInst>(GlobalUser)) {
791 // Ignore the store that stores "LV" to the global.
792 assert(GlobalUser->getOperand(1) == GV &&
793 "Must be storing *to* the global");
Chris Lattner708148e2004-10-10 23:14:11 +0000794 } else {
Chris Lattner92c6bd22009-01-14 00:12:58 +0000795 AllNonStoreUsesGone = false;
796
797 // If we get here we could have other crazy uses that are transitively
798 // loaded.
799 assert((isa<PHINode>(GlobalUser) || isa<SelectInst>(GlobalUser) ||
Chris Lattner98a42b22011-05-22 07:15:13 +0000800 isa<ConstantExpr>(GlobalUser) || isa<CmpInst>(GlobalUser)) &&
801 "Only expect load and stores!");
Chris Lattner708148e2004-10-10 23:14:11 +0000802 }
Chris Lattner92c6bd22009-01-14 00:12:58 +0000803 }
Chris Lattner708148e2004-10-10 23:14:11 +0000804
805 if (Changed) {
David Greene3215b0e2010-01-05 01:28:05 +0000806 DEBUG(dbgs() << "OPTIMIZED LOADS FROM STORED ONCE POINTER: " << *GV);
Chris Lattner708148e2004-10-10 23:14:11 +0000807 ++NumGlobUses;
808 }
809
Chris Lattner708148e2004-10-10 23:14:11 +0000810 // If we nuked all of the loads, then none of the stores are needed either,
811 // nor is the global.
Chris Lattner92c6bd22009-01-14 00:12:58 +0000812 if (AllNonStoreUsesGone) {
David Greene3215b0e2010-01-05 01:28:05 +0000813 DEBUG(dbgs() << " *** GLOBAL NOW DEAD!\n");
Nick Lewycky6a577f82012-02-12 01:13:18 +0000814 CleanupConstantGlobalUsers(GV, 0, TD, TLI);
Chris Lattner708148e2004-10-10 23:14:11 +0000815 if (GV->use_empty()) {
Chris Lattner7a7ed022004-10-16 18:09:00 +0000816 GV->eraseFromParent();
Chris Lattner708148e2004-10-10 23:14:11 +0000817 ++NumDeleted;
818 }
819 Changed = true;
820 }
821 return Changed;
822}
823
Chris Lattner30ba5692004-10-11 05:54:41 +0000824/// ConstantPropUsersOf - Walk the use list of V, constant folding all of the
825/// instructions that are foldable.
Nick Lewycky6a577f82012-02-12 01:13:18 +0000826static void ConstantPropUsersOf(Value *V,
827 TargetData *TD, TargetLibraryInfo *TLI) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000828 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; )
829 if (Instruction *I = dyn_cast<Instruction>(*UI++))
Nick Lewycky6a577f82012-02-12 01:13:18 +0000830 if (Constant *NewC = ConstantFoldInstruction(I, TD, TLI)) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000831 I->replaceAllUsesWith(NewC);
832
Chris Lattnerd514d822005-02-01 01:23:31 +0000833 // Advance UI to the next non-I use to avoid invalidating it!
834 // Instructions could multiply use V.
835 while (UI != E && *UI == I)
Chris Lattner30ba5692004-10-11 05:54:41 +0000836 ++UI;
Chris Lattnerd514d822005-02-01 01:23:31 +0000837 I->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +0000838 }
839}
840
841/// OptimizeGlobalAddressOfMalloc - This function takes the specified global
842/// variable, and transforms the program as if it always contained the result of
843/// the specified malloc. Because it is always the result of the specified
844/// malloc, there is no reason to actually DO the malloc. Instead, turn the
Chris Lattner6e8fbad2006-11-30 17:32:29 +0000845/// malloc into a global, and any loads of GV as uses of the new global.
Chris Lattner30ba5692004-10-11 05:54:41 +0000846static GlobalVariable *OptimizeGlobalAddressOfMalloc(GlobalVariable *GV,
Victor Hernandez83d63912009-09-18 22:35:49 +0000847 CallInst *CI,
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000848 Type *AllocTy,
Chris Lattnera6874652010-02-25 22:33:52 +0000849 ConstantInt *NElements,
Nick Lewycky6a577f82012-02-12 01:13:18 +0000850 TargetData *TD,
851 TargetLibraryInfo *TLI) {
Chris Lattnera6874652010-02-25 22:33:52 +0000852 DEBUG(errs() << "PROMOTING GLOBAL: " << *GV << " CALL = " << *CI << '\n');
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000853
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000854 Type *GlobalType;
Chris Lattnera6874652010-02-25 22:33:52 +0000855 if (NElements->getZExtValue() == 1)
856 GlobalType = AllocTy;
857 else
858 // If we have an array allocation, the global variable is of an array.
859 GlobalType = ArrayType::get(AllocTy, NElements->getZExtValue());
Victor Hernandez83d63912009-09-18 22:35:49 +0000860
861 // Create the new global variable. The contents of the malloc'd memory is
862 // undefined, so initialize with an undef value.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000863 GlobalVariable *NewGV = new GlobalVariable(*GV->getParent(),
Chris Lattnere9fd4442010-02-26 23:42:13 +0000864 GlobalType, false,
Chris Lattnera6874652010-02-25 22:33:52 +0000865 GlobalValue::InternalLinkage,
Chris Lattnere9fd4442010-02-26 23:42:13 +0000866 UndefValue::get(GlobalType),
Victor Hernandez83d63912009-09-18 22:35:49 +0000867 GV->getName()+".body",
868 GV,
Hans Wennborgce718ff2012-06-23 11:37:03 +0000869 GV->getThreadLocalMode());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000870
Chris Lattnera6874652010-02-25 22:33:52 +0000871 // If there are bitcast users of the malloc (which is typical, usually we have
872 // a malloc + bitcast) then replace them with uses of the new global. Update
873 // other users to use the global as well.
874 BitCastInst *TheBC = 0;
875 while (!CI->use_empty()) {
876 Instruction *User = cast<Instruction>(CI->use_back());
877 if (BitCastInst *BCI = dyn_cast<BitCastInst>(User)) {
878 if (BCI->getType() == NewGV->getType()) {
879 BCI->replaceAllUsesWith(NewGV);
880 BCI->eraseFromParent();
881 } else {
882 BCI->setOperand(0, NewGV);
883 }
884 } else {
885 if (TheBC == 0)
886 TheBC = new BitCastInst(NewGV, CI->getType(), "newgv", CI);
887 User->replaceUsesOfWith(CI, TheBC);
888 }
889 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000890
Victor Hernandez83d63912009-09-18 22:35:49 +0000891 Constant *RepValue = NewGV;
892 if (NewGV->getType() != GV->getType()->getElementType())
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000893 RepValue = ConstantExpr::getBitCast(RepValue,
Victor Hernandez83d63912009-09-18 22:35:49 +0000894 GV->getType()->getElementType());
895
896 // If there is a comparison against null, we will insert a global bool to
897 // keep track of whether the global was initialized yet or not.
898 GlobalVariable *InitBool =
Chris Lattner7b550cc2009-11-06 04:27:31 +0000899 new GlobalVariable(Type::getInt1Ty(GV->getContext()), false,
Victor Hernandez83d63912009-09-18 22:35:49 +0000900 GlobalValue::InternalLinkage,
Chris Lattner7b550cc2009-11-06 04:27:31 +0000901 ConstantInt::getFalse(GV->getContext()),
Hans Wennborgce718ff2012-06-23 11:37:03 +0000902 GV->getName()+".init", GV->getThreadLocalMode());
Victor Hernandez83d63912009-09-18 22:35:49 +0000903 bool InitBoolUsed = false;
904
905 // Loop over all uses of GV, processing them in turn.
Chris Lattnera6874652010-02-25 22:33:52 +0000906 while (!GV->use_empty()) {
907 if (StoreInst *SI = dyn_cast<StoreInst>(GV->use_back())) {
Victor Hernandez83d63912009-09-18 22:35:49 +0000908 // The global is initialized when the store to it occurs.
Nick Lewyckyfad4d402012-02-05 19:56:38 +0000909 new StoreInst(ConstantInt::getTrue(GV->getContext()), InitBool, false, 0,
910 SI->getOrdering(), SI->getSynchScope(), SI);
Victor Hernandez83d63912009-09-18 22:35:49 +0000911 SI->eraseFromParent();
Chris Lattnera6874652010-02-25 22:33:52 +0000912 continue;
Victor Hernandez83d63912009-09-18 22:35:49 +0000913 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000914
Chris Lattnera6874652010-02-25 22:33:52 +0000915 LoadInst *LI = cast<LoadInst>(GV->use_back());
916 while (!LI->use_empty()) {
917 Use &LoadUse = LI->use_begin().getUse();
918 if (!isa<ICmpInst>(LoadUse.getUser())) {
919 LoadUse = RepValue;
920 continue;
921 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000922
Chris Lattnera6874652010-02-25 22:33:52 +0000923 ICmpInst *ICI = cast<ICmpInst>(LoadUse.getUser());
924 // Replace the cmp X, 0 with a use of the bool value.
Nick Lewyckyfad4d402012-02-05 19:56:38 +0000925 // Sink the load to where the compare was, if atomic rules allow us to.
926 Value *LV = new LoadInst(InitBool, InitBool->getName()+".val", false, 0,
927 LI->getOrdering(), LI->getSynchScope(),
928 LI->isUnordered() ? (Instruction*)ICI : LI);
Chris Lattnera6874652010-02-25 22:33:52 +0000929 InitBoolUsed = true;
930 switch (ICI->getPredicate()) {
931 default: llvm_unreachable("Unknown ICmp Predicate!");
932 case ICmpInst::ICMP_ULT:
933 case ICmpInst::ICMP_SLT: // X < null -> always false
934 LV = ConstantInt::getFalse(GV->getContext());
935 break;
936 case ICmpInst::ICMP_ULE:
937 case ICmpInst::ICMP_SLE:
938 case ICmpInst::ICMP_EQ:
939 LV = BinaryOperator::CreateNot(LV, "notinit", ICI);
940 break;
941 case ICmpInst::ICMP_NE:
942 case ICmpInst::ICMP_UGE:
943 case ICmpInst::ICMP_SGE:
944 case ICmpInst::ICMP_UGT:
945 case ICmpInst::ICMP_SGT:
946 break; // no change.
947 }
948 ICI->replaceAllUsesWith(LV);
949 ICI->eraseFromParent();
950 }
951 LI->eraseFromParent();
952 }
Victor Hernandez83d63912009-09-18 22:35:49 +0000953
954 // If the initialization boolean was used, insert it, otherwise delete it.
955 if (!InitBoolUsed) {
956 while (!InitBool->use_empty()) // Delete initializations
Chris Lattnera6874652010-02-25 22:33:52 +0000957 cast<StoreInst>(InitBool->use_back())->eraseFromParent();
Victor Hernandez83d63912009-09-18 22:35:49 +0000958 delete InitBool;
959 } else
960 GV->getParent()->getGlobalList().insert(GV, InitBool);
961
Chris Lattnera6874652010-02-25 22:33:52 +0000962 // Now the GV is dead, nuke it and the malloc..
Victor Hernandez83d63912009-09-18 22:35:49 +0000963 GV->eraseFromParent();
Victor Hernandez83d63912009-09-18 22:35:49 +0000964 CI->eraseFromParent();
965
966 // To further other optimizations, loop over all users of NewGV and try to
967 // constant prop them. This will promote GEP instructions with constant
968 // indices into GEP constant-exprs, which will allow global-opt to hack on it.
Nick Lewycky6a577f82012-02-12 01:13:18 +0000969 ConstantPropUsersOf(NewGV, TD, TLI);
Victor Hernandez83d63912009-09-18 22:35:49 +0000970 if (RepValue != NewGV)
Nick Lewycky6a577f82012-02-12 01:13:18 +0000971 ConstantPropUsersOf(RepValue, TD, TLI);
Victor Hernandez83d63912009-09-18 22:35:49 +0000972
973 return NewGV;
974}
975
Chris Lattnerfa07e4f2004-12-02 07:11:07 +0000976/// ValueIsOnlyUsedLocallyOrStoredToOneGlobal - Scan the use-list of V checking
977/// to make sure that there are no complex uses of V. We permit simple things
978/// like dereferencing the pointer, but not storing through the address, unless
979/// it is to the specified global.
Gabor Greif0b520db2010-04-06 18:58:22 +0000980static bool ValueIsOnlyUsedLocallyOrStoredToOneGlobal(const Instruction *V,
981 const GlobalVariable *GV,
Gabor Greifa01d6db2010-04-06 19:14:05 +0000982 SmallPtrSet<const PHINode*, 8> &PHIs) {
Gabor Greif0b520db2010-04-06 18:58:22 +0000983 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end();
Gabor Greifa01d6db2010-04-06 19:14:05 +0000984 UI != E; ++UI) {
Gabor Greif0b520db2010-04-06 18:58:22 +0000985 const Instruction *Inst = cast<Instruction>(*UI);
Gabor Greifa01d6db2010-04-06 19:14:05 +0000986
Chris Lattner49b6d4a2008-12-15 21:08:54 +0000987 if (isa<LoadInst>(Inst) || isa<CmpInst>(Inst)) {
988 continue; // Fine, ignore.
989 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000990
Gabor Greif0b520db2010-04-06 18:58:22 +0000991 if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
Chris Lattnerfa07e4f2004-12-02 07:11:07 +0000992 if (SI->getOperand(0) == V && SI->getOperand(1) != GV)
993 return false; // Storing the pointer itself... bad.
Chris Lattner49b6d4a2008-12-15 21:08:54 +0000994 continue; // Otherwise, storing through it, or storing into GV... fine.
995 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000996
Chris Lattnera2fb2342010-04-10 18:19:22 +0000997 // Must index into the array and into the struct.
998 if (isa<GetElementPtrInst>(Inst) && Inst->getNumOperands() >= 3) {
Chris Lattner49b6d4a2008-12-15 21:08:54 +0000999 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(Inst, GV, PHIs))
Chris Lattnerfa07e4f2004-12-02 07:11:07 +00001000 return false;
Chris Lattner49b6d4a2008-12-15 21:08:54 +00001001 continue;
1002 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001003
Gabor Greif0b520db2010-04-06 18:58:22 +00001004 if (const PHINode *PN = dyn_cast<PHINode>(Inst)) {
Chris Lattnerc451f9c2007-09-13 16:37:20 +00001005 // PHIs are ok if all uses are ok. Don't infinitely recurse through PHI
1006 // cycles.
1007 if (PHIs.insert(PN))
Chris Lattner5e6e4942007-09-14 03:41:21 +00001008 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(PN, GV, PHIs))
1009 return false;
Chris Lattner49b6d4a2008-12-15 21:08:54 +00001010 continue;
Chris Lattnerfa07e4f2004-12-02 07:11:07 +00001011 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001012
Gabor Greif0b520db2010-04-06 18:58:22 +00001013 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Inst)) {
Chris Lattner49b6d4a2008-12-15 21:08:54 +00001014 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(BCI, GV, PHIs))
1015 return false;
1016 continue;
1017 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001018
Chris Lattner49b6d4a2008-12-15 21:08:54 +00001019 return false;
1020 }
Chris Lattnerfa07e4f2004-12-02 07:11:07 +00001021 return true;
Chris Lattnerfa07e4f2004-12-02 07:11:07 +00001022}
1023
Chris Lattner86395032006-09-30 23:32:09 +00001024/// ReplaceUsesOfMallocWithGlobal - The Alloc pointer is stored into GV
1025/// somewhere. Transform all uses of the allocation into loads from the
1026/// global and uses of the resultant pointer. Further, delete the store into
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001027/// GV. This assumes that these value pass the
Chris Lattner86395032006-09-30 23:32:09 +00001028/// 'ValueIsOnlyUsedLocallyOrStoredToOneGlobal' predicate.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001029static void ReplaceUsesOfMallocWithGlobal(Instruction *Alloc,
Chris Lattner86395032006-09-30 23:32:09 +00001030 GlobalVariable *GV) {
1031 while (!Alloc->use_empty()) {
Chris Lattnera637a8b2007-09-13 18:00:31 +00001032 Instruction *U = cast<Instruction>(*Alloc->use_begin());
1033 Instruction *InsertPt = U;
Chris Lattner86395032006-09-30 23:32:09 +00001034 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
1035 // If this is the store of the allocation into the global, remove it.
1036 if (SI->getOperand(1) == GV) {
1037 SI->eraseFromParent();
1038 continue;
1039 }
Chris Lattnera637a8b2007-09-13 18:00:31 +00001040 } else if (PHINode *PN = dyn_cast<PHINode>(U)) {
1041 // Insert the load in the corresponding predecessor, not right before the
1042 // PHI.
Gabor Greifa36791d2009-01-23 19:40:15 +00001043 InsertPt = PN->getIncomingBlock(Alloc->use_begin())->getTerminator();
Chris Lattner101f44e2008-12-15 21:44:34 +00001044 } else if (isa<BitCastInst>(U)) {
1045 // Must be bitcast between the malloc and store to initialize the global.
1046 ReplaceUsesOfMallocWithGlobal(U, GV);
1047 U->eraseFromParent();
1048 continue;
1049 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
1050 // If this is a "GEP bitcast" and the user is a store to the global, then
1051 // just process it as a bitcast.
1052 if (GEPI->hasAllZeroIndices() && GEPI->hasOneUse())
1053 if (StoreInst *SI = dyn_cast<StoreInst>(GEPI->use_back()))
1054 if (SI->getOperand(1) == GV) {
1055 // Must be bitcast GEP between the malloc and store to initialize
1056 // the global.
1057 ReplaceUsesOfMallocWithGlobal(GEPI, GV);
1058 GEPI->eraseFromParent();
1059 continue;
1060 }
Chris Lattner86395032006-09-30 23:32:09 +00001061 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001062
Chris Lattner86395032006-09-30 23:32:09 +00001063 // Insert a load from the global, and use it instead of the malloc.
Chris Lattnera637a8b2007-09-13 18:00:31 +00001064 Value *NL = new LoadInst(GV, GV->getName()+".val", InsertPt);
Chris Lattner86395032006-09-30 23:32:09 +00001065 U->replaceUsesOfWith(Alloc, NL);
1066 }
1067}
1068
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001069/// LoadUsesSimpleEnoughForHeapSRA - Verify that all uses of V (a load, or a phi
1070/// of a load) are simple enough to perform heap SRA on. This permits GEP's
1071/// that index through the array and struct field, icmps of null, and PHIs.
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001072static bool LoadUsesSimpleEnoughForHeapSRA(const Value *V,
Gabor Greif27236912010-04-07 18:59:26 +00001073 SmallPtrSet<const PHINode*, 32> &LoadUsingPHIs,
1074 SmallPtrSet<const PHINode*, 32> &LoadUsingPHIsPerLoad) {
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001075 // We permit two users of the load: setcc comparing against the null
1076 // pointer, and a getelementptr of a specific form.
Gabor Greif27236912010-04-07 18:59:26 +00001077 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;
1078 ++UI) {
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001079 const Instruction *User = cast<Instruction>(*UI);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001080
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001081 // Comparison against null is ok.
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001082 if (const ICmpInst *ICI = dyn_cast<ICmpInst>(User)) {
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001083 if (!isa<ConstantPointerNull>(ICI->getOperand(1)))
1084 return false;
1085 continue;
1086 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001087
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001088 // getelementptr is also ok, but only a simple form.
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001089 if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001090 // Must index into the array and into the struct.
1091 if (GEPI->getNumOperands() < 3)
1092 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001093
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001094 // Otherwise the GEP is ok.
1095 continue;
1096 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001097
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001098 if (const PHINode *PN = dyn_cast<PHINode>(User)) {
Evan Cheng5d163962009-06-02 00:56:07 +00001099 if (!LoadUsingPHIsPerLoad.insert(PN))
1100 // This means some phi nodes are dependent on each other.
1101 // Avoid infinite looping!
1102 return false;
1103 if (!LoadUsingPHIs.insert(PN))
1104 // If we have already analyzed this PHI, then it is safe.
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001105 continue;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001106
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001107 // Make sure all uses of the PHI are simple enough to transform.
Evan Cheng5d163962009-06-02 00:56:07 +00001108 if (!LoadUsesSimpleEnoughForHeapSRA(PN,
1109 LoadUsingPHIs, LoadUsingPHIsPerLoad))
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001110 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001111
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001112 continue;
Chris Lattner86395032006-09-30 23:32:09 +00001113 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001114
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001115 // Otherwise we don't know what this is, not ok.
1116 return false;
1117 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001118
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001119 return true;
1120}
1121
1122
1123/// AllGlobalLoadUsesSimpleEnoughForHeapSRA - If all users of values loaded from
1124/// GV are simple enough to perform HeapSRA, return true.
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001125static bool AllGlobalLoadUsesSimpleEnoughForHeapSRA(const GlobalVariable *GV,
Victor Hernandez83d63912009-09-18 22:35:49 +00001126 Instruction *StoredVal) {
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001127 SmallPtrSet<const PHINode*, 32> LoadUsingPHIs;
1128 SmallPtrSet<const PHINode*, 32> LoadUsingPHIsPerLoad;
Gabor Greif27236912010-04-07 18:59:26 +00001129 for (Value::const_use_iterator UI = GV->use_begin(), E = GV->use_end();
1130 UI != E; ++UI)
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001131 if (const LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
Evan Cheng5d163962009-06-02 00:56:07 +00001132 if (!LoadUsesSimpleEnoughForHeapSRA(LI, LoadUsingPHIs,
1133 LoadUsingPHIsPerLoad))
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001134 return false;
Evan Cheng5d163962009-06-02 00:56:07 +00001135 LoadUsingPHIsPerLoad.clear();
1136 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001137
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001138 // If we reach here, we know that all uses of the loads and transitive uses
1139 // (through PHI nodes) are simple enough to transform. However, we don't know
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001140 // that all inputs the to the PHI nodes are in the same equivalence sets.
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001141 // Check to verify that all operands of the PHIs are either PHIS that can be
1142 // transformed, loads from GV, or MI itself.
Gabor Greif27236912010-04-07 18:59:26 +00001143 for (SmallPtrSet<const PHINode*, 32>::const_iterator I = LoadUsingPHIs.begin()
1144 , E = LoadUsingPHIs.end(); I != E; ++I) {
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001145 const PHINode *PN = *I;
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001146 for (unsigned op = 0, e = PN->getNumIncomingValues(); op != e; ++op) {
1147 Value *InVal = PN->getIncomingValue(op);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001148
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001149 // PHI of the stored value itself is ok.
Victor Hernandez83d63912009-09-18 22:35:49 +00001150 if (InVal == StoredVal) continue;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001151
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001152 if (const PHINode *InPN = dyn_cast<PHINode>(InVal)) {
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001153 // One of the PHIs in our set is (optimistically) ok.
1154 if (LoadUsingPHIs.count(InPN))
1155 continue;
1156 return false;
1157 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001158
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001159 // Load from GV is ok.
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001160 if (const LoadInst *LI = dyn_cast<LoadInst>(InVal))
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001161 if (LI->getOperand(0) == GV)
1162 continue;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001163
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001164 // UNDEF? NULL?
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001165
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001166 // Anything else is rejected.
1167 return false;
1168 }
1169 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001170
Chris Lattner86395032006-09-30 23:32:09 +00001171 return true;
1172}
1173
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001174static Value *GetHeapSROAValue(Value *V, unsigned FieldNo,
1175 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001176 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001177 std::vector<Value*> &FieldVals = InsertedScalarizedValues[V];
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001178
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001179 if (FieldNo >= FieldVals.size())
1180 FieldVals.resize(FieldNo+1);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001181
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001182 // If we already have this value, just reuse the previously scalarized
1183 // version.
1184 if (Value *FieldVal = FieldVals[FieldNo])
1185 return FieldVal;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001186
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001187 // Depending on what instruction this is, we have several cases.
1188 Value *Result;
1189 if (LoadInst *LI = dyn_cast<LoadInst>(V)) {
1190 // This is a scalarized version of the load from the global. Just create
1191 // a new Load of the scalarized global.
1192 Result = new LoadInst(GetHeapSROAValue(LI->getOperand(0), FieldNo,
1193 InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001194 PHIsToRewrite),
Daniel Dunbarfe09b202009-07-30 17:37:43 +00001195 LI->getName()+".f"+Twine(FieldNo), LI);
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001196 } else if (PHINode *PN = dyn_cast<PHINode>(V)) {
1197 // PN's type is pointer to struct. Make a new PHI of pointer to struct
1198 // field.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001199 StructType *ST =
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001200 cast<StructType>(cast<PointerType>(PN->getType())->getElementType());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001201
Jay Foadd8b4fb42011-03-30 11:19:20 +00001202 PHINode *NewPN =
Owen Andersondebcb012009-07-29 22:17:13 +00001203 PHINode::Create(PointerType::getUnqual(ST->getElementType(FieldNo)),
Jay Foad3ecfc862011-03-30 11:28:46 +00001204 PN->getNumIncomingValues(),
Daniel Dunbarfe09b202009-07-30 17:37:43 +00001205 PN->getName()+".f"+Twine(FieldNo), PN);
Jay Foadd8b4fb42011-03-30 11:19:20 +00001206 Result = NewPN;
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001207 PHIsToRewrite.push_back(std::make_pair(PN, FieldNo));
1208 } else {
Torok Edwinc23197a2009-07-14 16:55:14 +00001209 llvm_unreachable("Unknown usable value");
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001210 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001211
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001212 return FieldVals[FieldNo] = Result;
Chris Lattnera637a8b2007-09-13 18:00:31 +00001213}
1214
Chris Lattner330245e2007-09-13 17:29:05 +00001215/// RewriteHeapSROALoadUser - Given a load instruction and a value derived from
1216/// the load, rewrite the derived value to use the HeapSRoA'd load.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001217static void RewriteHeapSROALoadUser(Instruction *LoadUser,
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001218 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001219 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
Chris Lattner330245e2007-09-13 17:29:05 +00001220 // If this is a comparison against null, handle it.
1221 if (ICmpInst *SCI = dyn_cast<ICmpInst>(LoadUser)) {
1222 assert(isa<ConstantPointerNull>(SCI->getOperand(1)));
1223 // If we have a setcc of the loaded pointer, we can use a setcc of any
1224 // field.
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001225 Value *NPtr = GetHeapSROAValue(SCI->getOperand(0), 0,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001226 InsertedScalarizedValues, PHIsToRewrite);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001227
Owen Anderson333c4002009-07-09 23:48:35 +00001228 Value *New = new ICmpInst(SCI, SCI->getPredicate(), NPtr,
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001229 Constant::getNullValue(NPtr->getType()),
Owen Anderson333c4002009-07-09 23:48:35 +00001230 SCI->getName());
Chris Lattner330245e2007-09-13 17:29:05 +00001231 SCI->replaceAllUsesWith(New);
1232 SCI->eraseFromParent();
1233 return;
1234 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001235
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001236 // Handle 'getelementptr Ptr, Idx, i32 FieldNo ...'
Chris Lattnera637a8b2007-09-13 18:00:31 +00001237 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(LoadUser)) {
1238 assert(GEPI->getNumOperands() >= 3 && isa<ConstantInt>(GEPI->getOperand(2))
1239 && "Unexpected GEPI!");
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001240
Chris Lattnera637a8b2007-09-13 18:00:31 +00001241 // Load the pointer for this field.
1242 unsigned FieldNo = cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue();
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001243 Value *NewPtr = GetHeapSROAValue(GEPI->getOperand(0), FieldNo,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001244 InsertedScalarizedValues, PHIsToRewrite);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001245
Chris Lattnera637a8b2007-09-13 18:00:31 +00001246 // Create the new GEP idx vector.
1247 SmallVector<Value*, 8> GEPIdx;
1248 GEPIdx.push_back(GEPI->getOperand(1));
1249 GEPIdx.append(GEPI->op_begin()+3, GEPI->op_end());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001250
Jay Foada9203102011-07-25 09:48:08 +00001251 Value *NGEPI = GetElementPtrInst::Create(NewPtr, GEPIdx,
Gabor Greif051a9502008-04-06 20:25:17 +00001252 GEPI->getName(), GEPI);
Chris Lattnera637a8b2007-09-13 18:00:31 +00001253 GEPI->replaceAllUsesWith(NGEPI);
1254 GEPI->eraseFromParent();
1255 return;
1256 }
Chris Lattner309f20f2007-09-13 21:31:36 +00001257
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001258 // Recursively transform the users of PHI nodes. This will lazily create the
1259 // PHIs that are needed for individual elements. Keep track of what PHIs we
1260 // see in InsertedScalarizedValues so that we don't get infinite loops (very
1261 // antisocial). If the PHI is already in InsertedScalarizedValues, it has
1262 // already been seen first by another load, so its uses have already been
1263 // processed.
1264 PHINode *PN = cast<PHINode>(LoadUser);
Chris Lattnerc30a38f2011-07-21 06:21:31 +00001265 if (!InsertedScalarizedValues.insert(std::make_pair(PN,
1266 std::vector<Value*>())).second)
1267 return;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001268
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001269 // If this is the first time we've seen this PHI, recursively process all
1270 // users.
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001271 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end(); UI != E; ) {
1272 Instruction *User = cast<Instruction>(*UI++);
Chris Lattner7b550cc2009-11-06 04:27:31 +00001273 RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite);
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001274 }
Chris Lattner330245e2007-09-13 17:29:05 +00001275}
1276
Chris Lattner86395032006-09-30 23:32:09 +00001277/// RewriteUsesOfLoadForHeapSRoA - We are performing Heap SRoA on a global. Ptr
1278/// is a value loaded from the global. Eliminate all uses of Ptr, making them
1279/// use FieldGlobals instead. All uses of loaded values satisfy
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001280/// AllGlobalLoadUsesSimpleEnoughForHeapSRA.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001281static void RewriteUsesOfLoadForHeapSRoA(LoadInst *Load,
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001282 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001283 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001284 for (Value::use_iterator UI = Load->use_begin(), E = Load->use_end();
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001285 UI != E; ) {
1286 Instruction *User = cast<Instruction>(*UI++);
Chris Lattner7b550cc2009-11-06 04:27:31 +00001287 RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite);
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001288 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001289
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001290 if (Load->use_empty()) {
1291 Load->eraseFromParent();
1292 InsertedScalarizedValues.erase(Load);
1293 }
Chris Lattner86395032006-09-30 23:32:09 +00001294}
1295
Victor Hernandez83d63912009-09-18 22:35:49 +00001296/// PerformHeapAllocSRoA - CI is an allocation of an array of structures. Break
1297/// it up into multiple allocations of arrays of the fields.
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001298static GlobalVariable *PerformHeapAllocSRoA(GlobalVariable *GV, CallInst *CI,
Nick Lewyckybc384a12012-02-05 19:48:37 +00001299 Value *NElems, TargetData *TD) {
David Greene3215b0e2010-01-05 01:28:05 +00001300 DEBUG(dbgs() << "SROA HEAP ALLOC: " << *GV << " MALLOC = " << *CI << '\n');
Nick Lewyckybc384a12012-02-05 19:48:37 +00001301 Type *MAT = getMallocAllocatedType(CI);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001302 StructType *STy = cast<StructType>(MAT);
Victor Hernandez83d63912009-09-18 22:35:49 +00001303
1304 // There is guaranteed to be at least one use of the malloc (storing
1305 // it into GV). If there are other uses, change them to be uses of
1306 // the global to simplify later code. This also deletes the store
1307 // into GV.
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001308 ReplaceUsesOfMallocWithGlobal(CI, GV);
1309
Victor Hernandez83d63912009-09-18 22:35:49 +00001310 // Okay, at this point, there are no users of the malloc. Insert N
1311 // new mallocs at the same place as CI, and N globals.
1312 std::vector<Value*> FieldGlobals;
1313 std::vector<Value*> FieldMallocs;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001314
Victor Hernandez83d63912009-09-18 22:35:49 +00001315 for (unsigned FieldNo = 0, e = STy->getNumElements(); FieldNo != e;++FieldNo){
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001316 Type *FieldTy = STy->getElementType(FieldNo);
1317 PointerType *PFieldTy = PointerType::getUnqual(FieldTy);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001318
Victor Hernandez83d63912009-09-18 22:35:49 +00001319 GlobalVariable *NGV =
1320 new GlobalVariable(*GV->getParent(),
1321 PFieldTy, false, GlobalValue::InternalLinkage,
1322 Constant::getNullValue(PFieldTy),
1323 GV->getName() + ".f" + Twine(FieldNo), GV,
Hans Wennborgce718ff2012-06-23 11:37:03 +00001324 GV->getThreadLocalMode());
Victor Hernandez83d63912009-09-18 22:35:49 +00001325 FieldGlobals.push_back(NGV);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001326
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001327 unsigned TypeSize = TD->getTypeAllocSize(FieldTy);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001328 if (StructType *ST = dyn_cast<StructType>(FieldTy))
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001329 TypeSize = TD->getStructLayout(ST)->getSizeInBytes();
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001330 Type *IntPtrTy = TD->getIntPtrType(CI->getContext());
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001331 Value *NMI = CallInst::CreateMalloc(CI, IntPtrTy, FieldTy,
1332 ConstantInt::get(IntPtrTy, TypeSize),
Chris Lattner5a30a852010-07-12 00:57:28 +00001333 NElems, 0,
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001334 CI->getName() + ".f" + Twine(FieldNo));
Chris Lattner3f5e0b82010-02-26 18:23:13 +00001335 FieldMallocs.push_back(NMI);
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001336 new StoreInst(NMI, NGV, CI);
Victor Hernandez83d63912009-09-18 22:35:49 +00001337 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001338
Victor Hernandez83d63912009-09-18 22:35:49 +00001339 // The tricky aspect of this transformation is handling the case when malloc
1340 // fails. In the original code, malloc failing would set the result pointer
1341 // of malloc to null. In this case, some mallocs could succeed and others
1342 // could fail. As such, we emit code that looks like this:
1343 // F0 = malloc(field0)
1344 // F1 = malloc(field1)
1345 // F2 = malloc(field2)
1346 // if (F0 == 0 || F1 == 0 || F2 == 0) {
1347 // if (F0) { free(F0); F0 = 0; }
1348 // if (F1) { free(F1); F1 = 0; }
1349 // if (F2) { free(F2); F2 = 0; }
1350 // }
Victor Hernandez8e345a12009-11-10 08:32:25 +00001351 // The malloc can also fail if its argument is too large.
Gabor Greif9e4f2432010-06-24 14:42:01 +00001352 Constant *ConstantZero = ConstantInt::get(CI->getArgOperand(0)->getType(), 0);
1353 Value *RunningOr = new ICmpInst(CI, ICmpInst::ICMP_SLT, CI->getArgOperand(0),
Victor Hernandez8e345a12009-11-10 08:32:25 +00001354 ConstantZero, "isneg");
Victor Hernandez83d63912009-09-18 22:35:49 +00001355 for (unsigned i = 0, e = FieldMallocs.size(); i != e; ++i) {
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001356 Value *Cond = new ICmpInst(CI, ICmpInst::ICMP_EQ, FieldMallocs[i],
1357 Constant::getNullValue(FieldMallocs[i]->getType()),
1358 "isnull");
Victor Hernandez8e345a12009-11-10 08:32:25 +00001359 RunningOr = BinaryOperator::CreateOr(RunningOr, Cond, "tmp", CI);
Victor Hernandez83d63912009-09-18 22:35:49 +00001360 }
1361
1362 // Split the basic block at the old malloc.
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001363 BasicBlock *OrigBB = CI->getParent();
1364 BasicBlock *ContBB = OrigBB->splitBasicBlock(CI, "malloc_cont");
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001365
Victor Hernandez83d63912009-09-18 22:35:49 +00001366 // Create the block to check the first condition. Put all these blocks at the
1367 // end of the function as they are unlikely to be executed.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001368 BasicBlock *NullPtrBlock = BasicBlock::Create(OrigBB->getContext(),
1369 "malloc_ret_null",
Victor Hernandez83d63912009-09-18 22:35:49 +00001370 OrigBB->getParent());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001371
Victor Hernandez83d63912009-09-18 22:35:49 +00001372 // Remove the uncond branch from OrigBB to ContBB, turning it into a cond
1373 // branch on RunningOr.
1374 OrigBB->getTerminator()->eraseFromParent();
1375 BranchInst::Create(NullPtrBlock, ContBB, RunningOr, OrigBB);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001376
Victor Hernandez83d63912009-09-18 22:35:49 +00001377 // Within the NullPtrBlock, we need to emit a comparison and branch for each
1378 // pointer, because some may be null while others are not.
1379 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
1380 Value *GVVal = new LoadInst(FieldGlobals[i], "tmp", NullPtrBlock);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001381 Value *Cmp = new ICmpInst(*NullPtrBlock, ICmpInst::ICMP_NE, GVVal,
Benjamin Kramera9390a42011-09-27 20:39:19 +00001382 Constant::getNullValue(GVVal->getType()));
Chris Lattner7b550cc2009-11-06 04:27:31 +00001383 BasicBlock *FreeBlock = BasicBlock::Create(Cmp->getContext(), "free_it",
Victor Hernandez83d63912009-09-18 22:35:49 +00001384 OrigBB->getParent());
Chris Lattner7b550cc2009-11-06 04:27:31 +00001385 BasicBlock *NextBlock = BasicBlock::Create(Cmp->getContext(), "next",
Victor Hernandez83d63912009-09-18 22:35:49 +00001386 OrigBB->getParent());
Victor Hernandez66284e02009-10-24 04:23:03 +00001387 Instruction *BI = BranchInst::Create(FreeBlock, NextBlock,
1388 Cmp, NullPtrBlock);
Victor Hernandez83d63912009-09-18 22:35:49 +00001389
1390 // Fill in FreeBlock.
Victor Hernandez66284e02009-10-24 04:23:03 +00001391 CallInst::CreateFree(GVVal, BI);
Victor Hernandez83d63912009-09-18 22:35:49 +00001392 new StoreInst(Constant::getNullValue(GVVal->getType()), FieldGlobals[i],
1393 FreeBlock);
1394 BranchInst::Create(NextBlock, FreeBlock);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001395
Victor Hernandez83d63912009-09-18 22:35:49 +00001396 NullPtrBlock = NextBlock;
1397 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001398
Victor Hernandez83d63912009-09-18 22:35:49 +00001399 BranchInst::Create(ContBB, NullPtrBlock);
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001400
1401 // CI is no longer needed, remove it.
Victor Hernandez83d63912009-09-18 22:35:49 +00001402 CI->eraseFromParent();
1403
1404 /// InsertedScalarizedLoads - As we process loads, if we can't immediately
1405 /// update all uses of the load, keep track of what scalarized loads are
1406 /// inserted for a given load.
1407 DenseMap<Value*, std::vector<Value*> > InsertedScalarizedValues;
1408 InsertedScalarizedValues[GV] = FieldGlobals;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001409
Victor Hernandez83d63912009-09-18 22:35:49 +00001410 std::vector<std::pair<PHINode*, unsigned> > PHIsToRewrite;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001411
Victor Hernandez83d63912009-09-18 22:35:49 +00001412 // Okay, the malloc site is completely handled. All of the uses of GV are now
1413 // loads, and all uses of those loads are simple. Rewrite them to use loads
1414 // of the per-field globals instead.
1415 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI != E;) {
1416 Instruction *User = cast<Instruction>(*UI++);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001417
Victor Hernandez83d63912009-09-18 22:35:49 +00001418 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Chris Lattner7b550cc2009-11-06 04:27:31 +00001419 RewriteUsesOfLoadForHeapSRoA(LI, InsertedScalarizedValues, PHIsToRewrite);
Victor Hernandez83d63912009-09-18 22:35:49 +00001420 continue;
1421 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001422
Victor Hernandez83d63912009-09-18 22:35:49 +00001423 // Must be a store of null.
1424 StoreInst *SI = cast<StoreInst>(User);
1425 assert(isa<ConstantPointerNull>(SI->getOperand(0)) &&
1426 "Unexpected heap-sra user!");
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001427
Victor Hernandez83d63912009-09-18 22:35:49 +00001428 // Insert a store of null into each global.
1429 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001430 PointerType *PT = cast<PointerType>(FieldGlobals[i]->getType());
Victor Hernandez83d63912009-09-18 22:35:49 +00001431 Constant *Null = Constant::getNullValue(PT->getElementType());
1432 new StoreInst(Null, FieldGlobals[i], SI);
1433 }
1434 // Erase the original store.
1435 SI->eraseFromParent();
1436 }
1437
1438 // While we have PHIs that are interesting to rewrite, do it.
1439 while (!PHIsToRewrite.empty()) {
1440 PHINode *PN = PHIsToRewrite.back().first;
1441 unsigned FieldNo = PHIsToRewrite.back().second;
1442 PHIsToRewrite.pop_back();
1443 PHINode *FieldPN = cast<PHINode>(InsertedScalarizedValues[PN][FieldNo]);
1444 assert(FieldPN->getNumIncomingValues() == 0 &&"Already processed this phi");
1445
1446 // Add all the incoming values. This can materialize more phis.
1447 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1448 Value *InVal = PN->getIncomingValue(i);
1449 InVal = GetHeapSROAValue(InVal, FieldNo, InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001450 PHIsToRewrite);
Victor Hernandez83d63912009-09-18 22:35:49 +00001451 FieldPN->addIncoming(InVal, PN->getIncomingBlock(i));
1452 }
1453 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001454
Victor Hernandez83d63912009-09-18 22:35:49 +00001455 // Drop all inter-phi links and any loads that made it this far.
1456 for (DenseMap<Value*, std::vector<Value*> >::iterator
1457 I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
1458 I != E; ++I) {
1459 if (PHINode *PN = dyn_cast<PHINode>(I->first))
1460 PN->dropAllReferences();
1461 else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
1462 LI->dropAllReferences();
1463 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001464
Victor Hernandez83d63912009-09-18 22:35:49 +00001465 // Delete all the phis and loads now that inter-references are dead.
1466 for (DenseMap<Value*, std::vector<Value*> >::iterator
1467 I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
1468 I != E; ++I) {
1469 if (PHINode *PN = dyn_cast<PHINode>(I->first))
1470 PN->eraseFromParent();
1471 else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
1472 LI->eraseFromParent();
1473 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001474
Victor Hernandez83d63912009-09-18 22:35:49 +00001475 // The old global is now dead, remove it.
1476 GV->eraseFromParent();
1477
1478 ++NumHeapSRA;
1479 return cast<GlobalVariable>(FieldGlobals[0]);
1480}
1481
Chris Lattnere61d0a62008-12-15 21:02:25 +00001482/// TryToOptimizeStoreOfMallocToGlobal - This function is called when we see a
1483/// pointer global variable with a single value stored it that is a malloc or
1484/// cast of malloc.
1485static bool TryToOptimizeStoreOfMallocToGlobal(GlobalVariable *GV,
Victor Hernandez83d63912009-09-18 22:35:49 +00001486 CallInst *CI,
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001487 Type *AllocTy,
Nick Lewyckyfad4d402012-02-05 19:56:38 +00001488 AtomicOrdering Ordering,
Victor Hernandez83d63912009-09-18 22:35:49 +00001489 Module::global_iterator &GVI,
Nick Lewycky6a577f82012-02-12 01:13:18 +00001490 TargetData *TD,
1491 TargetLibraryInfo *TLI) {
Evan Cheng86cd4452010-04-14 20:52:55 +00001492 if (!TD)
1493 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001494
Victor Hernandez83d63912009-09-18 22:35:49 +00001495 // If this is a malloc of an abstract type, don't touch it.
1496 if (!AllocTy->isSized())
1497 return false;
1498
1499 // We can't optimize this global unless all uses of it are *known* to be
1500 // of the malloc value, not of the null initializer value (consider a use
1501 // that compares the global's value against zero to see if the malloc has
1502 // been reached). To do this, we check to see if all uses of the global
1503 // would trap if the global were null: this proves that they must all
1504 // happen after the malloc.
1505 if (!AllUsesOfLoadedValueWillTrapIfNull(GV))
1506 return false;
1507
1508 // We can't optimize this if the malloc itself is used in a complex way,
1509 // for example, being stored into multiple globals. This allows the
Nick Lewyckybc384a12012-02-05 19:48:37 +00001510 // malloc to be stored into the specified global, loaded icmp'd, and
Victor Hernandez83d63912009-09-18 22:35:49 +00001511 // GEP'd. These are all things we could transform to using the global
1512 // for.
Evan Cheng86cd4452010-04-14 20:52:55 +00001513 SmallPtrSet<const PHINode*, 8> PHIs;
1514 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(CI, GV, PHIs))
1515 return false;
Victor Hernandez83d63912009-09-18 22:35:49 +00001516
1517 // If we have a global that is only initialized with a fixed size malloc,
1518 // transform the program to use global memory instead of malloc'd memory.
1519 // This eliminates dynamic allocation, avoids an indirection accessing the
1520 // data, and exposes the resultant global to further GlobalOpt.
Victor Hernandez8db42d22009-10-16 23:12:25 +00001521 // We cannot optimize the malloc if we cannot determine malloc array size.
Evan Cheng86cd4452010-04-14 20:52:55 +00001522 Value *NElems = getMallocArraySize(CI, TD, true);
1523 if (!NElems)
1524 return false;
Victor Hernandez83d63912009-09-18 22:35:49 +00001525
Evan Cheng86cd4452010-04-14 20:52:55 +00001526 if (ConstantInt *NElements = dyn_cast<ConstantInt>(NElems))
1527 // Restrict this transformation to only working on small allocations
1528 // (2048 bytes currently), as we don't want to introduce a 16M global or
1529 // something.
1530 if (NElements->getZExtValue() * TD->getTypeAllocSize(AllocTy) < 2048) {
Nick Lewycky6a577f82012-02-12 01:13:18 +00001531 GVI = OptimizeGlobalAddressOfMalloc(GV, CI, AllocTy, NElements, TD, TLI);
Evan Cheng86cd4452010-04-14 20:52:55 +00001532 return true;
Victor Hernandez83d63912009-09-18 22:35:49 +00001533 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001534
Evan Cheng86cd4452010-04-14 20:52:55 +00001535 // If the allocation is an array of structures, consider transforming this
1536 // into multiple malloc'd arrays, one for each field. This is basically
1537 // SRoA for malloc'd memory.
1538
Nick Lewyckyfad4d402012-02-05 19:56:38 +00001539 if (Ordering != NotAtomic)
1540 return false;
1541
Evan Cheng86cd4452010-04-14 20:52:55 +00001542 // If this is an allocation of a fixed size array of structs, analyze as a
1543 // variable size array. malloc [100 x struct],1 -> malloc struct, 100
Gabor Greif9e4f2432010-06-24 14:42:01 +00001544 if (NElems == ConstantInt::get(CI->getArgOperand(0)->getType(), 1))
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001545 if (ArrayType *AT = dyn_cast<ArrayType>(AllocTy))
Evan Cheng86cd4452010-04-14 20:52:55 +00001546 AllocTy = AT->getElementType();
Gabor Greif9e4f2432010-06-24 14:42:01 +00001547
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001548 StructType *AllocSTy = dyn_cast<StructType>(AllocTy);
Evan Cheng86cd4452010-04-14 20:52:55 +00001549 if (!AllocSTy)
1550 return false;
1551
1552 // This the structure has an unreasonable number of fields, leave it
1553 // alone.
1554 if (AllocSTy->getNumElements() <= 16 && AllocSTy->getNumElements() != 0 &&
1555 AllGlobalLoadUsesSimpleEnoughForHeapSRA(GV, CI)) {
1556
1557 // If this is a fixed size array, transform the Malloc to be an alloc of
1558 // structs. malloc [100 x struct],1 -> malloc struct, 100
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001559 if (ArrayType *AT = dyn_cast<ArrayType>(getMallocAllocatedType(CI))) {
1560 Type *IntPtrTy = TD->getIntPtrType(CI->getContext());
Evan Cheng86cd4452010-04-14 20:52:55 +00001561 unsigned TypeSize = TD->getStructLayout(AllocSTy)->getSizeInBytes();
1562 Value *AllocSize = ConstantInt::get(IntPtrTy, TypeSize);
1563 Value *NumElements = ConstantInt::get(IntPtrTy, AT->getNumElements());
1564 Instruction *Malloc = CallInst::CreateMalloc(CI, IntPtrTy, AllocSTy,
1565 AllocSize, NumElements,
Chris Lattner5a30a852010-07-12 00:57:28 +00001566 0, CI->getName());
Evan Cheng86cd4452010-04-14 20:52:55 +00001567 Instruction *Cast = new BitCastInst(Malloc, CI->getType(), "tmp", CI);
1568 CI->replaceAllUsesWith(Cast);
1569 CI->eraseFromParent();
Nuno Lopeseb7c6862012-06-22 00:25:01 +00001570 if (BitCastInst *BCI = dyn_cast<BitCastInst>(Malloc))
1571 CI = cast<CallInst>(BCI->getOperand(0));
1572 else
Nuno Lopescd88efe2012-06-22 00:29:58 +00001573 CI = cast<CallInst>(Malloc);
Evan Cheng86cd4452010-04-14 20:52:55 +00001574 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001575
Nick Lewyckybc384a12012-02-05 19:48:37 +00001576 GVI = PerformHeapAllocSRoA(GV, CI, getMallocArraySize(CI, TD, true), TD);
Evan Cheng86cd4452010-04-14 20:52:55 +00001577 return true;
Victor Hernandez83d63912009-09-18 22:35:49 +00001578 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001579
Victor Hernandez83d63912009-09-18 22:35:49 +00001580 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001581}
Victor Hernandez83d63912009-09-18 22:35:49 +00001582
Chris Lattner9b34a612004-10-09 21:48:45 +00001583// OptimizeOnceStoredGlobal - Try to optimize globals based on the knowledge
1584// that only one value (besides its initializer) is ever stored to the global.
Chris Lattner30ba5692004-10-11 05:54:41 +00001585static bool OptimizeOnceStoredGlobal(GlobalVariable *GV, Value *StoredOnceVal,
Nick Lewyckyfad4d402012-02-05 19:56:38 +00001586 AtomicOrdering Ordering,
Chris Lattner7f8897f2006-08-27 22:42:52 +00001587 Module::global_iterator &GVI,
Nick Lewycky6a577f82012-02-12 01:13:18 +00001588 TargetData *TD, TargetLibraryInfo *TLI) {
Chris Lattner344b41c2008-12-15 21:20:32 +00001589 // Ignore no-op GEPs and bitcasts.
1590 StoredOnceVal = StoredOnceVal->stripPointerCasts();
Chris Lattner9b34a612004-10-09 21:48:45 +00001591
Chris Lattner708148e2004-10-10 23:14:11 +00001592 // If we are dealing with a pointer global that is initialized to null and
1593 // only has one (non-null) value stored into it, then we can optimize any
1594 // users of the loaded value (often calls and loads) that would trap if the
1595 // value was null.
Duncan Sands1df98592010-02-16 11:11:14 +00001596 if (GV->getInitializer()->getType()->isPointerTy() &&
Chris Lattner9b34a612004-10-09 21:48:45 +00001597 GV->getInitializer()->isNullValue()) {
Chris Lattner708148e2004-10-10 23:14:11 +00001598 if (Constant *SOVC = dyn_cast<Constant>(StoredOnceVal)) {
1599 if (GV->getInitializer()->getType() != SOVC->getType())
Chris Lattner98a42b22011-05-22 07:15:13 +00001600 SOVC = ConstantExpr::getBitCast(SOVC, GV->getInitializer()->getType());
Misha Brukmanfd939082005-04-21 23:48:37 +00001601
Chris Lattner708148e2004-10-10 23:14:11 +00001602 // Optimize away any trapping uses of the loaded value.
Nick Lewycky6a577f82012-02-12 01:13:18 +00001603 if (OptimizeAwayTrappingUsesOfLoads(GV, SOVC, TD, TLI))
Chris Lattner8be80122004-10-10 17:07:12 +00001604 return true;
Victor Hernandez83d63912009-09-18 22:35:49 +00001605 } else if (CallInst *CI = extractMallocCall(StoredOnceVal)) {
Nick Lewyckybc384a12012-02-05 19:48:37 +00001606 Type *MallocType = getMallocAllocatedType(CI);
Nick Lewycky6a577f82012-02-12 01:13:18 +00001607 if (MallocType &&
1608 TryToOptimizeStoreOfMallocToGlobal(GV, CI, MallocType, Ordering, GVI,
1609 TD, TLI))
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001610 return true;
Chris Lattner708148e2004-10-10 23:14:11 +00001611 }
Chris Lattner9b34a612004-10-09 21:48:45 +00001612 }
Chris Lattner30ba5692004-10-11 05:54:41 +00001613
Chris Lattner9b34a612004-10-09 21:48:45 +00001614 return false;
1615}
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001616
Chris Lattner58e44f42008-01-14 01:17:44 +00001617/// TryToShrinkGlobalToBoolean - At this point, we have learned that the only
1618/// two values ever stored into GV are its initializer and OtherVal. See if we
1619/// can shrink the global into a boolean and select between the two values
1620/// whenever it is used. This exposes the values to other scalar optimizations.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001621static bool TryToShrinkGlobalToBoolean(GlobalVariable *GV, Constant *OtherVal) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001622 Type *GVElType = GV->getType()->getElementType();
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001623
Chris Lattner58e44f42008-01-14 01:17:44 +00001624 // If GVElType is already i1, it is already shrunk. If the type of the GV is
Chris Lattner6f6923f2009-03-07 23:32:02 +00001625 // an FP value, pointer or vector, don't do this optimization because a select
1626 // between them is very expensive and unlikely to lead to later
1627 // simplification. In these cases, we typically end up with "cond ? v1 : v2"
1628 // where v1 and v2 both require constant pool loads, a big loss.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001629 if (GVElType == Type::getInt1Ty(GV->getContext()) ||
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001630 GVElType->isFloatingPointTy() ||
Duncan Sands1df98592010-02-16 11:11:14 +00001631 GVElType->isPointerTy() || GVElType->isVectorTy())
Chris Lattner58e44f42008-01-14 01:17:44 +00001632 return false;
Gabor Greifaaaaa022010-07-12 14:13:15 +00001633
Chris Lattner58e44f42008-01-14 01:17:44 +00001634 // Walk the use list of the global seeing if all the uses are load or store.
1635 // If there is anything else, bail out.
Gabor Greifaaaaa022010-07-12 14:13:15 +00001636 for (Value::use_iterator I = GV->use_begin(), E = GV->use_end(); I != E; ++I){
1637 User *U = *I;
1638 if (!isa<LoadInst>(U) && !isa<StoreInst>(U))
Chris Lattner58e44f42008-01-14 01:17:44 +00001639 return false;
Gabor Greifaaaaa022010-07-12 14:13:15 +00001640 }
1641
David Greene3215b0e2010-01-05 01:28:05 +00001642 DEBUG(dbgs() << " *** SHRINKING TO BOOL: " << *GV);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001643
Chris Lattner96a86b22004-12-12 05:53:50 +00001644 // Create the new global, initializing it to false.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001645 GlobalVariable *NewGV = new GlobalVariable(Type::getInt1Ty(GV->getContext()),
1646 false,
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001647 GlobalValue::InternalLinkage,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001648 ConstantInt::getFalse(GV->getContext()),
Nick Lewycky0e670df2009-05-03 03:49:08 +00001649 GV->getName()+".b",
Hans Wennborgce718ff2012-06-23 11:37:03 +00001650 GV->getThreadLocalMode());
Chris Lattner96a86b22004-12-12 05:53:50 +00001651 GV->getParent()->getGlobalList().insert(GV, NewGV);
1652
1653 Constant *InitVal = GV->getInitializer();
Chris Lattner7b550cc2009-11-06 04:27:31 +00001654 assert(InitVal->getType() != Type::getInt1Ty(GV->getContext()) &&
Owen Anderson1d0be152009-08-13 21:58:54 +00001655 "No reason to shrink to bool!");
Chris Lattner96a86b22004-12-12 05:53:50 +00001656
1657 // If initialized to zero and storing one into the global, we can use a cast
1658 // instead of a select to synthesize the desired value.
1659 bool IsOneZero = false;
1660 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal))
Reid Spencercae57542007-03-02 00:28:52 +00001661 IsOneZero = InitVal->isNullValue() && CI->isOne();
Chris Lattner96a86b22004-12-12 05:53:50 +00001662
1663 while (!GV->use_empty()) {
Devang Patel771281f2009-03-06 01:39:36 +00001664 Instruction *UI = cast<Instruction>(GV->use_back());
1665 if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
Chris Lattner96a86b22004-12-12 05:53:50 +00001666 // Change the store into a boolean store.
1667 bool StoringOther = SI->getOperand(0) == OtherVal;
1668 // Only do this if we weren't storing a loaded value.
Chris Lattner38c25562004-12-12 19:34:41 +00001669 Value *StoreVal;
Chris Lattner96a86b22004-12-12 05:53:50 +00001670 if (StoringOther || SI->getOperand(0) == InitVal)
Chris Lattner7b550cc2009-11-06 04:27:31 +00001671 StoreVal = ConstantInt::get(Type::getInt1Ty(GV->getContext()),
1672 StoringOther);
Chris Lattner38c25562004-12-12 19:34:41 +00001673 else {
1674 // Otherwise, we are storing a previously loaded copy. To do this,
1675 // change the copy from copying the original value to just copying the
1676 // bool.
1677 Instruction *StoredVal = cast<Instruction>(SI->getOperand(0));
1678
Gabor Greif9e4f2432010-06-24 14:42:01 +00001679 // If we've already replaced the input, StoredVal will be a cast or
Chris Lattner38c25562004-12-12 19:34:41 +00001680 // select instruction. If not, it will be a load of the original
1681 // global.
1682 if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
1683 assert(LI->getOperand(0) == GV && "Not a copy!");
1684 // Insert a new load, to preserve the saved value.
Nick Lewyckyfad4d402012-02-05 19:56:38 +00001685 StoreVal = new LoadInst(NewGV, LI->getName()+".b", false, 0,
1686 LI->getOrdering(), LI->getSynchScope(), LI);
Chris Lattner38c25562004-12-12 19:34:41 +00001687 } else {
1688 assert((isa<CastInst>(StoredVal) || isa<SelectInst>(StoredVal)) &&
1689 "This is not a form that we understand!");
1690 StoreVal = StoredVal->getOperand(0);
1691 assert(isa<LoadInst>(StoreVal) && "Not a load of NewGV!");
1692 }
1693 }
Nick Lewyckyfad4d402012-02-05 19:56:38 +00001694 new StoreInst(StoreVal, NewGV, false, 0,
1695 SI->getOrdering(), SI->getSynchScope(), SI);
Devang Patel771281f2009-03-06 01:39:36 +00001696 } else {
Chris Lattner96a86b22004-12-12 05:53:50 +00001697 // Change the load into a load of bool then a select.
Devang Patel771281f2009-03-06 01:39:36 +00001698 LoadInst *LI = cast<LoadInst>(UI);
Nick Lewyckyfad4d402012-02-05 19:56:38 +00001699 LoadInst *NLI = new LoadInst(NewGV, LI->getName()+".b", false, 0,
1700 LI->getOrdering(), LI->getSynchScope(), LI);
Chris Lattner96a86b22004-12-12 05:53:50 +00001701 Value *NSI;
1702 if (IsOneZero)
Chris Lattner046800a2007-02-11 01:08:35 +00001703 NSI = new ZExtInst(NLI, LI->getType(), "", LI);
Misha Brukmanfd939082005-04-21 23:48:37 +00001704 else
Gabor Greif051a9502008-04-06 20:25:17 +00001705 NSI = SelectInst::Create(NLI, OtherVal, InitVal, "", LI);
Chris Lattner046800a2007-02-11 01:08:35 +00001706 NSI->takeName(LI);
Chris Lattner96a86b22004-12-12 05:53:50 +00001707 LI->replaceAllUsesWith(NSI);
Devang Patel771281f2009-03-06 01:39:36 +00001708 }
1709 UI->eraseFromParent();
Chris Lattner96a86b22004-12-12 05:53:50 +00001710 }
1711
1712 GV->eraseFromParent();
Chris Lattner58e44f42008-01-14 01:17:44 +00001713 return true;
Chris Lattner96a86b22004-12-12 05:53:50 +00001714}
1715
1716
Nick Lewyckydb292a62012-02-12 00:52:26 +00001717/// ProcessGlobal - Analyze the specified global variable and optimize it if
1718/// possible. If we make a change, return true.
Rafael Espindolac4440e32011-01-19 16:32:21 +00001719bool GlobalOpt::ProcessGlobal(GlobalVariable *GV,
1720 Module::global_iterator &GVI) {
Rafael Espindola03977292012-06-14 22:48:13 +00001721 if (!GV->isDiscardableIfUnused())
Rafael Espindolac4440e32011-01-19 16:32:21 +00001722 return false;
1723
1724 // Do more involved optimizations if the global is internal.
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001725 GV->removeDeadConstantUsers();
1726
1727 if (GV->use_empty()) {
David Greene3215b0e2010-01-05 01:28:05 +00001728 DEBUG(dbgs() << "GLOBAL DEAD: " << *GV);
Chris Lattner7a7ed022004-10-16 18:09:00 +00001729 GV->eraseFromParent();
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001730 ++NumDeleted;
1731 return true;
1732 }
1733
Rafael Espindola2f135d42012-06-15 18:00:24 +00001734 if (!GV->hasLocalLinkage())
1735 return false;
1736
Rafael Espindolac4440e32011-01-19 16:32:21 +00001737 SmallPtrSet<const PHINode*, 16> PHIUsers;
1738 GlobalStatus GS;
1739
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001740 if (AnalyzeGlobal(GV, GS, PHIUsers))
1741 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001742
Rafael Espindolac4440e32011-01-19 16:32:21 +00001743 if (!GS.isCompared && !GV->hasUnnamedAddr()) {
1744 GV->setUnnamedAddr(true);
1745 NumUnnamed++;
1746 }
1747
1748 if (GV->isConstant() || !GV->hasInitializer())
1749 return false;
1750
1751 return ProcessInternalGlobal(GV, GVI, PHIUsers, GS);
1752}
1753
1754/// ProcessInternalGlobal - Analyze the specified global variable and optimize
1755/// it if possible. If we make a change, return true.
1756bool GlobalOpt::ProcessInternalGlobal(GlobalVariable *GV,
1757 Module::global_iterator &GVI,
Nick Lewyckydb292a62012-02-12 00:52:26 +00001758 const SmallPtrSet<const PHINode*, 16> &PHIUsers,
Rafael Espindolac4440e32011-01-19 16:32:21 +00001759 const GlobalStatus &GS) {
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001760 // If this is a first class global and has only one accessing function
1761 // and this function is main (which we know is not recursive we can make
1762 // this global a local variable) we replace the global with a local alloca
1763 // in this function.
1764 //
1765 // NOTE: It doesn't make sense to promote non single-value types since we
1766 // are just replacing static memory to stack memory.
1767 //
1768 // If the global is in different address space, don't bring it to stack.
1769 if (!GS.HasMultipleAccessingFunctions &&
1770 GS.AccessingFunction && !GS.HasNonInstructionUser &&
1771 GV->getType()->getElementType()->isSingleValueType() &&
1772 GS.AccessingFunction->getName() == "main" &&
1773 GS.AccessingFunction->hasExternalLinkage() &&
1774 GV->getType()->getAddressSpace() == 0) {
1775 DEBUG(dbgs() << "LOCALIZING GLOBAL: " << *GV);
Nick Lewyckybc384a12012-02-05 19:48:37 +00001776 Instruction &FirstI = const_cast<Instruction&>(*GS.AccessingFunction
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001777 ->getEntryBlock().begin());
Nick Lewyckybc384a12012-02-05 19:48:37 +00001778 Type *ElemTy = GV->getType()->getElementType();
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001779 // FIXME: Pass Global's alignment when globals have alignment
Nick Lewyckybc384a12012-02-05 19:48:37 +00001780 AllocaInst *Alloca = new AllocaInst(ElemTy, NULL, GV->getName(), &FirstI);
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001781 if (!isa<UndefValue>(GV->getInitializer()))
1782 new StoreInst(GV->getInitializer(), Alloca, &FirstI);
Misha Brukmanfd939082005-04-21 23:48:37 +00001783
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001784 GV->replaceAllUsesWith(Alloca);
1785 GV->eraseFromParent();
1786 ++NumLocalized;
1787 return true;
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001788 }
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001789
1790 // If the global is never loaded (but may be stored to), it is dead.
1791 // Delete it now.
1792 if (!GS.isLoaded) {
1793 DEBUG(dbgs() << "GLOBAL NEVER LOADED: " << *GV);
1794
1795 // Delete any stores we can find to the global. We may not be able to
1796 // make it completely dead though.
Nick Lewycky6a577f82012-02-12 01:13:18 +00001797 bool Changed = CleanupConstantGlobalUsers(GV, GV->getInitializer(),
1798 TD, TLI);
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001799
1800 // If the global is dead now, delete it.
1801 if (GV->use_empty()) {
1802 GV->eraseFromParent();
1803 ++NumDeleted;
1804 Changed = true;
1805 }
1806 return Changed;
1807
1808 } else if (GS.StoredType <= GlobalStatus::isInitializerStored) {
1809 DEBUG(dbgs() << "MARKING CONSTANT: " << *GV);
1810 GV->setConstant(true);
1811
1812 // Clean up any obviously simplifiable users now.
Nick Lewycky6a577f82012-02-12 01:13:18 +00001813 CleanupConstantGlobalUsers(GV, GV->getInitializer(), TD, TLI);
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001814
1815 // If the global is dead now, just nuke it.
1816 if (GV->use_empty()) {
1817 DEBUG(dbgs() << " *** Marking constant allowed us to simplify "
1818 << "all users and delete global!\n");
1819 GV->eraseFromParent();
1820 ++NumDeleted;
1821 }
1822
1823 ++NumMarked;
1824 return true;
1825 } else if (!GV->getInitializer()->getType()->isSingleValueType()) {
1826 if (TargetData *TD = getAnalysisIfAvailable<TargetData>())
1827 if (GlobalVariable *FirstNewGV = SRAGlobal(GV, *TD)) {
1828 GVI = FirstNewGV; // Don't skip the newly produced globals!
1829 return true;
1830 }
1831 } else if (GS.StoredType == GlobalStatus::isStoredOnce) {
1832 // If the initial value for the global was an undef value, and if only
1833 // one other value was stored into it, we can just change the
1834 // initializer to be the stored value, then delete all stores to the
1835 // global. This allows us to mark it constant.
1836 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
1837 if (isa<UndefValue>(GV->getInitializer())) {
1838 // Change the initial value here.
1839 GV->setInitializer(SOVConstant);
1840
1841 // Clean up any obviously simplifiable users now.
Nick Lewycky6a577f82012-02-12 01:13:18 +00001842 CleanupConstantGlobalUsers(GV, GV->getInitializer(), TD, TLI);
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001843
1844 if (GV->use_empty()) {
1845 DEBUG(dbgs() << " *** Substituting initializer allowed us to "
1846 << "simplify all users and delete global!\n");
1847 GV->eraseFromParent();
1848 ++NumDeleted;
1849 } else {
1850 GVI = GV;
1851 }
1852 ++NumSubstitute;
1853 return true;
1854 }
1855
1856 // Try to optimize globals based on the knowledge that only one value
1857 // (besides its initializer) is ever stored to the global.
Nick Lewyckyfad4d402012-02-05 19:56:38 +00001858 if (OptimizeOnceStoredGlobal(GV, GS.StoredOnceValue, GS.Ordering, GVI,
Nick Lewycky6a577f82012-02-12 01:13:18 +00001859 TD, TLI))
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001860 return true;
1861
1862 // Otherwise, if the global was not a boolean, we can shrink it to be a
1863 // boolean.
1864 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
1865 if (TryToShrinkGlobalToBoolean(GV, SOVConstant)) {
1866 ++NumShrunkToBool;
1867 return true;
1868 }
1869 }
1870
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001871 return false;
1872}
1873
Chris Lattnerfb217ad2005-05-08 22:18:06 +00001874/// ChangeCalleesToFastCall - Walk all of the direct calls of the specified
1875/// function, changing them to FastCC.
1876static void ChangeCalleesToFastCall(Function *F) {
1877 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
Jay Foadb7454fd2012-05-12 08:30:16 +00001878 if (isa<BlockAddress>(*UI))
1879 continue;
Duncan Sands548448a2008-02-18 17:32:13 +00001880 CallSite User(cast<Instruction>(*UI));
1881 User.setCallingConv(CallingConv::Fast);
Chris Lattnerfb217ad2005-05-08 22:18:06 +00001882 }
1883}
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001884
Devang Patel05988662008-09-25 21:00:45 +00001885static AttrListPtr StripNest(const AttrListPtr &Attrs) {
Chris Lattner58d74912008-03-12 17:45:29 +00001886 for (unsigned i = 0, e = Attrs.getNumSlots(); i != e; ++i) {
Devang Patel05988662008-09-25 21:00:45 +00001887 if ((Attrs.getSlot(i).Attrs & Attribute::Nest) == 0)
Duncan Sands548448a2008-02-18 17:32:13 +00001888 continue;
1889
Duncan Sands548448a2008-02-18 17:32:13 +00001890 // There can be only one.
Devang Patel05988662008-09-25 21:00:45 +00001891 return Attrs.removeAttr(Attrs.getSlot(i).Index, Attribute::Nest);
Duncan Sands3d5378f2008-02-16 20:56:04 +00001892 }
1893
1894 return Attrs;
1895}
1896
1897static void RemoveNestAttribute(Function *F) {
Devang Patel05988662008-09-25 21:00:45 +00001898 F->setAttributes(StripNest(F->getAttributes()));
Duncan Sands3d5378f2008-02-16 20:56:04 +00001899 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
Jay Foadb7454fd2012-05-12 08:30:16 +00001900 if (isa<BlockAddress>(*UI))
1901 continue;
Duncan Sands548448a2008-02-18 17:32:13 +00001902 CallSite User(cast<Instruction>(*UI));
Devang Patel05988662008-09-25 21:00:45 +00001903 User.setAttributes(StripNest(User.getAttributes()));
Duncan Sands3d5378f2008-02-16 20:56:04 +00001904 }
1905}
1906
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001907bool GlobalOpt::OptimizeFunctions(Module &M) {
1908 bool Changed = false;
1909 // Optimize functions.
1910 for (Module::iterator FI = M.begin(), E = M.end(); FI != E; ) {
1911 Function *F = FI++;
Duncan Sandsfc5940d2009-03-06 10:21:56 +00001912 // Functions without names cannot be referenced outside this module.
1913 if (!F->hasName() && !F->isDeclaration())
1914 F->setLinkage(GlobalValue::InternalLinkage);
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001915 F->removeDeadConstantUsers();
Eli Friedmanc6633052011-10-20 05:23:42 +00001916 if (F->isDefTriviallyDead()) {
Chris Lattnerec4c7b92009-11-01 19:03:42 +00001917 F->eraseFromParent();
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001918 Changed = true;
1919 ++NumFnDeleted;
Rafael Espindolabb46f522009-01-15 20:18:42 +00001920 } else if (F->hasLocalLinkage()) {
Duncan Sands3d5378f2008-02-16 20:56:04 +00001921 if (F->getCallingConv() == CallingConv::C && !F->isVarArg() &&
Jay Foad757068f2009-06-10 08:41:11 +00001922 !F->hasAddressTaken()) {
Duncan Sands3d5378f2008-02-16 20:56:04 +00001923 // If this function has C calling conventions, is not a varargs
1924 // function, and is only called directly, promote it to use the Fast
1925 // calling convention.
1926 F->setCallingConv(CallingConv::Fast);
1927 ChangeCalleesToFastCall(F);
1928 ++NumFastCallFns;
1929 Changed = true;
1930 }
1931
Devang Patel05988662008-09-25 21:00:45 +00001932 if (F->getAttributes().hasAttrSomewhere(Attribute::Nest) &&
Jay Foad757068f2009-06-10 08:41:11 +00001933 !F->hasAddressTaken()) {
Duncan Sands3d5378f2008-02-16 20:56:04 +00001934 // The function is not used by a trampoline intrinsic, so it is safe
1935 // to remove the 'nest' attribute.
1936 RemoveNestAttribute(F);
1937 ++NumNestRemoved;
1938 Changed = true;
1939 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001940 }
1941 }
1942 return Changed;
1943}
1944
1945bool GlobalOpt::OptimizeGlobalVars(Module &M) {
1946 bool Changed = false;
1947 for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
1948 GVI != E; ) {
1949 GlobalVariable *GV = GVI++;
Duncan Sandsfc5940d2009-03-06 10:21:56 +00001950 // Global variables without names cannot be referenced outside this module.
1951 if (!GV->hasName() && !GV->isDeclaration())
1952 GV->setLinkage(GlobalValue::InternalLinkage);
Dan Gohman01b97dd2009-11-23 16:22:21 +00001953 // Simplify the initializer.
1954 if (GV->hasInitializer())
1955 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GV->getInitializer())) {
Chad Rosieraab8e282011-12-02 01:26:24 +00001956 Constant *New = ConstantFoldConstantExpression(CE, TD, TLI);
Dan Gohman01b97dd2009-11-23 16:22:21 +00001957 if (New && New != CE)
1958 GV->setInitializer(New);
1959 }
Rafael Espindolac4440e32011-01-19 16:32:21 +00001960
1961 Changed |= ProcessGlobal(GV, GVI);
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001962 }
1963 return Changed;
1964}
1965
Nick Lewycky2c44a802011-04-08 07:30:21 +00001966/// FindGlobalCtors - Find the llvm.global_ctors list, verifying that all
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001967/// initializers have an init priority of 65535.
1968GlobalVariable *GlobalOpt::FindGlobalCtors(Module &M) {
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00001969 GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
1970 if (GV == 0) return 0;
1971
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00001972 // Verify that the initializer is simple enough for us to handle. We are
1973 // only allowed to optimize the initializer if it is unique.
1974 if (!GV->hasUniqueInitializer()) return 0;
Nick Lewycky5ea5c612011-04-11 22:11:20 +00001975
1976 if (isa<ConstantAggregateZero>(GV->getInitializer()))
1977 return GV;
1978 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
Eli Friedman18a2e502011-04-09 09:11:09 +00001979
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00001980 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i) {
Nick Lewycky5ea5c612011-04-11 22:11:20 +00001981 if (isa<ConstantAggregateZero>(*i))
1982 continue;
1983 ConstantStruct *CS = cast<ConstantStruct>(*i);
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00001984 if (isa<ConstantPointerNull>(CS->getOperand(1)))
1985 continue;
Chris Lattner7d8e58f2005-09-26 02:19:27 +00001986
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00001987 // Must have a function or null ptr.
1988 if (!isa<Function>(CS->getOperand(1)))
1989 return 0;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001990
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00001991 // Init priority must be standard.
Nick Lewycky2c44a802011-04-08 07:30:21 +00001992 ConstantInt *CI = cast<ConstantInt>(CS->getOperand(0));
1993 if (CI->getZExtValue() != 65535)
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00001994 return 0;
1995 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001996
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00001997 return GV;
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001998}
1999
Chris Lattnerdb973e62005-09-26 02:31:18 +00002000/// ParseGlobalCtors - Given a llvm.global_ctors list that we can understand,
2001/// return a list of the functions and null terminator as a vector.
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002002static std::vector<Function*> ParseGlobalCtors(GlobalVariable *GV) {
Nick Lewycky5ea5c612011-04-11 22:11:20 +00002003 if (GV->getInitializer()->isNullValue())
2004 return std::vector<Function*>();
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002005 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
2006 std::vector<Function*> Result;
2007 Result.reserve(CA->getNumOperands());
Gabor Greif5e463212008-05-29 01:59:18 +00002008 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i) {
2009 ConstantStruct *CS = cast<ConstantStruct>(*i);
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002010 Result.push_back(dyn_cast<Function>(CS->getOperand(1)));
2011 }
2012 return Result;
2013}
2014
Chris Lattnerdb973e62005-09-26 02:31:18 +00002015/// InstallGlobalCtors - Given a specified llvm.global_ctors list, install the
2016/// specified array, returning the new global to use.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002017static GlobalVariable *InstallGlobalCtors(GlobalVariable *GCL,
Chris Lattner7b550cc2009-11-06 04:27:31 +00002018 const std::vector<Function*> &Ctors) {
Chris Lattnerdb973e62005-09-26 02:31:18 +00002019 // If we made a change, reassemble the initializer list.
Chris Lattnerb065b062011-06-20 04:01:31 +00002020 Constant *CSVals[2];
2021 CSVals[0] = ConstantInt::get(Type::getInt32Ty(GCL->getContext()), 65535);
2022 CSVals[1] = 0;
2023
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002024 StructType *StructTy =
Chris Lattnerb065b062011-06-20 04:01:31 +00002025 cast <StructType>(
2026 cast<ArrayType>(GCL->getType()->getElementType())->getElementType());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002027
Chris Lattnerdb973e62005-09-26 02:31:18 +00002028 // Create the new init list.
2029 std::vector<Constant*> CAList;
2030 for (unsigned i = 0, e = Ctors.size(); i != e; ++i) {
Chris Lattner79c11012005-09-26 04:44:35 +00002031 if (Ctors[i]) {
Chris Lattnerdb973e62005-09-26 02:31:18 +00002032 CSVals[1] = Ctors[i];
Chris Lattner79c11012005-09-26 04:44:35 +00002033 } else {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002034 Type *FTy = FunctionType::get(Type::getVoidTy(GCL->getContext()),
Chris Lattner7b550cc2009-11-06 04:27:31 +00002035 false);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002036 PointerType *PFTy = PointerType::getUnqual(FTy);
Owen Andersona7235ea2009-07-31 20:28:14 +00002037 CSVals[1] = Constant::getNullValue(PFTy);
Chris Lattner7b550cc2009-11-06 04:27:31 +00002038 CSVals[0] = ConstantInt::get(Type::getInt32Ty(GCL->getContext()),
Nick Lewycky5ea5c612011-04-11 22:11:20 +00002039 0x7fffffff);
Chris Lattnerdb973e62005-09-26 02:31:18 +00002040 }
Chris Lattnerb065b062011-06-20 04:01:31 +00002041 CAList.push_back(ConstantStruct::get(StructTy, CSVals));
Chris Lattnerdb973e62005-09-26 02:31:18 +00002042 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002043
Chris Lattnerdb973e62005-09-26 02:31:18 +00002044 // Create the array initializer.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002045 Constant *CA = ConstantArray::get(ArrayType::get(StructTy,
Nick Lewyckyc332fba2009-09-19 20:30:26 +00002046 CAList.size()), CAList);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002047
Chris Lattnerdb973e62005-09-26 02:31:18 +00002048 // If we didn't change the number of elements, don't create a new GV.
2049 if (CA->getType() == GCL->getInitializer()->getType()) {
2050 GCL->setInitializer(CA);
2051 return GCL;
2052 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002053
Chris Lattnerdb973e62005-09-26 02:31:18 +00002054 // Create the new global and insert it next to the existing list.
Chris Lattner7b550cc2009-11-06 04:27:31 +00002055 GlobalVariable *NGV = new GlobalVariable(CA->getType(), GCL->isConstant(),
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +00002056 GCL->getLinkage(), CA, "",
Hans Wennborgce718ff2012-06-23 11:37:03 +00002057 GCL->getThreadLocalMode());
Chris Lattnerdb973e62005-09-26 02:31:18 +00002058 GCL->getParent()->getGlobalList().insert(GCL, NGV);
Chris Lattner046800a2007-02-11 01:08:35 +00002059 NGV->takeName(GCL);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002060
Chris Lattnerdb973e62005-09-26 02:31:18 +00002061 // Nuke the old list, replacing any uses with the new one.
2062 if (!GCL->use_empty()) {
2063 Constant *V = NGV;
2064 if (V->getType() != GCL->getType())
Owen Andersonbaf3c402009-07-29 18:55:55 +00002065 V = ConstantExpr::getBitCast(V, GCL->getType());
Chris Lattnerdb973e62005-09-26 02:31:18 +00002066 GCL->replaceAllUsesWith(V);
2067 }
2068 GCL->eraseFromParent();
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002069
Chris Lattnerdb973e62005-09-26 02:31:18 +00002070 if (Ctors.size())
2071 return NGV;
2072 else
2073 return 0;
2074}
Chris Lattner79c11012005-09-26 04:44:35 +00002075
2076
Chris Lattner1945d582010-12-07 04:33:29 +00002077static inline bool
2078isSimpleEnoughValueToCommit(Constant *C,
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002079 SmallPtrSet<Constant*, 8> &SimpleConstants,
2080 const TargetData *TD);
Chris Lattner1945d582010-12-07 04:33:29 +00002081
2082
2083/// isSimpleEnoughValueToCommit - Return true if the specified constant can be
2084/// handled by the code generator. We don't want to generate something like:
2085/// void *X = &X/42;
2086/// because the code generator doesn't have a relocation that can handle that.
2087///
2088/// This function should be called if C was not found (but just got inserted)
2089/// in SimpleConstants to avoid having to rescan the same constants all the
2090/// time.
2091static bool isSimpleEnoughValueToCommitHelper(Constant *C,
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002092 SmallPtrSet<Constant*, 8> &SimpleConstants,
2093 const TargetData *TD) {
Chris Lattner1945d582010-12-07 04:33:29 +00002094 // Simple integer, undef, constant aggregate zero, global addresses, etc are
2095 // all supported.
2096 if (C->getNumOperands() == 0 || isa<BlockAddress>(C) ||
2097 isa<GlobalValue>(C))
2098 return true;
2099
2100 // Aggregate values are safe if all their elements are.
2101 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C) ||
2102 isa<ConstantVector>(C)) {
2103 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i) {
2104 Constant *Op = cast<Constant>(C->getOperand(i));
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002105 if (!isSimpleEnoughValueToCommit(Op, SimpleConstants, TD))
Chris Lattner1945d582010-12-07 04:33:29 +00002106 return false;
2107 }
2108 return true;
2109 }
2110
2111 // We don't know exactly what relocations are allowed in constant expressions,
2112 // so we allow &global+constantoffset, which is safe and uniformly supported
2113 // across targets.
2114 ConstantExpr *CE = cast<ConstantExpr>(C);
2115 switch (CE->getOpcode()) {
2116 case Instruction::BitCast:
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002117 // Bitcast is fine if the casted value is fine.
2118 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, TD);
2119
Chris Lattner1945d582010-12-07 04:33:29 +00002120 case Instruction::IntToPtr:
2121 case Instruction::PtrToInt:
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002122 // int <=> ptr is fine if the int type is the same size as the
2123 // pointer type.
2124 if (!TD || TD->getTypeSizeInBits(CE->getType()) !=
2125 TD->getTypeSizeInBits(CE->getOperand(0)->getType()))
2126 return false;
2127 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, TD);
Chris Lattner1945d582010-12-07 04:33:29 +00002128
2129 // GEP is fine if it is simple + constant offset.
2130 case Instruction::GetElementPtr:
2131 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
2132 if (!isa<ConstantInt>(CE->getOperand(i)))
2133 return false;
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002134 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, TD);
Chris Lattner1945d582010-12-07 04:33:29 +00002135
2136 case Instruction::Add:
2137 // We allow simple+cst.
2138 if (!isa<ConstantInt>(CE->getOperand(1)))
2139 return false;
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002140 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, TD);
Chris Lattner1945d582010-12-07 04:33:29 +00002141 }
2142 return false;
2143}
2144
2145static inline bool
2146isSimpleEnoughValueToCommit(Constant *C,
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002147 SmallPtrSet<Constant*, 8> &SimpleConstants,
2148 const TargetData *TD) {
Chris Lattner1945d582010-12-07 04:33:29 +00002149 // If we already checked this constant, we win.
2150 if (!SimpleConstants.insert(C)) return true;
2151 // Check the constant.
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002152 return isSimpleEnoughValueToCommitHelper(C, SimpleConstants, TD);
Chris Lattner1945d582010-12-07 04:33:29 +00002153}
2154
2155
Chris Lattner79c11012005-09-26 04:44:35 +00002156/// isSimpleEnoughPointerToCommit - Return true if this constant is simple
Owen Andersoncff6b372011-01-14 22:19:20 +00002157/// enough for us to understand. In particular, if it is a cast to anything
2158/// other than from one pointer type to another pointer type, we punt.
2159/// We basically just support direct accesses to globals and GEP's of
Chris Lattner79c11012005-09-26 04:44:35 +00002160/// globals. This should be kept up to date with CommitValueTo.
Chris Lattner7b550cc2009-11-06 04:27:31 +00002161static bool isSimpleEnoughPointerToCommit(Constant *C) {
Dan Gohmance5de5b2009-09-07 22:42:05 +00002162 // Conservatively, avoid aggregate types. This is because we don't
2163 // want to worry about them partially overlapping other stores.
2164 if (!cast<PointerType>(C->getType())->getElementType()->isSingleValueType())
2165 return false;
2166
Dan Gohmanfd54a892009-09-07 22:31:26 +00002167 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
Mikhail Glushenkov99fca5d2010-10-19 16:47:23 +00002168 // Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or
Dan Gohmanfd54a892009-09-07 22:31:26 +00002169 // external globals.
Mikhail Glushenkov99fca5d2010-10-19 16:47:23 +00002170 return GV->hasUniqueInitializer();
Dan Gohmanfd54a892009-09-07 22:31:26 +00002171
Owen Andersone95a32c2011-01-14 22:31:13 +00002172 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002173 // Handle a constantexpr gep.
2174 if (CE->getOpcode() == Instruction::GetElementPtr &&
Dan Gohmanc62482d2009-09-07 22:40:13 +00002175 isa<GlobalVariable>(CE->getOperand(0)) &&
2176 cast<GEPOperator>(CE)->isInBounds()) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002177 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
Mikhail Glushenkov99fca5d2010-10-19 16:47:23 +00002178 // Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or
Dan Gohmanfd54a892009-09-07 22:31:26 +00002179 // external globals.
Mikhail Glushenkov99fca5d2010-10-19 16:47:23 +00002180 if (!GV->hasUniqueInitializer())
Dan Gohmanfd54a892009-09-07 22:31:26 +00002181 return false;
Dan Gohman80bdc962009-09-07 22:44:55 +00002182
Dan Gohman80bdc962009-09-07 22:44:55 +00002183 // The first index must be zero.
Oscar Fuentesee56c422010-08-02 06:00:15 +00002184 ConstantInt *CI = dyn_cast<ConstantInt>(*llvm::next(CE->op_begin()));
Dan Gohman80bdc962009-09-07 22:44:55 +00002185 if (!CI || !CI->isZero()) return false;
Dan Gohman80bdc962009-09-07 22:44:55 +00002186
2187 // The remaining indices must be compile-time known integers within the
Dan Gohmane6992f72009-09-10 23:37:55 +00002188 // notional bounds of the corresponding static array types.
2189 if (!CE->isGEPWithNoNotionalOverIndexing())
2190 return false;
Dan Gohman80bdc962009-09-07 22:44:55 +00002191
Dan Gohmanc6f69e92009-10-05 16:36:26 +00002192 return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
Owen Andersoncff6b372011-01-14 22:19:20 +00002193
2194 // A constantexpr bitcast from a pointer to another pointer is a no-op,
2195 // and we know how to evaluate it by moving the bitcast from the pointer
2196 // operand to the value operand.
2197 } else if (CE->getOpcode() == Instruction::BitCast &&
Chris Lattnerd5f656f2011-01-16 02:05:10 +00002198 isa<GlobalVariable>(CE->getOperand(0))) {
Owen Andersoncff6b372011-01-14 22:19:20 +00002199 // Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or
2200 // external globals.
Chris Lattnerd5f656f2011-01-16 02:05:10 +00002201 return cast<GlobalVariable>(CE->getOperand(0))->hasUniqueInitializer();
Chris Lattner798b4d52005-09-26 06:52:44 +00002202 }
Owen Andersone95a32c2011-01-14 22:31:13 +00002203 }
2204
Chris Lattner79c11012005-09-26 04:44:35 +00002205 return false;
2206}
2207
Chris Lattner798b4d52005-09-26 06:52:44 +00002208/// EvaluateStoreInto - Evaluate a piece of a constantexpr store into a global
2209/// initializer. This returns 'Init' modified to reflect 'Val' stored into it.
2210/// At this point, the GEP operands of Addr [0, OpNo) have been stepped into.
2211static Constant *EvaluateStoreInto(Constant *Init, Constant *Val,
Chris Lattner7b550cc2009-11-06 04:27:31 +00002212 ConstantExpr *Addr, unsigned OpNo) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002213 // Base case of the recursion.
2214 if (OpNo == Addr->getNumOperands()) {
2215 assert(Val->getType() == Init->getType() && "Type mismatch!");
2216 return Val;
2217 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002218
Chris Lattnera78fa8c2012-01-27 03:08:05 +00002219 SmallVector<Constant*, 32> Elts;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002220 if (StructType *STy = dyn_cast<StructType>(Init->getType())) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002221 // Break up the constant into its elements.
Chris Lattnerd59ae902012-01-26 02:32:04 +00002222 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
2223 Elts.push_back(Init->getAggregateElement(i));
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002224
Chris Lattner798b4d52005-09-26 06:52:44 +00002225 // Replace the element that we are supposed to.
Reid Spencerb83eb642006-10-20 07:07:24 +00002226 ConstantInt *CU = cast<ConstantInt>(Addr->getOperand(OpNo));
2227 unsigned Idx = CU->getZExtValue();
2228 assert(Idx < STy->getNumElements() && "Struct index out of range!");
Chris Lattner7b550cc2009-11-06 04:27:31 +00002229 Elts[Idx] = EvaluateStoreInto(Elts[Idx], Val, Addr, OpNo+1);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002230
Chris Lattner798b4d52005-09-26 06:52:44 +00002231 // Return the modified struct.
Chris Lattnerb065b062011-06-20 04:01:31 +00002232 return ConstantStruct::get(STy, Elts);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002233 }
Chris Lattnerb065b062011-06-20 04:01:31 +00002234
2235 ConstantInt *CI = cast<ConstantInt>(Addr->getOperand(OpNo));
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002236 SequentialType *InitTy = cast<SequentialType>(Init->getType());
Chris Lattnerb065b062011-06-20 04:01:31 +00002237
2238 uint64_t NumElts;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002239 if (ArrayType *ATy = dyn_cast<ArrayType>(InitTy))
Chris Lattnerb065b062011-06-20 04:01:31 +00002240 NumElts = ATy->getNumElements();
2241 else
Chris Lattnerd59ae902012-01-26 02:32:04 +00002242 NumElts = InitTy->getVectorNumElements();
Chris Lattnerb065b062011-06-20 04:01:31 +00002243
2244 // Break up the array into elements.
Chris Lattnerd59ae902012-01-26 02:32:04 +00002245 for (uint64_t i = 0, e = NumElts; i != e; ++i)
2246 Elts.push_back(Init->getAggregateElement(i));
Chris Lattnerb065b062011-06-20 04:01:31 +00002247
2248 assert(CI->getZExtValue() < NumElts);
2249 Elts[CI->getZExtValue()] =
2250 EvaluateStoreInto(Elts[CI->getZExtValue()], Val, Addr, OpNo+1);
2251
2252 if (Init->getType()->isArrayTy())
2253 return ConstantArray::get(cast<ArrayType>(InitTy), Elts);
2254 return ConstantVector::get(Elts);
Chris Lattner798b4d52005-09-26 06:52:44 +00002255}
2256
Chris Lattner79c11012005-09-26 04:44:35 +00002257/// CommitValueTo - We have decided that Addr (which satisfies the predicate
2258/// isSimpleEnoughPointerToCommit) should get Val as its value. Make it happen.
Chris Lattner7b550cc2009-11-06 04:27:31 +00002259static void CommitValueTo(Constant *Val, Constant *Addr) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002260 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Addr)) {
2261 assert(GV->hasInitializer());
2262 GV->setInitializer(Val);
2263 return;
2264 }
Chris Lattnera0e9a242010-01-07 01:16:21 +00002265
Chris Lattner798b4d52005-09-26 06:52:44 +00002266 ConstantExpr *CE = cast<ConstantExpr>(Addr);
2267 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
Chris Lattnera0e9a242010-01-07 01:16:21 +00002268 GV->setInitializer(EvaluateStoreInto(GV->getInitializer(), Val, CE, 2));
Chris Lattner79c11012005-09-26 04:44:35 +00002269}
2270
Nick Lewycky7fa76772012-02-20 03:25:59 +00002271namespace {
2272
2273/// Evaluator - This class evaluates LLVM IR, producing the Constant
2274/// representing each SSA instruction. Changes to global variables are stored
2275/// in a mapping that can be iterated over after the evaluation is complete.
2276/// Once an evaluation call fails, the evaluation object should not be reused.
2277class Evaluator {
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002278public:
Nick Lewycky7fa76772012-02-20 03:25:59 +00002279 Evaluator(const TargetData *TD, const TargetLibraryInfo *TLI)
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002280 : TD(TD), TLI(TLI) {
2281 ValueStack.push_back(new DenseMap<Value*, Constant*>);
2282 }
2283
Nick Lewycky7fa76772012-02-20 03:25:59 +00002284 ~Evaluator() {
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002285 DeleteContainerPointers(ValueStack);
2286 while (!AllocaTmps.empty()) {
2287 GlobalVariable *Tmp = AllocaTmps.back();
2288 AllocaTmps.pop_back();
2289
2290 // If there are still users of the alloca, the program is doing something
2291 // silly, e.g. storing the address of the alloca somewhere and using it
2292 // later. Since this is undefined, we'll just make it be null.
2293 if (!Tmp->use_empty())
2294 Tmp->replaceAllUsesWith(Constant::getNullValue(Tmp->getType()));
2295 delete Tmp;
2296 }
2297 }
2298
2299 /// EvaluateFunction - Evaluate a call to function F, returning true if
2300 /// successful, false if we can't evaluate it. ActualArgs contains the formal
2301 /// arguments for the function.
2302 bool EvaluateFunction(Function *F, Constant *&RetVal,
2303 const SmallVectorImpl<Constant*> &ActualArgs);
2304
2305 /// EvaluateBlock - Evaluate all instructions in block BB, returning true if
2306 /// successful, false if we can't evaluate it. NewBB returns the next BB that
2307 /// control flows into, or null upon return.
2308 bool EvaluateBlock(BasicBlock::iterator CurInst, BasicBlock *&NextBB);
2309
2310 Constant *getVal(Value *V) {
2311 if (Constant *CV = dyn_cast<Constant>(V)) return CV;
2312 Constant *R = ValueStack.back()->lookup(V);
2313 assert(R && "Reference to an uncomputed value!");
2314 return R;
2315 }
2316
2317 void setVal(Value *V, Constant *C) {
2318 ValueStack.back()->operator[](V) = C;
2319 }
2320
2321 const DenseMap<Constant*, Constant*> &getMutatedMemory() const {
2322 return MutatedMemory;
2323 }
2324
2325 const SmallPtrSet<GlobalVariable*, 8> &getInvariants() const {
2326 return Invariants;
2327 }
2328
2329private:
2330 Constant *ComputeLoadResult(Constant *P);
2331
2332 /// ValueStack - As we compute SSA register values, we store their contents
2333 /// here. The back of the vector contains the current function and the stack
2334 /// contains the values in the calling frames.
2335 SmallVector<DenseMap<Value*, Constant*>*, 4> ValueStack;
2336
2337 /// CallStack - This is used to detect recursion. In pathological situations
2338 /// we could hit exponential behavior, but at least there is nothing
2339 /// unbounded.
2340 SmallVector<Function*, 4> CallStack;
2341
2342 /// MutatedMemory - For each store we execute, we update this map. Loads
2343 /// check this to get the most up-to-date value. If evaluation is successful,
2344 /// this state is committed to the process.
2345 DenseMap<Constant*, Constant*> MutatedMemory;
2346
2347 /// AllocaTmps - To 'execute' an alloca, we create a temporary global variable
2348 /// to represent its body. This vector is needed so we can delete the
2349 /// temporary globals when we are done.
2350 SmallVector<GlobalVariable*, 32> AllocaTmps;
2351
2352 /// Invariants - These global variables have been marked invariant by the
2353 /// static constructor.
2354 SmallPtrSet<GlobalVariable*, 8> Invariants;
2355
2356 /// SimpleConstants - These are constants we have checked and know to be
2357 /// simple enough to live in a static initializer of a global.
2358 SmallPtrSet<Constant*, 8> SimpleConstants;
2359
2360 const TargetData *TD;
2361 const TargetLibraryInfo *TLI;
2362};
2363
Nick Lewycky7fa76772012-02-20 03:25:59 +00002364} // anonymous namespace
2365
Chris Lattner562a0552005-09-26 05:16:34 +00002366/// ComputeLoadResult - Return the value that would be computed by a load from
2367/// P after the stores reflected by 'memory' have been performed. If we can't
2368/// decide, return null.
Nick Lewycky7fa76772012-02-20 03:25:59 +00002369Constant *Evaluator::ComputeLoadResult(Constant *P) {
Chris Lattner04de1cf2005-09-26 05:15:37 +00002370 // If this memory location has been recently stored, use the stored value: it
2371 // is the most up-to-date.
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002372 DenseMap<Constant*, Constant*>::const_iterator I = MutatedMemory.find(P);
2373 if (I != MutatedMemory.end()) return I->second;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002374
Chris Lattner04de1cf2005-09-26 05:15:37 +00002375 // Access it.
2376 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(P)) {
Dan Gohman82555732009-08-19 18:20:44 +00002377 if (GV->hasDefinitiveInitializer())
Chris Lattner04de1cf2005-09-26 05:15:37 +00002378 return GV->getInitializer();
2379 return 0;
Chris Lattner04de1cf2005-09-26 05:15:37 +00002380 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002381
Chris Lattner798b4d52005-09-26 06:52:44 +00002382 // Handle a constantexpr getelementptr.
2383 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(P))
2384 if (CE->getOpcode() == Instruction::GetElementPtr &&
2385 isa<GlobalVariable>(CE->getOperand(0))) {
2386 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
Dan Gohman82555732009-08-19 18:20:44 +00002387 if (GV->hasDefinitiveInitializer())
Dan Gohmanc6f69e92009-10-05 16:36:26 +00002388 return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
Chris Lattner798b4d52005-09-26 06:52:44 +00002389 }
2390
2391 return 0; // don't know how to evaluate.
Chris Lattner04de1cf2005-09-26 05:15:37 +00002392}
2393
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002394/// EvaluateBlock - Evaluate all instructions in block BB, returning true if
2395/// successful, false if we can't evaluate it. NewBB returns the next BB that
2396/// control flows into, or null upon return.
Nick Lewycky7fa76772012-02-20 03:25:59 +00002397bool Evaluator::EvaluateBlock(BasicBlock::iterator CurInst,
2398 BasicBlock *&NextBB) {
Chris Lattner79c11012005-09-26 04:44:35 +00002399 // This is the main evaluation loop.
2400 while (1) {
2401 Constant *InstResult = 0;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002402
Chris Lattner79c11012005-09-26 04:44:35 +00002403 if (StoreInst *SI = dyn_cast<StoreInst>(CurInst)) {
Eli Friedman33cb4452011-08-16 00:20:11 +00002404 if (!SI->isSimple()) return false; // no volatile/atomic accesses.
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002405 Constant *Ptr = getVal(SI->getOperand(1));
Nick Lewyckya641c072012-02-21 22:08:06 +00002406 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
2407 Ptr = ConstantFoldConstantExpression(CE, TD, TLI);
Chris Lattner7b550cc2009-11-06 04:27:31 +00002408 if (!isSimpleEnoughPointerToCommit(Ptr))
Chris Lattner79c11012005-09-26 04:44:35 +00002409 // If this is too complex for us to commit, reject it.
Chris Lattnercd271422005-09-27 04:45:34 +00002410 return false;
Chris Lattner1945d582010-12-07 04:33:29 +00002411
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002412 Constant *Val = getVal(SI->getOperand(0));
Chris Lattner1945d582010-12-07 04:33:29 +00002413
2414 // If this might be too difficult for the backend to handle (e.g. the addr
2415 // of one global variable divided by another) then we can't commit it.
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002416 if (!isSimpleEnoughValueToCommit(Val, SimpleConstants, TD))
Chris Lattner1945d582010-12-07 04:33:29 +00002417 return false;
Owen Andersoncff6b372011-01-14 22:19:20 +00002418
2419 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
2420 if (CE->getOpcode() == Instruction::BitCast) {
2421 // If we're evaluating a store through a bitcast, then we need
2422 // to pull the bitcast off the pointer type and push it onto the
2423 // stored value.
Chris Lattnerd5f656f2011-01-16 02:05:10 +00002424 Ptr = CE->getOperand(0);
Owen Andersoncff6b372011-01-14 22:19:20 +00002425
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002426 Type *NewTy = cast<PointerType>(Ptr->getType())->getElementType();
Owen Andersoncff6b372011-01-14 22:19:20 +00002427
Owen Anderson66f708f2011-01-16 04:33:33 +00002428 // In order to push the bitcast onto the stored value, a bitcast
2429 // from NewTy to Val's type must be legal. If it's not, we can try
2430 // introspecting NewTy to find a legal conversion.
2431 while (!Val->getType()->canLosslesslyBitCastTo(NewTy)) {
2432 // If NewTy is a struct, we can convert the pointer to the struct
2433 // into a pointer to its first member.
2434 // FIXME: This could be extended to support arrays as well.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002435 if (StructType *STy = dyn_cast<StructType>(NewTy)) {
Owen Anderson66f708f2011-01-16 04:33:33 +00002436 NewTy = STy->getTypeAtIndex(0U);
2437
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002438 IntegerType *IdxTy = IntegerType::get(NewTy->getContext(), 32);
Owen Anderson66f708f2011-01-16 04:33:33 +00002439 Constant *IdxZero = ConstantInt::get(IdxTy, 0, false);
2440 Constant * const IdxList[] = {IdxZero, IdxZero};
2441
Jay Foadb4263a62011-07-22 08:52:50 +00002442 Ptr = ConstantExpr::getGetElementPtr(Ptr, IdxList);
Nick Lewyckya641c072012-02-21 22:08:06 +00002443 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
2444 Ptr = ConstantFoldConstantExpression(CE, TD, TLI);
2445
Owen Anderson66f708f2011-01-16 04:33:33 +00002446 // If we can't improve the situation by introspecting NewTy,
2447 // we have to give up.
2448 } else {
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002449 return false;
Owen Anderson66f708f2011-01-16 04:33:33 +00002450 }
Owen Andersoncff6b372011-01-14 22:19:20 +00002451 }
2452
Owen Anderson66f708f2011-01-16 04:33:33 +00002453 // If we found compatible types, go ahead and push the bitcast
2454 // onto the stored value.
Owen Andersoncff6b372011-01-14 22:19:20 +00002455 Val = ConstantExpr::getBitCast(Val, NewTy);
2456 }
2457
Chris Lattner79c11012005-09-26 04:44:35 +00002458 MutatedMemory[Ptr] = Val;
2459 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CurInst)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002460 InstResult = ConstantExpr::get(BO->getOpcode(),
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002461 getVal(BO->getOperand(0)),
2462 getVal(BO->getOperand(1)));
Reid Spencere4d87aa2006-12-23 06:05:41 +00002463 } else if (CmpInst *CI = dyn_cast<CmpInst>(CurInst)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002464 InstResult = ConstantExpr::getCompare(CI->getPredicate(),
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002465 getVal(CI->getOperand(0)),
2466 getVal(CI->getOperand(1)));
Chris Lattner79c11012005-09-26 04:44:35 +00002467 } else if (CastInst *CI = dyn_cast<CastInst>(CurInst)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002468 InstResult = ConstantExpr::getCast(CI->getOpcode(),
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002469 getVal(CI->getOperand(0)),
Chris Lattner79c11012005-09-26 04:44:35 +00002470 CI->getType());
2471 } else if (SelectInst *SI = dyn_cast<SelectInst>(CurInst)) {
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002472 InstResult = ConstantExpr::getSelect(getVal(SI->getOperand(0)),
2473 getVal(SI->getOperand(1)),
2474 getVal(SI->getOperand(2)));
Chris Lattner04de1cf2005-09-26 05:15:37 +00002475 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurInst)) {
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002476 Constant *P = getVal(GEP->getOperand(0));
Chris Lattner55eb1c42007-01-31 04:40:53 +00002477 SmallVector<Constant*, 8> GEPOps;
Gabor Greif5e463212008-05-29 01:59:18 +00002478 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end();
2479 i != e; ++i)
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002480 GEPOps.push_back(getVal(*i));
Jay Foad4b5e2072011-07-21 15:15:37 +00002481 InstResult =
2482 ConstantExpr::getGetElementPtr(P, GEPOps,
2483 cast<GEPOperator>(GEP)->isInBounds());
Chris Lattner04de1cf2005-09-26 05:15:37 +00002484 } else if (LoadInst *LI = dyn_cast<LoadInst>(CurInst)) {
Eli Friedman33cb4452011-08-16 00:20:11 +00002485 if (!LI->isSimple()) return false; // no volatile/atomic accesses.
Nick Lewyckya641c072012-02-21 22:08:06 +00002486 Constant *Ptr = getVal(LI->getOperand(0));
2487 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
2488 Ptr = ConstantFoldConstantExpression(CE, TD, TLI);
2489 InstResult = ComputeLoadResult(Ptr);
Chris Lattnercd271422005-09-27 04:45:34 +00002490 if (InstResult == 0) return false; // Could not evaluate load.
Chris Lattnera22fdb02005-09-26 17:07:09 +00002491 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(CurInst)) {
Chris Lattnercd271422005-09-27 04:45:34 +00002492 if (AI->isArrayAllocation()) return false; // Cannot handle array allocs.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002493 Type *Ty = AI->getType()->getElementType();
Chris Lattner7b550cc2009-11-06 04:27:31 +00002494 AllocaTmps.push_back(new GlobalVariable(Ty, false,
Chris Lattnera22fdb02005-09-26 17:07:09 +00002495 GlobalValue::InternalLinkage,
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002496 UndefValue::get(Ty),
Chris Lattnera22fdb02005-09-26 17:07:09 +00002497 AI->getName()));
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002498 InstResult = AllocaTmps.back();
Nick Lewycky132bd9c2012-02-12 05:09:35 +00002499 } else if (isa<CallInst>(CurInst) || isa<InvokeInst>(CurInst)) {
2500 CallSite CS(CurInst);
Devang Patel412a4462009-03-09 23:04:12 +00002501
2502 // Debug info can safely be ignored here.
Nick Lewycky132bd9c2012-02-12 05:09:35 +00002503 if (isa<DbgInfoIntrinsic>(CS.getInstruction())) {
Devang Patel412a4462009-03-09 23:04:12 +00002504 ++CurInst;
2505 continue;
2506 }
2507
Chris Lattner7cd580f2006-07-07 21:37:01 +00002508 // Cannot handle inline asm.
Nick Lewycky132bd9c2012-02-12 05:09:35 +00002509 if (isa<InlineAsm>(CS.getCalledValue())) return false;
Chris Lattner7cd580f2006-07-07 21:37:01 +00002510
Nick Lewycky81266c52012-02-17 06:59:21 +00002511 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CS.getInstruction())) {
2512 if (MemSetInst *MSI = dyn_cast<MemSetInst>(II)) {
2513 if (MSI->isVolatile()) return false;
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002514 Constant *Ptr = getVal(MSI->getDest());
2515 Constant *Val = getVal(MSI->getValue());
2516 Constant *DestVal = ComputeLoadResult(getVal(Ptr));
Nick Lewycky81266c52012-02-17 06:59:21 +00002517 if (Val->isNullValue() && DestVal && DestVal->isNullValue()) {
2518 // This memset is a no-op.
2519 ++CurInst;
2520 continue;
2521 }
2522 }
2523
2524 if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
2525 II->getIntrinsicID() == Intrinsic::lifetime_end) {
2526 ++CurInst;
2527 continue;
2528 }
2529
2530 if (II->getIntrinsicID() == Intrinsic::invariant_start) {
2531 // We don't insert an entry into Values, as it doesn't have a
2532 // meaningful return value.
2533 if (!II->use_empty())
2534 return false;
2535 ConstantInt *Size = cast<ConstantInt>(II->getArgOperand(0));
Nick Lewycky0ef05572012-02-20 23:32:26 +00002536 Value *PtrArg = getVal(II->getArgOperand(1));
2537 Value *Ptr = PtrArg->stripPointerCasts();
2538 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr)) {
2539 Type *ElemTy = cast<PointerType>(GV->getType())->getElementType();
2540 if (!Size->isAllOnesValue() &&
2541 Size->getValue().getLimitedValue() >=
2542 TD->getTypeStoreSize(ElemTy))
Nick Lewycky81266c52012-02-17 06:59:21 +00002543 Invariants.insert(GV);
2544 }
2545 // Continue even if we do nothing.
Nick Lewycky1f237b02011-05-29 18:41:56 +00002546 ++CurInst;
2547 continue;
2548 }
2549 return false;
2550 }
2551
Chris Lattnercd271422005-09-27 04:45:34 +00002552 // Resolve function pointers.
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002553 Function *Callee = dyn_cast<Function>(getVal(CS.getCalledValue()));
Nick Lewycky132bd9c2012-02-12 05:09:35 +00002554 if (!Callee || Callee->mayBeOverridden())
2555 return false; // Cannot resolve.
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002556
Duncan Sandsfa6a1cf2009-08-17 14:33:27 +00002557 SmallVector<Constant*, 8> Formals;
Nick Lewycky132bd9c2012-02-12 05:09:35 +00002558 for (User::op_iterator i = CS.arg_begin(), e = CS.arg_end(); i != e; ++i)
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002559 Formals.push_back(getVal(*i));
Duncan Sandsfa6a1cf2009-08-17 14:33:27 +00002560
Reid Spencer5cbf9852007-01-30 20:08:39 +00002561 if (Callee->isDeclaration()) {
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002562 // If this is a function we can constant fold, do it.
Chad Rosier00737bd2011-12-01 21:29:16 +00002563 if (Constant *C = ConstantFoldCall(Callee, Formals, TLI)) {
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002564 InstResult = C;
2565 } else {
2566 return false;
2567 }
2568 } else {
2569 if (Callee->getFunctionType()->isVarArg())
2570 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002571
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002572 Constant *RetVal;
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002573 // Execute the call, if successful, use the return value.
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002574 ValueStack.push_back(new DenseMap<Value*, Constant*>);
2575 if (!EvaluateFunction(Callee, RetVal, Formals))
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002576 return false;
Benjamin Kramer3bbf2b62012-02-27 12:48:24 +00002577 delete ValueStack.pop_back_val();
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002578 InstResult = RetVal;
2579 }
Reid Spencer3ed469c2006-11-02 20:25:50 +00002580 } else if (isa<TerminatorInst>(CurInst)) {
Chris Lattnercdf98be2005-09-26 04:57:38 +00002581 if (BranchInst *BI = dyn_cast<BranchInst>(CurInst)) {
2582 if (BI->isUnconditional()) {
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002583 NextBB = BI->getSuccessor(0);
Chris Lattnercdf98be2005-09-26 04:57:38 +00002584 } else {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002585 ConstantInt *Cond =
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002586 dyn_cast<ConstantInt>(getVal(BI->getCondition()));
Chris Lattner97d1fad2007-01-12 18:30:11 +00002587 if (!Cond) return false; // Cannot determine.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002588
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002589 NextBB = BI->getSuccessor(!Cond->getZExtValue());
Chris Lattnercdf98be2005-09-26 04:57:38 +00002590 }
2591 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(CurInst)) {
2592 ConstantInt *Val =
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002593 dyn_cast<ConstantInt>(getVal(SI->getCondition()));
Chris Lattnercd271422005-09-27 04:45:34 +00002594 if (!Val) return false; // Cannot determine.
Stepan Dyatkovskiyc10fa6c2012-03-08 07:06:20 +00002595 NextBB = SI->findCaseValue(Val).getCaseSuccessor();
Chris Lattnerb3d5a652009-10-29 05:51:50 +00002596 } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(CurInst)) {
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002597 Value *Val = getVal(IBI->getAddress())->stripPointerCasts();
Chris Lattnerb3d5a652009-10-29 05:51:50 +00002598 if (BlockAddress *BA = dyn_cast<BlockAddress>(Val))
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002599 NextBB = BA->getBasicBlock();
Chris Lattnercdfc9402009-11-01 01:27:45 +00002600 else
2601 return false; // Cannot determine.
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002602 } else if (isa<ReturnInst>(CurInst)) {
2603 NextBB = 0;
Chris Lattnercdf98be2005-09-26 04:57:38 +00002604 } else {
Bill Wendlingdccc03b2011-07-31 06:30:59 +00002605 // invoke, unwind, resume, unreachable.
Chris Lattnercd271422005-09-27 04:45:34 +00002606 return false; // Cannot handle this terminator.
Chris Lattnercdf98be2005-09-26 04:57:38 +00002607 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002608
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002609 // We succeeded at evaluating this block!
2610 return true;
Chris Lattner79c11012005-09-26 04:44:35 +00002611 } else {
Chris Lattner79c11012005-09-26 04:44:35 +00002612 // Did not know how to evaluate this!
Chris Lattnercd271422005-09-27 04:45:34 +00002613 return false;
Chris Lattner79c11012005-09-26 04:44:35 +00002614 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002615
Chris Lattner1945d582010-12-07 04:33:29 +00002616 if (!CurInst->use_empty()) {
2617 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(InstResult))
Chad Rosieraab8e282011-12-02 01:26:24 +00002618 InstResult = ConstantFoldConstantExpression(CE, TD, TLI);
Chris Lattner1945d582010-12-07 04:33:29 +00002619
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002620 setVal(CurInst, InstResult);
Chris Lattner1945d582010-12-07 04:33:29 +00002621 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002622
Dan Gohmanf1ce79f2012-03-13 18:01:37 +00002623 // If we just processed an invoke, we finished evaluating the block.
2624 if (InvokeInst *II = dyn_cast<InvokeInst>(CurInst)) {
2625 NextBB = II->getNormalDest();
2626 return true;
2627 }
2628
Chris Lattner79c11012005-09-26 04:44:35 +00002629 // Advance program counter.
2630 ++CurInst;
2631 }
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002632}
2633
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002634/// EvaluateFunction - Evaluate a call to function F, returning true if
2635/// successful, false if we can't evaluate it. ActualArgs contains the formal
2636/// arguments for the function.
Nick Lewycky7fa76772012-02-20 03:25:59 +00002637bool Evaluator::EvaluateFunction(Function *F, Constant *&RetVal,
2638 const SmallVectorImpl<Constant*> &ActualArgs) {
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002639 // Check to see if this function is already executing (recursion). If so,
2640 // bail out. TODO: we might want to accept limited recursion.
2641 if (std::find(CallStack.begin(), CallStack.end(), F) != CallStack.end())
2642 return false;
2643
2644 CallStack.push_back(F);
2645
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002646 // Initialize arguments to the incoming values specified.
2647 unsigned ArgNo = 0;
2648 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); AI != E;
2649 ++AI, ++ArgNo)
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002650 setVal(AI, ActualArgs[ArgNo]);
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002651
2652 // ExecutedBlocks - We only handle non-looping, non-recursive code. As such,
2653 // we can only evaluate any one basic block at most once. This set keeps
2654 // track of what we have executed so we can detect recursive cases etc.
2655 SmallPtrSet<BasicBlock*, 32> ExecutedBlocks;
2656
2657 // CurBB - The current basic block we're evaluating.
2658 BasicBlock *CurBB = F->begin();
2659
Nick Lewycky8e4ba6b2012-02-12 00:47:24 +00002660 BasicBlock::iterator CurInst = CurBB->begin();
2661
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002662 while (1) {
Duncan Sands4b794f82012-02-23 08:23:06 +00002663 BasicBlock *NextBB = 0; // Initialized to avoid compiler warnings.
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002664 if (!EvaluateBlock(CurInst, NextBB))
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002665 return false;
2666
2667 if (NextBB == 0) {
2668 // Successfully running until there's no next block means that we found
2669 // the return. Fill it the return value and pop the call stack.
2670 ReturnInst *RI = cast<ReturnInst>(CurBB->getTerminator());
2671 if (RI->getNumOperands())
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002672 RetVal = getVal(RI->getOperand(0));
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002673 CallStack.pop_back();
2674 return true;
2675 }
2676
2677 // Okay, we succeeded in evaluating this control flow. See if we have
2678 // executed the new block before. If so, we have a looping function,
2679 // which we cannot evaluate in reasonable time.
2680 if (!ExecutedBlocks.insert(NextBB))
2681 return false; // looped!
2682
2683 // Okay, we have never been in this block before. Check to see if there
2684 // are any PHI nodes. If so, evaluate them with information about where
2685 // we came from.
2686 PHINode *PN = 0;
Nick Lewycky8e4ba6b2012-02-12 00:47:24 +00002687 for (CurInst = NextBB->begin();
2688 (PN = dyn_cast<PHINode>(CurInst)); ++CurInst)
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002689 setVal(PN, getVal(PN->getIncomingValueForBlock(CurBB)));
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002690
2691 // Advance to the next block.
2692 CurBB = NextBB;
2693 }
2694}
2695
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002696/// EvaluateStaticConstructor - Evaluate static constructors in the function, if
2697/// we can. Return true if we can, false otherwise.
Chad Rosier00737bd2011-12-01 21:29:16 +00002698static bool EvaluateStaticConstructor(Function *F, const TargetData *TD,
2699 const TargetLibraryInfo *TLI) {
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002700 // Call the function.
Nick Lewycky7fa76772012-02-20 03:25:59 +00002701 Evaluator Eval(TD, TLI);
Chris Lattnercd271422005-09-27 04:45:34 +00002702 Constant *RetValDummy;
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002703 bool EvalSuccess = Eval.EvaluateFunction(F, RetValDummy,
2704 SmallVector<Constant*, 0>());
Chris Lattner1945d582010-12-07 04:33:29 +00002705
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002706 if (EvalSuccess) {
Chris Lattnera22fdb02005-09-26 17:07:09 +00002707 // We succeeded at evaluation: commit the result.
David Greene3215b0e2010-01-05 01:28:05 +00002708 DEBUG(dbgs() << "FULLY EVALUATED GLOBAL CTOR FUNCTION '"
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002709 << F->getName() << "' to " << Eval.getMutatedMemory().size()
Daniel Dunbarce63ffb2009-07-25 00:23:56 +00002710 << " stores.\n");
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002711 for (DenseMap<Constant*, Constant*>::const_iterator I =
2712 Eval.getMutatedMemory().begin(), E = Eval.getMutatedMemory().end();
Nick Lewycky3eab3c42012-06-24 04:07:14 +00002713 I != E; ++I)
Chris Lattner7b550cc2009-11-06 04:27:31 +00002714 CommitValueTo(I->second, I->first);
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002715 for (SmallPtrSet<GlobalVariable*, 8>::const_iterator I =
2716 Eval.getInvariants().begin(), E = Eval.getInvariants().end();
2717 I != E; ++I)
Nick Lewycky81266c52012-02-17 06:59:21 +00002718 (*I)->setConstant(true);
Chris Lattnera22fdb02005-09-26 17:07:09 +00002719 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002720
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002721 return EvalSuccess;
Chris Lattner79c11012005-09-26 04:44:35 +00002722}
2723
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002724/// OptimizeGlobalCtorsList - Simplify and evaluation global ctors if possible.
2725/// Return true if anything changed.
2726bool GlobalOpt::OptimizeGlobalCtorsList(GlobalVariable *&GCL) {
2727 std::vector<Function*> Ctors = ParseGlobalCtors(GCL);
2728 bool MadeChange = false;
2729 if (Ctors.empty()) return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002730
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002731 // Loop over global ctors, optimizing them when we can.
2732 for (unsigned i = 0; i != Ctors.size(); ++i) {
2733 Function *F = Ctors[i];
2734 // Found a null terminator in the middle of the list, prune off the rest of
2735 // the list.
Chris Lattner7d8e58f2005-09-26 02:19:27 +00002736 if (F == 0) {
2737 if (i != Ctors.size()-1) {
2738 Ctors.resize(i+1);
2739 MadeChange = true;
2740 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002741 break;
2742 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002743
Chris Lattner79c11012005-09-26 04:44:35 +00002744 // We cannot simplify external ctor functions.
2745 if (F->empty()) continue;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002746
Chris Lattner79c11012005-09-26 04:44:35 +00002747 // If we can evaluate the ctor at compile time, do.
Chad Rosier00737bd2011-12-01 21:29:16 +00002748 if (EvaluateStaticConstructor(F, TD, TLI)) {
Chris Lattner79c11012005-09-26 04:44:35 +00002749 Ctors.erase(Ctors.begin()+i);
2750 MadeChange = true;
2751 --i;
2752 ++NumCtorsEvaluated;
2753 continue;
2754 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002755 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002756
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002757 if (!MadeChange) return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002758
Chris Lattner7b550cc2009-11-06 04:27:31 +00002759 GCL = InstallGlobalCtors(GCL, Ctors);
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002760 return true;
2761}
2762
Duncan Sandsfc5940d2009-03-06 10:21:56 +00002763bool GlobalOpt::OptimizeGlobalAliases(Module &M) {
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002764 bool Changed = false;
2765
Duncan Sands177d84e2009-01-07 20:01:06 +00002766 for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end();
Duncan Sands4782b302009-02-15 09:56:08 +00002767 I != E;) {
2768 Module::alias_iterator J = I++;
Duncan Sandsfc5940d2009-03-06 10:21:56 +00002769 // Aliases without names cannot be referenced outside this module.
2770 if (!J->hasName() && !J->isDeclaration())
2771 J->setLinkage(GlobalValue::InternalLinkage);
Duncan Sands4782b302009-02-15 09:56:08 +00002772 // If the aliasee may change at link time, nothing can be done - bail out.
2773 if (J->mayBeOverridden())
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002774 continue;
2775
Duncan Sands4782b302009-02-15 09:56:08 +00002776 Constant *Aliasee = J->getAliasee();
2777 GlobalValue *Target = cast<GlobalValue>(Aliasee->stripPointerCasts());
Duncan Sands95c5d0f2009-02-18 17:55:38 +00002778 Target->removeDeadConstantUsers();
Duncan Sands4782b302009-02-15 09:56:08 +00002779 bool hasOneUse = Target->hasOneUse() && Aliasee->hasOneUse();
2780
2781 // Make all users of the alias use the aliasee instead.
2782 if (!J->use_empty()) {
2783 J->replaceAllUsesWith(Aliasee);
2784 ++NumAliasesResolved;
2785 Changed = true;
2786 }
2787
Duncan Sands7a154cf2009-12-08 10:10:20 +00002788 // If the alias is externally visible, we may still be able to simplify it.
2789 if (!J->hasLocalLinkage()) {
2790 // If the aliasee has internal linkage, give it the name and linkage
2791 // of the alias, and delete the alias. This turns:
2792 // define internal ... @f(...)
2793 // @a = alias ... @f
2794 // into:
2795 // define ... @a(...)
2796 if (!Target->hasLocalLinkage())
2797 continue;
Duncan Sands4782b302009-02-15 09:56:08 +00002798
Duncan Sands7a154cf2009-12-08 10:10:20 +00002799 // Do not perform the transform if multiple aliases potentially target the
Gabor Greif27236912010-04-07 18:59:26 +00002800 // aliasee. This check also ensures that it is safe to replace the section
Duncan Sands7a154cf2009-12-08 10:10:20 +00002801 // and other attributes of the aliasee with those of the alias.
2802 if (!hasOneUse)
2803 continue;
Duncan Sands4782b302009-02-15 09:56:08 +00002804
Duncan Sands7a154cf2009-12-08 10:10:20 +00002805 // Give the aliasee the name, linkage and other attributes of the alias.
2806 Target->takeName(J);
2807 Target->setLinkage(J->getLinkage());
2808 Target->GlobalValue::copyAttributesFrom(J);
2809 }
Duncan Sands4782b302009-02-15 09:56:08 +00002810
2811 // Delete the alias.
2812 M.getAliasList().erase(J);
2813 ++NumAliasesRemoved;
2814 Changed = true;
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002815 }
2816
2817 return Changed;
2818}
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002819
Nick Lewycky6a7df9a2012-02-12 02:15:20 +00002820static Function *FindCXAAtExit(Module &M, TargetLibraryInfo *TLI) {
2821 if (!TLI->has(LibFunc::cxa_atexit))
Nick Lewycky6f160d32012-02-12 02:17:18 +00002822 return 0;
Nick Lewycky6a7df9a2012-02-12 02:15:20 +00002823
2824 Function *Fn = M.getFunction(TLI->getName(LibFunc::cxa_atexit));
Anders Carlssona201c4c2011-03-20 17:59:11 +00002825
2826 if (!Fn)
2827 return 0;
Nick Lewycky6a7df9a2012-02-12 02:15:20 +00002828
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002829 FunctionType *FTy = Fn->getFunctionType();
Anders Carlssona201c4c2011-03-20 17:59:11 +00002830
Anders Carlsson1f7c7ba2011-03-20 19:51:13 +00002831 // Checking that the function has the right return type, the right number of
2832 // parameters and that they all have pointer types should be enough.
2833 if (!FTy->getReturnType()->isIntegerTy() ||
2834 FTy->getNumParams() != 3 ||
Anders Carlssona201c4c2011-03-20 17:59:11 +00002835 !FTy->getParamType(0)->isPointerTy() ||
2836 !FTy->getParamType(1)->isPointerTy() ||
2837 !FTy->getParamType(2)->isPointerTy())
2838 return 0;
2839
2840 return Fn;
2841}
2842
2843/// cxxDtorIsEmpty - Returns whether the given function is an empty C++
2844/// destructor and can therefore be eliminated.
2845/// Note that we assume that other optimization passes have already simplified
2846/// the code so we only look for a function with a single basic block, where
Benjamin Kramerc1322a12012-02-09 16:28:15 +00002847/// the only allowed instructions are 'ret', 'call' to an empty C++ dtor and
2848/// other side-effect free instructions.
Anders Carlsson372ec6a2011-03-20 20:16:43 +00002849static bool cxxDtorIsEmpty(const Function &Fn,
2850 SmallPtrSet<const Function *, 8> &CalledFunctions) {
Anders Carlsson1f7c7ba2011-03-20 19:51:13 +00002851 // FIXME: We could eliminate C++ destructors if they're readonly/readnone and
Nick Lewycky35ee1c92011-03-21 02:26:01 +00002852 // nounwind, but that doesn't seem worth doing.
Anders Carlsson1f7c7ba2011-03-20 19:51:13 +00002853 if (Fn.isDeclaration())
2854 return false;
Anders Carlssona201c4c2011-03-20 17:59:11 +00002855
2856 if (++Fn.begin() != Fn.end())
2857 return false;
2858
2859 const BasicBlock &EntryBlock = Fn.getEntryBlock();
2860 for (BasicBlock::const_iterator I = EntryBlock.begin(), E = EntryBlock.end();
2861 I != E; ++I) {
2862 if (const CallInst *CI = dyn_cast<CallInst>(I)) {
Anders Carlssonb12caf32011-03-21 14:54:40 +00002863 // Ignore debug intrinsics.
2864 if (isa<DbgInfoIntrinsic>(CI))
2865 continue;
2866
Anders Carlssona201c4c2011-03-20 17:59:11 +00002867 const Function *CalledFn = CI->getCalledFunction();
2868
2869 if (!CalledFn)
2870 return false;
2871
Anders Carlsson807bc2a2011-03-22 03:21:01 +00002872 SmallPtrSet<const Function *, 8> NewCalledFunctions(CalledFunctions);
2873
Anders Carlsson1f7c7ba2011-03-20 19:51:13 +00002874 // Don't treat recursive functions as empty.
Anders Carlsson807bc2a2011-03-22 03:21:01 +00002875 if (!NewCalledFunctions.insert(CalledFn))
Anders Carlsson1f7c7ba2011-03-20 19:51:13 +00002876 return false;
2877
Anders Carlsson807bc2a2011-03-22 03:21:01 +00002878 if (!cxxDtorIsEmpty(*CalledFn, NewCalledFunctions))
Anders Carlssona201c4c2011-03-20 17:59:11 +00002879 return false;
2880 } else if (isa<ReturnInst>(*I))
Benjamin Kramerd4692742012-02-09 14:26:06 +00002881 return true; // We're done.
2882 else if (I->mayHaveSideEffects())
2883 return false; // Destructor with side effects, bail.
Anders Carlssona201c4c2011-03-20 17:59:11 +00002884 }
2885
2886 return false;
2887}
2888
2889bool GlobalOpt::OptimizeEmptyGlobalCXXDtors(Function *CXAAtExitFn) {
2890 /// Itanium C++ ABI p3.3.5:
2891 ///
2892 /// After constructing a global (or local static) object, that will require
2893 /// destruction on exit, a termination function is registered as follows:
2894 ///
2895 /// extern "C" int __cxa_atexit ( void (*f)(void *), void *p, void *d );
2896 ///
2897 /// This registration, e.g. __cxa_atexit(f,p,d), is intended to cause the
2898 /// call f(p) when DSO d is unloaded, before all such termination calls
2899 /// registered before this one. It returns zero if registration is
Nick Lewycky35ee1c92011-03-21 02:26:01 +00002900 /// successful, nonzero on failure.
Anders Carlssona201c4c2011-03-20 17:59:11 +00002901
2902 // This pass will look for calls to __cxa_atexit where the function is trivial
2903 // and remove them.
2904 bool Changed = false;
2905
2906 for (Function::use_iterator I = CXAAtExitFn->use_begin(),
2907 E = CXAAtExitFn->use_end(); I != E;) {
Anders Carlsson4f735ca2011-03-20 20:21:33 +00002908 // We're only interested in calls. Theoretically, we could handle invoke
2909 // instructions as well, but neither llvm-gcc nor clang generate invokes
2910 // to __cxa_atexit.
Anders Carlssonb12caf32011-03-21 14:54:40 +00002911 CallInst *CI = dyn_cast<CallInst>(*I++);
2912 if (!CI)
Anders Carlsson4f735ca2011-03-20 20:21:33 +00002913 continue;
2914
Anders Carlssona201c4c2011-03-20 17:59:11 +00002915 Function *DtorFn =
Anders Carlssonb12caf32011-03-21 14:54:40 +00002916 dyn_cast<Function>(CI->getArgOperand(0)->stripPointerCasts());
Anders Carlssona201c4c2011-03-20 17:59:11 +00002917 if (!DtorFn)
2918 continue;
2919
Anders Carlsson372ec6a2011-03-20 20:16:43 +00002920 SmallPtrSet<const Function *, 8> CalledFunctions;
2921 if (!cxxDtorIsEmpty(*DtorFn, CalledFunctions))
Anders Carlssona201c4c2011-03-20 17:59:11 +00002922 continue;
2923
2924 // Just remove the call.
Anders Carlssonb12caf32011-03-21 14:54:40 +00002925 CI->replaceAllUsesWith(Constant::getNullValue(CI->getType()));
2926 CI->eraseFromParent();
Anders Carlsson1f7c7ba2011-03-20 19:51:13 +00002927
Anders Carlssona201c4c2011-03-20 17:59:11 +00002928 ++NumCXXDtorsRemoved;
2929
2930 Changed |= true;
2931 }
2932
2933 return Changed;
2934}
2935
Chris Lattner7a90b682004-10-07 04:16:33 +00002936bool GlobalOpt::runOnModule(Module &M) {
Chris Lattner079236d2004-02-25 21:34:36 +00002937 bool Changed = false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002938
Nick Lewycky6a577f82012-02-12 01:13:18 +00002939 TD = getAnalysisIfAvailable<TargetData>();
Nick Lewycky6a7df9a2012-02-12 02:15:20 +00002940 TLI = &getAnalysis<TargetLibraryInfo>();
Nick Lewycky6a577f82012-02-12 01:13:18 +00002941
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002942 // Try to find the llvm.globalctors list.
2943 GlobalVariable *GlobalCtors = FindGlobalCtors(M);
Chris Lattner7a90b682004-10-07 04:16:33 +00002944
Nick Lewycky6a7df9a2012-02-12 02:15:20 +00002945 Function *CXAAtExitFn = FindCXAAtExit(M, TLI);
Anders Carlssona201c4c2011-03-20 17:59:11 +00002946
Chris Lattner7a90b682004-10-07 04:16:33 +00002947 bool LocalChange = true;
2948 while (LocalChange) {
2949 LocalChange = false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002950
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002951 // Delete functions that are trivially dead, ccc -> fastcc
2952 LocalChange |= OptimizeFunctions(M);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002953
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002954 // Optimize global_ctors list.
2955 if (GlobalCtors)
2956 LocalChange |= OptimizeGlobalCtorsList(GlobalCtors);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002957
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002958 // Optimize non-address-taken globals.
2959 LocalChange |= OptimizeGlobalVars(M);
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002960
2961 // Resolve aliases, when possible.
Duncan Sandsfc5940d2009-03-06 10:21:56 +00002962 LocalChange |= OptimizeGlobalAliases(M);
Anders Carlssona201c4c2011-03-20 17:59:11 +00002963
2964 // Try to remove trivial global destructors.
2965 if (CXAAtExitFn)
2966 LocalChange |= OptimizeEmptyGlobalCXXDtors(CXAAtExitFn);
2967
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002968 Changed |= LocalChange;
Chris Lattner7a90b682004-10-07 04:16:33 +00002969 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002970
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002971 // TODO: Move all global ctors functions to the end of the module for code
2972 // layout.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002973
Chris Lattner079236d2004-02-25 21:34:36 +00002974 return Changed;
2975}