blob: 9d7477a9ac301b4a9ad7897bd6aadf9ba8de59d2 [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);
Chris Lattner079236d2004-02-25 21:34:36 +000085 };
Chris Lattner079236d2004-02-25 21:34:36 +000086}
87
Dan Gohman844731a2008-05-13 00:00:25 +000088char GlobalOpt::ID = 0;
Chad Rosier00737bd2011-12-01 21:29:16 +000089INITIALIZE_PASS_BEGIN(GlobalOpt, "globalopt",
90 "Global Variable Optimizer", false, false)
91INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
92INITIALIZE_PASS_END(GlobalOpt, "globalopt",
Owen Andersonce665bd2010-10-07 22:25:06 +000093 "Global Variable Optimizer", false, false)
Dan Gohman844731a2008-05-13 00:00:25 +000094
Chris Lattner7a90b682004-10-07 04:16:33 +000095ModulePass *llvm::createGlobalOptimizerPass() { return new GlobalOpt(); }
Chris Lattner079236d2004-02-25 21:34:36 +000096
Dan Gohman844731a2008-05-13 00:00:25 +000097namespace {
98
Chris Lattner7a90b682004-10-07 04:16:33 +000099/// GlobalStatus - As we analyze each global, keep track of some information
100/// about it. If we find out that the address of the global is taken, none of
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000101/// this info will be accurate.
Nick Lewycky6726b6d2009-10-25 06:33:48 +0000102struct GlobalStatus {
Rafael Espindolac4440e32011-01-19 16:32:21 +0000103 /// isCompared - True if the global's address is used in a comparison.
104 bool isCompared;
105
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000106 /// isLoaded - True if the global is ever loaded. If the global isn't ever
107 /// loaded it can be deleted.
Chris Lattner7a90b682004-10-07 04:16:33 +0000108 bool isLoaded;
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000109
110 /// StoredType - Keep track of what stores to the global look like.
111 ///
Chris Lattner7a90b682004-10-07 04:16:33 +0000112 enum StoredType {
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000113 /// NotStored - There is no store to this global. It can thus be marked
114 /// constant.
115 NotStored,
116
117 /// isInitializerStored - This global is stored to, but the only thing
118 /// stored is the constant it was initialized with. This is only tracked
119 /// for scalar globals.
120 isInitializerStored,
121
122 /// isStoredOnce - This global is stored to, but only its initializer and
123 /// one other value is ever stored to it. If this global isStoredOnce, we
124 /// track the value stored to it in StoredOnceValue below. This is only
125 /// tracked for scalar globals.
126 isStoredOnce,
127
128 /// isStored - This global is stored to by multiple values or something else
129 /// that we cannot track.
130 isStored
Chris Lattner7a90b682004-10-07 04:16:33 +0000131 } StoredType;
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000132
133 /// StoredOnceValue - If only one value (besides the initializer constant) is
134 /// ever stored to this global, keep track of what value it is.
135 Value *StoredOnceValue;
136
Chris Lattner25de4e52006-11-01 18:03:33 +0000137 /// AccessingFunction/HasMultipleAccessingFunctions - These start out
138 /// null/false. When the first accessing function is noticed, it is recorded.
139 /// When a second different accessing function is noticed,
140 /// HasMultipleAccessingFunctions is set to true.
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000141 const Function *AccessingFunction;
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +0000142 bool HasMultipleAccessingFunctions;
143
Chris Lattner25de4e52006-11-01 18:03:33 +0000144 /// HasNonInstructionUser - Set to true if this global has a user that is not
145 /// an instruction (e.g. a constant expr or GV initializer).
Chris Lattner553ca522005-06-15 21:11:48 +0000146 bool HasNonInstructionUser;
147
Chris Lattner25de4e52006-11-01 18:03:33 +0000148 /// HasPHIUser - Set to true if this global has a user that is a PHI node.
149 bool HasPHIUser;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000150
Nick Lewyckyfad4d402012-02-05 19:56:38 +0000151 /// AtomicOrdering - Set to the strongest atomic ordering requirement.
152 AtomicOrdering Ordering;
153
Rafael Espindolac4440e32011-01-19 16:32:21 +0000154 GlobalStatus() : isCompared(false), isLoaded(false), StoredType(NotStored),
155 StoredOnceValue(0), AccessingFunction(0),
Nick Lewyckyfad4d402012-02-05 19:56:38 +0000156 HasMultipleAccessingFunctions(false),
157 HasNonInstructionUser(false), HasPHIUser(false),
158 Ordering(NotAtomic) {}
Chris Lattner7a90b682004-10-07 04:16:33 +0000159};
Chris Lattnere47ba742004-10-06 20:57:02 +0000160
Dan Gohman844731a2008-05-13 00:00:25 +0000161}
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000162
Nick Lewyckyfad4d402012-02-05 19:56:38 +0000163/// StrongerOrdering - Return the stronger of the two ordering. If the two
164/// orderings are acquire and release, then return AcquireRelease.
165///
166static AtomicOrdering StrongerOrdering(AtomicOrdering X, AtomicOrdering Y) {
167 if (X == Acquire && Y == Release) return AcquireRelease;
168 if (Y == Acquire && X == Release) return AcquireRelease;
169 return (AtomicOrdering)std::max(X, Y);
170}
171
Nick Lewyckybc384a12012-02-05 19:48:37 +0000172/// SafeToDestroyConstant - It is safe to destroy a constant iff it is only used
173/// by constants itself. Note that constants cannot be cyclic, so this test is
174/// pretty easy to implement recursively.
175///
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000176static bool SafeToDestroyConstant(const Constant *C) {
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000177 if (isa<GlobalValue>(C)) return false;
178
Gabor Greif27236912010-04-07 18:59:26 +0000179 for (Value::const_use_iterator UI = C->use_begin(), E = C->use_end(); UI != E;
180 ++UI)
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000181 if (const Constant *CU = dyn_cast<Constant>(*UI)) {
Jay Foade3acf152009-06-09 21:37:11 +0000182 if (!SafeToDestroyConstant(CU)) return false;
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000183 } else
184 return false;
185 return true;
186}
187
188
Chris Lattner7a90b682004-10-07 04:16:33 +0000189/// AnalyzeGlobal - Look at all uses of the global and fill in the GlobalStatus
190/// structure. If the global has its address taken, return true to indicate we
191/// can't do anything with it.
Chris Lattner079236d2004-02-25 21:34:36 +0000192///
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000193static bool AnalyzeGlobal(const Value *V, GlobalStatus &GS,
194 SmallPtrSet<const PHINode*, 16> &PHIUsers) {
Gabor Greif27236912010-04-07 18:59:26 +0000195 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;
Gabor Greife6642672010-07-09 16:51:20 +0000196 ++UI) {
197 const User *U = *UI;
198 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
Chris Lattner553ca522005-06-15 21:11:48 +0000199 GS.HasNonInstructionUser = true;
Chris Lattnerd91ed102011-01-01 22:31:46 +0000200
201 // If the result of the constantexpr isn't pointer type, then we won't
202 // know to expect it in various places. Just reject early.
203 if (!isa<PointerType>(CE->getType())) return true;
204
Chris Lattner7a90b682004-10-07 04:16:33 +0000205 if (AnalyzeGlobal(CE, GS, PHIUsers)) return true;
Gabor Greife6642672010-07-09 16:51:20 +0000206 } else if (const Instruction *I = dyn_cast<Instruction>(U)) {
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +0000207 if (!GS.HasMultipleAccessingFunctions) {
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000208 const Function *F = I->getParent()->getParent();
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +0000209 if (GS.AccessingFunction == 0)
210 GS.AccessingFunction = F;
211 else if (GS.AccessingFunction != F)
212 GS.HasMultipleAccessingFunctions = true;
213 }
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000214 if (const LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattner7a90b682004-10-07 04:16:33 +0000215 GS.isLoaded = true;
Nick Lewyckyfad4d402012-02-05 19:56:38 +0000216 // Don't hack on volatile loads.
217 if (LI->isVolatile()) return true;
218 GS.Ordering = StrongerOrdering(GS.Ordering, LI->getOrdering());
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000219 } else if (const StoreInst *SI = dyn_cast<StoreInst>(I)) {
Chris Lattner36025492004-10-07 06:01:25 +0000220 // Don't allow a store OF the address, only stores TO the address.
221 if (SI->getOperand(0) == V) return true;
222
Nick Lewyckyfad4d402012-02-05 19:56:38 +0000223 // Don't hack on volatile stores.
224 if (SI->isVolatile()) return true;
225 GS.Ordering = StrongerOrdering(GS.Ordering, SI->getOrdering());
Chris Lattnerc69d3c92008-01-29 19:01:37 +0000226
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000227 // If this is a direct store to the global (i.e., the global is a scalar
228 // value, not an aggregate), keep more specific information about
229 // stores.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000230 if (GS.StoredType != GlobalStatus::isStored) {
Gabor Greif27236912010-04-07 18:59:26 +0000231 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(
232 SI->getOperand(1))) {
Chris Lattnerbd38edf2004-11-14 20:50:30 +0000233 Value *StoredVal = SI->getOperand(0);
234 if (StoredVal == GV->getInitializer()) {
235 if (GS.StoredType < GlobalStatus::isInitializerStored)
236 GS.StoredType = GlobalStatus::isInitializerStored;
237 } else if (isa<LoadInst>(StoredVal) &&
238 cast<LoadInst>(StoredVal)->getOperand(0) == GV) {
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000239 if (GS.StoredType < GlobalStatus::isInitializerStored)
240 GS.StoredType = GlobalStatus::isInitializerStored;
241 } else if (GS.StoredType < GlobalStatus::isStoredOnce) {
242 GS.StoredType = GlobalStatus::isStoredOnce;
Chris Lattnerbd38edf2004-11-14 20:50:30 +0000243 GS.StoredOnceValue = StoredVal;
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000244 } else if (GS.StoredType == GlobalStatus::isStoredOnce &&
Chris Lattnerbd38edf2004-11-14 20:50:30 +0000245 GS.StoredOnceValue == StoredVal) {
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000246 // noop.
247 } else {
248 GS.StoredType = GlobalStatus::isStored;
249 }
250 } else {
Chris Lattner7a90b682004-10-07 04:16:33 +0000251 GS.StoredType = GlobalStatus::isStored;
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000252 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000253 }
Chris Lattner35c81b02005-02-27 18:58:52 +0000254 } else if (isa<GetElementPtrInst>(I)) {
Chris Lattner7a90b682004-10-07 04:16:33 +0000255 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Chris Lattner35c81b02005-02-27 18:58:52 +0000256 } else if (isa<SelectInst>(I)) {
Chris Lattner7a90b682004-10-07 04:16:33 +0000257 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000258 } else if (const PHINode *PN = dyn_cast<PHINode>(I)) {
Chris Lattner7a90b682004-10-07 04:16:33 +0000259 // PHI nodes we can check just like select or GEP instructions, but we
260 // have to be careful about infinite recursion.
Chris Lattner5a6bb6a2008-12-16 07:34:30 +0000261 if (PHIUsers.insert(PN)) // Not already visited.
Chris Lattner7a90b682004-10-07 04:16:33 +0000262 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Chris Lattner25de4e52006-11-01 18:03:33 +0000263 GS.HasPHIUser = true;
Reid Spencere4d87aa2006-12-23 06:05:41 +0000264 } else if (isa<CmpInst>(I)) {
Rafael Espindolac4440e32011-01-19 16:32:21 +0000265 GS.isCompared = true;
Nick Lewycky1f237b02011-05-29 18:41:56 +0000266 } else if (const MemTransferInst *MTI = dyn_cast<MemTransferInst>(I)) {
267 if (MTI->isVolatile()) return true;
Gabor Greif9e4f2432010-06-24 14:42:01 +0000268 if (MTI->getArgOperand(0) == V)
Eric Christopher551754c2010-04-16 23:37:20 +0000269 GS.StoredType = GlobalStatus::isStored;
Gabor Greif9e4f2432010-06-24 14:42:01 +0000270 if (MTI->getArgOperand(1) == V)
Chris Lattner35c81b02005-02-27 18:58:52 +0000271 GS.isLoaded = true;
Nick Lewycky1f237b02011-05-29 18:41:56 +0000272 } else if (const MemSetInst *MSI = dyn_cast<MemSetInst>(I)) {
273 assert(MSI->getArgOperand(0) == V && "Memset only takes one pointer!");
274 if (MSI->isVolatile()) return true;
Chris Lattner35c81b02005-02-27 18:58:52 +0000275 GS.StoredType = GlobalStatus::isStored;
Chris Lattner7a90b682004-10-07 04:16:33 +0000276 } else {
277 return true; // Any other non-load instruction might take address!
Chris Lattner9ce30002004-07-20 03:58:07 +0000278 }
Gabor Greife6642672010-07-09 16:51:20 +0000279 } else if (const Constant *C = dyn_cast<Constant>(U)) {
Chris Lattner553ca522005-06-15 21:11:48 +0000280 GS.HasNonInstructionUser = true;
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000281 // We might have a dead and dangling constant hanging off of here.
Jay Foade3acf152009-06-09 21:37:11 +0000282 if (!SafeToDestroyConstant(C))
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000283 return true;
Chris Lattner079236d2004-02-25 21:34:36 +0000284 } else {
Chris Lattner553ca522005-06-15 21:11:48 +0000285 GS.HasNonInstructionUser = true;
286 // Otherwise must be some other user.
Chris Lattner079236d2004-02-25 21:34:36 +0000287 return true;
288 }
Gabor Greife6642672010-07-09 16:51:20 +0000289 }
Chris Lattner079236d2004-02-25 21:34:36 +0000290
291 return false;
292}
293
Chris Lattnere47ba742004-10-06 20:57:02 +0000294/// CleanupConstantGlobalUsers - We just marked GV constant. Loop over all
295/// users of the global, cleaning up the obvious ones. This is largely just a
Chris Lattner031955d2004-10-10 16:43:46 +0000296/// quick scan over the use list to clean up the easy and obvious cruft. This
297/// returns true if it made a change.
Chris Lattner7b550cc2009-11-06 04:27:31 +0000298static bool CleanupConstantGlobalUsers(Value *V, Constant *Init) {
Chris Lattner031955d2004-10-10 16:43:46 +0000299 bool Changed = false;
Chris Lattner7a90b682004-10-07 04:16:33 +0000300 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;) {
301 User *U = *UI++;
Misha Brukmanfd939082005-04-21 23:48:37 +0000302
Chris Lattner7a90b682004-10-07 04:16:33 +0000303 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
Chris Lattner35c81b02005-02-27 18:58:52 +0000304 if (Init) {
305 // Replace the load with the initializer.
306 LI->replaceAllUsesWith(Init);
307 LI->eraseFromParent();
308 Changed = true;
309 }
Chris Lattner7a90b682004-10-07 04:16:33 +0000310 } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
Chris Lattnere47ba742004-10-06 20:57:02 +0000311 // Store must be unreachable or storing Init into the global.
Chris Lattner7a7ed022004-10-16 18:09:00 +0000312 SI->eraseFromParent();
Chris Lattner031955d2004-10-10 16:43:46 +0000313 Changed = true;
Chris Lattner7a90b682004-10-07 04:16:33 +0000314 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
315 if (CE->getOpcode() == Instruction::GetElementPtr) {
Chris Lattneraae4a1c2005-09-26 07:34:35 +0000316 Constant *SubInit = 0;
317 if (Init)
Dan Gohmanc6f69e92009-10-05 16:36:26 +0000318 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
Chris Lattner7b550cc2009-11-06 04:27:31 +0000319 Changed |= CleanupConstantGlobalUsers(CE, SubInit);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000320 } else if (CE->getOpcode() == Instruction::BitCast &&
Duncan Sands1df98592010-02-16 11:11:14 +0000321 CE->getType()->isPointerTy()) {
Chris Lattner35c81b02005-02-27 18:58:52 +0000322 // Pointer cast, delete any stores and memsets to the global.
Chris Lattner7b550cc2009-11-06 04:27:31 +0000323 Changed |= CleanupConstantGlobalUsers(CE, 0);
Chris Lattner35c81b02005-02-27 18:58:52 +0000324 }
325
326 if (CE->use_empty()) {
327 CE->destroyConstant();
328 Changed = true;
Chris Lattner7a90b682004-10-07 04:16:33 +0000329 }
330 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
Chris Lattner7b52fe72007-11-09 17:33:02 +0000331 // Do not transform "gepinst (gep constexpr (GV))" here, because forming
332 // "gepconstexpr (gep constexpr (GV))" will cause the two gep's to fold
333 // and will invalidate our notion of what Init is.
Chris Lattner19450242007-11-13 21:46:23 +0000334 Constant *SubInit = 0;
Chris Lattner7b52fe72007-11-09 17:33:02 +0000335 if (!isa<ConstantExpr>(GEP->getOperand(0))) {
Chad Rosieraab8e282011-12-02 01:26:24 +0000336 // FIXME: use TargetData/TargetLibraryInfo for smarter constant folding.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000337 ConstantExpr *CE =
Chris Lattner7b550cc2009-11-06 04:27:31 +0000338 dyn_cast_or_null<ConstantExpr>(ConstantFoldInstruction(GEP));
Chris Lattner7b52fe72007-11-09 17:33:02 +0000339 if (Init && CE && CE->getOpcode() == Instruction::GetElementPtr)
Dan Gohmanc6f69e92009-10-05 16:36:26 +0000340 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
Chris Lattner7b52fe72007-11-09 17:33:02 +0000341 }
Chris Lattner7b550cc2009-11-06 04:27:31 +0000342 Changed |= CleanupConstantGlobalUsers(GEP, SubInit);
Chris Lattnerc4d81b02004-10-10 16:47:33 +0000343
Chris Lattner031955d2004-10-10 16:43:46 +0000344 if (GEP->use_empty()) {
Chris Lattner7a7ed022004-10-16 18:09:00 +0000345 GEP->eraseFromParent();
Chris Lattner031955d2004-10-10 16:43:46 +0000346 Changed = true;
347 }
Chris Lattner35c81b02005-02-27 18:58:52 +0000348 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U)) { // memset/cpy/mv
349 if (MI->getRawDest() == V) {
350 MI->eraseFromParent();
351 Changed = true;
352 }
353
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000354 } else if (Constant *C = dyn_cast<Constant>(U)) {
355 // If we have a chain of dead constantexprs or other things dangling from
356 // us, and if they are all dead, nuke them without remorse.
Jay Foade3acf152009-06-09 21:37:11 +0000357 if (SafeToDestroyConstant(C)) {
Devang Patel743cdf82009-03-06 01:37:41 +0000358 C->destroyConstant();
Chris Lattner35c81b02005-02-27 18:58:52 +0000359 // This could have invalidated UI, start over from scratch.
Chris Lattner7b550cc2009-11-06 04:27:31 +0000360 CleanupConstantGlobalUsers(V, Init);
Chris Lattner031955d2004-10-10 16:43:46 +0000361 return true;
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000362 }
Chris Lattnere47ba742004-10-06 20:57:02 +0000363 }
364 }
Chris Lattner031955d2004-10-10 16:43:46 +0000365 return Changed;
Chris Lattnere47ba742004-10-06 20:57:02 +0000366}
367
Chris Lattner941db492008-01-14 02:09:12 +0000368/// isSafeSROAElementUse - Return true if the specified instruction is a safe
369/// user of a derived expression from a global that we want to SROA.
370static bool isSafeSROAElementUse(Value *V) {
371 // We might have a dead and dangling constant hanging off of here.
372 if (Constant *C = dyn_cast<Constant>(V))
Jay Foade3acf152009-06-09 21:37:11 +0000373 return SafeToDestroyConstant(C);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000374
Chris Lattner941db492008-01-14 02:09:12 +0000375 Instruction *I = dyn_cast<Instruction>(V);
376 if (!I) return false;
377
378 // Loads are ok.
379 if (isa<LoadInst>(I)) return true;
380
381 // Stores *to* the pointer are ok.
382 if (StoreInst *SI = dyn_cast<StoreInst>(I))
383 return SI->getOperand(0) != V;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000384
Chris Lattner941db492008-01-14 02:09:12 +0000385 // Otherwise, it must be a GEP.
386 GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I);
387 if (GEPI == 0) return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000388
Chris Lattner941db492008-01-14 02:09:12 +0000389 if (GEPI->getNumOperands() < 3 || !isa<Constant>(GEPI->getOperand(1)) ||
390 !cast<Constant>(GEPI->getOperand(1))->isNullValue())
391 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000392
Chris Lattner941db492008-01-14 02:09:12 +0000393 for (Value::use_iterator I = GEPI->use_begin(), E = GEPI->use_end();
394 I != E; ++I)
395 if (!isSafeSROAElementUse(*I))
396 return false;
Chris Lattner727c2102008-01-14 01:31:05 +0000397 return true;
398}
399
Chris Lattner941db492008-01-14 02:09:12 +0000400
401/// IsUserOfGlobalSafeForSRA - U is a direct user of the specified global value.
402/// Look at it and its uses and decide whether it is safe to SROA this global.
403///
404static bool IsUserOfGlobalSafeForSRA(User *U, GlobalValue *GV) {
405 // The user of the global must be a GEP Inst or a ConstantExpr GEP.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000406 if (!isa<GetElementPtrInst>(U) &&
407 (!isa<ConstantExpr>(U) ||
Chris Lattner941db492008-01-14 02:09:12 +0000408 cast<ConstantExpr>(U)->getOpcode() != Instruction::GetElementPtr))
409 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000410
Chris Lattner941db492008-01-14 02:09:12 +0000411 // Check to see if this ConstantExpr GEP is SRA'able. In particular, we
412 // don't like < 3 operand CE's, and we don't like non-constant integer
413 // indices. This enforces that all uses are 'gep GV, 0, C, ...' for some
414 // value of C.
415 if (U->getNumOperands() < 3 || !isa<Constant>(U->getOperand(1)) ||
416 !cast<Constant>(U->getOperand(1))->isNullValue() ||
417 !isa<ConstantInt>(U->getOperand(2)))
418 return false;
419
420 gep_type_iterator GEPI = gep_type_begin(U), E = gep_type_end(U);
421 ++GEPI; // Skip over the pointer index.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000422
Chris Lattner941db492008-01-14 02:09:12 +0000423 // If this is a use of an array allocation, do a bit more checking for sanity.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000424 if (ArrayType *AT = dyn_cast<ArrayType>(*GEPI)) {
Chris Lattner941db492008-01-14 02:09:12 +0000425 uint64_t NumElements = AT->getNumElements();
426 ConstantInt *Idx = cast<ConstantInt>(U->getOperand(2));
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000427
Chris Lattner941db492008-01-14 02:09:12 +0000428 // Check to make sure that index falls within the array. If not,
429 // something funny is going on, so we won't do the optimization.
430 //
431 if (Idx->getZExtValue() >= NumElements)
432 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000433
Chris Lattner941db492008-01-14 02:09:12 +0000434 // We cannot scalar repl this level of the array unless any array
435 // sub-indices are in-range constants. In particular, consider:
436 // A[0][i]. We cannot know that the user isn't doing invalid things like
437 // allowing i to index an out-of-range subscript that accesses A[1].
438 //
439 // Scalar replacing *just* the outer index of the array is probably not
440 // going to be a win anyway, so just give up.
441 for (++GEPI; // Skip array index.
Dan Gohman6874a2a2009-08-18 14:58:19 +0000442 GEPI != E;
Chris Lattner941db492008-01-14 02:09:12 +0000443 ++GEPI) {
444 uint64_t NumElements;
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000445 if (ArrayType *SubArrayTy = dyn_cast<ArrayType>(*GEPI))
Chris Lattner941db492008-01-14 02:09:12 +0000446 NumElements = SubArrayTy->getNumElements();
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000447 else if (VectorType *SubVectorTy = dyn_cast<VectorType>(*GEPI))
Dan Gohman6874a2a2009-08-18 14:58:19 +0000448 NumElements = SubVectorTy->getNumElements();
449 else {
Duncan Sands1df98592010-02-16 11:11:14 +0000450 assert((*GEPI)->isStructTy() &&
Dan Gohman6874a2a2009-08-18 14:58:19 +0000451 "Indexed GEP type is not array, vector, or struct!");
452 continue;
453 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000454
Chris Lattner941db492008-01-14 02:09:12 +0000455 ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPI.getOperand());
456 if (!IdxVal || IdxVal->getZExtValue() >= NumElements)
457 return false;
458 }
459 }
460
461 for (Value::use_iterator I = U->use_begin(), E = U->use_end(); I != E; ++I)
462 if (!isSafeSROAElementUse(*I))
463 return false;
464 return true;
465}
466
467/// GlobalUsersSafeToSRA - Look at all uses of the global and decide whether it
468/// is safe for us to perform this transformation.
469///
470static bool GlobalUsersSafeToSRA(GlobalValue *GV) {
471 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end();
472 UI != E; ++UI) {
473 if (!IsUserOfGlobalSafeForSRA(*UI, GV))
474 return false;
475 }
476 return true;
477}
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000478
Chris Lattner941db492008-01-14 02:09:12 +0000479
Chris Lattner670c8892004-10-08 17:32:09 +0000480/// SRAGlobal - Perform scalar replacement of aggregates on the specified global
481/// variable. This opens the door for other optimizations by exposing the
482/// behavior of the program in a more fine-grained way. We have determined that
483/// this transformation is safe already. We return the first global variable we
484/// insert so that the caller can reprocess it.
Chris Lattner7b550cc2009-11-06 04:27:31 +0000485static GlobalVariable *SRAGlobal(GlobalVariable *GV, const TargetData &TD) {
Chris Lattner727c2102008-01-14 01:31:05 +0000486 // Make sure this global only has simple uses that we can SRA.
Chris Lattner941db492008-01-14 02:09:12 +0000487 if (!GlobalUsersSafeToSRA(GV))
Chris Lattner727c2102008-01-14 01:31:05 +0000488 return 0;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000489
Rafael Espindolabb46f522009-01-15 20:18:42 +0000490 assert(GV->hasLocalLinkage() && !GV->isConstant());
Chris Lattner670c8892004-10-08 17:32:09 +0000491 Constant *Init = GV->getInitializer();
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000492 Type *Ty = Init->getType();
Misha Brukmanfd939082005-04-21 23:48:37 +0000493
Chris Lattner670c8892004-10-08 17:32:09 +0000494 std::vector<GlobalVariable*> NewGlobals;
495 Module::GlobalListType &Globals = GV->getParent()->getGlobalList();
496
Chris Lattner998182b2008-04-26 07:40:11 +0000497 // Get the alignment of the global, either explicit or target-specific.
498 unsigned StartAlignment = GV->getAlignment();
499 if (StartAlignment == 0)
500 StartAlignment = TD.getABITypeAlignment(GV->getType());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000501
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000502 if (StructType *STy = dyn_cast<StructType>(Ty)) {
Chris Lattner670c8892004-10-08 17:32:09 +0000503 NewGlobals.reserve(STy->getNumElements());
Chris Lattner998182b2008-04-26 07:40:11 +0000504 const StructLayout &Layout = *TD.getStructLayout(STy);
Chris Lattner670c8892004-10-08 17:32:09 +0000505 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
Chris Lattnera1f00f42012-01-25 06:48:06 +0000506 Constant *In = Init->getAggregateElement(i);
Chris Lattner670c8892004-10-08 17:32:09 +0000507 assert(In && "Couldn't get element of initializer?");
Chris Lattner7b550cc2009-11-06 04:27:31 +0000508 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(i), false,
Chris Lattner670c8892004-10-08 17:32:09 +0000509 GlobalVariable::InternalLinkage,
Daniel Dunbarfe09b202009-07-30 17:37:43 +0000510 In, GV->getName()+"."+Twine(i),
Matthijs Kooijmanbc1f9892008-07-17 11:59:53 +0000511 GV->isThreadLocal(),
Owen Anderson3d29df32009-07-08 01:26:06 +0000512 GV->getType()->getAddressSpace());
Chris Lattner670c8892004-10-08 17:32:09 +0000513 Globals.insert(GV, NGV);
514 NewGlobals.push_back(NGV);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000515
Chris Lattner998182b2008-04-26 07:40:11 +0000516 // Calculate the known alignment of the field. If the original aggregate
517 // had 256 byte alignment for example, something might depend on that:
518 // propagate info to each field.
519 uint64_t FieldOffset = Layout.getElementOffset(i);
520 unsigned NewAlign = (unsigned)MinAlign(StartAlignment, FieldOffset);
521 if (NewAlign > TD.getABITypeAlignment(STy->getElementType(i)))
522 NGV->setAlignment(NewAlign);
Chris Lattner670c8892004-10-08 17:32:09 +0000523 }
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000524 } else if (SequentialType *STy = dyn_cast<SequentialType>(Ty)) {
Chris Lattner670c8892004-10-08 17:32:09 +0000525 unsigned NumElements = 0;
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000526 if (ArrayType *ATy = dyn_cast<ArrayType>(STy))
Chris Lattner670c8892004-10-08 17:32:09 +0000527 NumElements = ATy->getNumElements();
Chris Lattner670c8892004-10-08 17:32:09 +0000528 else
Chris Lattner998182b2008-04-26 07:40:11 +0000529 NumElements = cast<VectorType>(STy)->getNumElements();
Chris Lattner670c8892004-10-08 17:32:09 +0000530
Chris Lattner1f21ef12005-02-23 16:53:04 +0000531 if (NumElements > 16 && GV->hasNUsesOrMore(16))
Chris Lattnerd514d822005-02-01 01:23:31 +0000532 return 0; // It's not worth it.
Chris Lattner670c8892004-10-08 17:32:09 +0000533 NewGlobals.reserve(NumElements);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000534
Duncan Sands777d2302009-05-09 07:06:46 +0000535 uint64_t EltSize = TD.getTypeAllocSize(STy->getElementType());
Chris Lattner998182b2008-04-26 07:40:11 +0000536 unsigned EltAlign = TD.getABITypeAlignment(STy->getElementType());
Chris Lattner670c8892004-10-08 17:32:09 +0000537 for (unsigned i = 0, e = NumElements; i != e; ++i) {
Chris Lattnera1f00f42012-01-25 06:48:06 +0000538 Constant *In = Init->getAggregateElement(i);
Chris Lattner670c8892004-10-08 17:32:09 +0000539 assert(In && "Couldn't get element of initializer?");
540
Chris Lattner7b550cc2009-11-06 04:27:31 +0000541 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(), false,
Chris Lattner670c8892004-10-08 17:32:09 +0000542 GlobalVariable::InternalLinkage,
Daniel Dunbarfe09b202009-07-30 17:37:43 +0000543 In, GV->getName()+"."+Twine(i),
Matthijs Kooijmanbc1f9892008-07-17 11:59:53 +0000544 GV->isThreadLocal(),
Owen Andersone9b11b42009-07-08 19:03:57 +0000545 GV->getType()->getAddressSpace());
Chris Lattner670c8892004-10-08 17:32:09 +0000546 Globals.insert(GV, NGV);
547 NewGlobals.push_back(NGV);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000548
Chris Lattner998182b2008-04-26 07:40:11 +0000549 // Calculate the known alignment of the field. If the original aggregate
550 // had 256 byte alignment for example, something might depend on that:
551 // propagate info to each field.
552 unsigned NewAlign = (unsigned)MinAlign(StartAlignment, EltSize*i);
553 if (NewAlign > EltAlign)
554 NGV->setAlignment(NewAlign);
Chris Lattner670c8892004-10-08 17:32:09 +0000555 }
556 }
557
558 if (NewGlobals.empty())
559 return 0;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000560
David Greene3215b0e2010-01-05 01:28:05 +0000561 DEBUG(dbgs() << "PERFORMING GLOBAL SRA ON: " << *GV);
Chris Lattner30ba5692004-10-11 05:54:41 +0000562
Chris Lattner7b550cc2009-11-06 04:27:31 +0000563 Constant *NullInt =Constant::getNullValue(Type::getInt32Ty(GV->getContext()));
Chris Lattner670c8892004-10-08 17:32:09 +0000564
565 // Loop over all of the uses of the global, replacing the constantexpr geps,
566 // with smaller constantexpr geps or direct references.
567 while (!GV->use_empty()) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000568 User *GEP = GV->use_back();
569 assert(((isa<ConstantExpr>(GEP) &&
570 cast<ConstantExpr>(GEP)->getOpcode()==Instruction::GetElementPtr)||
571 isa<GetElementPtrInst>(GEP)) && "NonGEP CE's are not SRAable!");
Misha Brukmanfd939082005-04-21 23:48:37 +0000572
Chris Lattner670c8892004-10-08 17:32:09 +0000573 // Ignore the 1th operand, which has to be zero or else the program is quite
574 // broken (undefined). Get the 2nd operand, which is the structure or array
575 // index.
Reid Spencerb83eb642006-10-20 07:07:24 +0000576 unsigned Val = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
Chris Lattner670c8892004-10-08 17:32:09 +0000577 if (Val >= NewGlobals.size()) Val = 0; // Out of bound array access.
578
Chris Lattner30ba5692004-10-11 05:54:41 +0000579 Value *NewPtr = NewGlobals[Val];
Chris Lattner670c8892004-10-08 17:32:09 +0000580
581 // Form a shorter GEP if needed.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000582 if (GEP->getNumOperands() > 3) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000583 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEP)) {
Chris Lattner55eb1c42007-01-31 04:40:53 +0000584 SmallVector<Constant*, 8> Idxs;
Chris Lattner30ba5692004-10-11 05:54:41 +0000585 Idxs.push_back(NullInt);
586 for (unsigned i = 3, e = CE->getNumOperands(); i != e; ++i)
587 Idxs.push_back(CE->getOperand(i));
Jay Foaddab3d292011-07-21 14:31:17 +0000588 NewPtr = ConstantExpr::getGetElementPtr(cast<Constant>(NewPtr), Idxs);
Chris Lattner30ba5692004-10-11 05:54:41 +0000589 } else {
590 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(GEP);
Chris Lattner699d1442007-01-31 19:59:55 +0000591 SmallVector<Value*, 8> Idxs;
Chris Lattner30ba5692004-10-11 05:54:41 +0000592 Idxs.push_back(NullInt);
593 for (unsigned i = 3, e = GEPI->getNumOperands(); i != e; ++i)
594 Idxs.push_back(GEPI->getOperand(i));
Jay Foada9203102011-07-25 09:48:08 +0000595 NewPtr = GetElementPtrInst::Create(NewPtr, Idxs,
Daniel Dunbarfe09b202009-07-30 17:37:43 +0000596 GEPI->getName()+"."+Twine(Val),GEPI);
Chris Lattner30ba5692004-10-11 05:54:41 +0000597 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000598 }
Chris Lattner30ba5692004-10-11 05:54:41 +0000599 GEP->replaceAllUsesWith(NewPtr);
600
601 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(GEP))
Chris Lattner7a7ed022004-10-16 18:09:00 +0000602 GEPI->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +0000603 else
604 cast<ConstantExpr>(GEP)->destroyConstant();
Chris Lattner670c8892004-10-08 17:32:09 +0000605 }
606
Chris Lattnere40e2d12004-10-08 20:25:55 +0000607 // Delete the old global, now that it is dead.
608 Globals.erase(GV);
Chris Lattner670c8892004-10-08 17:32:09 +0000609 ++NumSRA;
Chris Lattner30ba5692004-10-11 05:54:41 +0000610
611 // Loop over the new globals array deleting any globals that are obviously
612 // dead. This can arise due to scalarization of a structure or an array that
613 // has elements that are dead.
614 unsigned FirstGlobal = 0;
615 for (unsigned i = 0, e = NewGlobals.size(); i != e; ++i)
616 if (NewGlobals[i]->use_empty()) {
617 Globals.erase(NewGlobals[i]);
618 if (FirstGlobal == i) ++FirstGlobal;
619 }
620
621 return FirstGlobal != NewGlobals.size() ? NewGlobals[FirstGlobal] : 0;
Chris Lattner670c8892004-10-08 17:32:09 +0000622}
623
Chris Lattner9b34a612004-10-09 21:48:45 +0000624/// AllUsesOfValueWillTrapIfNull - Return true if all users of the specified
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000625/// value will trap if the value is dynamically null. PHIs keeps track of any
Chris Lattner81686182007-09-13 16:30:19 +0000626/// phi nodes we've seen to avoid reprocessing them.
Gabor Greif6ce02b52010-04-06 19:24:18 +0000627static bool AllUsesOfValueWillTrapIfNull(const Value *V,
628 SmallPtrSet<const PHINode*, 8> &PHIs) {
629 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;
Gabor Greifa01d6db2010-04-06 19:14:05 +0000630 ++UI) {
Gabor Greif6ce02b52010-04-06 19:24:18 +0000631 const User *U = *UI;
Gabor Greifa01d6db2010-04-06 19:14:05 +0000632
633 if (isa<LoadInst>(U)) {
Chris Lattner9b34a612004-10-09 21:48:45 +0000634 // Will trap.
Gabor Greif6ce02b52010-04-06 19:24:18 +0000635 } else if (const StoreInst *SI = dyn_cast<StoreInst>(U)) {
Chris Lattner9b34a612004-10-09 21:48:45 +0000636 if (SI->getOperand(0) == V) {
Gabor Greifa01d6db2010-04-06 19:14:05 +0000637 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner9b34a612004-10-09 21:48:45 +0000638 return false; // Storing the value.
639 }
Gabor Greif6ce02b52010-04-06 19:24:18 +0000640 } else if (const CallInst *CI = dyn_cast<CallInst>(U)) {
Gabor Greif654c06f2010-03-20 21:00:25 +0000641 if (CI->getCalledValue() != V) {
Gabor Greifa01d6db2010-04-06 19:14:05 +0000642 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner9b34a612004-10-09 21:48:45 +0000643 return false; // Not calling the ptr
644 }
Gabor Greif6ce02b52010-04-06 19:24:18 +0000645 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(U)) {
Gabor Greif654c06f2010-03-20 21:00:25 +0000646 if (II->getCalledValue() != V) {
Gabor Greifa01d6db2010-04-06 19:14:05 +0000647 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner9b34a612004-10-09 21:48:45 +0000648 return false; // Not calling the ptr
649 }
Gabor Greif6ce02b52010-04-06 19:24:18 +0000650 } else if (const BitCastInst *CI = dyn_cast<BitCastInst>(U)) {
Chris Lattner81686182007-09-13 16:30:19 +0000651 if (!AllUsesOfValueWillTrapIfNull(CI, PHIs)) return false;
Gabor Greif6ce02b52010-04-06 19:24:18 +0000652 } else if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
Chris Lattner81686182007-09-13 16:30:19 +0000653 if (!AllUsesOfValueWillTrapIfNull(GEPI, PHIs)) return false;
Gabor Greif6ce02b52010-04-06 19:24:18 +0000654 } else if (const PHINode *PN = dyn_cast<PHINode>(U)) {
Chris Lattner81686182007-09-13 16:30:19 +0000655 // If we've already seen this phi node, ignore it, it has already been
656 // checked.
Jakob Stoklund Olesenb489d0f2010-01-29 23:54:14 +0000657 if (PHIs.insert(PN) && !AllUsesOfValueWillTrapIfNull(PN, PHIs))
658 return false;
Gabor Greifa01d6db2010-04-06 19:14:05 +0000659 } else if (isa<ICmpInst>(U) &&
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000660 isa<ConstantPointerNull>(UI->getOperand(1))) {
Nick Lewyckye7ee59b2010-02-25 06:39:10 +0000661 // Ignore icmp X, null
Chris Lattner9b34a612004-10-09 21:48:45 +0000662 } else {
Gabor Greifa01d6db2010-04-06 19:14:05 +0000663 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner9b34a612004-10-09 21:48:45 +0000664 return false;
665 }
Gabor Greifa01d6db2010-04-06 19:14:05 +0000666 }
Chris Lattner9b34a612004-10-09 21:48:45 +0000667 return true;
668}
669
670/// AllUsesOfLoadedValueWillTrapIfNull - Return true if all uses of any loads
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000671/// from GV will trap if the loaded value is null. Note that this also permits
672/// comparisons of the loaded value against null, as a special case.
Gabor Greif6ce02b52010-04-06 19:24:18 +0000673static bool AllUsesOfLoadedValueWillTrapIfNull(const GlobalVariable *GV) {
674 for (Value::const_use_iterator UI = GV->use_begin(), E = GV->use_end();
Gabor Greifa01d6db2010-04-06 19:14:05 +0000675 UI != E; ++UI) {
Gabor Greif6ce02b52010-04-06 19:24:18 +0000676 const User *U = *UI;
Gabor Greifa01d6db2010-04-06 19:14:05 +0000677
Gabor Greif6ce02b52010-04-06 19:24:18 +0000678 if (const LoadInst *LI = dyn_cast<LoadInst>(U)) {
679 SmallPtrSet<const PHINode*, 8> PHIs;
Chris Lattner81686182007-09-13 16:30:19 +0000680 if (!AllUsesOfValueWillTrapIfNull(LI, PHIs))
Chris Lattner9b34a612004-10-09 21:48:45 +0000681 return false;
Gabor Greifa01d6db2010-04-06 19:14:05 +0000682 } else if (isa<StoreInst>(U)) {
Chris Lattner9b34a612004-10-09 21:48:45 +0000683 // Ignore stores to the global.
684 } else {
685 // We don't know or understand this user, bail out.
Gabor Greifa01d6db2010-04-06 19:14:05 +0000686 //cerr << "UNKNOWN USER OF GLOBAL!: " << *U;
Chris Lattner9b34a612004-10-09 21:48:45 +0000687 return false;
688 }
Gabor Greifa01d6db2010-04-06 19:14:05 +0000689 }
Chris Lattner9b34a612004-10-09 21:48:45 +0000690 return true;
691}
692
Chris Lattner7b550cc2009-11-06 04:27:31 +0000693static bool OptimizeAwayTrappingUsesOfValue(Value *V, Constant *NewV) {
Chris Lattner708148e2004-10-10 23:14:11 +0000694 bool Changed = false;
695 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ) {
696 Instruction *I = cast<Instruction>(*UI++);
697 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
698 LI->setOperand(0, NewV);
699 Changed = true;
700 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
701 if (SI->getOperand(1) == V) {
702 SI->setOperand(1, NewV);
703 Changed = true;
704 }
705 } else if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
Gabor Greiffa1f5c22010-04-06 18:45:08 +0000706 CallSite CS(I);
707 if (CS.getCalledValue() == V) {
Chris Lattner708148e2004-10-10 23:14:11 +0000708 // Calling through the pointer! Turn into a direct call, but be careful
709 // that the pointer is not also being passed as an argument.
Gabor Greiffa1f5c22010-04-06 18:45:08 +0000710 CS.setCalledFunction(NewV);
Chris Lattner708148e2004-10-10 23:14:11 +0000711 Changed = true;
712 bool PassedAsArg = false;
Gabor Greiffa1f5c22010-04-06 18:45:08 +0000713 for (unsigned i = 0, e = CS.arg_size(); i != e; ++i)
714 if (CS.getArgument(i) == V) {
Chris Lattner708148e2004-10-10 23:14:11 +0000715 PassedAsArg = true;
Gabor Greiffa1f5c22010-04-06 18:45:08 +0000716 CS.setArgument(i, NewV);
Chris Lattner708148e2004-10-10 23:14:11 +0000717 }
718
719 if (PassedAsArg) {
720 // Being passed as an argument also. Be careful to not invalidate UI!
721 UI = V->use_begin();
722 }
723 }
724 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
725 Changed |= OptimizeAwayTrappingUsesOfValue(CI,
Owen Andersonbaf3c402009-07-29 18:55:55 +0000726 ConstantExpr::getCast(CI->getOpcode(),
Chris Lattner7b550cc2009-11-06 04:27:31 +0000727 NewV, CI->getType()));
Chris Lattner708148e2004-10-10 23:14:11 +0000728 if (CI->use_empty()) {
729 Changed = true;
Chris Lattner7a7ed022004-10-16 18:09:00 +0000730 CI->eraseFromParent();
Chris Lattner708148e2004-10-10 23:14:11 +0000731 }
732 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
733 // Should handle GEP here.
Chris Lattner55eb1c42007-01-31 04:40:53 +0000734 SmallVector<Constant*, 8> Idxs;
735 Idxs.reserve(GEPI->getNumOperands()-1);
Gabor Greif5e463212008-05-29 01:59:18 +0000736 for (User::op_iterator i = GEPI->op_begin() + 1, e = GEPI->op_end();
737 i != e; ++i)
738 if (Constant *C = dyn_cast<Constant>(*i))
Chris Lattner55eb1c42007-01-31 04:40:53 +0000739 Idxs.push_back(C);
Chris Lattner708148e2004-10-10 23:14:11 +0000740 else
741 break;
Chris Lattner55eb1c42007-01-31 04:40:53 +0000742 if (Idxs.size() == GEPI->getNumOperands()-1)
Chris Lattner708148e2004-10-10 23:14:11 +0000743 Changed |= OptimizeAwayTrappingUsesOfValue(GEPI,
Jay Foaddab3d292011-07-21 14:31:17 +0000744 ConstantExpr::getGetElementPtr(NewV, Idxs));
Chris Lattner708148e2004-10-10 23:14:11 +0000745 if (GEPI->use_empty()) {
746 Changed = true;
Chris Lattner7a7ed022004-10-16 18:09:00 +0000747 GEPI->eraseFromParent();
Chris Lattner708148e2004-10-10 23:14:11 +0000748 }
749 }
750 }
751
752 return Changed;
753}
754
755
756/// OptimizeAwayTrappingUsesOfLoads - The specified global has only one non-null
757/// value stored into it. If there are uses of the loaded value that would trap
758/// if the loaded value is dynamically null, then we know that they cannot be
759/// reachable with a null optimize away the load.
Chris Lattner7b550cc2009-11-06 04:27:31 +0000760static bool OptimizeAwayTrappingUsesOfLoads(GlobalVariable *GV, Constant *LV) {
Chris Lattner708148e2004-10-10 23:14:11 +0000761 bool Changed = false;
762
Chris Lattner92c6bd22009-01-14 00:12:58 +0000763 // Keep track of whether we are able to remove all the uses of the global
764 // other than the store that defines it.
765 bool AllNonStoreUsesGone = true;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000766
Chris Lattner708148e2004-10-10 23:14:11 +0000767 // Replace all uses of loads with uses of uses of the stored value.
Chris Lattner92c6bd22009-01-14 00:12:58 +0000768 for (Value::use_iterator GUI = GV->use_begin(), E = GV->use_end(); GUI != E;){
769 User *GlobalUser = *GUI++;
770 if (LoadInst *LI = dyn_cast<LoadInst>(GlobalUser)) {
Chris Lattner7b550cc2009-11-06 04:27:31 +0000771 Changed |= OptimizeAwayTrappingUsesOfValue(LI, LV);
Chris Lattner92c6bd22009-01-14 00:12:58 +0000772 // If we were able to delete all uses of the loads
773 if (LI->use_empty()) {
774 LI->eraseFromParent();
775 Changed = true;
776 } else {
777 AllNonStoreUsesGone = false;
778 }
779 } else if (isa<StoreInst>(GlobalUser)) {
780 // Ignore the store that stores "LV" to the global.
781 assert(GlobalUser->getOperand(1) == GV &&
782 "Must be storing *to* the global");
Chris Lattner708148e2004-10-10 23:14:11 +0000783 } else {
Chris Lattner92c6bd22009-01-14 00:12:58 +0000784 AllNonStoreUsesGone = false;
785
786 // If we get here we could have other crazy uses that are transitively
787 // loaded.
788 assert((isa<PHINode>(GlobalUser) || isa<SelectInst>(GlobalUser) ||
Chris Lattner98a42b22011-05-22 07:15:13 +0000789 isa<ConstantExpr>(GlobalUser) || isa<CmpInst>(GlobalUser)) &&
790 "Only expect load and stores!");
Chris Lattner708148e2004-10-10 23:14:11 +0000791 }
Chris Lattner92c6bd22009-01-14 00:12:58 +0000792 }
Chris Lattner708148e2004-10-10 23:14:11 +0000793
794 if (Changed) {
David Greene3215b0e2010-01-05 01:28:05 +0000795 DEBUG(dbgs() << "OPTIMIZED LOADS FROM STORED ONCE POINTER: " << *GV);
Chris Lattner708148e2004-10-10 23:14:11 +0000796 ++NumGlobUses;
797 }
798
Chris Lattner708148e2004-10-10 23:14:11 +0000799 // If we nuked all of the loads, then none of the stores are needed either,
800 // nor is the global.
Chris Lattner92c6bd22009-01-14 00:12:58 +0000801 if (AllNonStoreUsesGone) {
David Greene3215b0e2010-01-05 01:28:05 +0000802 DEBUG(dbgs() << " *** GLOBAL NOW DEAD!\n");
Chris Lattner7b550cc2009-11-06 04:27:31 +0000803 CleanupConstantGlobalUsers(GV, 0);
Chris Lattner708148e2004-10-10 23:14:11 +0000804 if (GV->use_empty()) {
Chris Lattner7a7ed022004-10-16 18:09:00 +0000805 GV->eraseFromParent();
Chris Lattner708148e2004-10-10 23:14:11 +0000806 ++NumDeleted;
807 }
808 Changed = true;
809 }
810 return Changed;
811}
812
Chris Lattner30ba5692004-10-11 05:54:41 +0000813/// ConstantPropUsersOf - Walk the use list of V, constant folding all of the
814/// instructions that are foldable.
Chris Lattner7b550cc2009-11-06 04:27:31 +0000815static void ConstantPropUsersOf(Value *V) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000816 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; )
817 if (Instruction *I = dyn_cast<Instruction>(*UI++))
Chad Rosieraab8e282011-12-02 01:26:24 +0000818 // FIXME: use TargetData/TargetLibraryInfo for smarter constant folding.
Chris Lattner7b550cc2009-11-06 04:27:31 +0000819 if (Constant *NewC = ConstantFoldInstruction(I)) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000820 I->replaceAllUsesWith(NewC);
821
Chris Lattnerd514d822005-02-01 01:23:31 +0000822 // Advance UI to the next non-I use to avoid invalidating it!
823 // Instructions could multiply use V.
824 while (UI != E && *UI == I)
Chris Lattner30ba5692004-10-11 05:54:41 +0000825 ++UI;
Chris Lattnerd514d822005-02-01 01:23:31 +0000826 I->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +0000827 }
828}
829
830/// OptimizeGlobalAddressOfMalloc - This function takes the specified global
831/// variable, and transforms the program as if it always contained the result of
832/// the specified malloc. Because it is always the result of the specified
833/// malloc, there is no reason to actually DO the malloc. Instead, turn the
Chris Lattner6e8fbad2006-11-30 17:32:29 +0000834/// malloc into a global, and any loads of GV as uses of the new global.
Chris Lattner30ba5692004-10-11 05:54:41 +0000835static GlobalVariable *OptimizeGlobalAddressOfMalloc(GlobalVariable *GV,
Victor Hernandez83d63912009-09-18 22:35:49 +0000836 CallInst *CI,
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000837 Type *AllocTy,
Chris Lattnera6874652010-02-25 22:33:52 +0000838 ConstantInt *NElements,
Nick Lewyckybc384a12012-02-05 19:48:37 +0000839 TargetData *TD) {
Chris Lattnera6874652010-02-25 22:33:52 +0000840 DEBUG(errs() << "PROMOTING GLOBAL: " << *GV << " CALL = " << *CI << '\n');
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000841
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000842 Type *GlobalType;
Chris Lattnera6874652010-02-25 22:33:52 +0000843 if (NElements->getZExtValue() == 1)
844 GlobalType = AllocTy;
845 else
846 // If we have an array allocation, the global variable is of an array.
847 GlobalType = ArrayType::get(AllocTy, NElements->getZExtValue());
Victor Hernandez83d63912009-09-18 22:35:49 +0000848
849 // Create the new global variable. The contents of the malloc'd memory is
850 // undefined, so initialize with an undef value.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000851 GlobalVariable *NewGV = new GlobalVariable(*GV->getParent(),
Chris Lattnere9fd4442010-02-26 23:42:13 +0000852 GlobalType, false,
Chris Lattnera6874652010-02-25 22:33:52 +0000853 GlobalValue::InternalLinkage,
Chris Lattnere9fd4442010-02-26 23:42:13 +0000854 UndefValue::get(GlobalType),
Victor Hernandez83d63912009-09-18 22:35:49 +0000855 GV->getName()+".body",
856 GV,
857 GV->isThreadLocal());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000858
Chris Lattnera6874652010-02-25 22:33:52 +0000859 // If there are bitcast users of the malloc (which is typical, usually we have
860 // a malloc + bitcast) then replace them with uses of the new global. Update
861 // other users to use the global as well.
862 BitCastInst *TheBC = 0;
863 while (!CI->use_empty()) {
864 Instruction *User = cast<Instruction>(CI->use_back());
865 if (BitCastInst *BCI = dyn_cast<BitCastInst>(User)) {
866 if (BCI->getType() == NewGV->getType()) {
867 BCI->replaceAllUsesWith(NewGV);
868 BCI->eraseFromParent();
869 } else {
870 BCI->setOperand(0, NewGV);
871 }
872 } else {
873 if (TheBC == 0)
874 TheBC = new BitCastInst(NewGV, CI->getType(), "newgv", CI);
875 User->replaceUsesOfWith(CI, TheBC);
876 }
877 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000878
Victor Hernandez83d63912009-09-18 22:35:49 +0000879 Constant *RepValue = NewGV;
880 if (NewGV->getType() != GV->getType()->getElementType())
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000881 RepValue = ConstantExpr::getBitCast(RepValue,
Victor Hernandez83d63912009-09-18 22:35:49 +0000882 GV->getType()->getElementType());
883
884 // If there is a comparison against null, we will insert a global bool to
885 // keep track of whether the global was initialized yet or not.
886 GlobalVariable *InitBool =
Chris Lattner7b550cc2009-11-06 04:27:31 +0000887 new GlobalVariable(Type::getInt1Ty(GV->getContext()), false,
Victor Hernandez83d63912009-09-18 22:35:49 +0000888 GlobalValue::InternalLinkage,
Chris Lattner7b550cc2009-11-06 04:27:31 +0000889 ConstantInt::getFalse(GV->getContext()),
890 GV->getName()+".init", GV->isThreadLocal());
Victor Hernandez83d63912009-09-18 22:35:49 +0000891 bool InitBoolUsed = false;
892
893 // Loop over all uses of GV, processing them in turn.
Chris Lattnera6874652010-02-25 22:33:52 +0000894 while (!GV->use_empty()) {
895 if (StoreInst *SI = dyn_cast<StoreInst>(GV->use_back())) {
Victor Hernandez83d63912009-09-18 22:35:49 +0000896 // The global is initialized when the store to it occurs.
Nick Lewyckyfad4d402012-02-05 19:56:38 +0000897 new StoreInst(ConstantInt::getTrue(GV->getContext()), InitBool, false, 0,
898 SI->getOrdering(), SI->getSynchScope(), SI);
Victor Hernandez83d63912009-09-18 22:35:49 +0000899 SI->eraseFromParent();
Chris Lattnera6874652010-02-25 22:33:52 +0000900 continue;
Victor Hernandez83d63912009-09-18 22:35:49 +0000901 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000902
Chris Lattnera6874652010-02-25 22:33:52 +0000903 LoadInst *LI = cast<LoadInst>(GV->use_back());
904 while (!LI->use_empty()) {
905 Use &LoadUse = LI->use_begin().getUse();
906 if (!isa<ICmpInst>(LoadUse.getUser())) {
907 LoadUse = RepValue;
908 continue;
909 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000910
Chris Lattnera6874652010-02-25 22:33:52 +0000911 ICmpInst *ICI = cast<ICmpInst>(LoadUse.getUser());
912 // Replace the cmp X, 0 with a use of the bool value.
Nick Lewyckyfad4d402012-02-05 19:56:38 +0000913 // Sink the load to where the compare was, if atomic rules allow us to.
914 Value *LV = new LoadInst(InitBool, InitBool->getName()+".val", false, 0,
915 LI->getOrdering(), LI->getSynchScope(),
916 LI->isUnordered() ? (Instruction*)ICI : LI);
Chris Lattnera6874652010-02-25 22:33:52 +0000917 InitBoolUsed = true;
918 switch (ICI->getPredicate()) {
919 default: llvm_unreachable("Unknown ICmp Predicate!");
920 case ICmpInst::ICMP_ULT:
921 case ICmpInst::ICMP_SLT: // X < null -> always false
922 LV = ConstantInt::getFalse(GV->getContext());
923 break;
924 case ICmpInst::ICMP_ULE:
925 case ICmpInst::ICMP_SLE:
926 case ICmpInst::ICMP_EQ:
927 LV = BinaryOperator::CreateNot(LV, "notinit", ICI);
928 break;
929 case ICmpInst::ICMP_NE:
930 case ICmpInst::ICMP_UGE:
931 case ICmpInst::ICMP_SGE:
932 case ICmpInst::ICMP_UGT:
933 case ICmpInst::ICMP_SGT:
934 break; // no change.
935 }
936 ICI->replaceAllUsesWith(LV);
937 ICI->eraseFromParent();
938 }
939 LI->eraseFromParent();
940 }
Victor Hernandez83d63912009-09-18 22:35:49 +0000941
942 // If the initialization boolean was used, insert it, otherwise delete it.
943 if (!InitBoolUsed) {
944 while (!InitBool->use_empty()) // Delete initializations
Chris Lattnera6874652010-02-25 22:33:52 +0000945 cast<StoreInst>(InitBool->use_back())->eraseFromParent();
Victor Hernandez83d63912009-09-18 22:35:49 +0000946 delete InitBool;
947 } else
948 GV->getParent()->getGlobalList().insert(GV, InitBool);
949
Chris Lattnera6874652010-02-25 22:33:52 +0000950 // Now the GV is dead, nuke it and the malloc..
Victor Hernandez83d63912009-09-18 22:35:49 +0000951 GV->eraseFromParent();
Victor Hernandez83d63912009-09-18 22:35:49 +0000952 CI->eraseFromParent();
953
954 // To further other optimizations, loop over all users of NewGV and try to
955 // constant prop them. This will promote GEP instructions with constant
956 // indices into GEP constant-exprs, which will allow global-opt to hack on it.
Chris Lattner7b550cc2009-11-06 04:27:31 +0000957 ConstantPropUsersOf(NewGV);
Victor Hernandez83d63912009-09-18 22:35:49 +0000958 if (RepValue != NewGV)
Chris Lattner7b550cc2009-11-06 04:27:31 +0000959 ConstantPropUsersOf(RepValue);
Victor Hernandez83d63912009-09-18 22:35:49 +0000960
961 return NewGV;
962}
963
Chris Lattnerfa07e4f2004-12-02 07:11:07 +0000964/// ValueIsOnlyUsedLocallyOrStoredToOneGlobal - Scan the use-list of V checking
965/// to make sure that there are no complex uses of V. We permit simple things
966/// like dereferencing the pointer, but not storing through the address, unless
967/// it is to the specified global.
Gabor Greif0b520db2010-04-06 18:58:22 +0000968static bool ValueIsOnlyUsedLocallyOrStoredToOneGlobal(const Instruction *V,
969 const GlobalVariable *GV,
Gabor Greifa01d6db2010-04-06 19:14:05 +0000970 SmallPtrSet<const PHINode*, 8> &PHIs) {
Gabor Greif0b520db2010-04-06 18:58:22 +0000971 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end();
Gabor Greifa01d6db2010-04-06 19:14:05 +0000972 UI != E; ++UI) {
Gabor Greif0b520db2010-04-06 18:58:22 +0000973 const Instruction *Inst = cast<Instruction>(*UI);
Gabor Greifa01d6db2010-04-06 19:14:05 +0000974
Chris Lattner49b6d4a2008-12-15 21:08:54 +0000975 if (isa<LoadInst>(Inst) || isa<CmpInst>(Inst)) {
976 continue; // Fine, ignore.
977 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000978
Gabor Greif0b520db2010-04-06 18:58:22 +0000979 if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
Chris Lattnerfa07e4f2004-12-02 07:11:07 +0000980 if (SI->getOperand(0) == V && SI->getOperand(1) != GV)
981 return false; // Storing the pointer itself... bad.
Chris Lattner49b6d4a2008-12-15 21:08:54 +0000982 continue; // Otherwise, storing through it, or storing into GV... fine.
983 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000984
Chris Lattnera2fb2342010-04-10 18:19:22 +0000985 // Must index into the array and into the struct.
986 if (isa<GetElementPtrInst>(Inst) && Inst->getNumOperands() >= 3) {
Chris Lattner49b6d4a2008-12-15 21:08:54 +0000987 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(Inst, GV, PHIs))
Chris Lattnerfa07e4f2004-12-02 07:11:07 +0000988 return false;
Chris Lattner49b6d4a2008-12-15 21:08:54 +0000989 continue;
990 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000991
Gabor Greif0b520db2010-04-06 18:58:22 +0000992 if (const PHINode *PN = dyn_cast<PHINode>(Inst)) {
Chris Lattnerc451f9c2007-09-13 16:37:20 +0000993 // PHIs are ok if all uses are ok. Don't infinitely recurse through PHI
994 // cycles.
995 if (PHIs.insert(PN))
Chris Lattner5e6e4942007-09-14 03:41:21 +0000996 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(PN, GV, PHIs))
997 return false;
Chris Lattner49b6d4a2008-12-15 21:08:54 +0000998 continue;
Chris Lattnerfa07e4f2004-12-02 07:11:07 +0000999 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001000
Gabor Greif0b520db2010-04-06 18:58:22 +00001001 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Inst)) {
Chris Lattner49b6d4a2008-12-15 21:08:54 +00001002 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(BCI, GV, PHIs))
1003 return false;
1004 continue;
1005 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001006
Chris Lattner49b6d4a2008-12-15 21:08:54 +00001007 return false;
1008 }
Chris Lattnerfa07e4f2004-12-02 07:11:07 +00001009 return true;
Chris Lattnerfa07e4f2004-12-02 07:11:07 +00001010}
1011
Chris Lattner86395032006-09-30 23:32:09 +00001012/// ReplaceUsesOfMallocWithGlobal - The Alloc pointer is stored into GV
1013/// somewhere. Transform all uses of the allocation into loads from the
1014/// global and uses of the resultant pointer. Further, delete the store into
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001015/// GV. This assumes that these value pass the
Chris Lattner86395032006-09-30 23:32:09 +00001016/// 'ValueIsOnlyUsedLocallyOrStoredToOneGlobal' predicate.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001017static void ReplaceUsesOfMallocWithGlobal(Instruction *Alloc,
Chris Lattner86395032006-09-30 23:32:09 +00001018 GlobalVariable *GV) {
1019 while (!Alloc->use_empty()) {
Chris Lattnera637a8b2007-09-13 18:00:31 +00001020 Instruction *U = cast<Instruction>(*Alloc->use_begin());
1021 Instruction *InsertPt = U;
Chris Lattner86395032006-09-30 23:32:09 +00001022 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
1023 // If this is the store of the allocation into the global, remove it.
1024 if (SI->getOperand(1) == GV) {
1025 SI->eraseFromParent();
1026 continue;
1027 }
Chris Lattnera637a8b2007-09-13 18:00:31 +00001028 } else if (PHINode *PN = dyn_cast<PHINode>(U)) {
1029 // Insert the load in the corresponding predecessor, not right before the
1030 // PHI.
Gabor Greifa36791d2009-01-23 19:40:15 +00001031 InsertPt = PN->getIncomingBlock(Alloc->use_begin())->getTerminator();
Chris Lattner101f44e2008-12-15 21:44:34 +00001032 } else if (isa<BitCastInst>(U)) {
1033 // Must be bitcast between the malloc and store to initialize the global.
1034 ReplaceUsesOfMallocWithGlobal(U, GV);
1035 U->eraseFromParent();
1036 continue;
1037 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
1038 // If this is a "GEP bitcast" and the user is a store to the global, then
1039 // just process it as a bitcast.
1040 if (GEPI->hasAllZeroIndices() && GEPI->hasOneUse())
1041 if (StoreInst *SI = dyn_cast<StoreInst>(GEPI->use_back()))
1042 if (SI->getOperand(1) == GV) {
1043 // Must be bitcast GEP between the malloc and store to initialize
1044 // the global.
1045 ReplaceUsesOfMallocWithGlobal(GEPI, GV);
1046 GEPI->eraseFromParent();
1047 continue;
1048 }
Chris Lattner86395032006-09-30 23:32:09 +00001049 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001050
Chris Lattner86395032006-09-30 23:32:09 +00001051 // Insert a load from the global, and use it instead of the malloc.
Chris Lattnera637a8b2007-09-13 18:00:31 +00001052 Value *NL = new LoadInst(GV, GV->getName()+".val", InsertPt);
Chris Lattner86395032006-09-30 23:32:09 +00001053 U->replaceUsesOfWith(Alloc, NL);
1054 }
1055}
1056
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001057/// LoadUsesSimpleEnoughForHeapSRA - Verify that all uses of V (a load, or a phi
1058/// of a load) are simple enough to perform heap SRA on. This permits GEP's
1059/// that index through the array and struct field, icmps of null, and PHIs.
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001060static bool LoadUsesSimpleEnoughForHeapSRA(const Value *V,
Gabor Greif27236912010-04-07 18:59:26 +00001061 SmallPtrSet<const PHINode*, 32> &LoadUsingPHIs,
1062 SmallPtrSet<const PHINode*, 32> &LoadUsingPHIsPerLoad) {
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001063 // We permit two users of the load: setcc comparing against the null
1064 // pointer, and a getelementptr of a specific form.
Gabor Greif27236912010-04-07 18:59:26 +00001065 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;
1066 ++UI) {
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001067 const Instruction *User = cast<Instruction>(*UI);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001068
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001069 // Comparison against null is ok.
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001070 if (const ICmpInst *ICI = dyn_cast<ICmpInst>(User)) {
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001071 if (!isa<ConstantPointerNull>(ICI->getOperand(1)))
1072 return false;
1073 continue;
1074 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001075
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001076 // getelementptr is also ok, but only a simple form.
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001077 if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001078 // Must index into the array and into the struct.
1079 if (GEPI->getNumOperands() < 3)
1080 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001081
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001082 // Otherwise the GEP is ok.
1083 continue;
1084 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001085
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001086 if (const PHINode *PN = dyn_cast<PHINode>(User)) {
Evan Cheng5d163962009-06-02 00:56:07 +00001087 if (!LoadUsingPHIsPerLoad.insert(PN))
1088 // This means some phi nodes are dependent on each other.
1089 // Avoid infinite looping!
1090 return false;
1091 if (!LoadUsingPHIs.insert(PN))
1092 // If we have already analyzed this PHI, then it is safe.
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001093 continue;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001094
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001095 // Make sure all uses of the PHI are simple enough to transform.
Evan Cheng5d163962009-06-02 00:56:07 +00001096 if (!LoadUsesSimpleEnoughForHeapSRA(PN,
1097 LoadUsingPHIs, LoadUsingPHIsPerLoad))
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001098 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001099
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001100 continue;
Chris Lattner86395032006-09-30 23:32:09 +00001101 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001102
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001103 // Otherwise we don't know what this is, not ok.
1104 return false;
1105 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001106
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001107 return true;
1108}
1109
1110
1111/// AllGlobalLoadUsesSimpleEnoughForHeapSRA - If all users of values loaded from
1112/// GV are simple enough to perform HeapSRA, return true.
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001113static bool AllGlobalLoadUsesSimpleEnoughForHeapSRA(const GlobalVariable *GV,
Victor Hernandez83d63912009-09-18 22:35:49 +00001114 Instruction *StoredVal) {
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001115 SmallPtrSet<const PHINode*, 32> LoadUsingPHIs;
1116 SmallPtrSet<const PHINode*, 32> LoadUsingPHIsPerLoad;
Gabor Greif27236912010-04-07 18:59:26 +00001117 for (Value::const_use_iterator UI = GV->use_begin(), E = GV->use_end();
1118 UI != E; ++UI)
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001119 if (const LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
Evan Cheng5d163962009-06-02 00:56:07 +00001120 if (!LoadUsesSimpleEnoughForHeapSRA(LI, LoadUsingPHIs,
1121 LoadUsingPHIsPerLoad))
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001122 return false;
Evan Cheng5d163962009-06-02 00:56:07 +00001123 LoadUsingPHIsPerLoad.clear();
1124 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001125
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001126 // If we reach here, we know that all uses of the loads and transitive uses
1127 // (through PHI nodes) are simple enough to transform. However, we don't know
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001128 // that all inputs the to the PHI nodes are in the same equivalence sets.
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001129 // Check to verify that all operands of the PHIs are either PHIS that can be
1130 // transformed, loads from GV, or MI itself.
Gabor Greif27236912010-04-07 18:59:26 +00001131 for (SmallPtrSet<const PHINode*, 32>::const_iterator I = LoadUsingPHIs.begin()
1132 , E = LoadUsingPHIs.end(); I != E; ++I) {
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001133 const PHINode *PN = *I;
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001134 for (unsigned op = 0, e = PN->getNumIncomingValues(); op != e; ++op) {
1135 Value *InVal = PN->getIncomingValue(op);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001136
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001137 // PHI of the stored value itself is ok.
Victor Hernandez83d63912009-09-18 22:35:49 +00001138 if (InVal == StoredVal) continue;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001139
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001140 if (const PHINode *InPN = dyn_cast<PHINode>(InVal)) {
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001141 // One of the PHIs in our set is (optimistically) ok.
1142 if (LoadUsingPHIs.count(InPN))
1143 continue;
1144 return false;
1145 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001146
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001147 // Load from GV is ok.
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001148 if (const LoadInst *LI = dyn_cast<LoadInst>(InVal))
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001149 if (LI->getOperand(0) == GV)
1150 continue;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001151
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001152 // UNDEF? NULL?
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001153
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001154 // Anything else is rejected.
1155 return false;
1156 }
1157 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001158
Chris Lattner86395032006-09-30 23:32:09 +00001159 return true;
1160}
1161
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001162static Value *GetHeapSROAValue(Value *V, unsigned FieldNo,
1163 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001164 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001165 std::vector<Value*> &FieldVals = InsertedScalarizedValues[V];
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001166
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001167 if (FieldNo >= FieldVals.size())
1168 FieldVals.resize(FieldNo+1);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001169
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001170 // If we already have this value, just reuse the previously scalarized
1171 // version.
1172 if (Value *FieldVal = FieldVals[FieldNo])
1173 return FieldVal;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001174
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001175 // Depending on what instruction this is, we have several cases.
1176 Value *Result;
1177 if (LoadInst *LI = dyn_cast<LoadInst>(V)) {
1178 // This is a scalarized version of the load from the global. Just create
1179 // a new Load of the scalarized global.
1180 Result = new LoadInst(GetHeapSROAValue(LI->getOperand(0), FieldNo,
1181 InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001182 PHIsToRewrite),
Daniel Dunbarfe09b202009-07-30 17:37:43 +00001183 LI->getName()+".f"+Twine(FieldNo), LI);
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001184 } else if (PHINode *PN = dyn_cast<PHINode>(V)) {
1185 // PN's type is pointer to struct. Make a new PHI of pointer to struct
1186 // field.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001187 StructType *ST =
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001188 cast<StructType>(cast<PointerType>(PN->getType())->getElementType());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001189
Jay Foadd8b4fb42011-03-30 11:19:20 +00001190 PHINode *NewPN =
Owen Andersondebcb012009-07-29 22:17:13 +00001191 PHINode::Create(PointerType::getUnqual(ST->getElementType(FieldNo)),
Jay Foad3ecfc862011-03-30 11:28:46 +00001192 PN->getNumIncomingValues(),
Daniel Dunbarfe09b202009-07-30 17:37:43 +00001193 PN->getName()+".f"+Twine(FieldNo), PN);
Jay Foadd8b4fb42011-03-30 11:19:20 +00001194 Result = NewPN;
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001195 PHIsToRewrite.push_back(std::make_pair(PN, FieldNo));
1196 } else {
Torok Edwinc23197a2009-07-14 16:55:14 +00001197 llvm_unreachable("Unknown usable value");
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001198 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001199
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001200 return FieldVals[FieldNo] = Result;
Chris Lattnera637a8b2007-09-13 18:00:31 +00001201}
1202
Chris Lattner330245e2007-09-13 17:29:05 +00001203/// RewriteHeapSROALoadUser - Given a load instruction and a value derived from
1204/// the load, rewrite the derived value to use the HeapSRoA'd load.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001205static void RewriteHeapSROALoadUser(Instruction *LoadUser,
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001206 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001207 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
Chris Lattner330245e2007-09-13 17:29:05 +00001208 // If this is a comparison against null, handle it.
1209 if (ICmpInst *SCI = dyn_cast<ICmpInst>(LoadUser)) {
1210 assert(isa<ConstantPointerNull>(SCI->getOperand(1)));
1211 // If we have a setcc of the loaded pointer, we can use a setcc of any
1212 // field.
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001213 Value *NPtr = GetHeapSROAValue(SCI->getOperand(0), 0,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001214 InsertedScalarizedValues, PHIsToRewrite);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001215
Owen Anderson333c4002009-07-09 23:48:35 +00001216 Value *New = new ICmpInst(SCI, SCI->getPredicate(), NPtr,
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001217 Constant::getNullValue(NPtr->getType()),
Owen Anderson333c4002009-07-09 23:48:35 +00001218 SCI->getName());
Chris Lattner330245e2007-09-13 17:29:05 +00001219 SCI->replaceAllUsesWith(New);
1220 SCI->eraseFromParent();
1221 return;
1222 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001223
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001224 // Handle 'getelementptr Ptr, Idx, i32 FieldNo ...'
Chris Lattnera637a8b2007-09-13 18:00:31 +00001225 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(LoadUser)) {
1226 assert(GEPI->getNumOperands() >= 3 && isa<ConstantInt>(GEPI->getOperand(2))
1227 && "Unexpected GEPI!");
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001228
Chris Lattnera637a8b2007-09-13 18:00:31 +00001229 // Load the pointer for this field.
1230 unsigned FieldNo = cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue();
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001231 Value *NewPtr = GetHeapSROAValue(GEPI->getOperand(0), FieldNo,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001232 InsertedScalarizedValues, PHIsToRewrite);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001233
Chris Lattnera637a8b2007-09-13 18:00:31 +00001234 // Create the new GEP idx vector.
1235 SmallVector<Value*, 8> GEPIdx;
1236 GEPIdx.push_back(GEPI->getOperand(1));
1237 GEPIdx.append(GEPI->op_begin()+3, GEPI->op_end());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001238
Jay Foada9203102011-07-25 09:48:08 +00001239 Value *NGEPI = GetElementPtrInst::Create(NewPtr, GEPIdx,
Gabor Greif051a9502008-04-06 20:25:17 +00001240 GEPI->getName(), GEPI);
Chris Lattnera637a8b2007-09-13 18:00:31 +00001241 GEPI->replaceAllUsesWith(NGEPI);
1242 GEPI->eraseFromParent();
1243 return;
1244 }
Chris Lattner309f20f2007-09-13 21:31:36 +00001245
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001246 // Recursively transform the users of PHI nodes. This will lazily create the
1247 // PHIs that are needed for individual elements. Keep track of what PHIs we
1248 // see in InsertedScalarizedValues so that we don't get infinite loops (very
1249 // antisocial). If the PHI is already in InsertedScalarizedValues, it has
1250 // already been seen first by another load, so its uses have already been
1251 // processed.
1252 PHINode *PN = cast<PHINode>(LoadUser);
Chris Lattnerc30a38f2011-07-21 06:21:31 +00001253 if (!InsertedScalarizedValues.insert(std::make_pair(PN,
1254 std::vector<Value*>())).second)
1255 return;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001256
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001257 // If this is the first time we've seen this PHI, recursively process all
1258 // users.
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001259 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end(); UI != E; ) {
1260 Instruction *User = cast<Instruction>(*UI++);
Chris Lattner7b550cc2009-11-06 04:27:31 +00001261 RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite);
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001262 }
Chris Lattner330245e2007-09-13 17:29:05 +00001263}
1264
Chris Lattner86395032006-09-30 23:32:09 +00001265/// RewriteUsesOfLoadForHeapSRoA - We are performing Heap SRoA on a global. Ptr
1266/// is a value loaded from the global. Eliminate all uses of Ptr, making them
1267/// use FieldGlobals instead. All uses of loaded values satisfy
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001268/// AllGlobalLoadUsesSimpleEnoughForHeapSRA.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001269static void RewriteUsesOfLoadForHeapSRoA(LoadInst *Load,
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001270 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001271 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001272 for (Value::use_iterator UI = Load->use_begin(), E = Load->use_end();
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001273 UI != E; ) {
1274 Instruction *User = cast<Instruction>(*UI++);
Chris Lattner7b550cc2009-11-06 04:27:31 +00001275 RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite);
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001276 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001277
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001278 if (Load->use_empty()) {
1279 Load->eraseFromParent();
1280 InsertedScalarizedValues.erase(Load);
1281 }
Chris Lattner86395032006-09-30 23:32:09 +00001282}
1283
Victor Hernandez83d63912009-09-18 22:35:49 +00001284/// PerformHeapAllocSRoA - CI is an allocation of an array of structures. Break
1285/// it up into multiple allocations of arrays of the fields.
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001286static GlobalVariable *PerformHeapAllocSRoA(GlobalVariable *GV, CallInst *CI,
Nick Lewyckybc384a12012-02-05 19:48:37 +00001287 Value *NElems, TargetData *TD) {
David Greene3215b0e2010-01-05 01:28:05 +00001288 DEBUG(dbgs() << "SROA HEAP ALLOC: " << *GV << " MALLOC = " << *CI << '\n');
Nick Lewyckybc384a12012-02-05 19:48:37 +00001289 Type *MAT = getMallocAllocatedType(CI);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001290 StructType *STy = cast<StructType>(MAT);
Victor Hernandez83d63912009-09-18 22:35:49 +00001291
1292 // There is guaranteed to be at least one use of the malloc (storing
1293 // it into GV). If there are other uses, change them to be uses of
1294 // the global to simplify later code. This also deletes the store
1295 // into GV.
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001296 ReplaceUsesOfMallocWithGlobal(CI, GV);
1297
Victor Hernandez83d63912009-09-18 22:35:49 +00001298 // Okay, at this point, there are no users of the malloc. Insert N
1299 // new mallocs at the same place as CI, and N globals.
1300 std::vector<Value*> FieldGlobals;
1301 std::vector<Value*> FieldMallocs;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001302
Victor Hernandez83d63912009-09-18 22:35:49 +00001303 for (unsigned FieldNo = 0, e = STy->getNumElements(); FieldNo != e;++FieldNo){
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001304 Type *FieldTy = STy->getElementType(FieldNo);
1305 PointerType *PFieldTy = PointerType::getUnqual(FieldTy);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001306
Victor Hernandez83d63912009-09-18 22:35:49 +00001307 GlobalVariable *NGV =
1308 new GlobalVariable(*GV->getParent(),
1309 PFieldTy, false, GlobalValue::InternalLinkage,
1310 Constant::getNullValue(PFieldTy),
1311 GV->getName() + ".f" + Twine(FieldNo), GV,
1312 GV->isThreadLocal());
1313 FieldGlobals.push_back(NGV);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001314
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001315 unsigned TypeSize = TD->getTypeAllocSize(FieldTy);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001316 if (StructType *ST = dyn_cast<StructType>(FieldTy))
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001317 TypeSize = TD->getStructLayout(ST)->getSizeInBytes();
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001318 Type *IntPtrTy = TD->getIntPtrType(CI->getContext());
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001319 Value *NMI = CallInst::CreateMalloc(CI, IntPtrTy, FieldTy,
1320 ConstantInt::get(IntPtrTy, TypeSize),
Chris Lattner5a30a852010-07-12 00:57:28 +00001321 NElems, 0,
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001322 CI->getName() + ".f" + Twine(FieldNo));
Chris Lattner3f5e0b82010-02-26 18:23:13 +00001323 FieldMallocs.push_back(NMI);
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001324 new StoreInst(NMI, NGV, CI);
Victor Hernandez83d63912009-09-18 22:35:49 +00001325 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001326
Victor Hernandez83d63912009-09-18 22:35:49 +00001327 // The tricky aspect of this transformation is handling the case when malloc
1328 // fails. In the original code, malloc failing would set the result pointer
1329 // of malloc to null. In this case, some mallocs could succeed and others
1330 // could fail. As such, we emit code that looks like this:
1331 // F0 = malloc(field0)
1332 // F1 = malloc(field1)
1333 // F2 = malloc(field2)
1334 // if (F0 == 0 || F1 == 0 || F2 == 0) {
1335 // if (F0) { free(F0); F0 = 0; }
1336 // if (F1) { free(F1); F1 = 0; }
1337 // if (F2) { free(F2); F2 = 0; }
1338 // }
Victor Hernandez8e345a12009-11-10 08:32:25 +00001339 // The malloc can also fail if its argument is too large.
Gabor Greif9e4f2432010-06-24 14:42:01 +00001340 Constant *ConstantZero = ConstantInt::get(CI->getArgOperand(0)->getType(), 0);
1341 Value *RunningOr = new ICmpInst(CI, ICmpInst::ICMP_SLT, CI->getArgOperand(0),
Victor Hernandez8e345a12009-11-10 08:32:25 +00001342 ConstantZero, "isneg");
Victor Hernandez83d63912009-09-18 22:35:49 +00001343 for (unsigned i = 0, e = FieldMallocs.size(); i != e; ++i) {
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001344 Value *Cond = new ICmpInst(CI, ICmpInst::ICMP_EQ, FieldMallocs[i],
1345 Constant::getNullValue(FieldMallocs[i]->getType()),
1346 "isnull");
Victor Hernandez8e345a12009-11-10 08:32:25 +00001347 RunningOr = BinaryOperator::CreateOr(RunningOr, Cond, "tmp", CI);
Victor Hernandez83d63912009-09-18 22:35:49 +00001348 }
1349
1350 // Split the basic block at the old malloc.
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001351 BasicBlock *OrigBB = CI->getParent();
1352 BasicBlock *ContBB = OrigBB->splitBasicBlock(CI, "malloc_cont");
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001353
Victor Hernandez83d63912009-09-18 22:35:49 +00001354 // Create the block to check the first condition. Put all these blocks at the
1355 // end of the function as they are unlikely to be executed.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001356 BasicBlock *NullPtrBlock = BasicBlock::Create(OrigBB->getContext(),
1357 "malloc_ret_null",
Victor Hernandez83d63912009-09-18 22:35:49 +00001358 OrigBB->getParent());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001359
Victor Hernandez83d63912009-09-18 22:35:49 +00001360 // Remove the uncond branch from OrigBB to ContBB, turning it into a cond
1361 // branch on RunningOr.
1362 OrigBB->getTerminator()->eraseFromParent();
1363 BranchInst::Create(NullPtrBlock, ContBB, RunningOr, OrigBB);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001364
Victor Hernandez83d63912009-09-18 22:35:49 +00001365 // Within the NullPtrBlock, we need to emit a comparison and branch for each
1366 // pointer, because some may be null while others are not.
1367 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
1368 Value *GVVal = new LoadInst(FieldGlobals[i], "tmp", NullPtrBlock);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001369 Value *Cmp = new ICmpInst(*NullPtrBlock, ICmpInst::ICMP_NE, GVVal,
Benjamin Kramera9390a42011-09-27 20:39:19 +00001370 Constant::getNullValue(GVVal->getType()));
Chris Lattner7b550cc2009-11-06 04:27:31 +00001371 BasicBlock *FreeBlock = BasicBlock::Create(Cmp->getContext(), "free_it",
Victor Hernandez83d63912009-09-18 22:35:49 +00001372 OrigBB->getParent());
Chris Lattner7b550cc2009-11-06 04:27:31 +00001373 BasicBlock *NextBlock = BasicBlock::Create(Cmp->getContext(), "next",
Victor Hernandez83d63912009-09-18 22:35:49 +00001374 OrigBB->getParent());
Victor Hernandez66284e02009-10-24 04:23:03 +00001375 Instruction *BI = BranchInst::Create(FreeBlock, NextBlock,
1376 Cmp, NullPtrBlock);
Victor Hernandez83d63912009-09-18 22:35:49 +00001377
1378 // Fill in FreeBlock.
Victor Hernandez66284e02009-10-24 04:23:03 +00001379 CallInst::CreateFree(GVVal, BI);
Victor Hernandez83d63912009-09-18 22:35:49 +00001380 new StoreInst(Constant::getNullValue(GVVal->getType()), FieldGlobals[i],
1381 FreeBlock);
1382 BranchInst::Create(NextBlock, FreeBlock);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001383
Victor Hernandez83d63912009-09-18 22:35:49 +00001384 NullPtrBlock = NextBlock;
1385 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001386
Victor Hernandez83d63912009-09-18 22:35:49 +00001387 BranchInst::Create(ContBB, NullPtrBlock);
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001388
1389 // CI is no longer needed, remove it.
Victor Hernandez83d63912009-09-18 22:35:49 +00001390 CI->eraseFromParent();
1391
1392 /// InsertedScalarizedLoads - As we process loads, if we can't immediately
1393 /// update all uses of the load, keep track of what scalarized loads are
1394 /// inserted for a given load.
1395 DenseMap<Value*, std::vector<Value*> > InsertedScalarizedValues;
1396 InsertedScalarizedValues[GV] = FieldGlobals;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001397
Victor Hernandez83d63912009-09-18 22:35:49 +00001398 std::vector<std::pair<PHINode*, unsigned> > PHIsToRewrite;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001399
Victor Hernandez83d63912009-09-18 22:35:49 +00001400 // Okay, the malloc site is completely handled. All of the uses of GV are now
1401 // loads, and all uses of those loads are simple. Rewrite them to use loads
1402 // of the per-field globals instead.
1403 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI != E;) {
1404 Instruction *User = cast<Instruction>(*UI++);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001405
Victor Hernandez83d63912009-09-18 22:35:49 +00001406 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Chris Lattner7b550cc2009-11-06 04:27:31 +00001407 RewriteUsesOfLoadForHeapSRoA(LI, InsertedScalarizedValues, PHIsToRewrite);
Victor Hernandez83d63912009-09-18 22:35:49 +00001408 continue;
1409 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001410
Victor Hernandez83d63912009-09-18 22:35:49 +00001411 // Must be a store of null.
1412 StoreInst *SI = cast<StoreInst>(User);
1413 assert(isa<ConstantPointerNull>(SI->getOperand(0)) &&
1414 "Unexpected heap-sra user!");
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001415
Victor Hernandez83d63912009-09-18 22:35:49 +00001416 // Insert a store of null into each global.
1417 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001418 PointerType *PT = cast<PointerType>(FieldGlobals[i]->getType());
Victor Hernandez83d63912009-09-18 22:35:49 +00001419 Constant *Null = Constant::getNullValue(PT->getElementType());
1420 new StoreInst(Null, FieldGlobals[i], SI);
1421 }
1422 // Erase the original store.
1423 SI->eraseFromParent();
1424 }
1425
1426 // While we have PHIs that are interesting to rewrite, do it.
1427 while (!PHIsToRewrite.empty()) {
1428 PHINode *PN = PHIsToRewrite.back().first;
1429 unsigned FieldNo = PHIsToRewrite.back().second;
1430 PHIsToRewrite.pop_back();
1431 PHINode *FieldPN = cast<PHINode>(InsertedScalarizedValues[PN][FieldNo]);
1432 assert(FieldPN->getNumIncomingValues() == 0 &&"Already processed this phi");
1433
1434 // Add all the incoming values. This can materialize more phis.
1435 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1436 Value *InVal = PN->getIncomingValue(i);
1437 InVal = GetHeapSROAValue(InVal, FieldNo, InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001438 PHIsToRewrite);
Victor Hernandez83d63912009-09-18 22:35:49 +00001439 FieldPN->addIncoming(InVal, PN->getIncomingBlock(i));
1440 }
1441 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001442
Victor Hernandez83d63912009-09-18 22:35:49 +00001443 // Drop all inter-phi links and any loads that made it this far.
1444 for (DenseMap<Value*, std::vector<Value*> >::iterator
1445 I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
1446 I != E; ++I) {
1447 if (PHINode *PN = dyn_cast<PHINode>(I->first))
1448 PN->dropAllReferences();
1449 else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
1450 LI->dropAllReferences();
1451 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001452
Victor Hernandez83d63912009-09-18 22:35:49 +00001453 // Delete all the phis and loads now that inter-references are dead.
1454 for (DenseMap<Value*, std::vector<Value*> >::iterator
1455 I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
1456 I != E; ++I) {
1457 if (PHINode *PN = dyn_cast<PHINode>(I->first))
1458 PN->eraseFromParent();
1459 else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
1460 LI->eraseFromParent();
1461 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001462
Victor Hernandez83d63912009-09-18 22:35:49 +00001463 // The old global is now dead, remove it.
1464 GV->eraseFromParent();
1465
1466 ++NumHeapSRA;
1467 return cast<GlobalVariable>(FieldGlobals[0]);
1468}
1469
Chris Lattnere61d0a62008-12-15 21:02:25 +00001470/// TryToOptimizeStoreOfMallocToGlobal - This function is called when we see a
1471/// pointer global variable with a single value stored it that is a malloc or
1472/// cast of malloc.
1473static bool TryToOptimizeStoreOfMallocToGlobal(GlobalVariable *GV,
Victor Hernandez83d63912009-09-18 22:35:49 +00001474 CallInst *CI,
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001475 Type *AllocTy,
Nick Lewyckyfad4d402012-02-05 19:56:38 +00001476 AtomicOrdering Ordering,
Victor Hernandez83d63912009-09-18 22:35:49 +00001477 Module::global_iterator &GVI,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001478 TargetData *TD) {
Evan Cheng86cd4452010-04-14 20:52:55 +00001479 if (!TD)
1480 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001481
Victor Hernandez83d63912009-09-18 22:35:49 +00001482 // If this is a malloc of an abstract type, don't touch it.
1483 if (!AllocTy->isSized())
1484 return false;
1485
1486 // We can't optimize this global unless all uses of it are *known* to be
1487 // of the malloc value, not of the null initializer value (consider a use
1488 // that compares the global's value against zero to see if the malloc has
1489 // been reached). To do this, we check to see if all uses of the global
1490 // would trap if the global were null: this proves that they must all
1491 // happen after the malloc.
1492 if (!AllUsesOfLoadedValueWillTrapIfNull(GV))
1493 return false;
1494
1495 // We can't optimize this if the malloc itself is used in a complex way,
1496 // for example, being stored into multiple globals. This allows the
Nick Lewyckybc384a12012-02-05 19:48:37 +00001497 // malloc to be stored into the specified global, loaded icmp'd, and
Victor Hernandez83d63912009-09-18 22:35:49 +00001498 // GEP'd. These are all things we could transform to using the global
1499 // for.
Evan Cheng86cd4452010-04-14 20:52:55 +00001500 SmallPtrSet<const PHINode*, 8> PHIs;
1501 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(CI, GV, PHIs))
1502 return false;
Victor Hernandez83d63912009-09-18 22:35:49 +00001503
1504 // If we have a global that is only initialized with a fixed size malloc,
1505 // transform the program to use global memory instead of malloc'd memory.
1506 // This eliminates dynamic allocation, avoids an indirection accessing the
1507 // data, and exposes the resultant global to further GlobalOpt.
Victor Hernandez8db42d22009-10-16 23:12:25 +00001508 // We cannot optimize the malloc if we cannot determine malloc array size.
Evan Cheng86cd4452010-04-14 20:52:55 +00001509 Value *NElems = getMallocArraySize(CI, TD, true);
1510 if (!NElems)
1511 return false;
Victor Hernandez83d63912009-09-18 22:35:49 +00001512
Evan Cheng86cd4452010-04-14 20:52:55 +00001513 if (ConstantInt *NElements = dyn_cast<ConstantInt>(NElems))
1514 // Restrict this transformation to only working on small allocations
1515 // (2048 bytes currently), as we don't want to introduce a 16M global or
1516 // something.
1517 if (NElements->getZExtValue() * TD->getTypeAllocSize(AllocTy) < 2048) {
1518 GVI = OptimizeGlobalAddressOfMalloc(GV, CI, AllocTy, NElements, TD);
1519 return true;
Victor Hernandez83d63912009-09-18 22:35:49 +00001520 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001521
Evan Cheng86cd4452010-04-14 20:52:55 +00001522 // If the allocation is an array of structures, consider transforming this
1523 // into multiple malloc'd arrays, one for each field. This is basically
1524 // SRoA for malloc'd memory.
1525
Nick Lewyckyfad4d402012-02-05 19:56:38 +00001526 if (Ordering != NotAtomic)
1527 return false;
1528
Evan Cheng86cd4452010-04-14 20:52:55 +00001529 // If this is an allocation of a fixed size array of structs, analyze as a
1530 // variable size array. malloc [100 x struct],1 -> malloc struct, 100
Gabor Greif9e4f2432010-06-24 14:42:01 +00001531 if (NElems == ConstantInt::get(CI->getArgOperand(0)->getType(), 1))
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001532 if (ArrayType *AT = dyn_cast<ArrayType>(AllocTy))
Evan Cheng86cd4452010-04-14 20:52:55 +00001533 AllocTy = AT->getElementType();
Gabor Greif9e4f2432010-06-24 14:42:01 +00001534
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001535 StructType *AllocSTy = dyn_cast<StructType>(AllocTy);
Evan Cheng86cd4452010-04-14 20:52:55 +00001536 if (!AllocSTy)
1537 return false;
1538
1539 // This the structure has an unreasonable number of fields, leave it
1540 // alone.
1541 if (AllocSTy->getNumElements() <= 16 && AllocSTy->getNumElements() != 0 &&
1542 AllGlobalLoadUsesSimpleEnoughForHeapSRA(GV, CI)) {
1543
1544 // If this is a fixed size array, transform the Malloc to be an alloc of
1545 // structs. malloc [100 x struct],1 -> malloc struct, 100
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001546 if (ArrayType *AT = dyn_cast<ArrayType>(getMallocAllocatedType(CI))) {
1547 Type *IntPtrTy = TD->getIntPtrType(CI->getContext());
Evan Cheng86cd4452010-04-14 20:52:55 +00001548 unsigned TypeSize = TD->getStructLayout(AllocSTy)->getSizeInBytes();
1549 Value *AllocSize = ConstantInt::get(IntPtrTy, TypeSize);
1550 Value *NumElements = ConstantInt::get(IntPtrTy, AT->getNumElements());
1551 Instruction *Malloc = CallInst::CreateMalloc(CI, IntPtrTy, AllocSTy,
1552 AllocSize, NumElements,
Chris Lattner5a30a852010-07-12 00:57:28 +00001553 0, CI->getName());
Evan Cheng86cd4452010-04-14 20:52:55 +00001554 Instruction *Cast = new BitCastInst(Malloc, CI->getType(), "tmp", CI);
1555 CI->replaceAllUsesWith(Cast);
1556 CI->eraseFromParent();
1557 CI = dyn_cast<BitCastInst>(Malloc) ?
1558 extractMallocCallFromBitCast(Malloc) : cast<CallInst>(Malloc);
1559 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001560
Nick Lewyckybc384a12012-02-05 19:48:37 +00001561 GVI = PerformHeapAllocSRoA(GV, CI, getMallocArraySize(CI, TD, true), TD);
Evan Cheng86cd4452010-04-14 20:52:55 +00001562 return true;
Victor Hernandez83d63912009-09-18 22:35:49 +00001563 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001564
Victor Hernandez83d63912009-09-18 22:35:49 +00001565 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001566}
Victor Hernandez83d63912009-09-18 22:35:49 +00001567
Chris Lattner9b34a612004-10-09 21:48:45 +00001568// OptimizeOnceStoredGlobal - Try to optimize globals based on the knowledge
1569// that only one value (besides its initializer) is ever stored to the global.
Chris Lattner30ba5692004-10-11 05:54:41 +00001570static bool OptimizeOnceStoredGlobal(GlobalVariable *GV, Value *StoredOnceVal,
Nick Lewyckyfad4d402012-02-05 19:56:38 +00001571 AtomicOrdering Ordering,
Chris Lattner7f8897f2006-08-27 22:42:52 +00001572 Module::global_iterator &GVI,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001573 TargetData *TD) {
Chris Lattner344b41c2008-12-15 21:20:32 +00001574 // Ignore no-op GEPs and bitcasts.
1575 StoredOnceVal = StoredOnceVal->stripPointerCasts();
Chris Lattner9b34a612004-10-09 21:48:45 +00001576
Chris Lattner708148e2004-10-10 23:14:11 +00001577 // If we are dealing with a pointer global that is initialized to null and
1578 // only has one (non-null) value stored into it, then we can optimize any
1579 // users of the loaded value (often calls and loads) that would trap if the
1580 // value was null.
Duncan Sands1df98592010-02-16 11:11:14 +00001581 if (GV->getInitializer()->getType()->isPointerTy() &&
Chris Lattner9b34a612004-10-09 21:48:45 +00001582 GV->getInitializer()->isNullValue()) {
Chris Lattner708148e2004-10-10 23:14:11 +00001583 if (Constant *SOVC = dyn_cast<Constant>(StoredOnceVal)) {
1584 if (GV->getInitializer()->getType() != SOVC->getType())
Chris Lattner98a42b22011-05-22 07:15:13 +00001585 SOVC = ConstantExpr::getBitCast(SOVC, GV->getInitializer()->getType());
Misha Brukmanfd939082005-04-21 23:48:37 +00001586
Chris Lattner708148e2004-10-10 23:14:11 +00001587 // Optimize away any trapping uses of the loaded value.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001588 if (OptimizeAwayTrappingUsesOfLoads(GV, SOVC))
Chris Lattner8be80122004-10-10 17:07:12 +00001589 return true;
Victor Hernandez83d63912009-09-18 22:35:49 +00001590 } else if (CallInst *CI = extractMallocCall(StoredOnceVal)) {
Nick Lewyckybc384a12012-02-05 19:48:37 +00001591 Type *MallocType = getMallocAllocatedType(CI);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001592 if (MallocType && TryToOptimizeStoreOfMallocToGlobal(GV, CI, MallocType,
Nick Lewyckyfad4d402012-02-05 19:56:38 +00001593 Ordering, GVI, TD))
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001594 return true;
Chris Lattner708148e2004-10-10 23:14:11 +00001595 }
Chris Lattner9b34a612004-10-09 21:48:45 +00001596 }
Chris Lattner30ba5692004-10-11 05:54:41 +00001597
Chris Lattner9b34a612004-10-09 21:48:45 +00001598 return false;
1599}
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001600
Chris Lattner58e44f42008-01-14 01:17:44 +00001601/// TryToShrinkGlobalToBoolean - At this point, we have learned that the only
1602/// two values ever stored into GV are its initializer and OtherVal. See if we
1603/// can shrink the global into a boolean and select between the two values
1604/// whenever it is used. This exposes the values to other scalar optimizations.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001605static bool TryToShrinkGlobalToBoolean(GlobalVariable *GV, Constant *OtherVal) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001606 Type *GVElType = GV->getType()->getElementType();
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001607
Chris Lattner58e44f42008-01-14 01:17:44 +00001608 // If GVElType is already i1, it is already shrunk. If the type of the GV is
Chris Lattner6f6923f2009-03-07 23:32:02 +00001609 // an FP value, pointer or vector, don't do this optimization because a select
1610 // between them is very expensive and unlikely to lead to later
1611 // simplification. In these cases, we typically end up with "cond ? v1 : v2"
1612 // where v1 and v2 both require constant pool loads, a big loss.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001613 if (GVElType == Type::getInt1Ty(GV->getContext()) ||
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001614 GVElType->isFloatingPointTy() ||
Duncan Sands1df98592010-02-16 11:11:14 +00001615 GVElType->isPointerTy() || GVElType->isVectorTy())
Chris Lattner58e44f42008-01-14 01:17:44 +00001616 return false;
Gabor Greifaaaaa022010-07-12 14:13:15 +00001617
Chris Lattner58e44f42008-01-14 01:17:44 +00001618 // Walk the use list of the global seeing if all the uses are load or store.
1619 // If there is anything else, bail out.
Gabor Greifaaaaa022010-07-12 14:13:15 +00001620 for (Value::use_iterator I = GV->use_begin(), E = GV->use_end(); I != E; ++I){
1621 User *U = *I;
1622 if (!isa<LoadInst>(U) && !isa<StoreInst>(U))
Chris Lattner58e44f42008-01-14 01:17:44 +00001623 return false;
Gabor Greifaaaaa022010-07-12 14:13:15 +00001624 }
1625
David Greene3215b0e2010-01-05 01:28:05 +00001626 DEBUG(dbgs() << " *** SHRINKING TO BOOL: " << *GV);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001627
Chris Lattner96a86b22004-12-12 05:53:50 +00001628 // Create the new global, initializing it to false.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001629 GlobalVariable *NewGV = new GlobalVariable(Type::getInt1Ty(GV->getContext()),
1630 false,
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001631 GlobalValue::InternalLinkage,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001632 ConstantInt::getFalse(GV->getContext()),
Nick Lewycky0e670df2009-05-03 03:49:08 +00001633 GV->getName()+".b",
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +00001634 GV->isThreadLocal());
Chris Lattner96a86b22004-12-12 05:53:50 +00001635 GV->getParent()->getGlobalList().insert(GV, NewGV);
1636
1637 Constant *InitVal = GV->getInitializer();
Chris Lattner7b550cc2009-11-06 04:27:31 +00001638 assert(InitVal->getType() != Type::getInt1Ty(GV->getContext()) &&
Owen Anderson1d0be152009-08-13 21:58:54 +00001639 "No reason to shrink to bool!");
Chris Lattner96a86b22004-12-12 05:53:50 +00001640
1641 // If initialized to zero and storing one into the global, we can use a cast
1642 // instead of a select to synthesize the desired value.
1643 bool IsOneZero = false;
1644 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal))
Reid Spencercae57542007-03-02 00:28:52 +00001645 IsOneZero = InitVal->isNullValue() && CI->isOne();
Chris Lattner96a86b22004-12-12 05:53:50 +00001646
1647 while (!GV->use_empty()) {
Devang Patel771281f2009-03-06 01:39:36 +00001648 Instruction *UI = cast<Instruction>(GV->use_back());
1649 if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
Chris Lattner96a86b22004-12-12 05:53:50 +00001650 // Change the store into a boolean store.
1651 bool StoringOther = SI->getOperand(0) == OtherVal;
1652 // Only do this if we weren't storing a loaded value.
Chris Lattner38c25562004-12-12 19:34:41 +00001653 Value *StoreVal;
Chris Lattner96a86b22004-12-12 05:53:50 +00001654 if (StoringOther || SI->getOperand(0) == InitVal)
Chris Lattner7b550cc2009-11-06 04:27:31 +00001655 StoreVal = ConstantInt::get(Type::getInt1Ty(GV->getContext()),
1656 StoringOther);
Chris Lattner38c25562004-12-12 19:34:41 +00001657 else {
1658 // Otherwise, we are storing a previously loaded copy. To do this,
1659 // change the copy from copying the original value to just copying the
1660 // bool.
1661 Instruction *StoredVal = cast<Instruction>(SI->getOperand(0));
1662
Gabor Greif9e4f2432010-06-24 14:42:01 +00001663 // If we've already replaced the input, StoredVal will be a cast or
Chris Lattner38c25562004-12-12 19:34:41 +00001664 // select instruction. If not, it will be a load of the original
1665 // global.
1666 if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
1667 assert(LI->getOperand(0) == GV && "Not a copy!");
1668 // Insert a new load, to preserve the saved value.
Nick Lewyckyfad4d402012-02-05 19:56:38 +00001669 StoreVal = new LoadInst(NewGV, LI->getName()+".b", false, 0,
1670 LI->getOrdering(), LI->getSynchScope(), LI);
Chris Lattner38c25562004-12-12 19:34:41 +00001671 } else {
1672 assert((isa<CastInst>(StoredVal) || isa<SelectInst>(StoredVal)) &&
1673 "This is not a form that we understand!");
1674 StoreVal = StoredVal->getOperand(0);
1675 assert(isa<LoadInst>(StoreVal) && "Not a load of NewGV!");
1676 }
1677 }
Nick Lewyckyfad4d402012-02-05 19:56:38 +00001678 new StoreInst(StoreVal, NewGV, false, 0,
1679 SI->getOrdering(), SI->getSynchScope(), SI);
Devang Patel771281f2009-03-06 01:39:36 +00001680 } else {
Chris Lattner96a86b22004-12-12 05:53:50 +00001681 // Change the load into a load of bool then a select.
Devang Patel771281f2009-03-06 01:39:36 +00001682 LoadInst *LI = cast<LoadInst>(UI);
Nick Lewyckyfad4d402012-02-05 19:56:38 +00001683 LoadInst *NLI = new LoadInst(NewGV, LI->getName()+".b", false, 0,
1684 LI->getOrdering(), LI->getSynchScope(), LI);
Chris Lattner96a86b22004-12-12 05:53:50 +00001685 Value *NSI;
1686 if (IsOneZero)
Chris Lattner046800a2007-02-11 01:08:35 +00001687 NSI = new ZExtInst(NLI, LI->getType(), "", LI);
Misha Brukmanfd939082005-04-21 23:48:37 +00001688 else
Gabor Greif051a9502008-04-06 20:25:17 +00001689 NSI = SelectInst::Create(NLI, OtherVal, InitVal, "", LI);
Chris Lattner046800a2007-02-11 01:08:35 +00001690 NSI->takeName(LI);
Chris Lattner96a86b22004-12-12 05:53:50 +00001691 LI->replaceAllUsesWith(NSI);
Devang Patel771281f2009-03-06 01:39:36 +00001692 }
1693 UI->eraseFromParent();
Chris Lattner96a86b22004-12-12 05:53:50 +00001694 }
1695
1696 GV->eraseFromParent();
Chris Lattner58e44f42008-01-14 01:17:44 +00001697 return true;
Chris Lattner96a86b22004-12-12 05:53:50 +00001698}
1699
1700
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001701/// ProcessInternalGlobal - Analyze the specified global variable and optimize
1702/// it if possible. If we make a change, return true.
Rafael Espindolac4440e32011-01-19 16:32:21 +00001703bool GlobalOpt::ProcessGlobal(GlobalVariable *GV,
1704 Module::global_iterator &GVI) {
1705 if (!GV->hasLocalLinkage())
1706 return false;
1707
1708 // Do more involved optimizations if the global is internal.
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001709 GV->removeDeadConstantUsers();
1710
1711 if (GV->use_empty()) {
David Greene3215b0e2010-01-05 01:28:05 +00001712 DEBUG(dbgs() << "GLOBAL DEAD: " << *GV);
Chris Lattner7a7ed022004-10-16 18:09:00 +00001713 GV->eraseFromParent();
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001714 ++NumDeleted;
1715 return true;
1716 }
1717
Rafael Espindolac4440e32011-01-19 16:32:21 +00001718 SmallPtrSet<const PHINode*, 16> PHIUsers;
1719 GlobalStatus GS;
1720
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001721 if (AnalyzeGlobal(GV, GS, PHIUsers))
1722 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001723
Rafael Espindolac4440e32011-01-19 16:32:21 +00001724 if (!GS.isCompared && !GV->hasUnnamedAddr()) {
1725 GV->setUnnamedAddr(true);
1726 NumUnnamed++;
1727 }
1728
1729 if (GV->isConstant() || !GV->hasInitializer())
1730 return false;
1731
1732 return ProcessInternalGlobal(GV, GVI, PHIUsers, GS);
1733}
1734
1735/// ProcessInternalGlobal - Analyze the specified global variable and optimize
1736/// it if possible. If we make a change, return true.
1737bool GlobalOpt::ProcessInternalGlobal(GlobalVariable *GV,
1738 Module::global_iterator &GVI,
1739 const SmallPtrSet<const PHINode*, 16> &PHIUsers,
1740 const GlobalStatus &GS) {
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001741 // If this is a first class global and has only one accessing function
1742 // and this function is main (which we know is not recursive we can make
1743 // this global a local variable) we replace the global with a local alloca
1744 // in this function.
1745 //
1746 // NOTE: It doesn't make sense to promote non single-value types since we
1747 // are just replacing static memory to stack memory.
1748 //
1749 // If the global is in different address space, don't bring it to stack.
1750 if (!GS.HasMultipleAccessingFunctions &&
1751 GS.AccessingFunction && !GS.HasNonInstructionUser &&
1752 GV->getType()->getElementType()->isSingleValueType() &&
1753 GS.AccessingFunction->getName() == "main" &&
1754 GS.AccessingFunction->hasExternalLinkage() &&
1755 GV->getType()->getAddressSpace() == 0) {
1756 DEBUG(dbgs() << "LOCALIZING GLOBAL: " << *GV);
Nick Lewyckybc384a12012-02-05 19:48:37 +00001757 Instruction &FirstI = const_cast<Instruction&>(*GS.AccessingFunction
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001758 ->getEntryBlock().begin());
Nick Lewyckybc384a12012-02-05 19:48:37 +00001759 Type *ElemTy = GV->getType()->getElementType();
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001760 // FIXME: Pass Global's alignment when globals have alignment
Nick Lewyckybc384a12012-02-05 19:48:37 +00001761 AllocaInst *Alloca = new AllocaInst(ElemTy, NULL, GV->getName(), &FirstI);
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001762 if (!isa<UndefValue>(GV->getInitializer()))
1763 new StoreInst(GV->getInitializer(), Alloca, &FirstI);
Misha Brukmanfd939082005-04-21 23:48:37 +00001764
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001765 GV->replaceAllUsesWith(Alloca);
1766 GV->eraseFromParent();
1767 ++NumLocalized;
1768 return true;
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001769 }
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001770
1771 // If the global is never loaded (but may be stored to), it is dead.
1772 // Delete it now.
1773 if (!GS.isLoaded) {
1774 DEBUG(dbgs() << "GLOBAL NEVER LOADED: " << *GV);
1775
1776 // Delete any stores we can find to the global. We may not be able to
1777 // make it completely dead though.
1778 bool Changed = CleanupConstantGlobalUsers(GV, GV->getInitializer());
1779
1780 // If the global is dead now, delete it.
1781 if (GV->use_empty()) {
1782 GV->eraseFromParent();
1783 ++NumDeleted;
1784 Changed = true;
1785 }
1786 return Changed;
1787
1788 } else if (GS.StoredType <= GlobalStatus::isInitializerStored) {
1789 DEBUG(dbgs() << "MARKING CONSTANT: " << *GV);
1790 GV->setConstant(true);
1791
1792 // Clean up any obviously simplifiable users now.
1793 CleanupConstantGlobalUsers(GV, GV->getInitializer());
1794
1795 // If the global is dead now, just nuke it.
1796 if (GV->use_empty()) {
1797 DEBUG(dbgs() << " *** Marking constant allowed us to simplify "
1798 << "all users and delete global!\n");
1799 GV->eraseFromParent();
1800 ++NumDeleted;
1801 }
1802
1803 ++NumMarked;
1804 return true;
1805 } else if (!GV->getInitializer()->getType()->isSingleValueType()) {
1806 if (TargetData *TD = getAnalysisIfAvailable<TargetData>())
1807 if (GlobalVariable *FirstNewGV = SRAGlobal(GV, *TD)) {
1808 GVI = FirstNewGV; // Don't skip the newly produced globals!
1809 return true;
1810 }
1811 } else if (GS.StoredType == GlobalStatus::isStoredOnce) {
1812 // If the initial value for the global was an undef value, and if only
1813 // one other value was stored into it, we can just change the
1814 // initializer to be the stored value, then delete all stores to the
1815 // global. This allows us to mark it constant.
1816 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
1817 if (isa<UndefValue>(GV->getInitializer())) {
1818 // Change the initial value here.
1819 GV->setInitializer(SOVConstant);
1820
1821 // Clean up any obviously simplifiable users now.
1822 CleanupConstantGlobalUsers(GV, GV->getInitializer());
1823
1824 if (GV->use_empty()) {
1825 DEBUG(dbgs() << " *** Substituting initializer allowed us to "
1826 << "simplify all users and delete global!\n");
1827 GV->eraseFromParent();
1828 ++NumDeleted;
1829 } else {
1830 GVI = GV;
1831 }
1832 ++NumSubstitute;
1833 return true;
1834 }
1835
1836 // Try to optimize globals based on the knowledge that only one value
1837 // (besides its initializer) is ever stored to the global.
Nick Lewyckyfad4d402012-02-05 19:56:38 +00001838 if (OptimizeOnceStoredGlobal(GV, GS.StoredOnceValue, GS.Ordering, GVI,
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001839 getAnalysisIfAvailable<TargetData>()))
1840 return true;
1841
1842 // Otherwise, if the global was not a boolean, we can shrink it to be a
1843 // boolean.
1844 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
1845 if (TryToShrinkGlobalToBoolean(GV, SOVConstant)) {
1846 ++NumShrunkToBool;
1847 return true;
1848 }
1849 }
1850
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001851 return false;
1852}
1853
Chris Lattnerfb217ad2005-05-08 22:18:06 +00001854/// ChangeCalleesToFastCall - Walk all of the direct calls of the specified
1855/// function, changing them to FastCC.
1856static void ChangeCalleesToFastCall(Function *F) {
1857 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
Duncan Sands548448a2008-02-18 17:32:13 +00001858 CallSite User(cast<Instruction>(*UI));
1859 User.setCallingConv(CallingConv::Fast);
Chris Lattnerfb217ad2005-05-08 22:18:06 +00001860 }
1861}
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001862
Devang Patel05988662008-09-25 21:00:45 +00001863static AttrListPtr StripNest(const AttrListPtr &Attrs) {
Chris Lattner58d74912008-03-12 17:45:29 +00001864 for (unsigned i = 0, e = Attrs.getNumSlots(); i != e; ++i) {
Devang Patel05988662008-09-25 21:00:45 +00001865 if ((Attrs.getSlot(i).Attrs & Attribute::Nest) == 0)
Duncan Sands548448a2008-02-18 17:32:13 +00001866 continue;
1867
Duncan Sands548448a2008-02-18 17:32:13 +00001868 // There can be only one.
Devang Patel05988662008-09-25 21:00:45 +00001869 return Attrs.removeAttr(Attrs.getSlot(i).Index, Attribute::Nest);
Duncan Sands3d5378f2008-02-16 20:56:04 +00001870 }
1871
1872 return Attrs;
1873}
1874
1875static void RemoveNestAttribute(Function *F) {
Devang Patel05988662008-09-25 21:00:45 +00001876 F->setAttributes(StripNest(F->getAttributes()));
Duncan Sands3d5378f2008-02-16 20:56:04 +00001877 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
Duncan Sands548448a2008-02-18 17:32:13 +00001878 CallSite User(cast<Instruction>(*UI));
Devang Patel05988662008-09-25 21:00:45 +00001879 User.setAttributes(StripNest(User.getAttributes()));
Duncan Sands3d5378f2008-02-16 20:56:04 +00001880 }
1881}
1882
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001883bool GlobalOpt::OptimizeFunctions(Module &M) {
1884 bool Changed = false;
1885 // Optimize functions.
1886 for (Module::iterator FI = M.begin(), E = M.end(); FI != E; ) {
1887 Function *F = FI++;
Duncan Sandsfc5940d2009-03-06 10:21:56 +00001888 // Functions without names cannot be referenced outside this module.
1889 if (!F->hasName() && !F->isDeclaration())
1890 F->setLinkage(GlobalValue::InternalLinkage);
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001891 F->removeDeadConstantUsers();
Eli Friedmanc6633052011-10-20 05:23:42 +00001892 if (F->isDefTriviallyDead()) {
Chris Lattnerec4c7b92009-11-01 19:03:42 +00001893 F->eraseFromParent();
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001894 Changed = true;
1895 ++NumFnDeleted;
Rafael Espindolabb46f522009-01-15 20:18:42 +00001896 } else if (F->hasLocalLinkage()) {
Duncan Sands3d5378f2008-02-16 20:56:04 +00001897 if (F->getCallingConv() == CallingConv::C && !F->isVarArg() &&
Jay Foad757068f2009-06-10 08:41:11 +00001898 !F->hasAddressTaken()) {
Duncan Sands3d5378f2008-02-16 20:56:04 +00001899 // If this function has C calling conventions, is not a varargs
1900 // function, and is only called directly, promote it to use the Fast
1901 // calling convention.
1902 F->setCallingConv(CallingConv::Fast);
1903 ChangeCalleesToFastCall(F);
1904 ++NumFastCallFns;
1905 Changed = true;
1906 }
1907
Devang Patel05988662008-09-25 21:00:45 +00001908 if (F->getAttributes().hasAttrSomewhere(Attribute::Nest) &&
Jay Foad757068f2009-06-10 08:41:11 +00001909 !F->hasAddressTaken()) {
Duncan Sands3d5378f2008-02-16 20:56:04 +00001910 // The function is not used by a trampoline intrinsic, so it is safe
1911 // to remove the 'nest' attribute.
1912 RemoveNestAttribute(F);
1913 ++NumNestRemoved;
1914 Changed = true;
1915 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001916 }
1917 }
1918 return Changed;
1919}
1920
1921bool GlobalOpt::OptimizeGlobalVars(Module &M) {
1922 bool Changed = false;
1923 for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
1924 GVI != E; ) {
1925 GlobalVariable *GV = GVI++;
Duncan Sandsfc5940d2009-03-06 10:21:56 +00001926 // Global variables without names cannot be referenced outside this module.
1927 if (!GV->hasName() && !GV->isDeclaration())
1928 GV->setLinkage(GlobalValue::InternalLinkage);
Dan Gohman01b97dd2009-11-23 16:22:21 +00001929 // Simplify the initializer.
1930 if (GV->hasInitializer())
1931 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GV->getInitializer())) {
Dan Gohmanf860db22010-04-02 03:04:37 +00001932 TargetData *TD = getAnalysisIfAvailable<TargetData>();
Chad Rosieraab8e282011-12-02 01:26:24 +00001933 TargetLibraryInfo *TLI = &getAnalysis<TargetLibraryInfo>();
1934 Constant *New = ConstantFoldConstantExpression(CE, TD, TLI);
Dan Gohman01b97dd2009-11-23 16:22:21 +00001935 if (New && New != CE)
1936 GV->setInitializer(New);
1937 }
Rafael Espindolac4440e32011-01-19 16:32:21 +00001938
1939 Changed |= ProcessGlobal(GV, GVI);
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001940 }
1941 return Changed;
1942}
1943
Nick Lewycky2c44a802011-04-08 07:30:21 +00001944/// FindGlobalCtors - Find the llvm.global_ctors list, verifying that all
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001945/// initializers have an init priority of 65535.
1946GlobalVariable *GlobalOpt::FindGlobalCtors(Module &M) {
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00001947 GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
1948 if (GV == 0) return 0;
1949
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00001950 // Verify that the initializer is simple enough for us to handle. We are
1951 // only allowed to optimize the initializer if it is unique.
1952 if (!GV->hasUniqueInitializer()) return 0;
Nick Lewycky5ea5c612011-04-11 22:11:20 +00001953
1954 if (isa<ConstantAggregateZero>(GV->getInitializer()))
1955 return GV;
1956 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
Eli Friedman18a2e502011-04-09 09:11:09 +00001957
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00001958 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i) {
Nick Lewycky5ea5c612011-04-11 22:11:20 +00001959 if (isa<ConstantAggregateZero>(*i))
1960 continue;
1961 ConstantStruct *CS = cast<ConstantStruct>(*i);
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00001962 if (isa<ConstantPointerNull>(CS->getOperand(1)))
1963 continue;
Chris Lattner7d8e58f2005-09-26 02:19:27 +00001964
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00001965 // Must have a function or null ptr.
1966 if (!isa<Function>(CS->getOperand(1)))
1967 return 0;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001968
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00001969 // Init priority must be standard.
Nick Lewycky2c44a802011-04-08 07:30:21 +00001970 ConstantInt *CI = cast<ConstantInt>(CS->getOperand(0));
1971 if (CI->getZExtValue() != 65535)
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00001972 return 0;
1973 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001974
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00001975 return GV;
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001976}
1977
Chris Lattnerdb973e62005-09-26 02:31:18 +00001978/// ParseGlobalCtors - Given a llvm.global_ctors list that we can understand,
1979/// return a list of the functions and null terminator as a vector.
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001980static std::vector<Function*> ParseGlobalCtors(GlobalVariable *GV) {
Nick Lewycky5ea5c612011-04-11 22:11:20 +00001981 if (GV->getInitializer()->isNullValue())
1982 return std::vector<Function*>();
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001983 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
1984 std::vector<Function*> Result;
1985 Result.reserve(CA->getNumOperands());
Gabor Greif5e463212008-05-29 01:59:18 +00001986 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i) {
1987 ConstantStruct *CS = cast<ConstantStruct>(*i);
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001988 Result.push_back(dyn_cast<Function>(CS->getOperand(1)));
1989 }
1990 return Result;
1991}
1992
Chris Lattnerdb973e62005-09-26 02:31:18 +00001993/// InstallGlobalCtors - Given a specified llvm.global_ctors list, install the
1994/// specified array, returning the new global to use.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001995static GlobalVariable *InstallGlobalCtors(GlobalVariable *GCL,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001996 const std::vector<Function*> &Ctors) {
Chris Lattnerdb973e62005-09-26 02:31:18 +00001997 // If we made a change, reassemble the initializer list.
Chris Lattnerb065b062011-06-20 04:01:31 +00001998 Constant *CSVals[2];
1999 CSVals[0] = ConstantInt::get(Type::getInt32Ty(GCL->getContext()), 65535);
2000 CSVals[1] = 0;
2001
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002002 StructType *StructTy =
Chris Lattnerb065b062011-06-20 04:01:31 +00002003 cast <StructType>(
2004 cast<ArrayType>(GCL->getType()->getElementType())->getElementType());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002005
Chris Lattnerdb973e62005-09-26 02:31:18 +00002006 // Create the new init list.
2007 std::vector<Constant*> CAList;
2008 for (unsigned i = 0, e = Ctors.size(); i != e; ++i) {
Chris Lattner79c11012005-09-26 04:44:35 +00002009 if (Ctors[i]) {
Chris Lattnerdb973e62005-09-26 02:31:18 +00002010 CSVals[1] = Ctors[i];
Chris Lattner79c11012005-09-26 04:44:35 +00002011 } else {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002012 Type *FTy = FunctionType::get(Type::getVoidTy(GCL->getContext()),
Chris Lattner7b550cc2009-11-06 04:27:31 +00002013 false);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002014 PointerType *PFTy = PointerType::getUnqual(FTy);
Owen Andersona7235ea2009-07-31 20:28:14 +00002015 CSVals[1] = Constant::getNullValue(PFTy);
Chris Lattner7b550cc2009-11-06 04:27:31 +00002016 CSVals[0] = ConstantInt::get(Type::getInt32Ty(GCL->getContext()),
Nick Lewycky5ea5c612011-04-11 22:11:20 +00002017 0x7fffffff);
Chris Lattnerdb973e62005-09-26 02:31:18 +00002018 }
Chris Lattnerb065b062011-06-20 04:01:31 +00002019 CAList.push_back(ConstantStruct::get(StructTy, CSVals));
Chris Lattnerdb973e62005-09-26 02:31:18 +00002020 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002021
Chris Lattnerdb973e62005-09-26 02:31:18 +00002022 // Create the array initializer.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002023 Constant *CA = ConstantArray::get(ArrayType::get(StructTy,
Nick Lewyckyc332fba2009-09-19 20:30:26 +00002024 CAList.size()), CAList);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002025
Chris Lattnerdb973e62005-09-26 02:31:18 +00002026 // If we didn't change the number of elements, don't create a new GV.
2027 if (CA->getType() == GCL->getInitializer()->getType()) {
2028 GCL->setInitializer(CA);
2029 return GCL;
2030 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002031
Chris Lattnerdb973e62005-09-26 02:31:18 +00002032 // Create the new global and insert it next to the existing list.
Chris Lattner7b550cc2009-11-06 04:27:31 +00002033 GlobalVariable *NGV = new GlobalVariable(CA->getType(), GCL->isConstant(),
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +00002034 GCL->getLinkage(), CA, "",
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +00002035 GCL->isThreadLocal());
Chris Lattnerdb973e62005-09-26 02:31:18 +00002036 GCL->getParent()->getGlobalList().insert(GCL, NGV);
Chris Lattner046800a2007-02-11 01:08:35 +00002037 NGV->takeName(GCL);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002038
Chris Lattnerdb973e62005-09-26 02:31:18 +00002039 // Nuke the old list, replacing any uses with the new one.
2040 if (!GCL->use_empty()) {
2041 Constant *V = NGV;
2042 if (V->getType() != GCL->getType())
Owen Andersonbaf3c402009-07-29 18:55:55 +00002043 V = ConstantExpr::getBitCast(V, GCL->getType());
Chris Lattnerdb973e62005-09-26 02:31:18 +00002044 GCL->replaceAllUsesWith(V);
2045 }
2046 GCL->eraseFromParent();
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002047
Chris Lattnerdb973e62005-09-26 02:31:18 +00002048 if (Ctors.size())
2049 return NGV;
2050 else
2051 return 0;
2052}
Chris Lattner79c11012005-09-26 04:44:35 +00002053
2054
Chris Lattner1945d582010-12-07 04:33:29 +00002055static Constant *getVal(DenseMap<Value*, Constant*> &ComputedValues, Value *V) {
Chris Lattner79c11012005-09-26 04:44:35 +00002056 if (Constant *CV = dyn_cast<Constant>(V)) return CV;
2057 Constant *R = ComputedValues[V];
2058 assert(R && "Reference to an uncomputed value!");
2059 return R;
2060}
2061
Chris Lattner1945d582010-12-07 04:33:29 +00002062static inline bool
2063isSimpleEnoughValueToCommit(Constant *C,
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002064 SmallPtrSet<Constant*, 8> &SimpleConstants,
2065 const TargetData *TD);
Chris Lattner1945d582010-12-07 04:33:29 +00002066
2067
2068/// isSimpleEnoughValueToCommit - Return true if the specified constant can be
2069/// handled by the code generator. We don't want to generate something like:
2070/// void *X = &X/42;
2071/// because the code generator doesn't have a relocation that can handle that.
2072///
2073/// This function should be called if C was not found (but just got inserted)
2074/// in SimpleConstants to avoid having to rescan the same constants all the
2075/// time.
2076static bool isSimpleEnoughValueToCommitHelper(Constant *C,
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002077 SmallPtrSet<Constant*, 8> &SimpleConstants,
2078 const TargetData *TD) {
Chris Lattner1945d582010-12-07 04:33:29 +00002079 // Simple integer, undef, constant aggregate zero, global addresses, etc are
2080 // all supported.
2081 if (C->getNumOperands() == 0 || isa<BlockAddress>(C) ||
2082 isa<GlobalValue>(C))
2083 return true;
2084
2085 // Aggregate values are safe if all their elements are.
2086 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C) ||
2087 isa<ConstantVector>(C)) {
2088 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i) {
2089 Constant *Op = cast<Constant>(C->getOperand(i));
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002090 if (!isSimpleEnoughValueToCommit(Op, SimpleConstants, TD))
Chris Lattner1945d582010-12-07 04:33:29 +00002091 return false;
2092 }
2093 return true;
2094 }
2095
2096 // We don't know exactly what relocations are allowed in constant expressions,
2097 // so we allow &global+constantoffset, which is safe and uniformly supported
2098 // across targets.
2099 ConstantExpr *CE = cast<ConstantExpr>(C);
2100 switch (CE->getOpcode()) {
2101 case Instruction::BitCast:
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002102 // Bitcast is fine if the casted value is fine.
2103 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, TD);
2104
Chris Lattner1945d582010-12-07 04:33:29 +00002105 case Instruction::IntToPtr:
2106 case Instruction::PtrToInt:
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002107 // int <=> ptr is fine if the int type is the same size as the
2108 // pointer type.
2109 if (!TD || TD->getTypeSizeInBits(CE->getType()) !=
2110 TD->getTypeSizeInBits(CE->getOperand(0)->getType()))
2111 return false;
2112 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, TD);
Chris Lattner1945d582010-12-07 04:33:29 +00002113
2114 // GEP is fine if it is simple + constant offset.
2115 case Instruction::GetElementPtr:
2116 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
2117 if (!isa<ConstantInt>(CE->getOperand(i)))
2118 return false;
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002119 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, TD);
Chris Lattner1945d582010-12-07 04:33:29 +00002120
2121 case Instruction::Add:
2122 // We allow simple+cst.
2123 if (!isa<ConstantInt>(CE->getOperand(1)))
2124 return false;
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002125 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, TD);
Chris Lattner1945d582010-12-07 04:33:29 +00002126 }
2127 return false;
2128}
2129
2130static inline bool
2131isSimpleEnoughValueToCommit(Constant *C,
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002132 SmallPtrSet<Constant*, 8> &SimpleConstants,
2133 const TargetData *TD) {
Chris Lattner1945d582010-12-07 04:33:29 +00002134 // If we already checked this constant, we win.
2135 if (!SimpleConstants.insert(C)) return true;
2136 // Check the constant.
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002137 return isSimpleEnoughValueToCommitHelper(C, SimpleConstants, TD);
Chris Lattner1945d582010-12-07 04:33:29 +00002138}
2139
2140
Chris Lattner79c11012005-09-26 04:44:35 +00002141/// isSimpleEnoughPointerToCommit - Return true if this constant is simple
Owen Andersoncff6b372011-01-14 22:19:20 +00002142/// enough for us to understand. In particular, if it is a cast to anything
2143/// other than from one pointer type to another pointer type, we punt.
2144/// We basically just support direct accesses to globals and GEP's of
Chris Lattner79c11012005-09-26 04:44:35 +00002145/// globals. This should be kept up to date with CommitValueTo.
Chris Lattner7b550cc2009-11-06 04:27:31 +00002146static bool isSimpleEnoughPointerToCommit(Constant *C) {
Dan Gohmance5de5b2009-09-07 22:42:05 +00002147 // Conservatively, avoid aggregate types. This is because we don't
2148 // want to worry about them partially overlapping other stores.
2149 if (!cast<PointerType>(C->getType())->getElementType()->isSingleValueType())
2150 return false;
2151
Dan Gohmanfd54a892009-09-07 22:31:26 +00002152 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
Mikhail Glushenkov99fca5d2010-10-19 16:47:23 +00002153 // Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or
Dan Gohmanfd54a892009-09-07 22:31:26 +00002154 // external globals.
Mikhail Glushenkov99fca5d2010-10-19 16:47:23 +00002155 return GV->hasUniqueInitializer();
Dan Gohmanfd54a892009-09-07 22:31:26 +00002156
Owen Andersone95a32c2011-01-14 22:31:13 +00002157 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002158 // Handle a constantexpr gep.
2159 if (CE->getOpcode() == Instruction::GetElementPtr &&
Dan Gohmanc62482d2009-09-07 22:40:13 +00002160 isa<GlobalVariable>(CE->getOperand(0)) &&
2161 cast<GEPOperator>(CE)->isInBounds()) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002162 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
Mikhail Glushenkov99fca5d2010-10-19 16:47:23 +00002163 // Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or
Dan Gohmanfd54a892009-09-07 22:31:26 +00002164 // external globals.
Mikhail Glushenkov99fca5d2010-10-19 16:47:23 +00002165 if (!GV->hasUniqueInitializer())
Dan Gohmanfd54a892009-09-07 22:31:26 +00002166 return false;
Dan Gohman80bdc962009-09-07 22:44:55 +00002167
Dan Gohman80bdc962009-09-07 22:44:55 +00002168 // The first index must be zero.
Oscar Fuentesee56c422010-08-02 06:00:15 +00002169 ConstantInt *CI = dyn_cast<ConstantInt>(*llvm::next(CE->op_begin()));
Dan Gohman80bdc962009-09-07 22:44:55 +00002170 if (!CI || !CI->isZero()) return false;
Dan Gohman80bdc962009-09-07 22:44:55 +00002171
2172 // The remaining indices must be compile-time known integers within the
Dan Gohmane6992f72009-09-10 23:37:55 +00002173 // notional bounds of the corresponding static array types.
2174 if (!CE->isGEPWithNoNotionalOverIndexing())
2175 return false;
Dan Gohman80bdc962009-09-07 22:44:55 +00002176
Dan Gohmanc6f69e92009-10-05 16:36:26 +00002177 return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
Owen Andersoncff6b372011-01-14 22:19:20 +00002178
2179 // A constantexpr bitcast from a pointer to another pointer is a no-op,
2180 // and we know how to evaluate it by moving the bitcast from the pointer
2181 // operand to the value operand.
2182 } else if (CE->getOpcode() == Instruction::BitCast &&
Chris Lattnerd5f656f2011-01-16 02:05:10 +00002183 isa<GlobalVariable>(CE->getOperand(0))) {
Owen Andersoncff6b372011-01-14 22:19:20 +00002184 // Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or
2185 // external globals.
Chris Lattnerd5f656f2011-01-16 02:05:10 +00002186 return cast<GlobalVariable>(CE->getOperand(0))->hasUniqueInitializer();
Chris Lattner798b4d52005-09-26 06:52:44 +00002187 }
Owen Andersone95a32c2011-01-14 22:31:13 +00002188 }
2189
Chris Lattner79c11012005-09-26 04:44:35 +00002190 return false;
2191}
2192
Chris Lattner798b4d52005-09-26 06:52:44 +00002193/// EvaluateStoreInto - Evaluate a piece of a constantexpr store into a global
2194/// initializer. This returns 'Init' modified to reflect 'Val' stored into it.
2195/// At this point, the GEP operands of Addr [0, OpNo) have been stepped into.
2196static Constant *EvaluateStoreInto(Constant *Init, Constant *Val,
Chris Lattner7b550cc2009-11-06 04:27:31 +00002197 ConstantExpr *Addr, unsigned OpNo) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002198 // Base case of the recursion.
2199 if (OpNo == Addr->getNumOperands()) {
2200 assert(Val->getType() == Init->getType() && "Type mismatch!");
2201 return Val;
2202 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002203
Chris Lattnera78fa8c2012-01-27 03:08:05 +00002204 SmallVector<Constant*, 32> Elts;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002205 if (StructType *STy = dyn_cast<StructType>(Init->getType())) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002206 // Break up the constant into its elements.
Chris Lattnerd59ae902012-01-26 02:32:04 +00002207 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
2208 Elts.push_back(Init->getAggregateElement(i));
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002209
Chris Lattner798b4d52005-09-26 06:52:44 +00002210 // Replace the element that we are supposed to.
Reid Spencerb83eb642006-10-20 07:07:24 +00002211 ConstantInt *CU = cast<ConstantInt>(Addr->getOperand(OpNo));
2212 unsigned Idx = CU->getZExtValue();
2213 assert(Idx < STy->getNumElements() && "Struct index out of range!");
Chris Lattner7b550cc2009-11-06 04:27:31 +00002214 Elts[Idx] = EvaluateStoreInto(Elts[Idx], Val, Addr, OpNo+1);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002215
Chris Lattner798b4d52005-09-26 06:52:44 +00002216 // Return the modified struct.
Chris Lattnerb065b062011-06-20 04:01:31 +00002217 return ConstantStruct::get(STy, Elts);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002218 }
Chris Lattnerb065b062011-06-20 04:01:31 +00002219
2220 ConstantInt *CI = cast<ConstantInt>(Addr->getOperand(OpNo));
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002221 SequentialType *InitTy = cast<SequentialType>(Init->getType());
Chris Lattnerb065b062011-06-20 04:01:31 +00002222
2223 uint64_t NumElts;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002224 if (ArrayType *ATy = dyn_cast<ArrayType>(InitTy))
Chris Lattnerb065b062011-06-20 04:01:31 +00002225 NumElts = ATy->getNumElements();
2226 else
Chris Lattnerd59ae902012-01-26 02:32:04 +00002227 NumElts = InitTy->getVectorNumElements();
Chris Lattnerb065b062011-06-20 04:01:31 +00002228
2229 // Break up the array into elements.
Chris Lattnerd59ae902012-01-26 02:32:04 +00002230 for (uint64_t i = 0, e = NumElts; i != e; ++i)
2231 Elts.push_back(Init->getAggregateElement(i));
Chris Lattnerb065b062011-06-20 04:01:31 +00002232
2233 assert(CI->getZExtValue() < NumElts);
2234 Elts[CI->getZExtValue()] =
2235 EvaluateStoreInto(Elts[CI->getZExtValue()], Val, Addr, OpNo+1);
2236
2237 if (Init->getType()->isArrayTy())
2238 return ConstantArray::get(cast<ArrayType>(InitTy), Elts);
2239 return ConstantVector::get(Elts);
Chris Lattner798b4d52005-09-26 06:52:44 +00002240}
2241
Chris Lattner79c11012005-09-26 04:44:35 +00002242/// CommitValueTo - We have decided that Addr (which satisfies the predicate
2243/// isSimpleEnoughPointerToCommit) should get Val as its value. Make it happen.
Chris Lattner7b550cc2009-11-06 04:27:31 +00002244static void CommitValueTo(Constant *Val, Constant *Addr) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002245 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Addr)) {
2246 assert(GV->hasInitializer());
2247 GV->setInitializer(Val);
2248 return;
2249 }
Chris Lattnera0e9a242010-01-07 01:16:21 +00002250
Chris Lattner798b4d52005-09-26 06:52:44 +00002251 ConstantExpr *CE = cast<ConstantExpr>(Addr);
2252 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
Chris Lattnera0e9a242010-01-07 01:16:21 +00002253 GV->setInitializer(EvaluateStoreInto(GV->getInitializer(), Val, CE, 2));
Chris Lattner79c11012005-09-26 04:44:35 +00002254}
2255
Chris Lattner562a0552005-09-26 05:16:34 +00002256/// ComputeLoadResult - Return the value that would be computed by a load from
2257/// P after the stores reflected by 'memory' have been performed. If we can't
2258/// decide, return null.
Chris Lattner04de1cf2005-09-26 05:15:37 +00002259static Constant *ComputeLoadResult(Constant *P,
Chris Lattner7b550cc2009-11-06 04:27:31 +00002260 const DenseMap<Constant*, Constant*> &Memory) {
Chris Lattner04de1cf2005-09-26 05:15:37 +00002261 // If this memory location has been recently stored, use the stored value: it
2262 // is the most up-to-date.
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002263 DenseMap<Constant*, Constant*>::const_iterator I = Memory.find(P);
Chris Lattner04de1cf2005-09-26 05:15:37 +00002264 if (I != Memory.end()) return I->second;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002265
Chris Lattner04de1cf2005-09-26 05:15:37 +00002266 // Access it.
2267 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(P)) {
Dan Gohman82555732009-08-19 18:20:44 +00002268 if (GV->hasDefinitiveInitializer())
Chris Lattner04de1cf2005-09-26 05:15:37 +00002269 return GV->getInitializer();
2270 return 0;
Chris Lattner04de1cf2005-09-26 05:15:37 +00002271 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002272
Chris Lattner798b4d52005-09-26 06:52:44 +00002273 // Handle a constantexpr getelementptr.
2274 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(P))
2275 if (CE->getOpcode() == Instruction::GetElementPtr &&
2276 isa<GlobalVariable>(CE->getOperand(0))) {
2277 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
Dan Gohman82555732009-08-19 18:20:44 +00002278 if (GV->hasDefinitiveInitializer())
Dan Gohmanc6f69e92009-10-05 16:36:26 +00002279 return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
Chris Lattner798b4d52005-09-26 06:52:44 +00002280 }
2281
2282 return 0; // don't know how to evaluate.
Chris Lattner04de1cf2005-09-26 05:15:37 +00002283}
2284
Chris Lattnercd271422005-09-27 04:45:34 +00002285static bool EvaluateFunction(Function *F, Constant *&RetVal,
Duncan Sandsfa6a1cf2009-08-17 14:33:27 +00002286 const SmallVectorImpl<Constant*> &ActualArgs,
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002287 std::vector<Function*> &CallStack,
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002288 DenseMap<Constant*, Constant*> &MutatedMemory,
Chris Lattner1945d582010-12-07 04:33:29 +00002289 std::vector<GlobalVariable*> &AllocaTmps,
2290 SmallPtrSet<Constant*, 8> &SimpleConstants,
Chad Rosier00737bd2011-12-01 21:29:16 +00002291 const TargetData *TD,
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002292 const TargetLibraryInfo *TLI);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002293
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002294/// EvaluateBlock - Evaluate all instructions in block BB, returning true if
2295/// successful, false if we can't evaluate it. NewBB returns the next BB that
2296/// control flows into, or null upon return.
2297static bool EvaluateBlock(BasicBlock *BB, BasicBlock *&NextBB,
2298 std::vector<Function*> &CallStack,
2299 DenseMap<Value*, Constant*> &Values,
2300 DenseMap<Constant*, Constant*> &MutatedMemory,
2301 std::vector<GlobalVariable*> &AllocaTmps,
2302 SmallPtrSet<Constant*, 8> &SimpleConstants,
2303 const TargetData *TD,
2304 const TargetLibraryInfo *TLI) {
Chris Lattner79c11012005-09-26 04:44:35 +00002305 // CurInst - The current instruction we're evaluating.
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002306 BasicBlock::iterator CurInst = BB->getFirstNonPHI();
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002307
Chris Lattner79c11012005-09-26 04:44:35 +00002308 // This is the main evaluation loop.
2309 while (1) {
2310 Constant *InstResult = 0;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002311
Chris Lattner79c11012005-09-26 04:44:35 +00002312 if (StoreInst *SI = dyn_cast<StoreInst>(CurInst)) {
Eli Friedman33cb4452011-08-16 00:20:11 +00002313 if (!SI->isSimple()) return false; // no volatile/atomic accesses.
Chris Lattner79c11012005-09-26 04:44:35 +00002314 Constant *Ptr = getVal(Values, SI->getOperand(1));
Chris Lattner7b550cc2009-11-06 04:27:31 +00002315 if (!isSimpleEnoughPointerToCommit(Ptr))
Chris Lattner79c11012005-09-26 04:44:35 +00002316 // If this is too complex for us to commit, reject it.
Chris Lattnercd271422005-09-27 04:45:34 +00002317 return false;
Chris Lattner1945d582010-12-07 04:33:29 +00002318
Chris Lattner79c11012005-09-26 04:44:35 +00002319 Constant *Val = getVal(Values, SI->getOperand(0));
Chris Lattner1945d582010-12-07 04:33:29 +00002320
2321 // If this might be too difficult for the backend to handle (e.g. the addr
2322 // of one global variable divided by another) then we can't commit it.
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002323 if (!isSimpleEnoughValueToCommit(Val, SimpleConstants, TD))
Chris Lattner1945d582010-12-07 04:33:29 +00002324 return false;
Owen Andersoncff6b372011-01-14 22:19:20 +00002325
2326 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
2327 if (CE->getOpcode() == Instruction::BitCast) {
2328 // If we're evaluating a store through a bitcast, then we need
2329 // to pull the bitcast off the pointer type and push it onto the
2330 // stored value.
Chris Lattnerd5f656f2011-01-16 02:05:10 +00002331 Ptr = CE->getOperand(0);
Owen Andersoncff6b372011-01-14 22:19:20 +00002332
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002333 Type *NewTy = cast<PointerType>(Ptr->getType())->getElementType();
Owen Andersoncff6b372011-01-14 22:19:20 +00002334
Owen Anderson66f708f2011-01-16 04:33:33 +00002335 // In order to push the bitcast onto the stored value, a bitcast
2336 // from NewTy to Val's type must be legal. If it's not, we can try
2337 // introspecting NewTy to find a legal conversion.
2338 while (!Val->getType()->canLosslesslyBitCastTo(NewTy)) {
2339 // If NewTy is a struct, we can convert the pointer to the struct
2340 // into a pointer to its first member.
2341 // FIXME: This could be extended to support arrays as well.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002342 if (StructType *STy = dyn_cast<StructType>(NewTy)) {
Owen Anderson66f708f2011-01-16 04:33:33 +00002343 NewTy = STy->getTypeAtIndex(0U);
2344
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002345 IntegerType *IdxTy = IntegerType::get(NewTy->getContext(), 32);
Owen Anderson66f708f2011-01-16 04:33:33 +00002346 Constant *IdxZero = ConstantInt::get(IdxTy, 0, false);
2347 Constant * const IdxList[] = {IdxZero, IdxZero};
2348
Jay Foadb4263a62011-07-22 08:52:50 +00002349 Ptr = ConstantExpr::getGetElementPtr(Ptr, IdxList);
Owen Andersoncff6b372011-01-14 22:19:20 +00002350
Owen Anderson66f708f2011-01-16 04:33:33 +00002351 // If we can't improve the situation by introspecting NewTy,
2352 // we have to give up.
2353 } else {
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002354 return false;
Owen Anderson66f708f2011-01-16 04:33:33 +00002355 }
Owen Andersoncff6b372011-01-14 22:19:20 +00002356 }
2357
Owen Anderson66f708f2011-01-16 04:33:33 +00002358 // If we found compatible types, go ahead and push the bitcast
2359 // onto the stored value.
Owen Andersoncff6b372011-01-14 22:19:20 +00002360 Val = ConstantExpr::getBitCast(Val, NewTy);
2361 }
2362
Chris Lattner79c11012005-09-26 04:44:35 +00002363 MutatedMemory[Ptr] = Val;
2364 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CurInst)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002365 InstResult = ConstantExpr::get(BO->getOpcode(),
Chris Lattner79c11012005-09-26 04:44:35 +00002366 getVal(Values, BO->getOperand(0)),
2367 getVal(Values, BO->getOperand(1)));
Reid Spencere4d87aa2006-12-23 06:05:41 +00002368 } else if (CmpInst *CI = dyn_cast<CmpInst>(CurInst)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002369 InstResult = ConstantExpr::getCompare(CI->getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00002370 getVal(Values, CI->getOperand(0)),
2371 getVal(Values, CI->getOperand(1)));
Chris Lattner79c11012005-09-26 04:44:35 +00002372 } else if (CastInst *CI = dyn_cast<CastInst>(CurInst)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002373 InstResult = ConstantExpr::getCast(CI->getOpcode(),
Chris Lattner9a989f02006-11-30 17:26:08 +00002374 getVal(Values, CI->getOperand(0)),
Chris Lattner79c11012005-09-26 04:44:35 +00002375 CI->getType());
2376 } else if (SelectInst *SI = dyn_cast<SelectInst>(CurInst)) {
Gabor Greif9e4f2432010-06-24 14:42:01 +00002377 InstResult = ConstantExpr::getSelect(getVal(Values, SI->getOperand(0)),
Eric Christopher551754c2010-04-16 23:37:20 +00002378 getVal(Values, SI->getOperand(1)),
2379 getVal(Values, SI->getOperand(2)));
Chris Lattner04de1cf2005-09-26 05:15:37 +00002380 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurInst)) {
2381 Constant *P = getVal(Values, GEP->getOperand(0));
Chris Lattner55eb1c42007-01-31 04:40:53 +00002382 SmallVector<Constant*, 8> GEPOps;
Gabor Greif5e463212008-05-29 01:59:18 +00002383 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end();
2384 i != e; ++i)
2385 GEPOps.push_back(getVal(Values, *i));
Jay Foad4b5e2072011-07-21 15:15:37 +00002386 InstResult =
2387 ConstantExpr::getGetElementPtr(P, GEPOps,
2388 cast<GEPOperator>(GEP)->isInBounds());
Chris Lattner04de1cf2005-09-26 05:15:37 +00002389 } else if (LoadInst *LI = dyn_cast<LoadInst>(CurInst)) {
Eli Friedman33cb4452011-08-16 00:20:11 +00002390 if (!LI->isSimple()) return false; // no volatile/atomic accesses.
Chris Lattner04de1cf2005-09-26 05:15:37 +00002391 InstResult = ComputeLoadResult(getVal(Values, LI->getOperand(0)),
Chris Lattner7b550cc2009-11-06 04:27:31 +00002392 MutatedMemory);
Chris Lattnercd271422005-09-27 04:45:34 +00002393 if (InstResult == 0) return false; // Could not evaluate load.
Chris Lattnera22fdb02005-09-26 17:07:09 +00002394 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(CurInst)) {
Chris Lattnercd271422005-09-27 04:45:34 +00002395 if (AI->isArrayAllocation()) return false; // Cannot handle array allocs.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002396 Type *Ty = AI->getType()->getElementType();
Chris Lattner7b550cc2009-11-06 04:27:31 +00002397 AllocaTmps.push_back(new GlobalVariable(Ty, false,
Chris Lattnera22fdb02005-09-26 17:07:09 +00002398 GlobalValue::InternalLinkage,
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002399 UndefValue::get(Ty),
Chris Lattnera22fdb02005-09-26 17:07:09 +00002400 AI->getName()));
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002401 InstResult = AllocaTmps.back();
Chris Lattnercd271422005-09-27 04:45:34 +00002402 } else if (CallInst *CI = dyn_cast<CallInst>(CurInst)) {
Devang Patel412a4462009-03-09 23:04:12 +00002403
2404 // Debug info can safely be ignored here.
2405 if (isa<DbgInfoIntrinsic>(CI)) {
2406 ++CurInst;
2407 continue;
2408 }
2409
Chris Lattner7cd580f2006-07-07 21:37:01 +00002410 // Cannot handle inline asm.
Gabor Greifa9b23132010-04-20 13:13:04 +00002411 if (isa<InlineAsm>(CI->getCalledValue())) return false;
Chris Lattner7cd580f2006-07-07 21:37:01 +00002412
Nick Lewycky1f237b02011-05-29 18:41:56 +00002413 if (MemSetInst *MSI = dyn_cast<MemSetInst>(CI)) {
2414 if (MSI->isVolatile()) return false;
2415 Constant *Ptr = getVal(Values, MSI->getDest());
2416 Constant *Val = getVal(Values, MSI->getValue());
2417 Constant *DestVal = ComputeLoadResult(getVal(Values, Ptr),
2418 MutatedMemory);
Nick Lewyckybcb85082011-05-29 19:33:36 +00002419 if (Val->isNullValue() && DestVal && DestVal->isNullValue()) {
Nick Lewycky1f237b02011-05-29 18:41:56 +00002420 // This memset is a no-op.
2421 ++CurInst;
2422 continue;
2423 }
2424 return false;
2425 }
2426
Chris Lattnercd271422005-09-27 04:45:34 +00002427 // Resolve function pointers.
Gabor Greifa3997812010-07-22 10:37:47 +00002428 Function *Callee = dyn_cast<Function>(getVal(Values,
2429 CI->getCalledValue()));
Chris Lattnercd271422005-09-27 04:45:34 +00002430 if (!Callee) return false; // Cannot resolve.
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002431
Duncan Sandsfa6a1cf2009-08-17 14:33:27 +00002432 SmallVector<Constant*, 8> Formals;
Gabor Greif9e4f2432010-06-24 14:42:01 +00002433 CallSite CS(CI);
2434 for (User::op_iterator i = CS.arg_begin(), e = CS.arg_end();
Gabor Greif5e463212008-05-29 01:59:18 +00002435 i != e; ++i)
2436 Formals.push_back(getVal(Values, *i));
Duncan Sandsfa6a1cf2009-08-17 14:33:27 +00002437
Reid Spencer5cbf9852007-01-30 20:08:39 +00002438 if (Callee->isDeclaration()) {
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002439 // If this is a function we can constant fold, do it.
Chad Rosier00737bd2011-12-01 21:29:16 +00002440 if (Constant *C = ConstantFoldCall(Callee, Formals, TLI)) {
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002441 InstResult = C;
2442 } else {
2443 return false;
2444 }
2445 } else {
2446 if (Callee->getFunctionType()->isVarArg())
2447 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002448
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002449 Constant *RetVal;
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002450 // Execute the call, if successful, use the return value.
2451 if (!EvaluateFunction(Callee, RetVal, Formals, CallStack,
Chad Rosier00737bd2011-12-01 21:29:16 +00002452 MutatedMemory, AllocaTmps, SimpleConstants, TD,
2453 TLI))
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002454 return false;
2455 InstResult = RetVal;
2456 }
Reid Spencer3ed469c2006-11-02 20:25:50 +00002457 } else if (isa<TerminatorInst>(CurInst)) {
Chris Lattnercdf98be2005-09-26 04:57:38 +00002458 if (BranchInst *BI = dyn_cast<BranchInst>(CurInst)) {
2459 if (BI->isUnconditional()) {
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002460 NextBB = BI->getSuccessor(0);
Chris Lattnercdf98be2005-09-26 04:57:38 +00002461 } else {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002462 ConstantInt *Cond =
2463 dyn_cast<ConstantInt>(getVal(Values, BI->getCondition()));
Chris Lattner97d1fad2007-01-12 18:30:11 +00002464 if (!Cond) return false; // Cannot determine.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002465
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002466 NextBB = BI->getSuccessor(!Cond->getZExtValue());
Chris Lattnercdf98be2005-09-26 04:57:38 +00002467 }
2468 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(CurInst)) {
2469 ConstantInt *Val =
2470 dyn_cast<ConstantInt>(getVal(Values, SI->getCondition()));
Chris Lattnercd271422005-09-27 04:45:34 +00002471 if (!Val) return false; // Cannot determine.
Stepan Dyatkovskiy24473122012-02-01 07:49:51 +00002472 unsigned ValTISucc = SI->resolveSuccessorIndex(SI->findCaseValue(Val));
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002473 NextBB = SI->getSuccessor(ValTISucc);
Chris Lattnerb3d5a652009-10-29 05:51:50 +00002474 } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(CurInst)) {
2475 Value *Val = getVal(Values, IBI->getAddress())->stripPointerCasts();
2476 if (BlockAddress *BA = dyn_cast<BlockAddress>(Val))
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002477 NextBB = BA->getBasicBlock();
Chris Lattnercdfc9402009-11-01 01:27:45 +00002478 else
2479 return false; // Cannot determine.
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002480 } else if (isa<ReturnInst>(CurInst)) {
2481 NextBB = 0;
Chris Lattnercdf98be2005-09-26 04:57:38 +00002482 } else {
Bill Wendlingdccc03b2011-07-31 06:30:59 +00002483 // invoke, unwind, resume, unreachable.
Chris Lattnercd271422005-09-27 04:45:34 +00002484 return false; // Cannot handle this terminator.
Chris Lattnercdf98be2005-09-26 04:57:38 +00002485 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002486
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002487 // We succeeded at evaluating this block!
2488 return true;
Chris Lattner79c11012005-09-26 04:44:35 +00002489 } else {
Chris Lattner79c11012005-09-26 04:44:35 +00002490 // Did not know how to evaluate this!
Chris Lattnercd271422005-09-27 04:45:34 +00002491 return false;
Chris Lattner79c11012005-09-26 04:44:35 +00002492 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002493
Chris Lattner1945d582010-12-07 04:33:29 +00002494 if (!CurInst->use_empty()) {
2495 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(InstResult))
Chad Rosieraab8e282011-12-02 01:26:24 +00002496 InstResult = ConstantFoldConstantExpression(CE, TD, TLI);
Chris Lattner1945d582010-12-07 04:33:29 +00002497
Chris Lattner79c11012005-09-26 04:44:35 +00002498 Values[CurInst] = InstResult;
Chris Lattner1945d582010-12-07 04:33:29 +00002499 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002500
Chris Lattner79c11012005-09-26 04:44:35 +00002501 // Advance program counter.
2502 ++CurInst;
2503 }
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002504}
2505
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002506/// EvaluateFunction - Evaluate a call to function F, returning true if
2507/// successful, false if we can't evaluate it. ActualArgs contains the formal
2508/// arguments for the function.
2509static bool EvaluateFunction(Function *F, Constant *&RetVal,
2510 const SmallVectorImpl<Constant*> &ActualArgs,
2511 std::vector<Function*> &CallStack,
2512 DenseMap<Constant*, Constant*> &MutatedMemory,
2513 std::vector<GlobalVariable*> &AllocaTmps,
2514 SmallPtrSet<Constant*, 8> &SimpleConstants,
2515 const TargetData *TD,
2516 const TargetLibraryInfo *TLI) {
2517 // Check to see if this function is already executing (recursion). If so,
2518 // bail out. TODO: we might want to accept limited recursion.
2519 if (std::find(CallStack.begin(), CallStack.end(), F) != CallStack.end())
2520 return false;
2521
2522 CallStack.push_back(F);
2523
2524 /// Values - As we compute SSA register values, we store their contents here.
2525 DenseMap<Value*, Constant*> Values;
2526
2527 // Initialize arguments to the incoming values specified.
2528 unsigned ArgNo = 0;
2529 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); AI != E;
2530 ++AI, ++ArgNo)
2531 Values[AI] = ActualArgs[ArgNo];
2532
2533 // ExecutedBlocks - We only handle non-looping, non-recursive code. As such,
2534 // we can only evaluate any one basic block at most once. This set keeps
2535 // track of what we have executed so we can detect recursive cases etc.
2536 SmallPtrSet<BasicBlock*, 32> ExecutedBlocks;
2537
2538 // CurBB - The current basic block we're evaluating.
2539 BasicBlock *CurBB = F->begin();
2540
2541 while (1) {
2542 BasicBlock *NextBB;
2543 if (!EvaluateBlock(CurBB, NextBB, CallStack, Values, MutatedMemory,
2544 AllocaTmps, SimpleConstants, TD, TLI))
2545 return false;
2546
2547 if (NextBB == 0) {
2548 // Successfully running until there's no next block means that we found
2549 // the return. Fill it the return value and pop the call stack.
2550 ReturnInst *RI = cast<ReturnInst>(CurBB->getTerminator());
2551 if (RI->getNumOperands())
2552 RetVal = getVal(Values, RI->getOperand(0));
2553 CallStack.pop_back();
2554 return true;
2555 }
2556
2557 // Okay, we succeeded in evaluating this control flow. See if we have
2558 // executed the new block before. If so, we have a looping function,
2559 // which we cannot evaluate in reasonable time.
2560 if (!ExecutedBlocks.insert(NextBB))
2561 return false; // looped!
2562
2563 // Okay, we have never been in this block before. Check to see if there
2564 // are any PHI nodes. If so, evaluate them with information about where
2565 // we came from.
2566 PHINode *PN = 0;
2567 for (BasicBlock::iterator Inst = NextBB->begin();
2568 (PN = dyn_cast<PHINode>(Inst)); ++Inst)
2569 Values[PN] = getVal(Values, PN->getIncomingValueForBlock(CurBB));
2570
2571 // Advance to the next block.
2572 CurBB = NextBB;
2573 }
2574}
2575
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002576/// EvaluateStaticConstructor - Evaluate static constructors in the function, if
2577/// we can. Return true if we can, false otherwise.
Chad Rosier00737bd2011-12-01 21:29:16 +00002578static bool EvaluateStaticConstructor(Function *F, const TargetData *TD,
2579 const TargetLibraryInfo *TLI) {
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002580 /// MutatedMemory - For each store we execute, we update this map. Loads
2581 /// check this to get the most up-to-date value. If evaluation is successful,
2582 /// this state is committed to the process.
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002583 DenseMap<Constant*, Constant*> MutatedMemory;
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002584
2585 /// AllocaTmps - To 'execute' an alloca, we create a temporary global variable
2586 /// to represent its body. This vector is needed so we can delete the
2587 /// temporary globals when we are done.
2588 std::vector<GlobalVariable*> AllocaTmps;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002589
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002590 /// CallStack - This is used to detect recursion. In pathological situations
2591 /// we could hit exponential behavior, but at least there is nothing
2592 /// unbounded.
2593 std::vector<Function*> CallStack;
2594
Chris Lattner1945d582010-12-07 04:33:29 +00002595 /// SimpleConstants - These are constants we have checked and know to be
2596 /// simple enough to live in a static initializer of a global.
2597 SmallPtrSet<Constant*, 8> SimpleConstants;
2598
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002599 // Call the function.
Chris Lattnercd271422005-09-27 04:45:34 +00002600 Constant *RetValDummy;
Duncan Sandsfa6a1cf2009-08-17 14:33:27 +00002601 bool EvalSuccess = EvaluateFunction(F, RetValDummy,
2602 SmallVector<Constant*, 0>(), CallStack,
Chris Lattner1945d582010-12-07 04:33:29 +00002603 MutatedMemory, AllocaTmps,
Chad Rosier00737bd2011-12-01 21:29:16 +00002604 SimpleConstants, TD, TLI);
Chris Lattner1945d582010-12-07 04:33:29 +00002605
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002606 if (EvalSuccess) {
Chris Lattnera22fdb02005-09-26 17:07:09 +00002607 // We succeeded at evaluation: commit the result.
David Greene3215b0e2010-01-05 01:28:05 +00002608 DEBUG(dbgs() << "FULLY EVALUATED GLOBAL CTOR FUNCTION '"
Daniel Dunbarce63ffb2009-07-25 00:23:56 +00002609 << F->getName() << "' to " << MutatedMemory.size()
2610 << " stores.\n");
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002611 for (DenseMap<Constant*, Constant*>::iterator I = MutatedMemory.begin(),
Chris Lattnera22fdb02005-09-26 17:07:09 +00002612 E = MutatedMemory.end(); I != E; ++I)
Chris Lattner7b550cc2009-11-06 04:27:31 +00002613 CommitValueTo(I->second, I->first);
Chris Lattnera22fdb02005-09-26 17:07:09 +00002614 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002615
Chris Lattnera22fdb02005-09-26 17:07:09 +00002616 // At this point, we are done interpreting. If we created any 'alloca'
2617 // temporaries, release them now.
2618 while (!AllocaTmps.empty()) {
2619 GlobalVariable *Tmp = AllocaTmps.back();
2620 AllocaTmps.pop_back();
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002621
Chris Lattnera22fdb02005-09-26 17:07:09 +00002622 // If there are still users of the alloca, the program is doing something
2623 // silly, e.g. storing the address of the alloca somewhere and using it
2624 // later. Since this is undefined, we'll just make it be null.
2625 if (!Tmp->use_empty())
Owen Andersona7235ea2009-07-31 20:28:14 +00002626 Tmp->replaceAllUsesWith(Constant::getNullValue(Tmp->getType()));
Chris Lattnera22fdb02005-09-26 17:07:09 +00002627 delete Tmp;
2628 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002629
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002630 return EvalSuccess;
Chris Lattner79c11012005-09-26 04:44:35 +00002631}
2632
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002633/// OptimizeGlobalCtorsList - Simplify and evaluation global ctors if possible.
2634/// Return true if anything changed.
2635bool GlobalOpt::OptimizeGlobalCtorsList(GlobalVariable *&GCL) {
2636 std::vector<Function*> Ctors = ParseGlobalCtors(GCL);
2637 bool MadeChange = false;
2638 if (Ctors.empty()) return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002639
Chris Lattner1945d582010-12-07 04:33:29 +00002640 const TargetData *TD = getAnalysisIfAvailable<TargetData>();
Chad Rosier00737bd2011-12-01 21:29:16 +00002641 const TargetLibraryInfo *TLI = &getAnalysis<TargetLibraryInfo>();
2642
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002643 // Loop over global ctors, optimizing them when we can.
2644 for (unsigned i = 0; i != Ctors.size(); ++i) {
2645 Function *F = Ctors[i];
2646 // Found a null terminator in the middle of the list, prune off the rest of
2647 // the list.
Chris Lattner7d8e58f2005-09-26 02:19:27 +00002648 if (F == 0) {
2649 if (i != Ctors.size()-1) {
2650 Ctors.resize(i+1);
2651 MadeChange = true;
2652 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002653 break;
2654 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002655
Chris Lattner79c11012005-09-26 04:44:35 +00002656 // We cannot simplify external ctor functions.
2657 if (F->empty()) continue;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002658
Chris Lattner79c11012005-09-26 04:44:35 +00002659 // If we can evaluate the ctor at compile time, do.
Chad Rosier00737bd2011-12-01 21:29:16 +00002660 if (EvaluateStaticConstructor(F, TD, TLI)) {
Chris Lattner79c11012005-09-26 04:44:35 +00002661 Ctors.erase(Ctors.begin()+i);
2662 MadeChange = true;
2663 --i;
2664 ++NumCtorsEvaluated;
2665 continue;
2666 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002667 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002668
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002669 if (!MadeChange) return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002670
Chris Lattner7b550cc2009-11-06 04:27:31 +00002671 GCL = InstallGlobalCtors(GCL, Ctors);
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002672 return true;
2673}
2674
Duncan Sandsfc5940d2009-03-06 10:21:56 +00002675bool GlobalOpt::OptimizeGlobalAliases(Module &M) {
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002676 bool Changed = false;
2677
Duncan Sands177d84e2009-01-07 20:01:06 +00002678 for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end();
Duncan Sands4782b302009-02-15 09:56:08 +00002679 I != E;) {
2680 Module::alias_iterator J = I++;
Duncan Sandsfc5940d2009-03-06 10:21:56 +00002681 // Aliases without names cannot be referenced outside this module.
2682 if (!J->hasName() && !J->isDeclaration())
2683 J->setLinkage(GlobalValue::InternalLinkage);
Duncan Sands4782b302009-02-15 09:56:08 +00002684 // If the aliasee may change at link time, nothing can be done - bail out.
2685 if (J->mayBeOverridden())
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002686 continue;
2687
Duncan Sands4782b302009-02-15 09:56:08 +00002688 Constant *Aliasee = J->getAliasee();
2689 GlobalValue *Target = cast<GlobalValue>(Aliasee->stripPointerCasts());
Duncan Sands95c5d0f2009-02-18 17:55:38 +00002690 Target->removeDeadConstantUsers();
Duncan Sands4782b302009-02-15 09:56:08 +00002691 bool hasOneUse = Target->hasOneUse() && Aliasee->hasOneUse();
2692
2693 // Make all users of the alias use the aliasee instead.
2694 if (!J->use_empty()) {
2695 J->replaceAllUsesWith(Aliasee);
2696 ++NumAliasesResolved;
2697 Changed = true;
2698 }
2699
Duncan Sands7a154cf2009-12-08 10:10:20 +00002700 // If the alias is externally visible, we may still be able to simplify it.
2701 if (!J->hasLocalLinkage()) {
2702 // If the aliasee has internal linkage, give it the name and linkage
2703 // of the alias, and delete the alias. This turns:
2704 // define internal ... @f(...)
2705 // @a = alias ... @f
2706 // into:
2707 // define ... @a(...)
2708 if (!Target->hasLocalLinkage())
2709 continue;
Duncan Sands4782b302009-02-15 09:56:08 +00002710
Duncan Sands7a154cf2009-12-08 10:10:20 +00002711 // Do not perform the transform if multiple aliases potentially target the
Gabor Greif27236912010-04-07 18:59:26 +00002712 // aliasee. This check also ensures that it is safe to replace the section
Duncan Sands7a154cf2009-12-08 10:10:20 +00002713 // and other attributes of the aliasee with those of the alias.
2714 if (!hasOneUse)
2715 continue;
Duncan Sands4782b302009-02-15 09:56:08 +00002716
Duncan Sands7a154cf2009-12-08 10:10:20 +00002717 // Give the aliasee the name, linkage and other attributes of the alias.
2718 Target->takeName(J);
2719 Target->setLinkage(J->getLinkage());
2720 Target->GlobalValue::copyAttributesFrom(J);
2721 }
Duncan Sands4782b302009-02-15 09:56:08 +00002722
2723 // Delete the alias.
2724 M.getAliasList().erase(J);
2725 ++NumAliasesRemoved;
2726 Changed = true;
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002727 }
2728
2729 return Changed;
2730}
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002731
Anders Carlssona201c4c2011-03-20 17:59:11 +00002732static Function *FindCXAAtExit(Module &M) {
2733 Function *Fn = M.getFunction("__cxa_atexit");
2734
2735 if (!Fn)
2736 return 0;
2737
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002738 FunctionType *FTy = Fn->getFunctionType();
Anders Carlssona201c4c2011-03-20 17:59:11 +00002739
Anders Carlsson1f7c7ba2011-03-20 19:51:13 +00002740 // Checking that the function has the right return type, the right number of
2741 // parameters and that they all have pointer types should be enough.
2742 if (!FTy->getReturnType()->isIntegerTy() ||
2743 FTy->getNumParams() != 3 ||
Anders Carlssona201c4c2011-03-20 17:59:11 +00002744 !FTy->getParamType(0)->isPointerTy() ||
2745 !FTy->getParamType(1)->isPointerTy() ||
2746 !FTy->getParamType(2)->isPointerTy())
2747 return 0;
2748
2749 return Fn;
2750}
2751
2752/// cxxDtorIsEmpty - Returns whether the given function is an empty C++
2753/// destructor and can therefore be eliminated.
2754/// Note that we assume that other optimization passes have already simplified
2755/// the code so we only look for a function with a single basic block, where
Benjamin Kramerc1322a12012-02-09 16:28:15 +00002756/// the only allowed instructions are 'ret', 'call' to an empty C++ dtor and
2757/// other side-effect free instructions.
Anders Carlsson372ec6a2011-03-20 20:16:43 +00002758static bool cxxDtorIsEmpty(const Function &Fn,
2759 SmallPtrSet<const Function *, 8> &CalledFunctions) {
Anders Carlsson1f7c7ba2011-03-20 19:51:13 +00002760 // FIXME: We could eliminate C++ destructors if they're readonly/readnone and
Nick Lewycky35ee1c92011-03-21 02:26:01 +00002761 // nounwind, but that doesn't seem worth doing.
Anders Carlsson1f7c7ba2011-03-20 19:51:13 +00002762 if (Fn.isDeclaration())
2763 return false;
Anders Carlssona201c4c2011-03-20 17:59:11 +00002764
2765 if (++Fn.begin() != Fn.end())
2766 return false;
2767
2768 const BasicBlock &EntryBlock = Fn.getEntryBlock();
2769 for (BasicBlock::const_iterator I = EntryBlock.begin(), E = EntryBlock.end();
2770 I != E; ++I) {
2771 if (const CallInst *CI = dyn_cast<CallInst>(I)) {
Anders Carlssonb12caf32011-03-21 14:54:40 +00002772 // Ignore debug intrinsics.
2773 if (isa<DbgInfoIntrinsic>(CI))
2774 continue;
2775
Anders Carlssona201c4c2011-03-20 17:59:11 +00002776 const Function *CalledFn = CI->getCalledFunction();
2777
2778 if (!CalledFn)
2779 return false;
2780
Anders Carlsson807bc2a2011-03-22 03:21:01 +00002781 SmallPtrSet<const Function *, 8> NewCalledFunctions(CalledFunctions);
2782
Anders Carlsson1f7c7ba2011-03-20 19:51:13 +00002783 // Don't treat recursive functions as empty.
Anders Carlsson807bc2a2011-03-22 03:21:01 +00002784 if (!NewCalledFunctions.insert(CalledFn))
Anders Carlsson1f7c7ba2011-03-20 19:51:13 +00002785 return false;
2786
Anders Carlsson807bc2a2011-03-22 03:21:01 +00002787 if (!cxxDtorIsEmpty(*CalledFn, NewCalledFunctions))
Anders Carlssona201c4c2011-03-20 17:59:11 +00002788 return false;
2789 } else if (isa<ReturnInst>(*I))
Benjamin Kramerd4692742012-02-09 14:26:06 +00002790 return true; // We're done.
2791 else if (I->mayHaveSideEffects())
2792 return false; // Destructor with side effects, bail.
Anders Carlssona201c4c2011-03-20 17:59:11 +00002793 }
2794
2795 return false;
2796}
2797
2798bool GlobalOpt::OptimizeEmptyGlobalCXXDtors(Function *CXAAtExitFn) {
2799 /// Itanium C++ ABI p3.3.5:
2800 ///
2801 /// After constructing a global (or local static) object, that will require
2802 /// destruction on exit, a termination function is registered as follows:
2803 ///
2804 /// extern "C" int __cxa_atexit ( void (*f)(void *), void *p, void *d );
2805 ///
2806 /// This registration, e.g. __cxa_atexit(f,p,d), is intended to cause the
2807 /// call f(p) when DSO d is unloaded, before all such termination calls
2808 /// registered before this one. It returns zero if registration is
Nick Lewycky35ee1c92011-03-21 02:26:01 +00002809 /// successful, nonzero on failure.
Anders Carlssona201c4c2011-03-20 17:59:11 +00002810
2811 // This pass will look for calls to __cxa_atexit where the function is trivial
2812 // and remove them.
2813 bool Changed = false;
2814
2815 for (Function::use_iterator I = CXAAtExitFn->use_begin(),
2816 E = CXAAtExitFn->use_end(); I != E;) {
Anders Carlsson4f735ca2011-03-20 20:21:33 +00002817 // We're only interested in calls. Theoretically, we could handle invoke
2818 // instructions as well, but neither llvm-gcc nor clang generate invokes
2819 // to __cxa_atexit.
Anders Carlssonb12caf32011-03-21 14:54:40 +00002820 CallInst *CI = dyn_cast<CallInst>(*I++);
2821 if (!CI)
Anders Carlsson4f735ca2011-03-20 20:21:33 +00002822 continue;
2823
Anders Carlssona201c4c2011-03-20 17:59:11 +00002824 Function *DtorFn =
Anders Carlssonb12caf32011-03-21 14:54:40 +00002825 dyn_cast<Function>(CI->getArgOperand(0)->stripPointerCasts());
Anders Carlssona201c4c2011-03-20 17:59:11 +00002826 if (!DtorFn)
2827 continue;
2828
Anders Carlsson372ec6a2011-03-20 20:16:43 +00002829 SmallPtrSet<const Function *, 8> CalledFunctions;
2830 if (!cxxDtorIsEmpty(*DtorFn, CalledFunctions))
Anders Carlssona201c4c2011-03-20 17:59:11 +00002831 continue;
2832
2833 // Just remove the call.
Anders Carlssonb12caf32011-03-21 14:54:40 +00002834 CI->replaceAllUsesWith(Constant::getNullValue(CI->getType()));
2835 CI->eraseFromParent();
Anders Carlsson1f7c7ba2011-03-20 19:51:13 +00002836
Anders Carlssona201c4c2011-03-20 17:59:11 +00002837 ++NumCXXDtorsRemoved;
2838
2839 Changed |= true;
2840 }
2841
2842 return Changed;
2843}
2844
Chris Lattner7a90b682004-10-07 04:16:33 +00002845bool GlobalOpt::runOnModule(Module &M) {
Chris Lattner079236d2004-02-25 21:34:36 +00002846 bool Changed = false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002847
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002848 // Try to find the llvm.globalctors list.
2849 GlobalVariable *GlobalCtors = FindGlobalCtors(M);
Chris Lattner7a90b682004-10-07 04:16:33 +00002850
Anders Carlssona201c4c2011-03-20 17:59:11 +00002851 Function *CXAAtExitFn = FindCXAAtExit(M);
2852
Chris Lattner7a90b682004-10-07 04:16:33 +00002853 bool LocalChange = true;
2854 while (LocalChange) {
2855 LocalChange = false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002856
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002857 // Delete functions that are trivially dead, ccc -> fastcc
2858 LocalChange |= OptimizeFunctions(M);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002859
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002860 // Optimize global_ctors list.
2861 if (GlobalCtors)
2862 LocalChange |= OptimizeGlobalCtorsList(GlobalCtors);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002863
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002864 // Optimize non-address-taken globals.
2865 LocalChange |= OptimizeGlobalVars(M);
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002866
2867 // Resolve aliases, when possible.
Duncan Sandsfc5940d2009-03-06 10:21:56 +00002868 LocalChange |= OptimizeGlobalAliases(M);
Anders Carlssona201c4c2011-03-20 17:59:11 +00002869
2870 // Try to remove trivial global destructors.
2871 if (CXAAtExitFn)
2872 LocalChange |= OptimizeEmptyGlobalCXXDtors(CXAAtExitFn);
2873
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002874 Changed |= LocalChange;
Chris Lattner7a90b682004-10-07 04:16:33 +00002875 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002876
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002877 // TODO: Move all global ctors functions to the end of the module for code
2878 // layout.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002879
Chris Lattner079236d2004-02-25 21:34:36 +00002880 return Changed;
2881}