blob: 3129559fb99a0c2698b703f5610364533e15628c [file] [log] [blame]
Chris Lattner7a90b682004-10-07 04:16:33 +00001//===- GlobalOpt.cpp - Optimize Global Variables --------------------------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
Chris Lattner079236d2004-02-25 21:34:36 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
Chris Lattner079236d2004-02-25 21:34:36 +00008//===----------------------------------------------------------------------===//
9//
Chris Lattner7a90b682004-10-07 04:16:33 +000010// This pass transforms simple global variables that never have their address
11// taken. If obviously true, it marks read/write globals as constant, deletes
12// variables only stored to, etc.
Chris Lattner079236d2004-02-25 21:34:36 +000013//
14//===----------------------------------------------------------------------===//
15
Chris Lattner7a90b682004-10-07 04:16:33 +000016#define DEBUG_TYPE "globalopt"
Chris Lattner079236d2004-02-25 21:34:36 +000017#include "llvm/Transforms/IPO.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000018#include "llvm/ADT/DenseMap.h"
19#include "llvm/ADT/STLExtras.h"
20#include "llvm/ADT/SmallPtrSet.h"
21#include "llvm/ADT/SmallVector.h"
22#include "llvm/ADT/Statistic.h"
23#include "llvm/Analysis/ConstantFolding.h"
24#include "llvm/Analysis/MemoryBuiltins.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000025#include "llvm/IR/CallingConv.h"
26#include "llvm/IR/Constants.h"
27#include "llvm/IR/DataLayout.h"
28#include "llvm/IR/DerivedTypes.h"
29#include "llvm/IR/Instructions.h"
30#include "llvm/IR/IntrinsicInst.h"
31#include "llvm/IR/Module.h"
32#include "llvm/IR/Operator.h"
Chris Lattner079236d2004-02-25 21:34:36 +000033#include "llvm/Pass.h"
Duncan Sands548448a2008-02-18 17:32:13 +000034#include "llvm/Support/CallSite.h"
Chris Lattner79066fa2007-01-30 23:46:24 +000035#include "llvm/Support/Debug.h"
Torok Edwinc25e7582009-07-11 20:10:48 +000036#include "llvm/Support/ErrorHandling.h"
Chris Lattner941db492008-01-14 02:09:12 +000037#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner998182b2008-04-26 07:40:11 +000038#include "llvm/Support/MathExtras.h"
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000039#include "llvm/Support/raw_ostream.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000040#include "llvm/Target/TargetLibraryInfo.h"
Rafael Espindola4ef7eaf2013-07-25 03:23:25 +000041#include "llvm/Transforms/Utils/ModuleUtils.h"
Chris Lattnere47ba742004-10-06 20:57:02 +000042#include <algorithm>
Chris Lattner079236d2004-02-25 21:34:36 +000043using namespace llvm;
44
Chris Lattner86453c52006-12-19 22:09:18 +000045STATISTIC(NumMarked , "Number of globals marked constant");
Rafael Espindolac4440e32011-01-19 16:32:21 +000046STATISTIC(NumUnnamed , "Number of globals marked unnamed_addr");
Chris Lattner86453c52006-12-19 22:09:18 +000047STATISTIC(NumSRA , "Number of aggregate globals broken into scalars");
48STATISTIC(NumHeapSRA , "Number of heap objects SRA'd");
49STATISTIC(NumSubstitute,"Number of globals with initializers stored into them");
50STATISTIC(NumDeleted , "Number of globals deleted");
51STATISTIC(NumFnDeleted , "Number of functions deleted");
52STATISTIC(NumGlobUses , "Number of global uses devirtualized");
Chris Lattner86453c52006-12-19 22:09:18 +000053STATISTIC(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,
Rafael Espindolac4440e32011-01-19 16:32:21 +000082 const GlobalStatus &GS);
Anders Carlssona201c4c2011-03-20 17:59:11 +000083 bool OptimizeEmptyGlobalCXXDtors(Function *CXAAtExitFn);
Nick Lewycky6a577f82012-02-12 01:13:18 +000084
Micah Villmow3574eca2012-10-08 16:38:25 +000085 DataLayout *TD;
Nick Lewycky6a577f82012-02-12 01:13:18 +000086 TargetLibraryInfo *TLI;
Chris Lattner079236d2004-02-25 21:34:36 +000087 };
Chris Lattner079236d2004-02-25 21:34:36 +000088}
89
Dan Gohman844731a2008-05-13 00:00:25 +000090char GlobalOpt::ID = 0;
Chad Rosier00737bd2011-12-01 21:29:16 +000091INITIALIZE_PASS_BEGIN(GlobalOpt, "globalopt",
92 "Global Variable Optimizer", false, false)
93INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
94INITIALIZE_PASS_END(GlobalOpt, "globalopt",
Owen Andersonce665bd2010-10-07 22:25:06 +000095 "Global Variable Optimizer", false, false)
Dan Gohman844731a2008-05-13 00:00:25 +000096
Chris Lattner7a90b682004-10-07 04:16:33 +000097ModulePass *llvm::createGlobalOptimizerPass() { return new GlobalOpt(); }
Chris Lattner079236d2004-02-25 21:34:36 +000098
Dan Gohman844731a2008-05-13 00:00:25 +000099namespace {
100
Chris Lattner7a90b682004-10-07 04:16:33 +0000101/// GlobalStatus - As we analyze each global, keep track of some information
102/// about it. If we find out that the address of the global is taken, none of
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000103/// this info will be accurate.
Nick Lewycky6726b6d2009-10-25 06:33:48 +0000104struct GlobalStatus {
Rafael Espindolac4440e32011-01-19 16:32:21 +0000105 /// isCompared - True if the global's address is used in a comparison.
106 bool isCompared;
107
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000108 /// isLoaded - True if the global is ever loaded. If the global isn't ever
109 /// loaded it can be deleted.
Chris Lattner7a90b682004-10-07 04:16:33 +0000110 bool isLoaded;
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000111
112 /// StoredType - Keep track of what stores to the global look like.
113 ///
Chris Lattner7a90b682004-10-07 04:16:33 +0000114 enum StoredType {
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000115 /// NotStored - There is no store to this global. It can thus be marked
116 /// constant.
117 NotStored,
118
119 /// isInitializerStored - This global is stored to, but the only thing
120 /// stored is the constant it was initialized with. This is only tracked
121 /// for scalar globals.
122 isInitializerStored,
123
124 /// isStoredOnce - This global is stored to, but only its initializer and
125 /// one other value is ever stored to it. If this global isStoredOnce, we
126 /// track the value stored to it in StoredOnceValue below. This is only
127 /// tracked for scalar globals.
128 isStoredOnce,
129
130 /// isStored - This global is stored to by multiple values or something else
131 /// that we cannot track.
132 isStored
Chris Lattner7a90b682004-10-07 04:16:33 +0000133 } StoredType;
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000134
135 /// StoredOnceValue - If only one value (besides the initializer constant) is
136 /// ever stored to this global, keep track of what value it is.
137 Value *StoredOnceValue;
138
Nick Lewyckyfad4d402012-02-05 19:56:38 +0000139 /// AtomicOrdering - Set to the strongest atomic ordering requirement.
140 AtomicOrdering Ordering;
141
Alexey Samsonov6ffce6f2013-10-02 15:31:34 +0000142 GlobalStatus()
143 : isCompared(false), isLoaded(false), StoredType(NotStored),
144 StoredOnceValue(0), Ordering(NotAtomic) {}
Chris Lattner7a90b682004-10-07 04:16:33 +0000145};
Chris Lattnere47ba742004-10-06 20:57:02 +0000146
Dan Gohman844731a2008-05-13 00:00:25 +0000147}
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000148
Nick Lewyckyfad4d402012-02-05 19:56:38 +0000149/// StrongerOrdering - Return the stronger of the two ordering. If the two
150/// orderings are acquire and release, then return AcquireRelease.
151///
152static AtomicOrdering StrongerOrdering(AtomicOrdering X, AtomicOrdering Y) {
153 if (X == Acquire && Y == Release) return AcquireRelease;
154 if (Y == Acquire && X == Release) return AcquireRelease;
155 return (AtomicOrdering)std::max(X, Y);
156}
157
Sylvestre Ledru94c22712012-09-27 10:14:43 +0000158/// SafeToDestroyConstant - It is safe to destroy a constant iff it is only used
Nick Lewyckybc384a12012-02-05 19:48:37 +0000159/// by constants itself. Note that constants cannot be cyclic, so this test is
160/// pretty easy to implement recursively.
161///
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000162static bool SafeToDestroyConstant(const Constant *C) {
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000163 if (isa<GlobalValue>(C)) return false;
164
Gabor Greif27236912010-04-07 18:59:26 +0000165 for (Value::const_use_iterator UI = C->use_begin(), E = C->use_end(); UI != E;
166 ++UI)
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000167 if (const Constant *CU = dyn_cast<Constant>(*UI)) {
Jay Foade3acf152009-06-09 21:37:11 +0000168 if (!SafeToDestroyConstant(CU)) return false;
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000169 } else
170 return false;
171 return true;
172}
173
174
Chris Lattner7a90b682004-10-07 04:16:33 +0000175/// AnalyzeGlobal - Look at all uses of the global and fill in the GlobalStatus
176/// structure. If the global has its address taken, return true to indicate we
177/// can't do anything with it.
Chris Lattner079236d2004-02-25 21:34:36 +0000178///
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000179static bool AnalyzeGlobal(const Value *V, GlobalStatus &GS,
180 SmallPtrSet<const PHINode*, 16> &PHIUsers) {
Gabor Greif27236912010-04-07 18:59:26 +0000181 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;
Gabor Greife6642672010-07-09 16:51:20 +0000182 ++UI) {
183 const User *U = *UI;
184 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
Chris Lattnerd91ed102011-01-01 22:31:46 +0000185 // If the result of the constantexpr isn't pointer type, then we won't
186 // know to expect it in various places. Just reject early.
187 if (!isa<PointerType>(CE->getType())) return true;
Jakub Staszak582088c2012-12-06 21:57:16 +0000188
Chris Lattner7a90b682004-10-07 04:16:33 +0000189 if (AnalyzeGlobal(CE, GS, PHIUsers)) return true;
Gabor Greife6642672010-07-09 16:51:20 +0000190 } else if (const Instruction *I = dyn_cast<Instruction>(U)) {
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000191 if (const LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattner7a90b682004-10-07 04:16:33 +0000192 GS.isLoaded = true;
Nick Lewyckyfad4d402012-02-05 19:56:38 +0000193 // Don't hack on volatile loads.
194 if (LI->isVolatile()) return true;
195 GS.Ordering = StrongerOrdering(GS.Ordering, LI->getOrdering());
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000196 } else if (const StoreInst *SI = dyn_cast<StoreInst>(I)) {
Chris Lattner36025492004-10-07 06:01:25 +0000197 // Don't allow a store OF the address, only stores TO the address.
198 if (SI->getOperand(0) == V) return true;
199
Nick Lewyckyfad4d402012-02-05 19:56:38 +0000200 // Don't hack on volatile stores.
201 if (SI->isVolatile()) return true;
Hans Wennborg18398582012-11-15 11:40:00 +0000202
Nick Lewyckyfad4d402012-02-05 19:56:38 +0000203 GS.Ordering = StrongerOrdering(GS.Ordering, SI->getOrdering());
Chris Lattnerc69d3c92008-01-29 19:01:37 +0000204
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000205 // If this is a direct store to the global (i.e., the global is a scalar
206 // value, not an aggregate), keep more specific information about
207 // stores.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000208 if (GS.StoredType != GlobalStatus::isStored) {
Gabor Greif27236912010-04-07 18:59:26 +0000209 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(
210 SI->getOperand(1))) {
Chris Lattnerbd38edf2004-11-14 20:50:30 +0000211 Value *StoredVal = SI->getOperand(0);
Hans Wennborg18398582012-11-15 11:40:00 +0000212
213 if (Constant *C = dyn_cast<Constant>(StoredVal)) {
214 if (C->isThreadDependent()) {
215 // The stored value changes between threads; don't track it.
216 return true;
217 }
218 }
219
Chris Lattnerbd38edf2004-11-14 20:50:30 +0000220 if (StoredVal == GV->getInitializer()) {
221 if (GS.StoredType < GlobalStatus::isInitializerStored)
222 GS.StoredType = GlobalStatus::isInitializerStored;
223 } else if (isa<LoadInst>(StoredVal) &&
224 cast<LoadInst>(StoredVal)->getOperand(0) == GV) {
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000225 if (GS.StoredType < GlobalStatus::isInitializerStored)
226 GS.StoredType = GlobalStatus::isInitializerStored;
227 } else if (GS.StoredType < GlobalStatus::isStoredOnce) {
228 GS.StoredType = GlobalStatus::isStoredOnce;
Chris Lattnerbd38edf2004-11-14 20:50:30 +0000229 GS.StoredOnceValue = StoredVal;
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000230 } else if (GS.StoredType == GlobalStatus::isStoredOnce &&
Chris Lattnerbd38edf2004-11-14 20:50:30 +0000231 GS.StoredOnceValue == StoredVal) {
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000232 // noop.
233 } else {
234 GS.StoredType = GlobalStatus::isStored;
235 }
236 } else {
Chris Lattner7a90b682004-10-07 04:16:33 +0000237 GS.StoredType = GlobalStatus::isStored;
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000238 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000239 }
Duncan Sandsb2fe7f12012-07-02 18:55:39 +0000240 } else if (isa<BitCastInst>(I)) {
241 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Chris Lattner35c81b02005-02-27 18:58:52 +0000242 } else if (isa<GetElementPtrInst>(I)) {
Chris Lattner7a90b682004-10-07 04:16:33 +0000243 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Chris Lattner35c81b02005-02-27 18:58:52 +0000244 } else if (isa<SelectInst>(I)) {
Chris Lattner7a90b682004-10-07 04:16:33 +0000245 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000246 } else if (const PHINode *PN = dyn_cast<PHINode>(I)) {
Chris Lattner7a90b682004-10-07 04:16:33 +0000247 // PHI nodes we can check just like select or GEP instructions, but we
248 // have to be careful about infinite recursion.
Chris Lattner5a6bb6a2008-12-16 07:34:30 +0000249 if (PHIUsers.insert(PN)) // Not already visited.
Chris Lattner7a90b682004-10-07 04:16:33 +0000250 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Reid Spencere4d87aa2006-12-23 06:05:41 +0000251 } else if (isa<CmpInst>(I)) {
Rafael Espindolac4440e32011-01-19 16:32:21 +0000252 GS.isCompared = true;
Nick Lewycky1f237b02011-05-29 18:41:56 +0000253 } else if (const MemTransferInst *MTI = dyn_cast<MemTransferInst>(I)) {
254 if (MTI->isVolatile()) return true;
Gabor Greif9e4f2432010-06-24 14:42:01 +0000255 if (MTI->getArgOperand(0) == V)
Eric Christopher551754c2010-04-16 23:37:20 +0000256 GS.StoredType = GlobalStatus::isStored;
Gabor Greif9e4f2432010-06-24 14:42:01 +0000257 if (MTI->getArgOperand(1) == V)
Chris Lattner35c81b02005-02-27 18:58:52 +0000258 GS.isLoaded = true;
Nick Lewycky1f237b02011-05-29 18:41:56 +0000259 } else if (const MemSetInst *MSI = dyn_cast<MemSetInst>(I)) {
260 assert(MSI->getArgOperand(0) == V && "Memset only takes one pointer!");
261 if (MSI->isVolatile()) return true;
Chris Lattner35c81b02005-02-27 18:58:52 +0000262 GS.StoredType = GlobalStatus::isStored;
Chris Lattner7a90b682004-10-07 04:16:33 +0000263 } else {
264 return true; // Any other non-load instruction might take address!
Chris Lattner9ce30002004-07-20 03:58:07 +0000265 }
Gabor Greife6642672010-07-09 16:51:20 +0000266 } else if (const Constant *C = dyn_cast<Constant>(U)) {
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000267 // We might have a dead and dangling constant hanging off of here.
Jay Foade3acf152009-06-09 21:37:11 +0000268 if (!SafeToDestroyConstant(C))
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000269 return true;
Chris Lattner079236d2004-02-25 21:34:36 +0000270 } else {
Chris Lattner553ca522005-06-15 21:11:48 +0000271 // Otherwise must be some other user.
Chris Lattner079236d2004-02-25 21:34:36 +0000272 return true;
273 }
Gabor Greife6642672010-07-09 16:51:20 +0000274 }
Chris Lattner079236d2004-02-25 21:34:36 +0000275
276 return false;
277}
278
Nick Lewycky8899d5c2012-07-24 07:21:08 +0000279/// isLeakCheckerRoot - Is this global variable possibly used by a leak checker
280/// as a root? If so, we might not really want to eliminate the stores to it.
281static bool isLeakCheckerRoot(GlobalVariable *GV) {
282 // A global variable is a root if it is a pointer, or could plausibly contain
283 // a pointer. There are two challenges; one is that we could have a struct
284 // the has an inner member which is a pointer. We recurse through the type to
285 // detect these (up to a point). The other is that we may actually be a union
286 // of a pointer and another type, and so our LLVM type is an integer which
287 // gets converted into a pointer, or our type is an [i8 x #] with a pointer
288 // potentially contained here.
289
290 if (GV->hasPrivateLinkage())
291 return false;
292
293 SmallVector<Type *, 4> Types;
294 Types.push_back(cast<PointerType>(GV->getType())->getElementType());
295
296 unsigned Limit = 20;
297 do {
298 Type *Ty = Types.pop_back_val();
299 switch (Ty->getTypeID()) {
300 default: break;
301 case Type::PointerTyID: return true;
302 case Type::ArrayTyID:
303 case Type::VectorTyID: {
304 SequentialType *STy = cast<SequentialType>(Ty);
305 Types.push_back(STy->getElementType());
306 break;
307 }
308 case Type::StructTyID: {
309 StructType *STy = cast<StructType>(Ty);
310 if (STy->isOpaque()) return true;
311 for (StructType::element_iterator I = STy->element_begin(),
312 E = STy->element_end(); I != E; ++I) {
313 Type *InnerTy = *I;
314 if (isa<PointerType>(InnerTy)) return true;
315 if (isa<CompositeType>(InnerTy))
316 Types.push_back(InnerTy);
317 }
318 break;
319 }
320 }
321 if (--Limit == 0) return true;
322 } while (!Types.empty());
323 return false;
324}
325
326/// Given a value that is stored to a global but never read, determine whether
327/// it's safe to remove the store and the chain of computation that feeds the
328/// store.
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000329static bool IsSafeComputationToRemove(Value *V, const TargetLibraryInfo *TLI) {
Nick Lewycky8899d5c2012-07-24 07:21:08 +0000330 do {
331 if (isa<Constant>(V))
332 return true;
333 if (!V->hasOneUse())
334 return false;
Nick Lewyckyb8cd66b2012-07-25 21:19:40 +0000335 if (isa<LoadInst>(V) || isa<InvokeInst>(V) || isa<Argument>(V) ||
336 isa<GlobalValue>(V))
Nick Lewycky8899d5c2012-07-24 07:21:08 +0000337 return false;
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000338 if (isAllocationFn(V, TLI))
Nick Lewycky8899d5c2012-07-24 07:21:08 +0000339 return true;
340
341 Instruction *I = cast<Instruction>(V);
342 if (I->mayHaveSideEffects())
343 return false;
344 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
345 if (!GEP->hasAllConstantIndices())
346 return false;
347 } else if (I->getNumOperands() != 1) {
348 return false;
349 }
350
351 V = I->getOperand(0);
352 } while (1);
353}
354
355/// CleanupPointerRootUsers - This GV is a pointer root. Loop over all users
356/// of the global and clean up any that obviously don't assign the global a
357/// value that isn't dynamically allocated.
358///
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000359static bool CleanupPointerRootUsers(GlobalVariable *GV,
360 const TargetLibraryInfo *TLI) {
Nick Lewycky8899d5c2012-07-24 07:21:08 +0000361 // A brief explanation of leak checkers. The goal is to find bugs where
362 // pointers are forgotten, causing an accumulating growth in memory
363 // usage over time. The common strategy for leak checkers is to whitelist the
364 // memory pointed to by globals at exit. This is popular because it also
365 // solves another problem where the main thread of a C++ program may shut down
366 // before other threads that are still expecting to use those globals. To
367 // handle that case, we expect the program may create a singleton and never
368 // destroy it.
369
370 bool Changed = false;
371
372 // If Dead[n].first is the only use of a malloc result, we can delete its
373 // chain of computation and the store to the global in Dead[n].second.
374 SmallVector<std::pair<Instruction *, Instruction *>, 32> Dead;
375
376 // Constants can't be pointers to dynamically allocated memory.
377 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end();
378 UI != E;) {
379 User *U = *UI++;
380 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
381 Value *V = SI->getValueOperand();
382 if (isa<Constant>(V)) {
383 Changed = true;
384 SI->eraseFromParent();
385 } else if (Instruction *I = dyn_cast<Instruction>(V)) {
386 if (I->hasOneUse())
387 Dead.push_back(std::make_pair(I, SI));
388 }
389 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(U)) {
390 if (isa<Constant>(MSI->getValue())) {
391 Changed = true;
392 MSI->eraseFromParent();
393 } else if (Instruction *I = dyn_cast<Instruction>(MSI->getValue())) {
394 if (I->hasOneUse())
395 Dead.push_back(std::make_pair(I, MSI));
396 }
397 } else if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(U)) {
398 GlobalVariable *MemSrc = dyn_cast<GlobalVariable>(MTI->getSource());
399 if (MemSrc && MemSrc->isConstant()) {
400 Changed = true;
401 MTI->eraseFromParent();
402 } else if (Instruction *I = dyn_cast<Instruction>(MemSrc)) {
403 if (I->hasOneUse())
404 Dead.push_back(std::make_pair(I, MTI));
405 }
406 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
407 if (CE->use_empty()) {
408 CE->destroyConstant();
409 Changed = true;
410 }
411 } else if (Constant *C = dyn_cast<Constant>(U)) {
412 if (SafeToDestroyConstant(C)) {
413 C->destroyConstant();
414 // This could have invalidated UI, start over from scratch.
415 Dead.clear();
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000416 CleanupPointerRootUsers(GV, TLI);
Nick Lewycky8899d5c2012-07-24 07:21:08 +0000417 return true;
418 }
419 }
420 }
421
422 for (int i = 0, e = Dead.size(); i != e; ++i) {
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000423 if (IsSafeComputationToRemove(Dead[i].first, TLI)) {
Nick Lewycky8899d5c2012-07-24 07:21:08 +0000424 Dead[i].second->eraseFromParent();
425 Instruction *I = Dead[i].first;
426 do {
Michael Gottesmandcf66952013-01-11 23:08:52 +0000427 if (isAllocationFn(I, TLI))
428 break;
Nick Lewycky8899d5c2012-07-24 07:21:08 +0000429 Instruction *J = dyn_cast<Instruction>(I->getOperand(0));
430 if (!J)
431 break;
432 I->eraseFromParent();
433 I = J;
Nick Lewycky952f5d52012-07-24 21:33:00 +0000434 } while (1);
Nick Lewycky8899d5c2012-07-24 07:21:08 +0000435 I->eraseFromParent();
436 }
437 }
438
439 return Changed;
440}
441
Chris Lattnere47ba742004-10-06 20:57:02 +0000442/// CleanupConstantGlobalUsers - We just marked GV constant. Loop over all
443/// users of the global, cleaning up the obvious ones. This is largely just a
Chris Lattner031955d2004-10-10 16:43:46 +0000444/// quick scan over the use list to clean up the easy and obvious cruft. This
445/// returns true if it made a change.
Nick Lewycky6a577f82012-02-12 01:13:18 +0000446static bool CleanupConstantGlobalUsers(Value *V, Constant *Init,
Micah Villmow3574eca2012-10-08 16:38:25 +0000447 DataLayout *TD, TargetLibraryInfo *TLI) {
Chris Lattner031955d2004-10-10 16:43:46 +0000448 bool Changed = false;
Bill Wendling2b792362013-04-02 08:16:45 +0000449 SmallVector<User*, 8> WorkList(V->use_begin(), V->use_end());
450 while (!WorkList.empty()) {
451 User *U = WorkList.pop_back_val();
Misha Brukmanfd939082005-04-21 23:48:37 +0000452
Chris Lattner7a90b682004-10-07 04:16:33 +0000453 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
Chris Lattner35c81b02005-02-27 18:58:52 +0000454 if (Init) {
455 // Replace the load with the initializer.
456 LI->replaceAllUsesWith(Init);
457 LI->eraseFromParent();
458 Changed = true;
459 }
Chris Lattner7a90b682004-10-07 04:16:33 +0000460 } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
Chris Lattnere47ba742004-10-06 20:57:02 +0000461 // Store must be unreachable or storing Init into the global.
Chris Lattner7a7ed022004-10-16 18:09:00 +0000462 SI->eraseFromParent();
Chris Lattner031955d2004-10-10 16:43:46 +0000463 Changed = true;
Chris Lattner7a90b682004-10-07 04:16:33 +0000464 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
465 if (CE->getOpcode() == Instruction::GetElementPtr) {
Chris Lattneraae4a1c2005-09-26 07:34:35 +0000466 Constant *SubInit = 0;
467 if (Init)
Dan Gohmanc6f69e92009-10-05 16:36:26 +0000468 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
Nick Lewycky6a577f82012-02-12 01:13:18 +0000469 Changed |= CleanupConstantGlobalUsers(CE, SubInit, TD, TLI);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000470 } else if (CE->getOpcode() == Instruction::BitCast &&
Duncan Sands1df98592010-02-16 11:11:14 +0000471 CE->getType()->isPointerTy()) {
Chris Lattner35c81b02005-02-27 18:58:52 +0000472 // Pointer cast, delete any stores and memsets to the global.
Nick Lewycky6a577f82012-02-12 01:13:18 +0000473 Changed |= CleanupConstantGlobalUsers(CE, 0, TD, TLI);
Chris Lattner35c81b02005-02-27 18:58:52 +0000474 }
475
476 if (CE->use_empty()) {
477 CE->destroyConstant();
478 Changed = true;
Chris Lattner7a90b682004-10-07 04:16:33 +0000479 }
480 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
Chris Lattner7b52fe72007-11-09 17:33:02 +0000481 // Do not transform "gepinst (gep constexpr (GV))" here, because forming
482 // "gepconstexpr (gep constexpr (GV))" will cause the two gep's to fold
483 // and will invalidate our notion of what Init is.
Chris Lattner19450242007-11-13 21:46:23 +0000484 Constant *SubInit = 0;
Chris Lattner7b52fe72007-11-09 17:33:02 +0000485 if (!isa<ConstantExpr>(GEP->getOperand(0))) {
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000486 ConstantExpr *CE =
Nick Lewycky6a577f82012-02-12 01:13:18 +0000487 dyn_cast_or_null<ConstantExpr>(ConstantFoldInstruction(GEP, TD, TLI));
Chris Lattner7b52fe72007-11-09 17:33:02 +0000488 if (Init && CE && CE->getOpcode() == Instruction::GetElementPtr)
Dan Gohmanc6f69e92009-10-05 16:36:26 +0000489 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
Benjamin Kramerc1ea16e2012-03-28 14:50:09 +0000490
491 // If the initializer is an all-null value and we have an inbounds GEP,
492 // we already know what the result of any load from that GEP is.
493 // TODO: Handle splats.
494 if (Init && isa<ConstantAggregateZero>(Init) && GEP->isInBounds())
495 SubInit = Constant::getNullValue(GEP->getType()->getElementType());
Chris Lattner7b52fe72007-11-09 17:33:02 +0000496 }
Nick Lewycky6a577f82012-02-12 01:13:18 +0000497 Changed |= CleanupConstantGlobalUsers(GEP, SubInit, TD, TLI);
Chris Lattnerc4d81b02004-10-10 16:47:33 +0000498
Chris Lattner031955d2004-10-10 16:43:46 +0000499 if (GEP->use_empty()) {
Chris Lattner7a7ed022004-10-16 18:09:00 +0000500 GEP->eraseFromParent();
Chris Lattner031955d2004-10-10 16:43:46 +0000501 Changed = true;
502 }
Chris Lattner35c81b02005-02-27 18:58:52 +0000503 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U)) { // memset/cpy/mv
504 if (MI->getRawDest() == V) {
505 MI->eraseFromParent();
506 Changed = true;
507 }
508
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000509 } else if (Constant *C = dyn_cast<Constant>(U)) {
510 // If we have a chain of dead constantexprs or other things dangling from
511 // us, and if they are all dead, nuke them without remorse.
Jay Foade3acf152009-06-09 21:37:11 +0000512 if (SafeToDestroyConstant(C)) {
Devang Patel743cdf82009-03-06 01:37:41 +0000513 C->destroyConstant();
Nick Lewycky6a577f82012-02-12 01:13:18 +0000514 CleanupConstantGlobalUsers(V, Init, TD, TLI);
Chris Lattner031955d2004-10-10 16:43:46 +0000515 return true;
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000516 }
Chris Lattnere47ba742004-10-06 20:57:02 +0000517 }
518 }
Chris Lattner031955d2004-10-10 16:43:46 +0000519 return Changed;
Chris Lattnere47ba742004-10-06 20:57:02 +0000520}
521
Chris Lattner941db492008-01-14 02:09:12 +0000522/// isSafeSROAElementUse - Return true if the specified instruction is a safe
523/// user of a derived expression from a global that we want to SROA.
524static bool isSafeSROAElementUse(Value *V) {
525 // We might have a dead and dangling constant hanging off of here.
526 if (Constant *C = dyn_cast<Constant>(V))
Jay Foade3acf152009-06-09 21:37:11 +0000527 return SafeToDestroyConstant(C);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000528
Chris Lattner941db492008-01-14 02:09:12 +0000529 Instruction *I = dyn_cast<Instruction>(V);
530 if (!I) return false;
531
532 // Loads are ok.
533 if (isa<LoadInst>(I)) return true;
534
535 // Stores *to* the pointer are ok.
536 if (StoreInst *SI = dyn_cast<StoreInst>(I))
537 return SI->getOperand(0) != V;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000538
Chris Lattner941db492008-01-14 02:09:12 +0000539 // Otherwise, it must be a GEP.
540 GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I);
541 if (GEPI == 0) return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000542
Chris Lattner941db492008-01-14 02:09:12 +0000543 if (GEPI->getNumOperands() < 3 || !isa<Constant>(GEPI->getOperand(1)) ||
544 !cast<Constant>(GEPI->getOperand(1))->isNullValue())
545 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000546
Chris Lattner941db492008-01-14 02:09:12 +0000547 for (Value::use_iterator I = GEPI->use_begin(), E = GEPI->use_end();
548 I != E; ++I)
549 if (!isSafeSROAElementUse(*I))
550 return false;
Chris Lattner727c2102008-01-14 01:31:05 +0000551 return true;
552}
553
Chris Lattner941db492008-01-14 02:09:12 +0000554
555/// IsUserOfGlobalSafeForSRA - U is a direct user of the specified global value.
556/// Look at it and its uses and decide whether it is safe to SROA this global.
557///
558static bool IsUserOfGlobalSafeForSRA(User *U, GlobalValue *GV) {
559 // The user of the global must be a GEP Inst or a ConstantExpr GEP.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000560 if (!isa<GetElementPtrInst>(U) &&
561 (!isa<ConstantExpr>(U) ||
Chris Lattner941db492008-01-14 02:09:12 +0000562 cast<ConstantExpr>(U)->getOpcode() != Instruction::GetElementPtr))
563 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000564
Chris Lattner941db492008-01-14 02:09:12 +0000565 // Check to see if this ConstantExpr GEP is SRA'able. In particular, we
566 // don't like < 3 operand CE's, and we don't like non-constant integer
567 // indices. This enforces that all uses are 'gep GV, 0, C, ...' for some
568 // value of C.
569 if (U->getNumOperands() < 3 || !isa<Constant>(U->getOperand(1)) ||
570 !cast<Constant>(U->getOperand(1))->isNullValue() ||
571 !isa<ConstantInt>(U->getOperand(2)))
572 return false;
573
574 gep_type_iterator GEPI = gep_type_begin(U), E = gep_type_end(U);
575 ++GEPI; // Skip over the pointer index.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000576
Chris Lattner941db492008-01-14 02:09:12 +0000577 // If this is a use of an array allocation, do a bit more checking for sanity.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000578 if (ArrayType *AT = dyn_cast<ArrayType>(*GEPI)) {
Chris Lattner941db492008-01-14 02:09:12 +0000579 uint64_t NumElements = AT->getNumElements();
580 ConstantInt *Idx = cast<ConstantInt>(U->getOperand(2));
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000581
Chris Lattner941db492008-01-14 02:09:12 +0000582 // Check to make sure that index falls within the array. If not,
583 // something funny is going on, so we won't do the optimization.
584 //
585 if (Idx->getZExtValue() >= NumElements)
586 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000587
Chris Lattner941db492008-01-14 02:09:12 +0000588 // We cannot scalar repl this level of the array unless any array
589 // sub-indices are in-range constants. In particular, consider:
590 // A[0][i]. We cannot know that the user isn't doing invalid things like
591 // allowing i to index an out-of-range subscript that accesses A[1].
592 //
593 // Scalar replacing *just* the outer index of the array is probably not
594 // going to be a win anyway, so just give up.
595 for (++GEPI; // Skip array index.
Dan Gohman6874a2a2009-08-18 14:58:19 +0000596 GEPI != E;
Chris Lattner941db492008-01-14 02:09:12 +0000597 ++GEPI) {
598 uint64_t NumElements;
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000599 if (ArrayType *SubArrayTy = dyn_cast<ArrayType>(*GEPI))
Chris Lattner941db492008-01-14 02:09:12 +0000600 NumElements = SubArrayTy->getNumElements();
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000601 else if (VectorType *SubVectorTy = dyn_cast<VectorType>(*GEPI))
Dan Gohman6874a2a2009-08-18 14:58:19 +0000602 NumElements = SubVectorTy->getNumElements();
603 else {
Duncan Sands1df98592010-02-16 11:11:14 +0000604 assert((*GEPI)->isStructTy() &&
Dan Gohman6874a2a2009-08-18 14:58:19 +0000605 "Indexed GEP type is not array, vector, or struct!");
606 continue;
607 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000608
Chris Lattner941db492008-01-14 02:09:12 +0000609 ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPI.getOperand());
610 if (!IdxVal || IdxVal->getZExtValue() >= NumElements)
611 return false;
612 }
613 }
614
615 for (Value::use_iterator I = U->use_begin(), E = U->use_end(); I != E; ++I)
616 if (!isSafeSROAElementUse(*I))
617 return false;
618 return true;
619}
620
621/// GlobalUsersSafeToSRA - Look at all uses of the global and decide whether it
622/// is safe for us to perform this transformation.
623///
624static bool GlobalUsersSafeToSRA(GlobalValue *GV) {
625 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end();
626 UI != E; ++UI) {
627 if (!IsUserOfGlobalSafeForSRA(*UI, GV))
628 return false;
629 }
630 return true;
631}
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000632
Chris Lattner941db492008-01-14 02:09:12 +0000633
Chris Lattner670c8892004-10-08 17:32:09 +0000634/// SRAGlobal - Perform scalar replacement of aggregates on the specified global
635/// variable. This opens the door for other optimizations by exposing the
636/// behavior of the program in a more fine-grained way. We have determined that
637/// this transformation is safe already. We return the first global variable we
638/// insert so that the caller can reprocess it.
Micah Villmow3574eca2012-10-08 16:38:25 +0000639static GlobalVariable *SRAGlobal(GlobalVariable *GV, const DataLayout &TD) {
Chris Lattner727c2102008-01-14 01:31:05 +0000640 // Make sure this global only has simple uses that we can SRA.
Chris Lattner941db492008-01-14 02:09:12 +0000641 if (!GlobalUsersSafeToSRA(GV))
Chris Lattner727c2102008-01-14 01:31:05 +0000642 return 0;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000643
Rafael Espindolabb46f522009-01-15 20:18:42 +0000644 assert(GV->hasLocalLinkage() && !GV->isConstant());
Chris Lattner670c8892004-10-08 17:32:09 +0000645 Constant *Init = GV->getInitializer();
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000646 Type *Ty = Init->getType();
Misha Brukmanfd939082005-04-21 23:48:37 +0000647
Chris Lattner670c8892004-10-08 17:32:09 +0000648 std::vector<GlobalVariable*> NewGlobals;
649 Module::GlobalListType &Globals = GV->getParent()->getGlobalList();
650
Chris Lattner998182b2008-04-26 07:40:11 +0000651 // Get the alignment of the global, either explicit or target-specific.
652 unsigned StartAlignment = GV->getAlignment();
653 if (StartAlignment == 0)
654 StartAlignment = TD.getABITypeAlignment(GV->getType());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000655
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000656 if (StructType *STy = dyn_cast<StructType>(Ty)) {
Chris Lattner670c8892004-10-08 17:32:09 +0000657 NewGlobals.reserve(STy->getNumElements());
Chris Lattner998182b2008-04-26 07:40:11 +0000658 const StructLayout &Layout = *TD.getStructLayout(STy);
Chris Lattner670c8892004-10-08 17:32:09 +0000659 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
Chris Lattnera1f00f42012-01-25 06:48:06 +0000660 Constant *In = Init->getAggregateElement(i);
Chris Lattner670c8892004-10-08 17:32:09 +0000661 assert(In && "Couldn't get element of initializer?");
Chris Lattner7b550cc2009-11-06 04:27:31 +0000662 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(i), false,
Chris Lattner670c8892004-10-08 17:32:09 +0000663 GlobalVariable::InternalLinkage,
Daniel Dunbarfe09b202009-07-30 17:37:43 +0000664 In, GV->getName()+"."+Twine(i),
Hans Wennborgce718ff2012-06-23 11:37:03 +0000665 GV->getThreadLocalMode(),
Owen Anderson3d29df32009-07-08 01:26:06 +0000666 GV->getType()->getAddressSpace());
Chris Lattner670c8892004-10-08 17:32:09 +0000667 Globals.insert(GV, NGV);
668 NewGlobals.push_back(NGV);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000669
Chris Lattner998182b2008-04-26 07:40:11 +0000670 // Calculate the known alignment of the field. If the original aggregate
671 // had 256 byte alignment for example, something might depend on that:
672 // propagate info to each field.
673 uint64_t FieldOffset = Layout.getElementOffset(i);
674 unsigned NewAlign = (unsigned)MinAlign(StartAlignment, FieldOffset);
675 if (NewAlign > TD.getABITypeAlignment(STy->getElementType(i)))
676 NGV->setAlignment(NewAlign);
Chris Lattner670c8892004-10-08 17:32:09 +0000677 }
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000678 } else if (SequentialType *STy = dyn_cast<SequentialType>(Ty)) {
Chris Lattner670c8892004-10-08 17:32:09 +0000679 unsigned NumElements = 0;
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000680 if (ArrayType *ATy = dyn_cast<ArrayType>(STy))
Chris Lattner670c8892004-10-08 17:32:09 +0000681 NumElements = ATy->getNumElements();
Chris Lattner670c8892004-10-08 17:32:09 +0000682 else
Chris Lattner998182b2008-04-26 07:40:11 +0000683 NumElements = cast<VectorType>(STy)->getNumElements();
Chris Lattner670c8892004-10-08 17:32:09 +0000684
Chris Lattner1f21ef12005-02-23 16:53:04 +0000685 if (NumElements > 16 && GV->hasNUsesOrMore(16))
Chris Lattnerd514d822005-02-01 01:23:31 +0000686 return 0; // It's not worth it.
Chris Lattner670c8892004-10-08 17:32:09 +0000687 NewGlobals.reserve(NumElements);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000688
Duncan Sands777d2302009-05-09 07:06:46 +0000689 uint64_t EltSize = TD.getTypeAllocSize(STy->getElementType());
Chris Lattner998182b2008-04-26 07:40:11 +0000690 unsigned EltAlign = TD.getABITypeAlignment(STy->getElementType());
Chris Lattner670c8892004-10-08 17:32:09 +0000691 for (unsigned i = 0, e = NumElements; i != e; ++i) {
Chris Lattnera1f00f42012-01-25 06:48:06 +0000692 Constant *In = Init->getAggregateElement(i);
Chris Lattner670c8892004-10-08 17:32:09 +0000693 assert(In && "Couldn't get element of initializer?");
694
Chris Lattner7b550cc2009-11-06 04:27:31 +0000695 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(), false,
Chris Lattner670c8892004-10-08 17:32:09 +0000696 GlobalVariable::InternalLinkage,
Daniel Dunbarfe09b202009-07-30 17:37:43 +0000697 In, GV->getName()+"."+Twine(i),
Hans Wennborgce718ff2012-06-23 11:37:03 +0000698 GV->getThreadLocalMode(),
Owen Andersone9b11b42009-07-08 19:03:57 +0000699 GV->getType()->getAddressSpace());
Chris Lattner670c8892004-10-08 17:32:09 +0000700 Globals.insert(GV, NGV);
701 NewGlobals.push_back(NGV);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000702
Chris Lattner998182b2008-04-26 07:40:11 +0000703 // Calculate the known alignment of the field. If the original aggregate
704 // had 256 byte alignment for example, something might depend on that:
705 // propagate info to each field.
706 unsigned NewAlign = (unsigned)MinAlign(StartAlignment, EltSize*i);
707 if (NewAlign > EltAlign)
708 NGV->setAlignment(NewAlign);
Chris Lattner670c8892004-10-08 17:32:09 +0000709 }
710 }
711
712 if (NewGlobals.empty())
713 return 0;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000714
David Greene3215b0e2010-01-05 01:28:05 +0000715 DEBUG(dbgs() << "PERFORMING GLOBAL SRA ON: " << *GV);
Chris Lattner30ba5692004-10-11 05:54:41 +0000716
Chris Lattner7b550cc2009-11-06 04:27:31 +0000717 Constant *NullInt =Constant::getNullValue(Type::getInt32Ty(GV->getContext()));
Chris Lattner670c8892004-10-08 17:32:09 +0000718
719 // Loop over all of the uses of the global, replacing the constantexpr geps,
720 // with smaller constantexpr geps or direct references.
721 while (!GV->use_empty()) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000722 User *GEP = GV->use_back();
723 assert(((isa<ConstantExpr>(GEP) &&
724 cast<ConstantExpr>(GEP)->getOpcode()==Instruction::GetElementPtr)||
725 isa<GetElementPtrInst>(GEP)) && "NonGEP CE's are not SRAable!");
Misha Brukmanfd939082005-04-21 23:48:37 +0000726
Chris Lattner670c8892004-10-08 17:32:09 +0000727 // Ignore the 1th operand, which has to be zero or else the program is quite
728 // broken (undefined). Get the 2nd operand, which is the structure or array
729 // index.
Reid Spencerb83eb642006-10-20 07:07:24 +0000730 unsigned Val = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
Chris Lattner670c8892004-10-08 17:32:09 +0000731 if (Val >= NewGlobals.size()) Val = 0; // Out of bound array access.
732
Chris Lattner30ba5692004-10-11 05:54:41 +0000733 Value *NewPtr = NewGlobals[Val];
Chris Lattner670c8892004-10-08 17:32:09 +0000734
735 // Form a shorter GEP if needed.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000736 if (GEP->getNumOperands() > 3) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000737 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEP)) {
Chris Lattner55eb1c42007-01-31 04:40:53 +0000738 SmallVector<Constant*, 8> Idxs;
Chris Lattner30ba5692004-10-11 05:54:41 +0000739 Idxs.push_back(NullInt);
740 for (unsigned i = 3, e = CE->getNumOperands(); i != e; ++i)
741 Idxs.push_back(CE->getOperand(i));
Jay Foaddab3d292011-07-21 14:31:17 +0000742 NewPtr = ConstantExpr::getGetElementPtr(cast<Constant>(NewPtr), Idxs);
Chris Lattner30ba5692004-10-11 05:54:41 +0000743 } else {
744 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(GEP);
Chris Lattner699d1442007-01-31 19:59:55 +0000745 SmallVector<Value*, 8> Idxs;
Chris Lattner30ba5692004-10-11 05:54:41 +0000746 Idxs.push_back(NullInt);
747 for (unsigned i = 3, e = GEPI->getNumOperands(); i != e; ++i)
748 Idxs.push_back(GEPI->getOperand(i));
Jay Foada9203102011-07-25 09:48:08 +0000749 NewPtr = GetElementPtrInst::Create(NewPtr, Idxs,
Daniel Dunbarfe09b202009-07-30 17:37:43 +0000750 GEPI->getName()+"."+Twine(Val),GEPI);
Chris Lattner30ba5692004-10-11 05:54:41 +0000751 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000752 }
Chris Lattner30ba5692004-10-11 05:54:41 +0000753 GEP->replaceAllUsesWith(NewPtr);
754
755 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(GEP))
Chris Lattner7a7ed022004-10-16 18:09:00 +0000756 GEPI->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +0000757 else
758 cast<ConstantExpr>(GEP)->destroyConstant();
Chris Lattner670c8892004-10-08 17:32:09 +0000759 }
760
Chris Lattnere40e2d12004-10-08 20:25:55 +0000761 // Delete the old global, now that it is dead.
762 Globals.erase(GV);
Chris Lattner670c8892004-10-08 17:32:09 +0000763 ++NumSRA;
Chris Lattner30ba5692004-10-11 05:54:41 +0000764
765 // Loop over the new globals array deleting any globals that are obviously
766 // dead. This can arise due to scalarization of a structure or an array that
767 // has elements that are dead.
768 unsigned FirstGlobal = 0;
769 for (unsigned i = 0, e = NewGlobals.size(); i != e; ++i)
770 if (NewGlobals[i]->use_empty()) {
771 Globals.erase(NewGlobals[i]);
772 if (FirstGlobal == i) ++FirstGlobal;
773 }
774
775 return FirstGlobal != NewGlobals.size() ? NewGlobals[FirstGlobal] : 0;
Chris Lattner670c8892004-10-08 17:32:09 +0000776}
777
Chris Lattner9b34a612004-10-09 21:48:45 +0000778/// AllUsesOfValueWillTrapIfNull - Return true if all users of the specified
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000779/// value will trap if the value is dynamically null. PHIs keeps track of any
Chris Lattner81686182007-09-13 16:30:19 +0000780/// phi nodes we've seen to avoid reprocessing them.
Gabor Greif6ce02b52010-04-06 19:24:18 +0000781static bool AllUsesOfValueWillTrapIfNull(const Value *V,
782 SmallPtrSet<const PHINode*, 8> &PHIs) {
783 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;
Gabor Greifa01d6db2010-04-06 19:14:05 +0000784 ++UI) {
Gabor Greif6ce02b52010-04-06 19:24:18 +0000785 const User *U = *UI;
Gabor Greifa01d6db2010-04-06 19:14:05 +0000786
787 if (isa<LoadInst>(U)) {
Chris Lattner9b34a612004-10-09 21:48:45 +0000788 // Will trap.
Gabor Greif6ce02b52010-04-06 19:24:18 +0000789 } else if (const StoreInst *SI = dyn_cast<StoreInst>(U)) {
Chris Lattner9b34a612004-10-09 21:48:45 +0000790 if (SI->getOperand(0) == V) {
Gabor Greifa01d6db2010-04-06 19:14:05 +0000791 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner9b34a612004-10-09 21:48:45 +0000792 return false; // Storing the value.
793 }
Gabor Greif6ce02b52010-04-06 19:24:18 +0000794 } else if (const CallInst *CI = dyn_cast<CallInst>(U)) {
Gabor Greif654c06f2010-03-20 21:00:25 +0000795 if (CI->getCalledValue() != V) {
Gabor Greifa01d6db2010-04-06 19:14:05 +0000796 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner9b34a612004-10-09 21:48:45 +0000797 return false; // Not calling the ptr
798 }
Gabor Greif6ce02b52010-04-06 19:24:18 +0000799 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(U)) {
Gabor Greif654c06f2010-03-20 21:00:25 +0000800 if (II->getCalledValue() != V) {
Gabor Greifa01d6db2010-04-06 19:14:05 +0000801 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner9b34a612004-10-09 21:48:45 +0000802 return false; // Not calling the ptr
803 }
Gabor Greif6ce02b52010-04-06 19:24:18 +0000804 } else if (const BitCastInst *CI = dyn_cast<BitCastInst>(U)) {
Chris Lattner81686182007-09-13 16:30:19 +0000805 if (!AllUsesOfValueWillTrapIfNull(CI, PHIs)) return false;
Gabor Greif6ce02b52010-04-06 19:24:18 +0000806 } else if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
Chris Lattner81686182007-09-13 16:30:19 +0000807 if (!AllUsesOfValueWillTrapIfNull(GEPI, PHIs)) return false;
Gabor Greif6ce02b52010-04-06 19:24:18 +0000808 } else if (const PHINode *PN = dyn_cast<PHINode>(U)) {
Chris Lattner81686182007-09-13 16:30:19 +0000809 // If we've already seen this phi node, ignore it, it has already been
810 // checked.
Jakob Stoklund Olesenb489d0f2010-01-29 23:54:14 +0000811 if (PHIs.insert(PN) && !AllUsesOfValueWillTrapIfNull(PN, PHIs))
812 return false;
Gabor Greifa01d6db2010-04-06 19:14:05 +0000813 } else if (isa<ICmpInst>(U) &&
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000814 isa<ConstantPointerNull>(UI->getOperand(1))) {
Nick Lewyckye7ee59b2010-02-25 06:39:10 +0000815 // Ignore icmp X, null
Chris Lattner9b34a612004-10-09 21:48:45 +0000816 } else {
Gabor Greifa01d6db2010-04-06 19:14:05 +0000817 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner9b34a612004-10-09 21:48:45 +0000818 return false;
819 }
Gabor Greifa01d6db2010-04-06 19:14:05 +0000820 }
Chris Lattner9b34a612004-10-09 21:48:45 +0000821 return true;
822}
823
824/// AllUsesOfLoadedValueWillTrapIfNull - Return true if all uses of any loads
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000825/// from GV will trap if the loaded value is null. Note that this also permits
826/// comparisons of the loaded value against null, as a special case.
Gabor Greif6ce02b52010-04-06 19:24:18 +0000827static bool AllUsesOfLoadedValueWillTrapIfNull(const GlobalVariable *GV) {
828 for (Value::const_use_iterator UI = GV->use_begin(), E = GV->use_end();
Gabor Greifa01d6db2010-04-06 19:14:05 +0000829 UI != E; ++UI) {
Gabor Greif6ce02b52010-04-06 19:24:18 +0000830 const User *U = *UI;
Gabor Greifa01d6db2010-04-06 19:14:05 +0000831
Gabor Greif6ce02b52010-04-06 19:24:18 +0000832 if (const LoadInst *LI = dyn_cast<LoadInst>(U)) {
833 SmallPtrSet<const PHINode*, 8> PHIs;
Chris Lattner81686182007-09-13 16:30:19 +0000834 if (!AllUsesOfValueWillTrapIfNull(LI, PHIs))
Chris Lattner9b34a612004-10-09 21:48:45 +0000835 return false;
Gabor Greifa01d6db2010-04-06 19:14:05 +0000836 } else if (isa<StoreInst>(U)) {
Chris Lattner9b34a612004-10-09 21:48:45 +0000837 // Ignore stores to the global.
838 } else {
839 // We don't know or understand this user, bail out.
Gabor Greifa01d6db2010-04-06 19:14:05 +0000840 //cerr << "UNKNOWN USER OF GLOBAL!: " << *U;
Chris Lattner9b34a612004-10-09 21:48:45 +0000841 return false;
842 }
Gabor Greifa01d6db2010-04-06 19:14:05 +0000843 }
Chris Lattner9b34a612004-10-09 21:48:45 +0000844 return true;
845}
846
Chris Lattner7b550cc2009-11-06 04:27:31 +0000847static bool OptimizeAwayTrappingUsesOfValue(Value *V, Constant *NewV) {
Chris Lattner708148e2004-10-10 23:14:11 +0000848 bool Changed = false;
849 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ) {
850 Instruction *I = cast<Instruction>(*UI++);
851 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
852 LI->setOperand(0, NewV);
853 Changed = true;
854 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
855 if (SI->getOperand(1) == V) {
856 SI->setOperand(1, NewV);
857 Changed = true;
858 }
859 } else if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
Gabor Greiffa1f5c22010-04-06 18:45:08 +0000860 CallSite CS(I);
861 if (CS.getCalledValue() == V) {
Chris Lattner708148e2004-10-10 23:14:11 +0000862 // Calling through the pointer! Turn into a direct call, but be careful
863 // that the pointer is not also being passed as an argument.
Gabor Greiffa1f5c22010-04-06 18:45:08 +0000864 CS.setCalledFunction(NewV);
Chris Lattner708148e2004-10-10 23:14:11 +0000865 Changed = true;
866 bool PassedAsArg = false;
Gabor Greiffa1f5c22010-04-06 18:45:08 +0000867 for (unsigned i = 0, e = CS.arg_size(); i != e; ++i)
868 if (CS.getArgument(i) == V) {
Chris Lattner708148e2004-10-10 23:14:11 +0000869 PassedAsArg = true;
Gabor Greiffa1f5c22010-04-06 18:45:08 +0000870 CS.setArgument(i, NewV);
Chris Lattner708148e2004-10-10 23:14:11 +0000871 }
872
873 if (PassedAsArg) {
874 // Being passed as an argument also. Be careful to not invalidate UI!
875 UI = V->use_begin();
876 }
877 }
878 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
879 Changed |= OptimizeAwayTrappingUsesOfValue(CI,
Owen Andersonbaf3c402009-07-29 18:55:55 +0000880 ConstantExpr::getCast(CI->getOpcode(),
Chris Lattner7b550cc2009-11-06 04:27:31 +0000881 NewV, CI->getType()));
Chris Lattner708148e2004-10-10 23:14:11 +0000882 if (CI->use_empty()) {
883 Changed = true;
Chris Lattner7a7ed022004-10-16 18:09:00 +0000884 CI->eraseFromParent();
Chris Lattner708148e2004-10-10 23:14:11 +0000885 }
886 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
887 // Should handle GEP here.
Chris Lattner55eb1c42007-01-31 04:40:53 +0000888 SmallVector<Constant*, 8> Idxs;
889 Idxs.reserve(GEPI->getNumOperands()-1);
Gabor Greif5e463212008-05-29 01:59:18 +0000890 for (User::op_iterator i = GEPI->op_begin() + 1, e = GEPI->op_end();
891 i != e; ++i)
892 if (Constant *C = dyn_cast<Constant>(*i))
Chris Lattner55eb1c42007-01-31 04:40:53 +0000893 Idxs.push_back(C);
Chris Lattner708148e2004-10-10 23:14:11 +0000894 else
895 break;
Chris Lattner55eb1c42007-01-31 04:40:53 +0000896 if (Idxs.size() == GEPI->getNumOperands()-1)
Chris Lattner708148e2004-10-10 23:14:11 +0000897 Changed |= OptimizeAwayTrappingUsesOfValue(GEPI,
Jay Foaddab3d292011-07-21 14:31:17 +0000898 ConstantExpr::getGetElementPtr(NewV, Idxs));
Chris Lattner708148e2004-10-10 23:14:11 +0000899 if (GEPI->use_empty()) {
900 Changed = true;
Chris Lattner7a7ed022004-10-16 18:09:00 +0000901 GEPI->eraseFromParent();
Chris Lattner708148e2004-10-10 23:14:11 +0000902 }
903 }
904 }
905
906 return Changed;
907}
908
909
910/// OptimizeAwayTrappingUsesOfLoads - The specified global has only one non-null
911/// value stored into it. If there are uses of the loaded value that would trap
912/// if the loaded value is dynamically null, then we know that they cannot be
913/// reachable with a null optimize away the load.
Nick Lewycky6a577f82012-02-12 01:13:18 +0000914static bool OptimizeAwayTrappingUsesOfLoads(GlobalVariable *GV, Constant *LV,
Micah Villmow3574eca2012-10-08 16:38:25 +0000915 DataLayout *TD,
Nick Lewycky6a577f82012-02-12 01:13:18 +0000916 TargetLibraryInfo *TLI) {
Chris Lattner708148e2004-10-10 23:14:11 +0000917 bool Changed = false;
918
Chris Lattner92c6bd22009-01-14 00:12:58 +0000919 // Keep track of whether we are able to remove all the uses of the global
920 // other than the store that defines it.
921 bool AllNonStoreUsesGone = true;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000922
Chris Lattner708148e2004-10-10 23:14:11 +0000923 // Replace all uses of loads with uses of uses of the stored value.
Chris Lattner92c6bd22009-01-14 00:12:58 +0000924 for (Value::use_iterator GUI = GV->use_begin(), E = GV->use_end(); GUI != E;){
925 User *GlobalUser = *GUI++;
926 if (LoadInst *LI = dyn_cast<LoadInst>(GlobalUser)) {
Chris Lattner7b550cc2009-11-06 04:27:31 +0000927 Changed |= OptimizeAwayTrappingUsesOfValue(LI, LV);
Chris Lattner92c6bd22009-01-14 00:12:58 +0000928 // If we were able to delete all uses of the loads
929 if (LI->use_empty()) {
930 LI->eraseFromParent();
931 Changed = true;
932 } else {
933 AllNonStoreUsesGone = false;
934 }
935 } else if (isa<StoreInst>(GlobalUser)) {
936 // Ignore the store that stores "LV" to the global.
937 assert(GlobalUser->getOperand(1) == GV &&
938 "Must be storing *to* the global");
Chris Lattner708148e2004-10-10 23:14:11 +0000939 } else {
Chris Lattner92c6bd22009-01-14 00:12:58 +0000940 AllNonStoreUsesGone = false;
941
942 // If we get here we could have other crazy uses that are transitively
943 // loaded.
944 assert((isa<PHINode>(GlobalUser) || isa<SelectInst>(GlobalUser) ||
Benjamin Kramerab164232012-09-28 10:01:27 +0000945 isa<ConstantExpr>(GlobalUser) || isa<CmpInst>(GlobalUser) ||
946 isa<BitCastInst>(GlobalUser) ||
947 isa<GetElementPtrInst>(GlobalUser)) &&
Chris Lattner98a42b22011-05-22 07:15:13 +0000948 "Only expect load and stores!");
Chris Lattner708148e2004-10-10 23:14:11 +0000949 }
Chris Lattner92c6bd22009-01-14 00:12:58 +0000950 }
Chris Lattner708148e2004-10-10 23:14:11 +0000951
952 if (Changed) {
David Greene3215b0e2010-01-05 01:28:05 +0000953 DEBUG(dbgs() << "OPTIMIZED LOADS FROM STORED ONCE POINTER: " << *GV);
Chris Lattner708148e2004-10-10 23:14:11 +0000954 ++NumGlobUses;
955 }
956
Chris Lattner708148e2004-10-10 23:14:11 +0000957 // If we nuked all of the loads, then none of the stores are needed either,
958 // nor is the global.
Chris Lattner92c6bd22009-01-14 00:12:58 +0000959 if (AllNonStoreUsesGone) {
Nick Lewycky8899d5c2012-07-24 07:21:08 +0000960 if (isLeakCheckerRoot(GV)) {
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000961 Changed |= CleanupPointerRootUsers(GV, TLI);
Nick Lewycky8899d5c2012-07-24 07:21:08 +0000962 } else {
963 Changed = true;
964 CleanupConstantGlobalUsers(GV, 0, TD, TLI);
965 }
Chris Lattner708148e2004-10-10 23:14:11 +0000966 if (GV->use_empty()) {
Nick Lewycky8899d5c2012-07-24 07:21:08 +0000967 DEBUG(dbgs() << " *** GLOBAL NOW DEAD!\n");
968 Changed = true;
Chris Lattner7a7ed022004-10-16 18:09:00 +0000969 GV->eraseFromParent();
Chris Lattner708148e2004-10-10 23:14:11 +0000970 ++NumDeleted;
971 }
Chris Lattner708148e2004-10-10 23:14:11 +0000972 }
973 return Changed;
974}
975
Chris Lattner30ba5692004-10-11 05:54:41 +0000976/// ConstantPropUsersOf - Walk the use list of V, constant folding all of the
977/// instructions that are foldable.
Nick Lewycky6a577f82012-02-12 01:13:18 +0000978static void ConstantPropUsersOf(Value *V,
Micah Villmow3574eca2012-10-08 16:38:25 +0000979 DataLayout *TD, TargetLibraryInfo *TLI) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000980 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; )
981 if (Instruction *I = dyn_cast<Instruction>(*UI++))
Nick Lewycky6a577f82012-02-12 01:13:18 +0000982 if (Constant *NewC = ConstantFoldInstruction(I, TD, TLI)) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000983 I->replaceAllUsesWith(NewC);
984
Chris Lattnerd514d822005-02-01 01:23:31 +0000985 // Advance UI to the next non-I use to avoid invalidating it!
986 // Instructions could multiply use V.
987 while (UI != E && *UI == I)
Chris Lattner30ba5692004-10-11 05:54:41 +0000988 ++UI;
Chris Lattnerd514d822005-02-01 01:23:31 +0000989 I->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +0000990 }
991}
992
993/// OptimizeGlobalAddressOfMalloc - This function takes the specified global
994/// variable, and transforms the program as if it always contained the result of
995/// the specified malloc. Because it is always the result of the specified
996/// malloc, there is no reason to actually DO the malloc. Instead, turn the
Chris Lattner6e8fbad2006-11-30 17:32:29 +0000997/// malloc into a global, and any loads of GV as uses of the new global.
Chris Lattner30ba5692004-10-11 05:54:41 +0000998static GlobalVariable *OptimizeGlobalAddressOfMalloc(GlobalVariable *GV,
Victor Hernandez83d63912009-09-18 22:35:49 +0000999 CallInst *CI,
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001000 Type *AllocTy,
Chris Lattnera6874652010-02-25 22:33:52 +00001001 ConstantInt *NElements,
Micah Villmow3574eca2012-10-08 16:38:25 +00001002 DataLayout *TD,
Nick Lewycky6a577f82012-02-12 01:13:18 +00001003 TargetLibraryInfo *TLI) {
Chris Lattnera6874652010-02-25 22:33:52 +00001004 DEBUG(errs() << "PROMOTING GLOBAL: " << *GV << " CALL = " << *CI << '\n');
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001005
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001006 Type *GlobalType;
Chris Lattnera6874652010-02-25 22:33:52 +00001007 if (NElements->getZExtValue() == 1)
1008 GlobalType = AllocTy;
1009 else
1010 // If we have an array allocation, the global variable is of an array.
1011 GlobalType = ArrayType::get(AllocTy, NElements->getZExtValue());
Victor Hernandez83d63912009-09-18 22:35:49 +00001012
1013 // Create the new global variable. The contents of the malloc'd memory is
1014 // undefined, so initialize with an undef value.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001015 GlobalVariable *NewGV = new GlobalVariable(*GV->getParent(),
Chris Lattnere9fd4442010-02-26 23:42:13 +00001016 GlobalType, false,
Chris Lattnera6874652010-02-25 22:33:52 +00001017 GlobalValue::InternalLinkage,
Chris Lattnere9fd4442010-02-26 23:42:13 +00001018 UndefValue::get(GlobalType),
Victor Hernandez83d63912009-09-18 22:35:49 +00001019 GV->getName()+".body",
1020 GV,
Hans Wennborgce718ff2012-06-23 11:37:03 +00001021 GV->getThreadLocalMode());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001022
Chris Lattnera6874652010-02-25 22:33:52 +00001023 // If there are bitcast users of the malloc (which is typical, usually we have
1024 // a malloc + bitcast) then replace them with uses of the new global. Update
1025 // other users to use the global as well.
1026 BitCastInst *TheBC = 0;
1027 while (!CI->use_empty()) {
1028 Instruction *User = cast<Instruction>(CI->use_back());
1029 if (BitCastInst *BCI = dyn_cast<BitCastInst>(User)) {
1030 if (BCI->getType() == NewGV->getType()) {
1031 BCI->replaceAllUsesWith(NewGV);
1032 BCI->eraseFromParent();
1033 } else {
1034 BCI->setOperand(0, NewGV);
1035 }
1036 } else {
1037 if (TheBC == 0)
1038 TheBC = new BitCastInst(NewGV, CI->getType(), "newgv", CI);
1039 User->replaceUsesOfWith(CI, TheBC);
1040 }
1041 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001042
Victor Hernandez83d63912009-09-18 22:35:49 +00001043 Constant *RepValue = NewGV;
1044 if (NewGV->getType() != GV->getType()->getElementType())
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001045 RepValue = ConstantExpr::getBitCast(RepValue,
Victor Hernandez83d63912009-09-18 22:35:49 +00001046 GV->getType()->getElementType());
1047
1048 // If there is a comparison against null, we will insert a global bool to
1049 // keep track of whether the global was initialized yet or not.
1050 GlobalVariable *InitBool =
Chris Lattner7b550cc2009-11-06 04:27:31 +00001051 new GlobalVariable(Type::getInt1Ty(GV->getContext()), false,
Victor Hernandez83d63912009-09-18 22:35:49 +00001052 GlobalValue::InternalLinkage,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001053 ConstantInt::getFalse(GV->getContext()),
Hans Wennborgce718ff2012-06-23 11:37:03 +00001054 GV->getName()+".init", GV->getThreadLocalMode());
Victor Hernandez83d63912009-09-18 22:35:49 +00001055 bool InitBoolUsed = false;
1056
1057 // Loop over all uses of GV, processing them in turn.
Chris Lattnera6874652010-02-25 22:33:52 +00001058 while (!GV->use_empty()) {
1059 if (StoreInst *SI = dyn_cast<StoreInst>(GV->use_back())) {
Victor Hernandez83d63912009-09-18 22:35:49 +00001060 // The global is initialized when the store to it occurs.
Nick Lewyckyfad4d402012-02-05 19:56:38 +00001061 new StoreInst(ConstantInt::getTrue(GV->getContext()), InitBool, false, 0,
1062 SI->getOrdering(), SI->getSynchScope(), SI);
Victor Hernandez83d63912009-09-18 22:35:49 +00001063 SI->eraseFromParent();
Chris Lattnera6874652010-02-25 22:33:52 +00001064 continue;
Victor Hernandez83d63912009-09-18 22:35:49 +00001065 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001066
Chris Lattnera6874652010-02-25 22:33:52 +00001067 LoadInst *LI = cast<LoadInst>(GV->use_back());
1068 while (!LI->use_empty()) {
1069 Use &LoadUse = LI->use_begin().getUse();
1070 if (!isa<ICmpInst>(LoadUse.getUser())) {
1071 LoadUse = RepValue;
1072 continue;
1073 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001074
Chris Lattnera6874652010-02-25 22:33:52 +00001075 ICmpInst *ICI = cast<ICmpInst>(LoadUse.getUser());
1076 // Replace the cmp X, 0 with a use of the bool value.
Nick Lewyckyfad4d402012-02-05 19:56:38 +00001077 // Sink the load to where the compare was, if atomic rules allow us to.
1078 Value *LV = new LoadInst(InitBool, InitBool->getName()+".val", false, 0,
1079 LI->getOrdering(), LI->getSynchScope(),
1080 LI->isUnordered() ? (Instruction*)ICI : LI);
Chris Lattnera6874652010-02-25 22:33:52 +00001081 InitBoolUsed = true;
1082 switch (ICI->getPredicate()) {
1083 default: llvm_unreachable("Unknown ICmp Predicate!");
1084 case ICmpInst::ICMP_ULT:
1085 case ICmpInst::ICMP_SLT: // X < null -> always false
1086 LV = ConstantInt::getFalse(GV->getContext());
1087 break;
1088 case ICmpInst::ICMP_ULE:
1089 case ICmpInst::ICMP_SLE:
1090 case ICmpInst::ICMP_EQ:
1091 LV = BinaryOperator::CreateNot(LV, "notinit", ICI);
1092 break;
1093 case ICmpInst::ICMP_NE:
1094 case ICmpInst::ICMP_UGE:
1095 case ICmpInst::ICMP_SGE:
1096 case ICmpInst::ICMP_UGT:
1097 case ICmpInst::ICMP_SGT:
1098 break; // no change.
1099 }
1100 ICI->replaceAllUsesWith(LV);
1101 ICI->eraseFromParent();
1102 }
1103 LI->eraseFromParent();
1104 }
Victor Hernandez83d63912009-09-18 22:35:49 +00001105
1106 // If the initialization boolean was used, insert it, otherwise delete it.
1107 if (!InitBoolUsed) {
1108 while (!InitBool->use_empty()) // Delete initializations
Chris Lattnera6874652010-02-25 22:33:52 +00001109 cast<StoreInst>(InitBool->use_back())->eraseFromParent();
Victor Hernandez83d63912009-09-18 22:35:49 +00001110 delete InitBool;
1111 } else
1112 GV->getParent()->getGlobalList().insert(GV, InitBool);
1113
Chris Lattnera6874652010-02-25 22:33:52 +00001114 // Now the GV is dead, nuke it and the malloc..
Victor Hernandez83d63912009-09-18 22:35:49 +00001115 GV->eraseFromParent();
Victor Hernandez83d63912009-09-18 22:35:49 +00001116 CI->eraseFromParent();
1117
1118 // To further other optimizations, loop over all users of NewGV and try to
1119 // constant prop them. This will promote GEP instructions with constant
1120 // indices into GEP constant-exprs, which will allow global-opt to hack on it.
Nick Lewycky6a577f82012-02-12 01:13:18 +00001121 ConstantPropUsersOf(NewGV, TD, TLI);
Victor Hernandez83d63912009-09-18 22:35:49 +00001122 if (RepValue != NewGV)
Nick Lewycky6a577f82012-02-12 01:13:18 +00001123 ConstantPropUsersOf(RepValue, TD, TLI);
Victor Hernandez83d63912009-09-18 22:35:49 +00001124
1125 return NewGV;
1126}
1127
Chris Lattnerfa07e4f2004-12-02 07:11:07 +00001128/// ValueIsOnlyUsedLocallyOrStoredToOneGlobal - Scan the use-list of V checking
1129/// to make sure that there are no complex uses of V. We permit simple things
1130/// like dereferencing the pointer, but not storing through the address, unless
1131/// it is to the specified global.
Gabor Greif0b520db2010-04-06 18:58:22 +00001132static bool ValueIsOnlyUsedLocallyOrStoredToOneGlobal(const Instruction *V,
1133 const GlobalVariable *GV,
Gabor Greifa01d6db2010-04-06 19:14:05 +00001134 SmallPtrSet<const PHINode*, 8> &PHIs) {
Gabor Greif0b520db2010-04-06 18:58:22 +00001135 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end();
Gabor Greifa01d6db2010-04-06 19:14:05 +00001136 UI != E; ++UI) {
Gabor Greif0b520db2010-04-06 18:58:22 +00001137 const Instruction *Inst = cast<Instruction>(*UI);
Gabor Greifa01d6db2010-04-06 19:14:05 +00001138
Chris Lattner49b6d4a2008-12-15 21:08:54 +00001139 if (isa<LoadInst>(Inst) || isa<CmpInst>(Inst)) {
1140 continue; // Fine, ignore.
1141 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001142
Gabor Greif0b520db2010-04-06 18:58:22 +00001143 if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
Chris Lattnerfa07e4f2004-12-02 07:11:07 +00001144 if (SI->getOperand(0) == V && SI->getOperand(1) != GV)
1145 return false; // Storing the pointer itself... bad.
Chris Lattner49b6d4a2008-12-15 21:08:54 +00001146 continue; // Otherwise, storing through it, or storing into GV... fine.
1147 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001148
Chris Lattnera2fb2342010-04-10 18:19:22 +00001149 // Must index into the array and into the struct.
1150 if (isa<GetElementPtrInst>(Inst) && Inst->getNumOperands() >= 3) {
Chris Lattner49b6d4a2008-12-15 21:08:54 +00001151 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(Inst, GV, PHIs))
Chris Lattnerfa07e4f2004-12-02 07:11:07 +00001152 return false;
Chris Lattner49b6d4a2008-12-15 21:08:54 +00001153 continue;
1154 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001155
Gabor Greif0b520db2010-04-06 18:58:22 +00001156 if (const PHINode *PN = dyn_cast<PHINode>(Inst)) {
Chris Lattnerc451f9c2007-09-13 16:37:20 +00001157 // PHIs are ok if all uses are ok. Don't infinitely recurse through PHI
1158 // cycles.
1159 if (PHIs.insert(PN))
Chris Lattner5e6e4942007-09-14 03:41:21 +00001160 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(PN, GV, PHIs))
1161 return false;
Chris Lattner49b6d4a2008-12-15 21:08:54 +00001162 continue;
Chris Lattnerfa07e4f2004-12-02 07:11:07 +00001163 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001164
Gabor Greif0b520db2010-04-06 18:58:22 +00001165 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Inst)) {
Chris Lattner49b6d4a2008-12-15 21:08:54 +00001166 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(BCI, GV, PHIs))
1167 return false;
1168 continue;
1169 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001170
Chris Lattner49b6d4a2008-12-15 21:08:54 +00001171 return false;
1172 }
Chris Lattnerfa07e4f2004-12-02 07:11:07 +00001173 return true;
Chris Lattnerfa07e4f2004-12-02 07:11:07 +00001174}
1175
Chris Lattner86395032006-09-30 23:32:09 +00001176/// ReplaceUsesOfMallocWithGlobal - The Alloc pointer is stored into GV
1177/// somewhere. Transform all uses of the allocation into loads from the
1178/// global and uses of the resultant pointer. Further, delete the store into
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001179/// GV. This assumes that these value pass the
Chris Lattner86395032006-09-30 23:32:09 +00001180/// 'ValueIsOnlyUsedLocallyOrStoredToOneGlobal' predicate.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001181static void ReplaceUsesOfMallocWithGlobal(Instruction *Alloc,
Chris Lattner86395032006-09-30 23:32:09 +00001182 GlobalVariable *GV) {
1183 while (!Alloc->use_empty()) {
Chris Lattnera637a8b2007-09-13 18:00:31 +00001184 Instruction *U = cast<Instruction>(*Alloc->use_begin());
1185 Instruction *InsertPt = U;
Chris Lattner86395032006-09-30 23:32:09 +00001186 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
1187 // If this is the store of the allocation into the global, remove it.
1188 if (SI->getOperand(1) == GV) {
1189 SI->eraseFromParent();
1190 continue;
1191 }
Chris Lattnera637a8b2007-09-13 18:00:31 +00001192 } else if (PHINode *PN = dyn_cast<PHINode>(U)) {
1193 // Insert the load in the corresponding predecessor, not right before the
1194 // PHI.
Gabor Greifa36791d2009-01-23 19:40:15 +00001195 InsertPt = PN->getIncomingBlock(Alloc->use_begin())->getTerminator();
Chris Lattner101f44e2008-12-15 21:44:34 +00001196 } else if (isa<BitCastInst>(U)) {
1197 // Must be bitcast between the malloc and store to initialize the global.
1198 ReplaceUsesOfMallocWithGlobal(U, GV);
1199 U->eraseFromParent();
1200 continue;
1201 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
1202 // If this is a "GEP bitcast" and the user is a store to the global, then
1203 // just process it as a bitcast.
1204 if (GEPI->hasAllZeroIndices() && GEPI->hasOneUse())
1205 if (StoreInst *SI = dyn_cast<StoreInst>(GEPI->use_back()))
1206 if (SI->getOperand(1) == GV) {
1207 // Must be bitcast GEP between the malloc and store to initialize
1208 // the global.
1209 ReplaceUsesOfMallocWithGlobal(GEPI, GV);
1210 GEPI->eraseFromParent();
1211 continue;
1212 }
Chris Lattner86395032006-09-30 23:32:09 +00001213 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001214
Chris Lattner86395032006-09-30 23:32:09 +00001215 // Insert a load from the global, and use it instead of the malloc.
Chris Lattnera637a8b2007-09-13 18:00:31 +00001216 Value *NL = new LoadInst(GV, GV->getName()+".val", InsertPt);
Chris Lattner86395032006-09-30 23:32:09 +00001217 U->replaceUsesOfWith(Alloc, NL);
1218 }
1219}
1220
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001221/// LoadUsesSimpleEnoughForHeapSRA - Verify that all uses of V (a load, or a phi
1222/// of a load) are simple enough to perform heap SRA on. This permits GEP's
1223/// that index through the array and struct field, icmps of null, and PHIs.
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001224static bool LoadUsesSimpleEnoughForHeapSRA(const Value *V,
Gabor Greif27236912010-04-07 18:59:26 +00001225 SmallPtrSet<const PHINode*, 32> &LoadUsingPHIs,
1226 SmallPtrSet<const PHINode*, 32> &LoadUsingPHIsPerLoad) {
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001227 // We permit two users of the load: setcc comparing against the null
1228 // pointer, and a getelementptr of a specific form.
Gabor Greif27236912010-04-07 18:59:26 +00001229 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;
1230 ++UI) {
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001231 const Instruction *User = cast<Instruction>(*UI);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001232
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001233 // Comparison against null is ok.
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001234 if (const ICmpInst *ICI = dyn_cast<ICmpInst>(User)) {
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001235 if (!isa<ConstantPointerNull>(ICI->getOperand(1)))
1236 return false;
1237 continue;
1238 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001239
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001240 // getelementptr is also ok, but only a simple form.
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001241 if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001242 // Must index into the array and into the struct.
1243 if (GEPI->getNumOperands() < 3)
1244 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001245
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001246 // Otherwise the GEP is ok.
1247 continue;
1248 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001249
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001250 if (const PHINode *PN = dyn_cast<PHINode>(User)) {
Evan Cheng5d163962009-06-02 00:56:07 +00001251 if (!LoadUsingPHIsPerLoad.insert(PN))
1252 // This means some phi nodes are dependent on each other.
1253 // Avoid infinite looping!
1254 return false;
1255 if (!LoadUsingPHIs.insert(PN))
1256 // If we have already analyzed this PHI, then it is safe.
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001257 continue;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001258
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001259 // Make sure all uses of the PHI are simple enough to transform.
Evan Cheng5d163962009-06-02 00:56:07 +00001260 if (!LoadUsesSimpleEnoughForHeapSRA(PN,
1261 LoadUsingPHIs, LoadUsingPHIsPerLoad))
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001262 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001263
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001264 continue;
Chris Lattner86395032006-09-30 23:32:09 +00001265 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001266
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001267 // Otherwise we don't know what this is, not ok.
1268 return false;
1269 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001270
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001271 return true;
1272}
1273
1274
1275/// AllGlobalLoadUsesSimpleEnoughForHeapSRA - If all users of values loaded from
1276/// GV are simple enough to perform HeapSRA, return true.
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001277static bool AllGlobalLoadUsesSimpleEnoughForHeapSRA(const GlobalVariable *GV,
Victor Hernandez83d63912009-09-18 22:35:49 +00001278 Instruction *StoredVal) {
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001279 SmallPtrSet<const PHINode*, 32> LoadUsingPHIs;
1280 SmallPtrSet<const PHINode*, 32> LoadUsingPHIsPerLoad;
Gabor Greif27236912010-04-07 18:59:26 +00001281 for (Value::const_use_iterator UI = GV->use_begin(), E = GV->use_end();
1282 UI != E; ++UI)
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001283 if (const LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
Evan Cheng5d163962009-06-02 00:56:07 +00001284 if (!LoadUsesSimpleEnoughForHeapSRA(LI, LoadUsingPHIs,
1285 LoadUsingPHIsPerLoad))
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001286 return false;
Evan Cheng5d163962009-06-02 00:56:07 +00001287 LoadUsingPHIsPerLoad.clear();
1288 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001289
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001290 // If we reach here, we know that all uses of the loads and transitive uses
1291 // (through PHI nodes) are simple enough to transform. However, we don't know
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001292 // that all inputs the to the PHI nodes are in the same equivalence sets.
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001293 // Check to verify that all operands of the PHIs are either PHIS that can be
1294 // transformed, loads from GV, or MI itself.
Gabor Greif27236912010-04-07 18:59:26 +00001295 for (SmallPtrSet<const PHINode*, 32>::const_iterator I = LoadUsingPHIs.begin()
1296 , E = LoadUsingPHIs.end(); I != E; ++I) {
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001297 const PHINode *PN = *I;
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001298 for (unsigned op = 0, e = PN->getNumIncomingValues(); op != e; ++op) {
1299 Value *InVal = PN->getIncomingValue(op);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001300
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001301 // PHI of the stored value itself is ok.
Victor Hernandez83d63912009-09-18 22:35:49 +00001302 if (InVal == StoredVal) continue;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001303
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001304 if (const PHINode *InPN = dyn_cast<PHINode>(InVal)) {
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001305 // One of the PHIs in our set is (optimistically) ok.
1306 if (LoadUsingPHIs.count(InPN))
1307 continue;
1308 return false;
1309 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001310
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001311 // Load from GV is ok.
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001312 if (const LoadInst *LI = dyn_cast<LoadInst>(InVal))
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001313 if (LI->getOperand(0) == GV)
1314 continue;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001315
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001316 // UNDEF? NULL?
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001317
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001318 // Anything else is rejected.
1319 return false;
1320 }
1321 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001322
Chris Lattner86395032006-09-30 23:32:09 +00001323 return true;
1324}
1325
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001326static Value *GetHeapSROAValue(Value *V, unsigned FieldNo,
1327 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001328 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001329 std::vector<Value*> &FieldVals = InsertedScalarizedValues[V];
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001330
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001331 if (FieldNo >= FieldVals.size())
1332 FieldVals.resize(FieldNo+1);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001333
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001334 // If we already have this value, just reuse the previously scalarized
1335 // version.
1336 if (Value *FieldVal = FieldVals[FieldNo])
1337 return FieldVal;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001338
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001339 // Depending on what instruction this is, we have several cases.
1340 Value *Result;
1341 if (LoadInst *LI = dyn_cast<LoadInst>(V)) {
1342 // This is a scalarized version of the load from the global. Just create
1343 // a new Load of the scalarized global.
1344 Result = new LoadInst(GetHeapSROAValue(LI->getOperand(0), FieldNo,
1345 InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001346 PHIsToRewrite),
Daniel Dunbarfe09b202009-07-30 17:37:43 +00001347 LI->getName()+".f"+Twine(FieldNo), LI);
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001348 } else if (PHINode *PN = dyn_cast<PHINode>(V)) {
1349 // PN's type is pointer to struct. Make a new PHI of pointer to struct
1350 // field.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001351 StructType *ST =
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001352 cast<StructType>(cast<PointerType>(PN->getType())->getElementType());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001353
Jay Foadd8b4fb42011-03-30 11:19:20 +00001354 PHINode *NewPN =
Owen Andersondebcb012009-07-29 22:17:13 +00001355 PHINode::Create(PointerType::getUnqual(ST->getElementType(FieldNo)),
Jay Foad3ecfc862011-03-30 11:28:46 +00001356 PN->getNumIncomingValues(),
Daniel Dunbarfe09b202009-07-30 17:37:43 +00001357 PN->getName()+".f"+Twine(FieldNo), PN);
Jay Foadd8b4fb42011-03-30 11:19:20 +00001358 Result = NewPN;
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001359 PHIsToRewrite.push_back(std::make_pair(PN, FieldNo));
1360 } else {
Torok Edwinc23197a2009-07-14 16:55:14 +00001361 llvm_unreachable("Unknown usable value");
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001362 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001363
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001364 return FieldVals[FieldNo] = Result;
Chris Lattnera637a8b2007-09-13 18:00:31 +00001365}
1366
Chris Lattner330245e2007-09-13 17:29:05 +00001367/// RewriteHeapSROALoadUser - Given a load instruction and a value derived from
1368/// the load, rewrite the derived value to use the HeapSRoA'd load.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001369static void RewriteHeapSROALoadUser(Instruction *LoadUser,
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001370 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001371 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
Chris Lattner330245e2007-09-13 17:29:05 +00001372 // If this is a comparison against null, handle it.
1373 if (ICmpInst *SCI = dyn_cast<ICmpInst>(LoadUser)) {
1374 assert(isa<ConstantPointerNull>(SCI->getOperand(1)));
1375 // If we have a setcc of the loaded pointer, we can use a setcc of any
1376 // field.
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001377 Value *NPtr = GetHeapSROAValue(SCI->getOperand(0), 0,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001378 InsertedScalarizedValues, PHIsToRewrite);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001379
Owen Anderson333c4002009-07-09 23:48:35 +00001380 Value *New = new ICmpInst(SCI, SCI->getPredicate(), NPtr,
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001381 Constant::getNullValue(NPtr->getType()),
Owen Anderson333c4002009-07-09 23:48:35 +00001382 SCI->getName());
Chris Lattner330245e2007-09-13 17:29:05 +00001383 SCI->replaceAllUsesWith(New);
1384 SCI->eraseFromParent();
1385 return;
1386 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001387
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001388 // Handle 'getelementptr Ptr, Idx, i32 FieldNo ...'
Chris Lattnera637a8b2007-09-13 18:00:31 +00001389 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(LoadUser)) {
1390 assert(GEPI->getNumOperands() >= 3 && isa<ConstantInt>(GEPI->getOperand(2))
1391 && "Unexpected GEPI!");
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001392
Chris Lattnera637a8b2007-09-13 18:00:31 +00001393 // Load the pointer for this field.
1394 unsigned FieldNo = cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue();
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001395 Value *NewPtr = GetHeapSROAValue(GEPI->getOperand(0), FieldNo,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001396 InsertedScalarizedValues, PHIsToRewrite);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001397
Chris Lattnera637a8b2007-09-13 18:00:31 +00001398 // Create the new GEP idx vector.
1399 SmallVector<Value*, 8> GEPIdx;
1400 GEPIdx.push_back(GEPI->getOperand(1));
1401 GEPIdx.append(GEPI->op_begin()+3, GEPI->op_end());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001402
Jay Foada9203102011-07-25 09:48:08 +00001403 Value *NGEPI = GetElementPtrInst::Create(NewPtr, GEPIdx,
Gabor Greif051a9502008-04-06 20:25:17 +00001404 GEPI->getName(), GEPI);
Chris Lattnera637a8b2007-09-13 18:00:31 +00001405 GEPI->replaceAllUsesWith(NGEPI);
1406 GEPI->eraseFromParent();
1407 return;
1408 }
Chris Lattner309f20f2007-09-13 21:31:36 +00001409
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001410 // Recursively transform the users of PHI nodes. This will lazily create the
1411 // PHIs that are needed for individual elements. Keep track of what PHIs we
1412 // see in InsertedScalarizedValues so that we don't get infinite loops (very
1413 // antisocial). If the PHI is already in InsertedScalarizedValues, it has
1414 // already been seen first by another load, so its uses have already been
1415 // processed.
1416 PHINode *PN = cast<PHINode>(LoadUser);
Chris Lattnerc30a38f2011-07-21 06:21:31 +00001417 if (!InsertedScalarizedValues.insert(std::make_pair(PN,
1418 std::vector<Value*>())).second)
1419 return;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001420
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001421 // If this is the first time we've seen this PHI, recursively process all
1422 // users.
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001423 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end(); UI != E; ) {
1424 Instruction *User = cast<Instruction>(*UI++);
Chris Lattner7b550cc2009-11-06 04:27:31 +00001425 RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite);
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001426 }
Chris Lattner330245e2007-09-13 17:29:05 +00001427}
1428
Chris Lattner86395032006-09-30 23:32:09 +00001429/// RewriteUsesOfLoadForHeapSRoA - We are performing Heap SRoA on a global. Ptr
1430/// is a value loaded from the global. Eliminate all uses of Ptr, making them
1431/// use FieldGlobals instead. All uses of loaded values satisfy
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001432/// AllGlobalLoadUsesSimpleEnoughForHeapSRA.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001433static void RewriteUsesOfLoadForHeapSRoA(LoadInst *Load,
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001434 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001435 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001436 for (Value::use_iterator UI = Load->use_begin(), E = Load->use_end();
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001437 UI != E; ) {
1438 Instruction *User = cast<Instruction>(*UI++);
Chris Lattner7b550cc2009-11-06 04:27:31 +00001439 RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite);
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001440 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001441
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001442 if (Load->use_empty()) {
1443 Load->eraseFromParent();
1444 InsertedScalarizedValues.erase(Load);
1445 }
Chris Lattner86395032006-09-30 23:32:09 +00001446}
1447
Victor Hernandez83d63912009-09-18 22:35:49 +00001448/// PerformHeapAllocSRoA - CI is an allocation of an array of structures. Break
1449/// it up into multiple allocations of arrays of the fields.
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001450static GlobalVariable *PerformHeapAllocSRoA(GlobalVariable *GV, CallInst *CI,
Micah Villmow3574eca2012-10-08 16:38:25 +00001451 Value *NElems, DataLayout *TD,
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +00001452 const TargetLibraryInfo *TLI) {
David Greene3215b0e2010-01-05 01:28:05 +00001453 DEBUG(dbgs() << "SROA HEAP ALLOC: " << *GV << " MALLOC = " << *CI << '\n');
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +00001454 Type *MAT = getMallocAllocatedType(CI, TLI);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001455 StructType *STy = cast<StructType>(MAT);
Victor Hernandez83d63912009-09-18 22:35:49 +00001456
1457 // There is guaranteed to be at least one use of the malloc (storing
1458 // it into GV). If there are other uses, change them to be uses of
1459 // the global to simplify later code. This also deletes the store
1460 // into GV.
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001461 ReplaceUsesOfMallocWithGlobal(CI, GV);
1462
Victor Hernandez83d63912009-09-18 22:35:49 +00001463 // Okay, at this point, there are no users of the malloc. Insert N
1464 // new mallocs at the same place as CI, and N globals.
1465 std::vector<Value*> FieldGlobals;
1466 std::vector<Value*> FieldMallocs;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001467
Victor Hernandez83d63912009-09-18 22:35:49 +00001468 for (unsigned FieldNo = 0, e = STy->getNumElements(); FieldNo != e;++FieldNo){
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001469 Type *FieldTy = STy->getElementType(FieldNo);
1470 PointerType *PFieldTy = PointerType::getUnqual(FieldTy);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001471
Victor Hernandez83d63912009-09-18 22:35:49 +00001472 GlobalVariable *NGV =
1473 new GlobalVariable(*GV->getParent(),
1474 PFieldTy, false, GlobalValue::InternalLinkage,
1475 Constant::getNullValue(PFieldTy),
1476 GV->getName() + ".f" + Twine(FieldNo), GV,
Hans Wennborgce718ff2012-06-23 11:37:03 +00001477 GV->getThreadLocalMode());
Victor Hernandez83d63912009-09-18 22:35:49 +00001478 FieldGlobals.push_back(NGV);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001479
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001480 unsigned TypeSize = TD->getTypeAllocSize(FieldTy);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001481 if (StructType *ST = dyn_cast<StructType>(FieldTy))
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001482 TypeSize = TD->getStructLayout(ST)->getSizeInBytes();
Matt Arsenaultcf16bae2013-09-11 07:29:40 +00001483 Type *IntPtrTy = TD->getIntPtrType(CI->getType());
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001484 Value *NMI = CallInst::CreateMalloc(CI, IntPtrTy, FieldTy,
1485 ConstantInt::get(IntPtrTy, TypeSize),
Chris Lattner5a30a852010-07-12 00:57:28 +00001486 NElems, 0,
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001487 CI->getName() + ".f" + Twine(FieldNo));
Chris Lattner3f5e0b82010-02-26 18:23:13 +00001488 FieldMallocs.push_back(NMI);
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001489 new StoreInst(NMI, NGV, CI);
Victor Hernandez83d63912009-09-18 22:35:49 +00001490 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001491
Victor Hernandez83d63912009-09-18 22:35:49 +00001492 // The tricky aspect of this transformation is handling the case when malloc
1493 // fails. In the original code, malloc failing would set the result pointer
1494 // of malloc to null. In this case, some mallocs could succeed and others
1495 // could fail. As such, we emit code that looks like this:
1496 // F0 = malloc(field0)
1497 // F1 = malloc(field1)
1498 // F2 = malloc(field2)
1499 // if (F0 == 0 || F1 == 0 || F2 == 0) {
1500 // if (F0) { free(F0); F0 = 0; }
1501 // if (F1) { free(F1); F1 = 0; }
1502 // if (F2) { free(F2); F2 = 0; }
1503 // }
Victor Hernandez8e345a12009-11-10 08:32:25 +00001504 // The malloc can also fail if its argument is too large.
Gabor Greif9e4f2432010-06-24 14:42:01 +00001505 Constant *ConstantZero = ConstantInt::get(CI->getArgOperand(0)->getType(), 0);
1506 Value *RunningOr = new ICmpInst(CI, ICmpInst::ICMP_SLT, CI->getArgOperand(0),
Victor Hernandez8e345a12009-11-10 08:32:25 +00001507 ConstantZero, "isneg");
Victor Hernandez83d63912009-09-18 22:35:49 +00001508 for (unsigned i = 0, e = FieldMallocs.size(); i != e; ++i) {
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001509 Value *Cond = new ICmpInst(CI, ICmpInst::ICMP_EQ, FieldMallocs[i],
1510 Constant::getNullValue(FieldMallocs[i]->getType()),
1511 "isnull");
Victor Hernandez8e345a12009-11-10 08:32:25 +00001512 RunningOr = BinaryOperator::CreateOr(RunningOr, Cond, "tmp", CI);
Victor Hernandez83d63912009-09-18 22:35:49 +00001513 }
1514
1515 // Split the basic block at the old malloc.
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001516 BasicBlock *OrigBB = CI->getParent();
1517 BasicBlock *ContBB = OrigBB->splitBasicBlock(CI, "malloc_cont");
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001518
Victor Hernandez83d63912009-09-18 22:35:49 +00001519 // Create the block to check the first condition. Put all these blocks at the
1520 // end of the function as they are unlikely to be executed.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001521 BasicBlock *NullPtrBlock = BasicBlock::Create(OrigBB->getContext(),
1522 "malloc_ret_null",
Victor Hernandez83d63912009-09-18 22:35:49 +00001523 OrigBB->getParent());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001524
Victor Hernandez83d63912009-09-18 22:35:49 +00001525 // Remove the uncond branch from OrigBB to ContBB, turning it into a cond
1526 // branch on RunningOr.
1527 OrigBB->getTerminator()->eraseFromParent();
1528 BranchInst::Create(NullPtrBlock, ContBB, RunningOr, OrigBB);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001529
Victor Hernandez83d63912009-09-18 22:35:49 +00001530 // Within the NullPtrBlock, we need to emit a comparison and branch for each
1531 // pointer, because some may be null while others are not.
1532 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
1533 Value *GVVal = new LoadInst(FieldGlobals[i], "tmp", NullPtrBlock);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001534 Value *Cmp = new ICmpInst(*NullPtrBlock, ICmpInst::ICMP_NE, GVVal,
Benjamin Kramera9390a42011-09-27 20:39:19 +00001535 Constant::getNullValue(GVVal->getType()));
Chris Lattner7b550cc2009-11-06 04:27:31 +00001536 BasicBlock *FreeBlock = BasicBlock::Create(Cmp->getContext(), "free_it",
Victor Hernandez83d63912009-09-18 22:35:49 +00001537 OrigBB->getParent());
Chris Lattner7b550cc2009-11-06 04:27:31 +00001538 BasicBlock *NextBlock = BasicBlock::Create(Cmp->getContext(), "next",
Victor Hernandez83d63912009-09-18 22:35:49 +00001539 OrigBB->getParent());
Victor Hernandez66284e02009-10-24 04:23:03 +00001540 Instruction *BI = BranchInst::Create(FreeBlock, NextBlock,
1541 Cmp, NullPtrBlock);
Victor Hernandez83d63912009-09-18 22:35:49 +00001542
1543 // Fill in FreeBlock.
Victor Hernandez66284e02009-10-24 04:23:03 +00001544 CallInst::CreateFree(GVVal, BI);
Victor Hernandez83d63912009-09-18 22:35:49 +00001545 new StoreInst(Constant::getNullValue(GVVal->getType()), FieldGlobals[i],
1546 FreeBlock);
1547 BranchInst::Create(NextBlock, FreeBlock);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001548
Victor Hernandez83d63912009-09-18 22:35:49 +00001549 NullPtrBlock = NextBlock;
1550 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001551
Victor Hernandez83d63912009-09-18 22:35:49 +00001552 BranchInst::Create(ContBB, NullPtrBlock);
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001553
1554 // CI is no longer needed, remove it.
Victor Hernandez83d63912009-09-18 22:35:49 +00001555 CI->eraseFromParent();
1556
1557 /// InsertedScalarizedLoads - As we process loads, if we can't immediately
1558 /// update all uses of the load, keep track of what scalarized loads are
1559 /// inserted for a given load.
1560 DenseMap<Value*, std::vector<Value*> > InsertedScalarizedValues;
1561 InsertedScalarizedValues[GV] = FieldGlobals;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001562
Victor Hernandez83d63912009-09-18 22:35:49 +00001563 std::vector<std::pair<PHINode*, unsigned> > PHIsToRewrite;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001564
Victor Hernandez83d63912009-09-18 22:35:49 +00001565 // Okay, the malloc site is completely handled. All of the uses of GV are now
1566 // loads, and all uses of those loads are simple. Rewrite them to use loads
1567 // of the per-field globals instead.
1568 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI != E;) {
1569 Instruction *User = cast<Instruction>(*UI++);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001570
Victor Hernandez83d63912009-09-18 22:35:49 +00001571 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Chris Lattner7b550cc2009-11-06 04:27:31 +00001572 RewriteUsesOfLoadForHeapSRoA(LI, InsertedScalarizedValues, PHIsToRewrite);
Victor Hernandez83d63912009-09-18 22:35:49 +00001573 continue;
1574 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001575
Victor Hernandez83d63912009-09-18 22:35:49 +00001576 // Must be a store of null.
1577 StoreInst *SI = cast<StoreInst>(User);
1578 assert(isa<ConstantPointerNull>(SI->getOperand(0)) &&
1579 "Unexpected heap-sra user!");
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001580
Victor Hernandez83d63912009-09-18 22:35:49 +00001581 // Insert a store of null into each global.
1582 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001583 PointerType *PT = cast<PointerType>(FieldGlobals[i]->getType());
Victor Hernandez83d63912009-09-18 22:35:49 +00001584 Constant *Null = Constant::getNullValue(PT->getElementType());
1585 new StoreInst(Null, FieldGlobals[i], SI);
1586 }
1587 // Erase the original store.
1588 SI->eraseFromParent();
1589 }
1590
1591 // While we have PHIs that are interesting to rewrite, do it.
1592 while (!PHIsToRewrite.empty()) {
1593 PHINode *PN = PHIsToRewrite.back().first;
1594 unsigned FieldNo = PHIsToRewrite.back().second;
1595 PHIsToRewrite.pop_back();
1596 PHINode *FieldPN = cast<PHINode>(InsertedScalarizedValues[PN][FieldNo]);
1597 assert(FieldPN->getNumIncomingValues() == 0 &&"Already processed this phi");
1598
1599 // Add all the incoming values. This can materialize more phis.
1600 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1601 Value *InVal = PN->getIncomingValue(i);
1602 InVal = GetHeapSROAValue(InVal, FieldNo, InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001603 PHIsToRewrite);
Victor Hernandez83d63912009-09-18 22:35:49 +00001604 FieldPN->addIncoming(InVal, PN->getIncomingBlock(i));
1605 }
1606 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001607
Victor Hernandez83d63912009-09-18 22:35:49 +00001608 // Drop all inter-phi links and any loads that made it this far.
1609 for (DenseMap<Value*, std::vector<Value*> >::iterator
1610 I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
1611 I != E; ++I) {
1612 if (PHINode *PN = dyn_cast<PHINode>(I->first))
1613 PN->dropAllReferences();
1614 else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
1615 LI->dropAllReferences();
1616 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001617
Victor Hernandez83d63912009-09-18 22:35:49 +00001618 // Delete all the phis and loads now that inter-references are dead.
1619 for (DenseMap<Value*, std::vector<Value*> >::iterator
1620 I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
1621 I != E; ++I) {
1622 if (PHINode *PN = dyn_cast<PHINode>(I->first))
1623 PN->eraseFromParent();
1624 else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
1625 LI->eraseFromParent();
1626 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001627
Victor Hernandez83d63912009-09-18 22:35:49 +00001628 // The old global is now dead, remove it.
1629 GV->eraseFromParent();
1630
1631 ++NumHeapSRA;
1632 return cast<GlobalVariable>(FieldGlobals[0]);
1633}
1634
Chris Lattnere61d0a62008-12-15 21:02:25 +00001635/// TryToOptimizeStoreOfMallocToGlobal - This function is called when we see a
1636/// pointer global variable with a single value stored it that is a malloc or
1637/// cast of malloc.
1638static bool TryToOptimizeStoreOfMallocToGlobal(GlobalVariable *GV,
Victor Hernandez83d63912009-09-18 22:35:49 +00001639 CallInst *CI,
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001640 Type *AllocTy,
Nick Lewyckyfad4d402012-02-05 19:56:38 +00001641 AtomicOrdering Ordering,
Victor Hernandez83d63912009-09-18 22:35:49 +00001642 Module::global_iterator &GVI,
Micah Villmow3574eca2012-10-08 16:38:25 +00001643 DataLayout *TD,
Nick Lewycky6a577f82012-02-12 01:13:18 +00001644 TargetLibraryInfo *TLI) {
Evan Cheng86cd4452010-04-14 20:52:55 +00001645 if (!TD)
1646 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001647
Victor Hernandez83d63912009-09-18 22:35:49 +00001648 // If this is a malloc of an abstract type, don't touch it.
1649 if (!AllocTy->isSized())
1650 return false;
1651
1652 // We can't optimize this global unless all uses of it are *known* to be
1653 // of the malloc value, not of the null initializer value (consider a use
1654 // that compares the global's value against zero to see if the malloc has
1655 // been reached). To do this, we check to see if all uses of the global
1656 // would trap if the global were null: this proves that they must all
1657 // happen after the malloc.
1658 if (!AllUsesOfLoadedValueWillTrapIfNull(GV))
1659 return false;
1660
1661 // We can't optimize this if the malloc itself is used in a complex way,
1662 // for example, being stored into multiple globals. This allows the
Nick Lewyckybc384a12012-02-05 19:48:37 +00001663 // malloc to be stored into the specified global, loaded icmp'd, and
Victor Hernandez83d63912009-09-18 22:35:49 +00001664 // GEP'd. These are all things we could transform to using the global
1665 // for.
Evan Cheng86cd4452010-04-14 20:52:55 +00001666 SmallPtrSet<const PHINode*, 8> PHIs;
1667 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(CI, GV, PHIs))
1668 return false;
Victor Hernandez83d63912009-09-18 22:35:49 +00001669
1670 // If we have a global that is only initialized with a fixed size malloc,
1671 // transform the program to use global memory instead of malloc'd memory.
1672 // This eliminates dynamic allocation, avoids an indirection accessing the
1673 // data, and exposes the resultant global to further GlobalOpt.
Victor Hernandez8db42d22009-10-16 23:12:25 +00001674 // We cannot optimize the malloc if we cannot determine malloc array size.
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +00001675 Value *NElems = getMallocArraySize(CI, TD, TLI, true);
Evan Cheng86cd4452010-04-14 20:52:55 +00001676 if (!NElems)
1677 return false;
Victor Hernandez83d63912009-09-18 22:35:49 +00001678
Evan Cheng86cd4452010-04-14 20:52:55 +00001679 if (ConstantInt *NElements = dyn_cast<ConstantInt>(NElems))
1680 // Restrict this transformation to only working on small allocations
1681 // (2048 bytes currently), as we don't want to introduce a 16M global or
1682 // something.
1683 if (NElements->getZExtValue() * TD->getTypeAllocSize(AllocTy) < 2048) {
Nick Lewycky6a577f82012-02-12 01:13:18 +00001684 GVI = OptimizeGlobalAddressOfMalloc(GV, CI, AllocTy, NElements, TD, TLI);
Evan Cheng86cd4452010-04-14 20:52:55 +00001685 return true;
Victor Hernandez83d63912009-09-18 22:35:49 +00001686 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001687
Evan Cheng86cd4452010-04-14 20:52:55 +00001688 // If the allocation is an array of structures, consider transforming this
1689 // into multiple malloc'd arrays, one for each field. This is basically
1690 // SRoA for malloc'd memory.
1691
Nick Lewyckyfad4d402012-02-05 19:56:38 +00001692 if (Ordering != NotAtomic)
1693 return false;
1694
Evan Cheng86cd4452010-04-14 20:52:55 +00001695 // If this is an allocation of a fixed size array of structs, analyze as a
1696 // variable size array. malloc [100 x struct],1 -> malloc struct, 100
Gabor Greif9e4f2432010-06-24 14:42:01 +00001697 if (NElems == ConstantInt::get(CI->getArgOperand(0)->getType(), 1))
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001698 if (ArrayType *AT = dyn_cast<ArrayType>(AllocTy))
Evan Cheng86cd4452010-04-14 20:52:55 +00001699 AllocTy = AT->getElementType();
Gabor Greif9e4f2432010-06-24 14:42:01 +00001700
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001701 StructType *AllocSTy = dyn_cast<StructType>(AllocTy);
Evan Cheng86cd4452010-04-14 20:52:55 +00001702 if (!AllocSTy)
1703 return false;
1704
1705 // This the structure has an unreasonable number of fields, leave it
1706 // alone.
1707 if (AllocSTy->getNumElements() <= 16 && AllocSTy->getNumElements() != 0 &&
1708 AllGlobalLoadUsesSimpleEnoughForHeapSRA(GV, CI)) {
1709
1710 // If this is a fixed size array, transform the Malloc to be an alloc of
1711 // structs. malloc [100 x struct],1 -> malloc struct, 100
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +00001712 if (ArrayType *AT = dyn_cast<ArrayType>(getMallocAllocatedType(CI, TLI))) {
Matt Arsenaultcf16bae2013-09-11 07:29:40 +00001713 Type *IntPtrTy = TD->getIntPtrType(CI->getType());
Evan Cheng86cd4452010-04-14 20:52:55 +00001714 unsigned TypeSize = TD->getStructLayout(AllocSTy)->getSizeInBytes();
1715 Value *AllocSize = ConstantInt::get(IntPtrTy, TypeSize);
1716 Value *NumElements = ConstantInt::get(IntPtrTy, AT->getNumElements());
1717 Instruction *Malloc = CallInst::CreateMalloc(CI, IntPtrTy, AllocSTy,
1718 AllocSize, NumElements,
Chris Lattner5a30a852010-07-12 00:57:28 +00001719 0, CI->getName());
Evan Cheng86cd4452010-04-14 20:52:55 +00001720 Instruction *Cast = new BitCastInst(Malloc, CI->getType(), "tmp", CI);
1721 CI->replaceAllUsesWith(Cast);
1722 CI->eraseFromParent();
Nuno Lopeseb7c6862012-06-22 00:25:01 +00001723 if (BitCastInst *BCI = dyn_cast<BitCastInst>(Malloc))
1724 CI = cast<CallInst>(BCI->getOperand(0));
1725 else
Nuno Lopescd88efe2012-06-22 00:29:58 +00001726 CI = cast<CallInst>(Malloc);
Evan Cheng86cd4452010-04-14 20:52:55 +00001727 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001728
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +00001729 GVI = PerformHeapAllocSRoA(GV, CI, getMallocArraySize(CI, TD, TLI, true),
1730 TD, TLI);
Evan Cheng86cd4452010-04-14 20:52:55 +00001731 return true;
Victor Hernandez83d63912009-09-18 22:35:49 +00001732 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001733
Victor Hernandez83d63912009-09-18 22:35:49 +00001734 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001735}
Victor Hernandez83d63912009-09-18 22:35:49 +00001736
Chris Lattner9b34a612004-10-09 21:48:45 +00001737// OptimizeOnceStoredGlobal - Try to optimize globals based on the knowledge
1738// that only one value (besides its initializer) is ever stored to the global.
Chris Lattner30ba5692004-10-11 05:54:41 +00001739static bool OptimizeOnceStoredGlobal(GlobalVariable *GV, Value *StoredOnceVal,
Nick Lewyckyfad4d402012-02-05 19:56:38 +00001740 AtomicOrdering Ordering,
Chris Lattner7f8897f2006-08-27 22:42:52 +00001741 Module::global_iterator &GVI,
Micah Villmow3574eca2012-10-08 16:38:25 +00001742 DataLayout *TD, TargetLibraryInfo *TLI) {
Chris Lattner344b41c2008-12-15 21:20:32 +00001743 // Ignore no-op GEPs and bitcasts.
1744 StoredOnceVal = StoredOnceVal->stripPointerCasts();
Chris Lattner9b34a612004-10-09 21:48:45 +00001745
Chris Lattner708148e2004-10-10 23:14:11 +00001746 // If we are dealing with a pointer global that is initialized to null and
1747 // only has one (non-null) value stored into it, then we can optimize any
1748 // users of the loaded value (often calls and loads) that would trap if the
1749 // value was null.
Duncan Sands1df98592010-02-16 11:11:14 +00001750 if (GV->getInitializer()->getType()->isPointerTy() &&
Chris Lattner9b34a612004-10-09 21:48:45 +00001751 GV->getInitializer()->isNullValue()) {
Chris Lattner708148e2004-10-10 23:14:11 +00001752 if (Constant *SOVC = dyn_cast<Constant>(StoredOnceVal)) {
1753 if (GV->getInitializer()->getType() != SOVC->getType())
Chris Lattner98a42b22011-05-22 07:15:13 +00001754 SOVC = ConstantExpr::getBitCast(SOVC, GV->getInitializer()->getType());
Misha Brukmanfd939082005-04-21 23:48:37 +00001755
Chris Lattner708148e2004-10-10 23:14:11 +00001756 // Optimize away any trapping uses of the loaded value.
Nick Lewycky6a577f82012-02-12 01:13:18 +00001757 if (OptimizeAwayTrappingUsesOfLoads(GV, SOVC, TD, TLI))
Chris Lattner8be80122004-10-10 17:07:12 +00001758 return true;
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +00001759 } else if (CallInst *CI = extractMallocCall(StoredOnceVal, TLI)) {
1760 Type *MallocType = getMallocAllocatedType(CI, TLI);
Nick Lewycky6a577f82012-02-12 01:13:18 +00001761 if (MallocType &&
1762 TryToOptimizeStoreOfMallocToGlobal(GV, CI, MallocType, Ordering, GVI,
1763 TD, TLI))
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001764 return true;
Chris Lattner708148e2004-10-10 23:14:11 +00001765 }
Chris Lattner9b34a612004-10-09 21:48:45 +00001766 }
Chris Lattner30ba5692004-10-11 05:54:41 +00001767
Chris Lattner9b34a612004-10-09 21:48:45 +00001768 return false;
1769}
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001770
Chris Lattner58e44f42008-01-14 01:17:44 +00001771/// TryToShrinkGlobalToBoolean - At this point, we have learned that the only
1772/// two values ever stored into GV are its initializer and OtherVal. See if we
1773/// can shrink the global into a boolean and select between the two values
1774/// whenever it is used. This exposes the values to other scalar optimizations.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001775static bool TryToShrinkGlobalToBoolean(GlobalVariable *GV, Constant *OtherVal) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001776 Type *GVElType = GV->getType()->getElementType();
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001777
Chris Lattner58e44f42008-01-14 01:17:44 +00001778 // If GVElType is already i1, it is already shrunk. If the type of the GV is
Chris Lattner6f6923f2009-03-07 23:32:02 +00001779 // an FP value, pointer or vector, don't do this optimization because a select
1780 // between them is very expensive and unlikely to lead to later
1781 // simplification. In these cases, we typically end up with "cond ? v1 : v2"
1782 // where v1 and v2 both require constant pool loads, a big loss.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001783 if (GVElType == Type::getInt1Ty(GV->getContext()) ||
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001784 GVElType->isFloatingPointTy() ||
Duncan Sands1df98592010-02-16 11:11:14 +00001785 GVElType->isPointerTy() || GVElType->isVectorTy())
Chris Lattner58e44f42008-01-14 01:17:44 +00001786 return false;
Gabor Greifaaaaa022010-07-12 14:13:15 +00001787
Chris Lattner58e44f42008-01-14 01:17:44 +00001788 // Walk the use list of the global seeing if all the uses are load or store.
1789 // If there is anything else, bail out.
Gabor Greifaaaaa022010-07-12 14:13:15 +00001790 for (Value::use_iterator I = GV->use_begin(), E = GV->use_end(); I != E; ++I){
1791 User *U = *I;
1792 if (!isa<LoadInst>(U) && !isa<StoreInst>(U))
Chris Lattner58e44f42008-01-14 01:17:44 +00001793 return false;
Gabor Greifaaaaa022010-07-12 14:13:15 +00001794 }
1795
David Greene3215b0e2010-01-05 01:28:05 +00001796 DEBUG(dbgs() << " *** SHRINKING TO BOOL: " << *GV);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001797
Chris Lattner96a86b22004-12-12 05:53:50 +00001798 // Create the new global, initializing it to false.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001799 GlobalVariable *NewGV = new GlobalVariable(Type::getInt1Ty(GV->getContext()),
1800 false,
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001801 GlobalValue::InternalLinkage,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001802 ConstantInt::getFalse(GV->getContext()),
Nick Lewycky0e670df2009-05-03 03:49:08 +00001803 GV->getName()+".b",
Joey Gouly1d505a32013-01-10 10:31:11 +00001804 GV->getThreadLocalMode(),
1805 GV->getType()->getAddressSpace());
Chris Lattner96a86b22004-12-12 05:53:50 +00001806 GV->getParent()->getGlobalList().insert(GV, NewGV);
1807
1808 Constant *InitVal = GV->getInitializer();
Chris Lattner7b550cc2009-11-06 04:27:31 +00001809 assert(InitVal->getType() != Type::getInt1Ty(GV->getContext()) &&
Owen Anderson1d0be152009-08-13 21:58:54 +00001810 "No reason to shrink to bool!");
Chris Lattner96a86b22004-12-12 05:53:50 +00001811
1812 // If initialized to zero and storing one into the global, we can use a cast
1813 // instead of a select to synthesize the desired value.
1814 bool IsOneZero = false;
1815 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal))
Reid Spencercae57542007-03-02 00:28:52 +00001816 IsOneZero = InitVal->isNullValue() && CI->isOne();
Chris Lattner96a86b22004-12-12 05:53:50 +00001817
1818 while (!GV->use_empty()) {
Devang Patel771281f2009-03-06 01:39:36 +00001819 Instruction *UI = cast<Instruction>(GV->use_back());
1820 if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
Chris Lattner96a86b22004-12-12 05:53:50 +00001821 // Change the store into a boolean store.
1822 bool StoringOther = SI->getOperand(0) == OtherVal;
1823 // Only do this if we weren't storing a loaded value.
Chris Lattner38c25562004-12-12 19:34:41 +00001824 Value *StoreVal;
Bill Wendling17fe48c2013-02-13 23:00:51 +00001825 if (StoringOther || SI->getOperand(0) == InitVal) {
Chris Lattner7b550cc2009-11-06 04:27:31 +00001826 StoreVal = ConstantInt::get(Type::getInt1Ty(GV->getContext()),
1827 StoringOther);
Bill Wendling17fe48c2013-02-13 23:00:51 +00001828 } else {
Chris Lattner38c25562004-12-12 19:34:41 +00001829 // Otherwise, we are storing a previously loaded copy. To do this,
1830 // change the copy from copying the original value to just copying the
1831 // bool.
1832 Instruction *StoredVal = cast<Instruction>(SI->getOperand(0));
1833
Gabor Greif9e4f2432010-06-24 14:42:01 +00001834 // If we've already replaced the input, StoredVal will be a cast or
Chris Lattner38c25562004-12-12 19:34:41 +00001835 // select instruction. If not, it will be a load of the original
1836 // global.
1837 if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
1838 assert(LI->getOperand(0) == GV && "Not a copy!");
1839 // Insert a new load, to preserve the saved value.
Nick Lewyckyfad4d402012-02-05 19:56:38 +00001840 StoreVal = new LoadInst(NewGV, LI->getName()+".b", false, 0,
1841 LI->getOrdering(), LI->getSynchScope(), LI);
Chris Lattner38c25562004-12-12 19:34:41 +00001842 } else {
1843 assert((isa<CastInst>(StoredVal) || isa<SelectInst>(StoredVal)) &&
1844 "This is not a form that we understand!");
1845 StoreVal = StoredVal->getOperand(0);
1846 assert(isa<LoadInst>(StoreVal) && "Not a load of NewGV!");
1847 }
1848 }
Nick Lewyckyfad4d402012-02-05 19:56:38 +00001849 new StoreInst(StoreVal, NewGV, false, 0,
1850 SI->getOrdering(), SI->getSynchScope(), SI);
Devang Patel771281f2009-03-06 01:39:36 +00001851 } else {
Chris Lattner96a86b22004-12-12 05:53:50 +00001852 // Change the load into a load of bool then a select.
Devang Patel771281f2009-03-06 01:39:36 +00001853 LoadInst *LI = cast<LoadInst>(UI);
Nick Lewyckyfad4d402012-02-05 19:56:38 +00001854 LoadInst *NLI = new LoadInst(NewGV, LI->getName()+".b", false, 0,
1855 LI->getOrdering(), LI->getSynchScope(), LI);
Chris Lattner96a86b22004-12-12 05:53:50 +00001856 Value *NSI;
1857 if (IsOneZero)
Chris Lattner046800a2007-02-11 01:08:35 +00001858 NSI = new ZExtInst(NLI, LI->getType(), "", LI);
Misha Brukmanfd939082005-04-21 23:48:37 +00001859 else
Gabor Greif051a9502008-04-06 20:25:17 +00001860 NSI = SelectInst::Create(NLI, OtherVal, InitVal, "", LI);
Chris Lattner046800a2007-02-11 01:08:35 +00001861 NSI->takeName(LI);
Chris Lattner96a86b22004-12-12 05:53:50 +00001862 LI->replaceAllUsesWith(NSI);
Devang Patel771281f2009-03-06 01:39:36 +00001863 }
1864 UI->eraseFromParent();
Chris Lattner96a86b22004-12-12 05:53:50 +00001865 }
1866
Bill Wendling17fe48c2013-02-13 23:00:51 +00001867 // Retain the name of the old global variable. People who are debugging their
1868 // programs may expect these variables to be named the same.
1869 NewGV->takeName(GV);
Chris Lattner96a86b22004-12-12 05:53:50 +00001870 GV->eraseFromParent();
Chris Lattner58e44f42008-01-14 01:17:44 +00001871 return true;
Chris Lattner96a86b22004-12-12 05:53:50 +00001872}
1873
1874
Nick Lewyckydb292a62012-02-12 00:52:26 +00001875/// ProcessGlobal - Analyze the specified global variable and optimize it if
1876/// possible. If we make a change, return true.
Rafael Espindolac4440e32011-01-19 16:32:21 +00001877bool GlobalOpt::ProcessGlobal(GlobalVariable *GV,
1878 Module::global_iterator &GVI) {
Rafael Espindola03977292012-06-14 22:48:13 +00001879 if (!GV->isDiscardableIfUnused())
Rafael Espindolac4440e32011-01-19 16:32:21 +00001880 return false;
1881
1882 // Do more involved optimizations if the global is internal.
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001883 GV->removeDeadConstantUsers();
1884
1885 if (GV->use_empty()) {
David Greene3215b0e2010-01-05 01:28:05 +00001886 DEBUG(dbgs() << "GLOBAL DEAD: " << *GV);
Chris Lattner7a7ed022004-10-16 18:09:00 +00001887 GV->eraseFromParent();
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001888 ++NumDeleted;
1889 return true;
1890 }
1891
Rafael Espindola2f135d42012-06-15 18:00:24 +00001892 if (!GV->hasLocalLinkage())
1893 return false;
1894
Rafael Espindolac4440e32011-01-19 16:32:21 +00001895 SmallPtrSet<const PHINode*, 16> PHIUsers;
1896 GlobalStatus GS;
1897
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001898 if (AnalyzeGlobal(GV, GS, PHIUsers))
1899 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001900
Rafael Espindolac4440e32011-01-19 16:32:21 +00001901 if (!GS.isCompared && !GV->hasUnnamedAddr()) {
1902 GV->setUnnamedAddr(true);
1903 NumUnnamed++;
1904 }
1905
1906 if (GV->isConstant() || !GV->hasInitializer())
1907 return false;
1908
Rafael Espindola466fa172013-09-05 19:15:21 +00001909 return ProcessInternalGlobal(GV, GVI, GS);
Rafael Espindolac4440e32011-01-19 16:32:21 +00001910}
1911
1912/// ProcessInternalGlobal - Analyze the specified global variable and optimize
1913/// it if possible. If we make a change, return true.
1914bool GlobalOpt::ProcessInternalGlobal(GlobalVariable *GV,
1915 Module::global_iterator &GVI,
Rafael Espindolac4440e32011-01-19 16:32:21 +00001916 const GlobalStatus &GS) {
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001917 // If the global is never loaded (but may be stored to), it is dead.
1918 // Delete it now.
1919 if (!GS.isLoaded) {
1920 DEBUG(dbgs() << "GLOBAL NEVER LOADED: " << *GV);
1921
Nick Lewycky8899d5c2012-07-24 07:21:08 +00001922 bool Changed;
1923 if (isLeakCheckerRoot(GV)) {
1924 // Delete any constant stores to the global.
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +00001925 Changed = CleanupPointerRootUsers(GV, TLI);
Nick Lewycky8899d5c2012-07-24 07:21:08 +00001926 } else {
1927 // Delete any stores we can find to the global. We may not be able to
1928 // make it completely dead though.
1929 Changed = CleanupConstantGlobalUsers(GV, GV->getInitializer(), TD, TLI);
1930 }
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001931
1932 // If the global is dead now, delete it.
1933 if (GV->use_empty()) {
1934 GV->eraseFromParent();
1935 ++NumDeleted;
1936 Changed = true;
1937 }
1938 return Changed;
1939
1940 } else if (GS.StoredType <= GlobalStatus::isInitializerStored) {
Michael Gottesmancddd8a62013-01-11 20:07:53 +00001941 DEBUG(dbgs() << "MARKING CONSTANT: " << *GV << "\n");
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001942 GV->setConstant(true);
1943
1944 // Clean up any obviously simplifiable users now.
Nick Lewycky6a577f82012-02-12 01:13:18 +00001945 CleanupConstantGlobalUsers(GV, GV->getInitializer(), TD, TLI);
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001946
1947 // If the global is dead now, just nuke it.
1948 if (GV->use_empty()) {
1949 DEBUG(dbgs() << " *** Marking constant allowed us to simplify "
1950 << "all users and delete global!\n");
1951 GV->eraseFromParent();
1952 ++NumDeleted;
1953 }
1954
1955 ++NumMarked;
1956 return true;
1957 } else if (!GV->getInitializer()->getType()->isSingleValueType()) {
Micah Villmow3574eca2012-10-08 16:38:25 +00001958 if (DataLayout *TD = getAnalysisIfAvailable<DataLayout>())
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001959 if (GlobalVariable *FirstNewGV = SRAGlobal(GV, *TD)) {
1960 GVI = FirstNewGV; // Don't skip the newly produced globals!
1961 return true;
1962 }
1963 } else if (GS.StoredType == GlobalStatus::isStoredOnce) {
1964 // If the initial value for the global was an undef value, and if only
1965 // one other value was stored into it, we can just change the
1966 // initializer to be the stored value, then delete all stores to the
1967 // global. This allows us to mark it constant.
1968 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
1969 if (isa<UndefValue>(GV->getInitializer())) {
1970 // Change the initial value here.
1971 GV->setInitializer(SOVConstant);
1972
1973 // Clean up any obviously simplifiable users now.
Nick Lewycky6a577f82012-02-12 01:13:18 +00001974 CleanupConstantGlobalUsers(GV, GV->getInitializer(), TD, TLI);
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001975
1976 if (GV->use_empty()) {
1977 DEBUG(dbgs() << " *** Substituting initializer allowed us to "
Nick Lewycky8899d5c2012-07-24 07:21:08 +00001978 << "simplify all users and delete global!\n");
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001979 GV->eraseFromParent();
1980 ++NumDeleted;
1981 } else {
1982 GVI = GV;
1983 }
1984 ++NumSubstitute;
1985 return true;
1986 }
1987
1988 // Try to optimize globals based on the knowledge that only one value
1989 // (besides its initializer) is ever stored to the global.
Nick Lewyckyfad4d402012-02-05 19:56:38 +00001990 if (OptimizeOnceStoredGlobal(GV, GS.StoredOnceValue, GS.Ordering, GVI,
Nick Lewycky6a577f82012-02-12 01:13:18 +00001991 TD, TLI))
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001992 return true;
1993
1994 // Otherwise, if the global was not a boolean, we can shrink it to be a
1995 // boolean.
Eli Friedmanb1c54932013-09-09 22:00:13 +00001996 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue)) {
1997 if (GS.Ordering == NotAtomic) {
1998 if (TryToShrinkGlobalToBoolean(GV, SOVConstant)) {
1999 ++NumShrunkToBool;
2000 return true;
2001 }
Rafael Espindoladaad56a2011-01-18 04:36:06 +00002002 }
Eli Friedmanb1c54932013-09-09 22:00:13 +00002003 }
Rafael Espindoladaad56a2011-01-18 04:36:06 +00002004 }
2005
Chris Lattnera4be1dc2004-10-08 20:59:28 +00002006 return false;
2007}
2008
Chris Lattnerfb217ad2005-05-08 22:18:06 +00002009/// ChangeCalleesToFastCall - Walk all of the direct calls of the specified
2010/// function, changing them to FastCC.
2011static void ChangeCalleesToFastCall(Function *F) {
2012 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
Jay Foadb7454fd2012-05-12 08:30:16 +00002013 if (isa<BlockAddress>(*UI))
2014 continue;
Duncan Sands548448a2008-02-18 17:32:13 +00002015 CallSite User(cast<Instruction>(*UI));
2016 User.setCallingConv(CallingConv::Fast);
Chris Lattnerfb217ad2005-05-08 22:18:06 +00002017 }
2018}
Chris Lattnera4be1dc2004-10-08 20:59:28 +00002019
Bill Wendling99faa3b2012-12-07 23:16:57 +00002020static AttributeSet StripNest(LLVMContext &C, const AttributeSet &Attrs) {
Chris Lattner58d74912008-03-12 17:45:29 +00002021 for (unsigned i = 0, e = Attrs.getNumSlots(); i != e; ++i) {
Bill Wendling8e47daf2013-01-25 23:09:36 +00002022 unsigned Index = Attrs.getSlotIndex(i);
2023 if (!Attrs.getSlotAttributes(i).hasAttribute(Index, Attribute::Nest))
Duncan Sands548448a2008-02-18 17:32:13 +00002024 continue;
2025
Duncan Sands548448a2008-02-18 17:32:13 +00002026 // There can be only one.
Bill Wendling8e47daf2013-01-25 23:09:36 +00002027 return Attrs.removeAttribute(C, Index, Attribute::Nest);
Duncan Sands3d5378f2008-02-16 20:56:04 +00002028 }
2029
2030 return Attrs;
2031}
2032
2033static void RemoveNestAttribute(Function *F) {
Bill Wendling5886b7b2012-10-14 06:39:53 +00002034 F->setAttributes(StripNest(F->getContext(), F->getAttributes()));
Duncan Sands3d5378f2008-02-16 20:56:04 +00002035 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
Jay Foadb7454fd2012-05-12 08:30:16 +00002036 if (isa<BlockAddress>(*UI))
2037 continue;
Duncan Sands548448a2008-02-18 17:32:13 +00002038 CallSite User(cast<Instruction>(*UI));
Bill Wendling5886b7b2012-10-14 06:39:53 +00002039 User.setAttributes(StripNest(F->getContext(), User.getAttributes()));
Duncan Sands3d5378f2008-02-16 20:56:04 +00002040 }
2041}
2042
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002043bool GlobalOpt::OptimizeFunctions(Module &M) {
2044 bool Changed = false;
2045 // Optimize functions.
2046 for (Module::iterator FI = M.begin(), E = M.end(); FI != E; ) {
2047 Function *F = FI++;
Duncan Sandsfc5940d2009-03-06 10:21:56 +00002048 // Functions without names cannot be referenced outside this module.
2049 if (!F->hasName() && !F->isDeclaration())
2050 F->setLinkage(GlobalValue::InternalLinkage);
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002051 F->removeDeadConstantUsers();
Eli Friedmanc6633052011-10-20 05:23:42 +00002052 if (F->isDefTriviallyDead()) {
Chris Lattnerec4c7b92009-11-01 19:03:42 +00002053 F->eraseFromParent();
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002054 Changed = true;
2055 ++NumFnDeleted;
Rafael Espindolabb46f522009-01-15 20:18:42 +00002056 } else if (F->hasLocalLinkage()) {
Duncan Sands3d5378f2008-02-16 20:56:04 +00002057 if (F->getCallingConv() == CallingConv::C && !F->isVarArg() &&
Jay Foad757068f2009-06-10 08:41:11 +00002058 !F->hasAddressTaken()) {
Duncan Sands3d5378f2008-02-16 20:56:04 +00002059 // If this function has C calling conventions, is not a varargs
2060 // function, and is only called directly, promote it to use the Fast
2061 // calling convention.
2062 F->setCallingConv(CallingConv::Fast);
2063 ChangeCalleesToFastCall(F);
2064 ++NumFastCallFns;
2065 Changed = true;
2066 }
2067
Bill Wendling034b94b2012-12-19 07:18:57 +00002068 if (F->getAttributes().hasAttrSomewhere(Attribute::Nest) &&
Jay Foad757068f2009-06-10 08:41:11 +00002069 !F->hasAddressTaken()) {
Duncan Sands3d5378f2008-02-16 20:56:04 +00002070 // The function is not used by a trampoline intrinsic, so it is safe
2071 // to remove the 'nest' attribute.
2072 RemoveNestAttribute(F);
2073 ++NumNestRemoved;
2074 Changed = true;
2075 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002076 }
2077 }
2078 return Changed;
2079}
2080
2081bool GlobalOpt::OptimizeGlobalVars(Module &M) {
2082 bool Changed = false;
2083 for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
2084 GVI != E; ) {
2085 GlobalVariable *GV = GVI++;
Duncan Sandsfc5940d2009-03-06 10:21:56 +00002086 // Global variables without names cannot be referenced outside this module.
2087 if (!GV->hasName() && !GV->isDeclaration())
2088 GV->setLinkage(GlobalValue::InternalLinkage);
Dan Gohman01b97dd2009-11-23 16:22:21 +00002089 // Simplify the initializer.
2090 if (GV->hasInitializer())
2091 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GV->getInitializer())) {
Chad Rosieraab8e282011-12-02 01:26:24 +00002092 Constant *New = ConstantFoldConstantExpression(CE, TD, TLI);
Dan Gohman01b97dd2009-11-23 16:22:21 +00002093 if (New && New != CE)
2094 GV->setInitializer(New);
2095 }
Rafael Espindolac4440e32011-01-19 16:32:21 +00002096
2097 Changed |= ProcessGlobal(GV, GVI);
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002098 }
2099 return Changed;
2100}
2101
Nick Lewycky2c44a802011-04-08 07:30:21 +00002102/// FindGlobalCtors - Find the llvm.global_ctors list, verifying that all
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002103/// initializers have an init priority of 65535.
2104GlobalVariable *GlobalOpt::FindGlobalCtors(Module &M) {
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00002105 GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
2106 if (GV == 0) return 0;
Jakub Staszak582088c2012-12-06 21:57:16 +00002107
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00002108 // Verify that the initializer is simple enough for us to handle. We are
2109 // only allowed to optimize the initializer if it is unique.
2110 if (!GV->hasUniqueInitializer()) return 0;
Nick Lewycky5ea5c612011-04-11 22:11:20 +00002111
2112 if (isa<ConstantAggregateZero>(GV->getInitializer()))
2113 return GV;
2114 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
Eli Friedman18a2e502011-04-09 09:11:09 +00002115
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00002116 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i) {
Nick Lewycky5ea5c612011-04-11 22:11:20 +00002117 if (isa<ConstantAggregateZero>(*i))
2118 continue;
2119 ConstantStruct *CS = cast<ConstantStruct>(*i);
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00002120 if (isa<ConstantPointerNull>(CS->getOperand(1)))
2121 continue;
Chris Lattner7d8e58f2005-09-26 02:19:27 +00002122
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00002123 // Must have a function or null ptr.
2124 if (!isa<Function>(CS->getOperand(1)))
2125 return 0;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002126
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00002127 // Init priority must be standard.
Nick Lewycky2c44a802011-04-08 07:30:21 +00002128 ConstantInt *CI = cast<ConstantInt>(CS->getOperand(0));
2129 if (CI->getZExtValue() != 65535)
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00002130 return 0;
2131 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002132
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00002133 return GV;
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002134}
2135
Chris Lattnerdb973e62005-09-26 02:31:18 +00002136/// ParseGlobalCtors - Given a llvm.global_ctors list that we can understand,
2137/// return a list of the functions and null terminator as a vector.
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002138static std::vector<Function*> ParseGlobalCtors(GlobalVariable *GV) {
Nick Lewycky5ea5c612011-04-11 22:11:20 +00002139 if (GV->getInitializer()->isNullValue())
2140 return std::vector<Function*>();
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002141 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
2142 std::vector<Function*> Result;
2143 Result.reserve(CA->getNumOperands());
Gabor Greif5e463212008-05-29 01:59:18 +00002144 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i) {
2145 ConstantStruct *CS = cast<ConstantStruct>(*i);
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002146 Result.push_back(dyn_cast<Function>(CS->getOperand(1)));
2147 }
2148 return Result;
2149}
2150
Chris Lattnerdb973e62005-09-26 02:31:18 +00002151/// InstallGlobalCtors - Given a specified llvm.global_ctors list, install the
2152/// specified array, returning the new global to use.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002153static GlobalVariable *InstallGlobalCtors(GlobalVariable *GCL,
Chris Lattner7b550cc2009-11-06 04:27:31 +00002154 const std::vector<Function*> &Ctors) {
Chris Lattnerdb973e62005-09-26 02:31:18 +00002155 // If we made a change, reassemble the initializer list.
Chris Lattnerb065b062011-06-20 04:01:31 +00002156 Constant *CSVals[2];
2157 CSVals[0] = ConstantInt::get(Type::getInt32Ty(GCL->getContext()), 65535);
2158 CSVals[1] = 0;
2159
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002160 StructType *StructTy =
Chris Lattnerb065b062011-06-20 04:01:31 +00002161 cast <StructType>(
2162 cast<ArrayType>(GCL->getType()->getElementType())->getElementType());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002163
Chris Lattnerdb973e62005-09-26 02:31:18 +00002164 // Create the new init list.
2165 std::vector<Constant*> CAList;
2166 for (unsigned i = 0, e = Ctors.size(); i != e; ++i) {
Chris Lattner79c11012005-09-26 04:44:35 +00002167 if (Ctors[i]) {
Chris Lattnerdb973e62005-09-26 02:31:18 +00002168 CSVals[1] = Ctors[i];
Chris Lattner79c11012005-09-26 04:44:35 +00002169 } else {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002170 Type *FTy = FunctionType::get(Type::getVoidTy(GCL->getContext()),
Chris Lattner7b550cc2009-11-06 04:27:31 +00002171 false);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002172 PointerType *PFTy = PointerType::getUnqual(FTy);
Owen Andersona7235ea2009-07-31 20:28:14 +00002173 CSVals[1] = Constant::getNullValue(PFTy);
Chris Lattner7b550cc2009-11-06 04:27:31 +00002174 CSVals[0] = ConstantInt::get(Type::getInt32Ty(GCL->getContext()),
Nick Lewycky5ea5c612011-04-11 22:11:20 +00002175 0x7fffffff);
Chris Lattnerdb973e62005-09-26 02:31:18 +00002176 }
Chris Lattnerb065b062011-06-20 04:01:31 +00002177 CAList.push_back(ConstantStruct::get(StructTy, CSVals));
Chris Lattnerdb973e62005-09-26 02:31:18 +00002178 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002179
Chris Lattnerdb973e62005-09-26 02:31:18 +00002180 // Create the array initializer.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002181 Constant *CA = ConstantArray::get(ArrayType::get(StructTy,
Nick Lewyckyc332fba2009-09-19 20:30:26 +00002182 CAList.size()), CAList);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002183
Chris Lattnerdb973e62005-09-26 02:31:18 +00002184 // If we didn't change the number of elements, don't create a new GV.
2185 if (CA->getType() == GCL->getInitializer()->getType()) {
2186 GCL->setInitializer(CA);
2187 return GCL;
2188 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002189
Chris Lattnerdb973e62005-09-26 02:31:18 +00002190 // Create the new global and insert it next to the existing list.
Chris Lattner7b550cc2009-11-06 04:27:31 +00002191 GlobalVariable *NGV = new GlobalVariable(CA->getType(), GCL->isConstant(),
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +00002192 GCL->getLinkage(), CA, "",
Hans Wennborgce718ff2012-06-23 11:37:03 +00002193 GCL->getThreadLocalMode());
Chris Lattnerdb973e62005-09-26 02:31:18 +00002194 GCL->getParent()->getGlobalList().insert(GCL, NGV);
Chris Lattner046800a2007-02-11 01:08:35 +00002195 NGV->takeName(GCL);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002196
Chris Lattnerdb973e62005-09-26 02:31:18 +00002197 // Nuke the old list, replacing any uses with the new one.
2198 if (!GCL->use_empty()) {
2199 Constant *V = NGV;
2200 if (V->getType() != GCL->getType())
Owen Andersonbaf3c402009-07-29 18:55:55 +00002201 V = ConstantExpr::getBitCast(V, GCL->getType());
Chris Lattnerdb973e62005-09-26 02:31:18 +00002202 GCL->replaceAllUsesWith(V);
2203 }
2204 GCL->eraseFromParent();
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002205
Chris Lattnerdb973e62005-09-26 02:31:18 +00002206 if (Ctors.size())
2207 return NGV;
2208 else
2209 return 0;
2210}
Chris Lattner79c11012005-09-26 04:44:35 +00002211
2212
Jakub Staszak582088c2012-12-06 21:57:16 +00002213static inline bool
Chris Lattner1945d582010-12-07 04:33:29 +00002214isSimpleEnoughValueToCommit(Constant *C,
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002215 SmallPtrSet<Constant*, 8> &SimpleConstants,
Micah Villmow3574eca2012-10-08 16:38:25 +00002216 const DataLayout *TD);
Chris Lattner1945d582010-12-07 04:33:29 +00002217
2218
2219/// isSimpleEnoughValueToCommit - Return true if the specified constant can be
2220/// handled by the code generator. We don't want to generate something like:
2221/// void *X = &X/42;
2222/// because the code generator doesn't have a relocation that can handle that.
2223///
2224/// This function should be called if C was not found (but just got inserted)
2225/// in SimpleConstants to avoid having to rescan the same constants all the
2226/// time.
2227static bool isSimpleEnoughValueToCommitHelper(Constant *C,
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002228 SmallPtrSet<Constant*, 8> &SimpleConstants,
Micah Villmow3574eca2012-10-08 16:38:25 +00002229 const DataLayout *TD) {
Chris Lattner1945d582010-12-07 04:33:29 +00002230 // Simple integer, undef, constant aggregate zero, global addresses, etc are
2231 // all supported.
2232 if (C->getNumOperands() == 0 || isa<BlockAddress>(C) ||
2233 isa<GlobalValue>(C))
2234 return true;
Jakub Staszak582088c2012-12-06 21:57:16 +00002235
Chris Lattner1945d582010-12-07 04:33:29 +00002236 // Aggregate values are safe if all their elements are.
2237 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C) ||
2238 isa<ConstantVector>(C)) {
2239 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i) {
2240 Constant *Op = cast<Constant>(C->getOperand(i));
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002241 if (!isSimpleEnoughValueToCommit(Op, SimpleConstants, TD))
Chris Lattner1945d582010-12-07 04:33:29 +00002242 return false;
2243 }
2244 return true;
2245 }
Jakub Staszak582088c2012-12-06 21:57:16 +00002246
Chris Lattner1945d582010-12-07 04:33:29 +00002247 // We don't know exactly what relocations are allowed in constant expressions,
2248 // so we allow &global+constantoffset, which is safe and uniformly supported
2249 // across targets.
2250 ConstantExpr *CE = cast<ConstantExpr>(C);
2251 switch (CE->getOpcode()) {
2252 case Instruction::BitCast:
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002253 // Bitcast is fine if the casted value is fine.
2254 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, TD);
2255
Chris Lattner1945d582010-12-07 04:33:29 +00002256 case Instruction::IntToPtr:
2257 case Instruction::PtrToInt:
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002258 // int <=> ptr is fine if the int type is the same size as the
2259 // pointer type.
2260 if (!TD || TD->getTypeSizeInBits(CE->getType()) !=
2261 TD->getTypeSizeInBits(CE->getOperand(0)->getType()))
2262 return false;
2263 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, TD);
Jakub Staszak582088c2012-12-06 21:57:16 +00002264
Chris Lattner1945d582010-12-07 04:33:29 +00002265 // GEP is fine if it is simple + constant offset.
2266 case Instruction::GetElementPtr:
2267 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
2268 if (!isa<ConstantInt>(CE->getOperand(i)))
2269 return false;
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002270 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, TD);
Jakub Staszak582088c2012-12-06 21:57:16 +00002271
Chris Lattner1945d582010-12-07 04:33:29 +00002272 case Instruction::Add:
2273 // We allow simple+cst.
2274 if (!isa<ConstantInt>(CE->getOperand(1)))
2275 return false;
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002276 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, TD);
Chris Lattner1945d582010-12-07 04:33:29 +00002277 }
2278 return false;
2279}
2280
Jakub Staszak582088c2012-12-06 21:57:16 +00002281static inline bool
Chris Lattner1945d582010-12-07 04:33:29 +00002282isSimpleEnoughValueToCommit(Constant *C,
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002283 SmallPtrSet<Constant*, 8> &SimpleConstants,
Micah Villmow3574eca2012-10-08 16:38:25 +00002284 const DataLayout *TD) {
Chris Lattner1945d582010-12-07 04:33:29 +00002285 // If we already checked this constant, we win.
2286 if (!SimpleConstants.insert(C)) return true;
2287 // Check the constant.
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002288 return isSimpleEnoughValueToCommitHelper(C, SimpleConstants, TD);
Chris Lattner1945d582010-12-07 04:33:29 +00002289}
2290
2291
Chris Lattner79c11012005-09-26 04:44:35 +00002292/// isSimpleEnoughPointerToCommit - Return true if this constant is simple
Owen Andersoncff6b372011-01-14 22:19:20 +00002293/// enough for us to understand. In particular, if it is a cast to anything
2294/// other than from one pointer type to another pointer type, we punt.
2295/// We basically just support direct accesses to globals and GEP's of
Chris Lattner79c11012005-09-26 04:44:35 +00002296/// globals. This should be kept up to date with CommitValueTo.
Chris Lattner7b550cc2009-11-06 04:27:31 +00002297static bool isSimpleEnoughPointerToCommit(Constant *C) {
Dan Gohmance5de5b2009-09-07 22:42:05 +00002298 // Conservatively, avoid aggregate types. This is because we don't
2299 // want to worry about them partially overlapping other stores.
2300 if (!cast<PointerType>(C->getType())->getElementType()->isSingleValueType())
2301 return false;
2302
Dan Gohmanfd54a892009-09-07 22:31:26 +00002303 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
Mikhail Glushenkov99fca5d2010-10-19 16:47:23 +00002304 // Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or
Dan Gohmanfd54a892009-09-07 22:31:26 +00002305 // external globals.
Mikhail Glushenkov99fca5d2010-10-19 16:47:23 +00002306 return GV->hasUniqueInitializer();
Dan Gohmanfd54a892009-09-07 22:31:26 +00002307
Owen Andersone95a32c2011-01-14 22:31:13 +00002308 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002309 // Handle a constantexpr gep.
2310 if (CE->getOpcode() == Instruction::GetElementPtr &&
Dan Gohmanc62482d2009-09-07 22:40:13 +00002311 isa<GlobalVariable>(CE->getOperand(0)) &&
2312 cast<GEPOperator>(CE)->isInBounds()) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002313 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
Mikhail Glushenkov99fca5d2010-10-19 16:47:23 +00002314 // Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or
Dan Gohmanfd54a892009-09-07 22:31:26 +00002315 // external globals.
Mikhail Glushenkov99fca5d2010-10-19 16:47:23 +00002316 if (!GV->hasUniqueInitializer())
Dan Gohmanfd54a892009-09-07 22:31:26 +00002317 return false;
Dan Gohman80bdc962009-09-07 22:44:55 +00002318
Dan Gohman80bdc962009-09-07 22:44:55 +00002319 // The first index must be zero.
Oscar Fuentesee56c422010-08-02 06:00:15 +00002320 ConstantInt *CI = dyn_cast<ConstantInt>(*llvm::next(CE->op_begin()));
Dan Gohman80bdc962009-09-07 22:44:55 +00002321 if (!CI || !CI->isZero()) return false;
Dan Gohman80bdc962009-09-07 22:44:55 +00002322
2323 // The remaining indices must be compile-time known integers within the
Dan Gohmane6992f72009-09-10 23:37:55 +00002324 // notional bounds of the corresponding static array types.
2325 if (!CE->isGEPWithNoNotionalOverIndexing())
2326 return false;
Dan Gohman80bdc962009-09-07 22:44:55 +00002327
Dan Gohmanc6f69e92009-10-05 16:36:26 +00002328 return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
Jakub Staszak582088c2012-12-06 21:57:16 +00002329
Owen Andersoncff6b372011-01-14 22:19:20 +00002330 // A constantexpr bitcast from a pointer to another pointer is a no-op,
2331 // and we know how to evaluate it by moving the bitcast from the pointer
2332 // operand to the value operand.
2333 } else if (CE->getOpcode() == Instruction::BitCast &&
Chris Lattnerd5f656f2011-01-16 02:05:10 +00002334 isa<GlobalVariable>(CE->getOperand(0))) {
Owen Andersoncff6b372011-01-14 22:19:20 +00002335 // Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or
2336 // external globals.
Chris Lattnerd5f656f2011-01-16 02:05:10 +00002337 return cast<GlobalVariable>(CE->getOperand(0))->hasUniqueInitializer();
Chris Lattner798b4d52005-09-26 06:52:44 +00002338 }
Owen Andersone95a32c2011-01-14 22:31:13 +00002339 }
Jakub Staszak582088c2012-12-06 21:57:16 +00002340
Chris Lattner79c11012005-09-26 04:44:35 +00002341 return false;
2342}
2343
Chris Lattner798b4d52005-09-26 06:52:44 +00002344/// EvaluateStoreInto - Evaluate a piece of a constantexpr store into a global
2345/// initializer. This returns 'Init' modified to reflect 'Val' stored into it.
2346/// At this point, the GEP operands of Addr [0, OpNo) have been stepped into.
2347static Constant *EvaluateStoreInto(Constant *Init, Constant *Val,
Zhou Shengefcdb292012-12-01 10:54:28 +00002348 ConstantExpr *Addr, unsigned OpNo) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002349 // Base case of the recursion.
2350 if (OpNo == Addr->getNumOperands()) {
2351 assert(Val->getType() == Init->getType() && "Type mismatch!");
2352 return Val;
2353 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002354
Chris Lattnera78fa8c2012-01-27 03:08:05 +00002355 SmallVector<Constant*, 32> Elts;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002356 if (StructType *STy = dyn_cast<StructType>(Init->getType())) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002357 // Break up the constant into its elements.
Chris Lattnerd59ae902012-01-26 02:32:04 +00002358 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
2359 Elts.push_back(Init->getAggregateElement(i));
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002360
Chris Lattner798b4d52005-09-26 06:52:44 +00002361 // Replace the element that we are supposed to.
Reid Spencerb83eb642006-10-20 07:07:24 +00002362 ConstantInt *CU = cast<ConstantInt>(Addr->getOperand(OpNo));
2363 unsigned Idx = CU->getZExtValue();
2364 assert(Idx < STy->getNumElements() && "Struct index out of range!");
Zhou Shengefcdb292012-12-01 10:54:28 +00002365 Elts[Idx] = EvaluateStoreInto(Elts[Idx], Val, Addr, OpNo+1);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002366
Chris Lattner798b4d52005-09-26 06:52:44 +00002367 // Return the modified struct.
Chris Lattnerb065b062011-06-20 04:01:31 +00002368 return ConstantStruct::get(STy, Elts);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002369 }
Jakub Staszak582088c2012-12-06 21:57:16 +00002370
Chris Lattnerb065b062011-06-20 04:01:31 +00002371 ConstantInt *CI = cast<ConstantInt>(Addr->getOperand(OpNo));
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002372 SequentialType *InitTy = cast<SequentialType>(Init->getType());
Chris Lattnerb065b062011-06-20 04:01:31 +00002373
2374 uint64_t NumElts;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002375 if (ArrayType *ATy = dyn_cast<ArrayType>(InitTy))
Chris Lattnerb065b062011-06-20 04:01:31 +00002376 NumElts = ATy->getNumElements();
2377 else
Chris Lattnerd59ae902012-01-26 02:32:04 +00002378 NumElts = InitTy->getVectorNumElements();
Chris Lattnerb065b062011-06-20 04:01:31 +00002379
2380 // Break up the array into elements.
Chris Lattnerd59ae902012-01-26 02:32:04 +00002381 for (uint64_t i = 0, e = NumElts; i != e; ++i)
2382 Elts.push_back(Init->getAggregateElement(i));
Chris Lattnerb065b062011-06-20 04:01:31 +00002383
2384 assert(CI->getZExtValue() < NumElts);
2385 Elts[CI->getZExtValue()] =
Zhou Shengefcdb292012-12-01 10:54:28 +00002386 EvaluateStoreInto(Elts[CI->getZExtValue()], Val, Addr, OpNo+1);
Chris Lattnerb065b062011-06-20 04:01:31 +00002387
2388 if (Init->getType()->isArrayTy())
2389 return ConstantArray::get(cast<ArrayType>(InitTy), Elts);
2390 return ConstantVector::get(Elts);
Chris Lattner798b4d52005-09-26 06:52:44 +00002391}
2392
Chris Lattner79c11012005-09-26 04:44:35 +00002393/// CommitValueTo - We have decided that Addr (which satisfies the predicate
2394/// isSimpleEnoughPointerToCommit) should get Val as its value. Make it happen.
Chris Lattner7b550cc2009-11-06 04:27:31 +00002395static void CommitValueTo(Constant *Val, Constant *Addr) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002396 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Addr)) {
2397 assert(GV->hasInitializer());
2398 GV->setInitializer(Val);
2399 return;
2400 }
Chris Lattnera0e9a242010-01-07 01:16:21 +00002401
Chris Lattner798b4d52005-09-26 06:52:44 +00002402 ConstantExpr *CE = cast<ConstantExpr>(Addr);
2403 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
Zhou Shengefcdb292012-12-01 10:54:28 +00002404 GV->setInitializer(EvaluateStoreInto(GV->getInitializer(), Val, CE, 2));
Chris Lattner79c11012005-09-26 04:44:35 +00002405}
2406
Nick Lewycky7fa76772012-02-20 03:25:59 +00002407namespace {
2408
2409/// Evaluator - This class evaluates LLVM IR, producing the Constant
2410/// representing each SSA instruction. Changes to global variables are stored
2411/// in a mapping that can be iterated over after the evaluation is complete.
2412/// Once an evaluation call fails, the evaluation object should not be reused.
2413class Evaluator {
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002414public:
Micah Villmow3574eca2012-10-08 16:38:25 +00002415 Evaluator(const DataLayout *TD, const TargetLibraryInfo *TLI)
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002416 : TD(TD), TLI(TLI) {
2417 ValueStack.push_back(new DenseMap<Value*, Constant*>);
2418 }
2419
Nick Lewycky7fa76772012-02-20 03:25:59 +00002420 ~Evaluator() {
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002421 DeleteContainerPointers(ValueStack);
2422 while (!AllocaTmps.empty()) {
2423 GlobalVariable *Tmp = AllocaTmps.back();
2424 AllocaTmps.pop_back();
2425
2426 // If there are still users of the alloca, the program is doing something
2427 // silly, e.g. storing the address of the alloca somewhere and using it
2428 // later. Since this is undefined, we'll just make it be null.
2429 if (!Tmp->use_empty())
2430 Tmp->replaceAllUsesWith(Constant::getNullValue(Tmp->getType()));
2431 delete Tmp;
2432 }
2433 }
2434
2435 /// EvaluateFunction - Evaluate a call to function F, returning true if
2436 /// successful, false if we can't evaluate it. ActualArgs contains the formal
2437 /// arguments for the function.
2438 bool EvaluateFunction(Function *F, Constant *&RetVal,
2439 const SmallVectorImpl<Constant*> &ActualArgs);
2440
2441 /// EvaluateBlock - Evaluate all instructions in block BB, returning true if
2442 /// successful, false if we can't evaluate it. NewBB returns the next BB that
2443 /// control flows into, or null upon return.
2444 bool EvaluateBlock(BasicBlock::iterator CurInst, BasicBlock *&NextBB);
2445
2446 Constant *getVal(Value *V) {
2447 if (Constant *CV = dyn_cast<Constant>(V)) return CV;
2448 Constant *R = ValueStack.back()->lookup(V);
2449 assert(R && "Reference to an uncomputed value!");
2450 return R;
2451 }
2452
2453 void setVal(Value *V, Constant *C) {
2454 ValueStack.back()->operator[](V) = C;
2455 }
2456
2457 const DenseMap<Constant*, Constant*> &getMutatedMemory() const {
2458 return MutatedMemory;
2459 }
2460
2461 const SmallPtrSet<GlobalVariable*, 8> &getInvariants() const {
2462 return Invariants;
2463 }
2464
2465private:
2466 Constant *ComputeLoadResult(Constant *P);
2467
2468 /// ValueStack - As we compute SSA register values, we store their contents
2469 /// here. The back of the vector contains the current function and the stack
2470 /// contains the values in the calling frames.
2471 SmallVector<DenseMap<Value*, Constant*>*, 4> ValueStack;
2472
2473 /// CallStack - This is used to detect recursion. In pathological situations
2474 /// we could hit exponential behavior, but at least there is nothing
2475 /// unbounded.
2476 SmallVector<Function*, 4> CallStack;
2477
2478 /// MutatedMemory - For each store we execute, we update this map. Loads
2479 /// check this to get the most up-to-date value. If evaluation is successful,
2480 /// this state is committed to the process.
2481 DenseMap<Constant*, Constant*> MutatedMemory;
2482
2483 /// AllocaTmps - To 'execute' an alloca, we create a temporary global variable
2484 /// to represent its body. This vector is needed so we can delete the
2485 /// temporary globals when we are done.
2486 SmallVector<GlobalVariable*, 32> AllocaTmps;
2487
2488 /// Invariants - These global variables have been marked invariant by the
2489 /// static constructor.
2490 SmallPtrSet<GlobalVariable*, 8> Invariants;
2491
2492 /// SimpleConstants - These are constants we have checked and know to be
2493 /// simple enough to live in a static initializer of a global.
2494 SmallPtrSet<Constant*, 8> SimpleConstants;
2495
Micah Villmow3574eca2012-10-08 16:38:25 +00002496 const DataLayout *TD;
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002497 const TargetLibraryInfo *TLI;
2498};
2499
Nick Lewycky7fa76772012-02-20 03:25:59 +00002500} // anonymous namespace
2501
Chris Lattner562a0552005-09-26 05:16:34 +00002502/// ComputeLoadResult - Return the value that would be computed by a load from
2503/// P after the stores reflected by 'memory' have been performed. If we can't
2504/// decide, return null.
Nick Lewycky7fa76772012-02-20 03:25:59 +00002505Constant *Evaluator::ComputeLoadResult(Constant *P) {
Chris Lattner04de1cf2005-09-26 05:15:37 +00002506 // If this memory location has been recently stored, use the stored value: it
2507 // is the most up-to-date.
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002508 DenseMap<Constant*, Constant*>::const_iterator I = MutatedMemory.find(P);
2509 if (I != MutatedMemory.end()) return I->second;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002510
Chris Lattner04de1cf2005-09-26 05:15:37 +00002511 // Access it.
2512 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(P)) {
Dan Gohman82555732009-08-19 18:20:44 +00002513 if (GV->hasDefinitiveInitializer())
Chris Lattner04de1cf2005-09-26 05:15:37 +00002514 return GV->getInitializer();
2515 return 0;
Chris Lattner04de1cf2005-09-26 05:15:37 +00002516 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002517
Chris Lattner798b4d52005-09-26 06:52:44 +00002518 // Handle a constantexpr getelementptr.
2519 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(P))
2520 if (CE->getOpcode() == Instruction::GetElementPtr &&
2521 isa<GlobalVariable>(CE->getOperand(0))) {
2522 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
Dan Gohman82555732009-08-19 18:20:44 +00002523 if (GV->hasDefinitiveInitializer())
Dan Gohmanc6f69e92009-10-05 16:36:26 +00002524 return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
Chris Lattner798b4d52005-09-26 06:52:44 +00002525 }
2526
2527 return 0; // don't know how to evaluate.
Chris Lattner04de1cf2005-09-26 05:15:37 +00002528}
2529
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002530/// EvaluateBlock - Evaluate all instructions in block BB, returning true if
2531/// successful, false if we can't evaluate it. NewBB returns the next BB that
2532/// control flows into, or null upon return.
Nick Lewycky7fa76772012-02-20 03:25:59 +00002533bool Evaluator::EvaluateBlock(BasicBlock::iterator CurInst,
2534 BasicBlock *&NextBB) {
Chris Lattner79c11012005-09-26 04:44:35 +00002535 // This is the main evaluation loop.
2536 while (1) {
2537 Constant *InstResult = 0;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002538
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002539 DEBUG(dbgs() << "Evaluating Instruction: " << *CurInst << "\n");
2540
Chris Lattner79c11012005-09-26 04:44:35 +00002541 if (StoreInst *SI = dyn_cast<StoreInst>(CurInst)) {
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002542 if (!SI->isSimple()) {
Michael Gottesmandcf66952013-01-11 23:08:52 +00002543 DEBUG(dbgs() << "Store is not simple! Can not evaluate.\n");
2544 return false; // no volatile/atomic accesses.
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002545 }
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002546 Constant *Ptr = getVal(SI->getOperand(1));
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002547 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
Michael Gottesmandcf66952013-01-11 23:08:52 +00002548 DEBUG(dbgs() << "Folding constant ptr expression: " << *Ptr);
Nick Lewyckya641c072012-02-21 22:08:06 +00002549 Ptr = ConstantFoldConstantExpression(CE, TD, TLI);
Michael Gottesmandcf66952013-01-11 23:08:52 +00002550 DEBUG(dbgs() << "; To: " << *Ptr << "\n");
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002551 }
2552 if (!isSimpleEnoughPointerToCommit(Ptr)) {
Chris Lattner79c11012005-09-26 04:44:35 +00002553 // If this is too complex for us to commit, reject it.
Michael Gottesmandcf66952013-01-11 23:08:52 +00002554 DEBUG(dbgs() << "Pointer is too complex for us to evaluate store.");
Chris Lattnercd271422005-09-27 04:45:34 +00002555 return false;
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002556 }
Jakub Staszak582088c2012-12-06 21:57:16 +00002557
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002558 Constant *Val = getVal(SI->getOperand(0));
Chris Lattner1945d582010-12-07 04:33:29 +00002559
2560 // If this might be too difficult for the backend to handle (e.g. the addr
2561 // of one global variable divided by another) then we can't commit it.
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002562 if (!isSimpleEnoughValueToCommit(Val, SimpleConstants, TD)) {
Michael Gottesmandcf66952013-01-11 23:08:52 +00002563 DEBUG(dbgs() << "Store value is too complex to evaluate store. " << *Val
2564 << "\n");
Chris Lattner1945d582010-12-07 04:33:29 +00002565 return false;
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002566 }
Jakub Staszak582088c2012-12-06 21:57:16 +00002567
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002568 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
Owen Andersoncff6b372011-01-14 22:19:20 +00002569 if (CE->getOpcode() == Instruction::BitCast) {
Michael Gottesmandcf66952013-01-11 23:08:52 +00002570 DEBUG(dbgs() << "Attempting to resolve bitcast on constant ptr.\n");
Owen Andersoncff6b372011-01-14 22:19:20 +00002571 // If we're evaluating a store through a bitcast, then we need
2572 // to pull the bitcast off the pointer type and push it onto the
2573 // stored value.
Chris Lattnerd5f656f2011-01-16 02:05:10 +00002574 Ptr = CE->getOperand(0);
Jakub Staszak582088c2012-12-06 21:57:16 +00002575
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002576 Type *NewTy = cast<PointerType>(Ptr->getType())->getElementType();
Jakub Staszak582088c2012-12-06 21:57:16 +00002577
Owen Anderson66f708f2011-01-16 04:33:33 +00002578 // In order to push the bitcast onto the stored value, a bitcast
2579 // from NewTy to Val's type must be legal. If it's not, we can try
2580 // introspecting NewTy to find a legal conversion.
2581 while (!Val->getType()->canLosslesslyBitCastTo(NewTy)) {
2582 // If NewTy is a struct, we can convert the pointer to the struct
2583 // into a pointer to its first member.
2584 // FIXME: This could be extended to support arrays as well.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002585 if (StructType *STy = dyn_cast<StructType>(NewTy)) {
Owen Anderson66f708f2011-01-16 04:33:33 +00002586 NewTy = STy->getTypeAtIndex(0U);
2587
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002588 IntegerType *IdxTy = IntegerType::get(NewTy->getContext(), 32);
Owen Anderson66f708f2011-01-16 04:33:33 +00002589 Constant *IdxZero = ConstantInt::get(IdxTy, 0, false);
2590 Constant * const IdxList[] = {IdxZero, IdxZero};
2591
Jay Foadb4263a62011-07-22 08:52:50 +00002592 Ptr = ConstantExpr::getGetElementPtr(Ptr, IdxList);
Nick Lewyckya641c072012-02-21 22:08:06 +00002593 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
2594 Ptr = ConstantFoldConstantExpression(CE, TD, TLI);
2595
Owen Anderson66f708f2011-01-16 04:33:33 +00002596 // If we can't improve the situation by introspecting NewTy,
2597 // we have to give up.
2598 } else {
Michael Gottesmandcf66952013-01-11 23:08:52 +00002599 DEBUG(dbgs() << "Failed to bitcast constant ptr, can not "
2600 "evaluate.\n");
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002601 return false;
Owen Anderson66f708f2011-01-16 04:33:33 +00002602 }
Owen Andersoncff6b372011-01-14 22:19:20 +00002603 }
Jakub Staszak582088c2012-12-06 21:57:16 +00002604
Owen Anderson66f708f2011-01-16 04:33:33 +00002605 // If we found compatible types, go ahead and push the bitcast
2606 // onto the stored value.
Owen Andersoncff6b372011-01-14 22:19:20 +00002607 Val = ConstantExpr::getBitCast(Val, NewTy);
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002608
Michael Gottesmandcf66952013-01-11 23:08:52 +00002609 DEBUG(dbgs() << "Evaluated bitcast: " << *Val << "\n");
Owen Andersoncff6b372011-01-14 22:19:20 +00002610 }
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002611 }
Jakub Staszak582088c2012-12-06 21:57:16 +00002612
Chris Lattner79c11012005-09-26 04:44:35 +00002613 MutatedMemory[Ptr] = Val;
2614 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CurInst)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002615 InstResult = ConstantExpr::get(BO->getOpcode(),
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002616 getVal(BO->getOperand(0)),
2617 getVal(BO->getOperand(1)));
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002618 DEBUG(dbgs() << "Found a BinaryOperator! Simplifying: " << *InstResult
Michael Gottesmandcf66952013-01-11 23:08:52 +00002619 << "\n");
Reid Spencere4d87aa2006-12-23 06:05:41 +00002620 } else if (CmpInst *CI = dyn_cast<CmpInst>(CurInst)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002621 InstResult = ConstantExpr::getCompare(CI->getPredicate(),
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002622 getVal(CI->getOperand(0)),
2623 getVal(CI->getOperand(1)));
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002624 DEBUG(dbgs() << "Found a CmpInst! Simplifying: " << *InstResult
Michael Gottesmandcf66952013-01-11 23:08:52 +00002625 << "\n");
Chris Lattner79c11012005-09-26 04:44:35 +00002626 } else if (CastInst *CI = dyn_cast<CastInst>(CurInst)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002627 InstResult = ConstantExpr::getCast(CI->getOpcode(),
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002628 getVal(CI->getOperand(0)),
Chris Lattner79c11012005-09-26 04:44:35 +00002629 CI->getType());
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002630 DEBUG(dbgs() << "Found a Cast! Simplifying: " << *InstResult
Michael Gottesmandcf66952013-01-11 23:08:52 +00002631 << "\n");
Chris Lattner79c11012005-09-26 04:44:35 +00002632 } else if (SelectInst *SI = dyn_cast<SelectInst>(CurInst)) {
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002633 InstResult = ConstantExpr::getSelect(getVal(SI->getOperand(0)),
2634 getVal(SI->getOperand(1)),
2635 getVal(SI->getOperand(2)));
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002636 DEBUG(dbgs() << "Found a Select! Simplifying: " << *InstResult
Michael Gottesmandcf66952013-01-11 23:08:52 +00002637 << "\n");
Chris Lattner04de1cf2005-09-26 05:15:37 +00002638 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurInst)) {
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002639 Constant *P = getVal(GEP->getOperand(0));
Chris Lattner55eb1c42007-01-31 04:40:53 +00002640 SmallVector<Constant*, 8> GEPOps;
Gabor Greif5e463212008-05-29 01:59:18 +00002641 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end();
2642 i != e; ++i)
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002643 GEPOps.push_back(getVal(*i));
Jay Foad4b5e2072011-07-21 15:15:37 +00002644 InstResult =
2645 ConstantExpr::getGetElementPtr(P, GEPOps,
2646 cast<GEPOperator>(GEP)->isInBounds());
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002647 DEBUG(dbgs() << "Found a GEP! Simplifying: " << *InstResult
Michael Gottesmandcf66952013-01-11 23:08:52 +00002648 << "\n");
Chris Lattner04de1cf2005-09-26 05:15:37 +00002649 } else if (LoadInst *LI = dyn_cast<LoadInst>(CurInst)) {
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002650
2651 if (!LI->isSimple()) {
Michael Gottesmandcf66952013-01-11 23:08:52 +00002652 DEBUG(dbgs() << "Found a Load! Not a simple load, can not evaluate.\n");
2653 return false; // no volatile/atomic accesses.
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002654 }
2655
Nick Lewyckya641c072012-02-21 22:08:06 +00002656 Constant *Ptr = getVal(LI->getOperand(0));
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002657 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
Nick Lewyckya641c072012-02-21 22:08:06 +00002658 Ptr = ConstantFoldConstantExpression(CE, TD, TLI);
Michael Gottesmandcf66952013-01-11 23:08:52 +00002659 DEBUG(dbgs() << "Found a constant pointer expression, constant "
2660 "folding: " << *Ptr << "\n");
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002661 }
Nick Lewyckya641c072012-02-21 22:08:06 +00002662 InstResult = ComputeLoadResult(Ptr);
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002663 if (InstResult == 0) {
Michael Gottesmandcf66952013-01-11 23:08:52 +00002664 DEBUG(dbgs() << "Failed to compute load result. Can not evaluate load."
2665 "\n");
2666 return false; // Could not evaluate load.
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002667 }
2668
2669 DEBUG(dbgs() << "Evaluated load: " << *InstResult << "\n");
Chris Lattnera22fdb02005-09-26 17:07:09 +00002670 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(CurInst)) {
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002671 if (AI->isArrayAllocation()) {
Michael Gottesmandcf66952013-01-11 23:08:52 +00002672 DEBUG(dbgs() << "Found an array alloca. Can not evaluate.\n");
2673 return false; // Cannot handle array allocs.
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002674 }
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002675 Type *Ty = AI->getType()->getElementType();
Chris Lattner7b550cc2009-11-06 04:27:31 +00002676 AllocaTmps.push_back(new GlobalVariable(Ty, false,
Chris Lattnera22fdb02005-09-26 17:07:09 +00002677 GlobalValue::InternalLinkage,
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002678 UndefValue::get(Ty),
Chris Lattnera22fdb02005-09-26 17:07:09 +00002679 AI->getName()));
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002680 InstResult = AllocaTmps.back();
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002681 DEBUG(dbgs() << "Found an alloca. Result: " << *InstResult << "\n");
Nick Lewycky132bd9c2012-02-12 05:09:35 +00002682 } else if (isa<CallInst>(CurInst) || isa<InvokeInst>(CurInst)) {
2683 CallSite CS(CurInst);
Devang Patel412a4462009-03-09 23:04:12 +00002684
2685 // Debug info can safely be ignored here.
Nick Lewycky132bd9c2012-02-12 05:09:35 +00002686 if (isa<DbgInfoIntrinsic>(CS.getInstruction())) {
Michael Gottesmandcf66952013-01-11 23:08:52 +00002687 DEBUG(dbgs() << "Ignoring debug info.\n");
Devang Patel412a4462009-03-09 23:04:12 +00002688 ++CurInst;
2689 continue;
2690 }
2691
Chris Lattner7cd580f2006-07-07 21:37:01 +00002692 // Cannot handle inline asm.
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002693 if (isa<InlineAsm>(CS.getCalledValue())) {
Michael Gottesmandcf66952013-01-11 23:08:52 +00002694 DEBUG(dbgs() << "Found inline asm, can not evaluate.\n");
2695 return false;
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002696 }
Chris Lattner7cd580f2006-07-07 21:37:01 +00002697
Nick Lewycky81266c52012-02-17 06:59:21 +00002698 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CS.getInstruction())) {
2699 if (MemSetInst *MSI = dyn_cast<MemSetInst>(II)) {
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002700 if (MSI->isVolatile()) {
Michael Gottesmandcf66952013-01-11 23:08:52 +00002701 DEBUG(dbgs() << "Can not optimize a volatile memset " <<
2702 "intrinsic.\n");
2703 return false;
2704 }
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002705 Constant *Ptr = getVal(MSI->getDest());
2706 Constant *Val = getVal(MSI->getValue());
2707 Constant *DestVal = ComputeLoadResult(getVal(Ptr));
Nick Lewycky81266c52012-02-17 06:59:21 +00002708 if (Val->isNullValue() && DestVal && DestVal->isNullValue()) {
2709 // This memset is a no-op.
Michael Gottesmandcf66952013-01-11 23:08:52 +00002710 DEBUG(dbgs() << "Ignoring no-op memset.\n");
Nick Lewycky81266c52012-02-17 06:59:21 +00002711 ++CurInst;
2712 continue;
2713 }
2714 }
2715
2716 if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
2717 II->getIntrinsicID() == Intrinsic::lifetime_end) {
Michael Gottesmandcf66952013-01-11 23:08:52 +00002718 DEBUG(dbgs() << "Ignoring lifetime intrinsic.\n");
Nick Lewycky81266c52012-02-17 06:59:21 +00002719 ++CurInst;
2720 continue;
2721 }
2722
2723 if (II->getIntrinsicID() == Intrinsic::invariant_start) {
2724 // We don't insert an entry into Values, as it doesn't have a
2725 // meaningful return value.
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002726 if (!II->use_empty()) {
Michael Gottesmandcf66952013-01-11 23:08:52 +00002727 DEBUG(dbgs() << "Found unused invariant_start. Cant evaluate.\n");
Nick Lewycky81266c52012-02-17 06:59:21 +00002728 return false;
Michael Gottesmandcf66952013-01-11 23:08:52 +00002729 }
Nick Lewycky81266c52012-02-17 06:59:21 +00002730 ConstantInt *Size = cast<ConstantInt>(II->getArgOperand(0));
Nick Lewycky0ef05572012-02-20 23:32:26 +00002731 Value *PtrArg = getVal(II->getArgOperand(1));
2732 Value *Ptr = PtrArg->stripPointerCasts();
2733 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr)) {
2734 Type *ElemTy = cast<PointerType>(GV->getType())->getElementType();
Nick Lewyckyb97b1622013-07-25 02:55:14 +00002735 if (TD && !Size->isAllOnesValue() &&
Nick Lewycky0ef05572012-02-20 23:32:26 +00002736 Size->getValue().getLimitedValue() >=
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002737 TD->getTypeStoreSize(ElemTy)) {
Nick Lewycky81266c52012-02-17 06:59:21 +00002738 Invariants.insert(GV);
Michael Gottesmandcf66952013-01-11 23:08:52 +00002739 DEBUG(dbgs() << "Found a global var that is an invariant: " << *GV
2740 << "\n");
2741 } else {
2742 DEBUG(dbgs() << "Found a global var, but can not treat it as an "
2743 "invariant.\n");
2744 }
Nick Lewycky81266c52012-02-17 06:59:21 +00002745 }
2746 // Continue even if we do nothing.
Nick Lewycky1f237b02011-05-29 18:41:56 +00002747 ++CurInst;
2748 continue;
2749 }
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002750
Michael Gottesmandcf66952013-01-11 23:08:52 +00002751 DEBUG(dbgs() << "Unknown intrinsic. Can not evaluate.\n");
Nick Lewycky1f237b02011-05-29 18:41:56 +00002752 return false;
2753 }
2754
Chris Lattnercd271422005-09-27 04:45:34 +00002755 // Resolve function pointers.
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002756 Function *Callee = dyn_cast<Function>(getVal(CS.getCalledValue()));
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002757 if (!Callee || Callee->mayBeOverridden()) {
Michael Gottesmandcf66952013-01-11 23:08:52 +00002758 DEBUG(dbgs() << "Can not resolve function pointer.\n");
Nick Lewycky132bd9c2012-02-12 05:09:35 +00002759 return false; // Cannot resolve.
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002760 }
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002761
Duncan Sandsfa6a1cf2009-08-17 14:33:27 +00002762 SmallVector<Constant*, 8> Formals;
Nick Lewycky132bd9c2012-02-12 05:09:35 +00002763 for (User::op_iterator i = CS.arg_begin(), e = CS.arg_end(); i != e; ++i)
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002764 Formals.push_back(getVal(*i));
Duncan Sandsfa6a1cf2009-08-17 14:33:27 +00002765
Reid Spencer5cbf9852007-01-30 20:08:39 +00002766 if (Callee->isDeclaration()) {
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002767 // If this is a function we can constant fold, do it.
Chad Rosier00737bd2011-12-01 21:29:16 +00002768 if (Constant *C = ConstantFoldCall(Callee, Formals, TLI)) {
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002769 InstResult = C;
Michael Gottesmandcf66952013-01-11 23:08:52 +00002770 DEBUG(dbgs() << "Constant folded function call. Result: " <<
2771 *InstResult << "\n");
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002772 } else {
Michael Gottesmandcf66952013-01-11 23:08:52 +00002773 DEBUG(dbgs() << "Can not constant fold function call.\n");
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002774 return false;
2775 }
2776 } else {
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002777 if (Callee->getFunctionType()->isVarArg()) {
Michael Gottesmandcf66952013-01-11 23:08:52 +00002778 DEBUG(dbgs() << "Can not constant fold vararg function call.\n");
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002779 return false;
Michael Gottesmandcf66952013-01-11 23:08:52 +00002780 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002781
Benjamin Kramer08135892013-01-12 15:34:31 +00002782 Constant *RetVal = 0;
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002783 // Execute the call, if successful, use the return value.
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002784 ValueStack.push_back(new DenseMap<Value*, Constant*>);
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002785 if (!EvaluateFunction(Callee, RetVal, Formals)) {
Michael Gottesmandcf66952013-01-11 23:08:52 +00002786 DEBUG(dbgs() << "Failed to evaluate function.\n");
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002787 return false;
Michael Gottesmandcf66952013-01-11 23:08:52 +00002788 }
Benjamin Kramer3bbf2b62012-02-27 12:48:24 +00002789 delete ValueStack.pop_back_val();
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002790 InstResult = RetVal;
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002791
Michael Gottesmandcf66952013-01-11 23:08:52 +00002792 if (InstResult != NULL) {
2793 DEBUG(dbgs() << "Successfully evaluated function. Result: " <<
2794 InstResult << "\n\n");
2795 } else {
2796 DEBUG(dbgs() << "Successfully evaluated function. Result: 0\n\n");
2797 }
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002798 }
Reid Spencer3ed469c2006-11-02 20:25:50 +00002799 } else if (isa<TerminatorInst>(CurInst)) {
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002800 DEBUG(dbgs() << "Found a terminator instruction.\n");
2801
Chris Lattnercdf98be2005-09-26 04:57:38 +00002802 if (BranchInst *BI = dyn_cast<BranchInst>(CurInst)) {
2803 if (BI->isUnconditional()) {
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002804 NextBB = BI->getSuccessor(0);
Chris Lattnercdf98be2005-09-26 04:57:38 +00002805 } else {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002806 ConstantInt *Cond =
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002807 dyn_cast<ConstantInt>(getVal(BI->getCondition()));
Chris Lattner97d1fad2007-01-12 18:30:11 +00002808 if (!Cond) return false; // Cannot determine.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002809
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002810 NextBB = BI->getSuccessor(!Cond->getZExtValue());
Chris Lattnercdf98be2005-09-26 04:57:38 +00002811 }
2812 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(CurInst)) {
2813 ConstantInt *Val =
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002814 dyn_cast<ConstantInt>(getVal(SI->getCondition()));
Chris Lattnercd271422005-09-27 04:45:34 +00002815 if (!Val) return false; // Cannot determine.
Stepan Dyatkovskiyc10fa6c2012-03-08 07:06:20 +00002816 NextBB = SI->findCaseValue(Val).getCaseSuccessor();
Chris Lattnerb3d5a652009-10-29 05:51:50 +00002817 } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(CurInst)) {
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002818 Value *Val = getVal(IBI->getAddress())->stripPointerCasts();
Chris Lattnerb3d5a652009-10-29 05:51:50 +00002819 if (BlockAddress *BA = dyn_cast<BlockAddress>(Val))
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002820 NextBB = BA->getBasicBlock();
Chris Lattnercdfc9402009-11-01 01:27:45 +00002821 else
2822 return false; // Cannot determine.
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002823 } else if (isa<ReturnInst>(CurInst)) {
2824 NextBB = 0;
Chris Lattnercdf98be2005-09-26 04:57:38 +00002825 } else {
Bill Wendlingdccc03b2011-07-31 06:30:59 +00002826 // invoke, unwind, resume, unreachable.
Michael Gottesmandcf66952013-01-11 23:08:52 +00002827 DEBUG(dbgs() << "Can not handle terminator.");
Chris Lattnercd271422005-09-27 04:45:34 +00002828 return false; // Cannot handle this terminator.
Chris Lattnercdf98be2005-09-26 04:57:38 +00002829 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002830
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002831 // We succeeded at evaluating this block!
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002832 DEBUG(dbgs() << "Successfully evaluated block.\n");
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002833 return true;
Chris Lattner79c11012005-09-26 04:44:35 +00002834 } else {
Chris Lattner79c11012005-09-26 04:44:35 +00002835 // Did not know how to evaluate this!
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002836 DEBUG(dbgs() << "Failed to evaluate block due to unhandled instruction."
Michael Gottesmandcf66952013-01-11 23:08:52 +00002837 "\n");
Chris Lattnercd271422005-09-27 04:45:34 +00002838 return false;
Chris Lattner79c11012005-09-26 04:44:35 +00002839 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002840
Chris Lattner1945d582010-12-07 04:33:29 +00002841 if (!CurInst->use_empty()) {
2842 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(InstResult))
Chad Rosieraab8e282011-12-02 01:26:24 +00002843 InstResult = ConstantFoldConstantExpression(CE, TD, TLI);
Jakub Staszak582088c2012-12-06 21:57:16 +00002844
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002845 setVal(CurInst, InstResult);
Chris Lattner1945d582010-12-07 04:33:29 +00002846 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002847
Dan Gohmanf1ce79f2012-03-13 18:01:37 +00002848 // If we just processed an invoke, we finished evaluating the block.
2849 if (InvokeInst *II = dyn_cast<InvokeInst>(CurInst)) {
2850 NextBB = II->getNormalDest();
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002851 DEBUG(dbgs() << "Found an invoke instruction. Finished Block.\n\n");
Dan Gohmanf1ce79f2012-03-13 18:01:37 +00002852 return true;
2853 }
2854
Chris Lattner79c11012005-09-26 04:44:35 +00002855 // Advance program counter.
2856 ++CurInst;
2857 }
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002858}
2859
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002860/// EvaluateFunction - Evaluate a call to function F, returning true if
2861/// successful, false if we can't evaluate it. ActualArgs contains the formal
2862/// arguments for the function.
Nick Lewycky7fa76772012-02-20 03:25:59 +00002863bool Evaluator::EvaluateFunction(Function *F, Constant *&RetVal,
2864 const SmallVectorImpl<Constant*> &ActualArgs) {
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002865 // Check to see if this function is already executing (recursion). If so,
2866 // bail out. TODO: we might want to accept limited recursion.
2867 if (std::find(CallStack.begin(), CallStack.end(), F) != CallStack.end())
2868 return false;
2869
2870 CallStack.push_back(F);
2871
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002872 // Initialize arguments to the incoming values specified.
2873 unsigned ArgNo = 0;
2874 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); AI != E;
2875 ++AI, ++ArgNo)
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002876 setVal(AI, ActualArgs[ArgNo]);
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002877
2878 // ExecutedBlocks - We only handle non-looping, non-recursive code. As such,
2879 // we can only evaluate any one basic block at most once. This set keeps
2880 // track of what we have executed so we can detect recursive cases etc.
2881 SmallPtrSet<BasicBlock*, 32> ExecutedBlocks;
2882
2883 // CurBB - The current basic block we're evaluating.
2884 BasicBlock *CurBB = F->begin();
2885
Nick Lewycky8e4ba6b2012-02-12 00:47:24 +00002886 BasicBlock::iterator CurInst = CurBB->begin();
2887
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002888 while (1) {
Duncan Sands4b794f82012-02-23 08:23:06 +00002889 BasicBlock *NextBB = 0; // Initialized to avoid compiler warnings.
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002890 DEBUG(dbgs() << "Trying to evaluate BB: " << *CurBB << "\n");
2891
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002892 if (!EvaluateBlock(CurInst, NextBB))
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002893 return false;
2894
2895 if (NextBB == 0) {
2896 // Successfully running until there's no next block means that we found
2897 // the return. Fill it the return value and pop the call stack.
2898 ReturnInst *RI = cast<ReturnInst>(CurBB->getTerminator());
2899 if (RI->getNumOperands())
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002900 RetVal = getVal(RI->getOperand(0));
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002901 CallStack.pop_back();
2902 return true;
2903 }
2904
2905 // Okay, we succeeded in evaluating this control flow. See if we have
2906 // executed the new block before. If so, we have a looping function,
2907 // which we cannot evaluate in reasonable time.
2908 if (!ExecutedBlocks.insert(NextBB))
2909 return false; // looped!
2910
2911 // Okay, we have never been in this block before. Check to see if there
2912 // are any PHI nodes. If so, evaluate them with information about where
2913 // we came from.
2914 PHINode *PN = 0;
Nick Lewycky8e4ba6b2012-02-12 00:47:24 +00002915 for (CurInst = NextBB->begin();
2916 (PN = dyn_cast<PHINode>(CurInst)); ++CurInst)
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002917 setVal(PN, getVal(PN->getIncomingValueForBlock(CurBB)));
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002918
2919 // Advance to the next block.
2920 CurBB = NextBB;
2921 }
2922}
2923
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002924/// EvaluateStaticConstructor - Evaluate static constructors in the function, if
2925/// we can. Return true if we can, false otherwise.
Micah Villmow3574eca2012-10-08 16:38:25 +00002926static bool EvaluateStaticConstructor(Function *F, const DataLayout *TD,
Chad Rosier00737bd2011-12-01 21:29:16 +00002927 const TargetLibraryInfo *TLI) {
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002928 // Call the function.
Nick Lewycky7fa76772012-02-20 03:25:59 +00002929 Evaluator Eval(TD, TLI);
Chris Lattnercd271422005-09-27 04:45:34 +00002930 Constant *RetValDummy;
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002931 bool EvalSuccess = Eval.EvaluateFunction(F, RetValDummy,
2932 SmallVector<Constant*, 0>());
Jakub Staszak582088c2012-12-06 21:57:16 +00002933
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002934 if (EvalSuccess) {
Chris Lattnera22fdb02005-09-26 17:07:09 +00002935 // We succeeded at evaluation: commit the result.
David Greene3215b0e2010-01-05 01:28:05 +00002936 DEBUG(dbgs() << "FULLY EVALUATED GLOBAL CTOR FUNCTION '"
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002937 << F->getName() << "' to " << Eval.getMutatedMemory().size()
Daniel Dunbarce63ffb2009-07-25 00:23:56 +00002938 << " stores.\n");
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002939 for (DenseMap<Constant*, Constant*>::const_iterator I =
2940 Eval.getMutatedMemory().begin(), E = Eval.getMutatedMemory().end();
Nick Lewycky3eab3c42012-06-24 04:07:14 +00002941 I != E; ++I)
Chris Lattner7b550cc2009-11-06 04:27:31 +00002942 CommitValueTo(I->second, I->first);
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002943 for (SmallPtrSet<GlobalVariable*, 8>::const_iterator I =
2944 Eval.getInvariants().begin(), E = Eval.getInvariants().end();
2945 I != E; ++I)
Nick Lewycky81266c52012-02-17 06:59:21 +00002946 (*I)->setConstant(true);
Chris Lattnera22fdb02005-09-26 17:07:09 +00002947 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002948
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002949 return EvalSuccess;
Chris Lattner79c11012005-09-26 04:44:35 +00002950}
2951
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002952/// OptimizeGlobalCtorsList - Simplify and evaluation global ctors if possible.
2953/// Return true if anything changed.
2954bool GlobalOpt::OptimizeGlobalCtorsList(GlobalVariable *&GCL) {
2955 std::vector<Function*> Ctors = ParseGlobalCtors(GCL);
2956 bool MadeChange = false;
2957 if (Ctors.empty()) return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002958
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002959 // Loop over global ctors, optimizing them when we can.
2960 for (unsigned i = 0; i != Ctors.size(); ++i) {
2961 Function *F = Ctors[i];
2962 // Found a null terminator in the middle of the list, prune off the rest of
2963 // the list.
Chris Lattner7d8e58f2005-09-26 02:19:27 +00002964 if (F == 0) {
2965 if (i != Ctors.size()-1) {
2966 Ctors.resize(i+1);
2967 MadeChange = true;
2968 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002969 break;
2970 }
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002971 DEBUG(dbgs() << "Optimizing Global Constructor: " << *F << "\n");
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002972
Chris Lattner79c11012005-09-26 04:44:35 +00002973 // We cannot simplify external ctor functions.
2974 if (F->empty()) continue;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002975
Chris Lattner79c11012005-09-26 04:44:35 +00002976 // If we can evaluate the ctor at compile time, do.
Chad Rosier00737bd2011-12-01 21:29:16 +00002977 if (EvaluateStaticConstructor(F, TD, TLI)) {
Chris Lattner79c11012005-09-26 04:44:35 +00002978 Ctors.erase(Ctors.begin()+i);
2979 MadeChange = true;
2980 --i;
2981 ++NumCtorsEvaluated;
2982 continue;
2983 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002984 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002985
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002986 if (!MadeChange) return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002987
Chris Lattner7b550cc2009-11-06 04:27:31 +00002988 GCL = InstallGlobalCtors(GCL, Ctors);
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002989 return true;
2990}
2991
Benjamin Kramer0d293e42013-09-22 14:09:50 +00002992static int compareNames(Constant *const *A, Constant *const *B) {
2993 return (*A)->getName().compare((*B)->getName());
Rafael Espindolad1b6ca22013-06-11 17:48:06 +00002994}
Rafael Espindola95f88532013-05-09 17:22:59 +00002995
Rafael Espindolad1b6ca22013-06-11 17:48:06 +00002996static void setUsedInitializer(GlobalVariable &V,
2997 SmallPtrSet<GlobalValue *, 8> Init) {
Rafael Espindola64f2f912013-07-20 23:33:15 +00002998 if (Init.empty()) {
2999 V.eraseFromParent();
3000 return;
3001 }
3002
Rafael Espindolad1b6ca22013-06-11 17:48:06 +00003003 SmallVector<llvm::Constant *, 8> UsedArray;
3004 PointerType *Int8PtrTy = Type::getInt8PtrTy(V.getContext());
Rafael Espindola95f88532013-05-09 17:22:59 +00003005
Rafael Espindolad1b6ca22013-06-11 17:48:06 +00003006 for (SmallPtrSet<GlobalValue *, 8>::iterator I = Init.begin(), E = Init.end();
3007 I != E; ++I) {
3008 Constant *Cast = llvm::ConstantExpr::getBitCast(*I, Int8PtrTy);
3009 UsedArray.push_back(Cast);
Rafael Espindola95f88532013-05-09 17:22:59 +00003010 }
Rafael Espindolad1b6ca22013-06-11 17:48:06 +00003011 // Sort to get deterministic order.
3012 array_pod_sort(UsedArray.begin(), UsedArray.end(), compareNames);
3013 ArrayType *ATy = ArrayType::get(Int8PtrTy, UsedArray.size());
Rafael Espindola95f88532013-05-09 17:22:59 +00003014
Rafael Espindolad1b6ca22013-06-11 17:48:06 +00003015 Module *M = V.getParent();
3016 V.removeFromParent();
3017 GlobalVariable *NV =
3018 new GlobalVariable(*M, ATy, false, llvm::GlobalValue::AppendingLinkage,
3019 llvm::ConstantArray::get(ATy, UsedArray), "");
3020 NV->takeName(&V);
3021 NV->setSection("llvm.metadata");
3022 delete &V;
Rafael Espindola95f88532013-05-09 17:22:59 +00003023}
3024
Rafael Espindolad1b6ca22013-06-11 17:48:06 +00003025namespace {
Rafael Espindola70968312013-07-19 18:44:51 +00003026/// \brief An easy to access representation of llvm.used and llvm.compiler.used.
Rafael Espindolad1b6ca22013-06-11 17:48:06 +00003027class LLVMUsed {
3028 SmallPtrSet<GlobalValue *, 8> Used;
3029 SmallPtrSet<GlobalValue *, 8> CompilerUsed;
3030 GlobalVariable *UsedV;
3031 GlobalVariable *CompilerUsedV;
3032
3033public:
Rafael Espindola2d680822013-07-25 02:50:08 +00003034 LLVMUsed(Module &M) {
Rafael Espindola4ef7eaf2013-07-25 03:23:25 +00003035 UsedV = collectUsedGlobalVariables(M, Used, false);
3036 CompilerUsedV = collectUsedGlobalVariables(M, CompilerUsed, true);
Rafael Espindola95f88532013-05-09 17:22:59 +00003037 }
Rafael Espindolad1b6ca22013-06-11 17:48:06 +00003038 typedef SmallPtrSet<GlobalValue *, 8>::iterator iterator;
3039 iterator usedBegin() { return Used.begin(); }
3040 iterator usedEnd() { return Used.end(); }
3041 iterator compilerUsedBegin() { return CompilerUsed.begin(); }
3042 iterator compilerUsedEnd() { return CompilerUsed.end(); }
3043 bool usedCount(GlobalValue *GV) const { return Used.count(GV); }
3044 bool compilerUsedCount(GlobalValue *GV) const {
3045 return CompilerUsed.count(GV);
3046 }
3047 bool usedErase(GlobalValue *GV) { return Used.erase(GV); }
3048 bool compilerUsedErase(GlobalValue *GV) { return CompilerUsed.erase(GV); }
3049 bool usedInsert(GlobalValue *GV) { return Used.insert(GV); }
3050 bool compilerUsedInsert(GlobalValue *GV) { return CompilerUsed.insert(GV); }
Rafael Espindola95f88532013-05-09 17:22:59 +00003051
Rafael Espindolad1b6ca22013-06-11 17:48:06 +00003052 void syncVariablesAndSets() {
3053 if (UsedV)
3054 setUsedInitializer(*UsedV, Used);
3055 if (CompilerUsedV)
3056 setUsedInitializer(*CompilerUsedV, CompilerUsed);
3057 }
3058};
Rafael Espindola95f88532013-05-09 17:22:59 +00003059}
3060
Rafael Espindolad1b6ca22013-06-11 17:48:06 +00003061static bool hasUseOtherThanLLVMUsed(GlobalAlias &GA, const LLVMUsed &U) {
3062 if (GA.use_empty()) // No use at all.
3063 return false;
3064
3065 assert((!U.usedCount(&GA) || !U.compilerUsedCount(&GA)) &&
3066 "We should have removed the duplicated "
Rafael Espindola70968312013-07-19 18:44:51 +00003067 "element from llvm.compiler.used");
Rafael Espindolad1b6ca22013-06-11 17:48:06 +00003068 if (!GA.hasOneUse())
3069 // Strictly more than one use. So at least one is not in llvm.used and
Rafael Espindola70968312013-07-19 18:44:51 +00003070 // llvm.compiler.used.
Rafael Espindolad1b6ca22013-06-11 17:48:06 +00003071 return true;
3072
Rafael Espindola70968312013-07-19 18:44:51 +00003073 // Exactly one use. Check if it is in llvm.used or llvm.compiler.used.
Rafael Espindolad1b6ca22013-06-11 17:48:06 +00003074 return !U.usedCount(&GA) && !U.compilerUsedCount(&GA);
Rafael Espindola95f88532013-05-09 17:22:59 +00003075}
3076
Rafael Espindolad1b6ca22013-06-11 17:48:06 +00003077static bool hasMoreThanOneUseOtherThanLLVMUsed(GlobalValue &V,
3078 const LLVMUsed &U) {
3079 unsigned N = 2;
3080 assert((!U.usedCount(&V) || !U.compilerUsedCount(&V)) &&
3081 "We should have removed the duplicated "
Rafael Espindola70968312013-07-19 18:44:51 +00003082 "element from llvm.compiler.used");
Rafael Espindolad1b6ca22013-06-11 17:48:06 +00003083 if (U.usedCount(&V) || U.compilerUsedCount(&V))
3084 ++N;
3085 return V.hasNUsesOrMore(N);
3086}
3087
3088static bool mayHaveOtherReferences(GlobalAlias &GA, const LLVMUsed &U) {
3089 if (!GA.hasLocalLinkage())
3090 return true;
3091
3092 return U.usedCount(&GA) || U.compilerUsedCount(&GA);
3093}
3094
3095static bool hasUsesToReplace(GlobalAlias &GA, LLVMUsed &U, bool &RenameTarget) {
3096 RenameTarget = false;
Rafael Espindola95f88532013-05-09 17:22:59 +00003097 bool Ret = false;
Rafael Espindolad1b6ca22013-06-11 17:48:06 +00003098 if (hasUseOtherThanLLVMUsed(GA, U))
Rafael Espindola95f88532013-05-09 17:22:59 +00003099 Ret = true;
Rafael Espindolad1b6ca22013-06-11 17:48:06 +00003100
3101 // If the alias is externally visible, we may still be able to simplify it.
3102 if (!mayHaveOtherReferences(GA, U))
3103 return Ret;
3104
3105 // If the aliasee has internal linkage, give it the name and linkage
3106 // of the alias, and delete the alias. This turns:
3107 // define internal ... @f(...)
3108 // @a = alias ... @f
3109 // into:
3110 // define ... @a(...)
3111 Constant *Aliasee = GA.getAliasee();
3112 GlobalValue *Target = cast<GlobalValue>(Aliasee->stripPointerCasts());
3113 if (!Target->hasLocalLinkage())
3114 return Ret;
3115
3116 // Do not perform the transform if multiple aliases potentially target the
3117 // aliasee. This check also ensures that it is safe to replace the section
3118 // and other attributes of the aliasee with those of the alias.
3119 if (hasMoreThanOneUseOtherThanLLVMUsed(*Target, U))
3120 return Ret;
3121
3122 RenameTarget = true;
3123 return true;
Rafael Espindola95f88532013-05-09 17:22:59 +00003124}
3125
Duncan Sandsfc5940d2009-03-06 10:21:56 +00003126bool GlobalOpt::OptimizeGlobalAliases(Module &M) {
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00003127 bool Changed = false;
Rafael Espindolad1b6ca22013-06-11 17:48:06 +00003128 LLVMUsed Used(M);
3129
3130 for (SmallPtrSet<GlobalValue *, 8>::iterator I = Used.usedBegin(),
3131 E = Used.usedEnd();
3132 I != E; ++I)
3133 Used.compilerUsedErase(*I);
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00003134
Duncan Sands177d84e2009-01-07 20:01:06 +00003135 for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end();
Duncan Sands4782b302009-02-15 09:56:08 +00003136 I != E;) {
3137 Module::alias_iterator J = I++;
Duncan Sandsfc5940d2009-03-06 10:21:56 +00003138 // Aliases without names cannot be referenced outside this module.
3139 if (!J->hasName() && !J->isDeclaration())
3140 J->setLinkage(GlobalValue::InternalLinkage);
Duncan Sands4782b302009-02-15 09:56:08 +00003141 // If the aliasee may change at link time, nothing can be done - bail out.
3142 if (J->mayBeOverridden())
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00003143 continue;
3144
Duncan Sands4782b302009-02-15 09:56:08 +00003145 Constant *Aliasee = J->getAliasee();
3146 GlobalValue *Target = cast<GlobalValue>(Aliasee->stripPointerCasts());
Duncan Sands95c5d0f2009-02-18 17:55:38 +00003147 Target->removeDeadConstantUsers();
Duncan Sands4782b302009-02-15 09:56:08 +00003148
3149 // Make all users of the alias use the aliasee instead.
Rafael Espindolad1b6ca22013-06-11 17:48:06 +00003150 bool RenameTarget;
3151 if (!hasUsesToReplace(*J, Used, RenameTarget))
Rafael Espindola95f88532013-05-09 17:22:59 +00003152 continue;
Duncan Sands4782b302009-02-15 09:56:08 +00003153
Rafael Espindolad1b6ca22013-06-11 17:48:06 +00003154 J->replaceAllUsesWith(Aliasee);
3155 ++NumAliasesResolved;
3156 Changed = true;
Duncan Sands4782b302009-02-15 09:56:08 +00003157
Rafael Espindolad1b6ca22013-06-11 17:48:06 +00003158 if (RenameTarget) {
Duncan Sands7a154cf2009-12-08 10:10:20 +00003159 // Give the aliasee the name, linkage and other attributes of the alias.
3160 Target->takeName(J);
3161 Target->setLinkage(J->getLinkage());
3162 Target->GlobalValue::copyAttributesFrom(J);
Rafael Espindolad1b6ca22013-06-11 17:48:06 +00003163
3164 if (Used.usedErase(J))
3165 Used.usedInsert(Target);
3166
3167 if (Used.compilerUsedErase(J))
3168 Used.compilerUsedInsert(Target);
Rafael Espindola100fbdd2013-06-12 16:45:47 +00003169 } else if (mayHaveOtherReferences(*J, Used))
Rafael Espindolad1b6ca22013-06-11 17:48:06 +00003170 continue;
3171
Duncan Sands4782b302009-02-15 09:56:08 +00003172 // Delete the alias.
3173 M.getAliasList().erase(J);
3174 ++NumAliasesRemoved;
3175 Changed = true;
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00003176 }
3177
Rafael Espindolad1b6ca22013-06-11 17:48:06 +00003178 Used.syncVariablesAndSets();
3179
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00003180 return Changed;
3181}
Chris Lattnerb1ab4582005-09-26 01:43:45 +00003182
Nick Lewycky6a7df9a2012-02-12 02:15:20 +00003183static Function *FindCXAAtExit(Module &M, TargetLibraryInfo *TLI) {
3184 if (!TLI->has(LibFunc::cxa_atexit))
Nick Lewycky6f160d32012-02-12 02:17:18 +00003185 return 0;
Nick Lewycky6a7df9a2012-02-12 02:15:20 +00003186
3187 Function *Fn = M.getFunction(TLI->getName(LibFunc::cxa_atexit));
Jakub Staszak582088c2012-12-06 21:57:16 +00003188
Anders Carlssona201c4c2011-03-20 17:59:11 +00003189 if (!Fn)
3190 return 0;
Nick Lewycky6a7df9a2012-02-12 02:15:20 +00003191
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003192 FunctionType *FTy = Fn->getFunctionType();
Jakub Staszak582088c2012-12-06 21:57:16 +00003193
3194 // Checking that the function has the right return type, the right number of
Anders Carlsson1f7c7ba2011-03-20 19:51:13 +00003195 // parameters and that they all have pointer types should be enough.
3196 if (!FTy->getReturnType()->isIntegerTy() ||
3197 FTy->getNumParams() != 3 ||
Anders Carlssona201c4c2011-03-20 17:59:11 +00003198 !FTy->getParamType(0)->isPointerTy() ||
3199 !FTy->getParamType(1)->isPointerTy() ||
3200 !FTy->getParamType(2)->isPointerTy())
3201 return 0;
3202
3203 return Fn;
3204}
3205
3206/// cxxDtorIsEmpty - Returns whether the given function is an empty C++
3207/// destructor and can therefore be eliminated.
3208/// Note that we assume that other optimization passes have already simplified
3209/// the code so we only look for a function with a single basic block, where
Benjamin Kramerc1322a12012-02-09 16:28:15 +00003210/// the only allowed instructions are 'ret', 'call' to an empty C++ dtor and
3211/// other side-effect free instructions.
Anders Carlsson372ec6a2011-03-20 20:16:43 +00003212static bool cxxDtorIsEmpty(const Function &Fn,
3213 SmallPtrSet<const Function *, 8> &CalledFunctions) {
Anders Carlsson1f7c7ba2011-03-20 19:51:13 +00003214 // FIXME: We could eliminate C++ destructors if they're readonly/readnone and
Nick Lewycky35ee1c92011-03-21 02:26:01 +00003215 // nounwind, but that doesn't seem worth doing.
Anders Carlsson1f7c7ba2011-03-20 19:51:13 +00003216 if (Fn.isDeclaration())
3217 return false;
Anders Carlssona201c4c2011-03-20 17:59:11 +00003218
3219 if (++Fn.begin() != Fn.end())
3220 return false;
3221
3222 const BasicBlock &EntryBlock = Fn.getEntryBlock();
3223 for (BasicBlock::const_iterator I = EntryBlock.begin(), E = EntryBlock.end();
3224 I != E; ++I) {
3225 if (const CallInst *CI = dyn_cast<CallInst>(I)) {
Anders Carlssonb12caf32011-03-21 14:54:40 +00003226 // Ignore debug intrinsics.
3227 if (isa<DbgInfoIntrinsic>(CI))
3228 continue;
3229
Anders Carlssona201c4c2011-03-20 17:59:11 +00003230 const Function *CalledFn = CI->getCalledFunction();
3231
3232 if (!CalledFn)
3233 return false;
3234
Anders Carlsson807bc2a2011-03-22 03:21:01 +00003235 SmallPtrSet<const Function *, 8> NewCalledFunctions(CalledFunctions);
3236
Anders Carlsson1f7c7ba2011-03-20 19:51:13 +00003237 // Don't treat recursive functions as empty.
Anders Carlsson807bc2a2011-03-22 03:21:01 +00003238 if (!NewCalledFunctions.insert(CalledFn))
Anders Carlsson1f7c7ba2011-03-20 19:51:13 +00003239 return false;
3240
Anders Carlsson807bc2a2011-03-22 03:21:01 +00003241 if (!cxxDtorIsEmpty(*CalledFn, NewCalledFunctions))
Anders Carlssona201c4c2011-03-20 17:59:11 +00003242 return false;
3243 } else if (isa<ReturnInst>(*I))
Benjamin Kramerd4692742012-02-09 14:26:06 +00003244 return true; // We're done.
3245 else if (I->mayHaveSideEffects())
3246 return false; // Destructor with side effects, bail.
Anders Carlssona201c4c2011-03-20 17:59:11 +00003247 }
3248
3249 return false;
3250}
3251
3252bool GlobalOpt::OptimizeEmptyGlobalCXXDtors(Function *CXAAtExitFn) {
3253 /// Itanium C++ ABI p3.3.5:
3254 ///
3255 /// After constructing a global (or local static) object, that will require
3256 /// destruction on exit, a termination function is registered as follows:
3257 ///
3258 /// extern "C" int __cxa_atexit ( void (*f)(void *), void *p, void *d );
3259 ///
3260 /// This registration, e.g. __cxa_atexit(f,p,d), is intended to cause the
3261 /// call f(p) when DSO d is unloaded, before all such termination calls
3262 /// registered before this one. It returns zero if registration is
Nick Lewycky35ee1c92011-03-21 02:26:01 +00003263 /// successful, nonzero on failure.
Anders Carlssona201c4c2011-03-20 17:59:11 +00003264
3265 // This pass will look for calls to __cxa_atexit where the function is trivial
3266 // and remove them.
3267 bool Changed = false;
3268
Jakub Staszak582088c2012-12-06 21:57:16 +00003269 for (Function::use_iterator I = CXAAtExitFn->use_begin(),
Anders Carlssona201c4c2011-03-20 17:59:11 +00003270 E = CXAAtExitFn->use_end(); I != E;) {
Anders Carlsson4f735ca2011-03-20 20:21:33 +00003271 // We're only interested in calls. Theoretically, we could handle invoke
3272 // instructions as well, but neither llvm-gcc nor clang generate invokes
3273 // to __cxa_atexit.
Anders Carlssonb12caf32011-03-21 14:54:40 +00003274 CallInst *CI = dyn_cast<CallInst>(*I++);
3275 if (!CI)
Anders Carlsson4f735ca2011-03-20 20:21:33 +00003276 continue;
3277
Jakub Staszak582088c2012-12-06 21:57:16 +00003278 Function *DtorFn =
Anders Carlssonb12caf32011-03-21 14:54:40 +00003279 dyn_cast<Function>(CI->getArgOperand(0)->stripPointerCasts());
Anders Carlssona201c4c2011-03-20 17:59:11 +00003280 if (!DtorFn)
3281 continue;
3282
Anders Carlsson372ec6a2011-03-20 20:16:43 +00003283 SmallPtrSet<const Function *, 8> CalledFunctions;
3284 if (!cxxDtorIsEmpty(*DtorFn, CalledFunctions))
Anders Carlssona201c4c2011-03-20 17:59:11 +00003285 continue;
3286
3287 // Just remove the call.
Anders Carlssonb12caf32011-03-21 14:54:40 +00003288 CI->replaceAllUsesWith(Constant::getNullValue(CI->getType()));
3289 CI->eraseFromParent();
Anders Carlsson1f7c7ba2011-03-20 19:51:13 +00003290
Anders Carlssona201c4c2011-03-20 17:59:11 +00003291 ++NumCXXDtorsRemoved;
3292
3293 Changed |= true;
3294 }
3295
3296 return Changed;
3297}
3298
Chris Lattner7a90b682004-10-07 04:16:33 +00003299bool GlobalOpt::runOnModule(Module &M) {
Chris Lattner079236d2004-02-25 21:34:36 +00003300 bool Changed = false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00003301
Micah Villmow3574eca2012-10-08 16:38:25 +00003302 TD = getAnalysisIfAvailable<DataLayout>();
Nick Lewycky6a7df9a2012-02-12 02:15:20 +00003303 TLI = &getAnalysis<TargetLibraryInfo>();
Nick Lewycky6a577f82012-02-12 01:13:18 +00003304
Chris Lattnerb1ab4582005-09-26 01:43:45 +00003305 // Try to find the llvm.globalctors list.
3306 GlobalVariable *GlobalCtors = FindGlobalCtors(M);
Chris Lattner7a90b682004-10-07 04:16:33 +00003307
Chris Lattner7a90b682004-10-07 04:16:33 +00003308 bool LocalChange = true;
3309 while (LocalChange) {
3310 LocalChange = false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00003311
Chris Lattnerb1ab4582005-09-26 01:43:45 +00003312 // Delete functions that are trivially dead, ccc -> fastcc
3313 LocalChange |= OptimizeFunctions(M);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00003314
Chris Lattnerb1ab4582005-09-26 01:43:45 +00003315 // Optimize global_ctors list.
3316 if (GlobalCtors)
3317 LocalChange |= OptimizeGlobalCtorsList(GlobalCtors);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00003318
Chris Lattnerb1ab4582005-09-26 01:43:45 +00003319 // Optimize non-address-taken globals.
3320 LocalChange |= OptimizeGlobalVars(M);
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00003321
3322 // Resolve aliases, when possible.
Duncan Sandsfc5940d2009-03-06 10:21:56 +00003323 LocalChange |= OptimizeGlobalAliases(M);
Anders Carlssona201c4c2011-03-20 17:59:11 +00003324
Manman Ren51502702013-05-14 21:52:44 +00003325 // Try to remove trivial global destructors if they are not removed
3326 // already.
3327 Function *CXAAtExitFn = FindCXAAtExit(M, TLI);
Anders Carlssona201c4c2011-03-20 17:59:11 +00003328 if (CXAAtExitFn)
3329 LocalChange |= OptimizeEmptyGlobalCXXDtors(CXAAtExitFn);
3330
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00003331 Changed |= LocalChange;
Chris Lattner7a90b682004-10-07 04:16:33 +00003332 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00003333
Chris Lattnerb1ab4582005-09-26 01:43:45 +00003334 // TODO: Move all global ctors functions to the end of the module for code
3335 // layout.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00003336
Chris Lattner079236d2004-02-25 21:34:36 +00003337 return Changed;
3338}