blob: 99766190deab8b8b964e79d5b27a2a826d2de2b5 [file] [log] [blame]
Chris Lattner25db5802004-10-07 04:16:33 +00001//===- GlobalOpt.cpp - Optimize Global Variables --------------------------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
Chris Lattner25db5802004-10-07 04:16:33 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-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 Brukmanb1c93172005-04-21 23:48:37 +00007//
Chris Lattner25db5802004-10-07 04:16:33 +00008//===----------------------------------------------------------------------===//
9//
10// 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.
13//
14//===----------------------------------------------------------------------===//
15
16#define DEBUG_TYPE "globalopt"
17#include "llvm/Transforms/IPO.h"
Chandler Carruthed0881b2012-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 Carruth9fb823b2013-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 Lattner25db5802004-10-07 04:16:33 +000033#include "llvm/Pass.h"
Duncan Sands85fab3a2008-02-18 17:32:13 +000034#include "llvm/Support/CallSite.h"
Chris Lattner024f4ab2007-01-30 23:46:24 +000035#include "llvm/Support/Debug.h"
Torok Edwin56d06592009-07-11 20:10:48 +000036#include "llvm/Support/ErrorHandling.h"
Chris Lattner26fe7eb2008-01-14 02:09:12 +000037#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner67ca6f632008-04-26 07:40:11 +000038#include "llvm/Support/MathExtras.h"
Daniel Dunbar0dd5e1e2009-07-25 00:23:56 +000039#include "llvm/Support/raw_ostream.h"
Hal Finkelf59fd7d2013-12-12 20:45:24 +000040#include "llvm/Support/ValueHandle.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000041#include "llvm/Target/TargetLibraryInfo.h"
Rafael Espindola3d7fc252013-10-21 17:14:55 +000042#include "llvm/Transforms/Utils/GlobalStatus.h"
Rafael Espindola17600e22013-07-25 03:23:25 +000043#include "llvm/Transforms/Utils/ModuleUtils.h"
Chris Lattner25db5802004-10-07 04:16:33 +000044#include <algorithm>
45using namespace llvm;
46
Chris Lattner1631bcb2006-12-19 22:09:18 +000047STATISTIC(NumMarked , "Number of globals marked constant");
Rafael Espindolafc355bc2011-01-19 16:32:21 +000048STATISTIC(NumUnnamed , "Number of globals marked unnamed_addr");
Chris Lattner1631bcb2006-12-19 22:09:18 +000049STATISTIC(NumSRA , "Number of aggregate globals broken into scalars");
50STATISTIC(NumHeapSRA , "Number of heap objects SRA'd");
51STATISTIC(NumSubstitute,"Number of globals with initializers stored into them");
52STATISTIC(NumDeleted , "Number of globals deleted");
53STATISTIC(NumFnDeleted , "Number of functions deleted");
54STATISTIC(NumGlobUses , "Number of global uses devirtualized");
Alexey Samsonova1944e62013-10-07 19:03:24 +000055STATISTIC(NumLocalized , "Number of globals localized");
Chris Lattner1631bcb2006-12-19 22:09:18 +000056STATISTIC(NumShrunkToBool , "Number of global vars shrunk to booleans");
57STATISTIC(NumFastCallFns , "Number of functions converted to fastcc");
58STATISTIC(NumCtorsEvaluated, "Number of static ctors evaluated");
Duncan Sands573b3f82008-02-16 20:56:04 +000059STATISTIC(NumNestRemoved , "Number of nest attributes removed");
Duncan Sandsb3f27882009-02-15 09:56:08 +000060STATISTIC(NumAliasesResolved, "Number of global aliases resolved");
61STATISTIC(NumAliasesRemoved, "Number of global aliases eliminated");
Anders Carlssonee6bc702011-03-20 17:59:11 +000062STATISTIC(NumCXXDtorsRemoved, "Number of global C++ destructors removed");
Chris Lattner25db5802004-10-07 04:16:33 +000063
Chris Lattner1631bcb2006-12-19 22:09:18 +000064namespace {
Nick Lewycky02d5f772009-10-25 06:33:48 +000065 struct GlobalOpt : public ModulePass {
Chris Lattner004e2502004-10-11 05:54:41 +000066 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chad Rosiere6de63d2011-12-01 21:29:16 +000067 AU.addRequired<TargetLibraryInfo>();
Chris Lattner004e2502004-10-11 05:54:41 +000068 }
Nick Lewyckye7da2d62007-05-06 13:37:16 +000069 static char ID; // Pass identification, replacement for typeid
Owen Anderson6c18d1a2010-10-19 17:21:58 +000070 GlobalOpt() : ModulePass(ID) {
71 initializeGlobalOptPass(*PassRegistry::getPassRegistry());
72 }
Misha Brukmanb1c93172005-04-21 23:48:37 +000073
Chris Lattner25db5802004-10-07 04:16:33 +000074 bool runOnModule(Module &M);
Chris Lattner004e2502004-10-11 05:54:41 +000075
76 private:
Chris Lattner41b6a5a2005-09-26 01:43:45 +000077 GlobalVariable *FindGlobalCtors(Module &M);
78 bool OptimizeFunctions(Module &M);
79 bool OptimizeGlobalVars(Module &M);
Duncan Sandsed722832009-03-06 10:21:56 +000080 bool OptimizeGlobalAliases(Module &M);
Chris Lattner41b6a5a2005-09-26 01:43:45 +000081 bool OptimizeGlobalCtorsList(GlobalVariable *&GCL);
Rafael Espindolafc355bc2011-01-19 16:32:21 +000082 bool ProcessGlobal(GlobalVariable *GV,Module::global_iterator &GVI);
83 bool ProcessInternalGlobal(GlobalVariable *GV,Module::global_iterator &GVI,
Rafael Espindolafc355bc2011-01-19 16:32:21 +000084 const GlobalStatus &GS);
Anders Carlssonee6bc702011-03-20 17:59:11 +000085 bool OptimizeEmptyGlobalCXXDtors(Function *CXAAtExitFn);
Nick Lewyckycf6aae62012-02-12 01:13:18 +000086
Micah Villmowcdfe20b2012-10-08 16:38:25 +000087 DataLayout *TD;
Nick Lewyckycf6aae62012-02-12 01:13:18 +000088 TargetLibraryInfo *TLI;
Chris Lattner25db5802004-10-07 04:16:33 +000089 };
Chris Lattner25db5802004-10-07 04:16:33 +000090}
91
Dan Gohmand78c4002008-05-13 00:00:25 +000092char GlobalOpt::ID = 0;
Chad Rosiere6de63d2011-12-01 21:29:16 +000093INITIALIZE_PASS_BEGIN(GlobalOpt, "globalopt",
94 "Global Variable Optimizer", false, false)
95INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
96INITIALIZE_PASS_END(GlobalOpt, "globalopt",
Owen Andersondf7a4f22010-10-07 22:25:06 +000097 "Global Variable Optimizer", false, false)
Dan Gohmand78c4002008-05-13 00:00:25 +000098
Chris Lattner25db5802004-10-07 04:16:33 +000099ModulePass *llvm::createGlobalOptimizerPass() { return new GlobalOpt(); }
100
Nick Lewyckyfaa9c3b02012-07-24 07:21:08 +0000101/// isLeakCheckerRoot - Is this global variable possibly used by a leak checker
102/// as a root? If so, we might not really want to eliminate the stores to it.
103static bool isLeakCheckerRoot(GlobalVariable *GV) {
104 // A global variable is a root if it is a pointer, or could plausibly contain
105 // a pointer. There are two challenges; one is that we could have a struct
106 // the has an inner member which is a pointer. We recurse through the type to
107 // detect these (up to a point). The other is that we may actually be a union
108 // of a pointer and another type, and so our LLVM type is an integer which
109 // gets converted into a pointer, or our type is an [i8 x #] with a pointer
110 // potentially contained here.
111
112 if (GV->hasPrivateLinkage())
113 return false;
114
115 SmallVector<Type *, 4> Types;
116 Types.push_back(cast<PointerType>(GV->getType())->getElementType());
117
118 unsigned Limit = 20;
119 do {
120 Type *Ty = Types.pop_back_val();
121 switch (Ty->getTypeID()) {
122 default: break;
123 case Type::PointerTyID: return true;
124 case Type::ArrayTyID:
125 case Type::VectorTyID: {
126 SequentialType *STy = cast<SequentialType>(Ty);
127 Types.push_back(STy->getElementType());
128 break;
129 }
130 case Type::StructTyID: {
131 StructType *STy = cast<StructType>(Ty);
132 if (STy->isOpaque()) return true;
133 for (StructType::element_iterator I = STy->element_begin(),
134 E = STy->element_end(); I != E; ++I) {
135 Type *InnerTy = *I;
136 if (isa<PointerType>(InnerTy)) return true;
137 if (isa<CompositeType>(InnerTy))
138 Types.push_back(InnerTy);
139 }
140 break;
141 }
142 }
143 if (--Limit == 0) return true;
144 } while (!Types.empty());
145 return false;
146}
147
148/// Given a value that is stored to a global but never read, determine whether
149/// it's safe to remove the store and the chain of computation that feeds the
150/// store.
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000151static bool IsSafeComputationToRemove(Value *V, const TargetLibraryInfo *TLI) {
Nick Lewyckyfaa9c3b02012-07-24 07:21:08 +0000152 do {
153 if (isa<Constant>(V))
154 return true;
155 if (!V->hasOneUse())
156 return false;
Nick Lewycky7d0f1102012-07-25 21:19:40 +0000157 if (isa<LoadInst>(V) || isa<InvokeInst>(V) || isa<Argument>(V) ||
158 isa<GlobalValue>(V))
Nick Lewyckyfaa9c3b02012-07-24 07:21:08 +0000159 return false;
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000160 if (isAllocationFn(V, TLI))
Nick Lewyckyfaa9c3b02012-07-24 07:21:08 +0000161 return true;
162
163 Instruction *I = cast<Instruction>(V);
164 if (I->mayHaveSideEffects())
165 return false;
166 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
167 if (!GEP->hasAllConstantIndices())
168 return false;
169 } else if (I->getNumOperands() != 1) {
170 return false;
171 }
172
173 V = I->getOperand(0);
174 } while (1);
175}
176
177/// CleanupPointerRootUsers - This GV is a pointer root. Loop over all users
178/// of the global and clean up any that obviously don't assign the global a
179/// value that isn't dynamically allocated.
180///
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000181static bool CleanupPointerRootUsers(GlobalVariable *GV,
182 const TargetLibraryInfo *TLI) {
Nick Lewyckyfaa9c3b02012-07-24 07:21:08 +0000183 // A brief explanation of leak checkers. The goal is to find bugs where
184 // pointers are forgotten, causing an accumulating growth in memory
185 // usage over time. The common strategy for leak checkers is to whitelist the
186 // memory pointed to by globals at exit. This is popular because it also
187 // solves another problem where the main thread of a C++ program may shut down
188 // before other threads that are still expecting to use those globals. To
189 // handle that case, we expect the program may create a singleton and never
190 // destroy it.
191
192 bool Changed = false;
193
194 // If Dead[n].first is the only use of a malloc result, we can delete its
195 // chain of computation and the store to the global in Dead[n].second.
196 SmallVector<std::pair<Instruction *, Instruction *>, 32> Dead;
197
198 // Constants can't be pointers to dynamically allocated memory.
199 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end();
200 UI != E;) {
201 User *U = *UI++;
202 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
203 Value *V = SI->getValueOperand();
204 if (isa<Constant>(V)) {
205 Changed = true;
206 SI->eraseFromParent();
207 } else if (Instruction *I = dyn_cast<Instruction>(V)) {
208 if (I->hasOneUse())
209 Dead.push_back(std::make_pair(I, SI));
210 }
211 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(U)) {
212 if (isa<Constant>(MSI->getValue())) {
213 Changed = true;
214 MSI->eraseFromParent();
215 } else if (Instruction *I = dyn_cast<Instruction>(MSI->getValue())) {
216 if (I->hasOneUse())
217 Dead.push_back(std::make_pair(I, MSI));
218 }
219 } else if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(U)) {
220 GlobalVariable *MemSrc = dyn_cast<GlobalVariable>(MTI->getSource());
221 if (MemSrc && MemSrc->isConstant()) {
222 Changed = true;
223 MTI->eraseFromParent();
224 } else if (Instruction *I = dyn_cast<Instruction>(MemSrc)) {
225 if (I->hasOneUse())
226 Dead.push_back(std::make_pair(I, MTI));
227 }
228 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
229 if (CE->use_empty()) {
230 CE->destroyConstant();
231 Changed = true;
232 }
233 } else if (Constant *C = dyn_cast<Constant>(U)) {
Rafael Espindola27797ba2013-10-17 18:06:32 +0000234 if (isSafeToDestroyConstant(C)) {
Nick Lewyckyfaa9c3b02012-07-24 07:21:08 +0000235 C->destroyConstant();
236 // This could have invalidated UI, start over from scratch.
237 Dead.clear();
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000238 CleanupPointerRootUsers(GV, TLI);
Nick Lewyckyfaa9c3b02012-07-24 07:21:08 +0000239 return true;
240 }
241 }
242 }
243
244 for (int i = 0, e = Dead.size(); i != e; ++i) {
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000245 if (IsSafeComputationToRemove(Dead[i].first, TLI)) {
Nick Lewyckyfaa9c3b02012-07-24 07:21:08 +0000246 Dead[i].second->eraseFromParent();
247 Instruction *I = Dead[i].first;
248 do {
Michael Gottesman2a654272013-01-11 23:08:52 +0000249 if (isAllocationFn(I, TLI))
250 break;
Nick Lewyckyfaa9c3b02012-07-24 07:21:08 +0000251 Instruction *J = dyn_cast<Instruction>(I->getOperand(0));
252 if (!J)
253 break;
254 I->eraseFromParent();
255 I = J;
Nick Lewycky38be9312012-07-24 21:33:00 +0000256 } while (1);
Nick Lewyckyfaa9c3b02012-07-24 07:21:08 +0000257 I->eraseFromParent();
258 }
259 }
260
261 return Changed;
262}
263
Chris Lattner25db5802004-10-07 04:16:33 +0000264/// CleanupConstantGlobalUsers - We just marked GV constant. Loop over all
265/// users of the global, cleaning up the obvious ones. This is largely just a
Chris Lattnercb9f1522004-10-10 16:43:46 +0000266/// quick scan over the use list to clean up the easy and obvious cruft. This
267/// returns true if it made a change.
Nick Lewyckycf6aae62012-02-12 01:13:18 +0000268static bool CleanupConstantGlobalUsers(Value *V, Constant *Init,
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000269 DataLayout *TD, TargetLibraryInfo *TLI) {
Chris Lattnercb9f1522004-10-10 16:43:46 +0000270 bool Changed = false;
Hal Finkelf59fd7d2013-12-12 20:45:24 +0000271 // Note that we need to use a weak value handle for the worklist items. When
272 // we delete a constant array, we may also be holding pointer to one of its
273 // elements (or an element of one of its elements if we're dealing with an
274 // array of arrays) in the worklist.
275 SmallVector<WeakVH, 8> WorkList(V->use_begin(), V->use_end());
Bill Wendling88d06c32013-04-02 08:16:45 +0000276 while (!WorkList.empty()) {
Hal Finkelf59fd7d2013-12-12 20:45:24 +0000277 Value *UV = WorkList.pop_back_val();
278 if (!UV)
279 continue;
280
281 User *U = cast<User>(UV);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000282
Chris Lattner25db5802004-10-07 04:16:33 +0000283 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
Chris Lattner7561ca12005-02-27 18:58:52 +0000284 if (Init) {
285 // Replace the load with the initializer.
286 LI->replaceAllUsesWith(Init);
287 LI->eraseFromParent();
288 Changed = true;
289 }
Chris Lattner25db5802004-10-07 04:16:33 +0000290 } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
291 // Store must be unreachable or storing Init into the global.
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000292 SI->eraseFromParent();
Chris Lattnercb9f1522004-10-10 16:43:46 +0000293 Changed = true;
Chris Lattner25db5802004-10-07 04:16:33 +0000294 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
295 if (CE->getOpcode() == Instruction::GetElementPtr) {
Chris Lattner46d9ff082005-09-26 07:34:35 +0000296 Constant *SubInit = 0;
297 if (Init)
Dan Gohmane525d9d2009-10-05 16:36:26 +0000298 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
Nick Lewyckycf6aae62012-02-12 01:13:18 +0000299 Changed |= CleanupConstantGlobalUsers(CE, SubInit, TD, TLI);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000300 } else if (CE->getOpcode() == Instruction::BitCast &&
Duncan Sands19d0b472010-02-16 11:11:14 +0000301 CE->getType()->isPointerTy()) {
Chris Lattner7561ca12005-02-27 18:58:52 +0000302 // Pointer cast, delete any stores and memsets to the global.
Nick Lewyckycf6aae62012-02-12 01:13:18 +0000303 Changed |= CleanupConstantGlobalUsers(CE, 0, TD, TLI);
Chris Lattner7561ca12005-02-27 18:58:52 +0000304 }
305
306 if (CE->use_empty()) {
307 CE->destroyConstant();
308 Changed = true;
Chris Lattner25db5802004-10-07 04:16:33 +0000309 }
310 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
Chris Lattnerf9c0fd72007-11-09 17:33:02 +0000311 // Do not transform "gepinst (gep constexpr (GV))" here, because forming
312 // "gepconstexpr (gep constexpr (GV))" will cause the two gep's to fold
313 // and will invalidate our notion of what Init is.
Chris Lattner68f04fa2007-11-13 21:46:23 +0000314 Constant *SubInit = 0;
Chris Lattnerf9c0fd72007-11-09 17:33:02 +0000315 if (!isa<ConstantExpr>(GEP->getOperand(0))) {
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000316 ConstantExpr *CE =
Nick Lewyckycf6aae62012-02-12 01:13:18 +0000317 dyn_cast_or_null<ConstantExpr>(ConstantFoldInstruction(GEP, TD, TLI));
Chris Lattnerf9c0fd72007-11-09 17:33:02 +0000318 if (Init && CE && CE->getOpcode() == Instruction::GetElementPtr)
Dan Gohmane525d9d2009-10-05 16:36:26 +0000319 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
Benjamin Krameraa9e4a52012-03-28 14:50:09 +0000320
321 // If the initializer is an all-null value and we have an inbounds GEP,
322 // we already know what the result of any load from that GEP is.
323 // TODO: Handle splats.
324 if (Init && isa<ConstantAggregateZero>(Init) && GEP->isInBounds())
325 SubInit = Constant::getNullValue(GEP->getType()->getElementType());
Chris Lattnerf9c0fd72007-11-09 17:33:02 +0000326 }
Nick Lewyckycf6aae62012-02-12 01:13:18 +0000327 Changed |= CleanupConstantGlobalUsers(GEP, SubInit, TD, TLI);
Chris Lattnera0e769c2004-10-10 16:47:33 +0000328
Chris Lattnercb9f1522004-10-10 16:43:46 +0000329 if (GEP->use_empty()) {
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000330 GEP->eraseFromParent();
Chris Lattnercb9f1522004-10-10 16:43:46 +0000331 Changed = true;
332 }
Chris Lattner7561ca12005-02-27 18:58:52 +0000333 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U)) { // memset/cpy/mv
334 if (MI->getRawDest() == V) {
335 MI->eraseFromParent();
336 Changed = true;
337 }
338
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000339 } else if (Constant *C = dyn_cast<Constant>(U)) {
340 // If we have a chain of dead constantexprs or other things dangling from
341 // us, and if they are all dead, nuke them without remorse.
Rafael Espindola27797ba2013-10-17 18:06:32 +0000342 if (isSafeToDestroyConstant(C)) {
Devang Pateld926aaa2009-03-06 01:37:41 +0000343 C->destroyConstant();
Nick Lewyckycf6aae62012-02-12 01:13:18 +0000344 CleanupConstantGlobalUsers(V, Init, TD, TLI);
Chris Lattnercb9f1522004-10-10 16:43:46 +0000345 return true;
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000346 }
Chris Lattner25db5802004-10-07 04:16:33 +0000347 }
348 }
Chris Lattnercb9f1522004-10-10 16:43:46 +0000349 return Changed;
Chris Lattner25db5802004-10-07 04:16:33 +0000350}
351
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000352/// isSafeSROAElementUse - Return true if the specified instruction is a safe
353/// user of a derived expression from a global that we want to SROA.
354static bool isSafeSROAElementUse(Value *V) {
355 // We might have a dead and dangling constant hanging off of here.
356 if (Constant *C = dyn_cast<Constant>(V))
Rafael Espindola27797ba2013-10-17 18:06:32 +0000357 return isSafeToDestroyConstant(C);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000358
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000359 Instruction *I = dyn_cast<Instruction>(V);
360 if (!I) return false;
361
362 // Loads are ok.
363 if (isa<LoadInst>(I)) return true;
364
365 // Stores *to* the pointer are ok.
366 if (StoreInst *SI = dyn_cast<StoreInst>(I))
367 return SI->getOperand(0) != V;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000368
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000369 // Otherwise, it must be a GEP.
370 GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I);
371 if (GEPI == 0) return false;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000372
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000373 if (GEPI->getNumOperands() < 3 || !isa<Constant>(GEPI->getOperand(1)) ||
374 !cast<Constant>(GEPI->getOperand(1))->isNullValue())
375 return false;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000376
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000377 for (Value::use_iterator I = GEPI->use_begin(), E = GEPI->use_end();
378 I != E; ++I)
379 if (!isSafeSROAElementUse(*I))
380 return false;
Chris Lattnerab053722008-01-14 01:31:05 +0000381 return true;
382}
383
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000384
385/// IsUserOfGlobalSafeForSRA - U is a direct user of the specified global value.
386/// Look at it and its uses and decide whether it is safe to SROA this global.
387///
388static bool IsUserOfGlobalSafeForSRA(User *U, GlobalValue *GV) {
389 // The user of the global must be a GEP Inst or a ConstantExpr GEP.
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000390 if (!isa<GetElementPtrInst>(U) &&
391 (!isa<ConstantExpr>(U) ||
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000392 cast<ConstantExpr>(U)->getOpcode() != Instruction::GetElementPtr))
393 return false;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000394
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000395 // Check to see if this ConstantExpr GEP is SRA'able. In particular, we
396 // don't like < 3 operand CE's, and we don't like non-constant integer
397 // indices. This enforces that all uses are 'gep GV, 0, C, ...' for some
398 // value of C.
399 if (U->getNumOperands() < 3 || !isa<Constant>(U->getOperand(1)) ||
400 !cast<Constant>(U->getOperand(1))->isNullValue() ||
401 !isa<ConstantInt>(U->getOperand(2)))
402 return false;
403
404 gep_type_iterator GEPI = gep_type_begin(U), E = gep_type_end(U);
405 ++GEPI; // Skip over the pointer index.
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000406
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000407 // If this is a use of an array allocation, do a bit more checking for sanity.
Chris Lattner229907c2011-07-18 04:54:35 +0000408 if (ArrayType *AT = dyn_cast<ArrayType>(*GEPI)) {
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000409 uint64_t NumElements = AT->getNumElements();
410 ConstantInt *Idx = cast<ConstantInt>(U->getOperand(2));
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000411
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000412 // Check to make sure that index falls within the array. If not,
413 // something funny is going on, so we won't do the optimization.
414 //
415 if (Idx->getZExtValue() >= NumElements)
416 return false;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000417
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000418 // We cannot scalar repl this level of the array unless any array
419 // sub-indices are in-range constants. In particular, consider:
420 // A[0][i]. We cannot know that the user isn't doing invalid things like
421 // allowing i to index an out-of-range subscript that accesses A[1].
422 //
423 // Scalar replacing *just* the outer index of the array is probably not
424 // going to be a win anyway, so just give up.
425 for (++GEPI; // Skip array index.
Dan Gohman82ac81b2009-08-18 14:58:19 +0000426 GEPI != E;
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000427 ++GEPI) {
428 uint64_t NumElements;
Chris Lattner229907c2011-07-18 04:54:35 +0000429 if (ArrayType *SubArrayTy = dyn_cast<ArrayType>(*GEPI))
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000430 NumElements = SubArrayTy->getNumElements();
Chris Lattner229907c2011-07-18 04:54:35 +0000431 else if (VectorType *SubVectorTy = dyn_cast<VectorType>(*GEPI))
Dan Gohman82ac81b2009-08-18 14:58:19 +0000432 NumElements = SubVectorTy->getNumElements();
433 else {
Duncan Sands19d0b472010-02-16 11:11:14 +0000434 assert((*GEPI)->isStructTy() &&
Dan Gohman82ac81b2009-08-18 14:58:19 +0000435 "Indexed GEP type is not array, vector, or struct!");
436 continue;
437 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000438
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000439 ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPI.getOperand());
440 if (!IdxVal || IdxVal->getZExtValue() >= NumElements)
441 return false;
442 }
443 }
444
445 for (Value::use_iterator I = U->use_begin(), E = U->use_end(); I != E; ++I)
446 if (!isSafeSROAElementUse(*I))
447 return false;
448 return true;
449}
450
451/// GlobalUsersSafeToSRA - Look at all uses of the global and decide whether it
452/// is safe for us to perform this transformation.
453///
454static bool GlobalUsersSafeToSRA(GlobalValue *GV) {
455 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end();
456 UI != E; ++UI) {
457 if (!IsUserOfGlobalSafeForSRA(*UI, GV))
458 return false;
459 }
460 return true;
461}
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000462
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000463
Chris Lattnerabab0712004-10-08 17:32:09 +0000464/// SRAGlobal - Perform scalar replacement of aggregates on the specified global
465/// variable. This opens the door for other optimizations by exposing the
466/// behavior of the program in a more fine-grained way. We have determined that
467/// this transformation is safe already. We return the first global variable we
468/// insert so that the caller can reprocess it.
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000469static GlobalVariable *SRAGlobal(GlobalVariable *GV, const DataLayout &TD) {
Chris Lattnerab053722008-01-14 01:31:05 +0000470 // Make sure this global only has simple uses that we can SRA.
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000471 if (!GlobalUsersSafeToSRA(GV))
Chris Lattnerab053722008-01-14 01:31:05 +0000472 return 0;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000473
Rafael Espindola6de96a12009-01-15 20:18:42 +0000474 assert(GV->hasLocalLinkage() && !GV->isConstant());
Chris Lattnerabab0712004-10-08 17:32:09 +0000475 Constant *Init = GV->getInitializer();
Chris Lattner229907c2011-07-18 04:54:35 +0000476 Type *Ty = Init->getType();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000477
Chris Lattnerabab0712004-10-08 17:32:09 +0000478 std::vector<GlobalVariable*> NewGlobals;
479 Module::GlobalListType &Globals = GV->getParent()->getGlobalList();
480
Chris Lattner67ca6f632008-04-26 07:40:11 +0000481 // Get the alignment of the global, either explicit or target-specific.
482 unsigned StartAlignment = GV->getAlignment();
483 if (StartAlignment == 0)
484 StartAlignment = TD.getABITypeAlignment(GV->getType());
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000485
Chris Lattner229907c2011-07-18 04:54:35 +0000486 if (StructType *STy = dyn_cast<StructType>(Ty)) {
Chris Lattnerabab0712004-10-08 17:32:09 +0000487 NewGlobals.reserve(STy->getNumElements());
Chris Lattner67ca6f632008-04-26 07:40:11 +0000488 const StructLayout &Layout = *TD.getStructLayout(STy);
Chris Lattnerabab0712004-10-08 17:32:09 +0000489 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
Chris Lattner67058832012-01-25 06:48:06 +0000490 Constant *In = Init->getAggregateElement(i);
Chris Lattnerabab0712004-10-08 17:32:09 +0000491 assert(In && "Couldn't get element of initializer?");
Chris Lattner46b5c642009-11-06 04:27:31 +0000492 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(i), false,
Chris Lattnerabab0712004-10-08 17:32:09 +0000493 GlobalVariable::InternalLinkage,
Daniel Dunbar132f7832009-07-30 17:37:43 +0000494 In, GV->getName()+"."+Twine(i),
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000495 GV->getThreadLocalMode(),
Owen Anderson5948fdf2009-07-08 01:26:06 +0000496 GV->getType()->getAddressSpace());
Chris Lattnerabab0712004-10-08 17:32:09 +0000497 Globals.insert(GV, NGV);
498 NewGlobals.push_back(NGV);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000499
Chris Lattner67ca6f632008-04-26 07:40:11 +0000500 // Calculate the known alignment of the field. If the original aggregate
501 // had 256 byte alignment for example, something might depend on that:
502 // propagate info to each field.
503 uint64_t FieldOffset = Layout.getElementOffset(i);
504 unsigned NewAlign = (unsigned)MinAlign(StartAlignment, FieldOffset);
505 if (NewAlign > TD.getABITypeAlignment(STy->getElementType(i)))
506 NGV->setAlignment(NewAlign);
Chris Lattnerabab0712004-10-08 17:32:09 +0000507 }
Chris Lattner229907c2011-07-18 04:54:35 +0000508 } else if (SequentialType *STy = dyn_cast<SequentialType>(Ty)) {
Chris Lattnerabab0712004-10-08 17:32:09 +0000509 unsigned NumElements = 0;
Chris Lattner229907c2011-07-18 04:54:35 +0000510 if (ArrayType *ATy = dyn_cast<ArrayType>(STy))
Chris Lattnerabab0712004-10-08 17:32:09 +0000511 NumElements = ATy->getNumElements();
Chris Lattnerabab0712004-10-08 17:32:09 +0000512 else
Chris Lattner67ca6f632008-04-26 07:40:11 +0000513 NumElements = cast<VectorType>(STy)->getNumElements();
Chris Lattnerabab0712004-10-08 17:32:09 +0000514
Chris Lattner25169ca2005-02-23 16:53:04 +0000515 if (NumElements > 16 && GV->hasNUsesOrMore(16))
Chris Lattnerd6a44922005-02-01 01:23:31 +0000516 return 0; // It's not worth it.
Chris Lattnerabab0712004-10-08 17:32:09 +0000517 NewGlobals.reserve(NumElements);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000518
Duncan Sandsaf9eaa82009-05-09 07:06:46 +0000519 uint64_t EltSize = TD.getTypeAllocSize(STy->getElementType());
Chris Lattner67ca6f632008-04-26 07:40:11 +0000520 unsigned EltAlign = TD.getABITypeAlignment(STy->getElementType());
Chris Lattnerabab0712004-10-08 17:32:09 +0000521 for (unsigned i = 0, e = NumElements; i != e; ++i) {
Chris Lattner67058832012-01-25 06:48:06 +0000522 Constant *In = Init->getAggregateElement(i);
Chris Lattnerabab0712004-10-08 17:32:09 +0000523 assert(In && "Couldn't get element of initializer?");
524
Chris Lattner46b5c642009-11-06 04:27:31 +0000525 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(), false,
Chris Lattnerabab0712004-10-08 17:32:09 +0000526 GlobalVariable::InternalLinkage,
Daniel Dunbar132f7832009-07-30 17:37:43 +0000527 In, GV->getName()+"."+Twine(i),
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000528 GV->getThreadLocalMode(),
Owen Andersonb17f3292009-07-08 19:03:57 +0000529 GV->getType()->getAddressSpace());
Chris Lattnerabab0712004-10-08 17:32:09 +0000530 Globals.insert(GV, NGV);
531 NewGlobals.push_back(NGV);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000532
Chris Lattner67ca6f632008-04-26 07:40:11 +0000533 // Calculate the known alignment of the field. If the original aggregate
534 // had 256 byte alignment for example, something might depend on that:
535 // propagate info to each field.
536 unsigned NewAlign = (unsigned)MinAlign(StartAlignment, EltSize*i);
537 if (NewAlign > EltAlign)
538 NGV->setAlignment(NewAlign);
Chris Lattnerabab0712004-10-08 17:32:09 +0000539 }
540 }
541
542 if (NewGlobals.empty())
543 return 0;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000544
David Greene44cb8ad2010-01-05 01:28:05 +0000545 DEBUG(dbgs() << "PERFORMING GLOBAL SRA ON: " << *GV);
Chris Lattner004e2502004-10-11 05:54:41 +0000546
Chris Lattner46b5c642009-11-06 04:27:31 +0000547 Constant *NullInt =Constant::getNullValue(Type::getInt32Ty(GV->getContext()));
Chris Lattnerabab0712004-10-08 17:32:09 +0000548
549 // Loop over all of the uses of the global, replacing the constantexpr geps,
550 // with smaller constantexpr geps or direct references.
551 while (!GV->use_empty()) {
Chris Lattner004e2502004-10-11 05:54:41 +0000552 User *GEP = GV->use_back();
553 assert(((isa<ConstantExpr>(GEP) &&
554 cast<ConstantExpr>(GEP)->getOpcode()==Instruction::GetElementPtr)||
555 isa<GetElementPtrInst>(GEP)) && "NonGEP CE's are not SRAable!");
Misha Brukmanb1c93172005-04-21 23:48:37 +0000556
Chris Lattnerabab0712004-10-08 17:32:09 +0000557 // Ignore the 1th operand, which has to be zero or else the program is quite
558 // broken (undefined). Get the 2nd operand, which is the structure or array
559 // index.
Reid Spencere0fc4df2006-10-20 07:07:24 +0000560 unsigned Val = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
Chris Lattnerabab0712004-10-08 17:32:09 +0000561 if (Val >= NewGlobals.size()) Val = 0; // Out of bound array access.
562
Chris Lattner004e2502004-10-11 05:54:41 +0000563 Value *NewPtr = NewGlobals[Val];
Chris Lattnerabab0712004-10-08 17:32:09 +0000564
565 // Form a shorter GEP if needed.
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +0000566 if (GEP->getNumOperands() > 3) {
Chris Lattner004e2502004-10-11 05:54:41 +0000567 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEP)) {
Chris Lattnerf96f4a82007-01-31 04:40:53 +0000568 SmallVector<Constant*, 8> Idxs;
Chris Lattner004e2502004-10-11 05:54:41 +0000569 Idxs.push_back(NullInt);
570 for (unsigned i = 3, e = CE->getNumOperands(); i != e; ++i)
571 Idxs.push_back(CE->getOperand(i));
Jay Foaded8db7d2011-07-21 14:31:17 +0000572 NewPtr = ConstantExpr::getGetElementPtr(cast<Constant>(NewPtr), Idxs);
Chris Lattner004e2502004-10-11 05:54:41 +0000573 } else {
574 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(GEP);
Chris Lattner927653f2007-01-31 19:59:55 +0000575 SmallVector<Value*, 8> Idxs;
Chris Lattner004e2502004-10-11 05:54:41 +0000576 Idxs.push_back(NullInt);
577 for (unsigned i = 3, e = GEPI->getNumOperands(); i != e; ++i)
578 Idxs.push_back(GEPI->getOperand(i));
Jay Foadd1b78492011-07-25 09:48:08 +0000579 NewPtr = GetElementPtrInst::Create(NewPtr, Idxs,
Daniel Dunbar132f7832009-07-30 17:37:43 +0000580 GEPI->getName()+"."+Twine(Val),GEPI);
Chris Lattner004e2502004-10-11 05:54:41 +0000581 }
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +0000582 }
Chris Lattner004e2502004-10-11 05:54:41 +0000583 GEP->replaceAllUsesWith(NewPtr);
584
585 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(GEP))
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000586 GEPI->eraseFromParent();
Chris Lattner004e2502004-10-11 05:54:41 +0000587 else
588 cast<ConstantExpr>(GEP)->destroyConstant();
Chris Lattnerabab0712004-10-08 17:32:09 +0000589 }
590
Chris Lattner73ad73e2004-10-08 20:25:55 +0000591 // Delete the old global, now that it is dead.
592 Globals.erase(GV);
Chris Lattnerabab0712004-10-08 17:32:09 +0000593 ++NumSRA;
Chris Lattner004e2502004-10-11 05:54:41 +0000594
595 // Loop over the new globals array deleting any globals that are obviously
596 // dead. This can arise due to scalarization of a structure or an array that
597 // has elements that are dead.
598 unsigned FirstGlobal = 0;
599 for (unsigned i = 0, e = NewGlobals.size(); i != e; ++i)
600 if (NewGlobals[i]->use_empty()) {
601 Globals.erase(NewGlobals[i]);
602 if (FirstGlobal == i) ++FirstGlobal;
603 }
604
605 return FirstGlobal != NewGlobals.size() ? NewGlobals[FirstGlobal] : 0;
Chris Lattnerabab0712004-10-08 17:32:09 +0000606}
607
Chris Lattner09a52722004-10-09 21:48:45 +0000608/// AllUsesOfValueWillTrapIfNull - Return true if all users of the specified
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000609/// value will trap if the value is dynamically null. PHIs keeps track of any
Chris Lattner2d2892e2007-09-13 16:30:19 +0000610/// phi nodes we've seen to avoid reprocessing them.
Gabor Greif67972872010-04-06 19:24:18 +0000611static bool AllUsesOfValueWillTrapIfNull(const Value *V,
612 SmallPtrSet<const PHINode*, 8> &PHIs) {
613 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;
Gabor Greif08355d62010-04-06 19:14:05 +0000614 ++UI) {
Gabor Greif67972872010-04-06 19:24:18 +0000615 const User *U = *UI;
Gabor Greif08355d62010-04-06 19:14:05 +0000616
617 if (isa<LoadInst>(U)) {
Chris Lattner09a52722004-10-09 21:48:45 +0000618 // Will trap.
Gabor Greif67972872010-04-06 19:24:18 +0000619 } else if (const StoreInst *SI = dyn_cast<StoreInst>(U)) {
Chris Lattner09a52722004-10-09 21:48:45 +0000620 if (SI->getOperand(0) == V) {
Gabor Greif08355d62010-04-06 19:14:05 +0000621 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner09a52722004-10-09 21:48:45 +0000622 return false; // Storing the value.
623 }
Gabor Greif67972872010-04-06 19:24:18 +0000624 } else if (const CallInst *CI = dyn_cast<CallInst>(U)) {
Gabor Greiffebf6ab2010-03-20 21:00:25 +0000625 if (CI->getCalledValue() != V) {
Gabor Greif08355d62010-04-06 19:14:05 +0000626 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner09a52722004-10-09 21:48:45 +0000627 return false; // Not calling the ptr
628 }
Gabor Greif67972872010-04-06 19:24:18 +0000629 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(U)) {
Gabor Greiffebf6ab2010-03-20 21:00:25 +0000630 if (II->getCalledValue() != V) {
Gabor Greif08355d62010-04-06 19:14:05 +0000631 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner09a52722004-10-09 21:48:45 +0000632 return false; // Not calling the ptr
633 }
Gabor Greif67972872010-04-06 19:24:18 +0000634 } else if (const BitCastInst *CI = dyn_cast<BitCastInst>(U)) {
Chris Lattner2d2892e2007-09-13 16:30:19 +0000635 if (!AllUsesOfValueWillTrapIfNull(CI, PHIs)) return false;
Gabor Greif67972872010-04-06 19:24:18 +0000636 } else if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
Chris Lattner2d2892e2007-09-13 16:30:19 +0000637 if (!AllUsesOfValueWillTrapIfNull(GEPI, PHIs)) return false;
Gabor Greif67972872010-04-06 19:24:18 +0000638 } else if (const PHINode *PN = dyn_cast<PHINode>(U)) {
Chris Lattner2d2892e2007-09-13 16:30:19 +0000639 // If we've already seen this phi node, ignore it, it has already been
640 // checked.
Jakob Stoklund Olesene27dc722010-01-29 23:54:14 +0000641 if (PHIs.insert(PN) && !AllUsesOfValueWillTrapIfNull(PN, PHIs))
642 return false;
Gabor Greif08355d62010-04-06 19:14:05 +0000643 } else if (isa<ICmpInst>(U) &&
Chris Lattnerfe9abf92004-10-22 06:43:28 +0000644 isa<ConstantPointerNull>(UI->getOperand(1))) {
Nick Lewycky614fb942010-02-25 06:39:10 +0000645 // Ignore icmp X, null
Chris Lattner09a52722004-10-09 21:48:45 +0000646 } else {
Gabor Greif08355d62010-04-06 19:14:05 +0000647 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner09a52722004-10-09 21:48:45 +0000648 return false;
649 }
Gabor Greif08355d62010-04-06 19:14:05 +0000650 }
Chris Lattner09a52722004-10-09 21:48:45 +0000651 return true;
652}
653
654/// AllUsesOfLoadedValueWillTrapIfNull - Return true if all uses of any loads
Chris Lattnerfe9abf92004-10-22 06:43:28 +0000655/// from GV will trap if the loaded value is null. Note that this also permits
656/// comparisons of the loaded value against null, as a special case.
Gabor Greif67972872010-04-06 19:24:18 +0000657static bool AllUsesOfLoadedValueWillTrapIfNull(const GlobalVariable *GV) {
658 for (Value::const_use_iterator UI = GV->use_begin(), E = GV->use_end();
Gabor Greif08355d62010-04-06 19:14:05 +0000659 UI != E; ++UI) {
Gabor Greif67972872010-04-06 19:24:18 +0000660 const User *U = *UI;
Gabor Greif08355d62010-04-06 19:14:05 +0000661
Gabor Greif67972872010-04-06 19:24:18 +0000662 if (const LoadInst *LI = dyn_cast<LoadInst>(U)) {
663 SmallPtrSet<const PHINode*, 8> PHIs;
Chris Lattner2d2892e2007-09-13 16:30:19 +0000664 if (!AllUsesOfValueWillTrapIfNull(LI, PHIs))
Chris Lattner09a52722004-10-09 21:48:45 +0000665 return false;
Gabor Greif08355d62010-04-06 19:14:05 +0000666 } else if (isa<StoreInst>(U)) {
Chris Lattner09a52722004-10-09 21:48:45 +0000667 // Ignore stores to the global.
668 } else {
669 // We don't know or understand this user, bail out.
Gabor Greif08355d62010-04-06 19:14:05 +0000670 //cerr << "UNKNOWN USER OF GLOBAL!: " << *U;
Chris Lattner09a52722004-10-09 21:48:45 +0000671 return false;
672 }
Gabor Greif08355d62010-04-06 19:14:05 +0000673 }
Chris Lattner09a52722004-10-09 21:48:45 +0000674 return true;
675}
676
Chris Lattner46b5c642009-11-06 04:27:31 +0000677static bool OptimizeAwayTrappingUsesOfValue(Value *V, Constant *NewV) {
Chris Lattnere42eb312004-10-10 23:14:11 +0000678 bool Changed = false;
679 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ) {
680 Instruction *I = cast<Instruction>(*UI++);
681 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
682 LI->setOperand(0, NewV);
683 Changed = true;
684 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
685 if (SI->getOperand(1) == V) {
686 SI->setOperand(1, NewV);
687 Changed = true;
688 }
689 } else if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
Gabor Greif04397892010-04-06 18:45:08 +0000690 CallSite CS(I);
691 if (CS.getCalledValue() == V) {
Chris Lattnere42eb312004-10-10 23:14:11 +0000692 // Calling through the pointer! Turn into a direct call, but be careful
693 // that the pointer is not also being passed as an argument.
Gabor Greif04397892010-04-06 18:45:08 +0000694 CS.setCalledFunction(NewV);
Chris Lattnere42eb312004-10-10 23:14:11 +0000695 Changed = true;
696 bool PassedAsArg = false;
Gabor Greif04397892010-04-06 18:45:08 +0000697 for (unsigned i = 0, e = CS.arg_size(); i != e; ++i)
698 if (CS.getArgument(i) == V) {
Chris Lattnere42eb312004-10-10 23:14:11 +0000699 PassedAsArg = true;
Gabor Greif04397892010-04-06 18:45:08 +0000700 CS.setArgument(i, NewV);
Chris Lattnere42eb312004-10-10 23:14:11 +0000701 }
702
703 if (PassedAsArg) {
704 // Being passed as an argument also. Be careful to not invalidate UI!
705 UI = V->use_begin();
706 }
707 }
708 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
709 Changed |= OptimizeAwayTrappingUsesOfValue(CI,
Owen Anderson487375e2009-07-29 18:55:55 +0000710 ConstantExpr::getCast(CI->getOpcode(),
Chris Lattner46b5c642009-11-06 04:27:31 +0000711 NewV, CI->getType()));
Chris Lattnere42eb312004-10-10 23:14:11 +0000712 if (CI->use_empty()) {
713 Changed = true;
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000714 CI->eraseFromParent();
Chris Lattnere42eb312004-10-10 23:14:11 +0000715 }
716 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
717 // Should handle GEP here.
Chris Lattnerf96f4a82007-01-31 04:40:53 +0000718 SmallVector<Constant*, 8> Idxs;
719 Idxs.reserve(GEPI->getNumOperands()-1);
Gabor Greif3a9fba52008-05-29 01:59:18 +0000720 for (User::op_iterator i = GEPI->op_begin() + 1, e = GEPI->op_end();
721 i != e; ++i)
722 if (Constant *C = dyn_cast<Constant>(*i))
Chris Lattnerf96f4a82007-01-31 04:40:53 +0000723 Idxs.push_back(C);
Chris Lattnere42eb312004-10-10 23:14:11 +0000724 else
725 break;
Chris Lattnerf96f4a82007-01-31 04:40:53 +0000726 if (Idxs.size() == GEPI->getNumOperands()-1)
Chris Lattnere42eb312004-10-10 23:14:11 +0000727 Changed |= OptimizeAwayTrappingUsesOfValue(GEPI,
Jay Foaded8db7d2011-07-21 14:31:17 +0000728 ConstantExpr::getGetElementPtr(NewV, Idxs));
Chris Lattnere42eb312004-10-10 23:14:11 +0000729 if (GEPI->use_empty()) {
730 Changed = true;
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000731 GEPI->eraseFromParent();
Chris Lattnere42eb312004-10-10 23:14:11 +0000732 }
733 }
734 }
735
736 return Changed;
737}
738
739
740/// OptimizeAwayTrappingUsesOfLoads - The specified global has only one non-null
741/// value stored into it. If there are uses of the loaded value that would trap
742/// if the loaded value is dynamically null, then we know that they cannot be
743/// reachable with a null optimize away the load.
Nick Lewyckycf6aae62012-02-12 01:13:18 +0000744static bool OptimizeAwayTrappingUsesOfLoads(GlobalVariable *GV, Constant *LV,
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000745 DataLayout *TD,
Nick Lewyckycf6aae62012-02-12 01:13:18 +0000746 TargetLibraryInfo *TLI) {
Chris Lattnere42eb312004-10-10 23:14:11 +0000747 bool Changed = false;
748
Chris Lattner2538eb62009-01-14 00:12:58 +0000749 // Keep track of whether we are able to remove all the uses of the global
750 // other than the store that defines it.
751 bool AllNonStoreUsesGone = true;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000752
Chris Lattnere42eb312004-10-10 23:14:11 +0000753 // Replace all uses of loads with uses of uses of the stored value.
Chris Lattner2538eb62009-01-14 00:12:58 +0000754 for (Value::use_iterator GUI = GV->use_begin(), E = GV->use_end(); GUI != E;){
755 User *GlobalUser = *GUI++;
756 if (LoadInst *LI = dyn_cast<LoadInst>(GlobalUser)) {
Chris Lattner46b5c642009-11-06 04:27:31 +0000757 Changed |= OptimizeAwayTrappingUsesOfValue(LI, LV);
Chris Lattner2538eb62009-01-14 00:12:58 +0000758 // If we were able to delete all uses of the loads
759 if (LI->use_empty()) {
760 LI->eraseFromParent();
761 Changed = true;
762 } else {
763 AllNonStoreUsesGone = false;
764 }
765 } else if (isa<StoreInst>(GlobalUser)) {
766 // Ignore the store that stores "LV" to the global.
767 assert(GlobalUser->getOperand(1) == GV &&
768 "Must be storing *to* the global");
Chris Lattnere42eb312004-10-10 23:14:11 +0000769 } else {
Chris Lattner2538eb62009-01-14 00:12:58 +0000770 AllNonStoreUsesGone = false;
771
772 // If we get here we could have other crazy uses that are transitively
773 // loaded.
774 assert((isa<PHINode>(GlobalUser) || isa<SelectInst>(GlobalUser) ||
Benjamin Kramered843602012-09-28 10:01:27 +0000775 isa<ConstantExpr>(GlobalUser) || isa<CmpInst>(GlobalUser) ||
776 isa<BitCastInst>(GlobalUser) ||
777 isa<GetElementPtrInst>(GlobalUser)) &&
Chris Lattner1a1acc22011-05-22 07:15:13 +0000778 "Only expect load and stores!");
Chris Lattnere42eb312004-10-10 23:14:11 +0000779 }
Chris Lattner2538eb62009-01-14 00:12:58 +0000780 }
Chris Lattnere42eb312004-10-10 23:14:11 +0000781
782 if (Changed) {
David Greene44cb8ad2010-01-05 01:28:05 +0000783 DEBUG(dbgs() << "OPTIMIZED LOADS FROM STORED ONCE POINTER: " << *GV);
Chris Lattnere42eb312004-10-10 23:14:11 +0000784 ++NumGlobUses;
785 }
786
Chris Lattnere42eb312004-10-10 23:14:11 +0000787 // If we nuked all of the loads, then none of the stores are needed either,
788 // nor is the global.
Chris Lattner2538eb62009-01-14 00:12:58 +0000789 if (AllNonStoreUsesGone) {
Nick Lewyckyfaa9c3b02012-07-24 07:21:08 +0000790 if (isLeakCheckerRoot(GV)) {
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000791 Changed |= CleanupPointerRootUsers(GV, TLI);
Nick Lewyckyfaa9c3b02012-07-24 07:21:08 +0000792 } else {
793 Changed = true;
794 CleanupConstantGlobalUsers(GV, 0, TD, TLI);
795 }
Chris Lattnere42eb312004-10-10 23:14:11 +0000796 if (GV->use_empty()) {
Nick Lewyckyfaa9c3b02012-07-24 07:21:08 +0000797 DEBUG(dbgs() << " *** GLOBAL NOW DEAD!\n");
798 Changed = true;
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000799 GV->eraseFromParent();
Chris Lattnere42eb312004-10-10 23:14:11 +0000800 ++NumDeleted;
801 }
Chris Lattnere42eb312004-10-10 23:14:11 +0000802 }
803 return Changed;
804}
805
Chris Lattner004e2502004-10-11 05:54:41 +0000806/// ConstantPropUsersOf - Walk the use list of V, constant folding all of the
807/// instructions that are foldable.
Nick Lewyckycf6aae62012-02-12 01:13:18 +0000808static void ConstantPropUsersOf(Value *V,
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000809 DataLayout *TD, TargetLibraryInfo *TLI) {
Chris Lattner004e2502004-10-11 05:54:41 +0000810 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; )
811 if (Instruction *I = dyn_cast<Instruction>(*UI++))
Nick Lewyckycf6aae62012-02-12 01:13:18 +0000812 if (Constant *NewC = ConstantFoldInstruction(I, TD, TLI)) {
Chris Lattner004e2502004-10-11 05:54:41 +0000813 I->replaceAllUsesWith(NewC);
814
Chris Lattnerd6a44922005-02-01 01:23:31 +0000815 // Advance UI to the next non-I use to avoid invalidating it!
816 // Instructions could multiply use V.
817 while (UI != E && *UI == I)
Chris Lattner004e2502004-10-11 05:54:41 +0000818 ++UI;
Chris Lattnerd6a44922005-02-01 01:23:31 +0000819 I->eraseFromParent();
Chris Lattner004e2502004-10-11 05:54:41 +0000820 }
821}
822
823/// OptimizeGlobalAddressOfMalloc - This function takes the specified global
824/// variable, and transforms the program as if it always contained the result of
825/// the specified malloc. Because it is always the result of the specified
826/// malloc, there is no reason to actually DO the malloc. Instead, turn the
Chris Lattner3ede00b2006-11-30 17:32:29 +0000827/// malloc into a global, and any loads of GV as uses of the new global.
Chris Lattner004e2502004-10-11 05:54:41 +0000828static GlobalVariable *OptimizeGlobalAddressOfMalloc(GlobalVariable *GV,
Victor Hernandez5d034492009-09-18 22:35:49 +0000829 CallInst *CI,
Chris Lattner229907c2011-07-18 04:54:35 +0000830 Type *AllocTy,
Chris Lattner7939f792010-02-25 22:33:52 +0000831 ConstantInt *NElements,
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000832 DataLayout *TD,
Nick Lewyckycf6aae62012-02-12 01:13:18 +0000833 TargetLibraryInfo *TLI) {
Chris Lattner7939f792010-02-25 22:33:52 +0000834 DEBUG(errs() << "PROMOTING GLOBAL: " << *GV << " CALL = " << *CI << '\n');
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000835
Chris Lattner229907c2011-07-18 04:54:35 +0000836 Type *GlobalType;
Chris Lattner7939f792010-02-25 22:33:52 +0000837 if (NElements->getZExtValue() == 1)
838 GlobalType = AllocTy;
839 else
840 // If we have an array allocation, the global variable is of an array.
841 GlobalType = ArrayType::get(AllocTy, NElements->getZExtValue());
Victor Hernandez5d034492009-09-18 22:35:49 +0000842
843 // Create the new global variable. The contents of the malloc'd memory is
844 // undefined, so initialize with an undef value.
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000845 GlobalVariable *NewGV = new GlobalVariable(*GV->getParent(),
Chris Lattner65d3a0a2010-02-26 23:42:13 +0000846 GlobalType, false,
Chris Lattner7939f792010-02-25 22:33:52 +0000847 GlobalValue::InternalLinkage,
Chris Lattner65d3a0a2010-02-26 23:42:13 +0000848 UndefValue::get(GlobalType),
Victor Hernandez5d034492009-09-18 22:35:49 +0000849 GV->getName()+".body",
850 GV,
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000851 GV->getThreadLocalMode());
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000852
Chris Lattner7939f792010-02-25 22:33:52 +0000853 // If there are bitcast users of the malloc (which is typical, usually we have
854 // a malloc + bitcast) then replace them with uses of the new global. Update
855 // other users to use the global as well.
856 BitCastInst *TheBC = 0;
857 while (!CI->use_empty()) {
858 Instruction *User = cast<Instruction>(CI->use_back());
859 if (BitCastInst *BCI = dyn_cast<BitCastInst>(User)) {
860 if (BCI->getType() == NewGV->getType()) {
861 BCI->replaceAllUsesWith(NewGV);
862 BCI->eraseFromParent();
863 } else {
864 BCI->setOperand(0, NewGV);
865 }
866 } else {
867 if (TheBC == 0)
868 TheBC = new BitCastInst(NewGV, CI->getType(), "newgv", CI);
869 User->replaceUsesOfWith(CI, TheBC);
870 }
871 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000872
Victor Hernandez5d034492009-09-18 22:35:49 +0000873 Constant *RepValue = NewGV;
874 if (NewGV->getType() != GV->getType()->getElementType())
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000875 RepValue = ConstantExpr::getBitCast(RepValue,
Victor Hernandez5d034492009-09-18 22:35:49 +0000876 GV->getType()->getElementType());
877
878 // If there is a comparison against null, we will insert a global bool to
879 // keep track of whether the global was initialized yet or not.
880 GlobalVariable *InitBool =
Chris Lattner46b5c642009-11-06 04:27:31 +0000881 new GlobalVariable(Type::getInt1Ty(GV->getContext()), false,
Victor Hernandez5d034492009-09-18 22:35:49 +0000882 GlobalValue::InternalLinkage,
Chris Lattner46b5c642009-11-06 04:27:31 +0000883 ConstantInt::getFalse(GV->getContext()),
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000884 GV->getName()+".init", GV->getThreadLocalMode());
Victor Hernandez5d034492009-09-18 22:35:49 +0000885 bool InitBoolUsed = false;
886
887 // Loop over all uses of GV, processing them in turn.
Chris Lattner7939f792010-02-25 22:33:52 +0000888 while (!GV->use_empty()) {
889 if (StoreInst *SI = dyn_cast<StoreInst>(GV->use_back())) {
Victor Hernandez5d034492009-09-18 22:35:49 +0000890 // The global is initialized when the store to it occurs.
Nick Lewycky52da72b2012-02-05 19:56:38 +0000891 new StoreInst(ConstantInt::getTrue(GV->getContext()), InitBool, false, 0,
892 SI->getOrdering(), SI->getSynchScope(), SI);
Victor Hernandez5d034492009-09-18 22:35:49 +0000893 SI->eraseFromParent();
Chris Lattner7939f792010-02-25 22:33:52 +0000894 continue;
Victor Hernandez5d034492009-09-18 22:35:49 +0000895 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000896
Chris Lattner7939f792010-02-25 22:33:52 +0000897 LoadInst *LI = cast<LoadInst>(GV->use_back());
898 while (!LI->use_empty()) {
899 Use &LoadUse = LI->use_begin().getUse();
900 if (!isa<ICmpInst>(LoadUse.getUser())) {
901 LoadUse = RepValue;
902 continue;
903 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000904
Chris Lattner7939f792010-02-25 22:33:52 +0000905 ICmpInst *ICI = cast<ICmpInst>(LoadUse.getUser());
906 // Replace the cmp X, 0 with a use of the bool value.
Nick Lewycky52da72b2012-02-05 19:56:38 +0000907 // Sink the load to where the compare was, if atomic rules allow us to.
908 Value *LV = new LoadInst(InitBool, InitBool->getName()+".val", false, 0,
909 LI->getOrdering(), LI->getSynchScope(),
910 LI->isUnordered() ? (Instruction*)ICI : LI);
Chris Lattner7939f792010-02-25 22:33:52 +0000911 InitBoolUsed = true;
912 switch (ICI->getPredicate()) {
913 default: llvm_unreachable("Unknown ICmp Predicate!");
914 case ICmpInst::ICMP_ULT:
915 case ICmpInst::ICMP_SLT: // X < null -> always false
916 LV = ConstantInt::getFalse(GV->getContext());
917 break;
918 case ICmpInst::ICMP_ULE:
919 case ICmpInst::ICMP_SLE:
920 case ICmpInst::ICMP_EQ:
921 LV = BinaryOperator::CreateNot(LV, "notinit", ICI);
922 break;
923 case ICmpInst::ICMP_NE:
924 case ICmpInst::ICMP_UGE:
925 case ICmpInst::ICMP_SGE:
926 case ICmpInst::ICMP_UGT:
927 case ICmpInst::ICMP_SGT:
928 break; // no change.
929 }
930 ICI->replaceAllUsesWith(LV);
931 ICI->eraseFromParent();
932 }
933 LI->eraseFromParent();
934 }
Victor Hernandez5d034492009-09-18 22:35:49 +0000935
936 // If the initialization boolean was used, insert it, otherwise delete it.
937 if (!InitBoolUsed) {
938 while (!InitBool->use_empty()) // Delete initializations
Chris Lattner7939f792010-02-25 22:33:52 +0000939 cast<StoreInst>(InitBool->use_back())->eraseFromParent();
Victor Hernandez5d034492009-09-18 22:35:49 +0000940 delete InitBool;
941 } else
942 GV->getParent()->getGlobalList().insert(GV, InitBool);
943
Chris Lattner7939f792010-02-25 22:33:52 +0000944 // Now the GV is dead, nuke it and the malloc..
Victor Hernandez5d034492009-09-18 22:35:49 +0000945 GV->eraseFromParent();
Victor Hernandez5d034492009-09-18 22:35:49 +0000946 CI->eraseFromParent();
947
948 // To further other optimizations, loop over all users of NewGV and try to
949 // constant prop them. This will promote GEP instructions with constant
950 // indices into GEP constant-exprs, which will allow global-opt to hack on it.
Nick Lewyckycf6aae62012-02-12 01:13:18 +0000951 ConstantPropUsersOf(NewGV, TD, TLI);
Victor Hernandez5d034492009-09-18 22:35:49 +0000952 if (RepValue != NewGV)
Nick Lewyckycf6aae62012-02-12 01:13:18 +0000953 ConstantPropUsersOf(RepValue, TD, TLI);
Victor Hernandez5d034492009-09-18 22:35:49 +0000954
955 return NewGV;
956}
957
Chris Lattnerc0677c02004-12-02 07:11:07 +0000958/// ValueIsOnlyUsedLocallyOrStoredToOneGlobal - Scan the use-list of V checking
959/// to make sure that there are no complex uses of V. We permit simple things
960/// like dereferencing the pointer, but not storing through the address, unless
961/// it is to the specified global.
Gabor Greifa21bc0f2010-04-06 18:58:22 +0000962static bool ValueIsOnlyUsedLocallyOrStoredToOneGlobal(const Instruction *V,
963 const GlobalVariable *GV,
Gabor Greif08355d62010-04-06 19:14:05 +0000964 SmallPtrSet<const PHINode*, 8> &PHIs) {
Gabor Greifa21bc0f2010-04-06 18:58:22 +0000965 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end();
Gabor Greif08355d62010-04-06 19:14:05 +0000966 UI != E; ++UI) {
Gabor Greifa21bc0f2010-04-06 18:58:22 +0000967 const Instruction *Inst = cast<Instruction>(*UI);
Gabor Greif08355d62010-04-06 19:14:05 +0000968
Chris Lattnerf0eb5682008-12-15 21:08:54 +0000969 if (isa<LoadInst>(Inst) || isa<CmpInst>(Inst)) {
970 continue; // Fine, ignore.
971 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000972
Gabor Greifa21bc0f2010-04-06 18:58:22 +0000973 if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
Chris Lattnerc0677c02004-12-02 07:11:07 +0000974 if (SI->getOperand(0) == V && SI->getOperand(1) != GV)
975 return false; // Storing the pointer itself... bad.
Chris Lattnerf0eb5682008-12-15 21:08:54 +0000976 continue; // Otherwise, storing through it, or storing into GV... fine.
977 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000978
Chris Lattnerb9801ff2010-04-10 18:19:22 +0000979 // Must index into the array and into the struct.
980 if (isa<GetElementPtrInst>(Inst) && Inst->getNumOperands() >= 3) {
Chris Lattnerf0eb5682008-12-15 21:08:54 +0000981 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(Inst, GV, PHIs))
Chris Lattnerc0677c02004-12-02 07:11:07 +0000982 return false;
Chris Lattnerf0eb5682008-12-15 21:08:54 +0000983 continue;
984 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000985
Gabor Greifa21bc0f2010-04-06 18:58:22 +0000986 if (const PHINode *PN = dyn_cast<PHINode>(Inst)) {
Chris Lattner6eed0e72007-09-13 16:37:20 +0000987 // PHIs are ok if all uses are ok. Don't infinitely recurse through PHI
988 // cycles.
989 if (PHIs.insert(PN))
Chris Lattner5d13fb532007-09-14 03:41:21 +0000990 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(PN, GV, PHIs))
991 return false;
Chris Lattnerf0eb5682008-12-15 21:08:54 +0000992 continue;
Chris Lattnerc0677c02004-12-02 07:11:07 +0000993 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000994
Gabor Greifa21bc0f2010-04-06 18:58:22 +0000995 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Inst)) {
Chris Lattnerf0eb5682008-12-15 21:08:54 +0000996 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(BCI, GV, PHIs))
997 return false;
998 continue;
999 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001000
Chris Lattnerf0eb5682008-12-15 21:08:54 +00001001 return false;
1002 }
Chris Lattnerc0677c02004-12-02 07:11:07 +00001003 return true;
Chris Lattnerc0677c02004-12-02 07:11:07 +00001004}
1005
Chris Lattner24d3d422006-09-30 23:32:09 +00001006/// ReplaceUsesOfMallocWithGlobal - The Alloc pointer is stored into GV
1007/// somewhere. Transform all uses of the allocation into loads from the
1008/// global and uses of the resultant pointer. Further, delete the store into
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001009/// GV. This assumes that these value pass the
Chris Lattner24d3d422006-09-30 23:32:09 +00001010/// 'ValueIsOnlyUsedLocallyOrStoredToOneGlobal' predicate.
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001011static void ReplaceUsesOfMallocWithGlobal(Instruction *Alloc,
Chris Lattner24d3d422006-09-30 23:32:09 +00001012 GlobalVariable *GV) {
1013 while (!Alloc->use_empty()) {
Chris Lattnerba98f892007-09-13 18:00:31 +00001014 Instruction *U = cast<Instruction>(*Alloc->use_begin());
1015 Instruction *InsertPt = U;
Chris Lattner24d3d422006-09-30 23:32:09 +00001016 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
1017 // If this is the store of the allocation into the global, remove it.
1018 if (SI->getOperand(1) == GV) {
1019 SI->eraseFromParent();
1020 continue;
1021 }
Chris Lattnerba98f892007-09-13 18:00:31 +00001022 } else if (PHINode *PN = dyn_cast<PHINode>(U)) {
1023 // Insert the load in the corresponding predecessor, not right before the
1024 // PHI.
Gabor Greifeb61fcf2009-01-23 19:40:15 +00001025 InsertPt = PN->getIncomingBlock(Alloc->use_begin())->getTerminator();
Chris Lattner49e3bdc2008-12-15 21:44:34 +00001026 } else if (isa<BitCastInst>(U)) {
1027 // Must be bitcast between the malloc and store to initialize the global.
1028 ReplaceUsesOfMallocWithGlobal(U, GV);
1029 U->eraseFromParent();
1030 continue;
1031 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
1032 // If this is a "GEP bitcast" and the user is a store to the global, then
1033 // just process it as a bitcast.
1034 if (GEPI->hasAllZeroIndices() && GEPI->hasOneUse())
1035 if (StoreInst *SI = dyn_cast<StoreInst>(GEPI->use_back()))
1036 if (SI->getOperand(1) == GV) {
1037 // Must be bitcast GEP between the malloc and store to initialize
1038 // the global.
1039 ReplaceUsesOfMallocWithGlobal(GEPI, GV);
1040 GEPI->eraseFromParent();
1041 continue;
1042 }
Chris Lattner24d3d422006-09-30 23:32:09 +00001043 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001044
Chris Lattner24d3d422006-09-30 23:32:09 +00001045 // Insert a load from the global, and use it instead of the malloc.
Chris Lattnerba98f892007-09-13 18:00:31 +00001046 Value *NL = new LoadInst(GV, GV->getName()+".val", InsertPt);
Chris Lattner24d3d422006-09-30 23:32:09 +00001047 U->replaceUsesOfWith(Alloc, NL);
1048 }
1049}
1050
Chris Lattner56b55382008-12-16 21:24:51 +00001051/// LoadUsesSimpleEnoughForHeapSRA - Verify that all uses of V (a load, or a phi
1052/// of a load) are simple enough to perform heap SRA on. This permits GEP's
1053/// that index through the array and struct field, icmps of null, and PHIs.
Gabor Greif5d5db532010-04-01 08:21:08 +00001054static bool LoadUsesSimpleEnoughForHeapSRA(const Value *V,
Gabor Greif08d85da2010-04-07 18:59:26 +00001055 SmallPtrSet<const PHINode*, 32> &LoadUsingPHIs,
1056 SmallPtrSet<const PHINode*, 32> &LoadUsingPHIsPerLoad) {
Chris Lattner56b55382008-12-16 21:24:51 +00001057 // We permit two users of the load: setcc comparing against the null
1058 // pointer, and a getelementptr of a specific form.
Gabor Greif08d85da2010-04-07 18:59:26 +00001059 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;
1060 ++UI) {
Gabor Greif5d5db532010-04-01 08:21:08 +00001061 const Instruction *User = cast<Instruction>(*UI);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001062
Chris Lattner56b55382008-12-16 21:24:51 +00001063 // Comparison against null is ok.
Gabor Greif5d5db532010-04-01 08:21:08 +00001064 if (const ICmpInst *ICI = dyn_cast<ICmpInst>(User)) {
Chris Lattner56b55382008-12-16 21:24:51 +00001065 if (!isa<ConstantPointerNull>(ICI->getOperand(1)))
1066 return false;
1067 continue;
1068 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001069
Chris Lattner56b55382008-12-16 21:24:51 +00001070 // getelementptr is also ok, but only a simple form.
Gabor Greif5d5db532010-04-01 08:21:08 +00001071 if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
Chris Lattner56b55382008-12-16 21:24:51 +00001072 // Must index into the array and into the struct.
1073 if (GEPI->getNumOperands() < 3)
1074 return false;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001075
Chris Lattner56b55382008-12-16 21:24:51 +00001076 // Otherwise the GEP is ok.
1077 continue;
1078 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001079
Gabor Greif5d5db532010-04-01 08:21:08 +00001080 if (const PHINode *PN = dyn_cast<PHINode>(User)) {
Evan Cheng83689442009-06-02 00:56:07 +00001081 if (!LoadUsingPHIsPerLoad.insert(PN))
1082 // This means some phi nodes are dependent on each other.
1083 // Avoid infinite looping!
1084 return false;
1085 if (!LoadUsingPHIs.insert(PN))
1086 // If we have already analyzed this PHI, then it is safe.
Chris Lattner56b55382008-12-16 21:24:51 +00001087 continue;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001088
Chris Lattner222ef4c2008-12-17 05:28:49 +00001089 // Make sure all uses of the PHI are simple enough to transform.
Evan Cheng83689442009-06-02 00:56:07 +00001090 if (!LoadUsesSimpleEnoughForHeapSRA(PN,
1091 LoadUsingPHIs, LoadUsingPHIsPerLoad))
Chris Lattner56b55382008-12-16 21:24:51 +00001092 return false;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001093
Chris Lattner56b55382008-12-16 21:24:51 +00001094 continue;
Chris Lattner24d3d422006-09-30 23:32:09 +00001095 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001096
Chris Lattner56b55382008-12-16 21:24:51 +00001097 // Otherwise we don't know what this is, not ok.
1098 return false;
1099 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001100
Chris Lattner56b55382008-12-16 21:24:51 +00001101 return true;
1102}
1103
1104
1105/// AllGlobalLoadUsesSimpleEnoughForHeapSRA - If all users of values loaded from
1106/// GV are simple enough to perform HeapSRA, return true.
Gabor Greif5d5db532010-04-01 08:21:08 +00001107static bool AllGlobalLoadUsesSimpleEnoughForHeapSRA(const GlobalVariable *GV,
Victor Hernandez5d034492009-09-18 22:35:49 +00001108 Instruction *StoredVal) {
Gabor Greif5d5db532010-04-01 08:21:08 +00001109 SmallPtrSet<const PHINode*, 32> LoadUsingPHIs;
1110 SmallPtrSet<const PHINode*, 32> LoadUsingPHIsPerLoad;
Gabor Greif08d85da2010-04-07 18:59:26 +00001111 for (Value::const_use_iterator UI = GV->use_begin(), E = GV->use_end();
1112 UI != E; ++UI)
Gabor Greif5d5db532010-04-01 08:21:08 +00001113 if (const LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
Evan Cheng83689442009-06-02 00:56:07 +00001114 if (!LoadUsesSimpleEnoughForHeapSRA(LI, LoadUsingPHIs,
1115 LoadUsingPHIsPerLoad))
Chris Lattner56b55382008-12-16 21:24:51 +00001116 return false;
Evan Cheng83689442009-06-02 00:56:07 +00001117 LoadUsingPHIsPerLoad.clear();
1118 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001119
Chris Lattner222ef4c2008-12-17 05:28:49 +00001120 // If we reach here, we know that all uses of the loads and transitive uses
1121 // (through PHI nodes) are simple enough to transform. However, we don't know
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001122 // that all inputs the to the PHI nodes are in the same equivalence sets.
Chris Lattner222ef4c2008-12-17 05:28:49 +00001123 // Check to verify that all operands of the PHIs are either PHIS that can be
1124 // transformed, loads from GV, or MI itself.
Gabor Greif08d85da2010-04-07 18:59:26 +00001125 for (SmallPtrSet<const PHINode*, 32>::const_iterator I = LoadUsingPHIs.begin()
1126 , E = LoadUsingPHIs.end(); I != E; ++I) {
Gabor Greif5d5db532010-04-01 08:21:08 +00001127 const PHINode *PN = *I;
Chris Lattner222ef4c2008-12-17 05:28:49 +00001128 for (unsigned op = 0, e = PN->getNumIncomingValues(); op != e; ++op) {
1129 Value *InVal = PN->getIncomingValue(op);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001130
Chris Lattner222ef4c2008-12-17 05:28:49 +00001131 // PHI of the stored value itself is ok.
Victor Hernandez5d034492009-09-18 22:35:49 +00001132 if (InVal == StoredVal) continue;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001133
Gabor Greif5d5db532010-04-01 08:21:08 +00001134 if (const PHINode *InPN = dyn_cast<PHINode>(InVal)) {
Chris Lattner222ef4c2008-12-17 05:28:49 +00001135 // One of the PHIs in our set is (optimistically) ok.
1136 if (LoadUsingPHIs.count(InPN))
1137 continue;
1138 return false;
1139 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001140
Chris Lattner222ef4c2008-12-17 05:28:49 +00001141 // Load from GV is ok.
Gabor Greif5d5db532010-04-01 08:21:08 +00001142 if (const LoadInst *LI = dyn_cast<LoadInst>(InVal))
Chris Lattner222ef4c2008-12-17 05:28:49 +00001143 if (LI->getOperand(0) == GV)
1144 continue;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001145
Chris Lattner222ef4c2008-12-17 05:28:49 +00001146 // UNDEF? NULL?
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001147
Chris Lattner222ef4c2008-12-17 05:28:49 +00001148 // Anything else is rejected.
1149 return false;
1150 }
1151 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001152
Chris Lattner24d3d422006-09-30 23:32:09 +00001153 return true;
1154}
1155
Chris Lattner222ef4c2008-12-17 05:28:49 +00001156static Value *GetHeapSROAValue(Value *V, unsigned FieldNo,
1157 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Chris Lattner46b5c642009-11-06 04:27:31 +00001158 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
Chris Lattner222ef4c2008-12-17 05:28:49 +00001159 std::vector<Value*> &FieldVals = InsertedScalarizedValues[V];
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001160
Chris Lattner222ef4c2008-12-17 05:28:49 +00001161 if (FieldNo >= FieldVals.size())
1162 FieldVals.resize(FieldNo+1);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001163
Chris Lattner222ef4c2008-12-17 05:28:49 +00001164 // If we already have this value, just reuse the previously scalarized
1165 // version.
1166 if (Value *FieldVal = FieldVals[FieldNo])
1167 return FieldVal;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001168
Chris Lattner222ef4c2008-12-17 05:28:49 +00001169 // Depending on what instruction this is, we have several cases.
1170 Value *Result;
1171 if (LoadInst *LI = dyn_cast<LoadInst>(V)) {
1172 // This is a scalarized version of the load from the global. Just create
1173 // a new Load of the scalarized global.
1174 Result = new LoadInst(GetHeapSROAValue(LI->getOperand(0), FieldNo,
1175 InsertedScalarizedValues,
Chris Lattner46b5c642009-11-06 04:27:31 +00001176 PHIsToRewrite),
Daniel Dunbar132f7832009-07-30 17:37:43 +00001177 LI->getName()+".f"+Twine(FieldNo), LI);
Chris Lattner222ef4c2008-12-17 05:28:49 +00001178 } else if (PHINode *PN = dyn_cast<PHINode>(V)) {
1179 // PN's type is pointer to struct. Make a new PHI of pointer to struct
1180 // field.
Matt Arsenault404c60a2013-10-21 19:43:56 +00001181 StructType *ST = cast<StructType>(PN->getType()->getPointerElementType());
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001182
Jay Foade0938d82011-03-30 11:19:20 +00001183 PHINode *NewPN =
Owen Anderson4056ca92009-07-29 22:17:13 +00001184 PHINode::Create(PointerType::getUnqual(ST->getElementType(FieldNo)),
Jay Foad52131342011-03-30 11:28:46 +00001185 PN->getNumIncomingValues(),
Daniel Dunbar132f7832009-07-30 17:37:43 +00001186 PN->getName()+".f"+Twine(FieldNo), PN);
Jay Foade0938d82011-03-30 11:19:20 +00001187 Result = NewPN;
Chris Lattner222ef4c2008-12-17 05:28:49 +00001188 PHIsToRewrite.push_back(std::make_pair(PN, FieldNo));
1189 } else {
Torok Edwinfbcc6632009-07-14 16:55:14 +00001190 llvm_unreachable("Unknown usable value");
Chris Lattner222ef4c2008-12-17 05:28:49 +00001191 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001192
Chris Lattner222ef4c2008-12-17 05:28:49 +00001193 return FieldVals[FieldNo] = Result;
Chris Lattnerba98f892007-09-13 18:00:31 +00001194}
1195
Chris Lattnerf315d4f2007-09-13 17:29:05 +00001196/// RewriteHeapSROALoadUser - Given a load instruction and a value derived from
1197/// the load, rewrite the derived value to use the HeapSRoA'd load.
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001198static void RewriteHeapSROALoadUser(Instruction *LoadUser,
Chris Lattner222ef4c2008-12-17 05:28:49 +00001199 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Chris Lattner46b5c642009-11-06 04:27:31 +00001200 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
Chris Lattnerf315d4f2007-09-13 17:29:05 +00001201 // If this is a comparison against null, handle it.
1202 if (ICmpInst *SCI = dyn_cast<ICmpInst>(LoadUser)) {
1203 assert(isa<ConstantPointerNull>(SCI->getOperand(1)));
1204 // If we have a setcc of the loaded pointer, we can use a setcc of any
1205 // field.
Chris Lattner222ef4c2008-12-17 05:28:49 +00001206 Value *NPtr = GetHeapSROAValue(SCI->getOperand(0), 0,
Chris Lattner46b5c642009-11-06 04:27:31 +00001207 InsertedScalarizedValues, PHIsToRewrite);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001208
Owen Anderson1e5f00e2009-07-09 23:48:35 +00001209 Value *New = new ICmpInst(SCI, SCI->getPredicate(), NPtr,
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001210 Constant::getNullValue(NPtr->getType()),
Owen Anderson1e5f00e2009-07-09 23:48:35 +00001211 SCI->getName());
Chris Lattnerf315d4f2007-09-13 17:29:05 +00001212 SCI->replaceAllUsesWith(New);
1213 SCI->eraseFromParent();
1214 return;
1215 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001216
Chris Lattner222ef4c2008-12-17 05:28:49 +00001217 // Handle 'getelementptr Ptr, Idx, i32 FieldNo ...'
Chris Lattnerba98f892007-09-13 18:00:31 +00001218 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(LoadUser)) {
1219 assert(GEPI->getNumOperands() >= 3 && isa<ConstantInt>(GEPI->getOperand(2))
1220 && "Unexpected GEPI!");
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001221
Chris Lattnerba98f892007-09-13 18:00:31 +00001222 // Load the pointer for this field.
1223 unsigned FieldNo = cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue();
Chris Lattner222ef4c2008-12-17 05:28:49 +00001224 Value *NewPtr = GetHeapSROAValue(GEPI->getOperand(0), FieldNo,
Chris Lattner46b5c642009-11-06 04:27:31 +00001225 InsertedScalarizedValues, PHIsToRewrite);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001226
Chris Lattnerba98f892007-09-13 18:00:31 +00001227 // Create the new GEP idx vector.
1228 SmallVector<Value*, 8> GEPIdx;
1229 GEPIdx.push_back(GEPI->getOperand(1));
1230 GEPIdx.append(GEPI->op_begin()+3, GEPI->op_end());
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001231
Jay Foadd1b78492011-07-25 09:48:08 +00001232 Value *NGEPI = GetElementPtrInst::Create(NewPtr, GEPIdx,
Gabor Greife9ecc682008-04-06 20:25:17 +00001233 GEPI->getName(), GEPI);
Chris Lattnerba98f892007-09-13 18:00:31 +00001234 GEPI->replaceAllUsesWith(NGEPI);
1235 GEPI->eraseFromParent();
1236 return;
1237 }
Chris Lattner011f91b2007-09-13 21:31:36 +00001238
Chris Lattner222ef4c2008-12-17 05:28:49 +00001239 // Recursively transform the users of PHI nodes. This will lazily create the
1240 // PHIs that are needed for individual elements. Keep track of what PHIs we
1241 // see in InsertedScalarizedValues so that we don't get infinite loops (very
1242 // antisocial). If the PHI is already in InsertedScalarizedValues, it has
1243 // already been seen first by another load, so its uses have already been
1244 // processed.
1245 PHINode *PN = cast<PHINode>(LoadUser);
Chris Lattner5cf753c2011-07-21 06:21:31 +00001246 if (!InsertedScalarizedValues.insert(std::make_pair(PN,
1247 std::vector<Value*>())).second)
1248 return;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001249
Chris Lattner222ef4c2008-12-17 05:28:49 +00001250 // If this is the first time we've seen this PHI, recursively process all
1251 // users.
Chris Lattner0cdf5232008-12-17 05:42:08 +00001252 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end(); UI != E; ) {
1253 Instruction *User = cast<Instruction>(*UI++);
Chris Lattner46b5c642009-11-06 04:27:31 +00001254 RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite);
Chris Lattner0cdf5232008-12-17 05:42:08 +00001255 }
Chris Lattnerf315d4f2007-09-13 17:29:05 +00001256}
1257
Chris Lattner24d3d422006-09-30 23:32:09 +00001258/// RewriteUsesOfLoadForHeapSRoA - We are performing Heap SRoA on a global. Ptr
1259/// is a value loaded from the global. Eliminate all uses of Ptr, making them
1260/// use FieldGlobals instead. All uses of loaded values satisfy
Chris Lattner56b55382008-12-16 21:24:51 +00001261/// AllGlobalLoadUsesSimpleEnoughForHeapSRA.
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001262static void RewriteUsesOfLoadForHeapSRoA(LoadInst *Load,
Chris Lattner222ef4c2008-12-17 05:28:49 +00001263 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Chris Lattner46b5c642009-11-06 04:27:31 +00001264 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
Chris Lattner222ef4c2008-12-17 05:28:49 +00001265 for (Value::use_iterator UI = Load->use_begin(), E = Load->use_end();
Chris Lattner0cdf5232008-12-17 05:42:08 +00001266 UI != E; ) {
1267 Instruction *User = cast<Instruction>(*UI++);
Chris Lattner46b5c642009-11-06 04:27:31 +00001268 RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite);
Chris Lattner0cdf5232008-12-17 05:42:08 +00001269 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001270
Chris Lattner222ef4c2008-12-17 05:28:49 +00001271 if (Load->use_empty()) {
1272 Load->eraseFromParent();
1273 InsertedScalarizedValues.erase(Load);
1274 }
Chris Lattner24d3d422006-09-30 23:32:09 +00001275}
1276
Victor Hernandez5d034492009-09-18 22:35:49 +00001277/// PerformHeapAllocSRoA - CI is an allocation of an array of structures. Break
1278/// it up into multiple allocations of arrays of the fields.
Victor Hernandezf3db9152009-11-07 00:16:28 +00001279static GlobalVariable *PerformHeapAllocSRoA(GlobalVariable *GV, CallInst *CI,
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001280 Value *NElems, DataLayout *TD,
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00001281 const TargetLibraryInfo *TLI) {
David Greene44cb8ad2010-01-05 01:28:05 +00001282 DEBUG(dbgs() << "SROA HEAP ALLOC: " << *GV << " MALLOC = " << *CI << '\n');
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00001283 Type *MAT = getMallocAllocatedType(CI, TLI);
Chris Lattner229907c2011-07-18 04:54:35 +00001284 StructType *STy = cast<StructType>(MAT);
Victor Hernandez5d034492009-09-18 22:35:49 +00001285
1286 // There is guaranteed to be at least one use of the malloc (storing
1287 // it into GV). If there are other uses, change them to be uses of
1288 // the global to simplify later code. This also deletes the store
1289 // into GV.
Victor Hernandezf3db9152009-11-07 00:16:28 +00001290 ReplaceUsesOfMallocWithGlobal(CI, GV);
1291
Victor Hernandez5d034492009-09-18 22:35:49 +00001292 // Okay, at this point, there are no users of the malloc. Insert N
1293 // new mallocs at the same place as CI, and N globals.
1294 std::vector<Value*> FieldGlobals;
1295 std::vector<Value*> FieldMallocs;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001296
Victor Hernandez5d034492009-09-18 22:35:49 +00001297 for (unsigned FieldNo = 0, e = STy->getNumElements(); FieldNo != e;++FieldNo){
Chris Lattner229907c2011-07-18 04:54:35 +00001298 Type *FieldTy = STy->getElementType(FieldNo);
1299 PointerType *PFieldTy = PointerType::getUnqual(FieldTy);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001300
Victor Hernandez5d034492009-09-18 22:35:49 +00001301 GlobalVariable *NGV =
1302 new GlobalVariable(*GV->getParent(),
1303 PFieldTy, false, GlobalValue::InternalLinkage,
1304 Constant::getNullValue(PFieldTy),
1305 GV->getName() + ".f" + Twine(FieldNo), GV,
Hans Wennborgcbe34b42012-06-23 11:37:03 +00001306 GV->getThreadLocalMode());
Victor Hernandez5d034492009-09-18 22:35:49 +00001307 FieldGlobals.push_back(NGV);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001308
Victor Hernandezf3db9152009-11-07 00:16:28 +00001309 unsigned TypeSize = TD->getTypeAllocSize(FieldTy);
Chris Lattner229907c2011-07-18 04:54:35 +00001310 if (StructType *ST = dyn_cast<StructType>(FieldTy))
Victor Hernandezf3db9152009-11-07 00:16:28 +00001311 TypeSize = TD->getStructLayout(ST)->getSizeInBytes();
Matt Arsenaultd3471e92013-09-11 07:29:40 +00001312 Type *IntPtrTy = TD->getIntPtrType(CI->getType());
Victor Hernandezf3db9152009-11-07 00:16:28 +00001313 Value *NMI = CallInst::CreateMalloc(CI, IntPtrTy, FieldTy,
1314 ConstantInt::get(IntPtrTy, TypeSize),
Chris Lattner601e390a2010-07-12 00:57:28 +00001315 NElems, 0,
Victor Hernandezf3db9152009-11-07 00:16:28 +00001316 CI->getName() + ".f" + Twine(FieldNo));
Chris Lattner0521c092010-02-26 18:23:13 +00001317 FieldMallocs.push_back(NMI);
Victor Hernandezf3db9152009-11-07 00:16:28 +00001318 new StoreInst(NMI, NGV, CI);
Victor Hernandez5d034492009-09-18 22:35:49 +00001319 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001320
Victor Hernandez5d034492009-09-18 22:35:49 +00001321 // The tricky aspect of this transformation is handling the case when malloc
1322 // fails. In the original code, malloc failing would set the result pointer
1323 // of malloc to null. In this case, some mallocs could succeed and others
1324 // could fail. As such, we emit code that looks like this:
1325 // F0 = malloc(field0)
1326 // F1 = malloc(field1)
1327 // F2 = malloc(field2)
1328 // if (F0 == 0 || F1 == 0 || F2 == 0) {
1329 // if (F0) { free(F0); F0 = 0; }
1330 // if (F1) { free(F1); F1 = 0; }
1331 // if (F2) { free(F2); F2 = 0; }
1332 // }
Victor Hernandezfcc77b12009-11-10 08:32:25 +00001333 // The malloc can also fail if its argument is too large.
Gabor Greif218f5542010-06-24 14:42:01 +00001334 Constant *ConstantZero = ConstantInt::get(CI->getArgOperand(0)->getType(), 0);
1335 Value *RunningOr = new ICmpInst(CI, ICmpInst::ICMP_SLT, CI->getArgOperand(0),
Victor Hernandezfcc77b12009-11-10 08:32:25 +00001336 ConstantZero, "isneg");
Victor Hernandez5d034492009-09-18 22:35:49 +00001337 for (unsigned i = 0, e = FieldMallocs.size(); i != e; ++i) {
Victor Hernandezf3db9152009-11-07 00:16:28 +00001338 Value *Cond = new ICmpInst(CI, ICmpInst::ICMP_EQ, FieldMallocs[i],
1339 Constant::getNullValue(FieldMallocs[i]->getType()),
1340 "isnull");
Victor Hernandezfcc77b12009-11-10 08:32:25 +00001341 RunningOr = BinaryOperator::CreateOr(RunningOr, Cond, "tmp", CI);
Victor Hernandez5d034492009-09-18 22:35:49 +00001342 }
1343
1344 // Split the basic block at the old malloc.
Victor Hernandezf3db9152009-11-07 00:16:28 +00001345 BasicBlock *OrigBB = CI->getParent();
1346 BasicBlock *ContBB = OrigBB->splitBasicBlock(CI, "malloc_cont");
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001347
Victor Hernandez5d034492009-09-18 22:35:49 +00001348 // Create the block to check the first condition. Put all these blocks at the
1349 // end of the function as they are unlikely to be executed.
Chris Lattner46b5c642009-11-06 04:27:31 +00001350 BasicBlock *NullPtrBlock = BasicBlock::Create(OrigBB->getContext(),
1351 "malloc_ret_null",
Victor Hernandez5d034492009-09-18 22:35:49 +00001352 OrigBB->getParent());
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001353
Victor Hernandez5d034492009-09-18 22:35:49 +00001354 // Remove the uncond branch from OrigBB to ContBB, turning it into a cond
1355 // branch on RunningOr.
1356 OrigBB->getTerminator()->eraseFromParent();
1357 BranchInst::Create(NullPtrBlock, ContBB, RunningOr, OrigBB);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001358
Victor Hernandez5d034492009-09-18 22:35:49 +00001359 // Within the NullPtrBlock, we need to emit a comparison and branch for each
1360 // pointer, because some may be null while others are not.
1361 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
1362 Value *GVVal = new LoadInst(FieldGlobals[i], "tmp", NullPtrBlock);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001363 Value *Cmp = new ICmpInst(*NullPtrBlock, ICmpInst::ICMP_NE, GVVal,
Benjamin Kramer547b6c52011-09-27 20:39:19 +00001364 Constant::getNullValue(GVVal->getType()));
Chris Lattner46b5c642009-11-06 04:27:31 +00001365 BasicBlock *FreeBlock = BasicBlock::Create(Cmp->getContext(), "free_it",
Victor Hernandez5d034492009-09-18 22:35:49 +00001366 OrigBB->getParent());
Chris Lattner46b5c642009-11-06 04:27:31 +00001367 BasicBlock *NextBlock = BasicBlock::Create(Cmp->getContext(), "next",
Victor Hernandez5d034492009-09-18 22:35:49 +00001368 OrigBB->getParent());
Victor Hernandeze2971492009-10-24 04:23:03 +00001369 Instruction *BI = BranchInst::Create(FreeBlock, NextBlock,
1370 Cmp, NullPtrBlock);
Victor Hernandez5d034492009-09-18 22:35:49 +00001371
1372 // Fill in FreeBlock.
Victor Hernandeze2971492009-10-24 04:23:03 +00001373 CallInst::CreateFree(GVVal, BI);
Victor Hernandez5d034492009-09-18 22:35:49 +00001374 new StoreInst(Constant::getNullValue(GVVal->getType()), FieldGlobals[i],
1375 FreeBlock);
1376 BranchInst::Create(NextBlock, FreeBlock);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001377
Victor Hernandez5d034492009-09-18 22:35:49 +00001378 NullPtrBlock = NextBlock;
1379 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001380
Victor Hernandez5d034492009-09-18 22:35:49 +00001381 BranchInst::Create(ContBB, NullPtrBlock);
Victor Hernandezf3db9152009-11-07 00:16:28 +00001382
1383 // CI is no longer needed, remove it.
Victor Hernandez5d034492009-09-18 22:35:49 +00001384 CI->eraseFromParent();
1385
1386 /// InsertedScalarizedLoads - As we process loads, if we can't immediately
1387 /// update all uses of the load, keep track of what scalarized loads are
1388 /// inserted for a given load.
1389 DenseMap<Value*, std::vector<Value*> > InsertedScalarizedValues;
1390 InsertedScalarizedValues[GV] = FieldGlobals;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001391
Victor Hernandez5d034492009-09-18 22:35:49 +00001392 std::vector<std::pair<PHINode*, unsigned> > PHIsToRewrite;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001393
Victor Hernandez5d034492009-09-18 22:35:49 +00001394 // Okay, the malloc site is completely handled. All of the uses of GV are now
1395 // loads, and all uses of those loads are simple. Rewrite them to use loads
1396 // of the per-field globals instead.
1397 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI != E;) {
1398 Instruction *User = cast<Instruction>(*UI++);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001399
Victor Hernandez5d034492009-09-18 22:35:49 +00001400 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Chris Lattner46b5c642009-11-06 04:27:31 +00001401 RewriteUsesOfLoadForHeapSRoA(LI, InsertedScalarizedValues, PHIsToRewrite);
Victor Hernandez5d034492009-09-18 22:35:49 +00001402 continue;
1403 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001404
Victor Hernandez5d034492009-09-18 22:35:49 +00001405 // Must be a store of null.
1406 StoreInst *SI = cast<StoreInst>(User);
1407 assert(isa<ConstantPointerNull>(SI->getOperand(0)) &&
1408 "Unexpected heap-sra user!");
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001409
Victor Hernandez5d034492009-09-18 22:35:49 +00001410 // Insert a store of null into each global.
1411 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
Chris Lattner229907c2011-07-18 04:54:35 +00001412 PointerType *PT = cast<PointerType>(FieldGlobals[i]->getType());
Victor Hernandez5d034492009-09-18 22:35:49 +00001413 Constant *Null = Constant::getNullValue(PT->getElementType());
1414 new StoreInst(Null, FieldGlobals[i], SI);
1415 }
1416 // Erase the original store.
1417 SI->eraseFromParent();
1418 }
1419
1420 // While we have PHIs that are interesting to rewrite, do it.
1421 while (!PHIsToRewrite.empty()) {
1422 PHINode *PN = PHIsToRewrite.back().first;
1423 unsigned FieldNo = PHIsToRewrite.back().second;
1424 PHIsToRewrite.pop_back();
1425 PHINode *FieldPN = cast<PHINode>(InsertedScalarizedValues[PN][FieldNo]);
1426 assert(FieldPN->getNumIncomingValues() == 0 &&"Already processed this phi");
1427
1428 // Add all the incoming values. This can materialize more phis.
1429 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1430 Value *InVal = PN->getIncomingValue(i);
1431 InVal = GetHeapSROAValue(InVal, FieldNo, InsertedScalarizedValues,
Chris Lattner46b5c642009-11-06 04:27:31 +00001432 PHIsToRewrite);
Victor Hernandez5d034492009-09-18 22:35:49 +00001433 FieldPN->addIncoming(InVal, PN->getIncomingBlock(i));
1434 }
1435 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001436
Victor Hernandez5d034492009-09-18 22:35:49 +00001437 // Drop all inter-phi links and any loads that made it this far.
1438 for (DenseMap<Value*, std::vector<Value*> >::iterator
1439 I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
1440 I != E; ++I) {
1441 if (PHINode *PN = dyn_cast<PHINode>(I->first))
1442 PN->dropAllReferences();
1443 else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
1444 LI->dropAllReferences();
1445 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001446
Victor Hernandez5d034492009-09-18 22:35:49 +00001447 // Delete all the phis and loads now that inter-references are dead.
1448 for (DenseMap<Value*, std::vector<Value*> >::iterator
1449 I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
1450 I != E; ++I) {
1451 if (PHINode *PN = dyn_cast<PHINode>(I->first))
1452 PN->eraseFromParent();
1453 else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
1454 LI->eraseFromParent();
1455 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001456
Victor Hernandez5d034492009-09-18 22:35:49 +00001457 // The old global is now dead, remove it.
1458 GV->eraseFromParent();
1459
1460 ++NumHeapSRA;
1461 return cast<GlobalVariable>(FieldGlobals[0]);
1462}
1463
Chris Lattnerc4274a72008-12-15 21:02:25 +00001464/// TryToOptimizeStoreOfMallocToGlobal - This function is called when we see a
1465/// pointer global variable with a single value stored it that is a malloc or
1466/// cast of malloc.
1467static bool TryToOptimizeStoreOfMallocToGlobal(GlobalVariable *GV,
Victor Hernandez5d034492009-09-18 22:35:49 +00001468 CallInst *CI,
Chris Lattner229907c2011-07-18 04:54:35 +00001469 Type *AllocTy,
Nick Lewycky52da72b2012-02-05 19:56:38 +00001470 AtomicOrdering Ordering,
Victor Hernandez5d034492009-09-18 22:35:49 +00001471 Module::global_iterator &GVI,
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001472 DataLayout *TD,
Nick Lewyckycf6aae62012-02-12 01:13:18 +00001473 TargetLibraryInfo *TLI) {
Evan Cheng21b588b2010-04-14 20:52:55 +00001474 if (!TD)
1475 return false;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001476
Victor Hernandez5d034492009-09-18 22:35:49 +00001477 // If this is a malloc of an abstract type, don't touch it.
1478 if (!AllocTy->isSized())
1479 return false;
1480
1481 // We can't optimize this global unless all uses of it are *known* to be
1482 // of the malloc value, not of the null initializer value (consider a use
1483 // that compares the global's value against zero to see if the malloc has
1484 // been reached). To do this, we check to see if all uses of the global
1485 // would trap if the global were null: this proves that they must all
1486 // happen after the malloc.
1487 if (!AllUsesOfLoadedValueWillTrapIfNull(GV))
1488 return false;
1489
1490 // We can't optimize this if the malloc itself is used in a complex way,
1491 // for example, being stored into multiple globals. This allows the
Nick Lewyckybbd11562012-02-05 19:48:37 +00001492 // malloc to be stored into the specified global, loaded icmp'd, and
Victor Hernandez5d034492009-09-18 22:35:49 +00001493 // GEP'd. These are all things we could transform to using the global
1494 // for.
Evan Cheng21b588b2010-04-14 20:52:55 +00001495 SmallPtrSet<const PHINode*, 8> PHIs;
1496 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(CI, GV, PHIs))
1497 return false;
Victor Hernandez5d034492009-09-18 22:35:49 +00001498
1499 // If we have a global that is only initialized with a fixed size malloc,
1500 // transform the program to use global memory instead of malloc'd memory.
1501 // This eliminates dynamic allocation, avoids an indirection accessing the
1502 // data, and exposes the resultant global to further GlobalOpt.
Victor Hernandez264da322009-10-16 23:12:25 +00001503 // We cannot optimize the malloc if we cannot determine malloc array size.
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00001504 Value *NElems = getMallocArraySize(CI, TD, TLI, true);
Evan Cheng21b588b2010-04-14 20:52:55 +00001505 if (!NElems)
1506 return false;
Victor Hernandez5d034492009-09-18 22:35:49 +00001507
Evan Cheng21b588b2010-04-14 20:52:55 +00001508 if (ConstantInt *NElements = dyn_cast<ConstantInt>(NElems))
1509 // Restrict this transformation to only working on small allocations
1510 // (2048 bytes currently), as we don't want to introduce a 16M global or
1511 // something.
1512 if (NElements->getZExtValue() * TD->getTypeAllocSize(AllocTy) < 2048) {
Nick Lewyckycf6aae62012-02-12 01:13:18 +00001513 GVI = OptimizeGlobalAddressOfMalloc(GV, CI, AllocTy, NElements, TD, TLI);
Evan Cheng21b588b2010-04-14 20:52:55 +00001514 return true;
Victor Hernandez5d034492009-09-18 22:35:49 +00001515 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001516
Evan Cheng21b588b2010-04-14 20:52:55 +00001517 // If the allocation is an array of structures, consider transforming this
1518 // into multiple malloc'd arrays, one for each field. This is basically
1519 // SRoA for malloc'd memory.
1520
Nick Lewycky52da72b2012-02-05 19:56:38 +00001521 if (Ordering != NotAtomic)
1522 return false;
1523
Evan Cheng21b588b2010-04-14 20:52:55 +00001524 // If this is an allocation of a fixed size array of structs, analyze as a
1525 // variable size array. malloc [100 x struct],1 -> malloc struct, 100
Gabor Greif218f5542010-06-24 14:42:01 +00001526 if (NElems == ConstantInt::get(CI->getArgOperand(0)->getType(), 1))
Chris Lattner229907c2011-07-18 04:54:35 +00001527 if (ArrayType *AT = dyn_cast<ArrayType>(AllocTy))
Evan Cheng21b588b2010-04-14 20:52:55 +00001528 AllocTy = AT->getElementType();
Gabor Greif218f5542010-06-24 14:42:01 +00001529
Chris Lattner229907c2011-07-18 04:54:35 +00001530 StructType *AllocSTy = dyn_cast<StructType>(AllocTy);
Evan Cheng21b588b2010-04-14 20:52:55 +00001531 if (!AllocSTy)
1532 return false;
1533
1534 // This the structure has an unreasonable number of fields, leave it
1535 // alone.
1536 if (AllocSTy->getNumElements() <= 16 && AllocSTy->getNumElements() != 0 &&
1537 AllGlobalLoadUsesSimpleEnoughForHeapSRA(GV, CI)) {
1538
1539 // If this is a fixed size array, transform the Malloc to be an alloc of
1540 // structs. malloc [100 x struct],1 -> malloc struct, 100
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00001541 if (ArrayType *AT = dyn_cast<ArrayType>(getMallocAllocatedType(CI, TLI))) {
Matt Arsenaultd3471e92013-09-11 07:29:40 +00001542 Type *IntPtrTy = TD->getIntPtrType(CI->getType());
Evan Cheng21b588b2010-04-14 20:52:55 +00001543 unsigned TypeSize = TD->getStructLayout(AllocSTy)->getSizeInBytes();
1544 Value *AllocSize = ConstantInt::get(IntPtrTy, TypeSize);
1545 Value *NumElements = ConstantInt::get(IntPtrTy, AT->getNumElements());
1546 Instruction *Malloc = CallInst::CreateMalloc(CI, IntPtrTy, AllocSTy,
1547 AllocSize, NumElements,
Chris Lattner601e390a2010-07-12 00:57:28 +00001548 0, CI->getName());
Evan Cheng21b588b2010-04-14 20:52:55 +00001549 Instruction *Cast = new BitCastInst(Malloc, CI->getType(), "tmp", CI);
1550 CI->replaceAllUsesWith(Cast);
1551 CI->eraseFromParent();
Nuno Lopes9792d682012-06-22 00:25:01 +00001552 if (BitCastInst *BCI = dyn_cast<BitCastInst>(Malloc))
1553 CI = cast<CallInst>(BCI->getOperand(0));
1554 else
Nuno Lopes0b60ebb2012-06-22 00:29:58 +00001555 CI = cast<CallInst>(Malloc);
Evan Cheng21b588b2010-04-14 20:52:55 +00001556 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001557
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00001558 GVI = PerformHeapAllocSRoA(GV, CI, getMallocArraySize(CI, TD, TLI, true),
1559 TD, TLI);
Evan Cheng21b588b2010-04-14 20:52:55 +00001560 return true;
Victor Hernandez5d034492009-09-18 22:35:49 +00001561 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001562
Victor Hernandez5d034492009-09-18 22:35:49 +00001563 return false;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001564}
Victor Hernandez5d034492009-09-18 22:35:49 +00001565
Chris Lattner09a52722004-10-09 21:48:45 +00001566// OptimizeOnceStoredGlobal - Try to optimize globals based on the knowledge
1567// that only one value (besides its initializer) is ever stored to the global.
Chris Lattner004e2502004-10-11 05:54:41 +00001568static bool OptimizeOnceStoredGlobal(GlobalVariable *GV, Value *StoredOnceVal,
Nick Lewycky52da72b2012-02-05 19:56:38 +00001569 AtomicOrdering Ordering,
Chris Lattnerc2d3d312006-08-27 22:42:52 +00001570 Module::global_iterator &GVI,
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001571 DataLayout *TD, TargetLibraryInfo *TLI) {
Chris Lattner1c731fa2008-12-15 21:20:32 +00001572 // Ignore no-op GEPs and bitcasts.
1573 StoredOnceVal = StoredOnceVal->stripPointerCasts();
Chris Lattner09a52722004-10-09 21:48:45 +00001574
Chris Lattnere42eb312004-10-10 23:14:11 +00001575 // If we are dealing with a pointer global that is initialized to null and
1576 // only has one (non-null) value stored into it, then we can optimize any
1577 // users of the loaded value (often calls and loads) that would trap if the
1578 // value was null.
Duncan Sands19d0b472010-02-16 11:11:14 +00001579 if (GV->getInitializer()->getType()->isPointerTy() &&
Chris Lattner09a52722004-10-09 21:48:45 +00001580 GV->getInitializer()->isNullValue()) {
Chris Lattnere42eb312004-10-10 23:14:11 +00001581 if (Constant *SOVC = dyn_cast<Constant>(StoredOnceVal)) {
1582 if (GV->getInitializer()->getType() != SOVC->getType())
Chris Lattner1a1acc22011-05-22 07:15:13 +00001583 SOVC = ConstantExpr::getBitCast(SOVC, GV->getInitializer()->getType());
Misha Brukmanb1c93172005-04-21 23:48:37 +00001584
Chris Lattnere42eb312004-10-10 23:14:11 +00001585 // Optimize away any trapping uses of the loaded value.
Nick Lewyckycf6aae62012-02-12 01:13:18 +00001586 if (OptimizeAwayTrappingUsesOfLoads(GV, SOVC, TD, TLI))
Chris Lattner604ed7a2004-10-10 17:07:12 +00001587 return true;
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00001588 } else if (CallInst *CI = extractMallocCall(StoredOnceVal, TLI)) {
1589 Type *MallocType = getMallocAllocatedType(CI, TLI);
Nick Lewyckycf6aae62012-02-12 01:13:18 +00001590 if (MallocType &&
1591 TryToOptimizeStoreOfMallocToGlobal(GV, CI, MallocType, Ordering, GVI,
1592 TD, TLI))
Victor Hernandezf3db9152009-11-07 00:16:28 +00001593 return true;
Chris Lattnere42eb312004-10-10 23:14:11 +00001594 }
Chris Lattner09a52722004-10-09 21:48:45 +00001595 }
Chris Lattner004e2502004-10-11 05:54:41 +00001596
Chris Lattner09a52722004-10-09 21:48:45 +00001597 return false;
1598}
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001599
Chris Lattner20bbac32008-01-14 01:17:44 +00001600/// TryToShrinkGlobalToBoolean - At this point, we have learned that the only
1601/// two values ever stored into GV are its initializer and OtherVal. See if we
1602/// can shrink the global into a boolean and select between the two values
1603/// whenever it is used. This exposes the values to other scalar optimizations.
Chris Lattner46b5c642009-11-06 04:27:31 +00001604static bool TryToShrinkGlobalToBoolean(GlobalVariable *GV, Constant *OtherVal) {
Chris Lattner229907c2011-07-18 04:54:35 +00001605 Type *GVElType = GV->getType()->getElementType();
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001606
Chris Lattner20bbac32008-01-14 01:17:44 +00001607 // If GVElType is already i1, it is already shrunk. If the type of the GV is
Chris Lattnere3132832009-03-07 23:32:02 +00001608 // an FP value, pointer or vector, don't do this optimization because a select
1609 // between them is very expensive and unlikely to lead to later
1610 // simplification. In these cases, we typically end up with "cond ? v1 : v2"
1611 // where v1 and v2 both require constant pool loads, a big loss.
Chris Lattner46b5c642009-11-06 04:27:31 +00001612 if (GVElType == Type::getInt1Ty(GV->getContext()) ||
Duncan Sands9dff9be2010-02-15 16:12:20 +00001613 GVElType->isFloatingPointTy() ||
Duncan Sands19d0b472010-02-16 11:11:14 +00001614 GVElType->isPointerTy() || GVElType->isVectorTy())
Chris Lattner20bbac32008-01-14 01:17:44 +00001615 return false;
Gabor Greifa75ed762010-07-12 14:13:15 +00001616
Chris Lattner20bbac32008-01-14 01:17:44 +00001617 // Walk the use list of the global seeing if all the uses are load or store.
1618 // If there is anything else, bail out.
Gabor Greifa75ed762010-07-12 14:13:15 +00001619 for (Value::use_iterator I = GV->use_begin(), E = GV->use_end(); I != E; ++I){
1620 User *U = *I;
1621 if (!isa<LoadInst>(U) && !isa<StoreInst>(U))
Chris Lattner20bbac32008-01-14 01:17:44 +00001622 return false;
Gabor Greifa75ed762010-07-12 14:13:15 +00001623 }
1624
David Greene44cb8ad2010-01-05 01:28:05 +00001625 DEBUG(dbgs() << " *** SHRINKING TO BOOL: " << *GV);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001626
Chris Lattner40e4cec2004-12-12 05:53:50 +00001627 // Create the new global, initializing it to false.
Chris Lattner46b5c642009-11-06 04:27:31 +00001628 GlobalVariable *NewGV = new GlobalVariable(Type::getInt1Ty(GV->getContext()),
1629 false,
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001630 GlobalValue::InternalLinkage,
Chris Lattner46b5c642009-11-06 04:27:31 +00001631 ConstantInt::getFalse(GV->getContext()),
Nick Lewycky431f97e2009-05-03 03:49:08 +00001632 GV->getName()+".b",
Joey Gouly58bf9512013-01-10 10:31:11 +00001633 GV->getThreadLocalMode(),
1634 GV->getType()->getAddressSpace());
Chris Lattner40e4cec2004-12-12 05:53:50 +00001635 GV->getParent()->getGlobalList().insert(GV, NewGV);
1636
1637 Constant *InitVal = GV->getInitializer();
Chris Lattner46b5c642009-11-06 04:27:31 +00001638 assert(InitVal->getType() != Type::getInt1Ty(GV->getContext()) &&
Owen Anderson55f1c092009-08-13 21:58:54 +00001639 "No reason to shrink to bool!");
Chris Lattner40e4cec2004-12-12 05:53:50 +00001640
1641 // If initialized to zero and storing one into the global, we can use a cast
1642 // instead of a select to synthesize the desired value.
1643 bool IsOneZero = false;
1644 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal))
Reid Spencer2e54a152007-03-02 00:28:52 +00001645 IsOneZero = InitVal->isNullValue() && CI->isOne();
Chris Lattner40e4cec2004-12-12 05:53:50 +00001646
1647 while (!GV->use_empty()) {
Devang Patelfc507a12009-03-06 01:39:36 +00001648 Instruction *UI = cast<Instruction>(GV->use_back());
1649 if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
Chris Lattner40e4cec2004-12-12 05:53:50 +00001650 // Change the store into a boolean store.
1651 bool StoringOther = SI->getOperand(0) == OtherVal;
1652 // Only do this if we weren't storing a loaded value.
Chris Lattner745196a2004-12-12 19:34:41 +00001653 Value *StoreVal;
Bill Wendling7297b862013-02-13 23:00:51 +00001654 if (StoringOther || SI->getOperand(0) == InitVal) {
Chris Lattner46b5c642009-11-06 04:27:31 +00001655 StoreVal = ConstantInt::get(Type::getInt1Ty(GV->getContext()),
1656 StoringOther);
Bill Wendling7297b862013-02-13 23:00:51 +00001657 } else {
Chris Lattner745196a2004-12-12 19:34:41 +00001658 // Otherwise, we are storing a previously loaded copy. To do this,
1659 // change the copy from copying the original value to just copying the
1660 // bool.
1661 Instruction *StoredVal = cast<Instruction>(SI->getOperand(0));
1662
Gabor Greif218f5542010-06-24 14:42:01 +00001663 // If we've already replaced the input, StoredVal will be a cast or
Chris Lattner745196a2004-12-12 19:34:41 +00001664 // select instruction. If not, it will be a load of the original
1665 // global.
1666 if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
1667 assert(LI->getOperand(0) == GV && "Not a copy!");
1668 // Insert a new load, to preserve the saved value.
Nick Lewycky52da72b2012-02-05 19:56:38 +00001669 StoreVal = new LoadInst(NewGV, LI->getName()+".b", false, 0,
1670 LI->getOrdering(), LI->getSynchScope(), LI);
Chris Lattner745196a2004-12-12 19:34:41 +00001671 } else {
1672 assert((isa<CastInst>(StoredVal) || isa<SelectInst>(StoredVal)) &&
1673 "This is not a form that we understand!");
1674 StoreVal = StoredVal->getOperand(0);
1675 assert(isa<LoadInst>(StoreVal) && "Not a load of NewGV!");
1676 }
1677 }
Nick Lewycky52da72b2012-02-05 19:56:38 +00001678 new StoreInst(StoreVal, NewGV, false, 0,
1679 SI->getOrdering(), SI->getSynchScope(), SI);
Devang Patelfc507a12009-03-06 01:39:36 +00001680 } else {
Chris Lattner40e4cec2004-12-12 05:53:50 +00001681 // Change the load into a load of bool then a select.
Devang Patelfc507a12009-03-06 01:39:36 +00001682 LoadInst *LI = cast<LoadInst>(UI);
Nick Lewycky52da72b2012-02-05 19:56:38 +00001683 LoadInst *NLI = new LoadInst(NewGV, LI->getName()+".b", false, 0,
1684 LI->getOrdering(), LI->getSynchScope(), LI);
Chris Lattner40e4cec2004-12-12 05:53:50 +00001685 Value *NSI;
1686 if (IsOneZero)
Chris Lattner8d4c36b2007-02-11 01:08:35 +00001687 NSI = new ZExtInst(NLI, LI->getType(), "", LI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001688 else
Gabor Greife9ecc682008-04-06 20:25:17 +00001689 NSI = SelectInst::Create(NLI, OtherVal, InitVal, "", LI);
Chris Lattner8d4c36b2007-02-11 01:08:35 +00001690 NSI->takeName(LI);
Chris Lattner40e4cec2004-12-12 05:53:50 +00001691 LI->replaceAllUsesWith(NSI);
Devang Patelfc507a12009-03-06 01:39:36 +00001692 }
1693 UI->eraseFromParent();
Chris Lattner40e4cec2004-12-12 05:53:50 +00001694 }
1695
Bill Wendling7297b862013-02-13 23:00:51 +00001696 // Retain the name of the old global variable. People who are debugging their
1697 // programs may expect these variables to be named the same.
1698 NewGV->takeName(GV);
Chris Lattner40e4cec2004-12-12 05:53:50 +00001699 GV->eraseFromParent();
Chris Lattner20bbac32008-01-14 01:17:44 +00001700 return true;
Chris Lattner40e4cec2004-12-12 05:53:50 +00001701}
1702
1703
Nick Lewycky1480f1d2012-02-12 00:52:26 +00001704/// ProcessGlobal - Analyze the specified global variable and optimize it if
1705/// possible. If we make a change, return true.
Rafael Espindolafc355bc2011-01-19 16:32:21 +00001706bool GlobalOpt::ProcessGlobal(GlobalVariable *GV,
1707 Module::global_iterator &GVI) {
Rafael Espindoladef1b092012-06-14 22:48:13 +00001708 if (!GV->isDiscardableIfUnused())
Rafael Espindolafc355bc2011-01-19 16:32:21 +00001709 return false;
1710
1711 // Do more involved optimizations if the global is internal.
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001712 GV->removeDeadConstantUsers();
1713
1714 if (GV->use_empty()) {
David Greene44cb8ad2010-01-05 01:28:05 +00001715 DEBUG(dbgs() << "GLOBAL DEAD: " << *GV);
Chris Lattner8e71c6a2004-10-16 18:09:00 +00001716 GV->eraseFromParent();
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001717 ++NumDeleted;
1718 return true;
1719 }
1720
Rafael Espindola1821c6c2012-06-15 18:00:24 +00001721 if (!GV->hasLocalLinkage())
1722 return false;
1723
Rafael Espindolafc355bc2011-01-19 16:32:21 +00001724 GlobalStatus GS;
1725
Rafael Espindola3d7fc252013-10-21 17:14:55 +00001726 if (GlobalStatus::analyzeGlobal(GV, GS))
Rafael Espindolaecd5b9a2011-01-18 04:36:06 +00001727 return false;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001728
Rafael Espindola045a78f2013-10-17 18:18:52 +00001729 if (!GS.IsCompared && !GV->hasUnnamedAddr()) {
Rafael Espindolafc355bc2011-01-19 16:32:21 +00001730 GV->setUnnamedAddr(true);
1731 NumUnnamed++;
1732 }
1733
1734 if (GV->isConstant() || !GV->hasInitializer())
1735 return false;
1736
Rafael Espindolad21ac192013-09-05 19:15:21 +00001737 return ProcessInternalGlobal(GV, GVI, GS);
Rafael Espindolafc355bc2011-01-19 16:32:21 +00001738}
1739
1740/// ProcessInternalGlobal - Analyze the specified global variable and optimize
1741/// it if possible. If we make a change, return true.
1742bool GlobalOpt::ProcessInternalGlobal(GlobalVariable *GV,
1743 Module::global_iterator &GVI,
Rafael Espindolafc355bc2011-01-19 16:32:21 +00001744 const GlobalStatus &GS) {
Alexey Samsonova1944e62013-10-07 19:03:24 +00001745 // If this is a first class global and has only one accessing function
1746 // and this function is main (which we know is not recursive), we replace
1747 // the global with a local alloca in this function.
1748 //
Alp Tokerf907b892013-12-05 05:44:44 +00001749 // NOTE: It doesn't make sense to promote non-single-value types since we
Alexey Samsonova1944e62013-10-07 19:03:24 +00001750 // are just replacing static memory to stack memory.
1751 //
1752 // If the global is in different address space, don't bring it to stack.
1753 if (!GS.HasMultipleAccessingFunctions &&
1754 GS.AccessingFunction && !GS.HasNonInstructionUser &&
1755 GV->getType()->getElementType()->isSingleValueType() &&
1756 GS.AccessingFunction->getName() == "main" &&
1757 GS.AccessingFunction->hasExternalLinkage() &&
1758 GV->getType()->getAddressSpace() == 0) {
1759 DEBUG(dbgs() << "LOCALIZING GLOBAL: " << *GV);
1760 Instruction &FirstI = const_cast<Instruction&>(*GS.AccessingFunction
1761 ->getEntryBlock().begin());
1762 Type *ElemTy = GV->getType()->getElementType();
1763 // FIXME: Pass Global's alignment when globals have alignment
1764 AllocaInst *Alloca = new AllocaInst(ElemTy, NULL, GV->getName(), &FirstI);
1765 if (!isa<UndefValue>(GV->getInitializer()))
1766 new StoreInst(GV->getInitializer(), Alloca, &FirstI);
1767
1768 GV->replaceAllUsesWith(Alloca);
1769 GV->eraseFromParent();
1770 ++NumLocalized;
1771 return true;
1772 }
1773
Rafael Espindolaecd5b9a2011-01-18 04:36:06 +00001774 // If the global is never loaded (but may be stored to), it is dead.
1775 // Delete it now.
Rafael Espindola045a78f2013-10-17 18:18:52 +00001776 if (!GS.IsLoaded) {
Rafael Espindolaecd5b9a2011-01-18 04:36:06 +00001777 DEBUG(dbgs() << "GLOBAL NEVER LOADED: " << *GV);
1778
Nick Lewyckyfaa9c3b02012-07-24 07:21:08 +00001779 bool Changed;
1780 if (isLeakCheckerRoot(GV)) {
1781 // Delete any constant stores to the global.
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00001782 Changed = CleanupPointerRootUsers(GV, TLI);
Nick Lewyckyfaa9c3b02012-07-24 07:21:08 +00001783 } else {
1784 // Delete any stores we can find to the global. We may not be able to
1785 // make it completely dead though.
1786 Changed = CleanupConstantGlobalUsers(GV, GV->getInitializer(), TD, TLI);
1787 }
Rafael Espindolaecd5b9a2011-01-18 04:36:06 +00001788
1789 // If the global is dead now, delete it.
1790 if (GV->use_empty()) {
1791 GV->eraseFromParent();
1792 ++NumDeleted;
1793 Changed = true;
1794 }
1795 return Changed;
1796
Rafael Espindola045a78f2013-10-17 18:18:52 +00001797 } else if (GS.StoredType <= GlobalStatus::InitializerStored) {
Michael Gottesmand1a46f22013-01-11 20:07:53 +00001798 DEBUG(dbgs() << "MARKING CONSTANT: " << *GV << "\n");
Rafael Espindolaecd5b9a2011-01-18 04:36:06 +00001799 GV->setConstant(true);
1800
1801 // Clean up any obviously simplifiable users now.
Nick Lewyckycf6aae62012-02-12 01:13:18 +00001802 CleanupConstantGlobalUsers(GV, GV->getInitializer(), TD, TLI);
Rafael Espindolaecd5b9a2011-01-18 04:36:06 +00001803
1804 // If the global is dead now, just nuke it.
1805 if (GV->use_empty()) {
1806 DEBUG(dbgs() << " *** Marking constant allowed us to simplify "
1807 << "all users and delete global!\n");
1808 GV->eraseFromParent();
1809 ++NumDeleted;
1810 }
1811
1812 ++NumMarked;
1813 return true;
1814 } else if (!GV->getInitializer()->getType()->isSingleValueType()) {
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001815 if (DataLayout *TD = getAnalysisIfAvailable<DataLayout>())
Rafael Espindolaecd5b9a2011-01-18 04:36:06 +00001816 if (GlobalVariable *FirstNewGV = SRAGlobal(GV, *TD)) {
1817 GVI = FirstNewGV; // Don't skip the newly produced globals!
1818 return true;
1819 }
Rafael Espindola045a78f2013-10-17 18:18:52 +00001820 } else if (GS.StoredType == GlobalStatus::StoredOnce) {
Rafael Espindolaecd5b9a2011-01-18 04:36:06 +00001821 // If the initial value for the global was an undef value, and if only
1822 // one other value was stored into it, we can just change the
1823 // initializer to be the stored value, then delete all stores to the
1824 // global. This allows us to mark it constant.
1825 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
1826 if (isa<UndefValue>(GV->getInitializer())) {
1827 // Change the initial value here.
1828 GV->setInitializer(SOVConstant);
1829
1830 // Clean up any obviously simplifiable users now.
Nick Lewyckycf6aae62012-02-12 01:13:18 +00001831 CleanupConstantGlobalUsers(GV, GV->getInitializer(), TD, TLI);
Rafael Espindolaecd5b9a2011-01-18 04:36:06 +00001832
1833 if (GV->use_empty()) {
1834 DEBUG(dbgs() << " *** Substituting initializer allowed us to "
Nick Lewyckyfaa9c3b02012-07-24 07:21:08 +00001835 << "simplify all users and delete global!\n");
Rafael Espindolaecd5b9a2011-01-18 04:36:06 +00001836 GV->eraseFromParent();
1837 ++NumDeleted;
1838 } else {
1839 GVI = GV;
1840 }
1841 ++NumSubstitute;
1842 return true;
1843 }
1844
1845 // Try to optimize globals based on the knowledge that only one value
1846 // (besides its initializer) is ever stored to the global.
Nick Lewycky52da72b2012-02-05 19:56:38 +00001847 if (OptimizeOnceStoredGlobal(GV, GS.StoredOnceValue, GS.Ordering, GVI,
Nick Lewyckycf6aae62012-02-12 01:13:18 +00001848 TD, TLI))
Rafael Espindolaecd5b9a2011-01-18 04:36:06 +00001849 return true;
1850
1851 // Otherwise, if the global was not a boolean, we can shrink it to be a
1852 // boolean.
Eli Friedman33d37002013-09-09 22:00:13 +00001853 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue)) {
1854 if (GS.Ordering == NotAtomic) {
1855 if (TryToShrinkGlobalToBoolean(GV, SOVConstant)) {
1856 ++NumShrunkToBool;
1857 return true;
1858 }
Rafael Espindolaecd5b9a2011-01-18 04:36:06 +00001859 }
Eli Friedman33d37002013-09-09 22:00:13 +00001860 }
Rafael Espindolaecd5b9a2011-01-18 04:36:06 +00001861 }
1862
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001863 return false;
1864}
1865
Chris Lattnera4c80222005-05-08 22:18:06 +00001866/// ChangeCalleesToFastCall - Walk all of the direct calls of the specified
1867/// function, changing them to FastCC.
1868static void ChangeCalleesToFastCall(Function *F) {
1869 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
Jay Foadca0c4992012-05-12 08:30:16 +00001870 if (isa<BlockAddress>(*UI))
1871 continue;
Duncan Sands85fab3a2008-02-18 17:32:13 +00001872 CallSite User(cast<Instruction>(*UI));
1873 User.setCallingConv(CallingConv::Fast);
Chris Lattnera4c80222005-05-08 22:18:06 +00001874 }
1875}
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001876
Bill Wendlinge94d8432012-12-07 23:16:57 +00001877static AttributeSet StripNest(LLVMContext &C, const AttributeSet &Attrs) {
Chris Lattner8a923e72008-03-12 17:45:29 +00001878 for (unsigned i = 0, e = Attrs.getNumSlots(); i != e; ++i) {
Bill Wendling57625a42013-01-25 23:09:36 +00001879 unsigned Index = Attrs.getSlotIndex(i);
1880 if (!Attrs.getSlotAttributes(i).hasAttribute(Index, Attribute::Nest))
Duncan Sands85fab3a2008-02-18 17:32:13 +00001881 continue;
1882
Duncan Sands85fab3a2008-02-18 17:32:13 +00001883 // There can be only one.
Bill Wendling57625a42013-01-25 23:09:36 +00001884 return Attrs.removeAttribute(C, Index, Attribute::Nest);
Duncan Sands573b3f82008-02-16 20:56:04 +00001885 }
1886
1887 return Attrs;
1888}
1889
1890static void RemoveNestAttribute(Function *F) {
Bill Wendling85a64c22012-10-14 06:39:53 +00001891 F->setAttributes(StripNest(F->getContext(), F->getAttributes()));
Duncan Sands573b3f82008-02-16 20:56:04 +00001892 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
Jay Foadca0c4992012-05-12 08:30:16 +00001893 if (isa<BlockAddress>(*UI))
1894 continue;
Duncan Sands85fab3a2008-02-18 17:32:13 +00001895 CallSite User(cast<Instruction>(*UI));
Bill Wendling85a64c22012-10-14 06:39:53 +00001896 User.setAttributes(StripNest(F->getContext(), User.getAttributes()));
Duncan Sands573b3f82008-02-16 20:56:04 +00001897 }
1898}
1899
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001900bool GlobalOpt::OptimizeFunctions(Module &M) {
1901 bool Changed = false;
1902 // Optimize functions.
1903 for (Module::iterator FI = M.begin(), E = M.end(); FI != E; ) {
1904 Function *F = FI++;
Duncan Sandsed722832009-03-06 10:21:56 +00001905 // Functions without names cannot be referenced outside this module.
1906 if (!F->hasName() && !F->isDeclaration())
1907 F->setLinkage(GlobalValue::InternalLinkage);
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001908 F->removeDeadConstantUsers();
Eli Friedman1923a332011-10-20 05:23:42 +00001909 if (F->isDefTriviallyDead()) {
Chris Lattnerb5d9c8c2009-11-01 19:03:42 +00001910 F->eraseFromParent();
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001911 Changed = true;
1912 ++NumFnDeleted;
Rafael Espindola6de96a12009-01-15 20:18:42 +00001913 } else if (F->hasLocalLinkage()) {
Duncan Sands573b3f82008-02-16 20:56:04 +00001914 if (F->getCallingConv() == CallingConv::C && !F->isVarArg() &&
Jay Foad557169d2009-06-10 08:41:11 +00001915 !F->hasAddressTaken()) {
Duncan Sands573b3f82008-02-16 20:56:04 +00001916 // If this function has C calling conventions, is not a varargs
1917 // function, and is only called directly, promote it to use the Fast
1918 // calling convention.
1919 F->setCallingConv(CallingConv::Fast);
1920 ChangeCalleesToFastCall(F);
1921 ++NumFastCallFns;
1922 Changed = true;
1923 }
1924
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001925 if (F->getAttributes().hasAttrSomewhere(Attribute::Nest) &&
Jay Foad557169d2009-06-10 08:41:11 +00001926 !F->hasAddressTaken()) {
Duncan Sands573b3f82008-02-16 20:56:04 +00001927 // The function is not used by a trampoline intrinsic, so it is safe
1928 // to remove the 'nest' attribute.
1929 RemoveNestAttribute(F);
1930 ++NumNestRemoved;
1931 Changed = true;
1932 }
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001933 }
1934 }
1935 return Changed;
1936}
1937
1938bool GlobalOpt::OptimizeGlobalVars(Module &M) {
1939 bool Changed = false;
1940 for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
1941 GVI != E; ) {
1942 GlobalVariable *GV = GVI++;
Duncan Sandsed722832009-03-06 10:21:56 +00001943 // Global variables without names cannot be referenced outside this module.
1944 if (!GV->hasName() && !GV->isDeclaration())
1945 GV->setLinkage(GlobalValue::InternalLinkage);
Dan Gohman580b80d2009-11-23 16:22:21 +00001946 // Simplify the initializer.
1947 if (GV->hasInitializer())
1948 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GV->getInitializer())) {
Chad Rosier43a33062011-12-02 01:26:24 +00001949 Constant *New = ConstantFoldConstantExpression(CE, TD, TLI);
Dan Gohman580b80d2009-11-23 16:22:21 +00001950 if (New && New != CE)
1951 GV->setInitializer(New);
1952 }
Rafael Espindolafc355bc2011-01-19 16:32:21 +00001953
1954 Changed |= ProcessGlobal(GV, GVI);
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001955 }
1956 return Changed;
1957}
1958
Nick Lewycky466d0c12011-04-08 07:30:21 +00001959/// FindGlobalCtors - Find the llvm.global_ctors list, verifying that all
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001960/// initializers have an init priority of 65535.
1961GlobalVariable *GlobalOpt::FindGlobalCtors(Module &M) {
Chris Lattner7ff0ba42010-12-06 21:53:07 +00001962 GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
1963 if (GV == 0) return 0;
Jakub Staszak9525a772012-12-06 21:57:16 +00001964
Chris Lattner7ff0ba42010-12-06 21:53:07 +00001965 // Verify that the initializer is simple enough for us to handle. We are
1966 // only allowed to optimize the initializer if it is unique.
1967 if (!GV->hasUniqueInitializer()) return 0;
Nick Lewycky0f857892011-04-11 22:11:20 +00001968
1969 if (isa<ConstantAggregateZero>(GV->getInitializer()))
1970 return GV;
1971 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
Eli Friedman9cca0712011-04-09 09:11:09 +00001972
Chris Lattner7ff0ba42010-12-06 21:53:07 +00001973 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i) {
Nick Lewycky0f857892011-04-11 22:11:20 +00001974 if (isa<ConstantAggregateZero>(*i))
1975 continue;
1976 ConstantStruct *CS = cast<ConstantStruct>(*i);
Chris Lattner7ff0ba42010-12-06 21:53:07 +00001977 if (isa<ConstantPointerNull>(CS->getOperand(1)))
1978 continue;
Chris Lattner838bdc12005-09-26 02:19:27 +00001979
Chris Lattner7ff0ba42010-12-06 21:53:07 +00001980 // Must have a function or null ptr.
1981 if (!isa<Function>(CS->getOperand(1)))
1982 return 0;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001983
Chris Lattner7ff0ba42010-12-06 21:53:07 +00001984 // Init priority must be standard.
Nick Lewycky466d0c12011-04-08 07:30:21 +00001985 ConstantInt *CI = cast<ConstantInt>(CS->getOperand(0));
1986 if (CI->getZExtValue() != 65535)
Chris Lattner7ff0ba42010-12-06 21:53:07 +00001987 return 0;
1988 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001989
Chris Lattner7ff0ba42010-12-06 21:53:07 +00001990 return GV;
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001991}
1992
Chris Lattner696beef2005-09-26 02:31:18 +00001993/// ParseGlobalCtors - Given a llvm.global_ctors list that we can understand,
1994/// return a list of the functions and null terminator as a vector.
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001995static std::vector<Function*> ParseGlobalCtors(GlobalVariable *GV) {
Nick Lewycky0f857892011-04-11 22:11:20 +00001996 if (GV->getInitializer()->isNullValue())
1997 return std::vector<Function*>();
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001998 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
1999 std::vector<Function*> Result;
2000 Result.reserve(CA->getNumOperands());
Gabor Greif3a9fba52008-05-29 01:59:18 +00002001 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i) {
2002 ConstantStruct *CS = cast<ConstantStruct>(*i);
Chris Lattner41b6a5a2005-09-26 01:43:45 +00002003 Result.push_back(dyn_cast<Function>(CS->getOperand(1)));
2004 }
2005 return Result;
2006}
2007
Chris Lattner696beef2005-09-26 02:31:18 +00002008/// InstallGlobalCtors - Given a specified llvm.global_ctors list, install the
2009/// specified array, returning the new global to use.
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002010static GlobalVariable *InstallGlobalCtors(GlobalVariable *GCL,
Chris Lattner46b5c642009-11-06 04:27:31 +00002011 const std::vector<Function*> &Ctors) {
Chris Lattner696beef2005-09-26 02:31:18 +00002012 // If we made a change, reassemble the initializer list.
Chris Lattnercc19efa2011-06-20 04:01:31 +00002013 Constant *CSVals[2];
2014 CSVals[0] = ConstantInt::get(Type::getInt32Ty(GCL->getContext()), 65535);
2015 CSVals[1] = 0;
2016
Chris Lattner229907c2011-07-18 04:54:35 +00002017 StructType *StructTy =
Matt Arsenault404c60a2013-10-21 19:43:56 +00002018 cast<StructType>(GCL->getType()->getElementType()->getArrayElementType());
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002019
Chris Lattner696beef2005-09-26 02:31:18 +00002020 // Create the new init list.
2021 std::vector<Constant*> CAList;
2022 for (unsigned i = 0, e = Ctors.size(); i != e; ++i) {
Chris Lattner99e23fa2005-09-26 04:44:35 +00002023 if (Ctors[i]) {
Chris Lattner696beef2005-09-26 02:31:18 +00002024 CSVals[1] = Ctors[i];
Chris Lattner99e23fa2005-09-26 04:44:35 +00002025 } else {
Chris Lattner229907c2011-07-18 04:54:35 +00002026 Type *FTy = FunctionType::get(Type::getVoidTy(GCL->getContext()),
Chris Lattner46b5c642009-11-06 04:27:31 +00002027 false);
Chris Lattner229907c2011-07-18 04:54:35 +00002028 PointerType *PFTy = PointerType::getUnqual(FTy);
Owen Anderson5a1acd92009-07-31 20:28:14 +00002029 CSVals[1] = Constant::getNullValue(PFTy);
Chris Lattner46b5c642009-11-06 04:27:31 +00002030 CSVals[0] = ConstantInt::get(Type::getInt32Ty(GCL->getContext()),
Nick Lewycky0f857892011-04-11 22:11:20 +00002031 0x7fffffff);
Chris Lattner696beef2005-09-26 02:31:18 +00002032 }
Chris Lattnercc19efa2011-06-20 04:01:31 +00002033 CAList.push_back(ConstantStruct::get(StructTy, CSVals));
Chris Lattner696beef2005-09-26 02:31:18 +00002034 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002035
Chris Lattner696beef2005-09-26 02:31:18 +00002036 // Create the array initializer.
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002037 Constant *CA = ConstantArray::get(ArrayType::get(StructTy,
Nick Lewycky1303c0a2009-09-19 20:30:26 +00002038 CAList.size()), CAList);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002039
Chris Lattner696beef2005-09-26 02:31:18 +00002040 // If we didn't change the number of elements, don't create a new GV.
2041 if (CA->getType() == GCL->getInitializer()->getType()) {
2042 GCL->setInitializer(CA);
2043 return GCL;
2044 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002045
Chris Lattner696beef2005-09-26 02:31:18 +00002046 // Create the new global and insert it next to the existing list.
Chris Lattner46b5c642009-11-06 04:27:31 +00002047 GlobalVariable *NGV = new GlobalVariable(CA->getType(), GCL->isConstant(),
Lauro Ramos Venancio749e4662007-04-12 18:32:50 +00002048 GCL->getLinkage(), CA, "",
Hans Wennborgcbe34b42012-06-23 11:37:03 +00002049 GCL->getThreadLocalMode());
Chris Lattner696beef2005-09-26 02:31:18 +00002050 GCL->getParent()->getGlobalList().insert(GCL, NGV);
Chris Lattner8d4c36b2007-02-11 01:08:35 +00002051 NGV->takeName(GCL);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002052
Chris Lattner696beef2005-09-26 02:31:18 +00002053 // Nuke the old list, replacing any uses with the new one.
2054 if (!GCL->use_empty()) {
2055 Constant *V = NGV;
2056 if (V->getType() != GCL->getType())
Owen Anderson487375e2009-07-29 18:55:55 +00002057 V = ConstantExpr::getBitCast(V, GCL->getType());
Chris Lattner696beef2005-09-26 02:31:18 +00002058 GCL->replaceAllUsesWith(V);
2059 }
2060 GCL->eraseFromParent();
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002061
Chris Lattner696beef2005-09-26 02:31:18 +00002062 if (Ctors.size())
2063 return NGV;
2064 else
2065 return 0;
2066}
Chris Lattner99e23fa2005-09-26 04:44:35 +00002067
2068
Jakub Staszak9525a772012-12-06 21:57:16 +00002069static inline bool
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002070isSimpleEnoughValueToCommit(Constant *C,
Eli Friedman55fa49f32012-01-05 23:03:32 +00002071 SmallPtrSet<Constant*, 8> &SimpleConstants,
Micah Villmowcdfe20b2012-10-08 16:38:25 +00002072 const DataLayout *TD);
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002073
2074
2075/// isSimpleEnoughValueToCommit - Return true if the specified constant can be
2076/// handled by the code generator. We don't want to generate something like:
2077/// void *X = &X/42;
2078/// because the code generator doesn't have a relocation that can handle that.
2079///
2080/// This function should be called if C was not found (but just got inserted)
2081/// in SimpleConstants to avoid having to rescan the same constants all the
2082/// time.
2083static bool isSimpleEnoughValueToCommitHelper(Constant *C,
Eli Friedman55fa49f32012-01-05 23:03:32 +00002084 SmallPtrSet<Constant*, 8> &SimpleConstants,
Micah Villmowcdfe20b2012-10-08 16:38:25 +00002085 const DataLayout *TD) {
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002086 // Simple integer, undef, constant aggregate zero, global addresses, etc are
2087 // all supported.
2088 if (C->getNumOperands() == 0 || isa<BlockAddress>(C) ||
2089 isa<GlobalValue>(C))
2090 return true;
Jakub Staszak9525a772012-12-06 21:57:16 +00002091
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002092 // Aggregate values are safe if all their elements are.
2093 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C) ||
2094 isa<ConstantVector>(C)) {
2095 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i) {
2096 Constant *Op = cast<Constant>(C->getOperand(i));
Eli Friedman55fa49f32012-01-05 23:03:32 +00002097 if (!isSimpleEnoughValueToCommit(Op, SimpleConstants, TD))
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002098 return false;
2099 }
2100 return true;
2101 }
Jakub Staszak9525a772012-12-06 21:57:16 +00002102
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002103 // We don't know exactly what relocations are allowed in constant expressions,
2104 // so we allow &global+constantoffset, which is safe and uniformly supported
2105 // across targets.
2106 ConstantExpr *CE = cast<ConstantExpr>(C);
2107 switch (CE->getOpcode()) {
2108 case Instruction::BitCast:
Eli Friedman55fa49f32012-01-05 23:03:32 +00002109 // Bitcast is fine if the casted value is fine.
2110 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, TD);
2111
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002112 case Instruction::IntToPtr:
2113 case Instruction::PtrToInt:
Eli Friedman55fa49f32012-01-05 23:03:32 +00002114 // int <=> ptr is fine if the int type is the same size as the
2115 // pointer type.
2116 if (!TD || TD->getTypeSizeInBits(CE->getType()) !=
2117 TD->getTypeSizeInBits(CE->getOperand(0)->getType()))
2118 return false;
2119 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, TD);
Jakub Staszak9525a772012-12-06 21:57:16 +00002120
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002121 // GEP is fine if it is simple + constant offset.
2122 case Instruction::GetElementPtr:
2123 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
2124 if (!isa<ConstantInt>(CE->getOperand(i)))
2125 return false;
Eli Friedman55fa49f32012-01-05 23:03:32 +00002126 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, TD);
Jakub Staszak9525a772012-12-06 21:57:16 +00002127
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002128 case Instruction::Add:
2129 // We allow simple+cst.
2130 if (!isa<ConstantInt>(CE->getOperand(1)))
2131 return false;
Eli Friedman55fa49f32012-01-05 23:03:32 +00002132 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, TD);
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002133 }
2134 return false;
2135}
2136
Jakub Staszak9525a772012-12-06 21:57:16 +00002137static inline bool
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002138isSimpleEnoughValueToCommit(Constant *C,
Eli Friedman55fa49f32012-01-05 23:03:32 +00002139 SmallPtrSet<Constant*, 8> &SimpleConstants,
Micah Villmowcdfe20b2012-10-08 16:38:25 +00002140 const DataLayout *TD) {
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002141 // If we already checked this constant, we win.
2142 if (!SimpleConstants.insert(C)) return true;
2143 // Check the constant.
Eli Friedman55fa49f32012-01-05 23:03:32 +00002144 return isSimpleEnoughValueToCommitHelper(C, SimpleConstants, TD);
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002145}
2146
2147
Chris Lattner99e23fa2005-09-26 04:44:35 +00002148/// isSimpleEnoughPointerToCommit - Return true if this constant is simple
Owen Anderson9eb7cb482011-01-14 22:19:20 +00002149/// enough for us to understand. In particular, if it is a cast to anything
2150/// other than from one pointer type to another pointer type, we punt.
2151/// We basically just support direct accesses to globals and GEP's of
Chris Lattner99e23fa2005-09-26 04:44:35 +00002152/// globals. This should be kept up to date with CommitValueTo.
Chris Lattner46b5c642009-11-06 04:27:31 +00002153static bool isSimpleEnoughPointerToCommit(Constant *C) {
Dan Gohman82e74752009-09-07 22:42:05 +00002154 // Conservatively, avoid aggregate types. This is because we don't
2155 // want to worry about them partially overlapping other stores.
2156 if (!cast<PointerType>(C->getType())->getElementType()->isSingleValueType())
2157 return false;
2158
Dan Gohmanf7f3fb12009-09-07 22:31:26 +00002159 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
Mikhail Glushenkov2072db22010-10-19 16:47:23 +00002160 // Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or
Dan Gohmanf7f3fb12009-09-07 22:31:26 +00002161 // external globals.
Mikhail Glushenkov2072db22010-10-19 16:47:23 +00002162 return GV->hasUniqueInitializer();
Dan Gohmanf7f3fb12009-09-07 22:31:26 +00002163
Owen Anderson3e2f6cf2011-01-14 22:31:13 +00002164 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
Chris Lattner46af55e2005-09-26 06:52:44 +00002165 // Handle a constantexpr gep.
2166 if (CE->getOpcode() == Instruction::GetElementPtr &&
Dan Gohmanbeee35a2009-09-07 22:40:13 +00002167 isa<GlobalVariable>(CE->getOperand(0)) &&
2168 cast<GEPOperator>(CE)->isInBounds()) {
Chris Lattner46af55e2005-09-26 06:52:44 +00002169 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
Mikhail Glushenkov2072db22010-10-19 16:47:23 +00002170 // Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or
Dan Gohmanf7f3fb12009-09-07 22:31:26 +00002171 // external globals.
Mikhail Glushenkov2072db22010-10-19 16:47:23 +00002172 if (!GV->hasUniqueInitializer())
Dan Gohmanf7f3fb12009-09-07 22:31:26 +00002173 return false;
Dan Gohman161429f2009-09-07 22:44:55 +00002174
Dan Gohman161429f2009-09-07 22:44:55 +00002175 // The first index must be zero.
Oscar Fuentes40b31ad2010-08-02 06:00:15 +00002176 ConstantInt *CI = dyn_cast<ConstantInt>(*llvm::next(CE->op_begin()));
Dan Gohman161429f2009-09-07 22:44:55 +00002177 if (!CI || !CI->isZero()) return false;
Dan Gohman161429f2009-09-07 22:44:55 +00002178
2179 // The remaining indices must be compile-time known integers within the
Dan Gohman7190d482009-09-10 23:37:55 +00002180 // notional bounds of the corresponding static array types.
2181 if (!CE->isGEPWithNoNotionalOverIndexing())
2182 return false;
Dan Gohman161429f2009-09-07 22:44:55 +00002183
Dan Gohmane525d9d2009-10-05 16:36:26 +00002184 return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
Jakub Staszak9525a772012-12-06 21:57:16 +00002185
Owen Anderson9eb7cb482011-01-14 22:19:20 +00002186 // A constantexpr bitcast from a pointer to another pointer is a no-op,
2187 // and we know how to evaluate it by moving the bitcast from the pointer
2188 // operand to the value operand.
2189 } else if (CE->getOpcode() == Instruction::BitCast &&
Chris Lattner8b4952f2011-01-16 02:05:10 +00002190 isa<GlobalVariable>(CE->getOperand(0))) {
Owen Anderson9eb7cb482011-01-14 22:19:20 +00002191 // Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or
2192 // external globals.
Chris Lattner8b4952f2011-01-16 02:05:10 +00002193 return cast<GlobalVariable>(CE->getOperand(0))->hasUniqueInitializer();
Chris Lattner46af55e2005-09-26 06:52:44 +00002194 }
Owen Anderson3e2f6cf2011-01-14 22:31:13 +00002195 }
Jakub Staszak9525a772012-12-06 21:57:16 +00002196
Chris Lattner99e23fa2005-09-26 04:44:35 +00002197 return false;
2198}
2199
Chris Lattner46af55e2005-09-26 06:52:44 +00002200/// EvaluateStoreInto - Evaluate a piece of a constantexpr store into a global
2201/// initializer. This returns 'Init' modified to reflect 'Val' stored into it.
2202/// At this point, the GEP operands of Addr [0, OpNo) have been stepped into.
2203static Constant *EvaluateStoreInto(Constant *Init, Constant *Val,
Zhou Sheng8e6d64a2012-12-01 10:54:28 +00002204 ConstantExpr *Addr, unsigned OpNo) {
Chris Lattner46af55e2005-09-26 06:52:44 +00002205 // Base case of the recursion.
2206 if (OpNo == Addr->getNumOperands()) {
2207 assert(Val->getType() == Init->getType() && "Type mismatch!");
2208 return Val;
2209 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002210
Chris Lattner0256be92012-01-27 03:08:05 +00002211 SmallVector<Constant*, 32> Elts;
Chris Lattner229907c2011-07-18 04:54:35 +00002212 if (StructType *STy = dyn_cast<StructType>(Init->getType())) {
Chris Lattner46af55e2005-09-26 06:52:44 +00002213 // Break up the constant into its elements.
Chris Lattnerfa775002012-01-26 02:32:04 +00002214 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
2215 Elts.push_back(Init->getAggregateElement(i));
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002216
Chris Lattner46af55e2005-09-26 06:52:44 +00002217 // Replace the element that we are supposed to.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002218 ConstantInt *CU = cast<ConstantInt>(Addr->getOperand(OpNo));
2219 unsigned Idx = CU->getZExtValue();
2220 assert(Idx < STy->getNumElements() && "Struct index out of range!");
Zhou Sheng8e6d64a2012-12-01 10:54:28 +00002221 Elts[Idx] = EvaluateStoreInto(Elts[Idx], Val, Addr, OpNo+1);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002222
Chris Lattner46af55e2005-09-26 06:52:44 +00002223 // Return the modified struct.
Chris Lattnercc19efa2011-06-20 04:01:31 +00002224 return ConstantStruct::get(STy, Elts);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002225 }
Jakub Staszak9525a772012-12-06 21:57:16 +00002226
Chris Lattnercc19efa2011-06-20 04:01:31 +00002227 ConstantInt *CI = cast<ConstantInt>(Addr->getOperand(OpNo));
Chris Lattner229907c2011-07-18 04:54:35 +00002228 SequentialType *InitTy = cast<SequentialType>(Init->getType());
Chris Lattnercc19efa2011-06-20 04:01:31 +00002229
2230 uint64_t NumElts;
Chris Lattner229907c2011-07-18 04:54:35 +00002231 if (ArrayType *ATy = dyn_cast<ArrayType>(InitTy))
Chris Lattnercc19efa2011-06-20 04:01:31 +00002232 NumElts = ATy->getNumElements();
2233 else
Chris Lattnerfa775002012-01-26 02:32:04 +00002234 NumElts = InitTy->getVectorNumElements();
Chris Lattnercc19efa2011-06-20 04:01:31 +00002235
2236 // Break up the array into elements.
Chris Lattnerfa775002012-01-26 02:32:04 +00002237 for (uint64_t i = 0, e = NumElts; i != e; ++i)
2238 Elts.push_back(Init->getAggregateElement(i));
Chris Lattnercc19efa2011-06-20 04:01:31 +00002239
2240 assert(CI->getZExtValue() < NumElts);
2241 Elts[CI->getZExtValue()] =
Zhou Sheng8e6d64a2012-12-01 10:54:28 +00002242 EvaluateStoreInto(Elts[CI->getZExtValue()], Val, Addr, OpNo+1);
Chris Lattnercc19efa2011-06-20 04:01:31 +00002243
2244 if (Init->getType()->isArrayTy())
2245 return ConstantArray::get(cast<ArrayType>(InitTy), Elts);
2246 return ConstantVector::get(Elts);
Chris Lattner46af55e2005-09-26 06:52:44 +00002247}
2248
Chris Lattner99e23fa2005-09-26 04:44:35 +00002249/// CommitValueTo - We have decided that Addr (which satisfies the predicate
2250/// isSimpleEnoughPointerToCommit) should get Val as its value. Make it happen.
Chris Lattner46b5c642009-11-06 04:27:31 +00002251static void CommitValueTo(Constant *Val, Constant *Addr) {
Chris Lattner46af55e2005-09-26 06:52:44 +00002252 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Addr)) {
2253 assert(GV->hasInitializer());
2254 GV->setInitializer(Val);
2255 return;
2256 }
Chris Lattner64ecc462010-01-07 01:16:21 +00002257
Chris Lattner46af55e2005-09-26 06:52:44 +00002258 ConstantExpr *CE = cast<ConstantExpr>(Addr);
2259 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
Zhou Sheng8e6d64a2012-12-01 10:54:28 +00002260 GV->setInitializer(EvaluateStoreInto(GV->getInitializer(), Val, CE, 2));
Chris Lattner99e23fa2005-09-26 04:44:35 +00002261}
2262
Nick Lewycky60829a582012-02-20 03:25:59 +00002263namespace {
2264
2265/// Evaluator - This class evaluates LLVM IR, producing the Constant
2266/// representing each SSA instruction. Changes to global variables are stored
2267/// in a mapping that can be iterated over after the evaluation is complete.
2268/// Once an evaluation call fails, the evaluation object should not be reused.
2269class Evaluator {
Nick Lewycky73be5e32012-02-19 23:26:27 +00002270public:
Micah Villmowcdfe20b2012-10-08 16:38:25 +00002271 Evaluator(const DataLayout *TD, const TargetLibraryInfo *TLI)
Nick Lewycky73be5e32012-02-19 23:26:27 +00002272 : TD(TD), TLI(TLI) {
2273 ValueStack.push_back(new DenseMap<Value*, Constant*>);
2274 }
2275
Nick Lewycky60829a582012-02-20 03:25:59 +00002276 ~Evaluator() {
Nick Lewycky73be5e32012-02-19 23:26:27 +00002277 DeleteContainerPointers(ValueStack);
2278 while (!AllocaTmps.empty()) {
2279 GlobalVariable *Tmp = AllocaTmps.back();
2280 AllocaTmps.pop_back();
2281
2282 // If there are still users of the alloca, the program is doing something
2283 // silly, e.g. storing the address of the alloca somewhere and using it
2284 // later. Since this is undefined, we'll just make it be null.
2285 if (!Tmp->use_empty())
2286 Tmp->replaceAllUsesWith(Constant::getNullValue(Tmp->getType()));
2287 delete Tmp;
2288 }
2289 }
2290
2291 /// EvaluateFunction - Evaluate a call to function F, returning true if
2292 /// successful, false if we can't evaluate it. ActualArgs contains the formal
2293 /// arguments for the function.
2294 bool EvaluateFunction(Function *F, Constant *&RetVal,
2295 const SmallVectorImpl<Constant*> &ActualArgs);
2296
2297 /// EvaluateBlock - Evaluate all instructions in block BB, returning true if
2298 /// successful, false if we can't evaluate it. NewBB returns the next BB that
2299 /// control flows into, or null upon return.
2300 bool EvaluateBlock(BasicBlock::iterator CurInst, BasicBlock *&NextBB);
2301
2302 Constant *getVal(Value *V) {
2303 if (Constant *CV = dyn_cast<Constant>(V)) return CV;
2304 Constant *R = ValueStack.back()->lookup(V);
2305 assert(R && "Reference to an uncomputed value!");
2306 return R;
2307 }
2308
2309 void setVal(Value *V, Constant *C) {
2310 ValueStack.back()->operator[](V) = C;
2311 }
2312
2313 const DenseMap<Constant*, Constant*> &getMutatedMemory() const {
2314 return MutatedMemory;
2315 }
2316
2317 const SmallPtrSet<GlobalVariable*, 8> &getInvariants() const {
2318 return Invariants;
2319 }
2320
2321private:
2322 Constant *ComputeLoadResult(Constant *P);
2323
2324 /// ValueStack - As we compute SSA register values, we store their contents
2325 /// here. The back of the vector contains the current function and the stack
2326 /// contains the values in the calling frames.
2327 SmallVector<DenseMap<Value*, Constant*>*, 4> ValueStack;
2328
2329 /// CallStack - This is used to detect recursion. In pathological situations
2330 /// we could hit exponential behavior, but at least there is nothing
2331 /// unbounded.
2332 SmallVector<Function*, 4> CallStack;
2333
2334 /// MutatedMemory - For each store we execute, we update this map. Loads
2335 /// check this to get the most up-to-date value. If evaluation is successful,
2336 /// this state is committed to the process.
2337 DenseMap<Constant*, Constant*> MutatedMemory;
2338
2339 /// AllocaTmps - To 'execute' an alloca, we create a temporary global variable
2340 /// to represent its body. This vector is needed so we can delete the
2341 /// temporary globals when we are done.
2342 SmallVector<GlobalVariable*, 32> AllocaTmps;
2343
2344 /// Invariants - These global variables have been marked invariant by the
2345 /// static constructor.
2346 SmallPtrSet<GlobalVariable*, 8> Invariants;
2347
2348 /// SimpleConstants - These are constants we have checked and know to be
2349 /// simple enough to live in a static initializer of a global.
2350 SmallPtrSet<Constant*, 8> SimpleConstants;
2351
Micah Villmowcdfe20b2012-10-08 16:38:25 +00002352 const DataLayout *TD;
Nick Lewycky73be5e32012-02-19 23:26:27 +00002353 const TargetLibraryInfo *TLI;
2354};
2355
Nick Lewycky60829a582012-02-20 03:25:59 +00002356} // anonymous namespace
2357
Chris Lattnerb0096632005-09-26 05:16:34 +00002358/// ComputeLoadResult - Return the value that would be computed by a load from
2359/// P after the stores reflected by 'memory' have been performed. If we can't
2360/// decide, return null.
Nick Lewycky60829a582012-02-20 03:25:59 +00002361Constant *Evaluator::ComputeLoadResult(Constant *P) {
Chris Lattner4b05c322005-09-26 05:15:37 +00002362 // If this memory location has been recently stored, use the stored value: it
2363 // is the most up-to-date.
Nick Lewycky73be5e32012-02-19 23:26:27 +00002364 DenseMap<Constant*, Constant*>::const_iterator I = MutatedMemory.find(P);
2365 if (I != MutatedMemory.end()) return I->second;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002366
Chris Lattner4b05c322005-09-26 05:15:37 +00002367 // Access it.
2368 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(P)) {
Dan Gohman5d5bc6d2009-08-19 18:20:44 +00002369 if (GV->hasDefinitiveInitializer())
Chris Lattner4b05c322005-09-26 05:15:37 +00002370 return GV->getInitializer();
2371 return 0;
Chris Lattner4b05c322005-09-26 05:15:37 +00002372 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002373
Chris Lattner46af55e2005-09-26 06:52:44 +00002374 // Handle a constantexpr getelementptr.
2375 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(P))
2376 if (CE->getOpcode() == Instruction::GetElementPtr &&
2377 isa<GlobalVariable>(CE->getOperand(0))) {
2378 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
Dan Gohman5d5bc6d2009-08-19 18:20:44 +00002379 if (GV->hasDefinitiveInitializer())
Dan Gohmane525d9d2009-10-05 16:36:26 +00002380 return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
Chris Lattner46af55e2005-09-26 06:52:44 +00002381 }
2382
2383 return 0; // don't know how to evaluate.
Chris Lattner4b05c322005-09-26 05:15:37 +00002384}
2385
Nick Lewycky239fdf02012-02-06 08:24:44 +00002386/// EvaluateBlock - Evaluate all instructions in block BB, returning true if
2387/// successful, false if we can't evaluate it. NewBB returns the next BB that
2388/// control flows into, or null upon return.
Nick Lewycky60829a582012-02-20 03:25:59 +00002389bool Evaluator::EvaluateBlock(BasicBlock::iterator CurInst,
2390 BasicBlock *&NextBB) {
Chris Lattner99e23fa2005-09-26 04:44:35 +00002391 // This is the main evaluation loop.
2392 while (1) {
2393 Constant *InstResult = 0;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002394
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002395 DEBUG(dbgs() << "Evaluating Instruction: " << *CurInst << "\n");
2396
Chris Lattner99e23fa2005-09-26 04:44:35 +00002397 if (StoreInst *SI = dyn_cast<StoreInst>(CurInst)) {
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002398 if (!SI->isSimple()) {
Michael Gottesman2a654272013-01-11 23:08:52 +00002399 DEBUG(dbgs() << "Store is not simple! Can not evaluate.\n");
2400 return false; // no volatile/atomic accesses.
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002401 }
Nick Lewycky73be5e32012-02-19 23:26:27 +00002402 Constant *Ptr = getVal(SI->getOperand(1));
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002403 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
Michael Gottesman2a654272013-01-11 23:08:52 +00002404 DEBUG(dbgs() << "Folding constant ptr expression: " << *Ptr);
Nick Lewycky9d0da182012-02-21 22:08:06 +00002405 Ptr = ConstantFoldConstantExpression(CE, TD, TLI);
Michael Gottesman2a654272013-01-11 23:08:52 +00002406 DEBUG(dbgs() << "; To: " << *Ptr << "\n");
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002407 }
2408 if (!isSimpleEnoughPointerToCommit(Ptr)) {
Chris Lattner99e23fa2005-09-26 04:44:35 +00002409 // If this is too complex for us to commit, reject it.
Michael Gottesman2a654272013-01-11 23:08:52 +00002410 DEBUG(dbgs() << "Pointer is too complex for us to evaluate store.");
Chris Lattner65a3a092005-09-27 04:45:34 +00002411 return false;
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002412 }
Jakub Staszak9525a772012-12-06 21:57:16 +00002413
Nick Lewycky73be5e32012-02-19 23:26:27 +00002414 Constant *Val = getVal(SI->getOperand(0));
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002415
2416 // If this might be too difficult for the backend to handle (e.g. the addr
2417 // of one global variable divided by another) then we can't commit it.
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002418 if (!isSimpleEnoughValueToCommit(Val, SimpleConstants, TD)) {
Michael Gottesman2a654272013-01-11 23:08:52 +00002419 DEBUG(dbgs() << "Store value is too complex to evaluate store. " << *Val
2420 << "\n");
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002421 return false;
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002422 }
Jakub Staszak9525a772012-12-06 21:57:16 +00002423
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002424 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
Owen Anderson9eb7cb482011-01-14 22:19:20 +00002425 if (CE->getOpcode() == Instruction::BitCast) {
Michael Gottesman2a654272013-01-11 23:08:52 +00002426 DEBUG(dbgs() << "Attempting to resolve bitcast on constant ptr.\n");
Owen Anderson9eb7cb482011-01-14 22:19:20 +00002427 // If we're evaluating a store through a bitcast, then we need
2428 // to pull the bitcast off the pointer type and push it onto the
2429 // stored value.
Chris Lattner8b4952f2011-01-16 02:05:10 +00002430 Ptr = CE->getOperand(0);
Jakub Staszak9525a772012-12-06 21:57:16 +00002431
Nick Lewycky239fdf02012-02-06 08:24:44 +00002432 Type *NewTy = cast<PointerType>(Ptr->getType())->getElementType();
Jakub Staszak9525a772012-12-06 21:57:16 +00002433
Owen Anderson4e54efd2011-01-16 04:33:33 +00002434 // In order to push the bitcast onto the stored value, a bitcast
2435 // from NewTy to Val's type must be legal. If it's not, we can try
2436 // introspecting NewTy to find a legal conversion.
2437 while (!Val->getType()->canLosslesslyBitCastTo(NewTy)) {
2438 // If NewTy is a struct, we can convert the pointer to the struct
2439 // into a pointer to its first member.
2440 // FIXME: This could be extended to support arrays as well.
Chris Lattner229907c2011-07-18 04:54:35 +00002441 if (StructType *STy = dyn_cast<StructType>(NewTy)) {
Owen Anderson4e54efd2011-01-16 04:33:33 +00002442 NewTy = STy->getTypeAtIndex(0U);
2443
Nick Lewycky239fdf02012-02-06 08:24:44 +00002444 IntegerType *IdxTy = IntegerType::get(NewTy->getContext(), 32);
Owen Anderson4e54efd2011-01-16 04:33:33 +00002445 Constant *IdxZero = ConstantInt::get(IdxTy, 0, false);
2446 Constant * const IdxList[] = {IdxZero, IdxZero};
2447
Jay Foad17bab442011-07-22 08:52:50 +00002448 Ptr = ConstantExpr::getGetElementPtr(Ptr, IdxList);
Nick Lewycky9d0da182012-02-21 22:08:06 +00002449 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
2450 Ptr = ConstantFoldConstantExpression(CE, TD, TLI);
2451
Owen Anderson4e54efd2011-01-16 04:33:33 +00002452 // If we can't improve the situation by introspecting NewTy,
2453 // we have to give up.
2454 } else {
Michael Gottesman2a654272013-01-11 23:08:52 +00002455 DEBUG(dbgs() << "Failed to bitcast constant ptr, can not "
2456 "evaluate.\n");
Nick Lewycky239fdf02012-02-06 08:24:44 +00002457 return false;
Owen Anderson4e54efd2011-01-16 04:33:33 +00002458 }
Owen Anderson9eb7cb482011-01-14 22:19:20 +00002459 }
Jakub Staszak9525a772012-12-06 21:57:16 +00002460
Owen Anderson4e54efd2011-01-16 04:33:33 +00002461 // If we found compatible types, go ahead and push the bitcast
2462 // onto the stored value.
Owen Anderson9eb7cb482011-01-14 22:19:20 +00002463 Val = ConstantExpr::getBitCast(Val, NewTy);
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002464
Michael Gottesman2a654272013-01-11 23:08:52 +00002465 DEBUG(dbgs() << "Evaluated bitcast: " << *Val << "\n");
Owen Anderson9eb7cb482011-01-14 22:19:20 +00002466 }
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002467 }
Jakub Staszak9525a772012-12-06 21:57:16 +00002468
Chris Lattner99e23fa2005-09-26 04:44:35 +00002469 MutatedMemory[Ptr] = Val;
2470 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CurInst)) {
Owen Anderson487375e2009-07-29 18:55:55 +00002471 InstResult = ConstantExpr::get(BO->getOpcode(),
Nick Lewycky73be5e32012-02-19 23:26:27 +00002472 getVal(BO->getOperand(0)),
2473 getVal(BO->getOperand(1)));
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002474 DEBUG(dbgs() << "Found a BinaryOperator! Simplifying: " << *InstResult
Michael Gottesman2a654272013-01-11 23:08:52 +00002475 << "\n");
Reid Spencer266e42b2006-12-23 06:05:41 +00002476 } else if (CmpInst *CI = dyn_cast<CmpInst>(CurInst)) {
Owen Anderson487375e2009-07-29 18:55:55 +00002477 InstResult = ConstantExpr::getCompare(CI->getPredicate(),
Nick Lewycky73be5e32012-02-19 23:26:27 +00002478 getVal(CI->getOperand(0)),
2479 getVal(CI->getOperand(1)));
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002480 DEBUG(dbgs() << "Found a CmpInst! Simplifying: " << *InstResult
Michael Gottesman2a654272013-01-11 23:08:52 +00002481 << "\n");
Chris Lattner99e23fa2005-09-26 04:44:35 +00002482 } else if (CastInst *CI = dyn_cast<CastInst>(CurInst)) {
Owen Anderson487375e2009-07-29 18:55:55 +00002483 InstResult = ConstantExpr::getCast(CI->getOpcode(),
Nick Lewycky73be5e32012-02-19 23:26:27 +00002484 getVal(CI->getOperand(0)),
Chris Lattner99e23fa2005-09-26 04:44:35 +00002485 CI->getType());
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002486 DEBUG(dbgs() << "Found a Cast! Simplifying: " << *InstResult
Michael Gottesman2a654272013-01-11 23:08:52 +00002487 << "\n");
Chris Lattner99e23fa2005-09-26 04:44:35 +00002488 } else if (SelectInst *SI = dyn_cast<SelectInst>(CurInst)) {
Nick Lewycky73be5e32012-02-19 23:26:27 +00002489 InstResult = ConstantExpr::getSelect(getVal(SI->getOperand(0)),
2490 getVal(SI->getOperand(1)),
2491 getVal(SI->getOperand(2)));
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002492 DEBUG(dbgs() << "Found a Select! Simplifying: " << *InstResult
Michael Gottesman2a654272013-01-11 23:08:52 +00002493 << "\n");
Chris Lattner4b05c322005-09-26 05:15:37 +00002494 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurInst)) {
Nick Lewycky73be5e32012-02-19 23:26:27 +00002495 Constant *P = getVal(GEP->getOperand(0));
Chris Lattnerf96f4a82007-01-31 04:40:53 +00002496 SmallVector<Constant*, 8> GEPOps;
Gabor Greif3a9fba52008-05-29 01:59:18 +00002497 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end();
2498 i != e; ++i)
Nick Lewycky73be5e32012-02-19 23:26:27 +00002499 GEPOps.push_back(getVal(*i));
Jay Foad2f5fc8c2011-07-21 15:15:37 +00002500 InstResult =
2501 ConstantExpr::getGetElementPtr(P, GEPOps,
2502 cast<GEPOperator>(GEP)->isInBounds());
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002503 DEBUG(dbgs() << "Found a GEP! Simplifying: " << *InstResult
Michael Gottesman2a654272013-01-11 23:08:52 +00002504 << "\n");
Chris Lattner4b05c322005-09-26 05:15:37 +00002505 } else if (LoadInst *LI = dyn_cast<LoadInst>(CurInst)) {
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002506
2507 if (!LI->isSimple()) {
Michael Gottesman2a654272013-01-11 23:08:52 +00002508 DEBUG(dbgs() << "Found a Load! Not a simple load, can not evaluate.\n");
2509 return false; // no volatile/atomic accesses.
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002510 }
2511
Nick Lewycky9d0da182012-02-21 22:08:06 +00002512 Constant *Ptr = getVal(LI->getOperand(0));
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002513 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
Nick Lewycky9d0da182012-02-21 22:08:06 +00002514 Ptr = ConstantFoldConstantExpression(CE, TD, TLI);
Michael Gottesman2a654272013-01-11 23:08:52 +00002515 DEBUG(dbgs() << "Found a constant pointer expression, constant "
2516 "folding: " << *Ptr << "\n");
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002517 }
Nick Lewycky9d0da182012-02-21 22:08:06 +00002518 InstResult = ComputeLoadResult(Ptr);
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002519 if (InstResult == 0) {
Michael Gottesman2a654272013-01-11 23:08:52 +00002520 DEBUG(dbgs() << "Failed to compute load result. Can not evaluate load."
2521 "\n");
2522 return false; // Could not evaluate load.
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002523 }
2524
2525 DEBUG(dbgs() << "Evaluated load: " << *InstResult << "\n");
Chris Lattner6bf2cd52005-09-26 17:07:09 +00002526 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(CurInst)) {
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002527 if (AI->isArrayAllocation()) {
Michael Gottesman2a654272013-01-11 23:08:52 +00002528 DEBUG(dbgs() << "Found an array alloca. Can not evaluate.\n");
2529 return false; // Cannot handle array allocs.
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002530 }
Chris Lattner229907c2011-07-18 04:54:35 +00002531 Type *Ty = AI->getType()->getElementType();
Chris Lattner46b5c642009-11-06 04:27:31 +00002532 AllocaTmps.push_back(new GlobalVariable(Ty, false,
Chris Lattner6bf2cd52005-09-26 17:07:09 +00002533 GlobalValue::InternalLinkage,
Owen Andersonb292b8c2009-07-30 23:03:37 +00002534 UndefValue::get(Ty),
Chris Lattner6bf2cd52005-09-26 17:07:09 +00002535 AI->getName()));
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002536 InstResult = AllocaTmps.back();
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002537 DEBUG(dbgs() << "Found an alloca. Result: " << *InstResult << "\n");
Nick Lewyckyc1572e42012-02-12 05:09:35 +00002538 } else if (isa<CallInst>(CurInst) || isa<InvokeInst>(CurInst)) {
2539 CallSite CS(CurInst);
Devang Patel04852aa2009-03-09 23:04:12 +00002540
2541 // Debug info can safely be ignored here.
Nick Lewyckyc1572e42012-02-12 05:09:35 +00002542 if (isa<DbgInfoIntrinsic>(CS.getInstruction())) {
Michael Gottesman2a654272013-01-11 23:08:52 +00002543 DEBUG(dbgs() << "Ignoring debug info.\n");
Devang Patel04852aa2009-03-09 23:04:12 +00002544 ++CurInst;
2545 continue;
2546 }
2547
Chris Lattnerfd2e13b2006-07-07 21:37:01 +00002548 // Cannot handle inline asm.
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002549 if (isa<InlineAsm>(CS.getCalledValue())) {
Michael Gottesman2a654272013-01-11 23:08:52 +00002550 DEBUG(dbgs() << "Found inline asm, can not evaluate.\n");
2551 return false;
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002552 }
Chris Lattnerfd2e13b2006-07-07 21:37:01 +00002553
Nick Lewycky68f9f9d2012-02-17 06:59:21 +00002554 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CS.getInstruction())) {
2555 if (MemSetInst *MSI = dyn_cast<MemSetInst>(II)) {
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002556 if (MSI->isVolatile()) {
Michael Gottesman2a654272013-01-11 23:08:52 +00002557 DEBUG(dbgs() << "Can not optimize a volatile memset " <<
2558 "intrinsic.\n");
2559 return false;
2560 }
Nick Lewycky73be5e32012-02-19 23:26:27 +00002561 Constant *Ptr = getVal(MSI->getDest());
2562 Constant *Val = getVal(MSI->getValue());
2563 Constant *DestVal = ComputeLoadResult(getVal(Ptr));
Nick Lewycky68f9f9d2012-02-17 06:59:21 +00002564 if (Val->isNullValue() && DestVal && DestVal->isNullValue()) {
2565 // This memset is a no-op.
Michael Gottesman2a654272013-01-11 23:08:52 +00002566 DEBUG(dbgs() << "Ignoring no-op memset.\n");
Nick Lewycky68f9f9d2012-02-17 06:59:21 +00002567 ++CurInst;
2568 continue;
2569 }
2570 }
2571
2572 if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
2573 II->getIntrinsicID() == Intrinsic::lifetime_end) {
Michael Gottesman2a654272013-01-11 23:08:52 +00002574 DEBUG(dbgs() << "Ignoring lifetime intrinsic.\n");
Nick Lewycky68f9f9d2012-02-17 06:59:21 +00002575 ++CurInst;
2576 continue;
2577 }
2578
2579 if (II->getIntrinsicID() == Intrinsic::invariant_start) {
2580 // We don't insert an entry into Values, as it doesn't have a
2581 // meaningful return value.
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002582 if (!II->use_empty()) {
Alp Tokerf907b892013-12-05 05:44:44 +00002583 DEBUG(dbgs() << "Found unused invariant_start. Can't evaluate.\n");
Nick Lewycky68f9f9d2012-02-17 06:59:21 +00002584 return false;
Michael Gottesman2a654272013-01-11 23:08:52 +00002585 }
Nick Lewycky68f9f9d2012-02-17 06:59:21 +00002586 ConstantInt *Size = cast<ConstantInt>(II->getArgOperand(0));
Nick Lewycky519561f2012-02-20 23:32:26 +00002587 Value *PtrArg = getVal(II->getArgOperand(1));
2588 Value *Ptr = PtrArg->stripPointerCasts();
2589 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr)) {
2590 Type *ElemTy = cast<PointerType>(GV->getType())->getElementType();
Nick Lewycky5b150372013-07-25 02:55:14 +00002591 if (TD && !Size->isAllOnesValue() &&
Nick Lewycky519561f2012-02-20 23:32:26 +00002592 Size->getValue().getLimitedValue() >=
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002593 TD->getTypeStoreSize(ElemTy)) {
Nick Lewycky68f9f9d2012-02-17 06:59:21 +00002594 Invariants.insert(GV);
Michael Gottesman2a654272013-01-11 23:08:52 +00002595 DEBUG(dbgs() << "Found a global var that is an invariant: " << *GV
2596 << "\n");
2597 } else {
2598 DEBUG(dbgs() << "Found a global var, but can not treat it as an "
2599 "invariant.\n");
2600 }
Nick Lewycky68f9f9d2012-02-17 06:59:21 +00002601 }
2602 // Continue even if we do nothing.
Nick Lewyckya3bb03e2011-05-29 18:41:56 +00002603 ++CurInst;
2604 continue;
2605 }
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002606
Michael Gottesman2a654272013-01-11 23:08:52 +00002607 DEBUG(dbgs() << "Unknown intrinsic. Can not evaluate.\n");
Nick Lewyckya3bb03e2011-05-29 18:41:56 +00002608 return false;
2609 }
2610
Chris Lattner65a3a092005-09-27 04:45:34 +00002611 // Resolve function pointers.
Nick Lewycky73be5e32012-02-19 23:26:27 +00002612 Function *Callee = dyn_cast<Function>(getVal(CS.getCalledValue()));
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002613 if (!Callee || Callee->mayBeOverridden()) {
Michael Gottesman2a654272013-01-11 23:08:52 +00002614 DEBUG(dbgs() << "Can not resolve function pointer.\n");
Nick Lewyckyc1572e42012-02-12 05:09:35 +00002615 return false; // Cannot resolve.
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002616 }
Chris Lattner3d27e7f2005-09-27 05:02:43 +00002617
Duncan Sandsc4ce58d82009-08-17 14:33:27 +00002618 SmallVector<Constant*, 8> Formals;
Nick Lewyckyc1572e42012-02-12 05:09:35 +00002619 for (User::op_iterator i = CS.arg_begin(), e = CS.arg_end(); i != e; ++i)
Nick Lewycky73be5e32012-02-19 23:26:27 +00002620 Formals.push_back(getVal(*i));
Duncan Sandsc4ce58d82009-08-17 14:33:27 +00002621
Reid Spencer5301e7c2007-01-30 20:08:39 +00002622 if (Callee->isDeclaration()) {
Chris Lattner3d27e7f2005-09-27 05:02:43 +00002623 // If this is a function we can constant fold, do it.
Chad Rosiere6de63d2011-12-01 21:29:16 +00002624 if (Constant *C = ConstantFoldCall(Callee, Formals, TLI)) {
Chris Lattner3d27e7f2005-09-27 05:02:43 +00002625 InstResult = C;
Michael Gottesman2a654272013-01-11 23:08:52 +00002626 DEBUG(dbgs() << "Constant folded function call. Result: " <<
2627 *InstResult << "\n");
Chris Lattner3d27e7f2005-09-27 05:02:43 +00002628 } else {
Michael Gottesman2a654272013-01-11 23:08:52 +00002629 DEBUG(dbgs() << "Can not constant fold function call.\n");
Chris Lattner3d27e7f2005-09-27 05:02:43 +00002630 return false;
2631 }
2632 } else {
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002633 if (Callee->getFunctionType()->isVarArg()) {
Michael Gottesman2a654272013-01-11 23:08:52 +00002634 DEBUG(dbgs() << "Can not constant fold vararg function call.\n");
Chris Lattner3d27e7f2005-09-27 05:02:43 +00002635 return false;
Michael Gottesman2a654272013-01-11 23:08:52 +00002636 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002637
Benjamin Kramer64a857a2013-01-12 15:34:31 +00002638 Constant *RetVal = 0;
Chris Lattner3d27e7f2005-09-27 05:02:43 +00002639 // Execute the call, if successful, use the return value.
Nick Lewycky73be5e32012-02-19 23:26:27 +00002640 ValueStack.push_back(new DenseMap<Value*, Constant*>);
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002641 if (!EvaluateFunction(Callee, RetVal, Formals)) {
Michael Gottesman2a654272013-01-11 23:08:52 +00002642 DEBUG(dbgs() << "Failed to evaluate function.\n");
Chris Lattner3d27e7f2005-09-27 05:02:43 +00002643 return false;
Michael Gottesman2a654272013-01-11 23:08:52 +00002644 }
Benjamin Kramer93887632012-02-27 12:48:24 +00002645 delete ValueStack.pop_back_val();
Chris Lattner3d27e7f2005-09-27 05:02:43 +00002646 InstResult = RetVal;
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002647
Michael Gottesman2a654272013-01-11 23:08:52 +00002648 if (InstResult != NULL) {
2649 DEBUG(dbgs() << "Successfully evaluated function. Result: " <<
2650 InstResult << "\n\n");
2651 } else {
2652 DEBUG(dbgs() << "Successfully evaluated function. Result: 0\n\n");
2653 }
Chris Lattner3d27e7f2005-09-27 05:02:43 +00002654 }
Reid Spencerde46e482006-11-02 20:25:50 +00002655 } else if (isa<TerminatorInst>(CurInst)) {
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002656 DEBUG(dbgs() << "Found a terminator instruction.\n");
2657
Chris Lattner3e9ea5f2005-09-26 04:57:38 +00002658 if (BranchInst *BI = dyn_cast<BranchInst>(CurInst)) {
2659 if (BI->isUnconditional()) {
Nick Lewycky239fdf02012-02-06 08:24:44 +00002660 NextBB = BI->getSuccessor(0);
Chris Lattner3e9ea5f2005-09-26 04:57:38 +00002661 } else {
Zhou Sheng75b871f2007-01-11 12:24:14 +00002662 ConstantInt *Cond =
Nick Lewycky73be5e32012-02-19 23:26:27 +00002663 dyn_cast<ConstantInt>(getVal(BI->getCondition()));
Chris Lattner15649082007-01-12 18:30:11 +00002664 if (!Cond) return false; // Cannot determine.
Zhou Sheng75b871f2007-01-11 12:24:14 +00002665
Nick Lewycky239fdf02012-02-06 08:24:44 +00002666 NextBB = BI->getSuccessor(!Cond->getZExtValue());
Chris Lattner3e9ea5f2005-09-26 04:57:38 +00002667 }
2668 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(CurInst)) {
2669 ConstantInt *Val =
Nick Lewycky73be5e32012-02-19 23:26:27 +00002670 dyn_cast<ConstantInt>(getVal(SI->getCondition()));
Chris Lattner65a3a092005-09-27 04:45:34 +00002671 if (!Val) return false; // Cannot determine.
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00002672 NextBB = SI->findCaseValue(Val).getCaseSuccessor();
Chris Lattner31274882009-10-29 05:51:50 +00002673 } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(CurInst)) {
Nick Lewycky73be5e32012-02-19 23:26:27 +00002674 Value *Val = getVal(IBI->getAddress())->stripPointerCasts();
Chris Lattner31274882009-10-29 05:51:50 +00002675 if (BlockAddress *BA = dyn_cast<BlockAddress>(Val))
Nick Lewycky239fdf02012-02-06 08:24:44 +00002676 NextBB = BA->getBasicBlock();
Chris Lattneraa99c942009-11-01 01:27:45 +00002677 else
2678 return false; // Cannot determine.
Nick Lewycky239fdf02012-02-06 08:24:44 +00002679 } else if (isa<ReturnInst>(CurInst)) {
2680 NextBB = 0;
Chris Lattner3e9ea5f2005-09-26 04:57:38 +00002681 } else {
Bill Wendlingf891bf82011-07-31 06:30:59 +00002682 // invoke, unwind, resume, unreachable.
Michael Gottesman2a654272013-01-11 23:08:52 +00002683 DEBUG(dbgs() << "Can not handle terminator.");
Chris Lattner65a3a092005-09-27 04:45:34 +00002684 return false; // Cannot handle this terminator.
Chris Lattner3e9ea5f2005-09-26 04:57:38 +00002685 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002686
Nick Lewycky239fdf02012-02-06 08:24:44 +00002687 // We succeeded at evaluating this block!
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002688 DEBUG(dbgs() << "Successfully evaluated block.\n");
Nick Lewycky239fdf02012-02-06 08:24:44 +00002689 return true;
Chris Lattner99e23fa2005-09-26 04:44:35 +00002690 } else {
Chris Lattner99e23fa2005-09-26 04:44:35 +00002691 // Did not know how to evaluate this!
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002692 DEBUG(dbgs() << "Failed to evaluate block due to unhandled instruction."
Michael Gottesman2a654272013-01-11 23:08:52 +00002693 "\n");
Chris Lattner65a3a092005-09-27 04:45:34 +00002694 return false;
Chris Lattner99e23fa2005-09-26 04:44:35 +00002695 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002696
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002697 if (!CurInst->use_empty()) {
2698 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(InstResult))
Chad Rosier43a33062011-12-02 01:26:24 +00002699 InstResult = ConstantFoldConstantExpression(CE, TD, TLI);
Jakub Staszak9525a772012-12-06 21:57:16 +00002700
Nick Lewycky73be5e32012-02-19 23:26:27 +00002701 setVal(CurInst, InstResult);
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002702 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002703
Dan Gohmaneab06fa2012-03-13 18:01:37 +00002704 // If we just processed an invoke, we finished evaluating the block.
2705 if (InvokeInst *II = dyn_cast<InvokeInst>(CurInst)) {
2706 NextBB = II->getNormalDest();
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002707 DEBUG(dbgs() << "Found an invoke instruction. Finished Block.\n\n");
Dan Gohmaneab06fa2012-03-13 18:01:37 +00002708 return true;
2709 }
2710
Chris Lattner99e23fa2005-09-26 04:44:35 +00002711 // Advance program counter.
2712 ++CurInst;
2713 }
Chris Lattnerda1889b2005-09-27 04:27:01 +00002714}
2715
Nick Lewycky239fdf02012-02-06 08:24:44 +00002716/// EvaluateFunction - Evaluate a call to function F, returning true if
2717/// successful, false if we can't evaluate it. ActualArgs contains the formal
2718/// arguments for the function.
Nick Lewycky60829a582012-02-20 03:25:59 +00002719bool Evaluator::EvaluateFunction(Function *F, Constant *&RetVal,
2720 const SmallVectorImpl<Constant*> &ActualArgs) {
Nick Lewycky239fdf02012-02-06 08:24:44 +00002721 // Check to see if this function is already executing (recursion). If so,
2722 // bail out. TODO: we might want to accept limited recursion.
2723 if (std::find(CallStack.begin(), CallStack.end(), F) != CallStack.end())
2724 return false;
2725
2726 CallStack.push_back(F);
2727
Nick Lewycky239fdf02012-02-06 08:24:44 +00002728 // Initialize arguments to the incoming values specified.
2729 unsigned ArgNo = 0;
2730 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); AI != E;
2731 ++AI, ++ArgNo)
Nick Lewycky73be5e32012-02-19 23:26:27 +00002732 setVal(AI, ActualArgs[ArgNo]);
Nick Lewycky239fdf02012-02-06 08:24:44 +00002733
2734 // ExecutedBlocks - We only handle non-looping, non-recursive code. As such,
2735 // we can only evaluate any one basic block at most once. This set keeps
2736 // track of what we have executed so we can detect recursive cases etc.
2737 SmallPtrSet<BasicBlock*, 32> ExecutedBlocks;
2738
2739 // CurBB - The current basic block we're evaluating.
2740 BasicBlock *CurBB = F->begin();
2741
Nick Lewycky4231c412012-02-12 00:47:24 +00002742 BasicBlock::iterator CurInst = CurBB->begin();
2743
Nick Lewycky239fdf02012-02-06 08:24:44 +00002744 while (1) {
Duncan Sands4730cb92012-02-23 08:23:06 +00002745 BasicBlock *NextBB = 0; // Initialized to avoid compiler warnings.
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002746 DEBUG(dbgs() << "Trying to evaluate BB: " << *CurBB << "\n");
2747
Nick Lewycky73be5e32012-02-19 23:26:27 +00002748 if (!EvaluateBlock(CurInst, NextBB))
Nick Lewycky239fdf02012-02-06 08:24:44 +00002749 return false;
2750
2751 if (NextBB == 0) {
2752 // Successfully running until there's no next block means that we found
2753 // the return. Fill it the return value and pop the call stack.
2754 ReturnInst *RI = cast<ReturnInst>(CurBB->getTerminator());
2755 if (RI->getNumOperands())
Nick Lewycky73be5e32012-02-19 23:26:27 +00002756 RetVal = getVal(RI->getOperand(0));
Nick Lewycky239fdf02012-02-06 08:24:44 +00002757 CallStack.pop_back();
2758 return true;
2759 }
2760
2761 // Okay, we succeeded in evaluating this control flow. See if we have
2762 // executed the new block before. If so, we have a looping function,
2763 // which we cannot evaluate in reasonable time.
2764 if (!ExecutedBlocks.insert(NextBB))
2765 return false; // looped!
2766
2767 // Okay, we have never been in this block before. Check to see if there
2768 // are any PHI nodes. If so, evaluate them with information about where
2769 // we came from.
2770 PHINode *PN = 0;
Nick Lewycky4231c412012-02-12 00:47:24 +00002771 for (CurInst = NextBB->begin();
2772 (PN = dyn_cast<PHINode>(CurInst)); ++CurInst)
Nick Lewycky73be5e32012-02-19 23:26:27 +00002773 setVal(PN, getVal(PN->getIncomingValueForBlock(CurBB)));
Nick Lewycky239fdf02012-02-06 08:24:44 +00002774
2775 // Advance to the next block.
2776 CurBB = NextBB;
2777 }
2778}
2779
Chris Lattnerda1889b2005-09-27 04:27:01 +00002780/// EvaluateStaticConstructor - Evaluate static constructors in the function, if
2781/// we can. Return true if we can, false otherwise.
Micah Villmowcdfe20b2012-10-08 16:38:25 +00002782static bool EvaluateStaticConstructor(Function *F, const DataLayout *TD,
Chad Rosiere6de63d2011-12-01 21:29:16 +00002783 const TargetLibraryInfo *TLI) {
Chris Lattnerda1889b2005-09-27 04:27:01 +00002784 // Call the function.
Nick Lewycky60829a582012-02-20 03:25:59 +00002785 Evaluator Eval(TD, TLI);
Chris Lattner65a3a092005-09-27 04:45:34 +00002786 Constant *RetValDummy;
Nick Lewycky73be5e32012-02-19 23:26:27 +00002787 bool EvalSuccess = Eval.EvaluateFunction(F, RetValDummy,
2788 SmallVector<Constant*, 0>());
Jakub Staszak9525a772012-12-06 21:57:16 +00002789
Chris Lattnerda1889b2005-09-27 04:27:01 +00002790 if (EvalSuccess) {
Chris Lattner6bf2cd52005-09-26 17:07:09 +00002791 // We succeeded at evaluation: commit the result.
David Greene44cb8ad2010-01-05 01:28:05 +00002792 DEBUG(dbgs() << "FULLY EVALUATED GLOBAL CTOR FUNCTION '"
Nick Lewycky73be5e32012-02-19 23:26:27 +00002793 << F->getName() << "' to " << Eval.getMutatedMemory().size()
Daniel Dunbar0dd5e1e2009-07-25 00:23:56 +00002794 << " stores.\n");
Nick Lewycky73be5e32012-02-19 23:26:27 +00002795 for (DenseMap<Constant*, Constant*>::const_iterator I =
2796 Eval.getMutatedMemory().begin(), E = Eval.getMutatedMemory().end();
Nick Lewyckyb74ae9c2012-06-24 04:07:14 +00002797 I != E; ++I)
Chris Lattner46b5c642009-11-06 04:27:31 +00002798 CommitValueTo(I->second, I->first);
Nick Lewycky73be5e32012-02-19 23:26:27 +00002799 for (SmallPtrSet<GlobalVariable*, 8>::const_iterator I =
2800 Eval.getInvariants().begin(), E = Eval.getInvariants().end();
2801 I != E; ++I)
Nick Lewycky68f9f9d2012-02-17 06:59:21 +00002802 (*I)->setConstant(true);
Chris Lattner6bf2cd52005-09-26 17:07:09 +00002803 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002804
Chris Lattnerda1889b2005-09-27 04:27:01 +00002805 return EvalSuccess;
Chris Lattner99e23fa2005-09-26 04:44:35 +00002806}
2807
Chris Lattner41b6a5a2005-09-26 01:43:45 +00002808/// OptimizeGlobalCtorsList - Simplify and evaluation global ctors if possible.
2809/// Return true if anything changed.
2810bool GlobalOpt::OptimizeGlobalCtorsList(GlobalVariable *&GCL) {
2811 std::vector<Function*> Ctors = ParseGlobalCtors(GCL);
2812 bool MadeChange = false;
2813 if (Ctors.empty()) return false;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002814
Chris Lattner41b6a5a2005-09-26 01:43:45 +00002815 // Loop over global ctors, optimizing them when we can.
2816 for (unsigned i = 0; i != Ctors.size(); ++i) {
2817 Function *F = Ctors[i];
2818 // Found a null terminator in the middle of the list, prune off the rest of
2819 // the list.
Chris Lattner838bdc12005-09-26 02:19:27 +00002820 if (F == 0) {
2821 if (i != Ctors.size()-1) {
2822 Ctors.resize(i+1);
2823 MadeChange = true;
2824 }
Chris Lattner41b6a5a2005-09-26 01:43:45 +00002825 break;
2826 }
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002827 DEBUG(dbgs() << "Optimizing Global Constructor: " << *F << "\n");
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002828
Chris Lattner99e23fa2005-09-26 04:44:35 +00002829 // We cannot simplify external ctor functions.
2830 if (F->empty()) continue;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002831
Chris Lattner99e23fa2005-09-26 04:44:35 +00002832 // If we can evaluate the ctor at compile time, do.
Chad Rosiere6de63d2011-12-01 21:29:16 +00002833 if (EvaluateStaticConstructor(F, TD, TLI)) {
Chris Lattner99e23fa2005-09-26 04:44:35 +00002834 Ctors.erase(Ctors.begin()+i);
2835 MadeChange = true;
2836 --i;
2837 ++NumCtorsEvaluated;
2838 continue;
2839 }
Chris Lattner41b6a5a2005-09-26 01:43:45 +00002840 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002841
Chris Lattner41b6a5a2005-09-26 01:43:45 +00002842 if (!MadeChange) return false;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002843
Chris Lattner46b5c642009-11-06 04:27:31 +00002844 GCL = InstallGlobalCtors(GCL, Ctors);
Chris Lattner41b6a5a2005-09-26 01:43:45 +00002845 return true;
2846}
2847
Benjamin Kramer8817cca2013-09-22 14:09:50 +00002848static int compareNames(Constant *const *A, Constant *const *B) {
2849 return (*A)->getName().compare((*B)->getName());
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002850}
Rafael Espindola00752162013-05-09 17:22:59 +00002851
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002852static void setUsedInitializer(GlobalVariable &V,
2853 SmallPtrSet<GlobalValue *, 8> Init) {
Rafael Espindolac2bb73f2013-07-20 23:33:15 +00002854 if (Init.empty()) {
2855 V.eraseFromParent();
2856 return;
2857 }
2858
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002859 SmallVector<llvm::Constant *, 8> UsedArray;
2860 PointerType *Int8PtrTy = Type::getInt8PtrTy(V.getContext());
Rafael Espindola00752162013-05-09 17:22:59 +00002861
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002862 for (SmallPtrSet<GlobalValue *, 8>::iterator I = Init.begin(), E = Init.end();
2863 I != E; ++I) {
2864 Constant *Cast = llvm::ConstantExpr::getBitCast(*I, Int8PtrTy);
2865 UsedArray.push_back(Cast);
Rafael Espindola00752162013-05-09 17:22:59 +00002866 }
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002867 // Sort to get deterministic order.
2868 array_pod_sort(UsedArray.begin(), UsedArray.end(), compareNames);
2869 ArrayType *ATy = ArrayType::get(Int8PtrTy, UsedArray.size());
Rafael Espindola00752162013-05-09 17:22:59 +00002870
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002871 Module *M = V.getParent();
2872 V.removeFromParent();
2873 GlobalVariable *NV =
2874 new GlobalVariable(*M, ATy, false, llvm::GlobalValue::AppendingLinkage,
2875 llvm::ConstantArray::get(ATy, UsedArray), "");
2876 NV->takeName(&V);
2877 NV->setSection("llvm.metadata");
2878 delete &V;
Rafael Espindola00752162013-05-09 17:22:59 +00002879}
2880
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002881namespace {
Rafael Espindola9aadcc42013-07-19 18:44:51 +00002882/// \brief An easy to access representation of llvm.used and llvm.compiler.used.
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002883class LLVMUsed {
2884 SmallPtrSet<GlobalValue *, 8> Used;
2885 SmallPtrSet<GlobalValue *, 8> CompilerUsed;
2886 GlobalVariable *UsedV;
2887 GlobalVariable *CompilerUsedV;
2888
2889public:
Rafael Espindolaec2375f2013-07-25 02:50:08 +00002890 LLVMUsed(Module &M) {
Rafael Espindola17600e22013-07-25 03:23:25 +00002891 UsedV = collectUsedGlobalVariables(M, Used, false);
2892 CompilerUsedV = collectUsedGlobalVariables(M, CompilerUsed, true);
Rafael Espindola00752162013-05-09 17:22:59 +00002893 }
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002894 typedef SmallPtrSet<GlobalValue *, 8>::iterator iterator;
2895 iterator usedBegin() { return Used.begin(); }
2896 iterator usedEnd() { return Used.end(); }
2897 iterator compilerUsedBegin() { return CompilerUsed.begin(); }
2898 iterator compilerUsedEnd() { return CompilerUsed.end(); }
2899 bool usedCount(GlobalValue *GV) const { return Used.count(GV); }
2900 bool compilerUsedCount(GlobalValue *GV) const {
2901 return CompilerUsed.count(GV);
2902 }
2903 bool usedErase(GlobalValue *GV) { return Used.erase(GV); }
2904 bool compilerUsedErase(GlobalValue *GV) { return CompilerUsed.erase(GV); }
2905 bool usedInsert(GlobalValue *GV) { return Used.insert(GV); }
2906 bool compilerUsedInsert(GlobalValue *GV) { return CompilerUsed.insert(GV); }
Rafael Espindola00752162013-05-09 17:22:59 +00002907
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002908 void syncVariablesAndSets() {
2909 if (UsedV)
2910 setUsedInitializer(*UsedV, Used);
2911 if (CompilerUsedV)
2912 setUsedInitializer(*CompilerUsedV, CompilerUsed);
2913 }
2914};
Rafael Espindola00752162013-05-09 17:22:59 +00002915}
2916
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002917static bool hasUseOtherThanLLVMUsed(GlobalAlias &GA, const LLVMUsed &U) {
2918 if (GA.use_empty()) // No use at all.
2919 return false;
2920
2921 assert((!U.usedCount(&GA) || !U.compilerUsedCount(&GA)) &&
2922 "We should have removed the duplicated "
Rafael Espindola9aadcc42013-07-19 18:44:51 +00002923 "element from llvm.compiler.used");
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002924 if (!GA.hasOneUse())
2925 // Strictly more than one use. So at least one is not in llvm.used and
Rafael Espindola9aadcc42013-07-19 18:44:51 +00002926 // llvm.compiler.used.
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002927 return true;
2928
Rafael Espindola9aadcc42013-07-19 18:44:51 +00002929 // Exactly one use. Check if it is in llvm.used or llvm.compiler.used.
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002930 return !U.usedCount(&GA) && !U.compilerUsedCount(&GA);
Rafael Espindola00752162013-05-09 17:22:59 +00002931}
2932
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002933static bool hasMoreThanOneUseOtherThanLLVMUsed(GlobalValue &V,
2934 const LLVMUsed &U) {
2935 unsigned N = 2;
2936 assert((!U.usedCount(&V) || !U.compilerUsedCount(&V)) &&
2937 "We should have removed the duplicated "
Rafael Espindola9aadcc42013-07-19 18:44:51 +00002938 "element from llvm.compiler.used");
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002939 if (U.usedCount(&V) || U.compilerUsedCount(&V))
2940 ++N;
2941 return V.hasNUsesOrMore(N);
2942}
2943
2944static bool mayHaveOtherReferences(GlobalAlias &GA, const LLVMUsed &U) {
2945 if (!GA.hasLocalLinkage())
2946 return true;
2947
2948 return U.usedCount(&GA) || U.compilerUsedCount(&GA);
2949}
2950
2951static bool hasUsesToReplace(GlobalAlias &GA, LLVMUsed &U, bool &RenameTarget) {
2952 RenameTarget = false;
Rafael Espindola00752162013-05-09 17:22:59 +00002953 bool Ret = false;
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002954 if (hasUseOtherThanLLVMUsed(GA, U))
Rafael Espindola00752162013-05-09 17:22:59 +00002955 Ret = true;
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002956
2957 // If the alias is externally visible, we may still be able to simplify it.
2958 if (!mayHaveOtherReferences(GA, U))
2959 return Ret;
2960
2961 // If the aliasee has internal linkage, give it the name and linkage
2962 // of the alias, and delete the alias. This turns:
2963 // define internal ... @f(...)
2964 // @a = alias ... @f
2965 // into:
2966 // define ... @a(...)
2967 Constant *Aliasee = GA.getAliasee();
2968 GlobalValue *Target = cast<GlobalValue>(Aliasee->stripPointerCasts());
2969 if (!Target->hasLocalLinkage())
2970 return Ret;
2971
2972 // Do not perform the transform if multiple aliases potentially target the
2973 // aliasee. This check also ensures that it is safe to replace the section
2974 // and other attributes of the aliasee with those of the alias.
2975 if (hasMoreThanOneUseOtherThanLLVMUsed(*Target, U))
2976 return Ret;
2977
2978 RenameTarget = true;
2979 return true;
Rafael Espindola00752162013-05-09 17:22:59 +00002980}
2981
Duncan Sandsed722832009-03-06 10:21:56 +00002982bool GlobalOpt::OptimizeGlobalAliases(Module &M) {
Anton Korobeynikova9b60ee2008-09-09 19:04:59 +00002983 bool Changed = false;
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002984 LLVMUsed Used(M);
2985
2986 for (SmallPtrSet<GlobalValue *, 8>::iterator I = Used.usedBegin(),
2987 E = Used.usedEnd();
2988 I != E; ++I)
2989 Used.compilerUsedErase(*I);
Anton Korobeynikova9b60ee2008-09-09 19:04:59 +00002990
Duncan Sands0bcf0852009-01-07 20:01:06 +00002991 for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end();
Duncan Sandsb3f27882009-02-15 09:56:08 +00002992 I != E;) {
2993 Module::alias_iterator J = I++;
Duncan Sandsed722832009-03-06 10:21:56 +00002994 // Aliases without names cannot be referenced outside this module.
2995 if (!J->hasName() && !J->isDeclaration())
2996 J->setLinkage(GlobalValue::InternalLinkage);
Duncan Sandsb3f27882009-02-15 09:56:08 +00002997 // If the aliasee may change at link time, nothing can be done - bail out.
2998 if (J->mayBeOverridden())
Anton Korobeynikova9b60ee2008-09-09 19:04:59 +00002999 continue;
3000
Duncan Sandsb3f27882009-02-15 09:56:08 +00003001 Constant *Aliasee = J->getAliasee();
3002 GlobalValue *Target = cast<GlobalValue>(Aliasee->stripPointerCasts());
Duncan Sands7a1db332009-02-18 17:55:38 +00003003 Target->removeDeadConstantUsers();
Duncan Sandsb3f27882009-02-15 09:56:08 +00003004
3005 // Make all users of the alias use the aliasee instead.
Rafael Espindolaa82555c2013-06-11 17:48:06 +00003006 bool RenameTarget;
3007 if (!hasUsesToReplace(*J, Used, RenameTarget))
Rafael Espindola00752162013-05-09 17:22:59 +00003008 continue;
Duncan Sandsb3f27882009-02-15 09:56:08 +00003009
Rafael Espindolaa82555c2013-06-11 17:48:06 +00003010 J->replaceAllUsesWith(Aliasee);
3011 ++NumAliasesResolved;
3012 Changed = true;
Duncan Sandsb3f27882009-02-15 09:56:08 +00003013
Rafael Espindolaa82555c2013-06-11 17:48:06 +00003014 if (RenameTarget) {
Duncan Sands6a3df7b2009-12-08 10:10:20 +00003015 // Give the aliasee the name, linkage and other attributes of the alias.
3016 Target->takeName(J);
3017 Target->setLinkage(J->getLinkage());
3018 Target->GlobalValue::copyAttributesFrom(J);
Rafael Espindolaa82555c2013-06-11 17:48:06 +00003019
3020 if (Used.usedErase(J))
3021 Used.usedInsert(Target);
3022
3023 if (Used.compilerUsedErase(J))
3024 Used.compilerUsedInsert(Target);
Rafael Espindola8d304802013-06-12 16:45:47 +00003025 } else if (mayHaveOtherReferences(*J, Used))
Rafael Espindolaa82555c2013-06-11 17:48:06 +00003026 continue;
3027
Duncan Sandsb3f27882009-02-15 09:56:08 +00003028 // Delete the alias.
3029 M.getAliasList().erase(J);
3030 ++NumAliasesRemoved;
3031 Changed = true;
Anton Korobeynikova9b60ee2008-09-09 19:04:59 +00003032 }
3033
Rafael Espindolaa82555c2013-06-11 17:48:06 +00003034 Used.syncVariablesAndSets();
3035
Anton Korobeynikova9b60ee2008-09-09 19:04:59 +00003036 return Changed;
3037}
Chris Lattner41b6a5a2005-09-26 01:43:45 +00003038
Nick Lewycky4b273cb2012-02-12 02:15:20 +00003039static Function *FindCXAAtExit(Module &M, TargetLibraryInfo *TLI) {
3040 if (!TLI->has(LibFunc::cxa_atexit))
Nick Lewyckyf2852562012-02-12 02:17:18 +00003041 return 0;
Nick Lewycky4b273cb2012-02-12 02:15:20 +00003042
3043 Function *Fn = M.getFunction(TLI->getName(LibFunc::cxa_atexit));
Jakub Staszak9525a772012-12-06 21:57:16 +00003044
Anders Carlssonee6bc702011-03-20 17:59:11 +00003045 if (!Fn)
3046 return 0;
Nick Lewycky4b273cb2012-02-12 02:15:20 +00003047
Chris Lattner229907c2011-07-18 04:54:35 +00003048 FunctionType *FTy = Fn->getFunctionType();
Jakub Staszak9525a772012-12-06 21:57:16 +00003049
3050 // Checking that the function has the right return type, the right number of
Anders Carlsson48a44912011-03-20 19:51:13 +00003051 // parameters and that they all have pointer types should be enough.
3052 if (!FTy->getReturnType()->isIntegerTy() ||
3053 FTy->getNumParams() != 3 ||
Anders Carlssonee6bc702011-03-20 17:59:11 +00003054 !FTy->getParamType(0)->isPointerTy() ||
3055 !FTy->getParamType(1)->isPointerTy() ||
3056 !FTy->getParamType(2)->isPointerTy())
3057 return 0;
3058
3059 return Fn;
3060}
3061
3062/// cxxDtorIsEmpty - Returns whether the given function is an empty C++
3063/// destructor and can therefore be eliminated.
3064/// Note that we assume that other optimization passes have already simplified
3065/// the code so we only look for a function with a single basic block, where
Benjamin Kramer1a4695a2012-02-09 16:28:15 +00003066/// the only allowed instructions are 'ret', 'call' to an empty C++ dtor and
3067/// other side-effect free instructions.
Anders Carlssonfcec2f52011-03-20 20:16:43 +00003068static bool cxxDtorIsEmpty(const Function &Fn,
3069 SmallPtrSet<const Function *, 8> &CalledFunctions) {
Anders Carlsson48a44912011-03-20 19:51:13 +00003070 // FIXME: We could eliminate C++ destructors if they're readonly/readnone and
Nick Lewyckyd0781832011-03-21 02:26:01 +00003071 // nounwind, but that doesn't seem worth doing.
Anders Carlsson48a44912011-03-20 19:51:13 +00003072 if (Fn.isDeclaration())
3073 return false;
Anders Carlssonee6bc702011-03-20 17:59:11 +00003074
3075 if (++Fn.begin() != Fn.end())
3076 return false;
3077
3078 const BasicBlock &EntryBlock = Fn.getEntryBlock();
3079 for (BasicBlock::const_iterator I = EntryBlock.begin(), E = EntryBlock.end();
3080 I != E; ++I) {
3081 if (const CallInst *CI = dyn_cast<CallInst>(I)) {
Anders Carlsson4dd420f2011-03-21 14:54:40 +00003082 // Ignore debug intrinsics.
3083 if (isa<DbgInfoIntrinsic>(CI))
3084 continue;
3085
Anders Carlssonee6bc702011-03-20 17:59:11 +00003086 const Function *CalledFn = CI->getCalledFunction();
3087
3088 if (!CalledFn)
3089 return false;
3090
Anders Carlsson1cc80732011-03-22 03:21:01 +00003091 SmallPtrSet<const Function *, 8> NewCalledFunctions(CalledFunctions);
3092
Anders Carlsson48a44912011-03-20 19:51:13 +00003093 // Don't treat recursive functions as empty.
Anders Carlsson1cc80732011-03-22 03:21:01 +00003094 if (!NewCalledFunctions.insert(CalledFn))
Anders Carlsson48a44912011-03-20 19:51:13 +00003095 return false;
3096
Anders Carlsson1cc80732011-03-22 03:21:01 +00003097 if (!cxxDtorIsEmpty(*CalledFn, NewCalledFunctions))
Anders Carlssonee6bc702011-03-20 17:59:11 +00003098 return false;
3099 } else if (isa<ReturnInst>(*I))
Benjamin Kramer487a3962012-02-09 14:26:06 +00003100 return true; // We're done.
3101 else if (I->mayHaveSideEffects())
3102 return false; // Destructor with side effects, bail.
Anders Carlssonee6bc702011-03-20 17:59:11 +00003103 }
3104
3105 return false;
3106}
3107
3108bool GlobalOpt::OptimizeEmptyGlobalCXXDtors(Function *CXAAtExitFn) {
3109 /// Itanium C++ ABI p3.3.5:
3110 ///
3111 /// After constructing a global (or local static) object, that will require
3112 /// destruction on exit, a termination function is registered as follows:
3113 ///
3114 /// extern "C" int __cxa_atexit ( void (*f)(void *), void *p, void *d );
3115 ///
3116 /// This registration, e.g. __cxa_atexit(f,p,d), is intended to cause the
3117 /// call f(p) when DSO d is unloaded, before all such termination calls
3118 /// registered before this one. It returns zero if registration is
Nick Lewyckyd0781832011-03-21 02:26:01 +00003119 /// successful, nonzero on failure.
Anders Carlssonee6bc702011-03-20 17:59:11 +00003120
3121 // This pass will look for calls to __cxa_atexit where the function is trivial
3122 // and remove them.
3123 bool Changed = false;
3124
Jakub Staszak9525a772012-12-06 21:57:16 +00003125 for (Function::use_iterator I = CXAAtExitFn->use_begin(),
Anders Carlssonee6bc702011-03-20 17:59:11 +00003126 E = CXAAtExitFn->use_end(); I != E;) {
Anders Carlsson336fd902011-03-20 20:21:33 +00003127 // We're only interested in calls. Theoretically, we could handle invoke
3128 // instructions as well, but neither llvm-gcc nor clang generate invokes
3129 // to __cxa_atexit.
Anders Carlsson4dd420f2011-03-21 14:54:40 +00003130 CallInst *CI = dyn_cast<CallInst>(*I++);
3131 if (!CI)
Anders Carlsson336fd902011-03-20 20:21:33 +00003132 continue;
3133
Jakub Staszak9525a772012-12-06 21:57:16 +00003134 Function *DtorFn =
Anders Carlsson4dd420f2011-03-21 14:54:40 +00003135 dyn_cast<Function>(CI->getArgOperand(0)->stripPointerCasts());
Anders Carlssonee6bc702011-03-20 17:59:11 +00003136 if (!DtorFn)
3137 continue;
3138
Anders Carlssonfcec2f52011-03-20 20:16:43 +00003139 SmallPtrSet<const Function *, 8> CalledFunctions;
3140 if (!cxxDtorIsEmpty(*DtorFn, CalledFunctions))
Anders Carlssonee6bc702011-03-20 17:59:11 +00003141 continue;
3142
3143 // Just remove the call.
Anders Carlsson4dd420f2011-03-21 14:54:40 +00003144 CI->replaceAllUsesWith(Constant::getNullValue(CI->getType()));
3145 CI->eraseFromParent();
Anders Carlsson48a44912011-03-20 19:51:13 +00003146
Anders Carlssonee6bc702011-03-20 17:59:11 +00003147 ++NumCXXDtorsRemoved;
3148
3149 Changed |= true;
3150 }
3151
3152 return Changed;
3153}
3154
Chris Lattner25db5802004-10-07 04:16:33 +00003155bool GlobalOpt::runOnModule(Module &M) {
3156 bool Changed = false;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00003157
Micah Villmowcdfe20b2012-10-08 16:38:25 +00003158 TD = getAnalysisIfAvailable<DataLayout>();
Nick Lewycky4b273cb2012-02-12 02:15:20 +00003159 TLI = &getAnalysis<TargetLibraryInfo>();
Nick Lewyckycf6aae62012-02-12 01:13:18 +00003160
Chris Lattner41b6a5a2005-09-26 01:43:45 +00003161 // Try to find the llvm.globalctors list.
3162 GlobalVariable *GlobalCtors = FindGlobalCtors(M);
Chris Lattner25db5802004-10-07 04:16:33 +00003163
Chris Lattner25db5802004-10-07 04:16:33 +00003164 bool LocalChange = true;
3165 while (LocalChange) {
3166 LocalChange = false;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00003167
Chris Lattner41b6a5a2005-09-26 01:43:45 +00003168 // Delete functions that are trivially dead, ccc -> fastcc
3169 LocalChange |= OptimizeFunctions(M);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00003170
Chris Lattner41b6a5a2005-09-26 01:43:45 +00003171 // Optimize global_ctors list.
3172 if (GlobalCtors)
3173 LocalChange |= OptimizeGlobalCtorsList(GlobalCtors);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00003174
Chris Lattner41b6a5a2005-09-26 01:43:45 +00003175 // Optimize non-address-taken globals.
3176 LocalChange |= OptimizeGlobalVars(M);
Anton Korobeynikova9b60ee2008-09-09 19:04:59 +00003177
3178 // Resolve aliases, when possible.
Duncan Sandsed722832009-03-06 10:21:56 +00003179 LocalChange |= OptimizeGlobalAliases(M);
Anders Carlssonee6bc702011-03-20 17:59:11 +00003180
Manman Renb3c52fb2013-05-14 21:52:44 +00003181 // Try to remove trivial global destructors if they are not removed
3182 // already.
3183 Function *CXAAtExitFn = FindCXAAtExit(M, TLI);
Anders Carlssonee6bc702011-03-20 17:59:11 +00003184 if (CXAAtExitFn)
3185 LocalChange |= OptimizeEmptyGlobalCXXDtors(CXAAtExitFn);
3186
Anton Korobeynikova9b60ee2008-09-09 19:04:59 +00003187 Changed |= LocalChange;
Chris Lattner25db5802004-10-07 04:16:33 +00003188 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00003189
Chris Lattner41b6a5a2005-09-26 01:43:45 +00003190 // TODO: Move all global ctors functions to the end of the module for code
3191 // layout.
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00003192
Chris Lattner25db5802004-10-07 04:16:33 +00003193 return Changed;
3194}