blob: 0381f8c180e5b65428b7a8c2960590387e5594a6 [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"
Hal Finkelf59fd7d2013-12-12 20:45:24 +000039#include "llvm/Support/ValueHandle.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000040#include "llvm/Support/raw_ostream.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);
Matt Arsenault461c8e02014-01-02 20:01:43 +0000300 } else if ((CE->getOpcode() == Instruction::BitCast &&
301 CE->getType()->isPointerTy()) ||
302 CE->getOpcode() == Instruction::AddrSpaceCast) {
Chris Lattner7561ca12005-02-27 18:58:52 +0000303 // Pointer cast, delete any stores and memsets to the global.
Nick Lewyckycf6aae62012-02-12 01:13:18 +0000304 Changed |= CleanupConstantGlobalUsers(CE, 0, TD, TLI);
Chris Lattner7561ca12005-02-27 18:58:52 +0000305 }
306
307 if (CE->use_empty()) {
308 CE->destroyConstant();
309 Changed = true;
Chris Lattner25db5802004-10-07 04:16:33 +0000310 }
311 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
Chris Lattnerf9c0fd72007-11-09 17:33:02 +0000312 // Do not transform "gepinst (gep constexpr (GV))" here, because forming
313 // "gepconstexpr (gep constexpr (GV))" will cause the two gep's to fold
314 // and will invalidate our notion of what Init is.
Chris Lattner68f04fa2007-11-13 21:46:23 +0000315 Constant *SubInit = 0;
Chris Lattnerf9c0fd72007-11-09 17:33:02 +0000316 if (!isa<ConstantExpr>(GEP->getOperand(0))) {
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000317 ConstantExpr *CE =
Nick Lewyckycf6aae62012-02-12 01:13:18 +0000318 dyn_cast_or_null<ConstantExpr>(ConstantFoldInstruction(GEP, TD, TLI));
Chris Lattnerf9c0fd72007-11-09 17:33:02 +0000319 if (Init && CE && CE->getOpcode() == Instruction::GetElementPtr)
Dan Gohmane525d9d2009-10-05 16:36:26 +0000320 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
Benjamin Krameraa9e4a52012-03-28 14:50:09 +0000321
322 // If the initializer is an all-null value and we have an inbounds GEP,
323 // we already know what the result of any load from that GEP is.
324 // TODO: Handle splats.
325 if (Init && isa<ConstantAggregateZero>(Init) && GEP->isInBounds())
326 SubInit = Constant::getNullValue(GEP->getType()->getElementType());
Chris Lattnerf9c0fd72007-11-09 17:33:02 +0000327 }
Nick Lewyckycf6aae62012-02-12 01:13:18 +0000328 Changed |= CleanupConstantGlobalUsers(GEP, SubInit, TD, TLI);
Chris Lattnera0e769c2004-10-10 16:47:33 +0000329
Chris Lattnercb9f1522004-10-10 16:43:46 +0000330 if (GEP->use_empty()) {
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000331 GEP->eraseFromParent();
Chris Lattnercb9f1522004-10-10 16:43:46 +0000332 Changed = true;
333 }
Chris Lattner7561ca12005-02-27 18:58:52 +0000334 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U)) { // memset/cpy/mv
335 if (MI->getRawDest() == V) {
336 MI->eraseFromParent();
337 Changed = true;
338 }
339
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000340 } else if (Constant *C = dyn_cast<Constant>(U)) {
341 // If we have a chain of dead constantexprs or other things dangling from
342 // us, and if they are all dead, nuke them without remorse.
Rafael Espindola27797ba2013-10-17 18:06:32 +0000343 if (isSafeToDestroyConstant(C)) {
Devang Pateld926aaa2009-03-06 01:37:41 +0000344 C->destroyConstant();
Nick Lewyckycf6aae62012-02-12 01:13:18 +0000345 CleanupConstantGlobalUsers(V, Init, TD, TLI);
Chris Lattnercb9f1522004-10-10 16:43:46 +0000346 return true;
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000347 }
Chris Lattner25db5802004-10-07 04:16:33 +0000348 }
349 }
Chris Lattnercb9f1522004-10-10 16:43:46 +0000350 return Changed;
Chris Lattner25db5802004-10-07 04:16:33 +0000351}
352
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000353/// isSafeSROAElementUse - Return true if the specified instruction is a safe
354/// user of a derived expression from a global that we want to SROA.
355static bool isSafeSROAElementUse(Value *V) {
356 // We might have a dead and dangling constant hanging off of here.
357 if (Constant *C = dyn_cast<Constant>(V))
Rafael Espindola27797ba2013-10-17 18:06:32 +0000358 return isSafeToDestroyConstant(C);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000359
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000360 Instruction *I = dyn_cast<Instruction>(V);
361 if (!I) return false;
362
363 // Loads are ok.
364 if (isa<LoadInst>(I)) return true;
365
366 // Stores *to* the pointer are ok.
367 if (StoreInst *SI = dyn_cast<StoreInst>(I))
368 return SI->getOperand(0) != V;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000369
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000370 // Otherwise, it must be a GEP.
371 GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I);
372 if (GEPI == 0) return false;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000373
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000374 if (GEPI->getNumOperands() < 3 || !isa<Constant>(GEPI->getOperand(1)) ||
375 !cast<Constant>(GEPI->getOperand(1))->isNullValue())
376 return false;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000377
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000378 for (Value::use_iterator I = GEPI->use_begin(), E = GEPI->use_end();
379 I != E; ++I)
380 if (!isSafeSROAElementUse(*I))
381 return false;
Chris Lattnerab053722008-01-14 01:31:05 +0000382 return true;
383}
384
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000385
386/// IsUserOfGlobalSafeForSRA - U is a direct user of the specified global value.
387/// Look at it and its uses and decide whether it is safe to SROA this global.
388///
389static bool IsUserOfGlobalSafeForSRA(User *U, GlobalValue *GV) {
390 // The user of the global must be a GEP Inst or a ConstantExpr GEP.
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000391 if (!isa<GetElementPtrInst>(U) &&
392 (!isa<ConstantExpr>(U) ||
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000393 cast<ConstantExpr>(U)->getOpcode() != Instruction::GetElementPtr))
394 return false;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000395
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000396 // Check to see if this ConstantExpr GEP is SRA'able. In particular, we
397 // don't like < 3 operand CE's, and we don't like non-constant integer
398 // indices. This enforces that all uses are 'gep GV, 0, C, ...' for some
399 // value of C.
400 if (U->getNumOperands() < 3 || !isa<Constant>(U->getOperand(1)) ||
401 !cast<Constant>(U->getOperand(1))->isNullValue() ||
402 !isa<ConstantInt>(U->getOperand(2)))
403 return false;
404
405 gep_type_iterator GEPI = gep_type_begin(U), E = gep_type_end(U);
406 ++GEPI; // Skip over the pointer index.
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000407
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000408 // If this is a use of an array allocation, do a bit more checking for sanity.
Chris Lattner229907c2011-07-18 04:54:35 +0000409 if (ArrayType *AT = dyn_cast<ArrayType>(*GEPI)) {
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000410 uint64_t NumElements = AT->getNumElements();
411 ConstantInt *Idx = cast<ConstantInt>(U->getOperand(2));
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000412
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000413 // Check to make sure that index falls within the array. If not,
414 // something funny is going on, so we won't do the optimization.
415 //
416 if (Idx->getZExtValue() >= NumElements)
417 return false;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000418
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000419 // We cannot scalar repl this level of the array unless any array
420 // sub-indices are in-range constants. In particular, consider:
421 // A[0][i]. We cannot know that the user isn't doing invalid things like
422 // allowing i to index an out-of-range subscript that accesses A[1].
423 //
424 // Scalar replacing *just* the outer index of the array is probably not
425 // going to be a win anyway, so just give up.
426 for (++GEPI; // Skip array index.
Dan Gohman82ac81b2009-08-18 14:58:19 +0000427 GEPI != E;
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000428 ++GEPI) {
429 uint64_t NumElements;
Chris Lattner229907c2011-07-18 04:54:35 +0000430 if (ArrayType *SubArrayTy = dyn_cast<ArrayType>(*GEPI))
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000431 NumElements = SubArrayTy->getNumElements();
Chris Lattner229907c2011-07-18 04:54:35 +0000432 else if (VectorType *SubVectorTy = dyn_cast<VectorType>(*GEPI))
Dan Gohman82ac81b2009-08-18 14:58:19 +0000433 NumElements = SubVectorTy->getNumElements();
434 else {
Duncan Sands19d0b472010-02-16 11:11:14 +0000435 assert((*GEPI)->isStructTy() &&
Dan Gohman82ac81b2009-08-18 14:58:19 +0000436 "Indexed GEP type is not array, vector, or struct!");
437 continue;
438 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000439
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000440 ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPI.getOperand());
441 if (!IdxVal || IdxVal->getZExtValue() >= NumElements)
442 return false;
443 }
444 }
445
446 for (Value::use_iterator I = U->use_begin(), E = U->use_end(); I != E; ++I)
447 if (!isSafeSROAElementUse(*I))
448 return false;
449 return true;
450}
451
452/// GlobalUsersSafeToSRA - Look at all uses of the global and decide whether it
453/// is safe for us to perform this transformation.
454///
455static bool GlobalUsersSafeToSRA(GlobalValue *GV) {
456 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end();
457 UI != E; ++UI) {
458 if (!IsUserOfGlobalSafeForSRA(*UI, GV))
459 return false;
460 }
461 return true;
462}
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000463
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000464
Chris Lattnerabab0712004-10-08 17:32:09 +0000465/// SRAGlobal - Perform scalar replacement of aggregates on the specified global
466/// variable. This opens the door for other optimizations by exposing the
467/// behavior of the program in a more fine-grained way. We have determined that
468/// this transformation is safe already. We return the first global variable we
469/// insert so that the caller can reprocess it.
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000470static GlobalVariable *SRAGlobal(GlobalVariable *GV, const DataLayout &TD) {
Chris Lattnerab053722008-01-14 01:31:05 +0000471 // Make sure this global only has simple uses that we can SRA.
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000472 if (!GlobalUsersSafeToSRA(GV))
Chris Lattnerab053722008-01-14 01:31:05 +0000473 return 0;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000474
Rafael Espindola6de96a12009-01-15 20:18:42 +0000475 assert(GV->hasLocalLinkage() && !GV->isConstant());
Chris Lattnerabab0712004-10-08 17:32:09 +0000476 Constant *Init = GV->getInitializer();
Chris Lattner229907c2011-07-18 04:54:35 +0000477 Type *Ty = Init->getType();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000478
Chris Lattnerabab0712004-10-08 17:32:09 +0000479 std::vector<GlobalVariable*> NewGlobals;
480 Module::GlobalListType &Globals = GV->getParent()->getGlobalList();
481
Chris Lattner67ca6f632008-04-26 07:40:11 +0000482 // Get the alignment of the global, either explicit or target-specific.
483 unsigned StartAlignment = GV->getAlignment();
484 if (StartAlignment == 0)
485 StartAlignment = TD.getABITypeAlignment(GV->getType());
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000486
Chris Lattner229907c2011-07-18 04:54:35 +0000487 if (StructType *STy = dyn_cast<StructType>(Ty)) {
Chris Lattnerabab0712004-10-08 17:32:09 +0000488 NewGlobals.reserve(STy->getNumElements());
Chris Lattner67ca6f632008-04-26 07:40:11 +0000489 const StructLayout &Layout = *TD.getStructLayout(STy);
Chris Lattnerabab0712004-10-08 17:32:09 +0000490 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
Chris Lattner67058832012-01-25 06:48:06 +0000491 Constant *In = Init->getAggregateElement(i);
Chris Lattnerabab0712004-10-08 17:32:09 +0000492 assert(In && "Couldn't get element of initializer?");
Chris Lattner46b5c642009-11-06 04:27:31 +0000493 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(i), false,
Chris Lattnerabab0712004-10-08 17:32:09 +0000494 GlobalVariable::InternalLinkage,
Daniel Dunbar132f7832009-07-30 17:37:43 +0000495 In, GV->getName()+"."+Twine(i),
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000496 GV->getThreadLocalMode(),
Owen Anderson5948fdf2009-07-08 01:26:06 +0000497 GV->getType()->getAddressSpace());
Chris Lattnerabab0712004-10-08 17:32:09 +0000498 Globals.insert(GV, NGV);
499 NewGlobals.push_back(NGV);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000500
Chris Lattner67ca6f632008-04-26 07:40:11 +0000501 // Calculate the known alignment of the field. If the original aggregate
502 // had 256 byte alignment for example, something might depend on that:
503 // propagate info to each field.
504 uint64_t FieldOffset = Layout.getElementOffset(i);
505 unsigned NewAlign = (unsigned)MinAlign(StartAlignment, FieldOffset);
506 if (NewAlign > TD.getABITypeAlignment(STy->getElementType(i)))
507 NGV->setAlignment(NewAlign);
Chris Lattnerabab0712004-10-08 17:32:09 +0000508 }
Chris Lattner229907c2011-07-18 04:54:35 +0000509 } else if (SequentialType *STy = dyn_cast<SequentialType>(Ty)) {
Chris Lattnerabab0712004-10-08 17:32:09 +0000510 unsigned NumElements = 0;
Chris Lattner229907c2011-07-18 04:54:35 +0000511 if (ArrayType *ATy = dyn_cast<ArrayType>(STy))
Chris Lattnerabab0712004-10-08 17:32:09 +0000512 NumElements = ATy->getNumElements();
Chris Lattnerabab0712004-10-08 17:32:09 +0000513 else
Chris Lattner67ca6f632008-04-26 07:40:11 +0000514 NumElements = cast<VectorType>(STy)->getNumElements();
Chris Lattnerabab0712004-10-08 17:32:09 +0000515
Chris Lattner25169ca2005-02-23 16:53:04 +0000516 if (NumElements > 16 && GV->hasNUsesOrMore(16))
Chris Lattnerd6a44922005-02-01 01:23:31 +0000517 return 0; // It's not worth it.
Chris Lattnerabab0712004-10-08 17:32:09 +0000518 NewGlobals.reserve(NumElements);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000519
Duncan Sandsaf9eaa82009-05-09 07:06:46 +0000520 uint64_t EltSize = TD.getTypeAllocSize(STy->getElementType());
Chris Lattner67ca6f632008-04-26 07:40:11 +0000521 unsigned EltAlign = TD.getABITypeAlignment(STy->getElementType());
Chris Lattnerabab0712004-10-08 17:32:09 +0000522 for (unsigned i = 0, e = NumElements; i != e; ++i) {
Chris Lattner67058832012-01-25 06:48:06 +0000523 Constant *In = Init->getAggregateElement(i);
Chris Lattnerabab0712004-10-08 17:32:09 +0000524 assert(In && "Couldn't get element of initializer?");
525
Chris Lattner46b5c642009-11-06 04:27:31 +0000526 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(), false,
Chris Lattnerabab0712004-10-08 17:32:09 +0000527 GlobalVariable::InternalLinkage,
Daniel Dunbar132f7832009-07-30 17:37:43 +0000528 In, GV->getName()+"."+Twine(i),
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000529 GV->getThreadLocalMode(),
Owen Andersonb17f3292009-07-08 19:03:57 +0000530 GV->getType()->getAddressSpace());
Chris Lattnerabab0712004-10-08 17:32:09 +0000531 Globals.insert(GV, NGV);
532 NewGlobals.push_back(NGV);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000533
Chris Lattner67ca6f632008-04-26 07:40:11 +0000534 // Calculate the known alignment of the field. If the original aggregate
535 // had 256 byte alignment for example, something might depend on that:
536 // propagate info to each field.
537 unsigned NewAlign = (unsigned)MinAlign(StartAlignment, EltSize*i);
538 if (NewAlign > EltAlign)
539 NGV->setAlignment(NewAlign);
Chris Lattnerabab0712004-10-08 17:32:09 +0000540 }
541 }
542
543 if (NewGlobals.empty())
544 return 0;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000545
David Greene44cb8ad2010-01-05 01:28:05 +0000546 DEBUG(dbgs() << "PERFORMING GLOBAL SRA ON: " << *GV);
Chris Lattner004e2502004-10-11 05:54:41 +0000547
Chris Lattner46b5c642009-11-06 04:27:31 +0000548 Constant *NullInt =Constant::getNullValue(Type::getInt32Ty(GV->getContext()));
Chris Lattnerabab0712004-10-08 17:32:09 +0000549
550 // Loop over all of the uses of the global, replacing the constantexpr geps,
551 // with smaller constantexpr geps or direct references.
552 while (!GV->use_empty()) {
Chris Lattner004e2502004-10-11 05:54:41 +0000553 User *GEP = GV->use_back();
554 assert(((isa<ConstantExpr>(GEP) &&
555 cast<ConstantExpr>(GEP)->getOpcode()==Instruction::GetElementPtr)||
556 isa<GetElementPtrInst>(GEP)) && "NonGEP CE's are not SRAable!");
Misha Brukmanb1c93172005-04-21 23:48:37 +0000557
Chris Lattnerabab0712004-10-08 17:32:09 +0000558 // Ignore the 1th operand, which has to be zero or else the program is quite
559 // broken (undefined). Get the 2nd operand, which is the structure or array
560 // index.
Reid Spencere0fc4df2006-10-20 07:07:24 +0000561 unsigned Val = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
Chris Lattnerabab0712004-10-08 17:32:09 +0000562 if (Val >= NewGlobals.size()) Val = 0; // Out of bound array access.
563
Chris Lattner004e2502004-10-11 05:54:41 +0000564 Value *NewPtr = NewGlobals[Val];
Chris Lattnerabab0712004-10-08 17:32:09 +0000565
566 // Form a shorter GEP if needed.
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +0000567 if (GEP->getNumOperands() > 3) {
Chris Lattner004e2502004-10-11 05:54:41 +0000568 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEP)) {
Chris Lattnerf96f4a82007-01-31 04:40:53 +0000569 SmallVector<Constant*, 8> Idxs;
Chris Lattner004e2502004-10-11 05:54:41 +0000570 Idxs.push_back(NullInt);
571 for (unsigned i = 3, e = CE->getNumOperands(); i != e; ++i)
572 Idxs.push_back(CE->getOperand(i));
Jay Foaded8db7d2011-07-21 14:31:17 +0000573 NewPtr = ConstantExpr::getGetElementPtr(cast<Constant>(NewPtr), Idxs);
Chris Lattner004e2502004-10-11 05:54:41 +0000574 } else {
575 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(GEP);
Chris Lattner927653f2007-01-31 19:59:55 +0000576 SmallVector<Value*, 8> Idxs;
Chris Lattner004e2502004-10-11 05:54:41 +0000577 Idxs.push_back(NullInt);
578 for (unsigned i = 3, e = GEPI->getNumOperands(); i != e; ++i)
579 Idxs.push_back(GEPI->getOperand(i));
Jay Foadd1b78492011-07-25 09:48:08 +0000580 NewPtr = GetElementPtrInst::Create(NewPtr, Idxs,
Daniel Dunbar132f7832009-07-30 17:37:43 +0000581 GEPI->getName()+"."+Twine(Val),GEPI);
Chris Lattner004e2502004-10-11 05:54:41 +0000582 }
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +0000583 }
Chris Lattner004e2502004-10-11 05:54:41 +0000584 GEP->replaceAllUsesWith(NewPtr);
585
586 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(GEP))
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000587 GEPI->eraseFromParent();
Chris Lattner004e2502004-10-11 05:54:41 +0000588 else
589 cast<ConstantExpr>(GEP)->destroyConstant();
Chris Lattnerabab0712004-10-08 17:32:09 +0000590 }
591
Chris Lattner73ad73e2004-10-08 20:25:55 +0000592 // Delete the old global, now that it is dead.
593 Globals.erase(GV);
Chris Lattnerabab0712004-10-08 17:32:09 +0000594 ++NumSRA;
Chris Lattner004e2502004-10-11 05:54:41 +0000595
596 // Loop over the new globals array deleting any globals that are obviously
597 // dead. This can arise due to scalarization of a structure or an array that
598 // has elements that are dead.
599 unsigned FirstGlobal = 0;
600 for (unsigned i = 0, e = NewGlobals.size(); i != e; ++i)
601 if (NewGlobals[i]->use_empty()) {
602 Globals.erase(NewGlobals[i]);
603 if (FirstGlobal == i) ++FirstGlobal;
604 }
605
606 return FirstGlobal != NewGlobals.size() ? NewGlobals[FirstGlobal] : 0;
Chris Lattnerabab0712004-10-08 17:32:09 +0000607}
608
Chris Lattner09a52722004-10-09 21:48:45 +0000609/// AllUsesOfValueWillTrapIfNull - Return true if all users of the specified
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000610/// value will trap if the value is dynamically null. PHIs keeps track of any
Chris Lattner2d2892e2007-09-13 16:30:19 +0000611/// phi nodes we've seen to avoid reprocessing them.
Gabor Greif67972872010-04-06 19:24:18 +0000612static bool AllUsesOfValueWillTrapIfNull(const Value *V,
613 SmallPtrSet<const PHINode*, 8> &PHIs) {
614 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;
Gabor Greif08355d62010-04-06 19:14:05 +0000615 ++UI) {
Gabor Greif67972872010-04-06 19:24:18 +0000616 const User *U = *UI;
Gabor Greif08355d62010-04-06 19:14:05 +0000617
618 if (isa<LoadInst>(U)) {
Chris Lattner09a52722004-10-09 21:48:45 +0000619 // Will trap.
Gabor Greif67972872010-04-06 19:24:18 +0000620 } else if (const StoreInst *SI = dyn_cast<StoreInst>(U)) {
Chris Lattner09a52722004-10-09 21:48:45 +0000621 if (SI->getOperand(0) == V) {
Gabor Greif08355d62010-04-06 19:14:05 +0000622 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner09a52722004-10-09 21:48:45 +0000623 return false; // Storing the value.
624 }
Gabor Greif67972872010-04-06 19:24:18 +0000625 } else if (const CallInst *CI = dyn_cast<CallInst>(U)) {
Gabor Greiffebf6ab2010-03-20 21:00:25 +0000626 if (CI->getCalledValue() != V) {
Gabor Greif08355d62010-04-06 19:14:05 +0000627 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner09a52722004-10-09 21:48:45 +0000628 return false; // Not calling the ptr
629 }
Gabor Greif67972872010-04-06 19:24:18 +0000630 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(U)) {
Gabor Greiffebf6ab2010-03-20 21:00:25 +0000631 if (II->getCalledValue() != V) {
Gabor Greif08355d62010-04-06 19:14:05 +0000632 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner09a52722004-10-09 21:48:45 +0000633 return false; // Not calling the ptr
634 }
Gabor Greif67972872010-04-06 19:24:18 +0000635 } else if (const BitCastInst *CI = dyn_cast<BitCastInst>(U)) {
Chris Lattner2d2892e2007-09-13 16:30:19 +0000636 if (!AllUsesOfValueWillTrapIfNull(CI, PHIs)) return false;
Gabor Greif67972872010-04-06 19:24:18 +0000637 } else if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
Chris Lattner2d2892e2007-09-13 16:30:19 +0000638 if (!AllUsesOfValueWillTrapIfNull(GEPI, PHIs)) return false;
Gabor Greif67972872010-04-06 19:24:18 +0000639 } else if (const PHINode *PN = dyn_cast<PHINode>(U)) {
Chris Lattner2d2892e2007-09-13 16:30:19 +0000640 // If we've already seen this phi node, ignore it, it has already been
641 // checked.
Jakob Stoklund Olesene27dc722010-01-29 23:54:14 +0000642 if (PHIs.insert(PN) && !AllUsesOfValueWillTrapIfNull(PN, PHIs))
643 return false;
Gabor Greif08355d62010-04-06 19:14:05 +0000644 } else if (isa<ICmpInst>(U) &&
Chris Lattnerfe9abf92004-10-22 06:43:28 +0000645 isa<ConstantPointerNull>(UI->getOperand(1))) {
Nick Lewycky614fb942010-02-25 06:39:10 +0000646 // Ignore icmp X, null
Chris Lattner09a52722004-10-09 21:48:45 +0000647 } else {
Gabor Greif08355d62010-04-06 19:14:05 +0000648 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner09a52722004-10-09 21:48:45 +0000649 return false;
650 }
Gabor Greif08355d62010-04-06 19:14:05 +0000651 }
Chris Lattner09a52722004-10-09 21:48:45 +0000652 return true;
653}
654
655/// AllUsesOfLoadedValueWillTrapIfNull - Return true if all uses of any loads
Chris Lattnerfe9abf92004-10-22 06:43:28 +0000656/// from GV will trap if the loaded value is null. Note that this also permits
657/// comparisons of the loaded value against null, as a special case.
Gabor Greif67972872010-04-06 19:24:18 +0000658static bool AllUsesOfLoadedValueWillTrapIfNull(const GlobalVariable *GV) {
659 for (Value::const_use_iterator UI = GV->use_begin(), E = GV->use_end();
Gabor Greif08355d62010-04-06 19:14:05 +0000660 UI != E; ++UI) {
Gabor Greif67972872010-04-06 19:24:18 +0000661 const User *U = *UI;
Gabor Greif08355d62010-04-06 19:14:05 +0000662
Gabor Greif67972872010-04-06 19:24:18 +0000663 if (const LoadInst *LI = dyn_cast<LoadInst>(U)) {
664 SmallPtrSet<const PHINode*, 8> PHIs;
Chris Lattner2d2892e2007-09-13 16:30:19 +0000665 if (!AllUsesOfValueWillTrapIfNull(LI, PHIs))
Chris Lattner09a52722004-10-09 21:48:45 +0000666 return false;
Gabor Greif08355d62010-04-06 19:14:05 +0000667 } else if (isa<StoreInst>(U)) {
Chris Lattner09a52722004-10-09 21:48:45 +0000668 // Ignore stores to the global.
669 } else {
670 // We don't know or understand this user, bail out.
Gabor Greif08355d62010-04-06 19:14:05 +0000671 //cerr << "UNKNOWN USER OF GLOBAL!: " << *U;
Chris Lattner09a52722004-10-09 21:48:45 +0000672 return false;
673 }
Gabor Greif08355d62010-04-06 19:14:05 +0000674 }
Chris Lattner09a52722004-10-09 21:48:45 +0000675 return true;
676}
677
Chris Lattner46b5c642009-11-06 04:27:31 +0000678static bool OptimizeAwayTrappingUsesOfValue(Value *V, Constant *NewV) {
Chris Lattnere42eb312004-10-10 23:14:11 +0000679 bool Changed = false;
680 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ) {
681 Instruction *I = cast<Instruction>(*UI++);
682 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
683 LI->setOperand(0, NewV);
684 Changed = true;
685 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
686 if (SI->getOperand(1) == V) {
687 SI->setOperand(1, NewV);
688 Changed = true;
689 }
690 } else if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
Gabor Greif04397892010-04-06 18:45:08 +0000691 CallSite CS(I);
692 if (CS.getCalledValue() == V) {
Chris Lattnere42eb312004-10-10 23:14:11 +0000693 // Calling through the pointer! Turn into a direct call, but be careful
694 // that the pointer is not also being passed as an argument.
Gabor Greif04397892010-04-06 18:45:08 +0000695 CS.setCalledFunction(NewV);
Chris Lattnere42eb312004-10-10 23:14:11 +0000696 Changed = true;
697 bool PassedAsArg = false;
Gabor Greif04397892010-04-06 18:45:08 +0000698 for (unsigned i = 0, e = CS.arg_size(); i != e; ++i)
699 if (CS.getArgument(i) == V) {
Chris Lattnere42eb312004-10-10 23:14:11 +0000700 PassedAsArg = true;
Gabor Greif04397892010-04-06 18:45:08 +0000701 CS.setArgument(i, NewV);
Chris Lattnere42eb312004-10-10 23:14:11 +0000702 }
703
704 if (PassedAsArg) {
705 // Being passed as an argument also. Be careful to not invalidate UI!
706 UI = V->use_begin();
707 }
708 }
709 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
710 Changed |= OptimizeAwayTrappingUsesOfValue(CI,
Owen Anderson487375e2009-07-29 18:55:55 +0000711 ConstantExpr::getCast(CI->getOpcode(),
Chris Lattner46b5c642009-11-06 04:27:31 +0000712 NewV, CI->getType()));
Chris Lattnere42eb312004-10-10 23:14:11 +0000713 if (CI->use_empty()) {
714 Changed = true;
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000715 CI->eraseFromParent();
Chris Lattnere42eb312004-10-10 23:14:11 +0000716 }
717 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
718 // Should handle GEP here.
Chris Lattnerf96f4a82007-01-31 04:40:53 +0000719 SmallVector<Constant*, 8> Idxs;
720 Idxs.reserve(GEPI->getNumOperands()-1);
Gabor Greif3a9fba52008-05-29 01:59:18 +0000721 for (User::op_iterator i = GEPI->op_begin() + 1, e = GEPI->op_end();
722 i != e; ++i)
723 if (Constant *C = dyn_cast<Constant>(*i))
Chris Lattnerf96f4a82007-01-31 04:40:53 +0000724 Idxs.push_back(C);
Chris Lattnere42eb312004-10-10 23:14:11 +0000725 else
726 break;
Chris Lattnerf96f4a82007-01-31 04:40:53 +0000727 if (Idxs.size() == GEPI->getNumOperands()-1)
Chris Lattnere42eb312004-10-10 23:14:11 +0000728 Changed |= OptimizeAwayTrappingUsesOfValue(GEPI,
Jay Foaded8db7d2011-07-21 14:31:17 +0000729 ConstantExpr::getGetElementPtr(NewV, Idxs));
Chris Lattnere42eb312004-10-10 23:14:11 +0000730 if (GEPI->use_empty()) {
731 Changed = true;
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000732 GEPI->eraseFromParent();
Chris Lattnere42eb312004-10-10 23:14:11 +0000733 }
734 }
735 }
736
737 return Changed;
738}
739
740
741/// OptimizeAwayTrappingUsesOfLoads - The specified global has only one non-null
742/// value stored into it. If there are uses of the loaded value that would trap
743/// if the loaded value is dynamically null, then we know that they cannot be
744/// reachable with a null optimize away the load.
Nick Lewyckycf6aae62012-02-12 01:13:18 +0000745static bool OptimizeAwayTrappingUsesOfLoads(GlobalVariable *GV, Constant *LV,
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000746 DataLayout *TD,
Nick Lewyckycf6aae62012-02-12 01:13:18 +0000747 TargetLibraryInfo *TLI) {
Chris Lattnere42eb312004-10-10 23:14:11 +0000748 bool Changed = false;
749
Chris Lattner2538eb62009-01-14 00:12:58 +0000750 // Keep track of whether we are able to remove all the uses of the global
751 // other than the store that defines it.
752 bool AllNonStoreUsesGone = true;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000753
Chris Lattnere42eb312004-10-10 23:14:11 +0000754 // Replace all uses of loads with uses of uses of the stored value.
Chris Lattner2538eb62009-01-14 00:12:58 +0000755 for (Value::use_iterator GUI = GV->use_begin(), E = GV->use_end(); GUI != E;){
756 User *GlobalUser = *GUI++;
757 if (LoadInst *LI = dyn_cast<LoadInst>(GlobalUser)) {
Chris Lattner46b5c642009-11-06 04:27:31 +0000758 Changed |= OptimizeAwayTrappingUsesOfValue(LI, LV);
Chris Lattner2538eb62009-01-14 00:12:58 +0000759 // If we were able to delete all uses of the loads
760 if (LI->use_empty()) {
761 LI->eraseFromParent();
762 Changed = true;
763 } else {
764 AllNonStoreUsesGone = false;
765 }
766 } else if (isa<StoreInst>(GlobalUser)) {
767 // Ignore the store that stores "LV" to the global.
768 assert(GlobalUser->getOperand(1) == GV &&
769 "Must be storing *to* the global");
Chris Lattnere42eb312004-10-10 23:14:11 +0000770 } else {
Chris Lattner2538eb62009-01-14 00:12:58 +0000771 AllNonStoreUsesGone = false;
772
773 // If we get here we could have other crazy uses that are transitively
774 // loaded.
775 assert((isa<PHINode>(GlobalUser) || isa<SelectInst>(GlobalUser) ||
Benjamin Kramered843602012-09-28 10:01:27 +0000776 isa<ConstantExpr>(GlobalUser) || isa<CmpInst>(GlobalUser) ||
777 isa<BitCastInst>(GlobalUser) ||
778 isa<GetElementPtrInst>(GlobalUser)) &&
Chris Lattner1a1acc22011-05-22 07:15:13 +0000779 "Only expect load and stores!");
Chris Lattnere42eb312004-10-10 23:14:11 +0000780 }
Chris Lattner2538eb62009-01-14 00:12:58 +0000781 }
Chris Lattnere42eb312004-10-10 23:14:11 +0000782
783 if (Changed) {
David Greene44cb8ad2010-01-05 01:28:05 +0000784 DEBUG(dbgs() << "OPTIMIZED LOADS FROM STORED ONCE POINTER: " << *GV);
Chris Lattnere42eb312004-10-10 23:14:11 +0000785 ++NumGlobUses;
786 }
787
Chris Lattnere42eb312004-10-10 23:14:11 +0000788 // If we nuked all of the loads, then none of the stores are needed either,
789 // nor is the global.
Chris Lattner2538eb62009-01-14 00:12:58 +0000790 if (AllNonStoreUsesGone) {
Nick Lewyckyfaa9c3b02012-07-24 07:21:08 +0000791 if (isLeakCheckerRoot(GV)) {
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000792 Changed |= CleanupPointerRootUsers(GV, TLI);
Nick Lewyckyfaa9c3b02012-07-24 07:21:08 +0000793 } else {
794 Changed = true;
795 CleanupConstantGlobalUsers(GV, 0, TD, TLI);
796 }
Chris Lattnere42eb312004-10-10 23:14:11 +0000797 if (GV->use_empty()) {
Nick Lewyckyfaa9c3b02012-07-24 07:21:08 +0000798 DEBUG(dbgs() << " *** GLOBAL NOW DEAD!\n");
799 Changed = true;
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000800 GV->eraseFromParent();
Chris Lattnere42eb312004-10-10 23:14:11 +0000801 ++NumDeleted;
802 }
Chris Lattnere42eb312004-10-10 23:14:11 +0000803 }
804 return Changed;
805}
806
Chris Lattner004e2502004-10-11 05:54:41 +0000807/// ConstantPropUsersOf - Walk the use list of V, constant folding all of the
808/// instructions that are foldable.
Nick Lewyckycf6aae62012-02-12 01:13:18 +0000809static void ConstantPropUsersOf(Value *V,
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000810 DataLayout *TD, TargetLibraryInfo *TLI) {
Chris Lattner004e2502004-10-11 05:54:41 +0000811 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; )
812 if (Instruction *I = dyn_cast<Instruction>(*UI++))
Nick Lewyckycf6aae62012-02-12 01:13:18 +0000813 if (Constant *NewC = ConstantFoldInstruction(I, TD, TLI)) {
Chris Lattner004e2502004-10-11 05:54:41 +0000814 I->replaceAllUsesWith(NewC);
815
Chris Lattnerd6a44922005-02-01 01:23:31 +0000816 // Advance UI to the next non-I use to avoid invalidating it!
817 // Instructions could multiply use V.
818 while (UI != E && *UI == I)
Chris Lattner004e2502004-10-11 05:54:41 +0000819 ++UI;
Chris Lattnerd6a44922005-02-01 01:23:31 +0000820 I->eraseFromParent();
Chris Lattner004e2502004-10-11 05:54:41 +0000821 }
822}
823
824/// OptimizeGlobalAddressOfMalloc - This function takes the specified global
825/// variable, and transforms the program as if it always contained the result of
826/// the specified malloc. Because it is always the result of the specified
827/// malloc, there is no reason to actually DO the malloc. Instead, turn the
Chris Lattner3ede00b2006-11-30 17:32:29 +0000828/// malloc into a global, and any loads of GV as uses of the new global.
Chris Lattner004e2502004-10-11 05:54:41 +0000829static GlobalVariable *OptimizeGlobalAddressOfMalloc(GlobalVariable *GV,
Victor Hernandez5d034492009-09-18 22:35:49 +0000830 CallInst *CI,
Chris Lattner229907c2011-07-18 04:54:35 +0000831 Type *AllocTy,
Chris Lattner7939f792010-02-25 22:33:52 +0000832 ConstantInt *NElements,
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000833 DataLayout *TD,
Nick Lewyckycf6aae62012-02-12 01:13:18 +0000834 TargetLibraryInfo *TLI) {
Chris Lattner7939f792010-02-25 22:33:52 +0000835 DEBUG(errs() << "PROMOTING GLOBAL: " << *GV << " CALL = " << *CI << '\n');
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000836
Chris Lattner229907c2011-07-18 04:54:35 +0000837 Type *GlobalType;
Chris Lattner7939f792010-02-25 22:33:52 +0000838 if (NElements->getZExtValue() == 1)
839 GlobalType = AllocTy;
840 else
841 // If we have an array allocation, the global variable is of an array.
842 GlobalType = ArrayType::get(AllocTy, NElements->getZExtValue());
Victor Hernandez5d034492009-09-18 22:35:49 +0000843
844 // Create the new global variable. The contents of the malloc'd memory is
845 // undefined, so initialize with an undef value.
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000846 GlobalVariable *NewGV = new GlobalVariable(*GV->getParent(),
Chris Lattner65d3a0a2010-02-26 23:42:13 +0000847 GlobalType, false,
Chris Lattner7939f792010-02-25 22:33:52 +0000848 GlobalValue::InternalLinkage,
Chris Lattner65d3a0a2010-02-26 23:42:13 +0000849 UndefValue::get(GlobalType),
Victor Hernandez5d034492009-09-18 22:35:49 +0000850 GV->getName()+".body",
851 GV,
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000852 GV->getThreadLocalMode());
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000853
Chris Lattner7939f792010-02-25 22:33:52 +0000854 // If there are bitcast users of the malloc (which is typical, usually we have
855 // a malloc + bitcast) then replace them with uses of the new global. Update
856 // other users to use the global as well.
857 BitCastInst *TheBC = 0;
858 while (!CI->use_empty()) {
859 Instruction *User = cast<Instruction>(CI->use_back());
860 if (BitCastInst *BCI = dyn_cast<BitCastInst>(User)) {
861 if (BCI->getType() == NewGV->getType()) {
862 BCI->replaceAllUsesWith(NewGV);
863 BCI->eraseFromParent();
864 } else {
865 BCI->setOperand(0, NewGV);
866 }
867 } else {
868 if (TheBC == 0)
869 TheBC = new BitCastInst(NewGV, CI->getType(), "newgv", CI);
870 User->replaceUsesOfWith(CI, TheBC);
871 }
872 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000873
Victor Hernandez5d034492009-09-18 22:35:49 +0000874 Constant *RepValue = NewGV;
875 if (NewGV->getType() != GV->getType()->getElementType())
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000876 RepValue = ConstantExpr::getBitCast(RepValue,
Victor Hernandez5d034492009-09-18 22:35:49 +0000877 GV->getType()->getElementType());
878
879 // If there is a comparison against null, we will insert a global bool to
880 // keep track of whether the global was initialized yet or not.
881 GlobalVariable *InitBool =
Chris Lattner46b5c642009-11-06 04:27:31 +0000882 new GlobalVariable(Type::getInt1Ty(GV->getContext()), false,
Victor Hernandez5d034492009-09-18 22:35:49 +0000883 GlobalValue::InternalLinkage,
Chris Lattner46b5c642009-11-06 04:27:31 +0000884 ConstantInt::getFalse(GV->getContext()),
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000885 GV->getName()+".init", GV->getThreadLocalMode());
Victor Hernandez5d034492009-09-18 22:35:49 +0000886 bool InitBoolUsed = false;
887
888 // Loop over all uses of GV, processing them in turn.
Chris Lattner7939f792010-02-25 22:33:52 +0000889 while (!GV->use_empty()) {
890 if (StoreInst *SI = dyn_cast<StoreInst>(GV->use_back())) {
Victor Hernandez5d034492009-09-18 22:35:49 +0000891 // The global is initialized when the store to it occurs.
Nick Lewycky52da72b2012-02-05 19:56:38 +0000892 new StoreInst(ConstantInt::getTrue(GV->getContext()), InitBool, false, 0,
893 SI->getOrdering(), SI->getSynchScope(), SI);
Victor Hernandez5d034492009-09-18 22:35:49 +0000894 SI->eraseFromParent();
Chris Lattner7939f792010-02-25 22:33:52 +0000895 continue;
Victor Hernandez5d034492009-09-18 22:35:49 +0000896 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000897
Chris Lattner7939f792010-02-25 22:33:52 +0000898 LoadInst *LI = cast<LoadInst>(GV->use_back());
899 while (!LI->use_empty()) {
900 Use &LoadUse = LI->use_begin().getUse();
901 if (!isa<ICmpInst>(LoadUse.getUser())) {
902 LoadUse = RepValue;
903 continue;
904 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000905
Chris Lattner7939f792010-02-25 22:33:52 +0000906 ICmpInst *ICI = cast<ICmpInst>(LoadUse.getUser());
907 // Replace the cmp X, 0 with a use of the bool value.
Nick Lewycky52da72b2012-02-05 19:56:38 +0000908 // Sink the load to where the compare was, if atomic rules allow us to.
909 Value *LV = new LoadInst(InitBool, InitBool->getName()+".val", false, 0,
910 LI->getOrdering(), LI->getSynchScope(),
911 LI->isUnordered() ? (Instruction*)ICI : LI);
Chris Lattner7939f792010-02-25 22:33:52 +0000912 InitBoolUsed = true;
913 switch (ICI->getPredicate()) {
914 default: llvm_unreachable("Unknown ICmp Predicate!");
915 case ICmpInst::ICMP_ULT:
916 case ICmpInst::ICMP_SLT: // X < null -> always false
917 LV = ConstantInt::getFalse(GV->getContext());
918 break;
919 case ICmpInst::ICMP_ULE:
920 case ICmpInst::ICMP_SLE:
921 case ICmpInst::ICMP_EQ:
922 LV = BinaryOperator::CreateNot(LV, "notinit", ICI);
923 break;
924 case ICmpInst::ICMP_NE:
925 case ICmpInst::ICMP_UGE:
926 case ICmpInst::ICMP_SGE:
927 case ICmpInst::ICMP_UGT:
928 case ICmpInst::ICMP_SGT:
929 break; // no change.
930 }
931 ICI->replaceAllUsesWith(LV);
932 ICI->eraseFromParent();
933 }
934 LI->eraseFromParent();
935 }
Victor Hernandez5d034492009-09-18 22:35:49 +0000936
937 // If the initialization boolean was used, insert it, otherwise delete it.
938 if (!InitBoolUsed) {
939 while (!InitBool->use_empty()) // Delete initializations
Chris Lattner7939f792010-02-25 22:33:52 +0000940 cast<StoreInst>(InitBool->use_back())->eraseFromParent();
Victor Hernandez5d034492009-09-18 22:35:49 +0000941 delete InitBool;
942 } else
943 GV->getParent()->getGlobalList().insert(GV, InitBool);
944
Chris Lattner7939f792010-02-25 22:33:52 +0000945 // Now the GV is dead, nuke it and the malloc..
Victor Hernandez5d034492009-09-18 22:35:49 +0000946 GV->eraseFromParent();
Victor Hernandez5d034492009-09-18 22:35:49 +0000947 CI->eraseFromParent();
948
949 // To further other optimizations, loop over all users of NewGV and try to
950 // constant prop them. This will promote GEP instructions with constant
951 // indices into GEP constant-exprs, which will allow global-opt to hack on it.
Nick Lewyckycf6aae62012-02-12 01:13:18 +0000952 ConstantPropUsersOf(NewGV, TD, TLI);
Victor Hernandez5d034492009-09-18 22:35:49 +0000953 if (RepValue != NewGV)
Nick Lewyckycf6aae62012-02-12 01:13:18 +0000954 ConstantPropUsersOf(RepValue, TD, TLI);
Victor Hernandez5d034492009-09-18 22:35:49 +0000955
956 return NewGV;
957}
958
Chris Lattnerc0677c02004-12-02 07:11:07 +0000959/// ValueIsOnlyUsedLocallyOrStoredToOneGlobal - Scan the use-list of V checking
960/// to make sure that there are no complex uses of V. We permit simple things
961/// like dereferencing the pointer, but not storing through the address, unless
962/// it is to the specified global.
Gabor Greifa21bc0f2010-04-06 18:58:22 +0000963static bool ValueIsOnlyUsedLocallyOrStoredToOneGlobal(const Instruction *V,
964 const GlobalVariable *GV,
Gabor Greif08355d62010-04-06 19:14:05 +0000965 SmallPtrSet<const PHINode*, 8> &PHIs) {
Gabor Greifa21bc0f2010-04-06 18:58:22 +0000966 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end();
Gabor Greif08355d62010-04-06 19:14:05 +0000967 UI != E; ++UI) {
Gabor Greifa21bc0f2010-04-06 18:58:22 +0000968 const Instruction *Inst = cast<Instruction>(*UI);
Gabor Greif08355d62010-04-06 19:14:05 +0000969
Chris Lattnerf0eb5682008-12-15 21:08:54 +0000970 if (isa<LoadInst>(Inst) || isa<CmpInst>(Inst)) {
971 continue; // Fine, ignore.
972 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000973
Gabor Greifa21bc0f2010-04-06 18:58:22 +0000974 if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
Chris Lattnerc0677c02004-12-02 07:11:07 +0000975 if (SI->getOperand(0) == V && SI->getOperand(1) != GV)
976 return false; // Storing the pointer itself... bad.
Chris Lattnerf0eb5682008-12-15 21:08:54 +0000977 continue; // Otherwise, storing through it, or storing into GV... fine.
978 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000979
Chris Lattnerb9801ff2010-04-10 18:19:22 +0000980 // Must index into the array and into the struct.
981 if (isa<GetElementPtrInst>(Inst) && Inst->getNumOperands() >= 3) {
Chris Lattnerf0eb5682008-12-15 21:08:54 +0000982 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(Inst, GV, PHIs))
Chris Lattnerc0677c02004-12-02 07:11:07 +0000983 return false;
Chris Lattnerf0eb5682008-12-15 21:08:54 +0000984 continue;
985 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000986
Gabor Greifa21bc0f2010-04-06 18:58:22 +0000987 if (const PHINode *PN = dyn_cast<PHINode>(Inst)) {
Chris Lattner6eed0e72007-09-13 16:37:20 +0000988 // PHIs are ok if all uses are ok. Don't infinitely recurse through PHI
989 // cycles.
990 if (PHIs.insert(PN))
Chris Lattner5d13fb532007-09-14 03:41:21 +0000991 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(PN, GV, PHIs))
992 return false;
Chris Lattnerf0eb5682008-12-15 21:08:54 +0000993 continue;
Chris Lattnerc0677c02004-12-02 07:11:07 +0000994 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000995
Gabor Greifa21bc0f2010-04-06 18:58:22 +0000996 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Inst)) {
Chris Lattnerf0eb5682008-12-15 21:08:54 +0000997 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(BCI, GV, PHIs))
998 return false;
999 continue;
1000 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001001
Chris Lattnerf0eb5682008-12-15 21:08:54 +00001002 return false;
1003 }
Chris Lattnerc0677c02004-12-02 07:11:07 +00001004 return true;
Chris Lattnerc0677c02004-12-02 07:11:07 +00001005}
1006
Chris Lattner24d3d422006-09-30 23:32:09 +00001007/// ReplaceUsesOfMallocWithGlobal - The Alloc pointer is stored into GV
1008/// somewhere. Transform all uses of the allocation into loads from the
1009/// global and uses of the resultant pointer. Further, delete the store into
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001010/// GV. This assumes that these value pass the
Chris Lattner24d3d422006-09-30 23:32:09 +00001011/// 'ValueIsOnlyUsedLocallyOrStoredToOneGlobal' predicate.
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001012static void ReplaceUsesOfMallocWithGlobal(Instruction *Alloc,
Chris Lattner24d3d422006-09-30 23:32:09 +00001013 GlobalVariable *GV) {
1014 while (!Alloc->use_empty()) {
Chris Lattnerba98f892007-09-13 18:00:31 +00001015 Instruction *U = cast<Instruction>(*Alloc->use_begin());
1016 Instruction *InsertPt = U;
Chris Lattner24d3d422006-09-30 23:32:09 +00001017 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
1018 // If this is the store of the allocation into the global, remove it.
1019 if (SI->getOperand(1) == GV) {
1020 SI->eraseFromParent();
1021 continue;
1022 }
Chris Lattnerba98f892007-09-13 18:00:31 +00001023 } else if (PHINode *PN = dyn_cast<PHINode>(U)) {
1024 // Insert the load in the corresponding predecessor, not right before the
1025 // PHI.
Gabor Greifeb61fcf2009-01-23 19:40:15 +00001026 InsertPt = PN->getIncomingBlock(Alloc->use_begin())->getTerminator();
Chris Lattner49e3bdc2008-12-15 21:44:34 +00001027 } else if (isa<BitCastInst>(U)) {
1028 // Must be bitcast between the malloc and store to initialize the global.
1029 ReplaceUsesOfMallocWithGlobal(U, GV);
1030 U->eraseFromParent();
1031 continue;
1032 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
1033 // If this is a "GEP bitcast" and the user is a store to the global, then
1034 // just process it as a bitcast.
1035 if (GEPI->hasAllZeroIndices() && GEPI->hasOneUse())
1036 if (StoreInst *SI = dyn_cast<StoreInst>(GEPI->use_back()))
1037 if (SI->getOperand(1) == GV) {
1038 // Must be bitcast GEP between the malloc and store to initialize
1039 // the global.
1040 ReplaceUsesOfMallocWithGlobal(GEPI, GV);
1041 GEPI->eraseFromParent();
1042 continue;
1043 }
Chris Lattner24d3d422006-09-30 23:32:09 +00001044 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001045
Chris Lattner24d3d422006-09-30 23:32:09 +00001046 // Insert a load from the global, and use it instead of the malloc.
Chris Lattnerba98f892007-09-13 18:00:31 +00001047 Value *NL = new LoadInst(GV, GV->getName()+".val", InsertPt);
Chris Lattner24d3d422006-09-30 23:32:09 +00001048 U->replaceUsesOfWith(Alloc, NL);
1049 }
1050}
1051
Chris Lattner56b55382008-12-16 21:24:51 +00001052/// LoadUsesSimpleEnoughForHeapSRA - Verify that all uses of V (a load, or a phi
1053/// of a load) are simple enough to perform heap SRA on. This permits GEP's
1054/// that index through the array and struct field, icmps of null, and PHIs.
Gabor Greif5d5db532010-04-01 08:21:08 +00001055static bool LoadUsesSimpleEnoughForHeapSRA(const Value *V,
Gabor Greif08d85da2010-04-07 18:59:26 +00001056 SmallPtrSet<const PHINode*, 32> &LoadUsingPHIs,
1057 SmallPtrSet<const PHINode*, 32> &LoadUsingPHIsPerLoad) {
Chris Lattner56b55382008-12-16 21:24:51 +00001058 // We permit two users of the load: setcc comparing against the null
1059 // pointer, and a getelementptr of a specific form.
Gabor Greif08d85da2010-04-07 18:59:26 +00001060 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;
1061 ++UI) {
Gabor Greif5d5db532010-04-01 08:21:08 +00001062 const Instruction *User = cast<Instruction>(*UI);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001063
Chris Lattner56b55382008-12-16 21:24:51 +00001064 // Comparison against null is ok.
Gabor Greif5d5db532010-04-01 08:21:08 +00001065 if (const ICmpInst *ICI = dyn_cast<ICmpInst>(User)) {
Chris Lattner56b55382008-12-16 21:24:51 +00001066 if (!isa<ConstantPointerNull>(ICI->getOperand(1)))
1067 return false;
1068 continue;
1069 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001070
Chris Lattner56b55382008-12-16 21:24:51 +00001071 // getelementptr is also ok, but only a simple form.
Gabor Greif5d5db532010-04-01 08:21:08 +00001072 if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
Chris Lattner56b55382008-12-16 21:24:51 +00001073 // Must index into the array and into the struct.
1074 if (GEPI->getNumOperands() < 3)
1075 return false;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001076
Chris Lattner56b55382008-12-16 21:24:51 +00001077 // Otherwise the GEP is ok.
1078 continue;
1079 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001080
Gabor Greif5d5db532010-04-01 08:21:08 +00001081 if (const PHINode *PN = dyn_cast<PHINode>(User)) {
Evan Cheng83689442009-06-02 00:56:07 +00001082 if (!LoadUsingPHIsPerLoad.insert(PN))
1083 // This means some phi nodes are dependent on each other.
1084 // Avoid infinite looping!
1085 return false;
1086 if (!LoadUsingPHIs.insert(PN))
1087 // If we have already analyzed this PHI, then it is safe.
Chris Lattner56b55382008-12-16 21:24:51 +00001088 continue;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001089
Chris Lattner222ef4c2008-12-17 05:28:49 +00001090 // Make sure all uses of the PHI are simple enough to transform.
Evan Cheng83689442009-06-02 00:56:07 +00001091 if (!LoadUsesSimpleEnoughForHeapSRA(PN,
1092 LoadUsingPHIs, LoadUsingPHIsPerLoad))
Chris Lattner56b55382008-12-16 21:24:51 +00001093 return false;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001094
Chris Lattner56b55382008-12-16 21:24:51 +00001095 continue;
Chris Lattner24d3d422006-09-30 23:32:09 +00001096 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001097
Chris Lattner56b55382008-12-16 21:24:51 +00001098 // Otherwise we don't know what this is, not ok.
1099 return false;
1100 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001101
Chris Lattner56b55382008-12-16 21:24:51 +00001102 return true;
1103}
1104
1105
1106/// AllGlobalLoadUsesSimpleEnoughForHeapSRA - If all users of values loaded from
1107/// GV are simple enough to perform HeapSRA, return true.
Gabor Greif5d5db532010-04-01 08:21:08 +00001108static bool AllGlobalLoadUsesSimpleEnoughForHeapSRA(const GlobalVariable *GV,
Victor Hernandez5d034492009-09-18 22:35:49 +00001109 Instruction *StoredVal) {
Gabor Greif5d5db532010-04-01 08:21:08 +00001110 SmallPtrSet<const PHINode*, 32> LoadUsingPHIs;
1111 SmallPtrSet<const PHINode*, 32> LoadUsingPHIsPerLoad;
Gabor Greif08d85da2010-04-07 18:59:26 +00001112 for (Value::const_use_iterator UI = GV->use_begin(), E = GV->use_end();
1113 UI != E; ++UI)
Gabor Greif5d5db532010-04-01 08:21:08 +00001114 if (const LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
Evan Cheng83689442009-06-02 00:56:07 +00001115 if (!LoadUsesSimpleEnoughForHeapSRA(LI, LoadUsingPHIs,
1116 LoadUsingPHIsPerLoad))
Chris Lattner56b55382008-12-16 21:24:51 +00001117 return false;
Evan Cheng83689442009-06-02 00:56:07 +00001118 LoadUsingPHIsPerLoad.clear();
1119 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001120
Chris Lattner222ef4c2008-12-17 05:28:49 +00001121 // If we reach here, we know that all uses of the loads and transitive uses
1122 // (through PHI nodes) are simple enough to transform. However, we don't know
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001123 // that all inputs the to the PHI nodes are in the same equivalence sets.
Chris Lattner222ef4c2008-12-17 05:28:49 +00001124 // Check to verify that all operands of the PHIs are either PHIS that can be
1125 // transformed, loads from GV, or MI itself.
Gabor Greif08d85da2010-04-07 18:59:26 +00001126 for (SmallPtrSet<const PHINode*, 32>::const_iterator I = LoadUsingPHIs.begin()
1127 , E = LoadUsingPHIs.end(); I != E; ++I) {
Gabor Greif5d5db532010-04-01 08:21:08 +00001128 const PHINode *PN = *I;
Chris Lattner222ef4c2008-12-17 05:28:49 +00001129 for (unsigned op = 0, e = PN->getNumIncomingValues(); op != e; ++op) {
1130 Value *InVal = PN->getIncomingValue(op);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001131
Chris Lattner222ef4c2008-12-17 05:28:49 +00001132 // PHI of the stored value itself is ok.
Victor Hernandez5d034492009-09-18 22:35:49 +00001133 if (InVal == StoredVal) continue;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001134
Gabor Greif5d5db532010-04-01 08:21:08 +00001135 if (const PHINode *InPN = dyn_cast<PHINode>(InVal)) {
Chris Lattner222ef4c2008-12-17 05:28:49 +00001136 // One of the PHIs in our set is (optimistically) ok.
1137 if (LoadUsingPHIs.count(InPN))
1138 continue;
1139 return false;
1140 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001141
Chris Lattner222ef4c2008-12-17 05:28:49 +00001142 // Load from GV is ok.
Gabor Greif5d5db532010-04-01 08:21:08 +00001143 if (const LoadInst *LI = dyn_cast<LoadInst>(InVal))
Chris Lattner222ef4c2008-12-17 05:28:49 +00001144 if (LI->getOperand(0) == GV)
1145 continue;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001146
Chris Lattner222ef4c2008-12-17 05:28:49 +00001147 // UNDEF? NULL?
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001148
Chris Lattner222ef4c2008-12-17 05:28:49 +00001149 // Anything else is rejected.
1150 return false;
1151 }
1152 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001153
Chris Lattner24d3d422006-09-30 23:32:09 +00001154 return true;
1155}
1156
Chris Lattner222ef4c2008-12-17 05:28:49 +00001157static Value *GetHeapSROAValue(Value *V, unsigned FieldNo,
1158 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Chris Lattner46b5c642009-11-06 04:27:31 +00001159 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
Chris Lattner222ef4c2008-12-17 05:28:49 +00001160 std::vector<Value*> &FieldVals = InsertedScalarizedValues[V];
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001161
Chris Lattner222ef4c2008-12-17 05:28:49 +00001162 if (FieldNo >= FieldVals.size())
1163 FieldVals.resize(FieldNo+1);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001164
Chris Lattner222ef4c2008-12-17 05:28:49 +00001165 // If we already have this value, just reuse the previously scalarized
1166 // version.
1167 if (Value *FieldVal = FieldVals[FieldNo])
1168 return FieldVal;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001169
Chris Lattner222ef4c2008-12-17 05:28:49 +00001170 // Depending on what instruction this is, we have several cases.
1171 Value *Result;
1172 if (LoadInst *LI = dyn_cast<LoadInst>(V)) {
1173 // This is a scalarized version of the load from the global. Just create
1174 // a new Load of the scalarized global.
1175 Result = new LoadInst(GetHeapSROAValue(LI->getOperand(0), FieldNo,
1176 InsertedScalarizedValues,
Chris Lattner46b5c642009-11-06 04:27:31 +00001177 PHIsToRewrite),
Daniel Dunbar132f7832009-07-30 17:37:43 +00001178 LI->getName()+".f"+Twine(FieldNo), LI);
Chris Lattner222ef4c2008-12-17 05:28:49 +00001179 } else if (PHINode *PN = dyn_cast<PHINode>(V)) {
1180 // PN's type is pointer to struct. Make a new PHI of pointer to struct
1181 // field.
Matt Arsenault404c60a2013-10-21 19:43:56 +00001182 StructType *ST = cast<StructType>(PN->getType()->getPointerElementType());
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001183
Jay Foade0938d82011-03-30 11:19:20 +00001184 PHINode *NewPN =
Owen Anderson4056ca92009-07-29 22:17:13 +00001185 PHINode::Create(PointerType::getUnqual(ST->getElementType(FieldNo)),
Jay Foad52131342011-03-30 11:28:46 +00001186 PN->getNumIncomingValues(),
Daniel Dunbar132f7832009-07-30 17:37:43 +00001187 PN->getName()+".f"+Twine(FieldNo), PN);
Jay Foade0938d82011-03-30 11:19:20 +00001188 Result = NewPN;
Chris Lattner222ef4c2008-12-17 05:28:49 +00001189 PHIsToRewrite.push_back(std::make_pair(PN, FieldNo));
1190 } else {
Torok Edwinfbcc6632009-07-14 16:55:14 +00001191 llvm_unreachable("Unknown usable value");
Chris Lattner222ef4c2008-12-17 05:28:49 +00001192 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001193
Chris Lattner222ef4c2008-12-17 05:28:49 +00001194 return FieldVals[FieldNo] = Result;
Chris Lattnerba98f892007-09-13 18:00:31 +00001195}
1196
Chris Lattnerf315d4f2007-09-13 17:29:05 +00001197/// RewriteHeapSROALoadUser - Given a load instruction and a value derived from
1198/// the load, rewrite the derived value to use the HeapSRoA'd load.
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001199static void RewriteHeapSROALoadUser(Instruction *LoadUser,
Chris Lattner222ef4c2008-12-17 05:28:49 +00001200 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Chris Lattner46b5c642009-11-06 04:27:31 +00001201 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
Chris Lattnerf315d4f2007-09-13 17:29:05 +00001202 // If this is a comparison against null, handle it.
1203 if (ICmpInst *SCI = dyn_cast<ICmpInst>(LoadUser)) {
1204 assert(isa<ConstantPointerNull>(SCI->getOperand(1)));
1205 // If we have a setcc of the loaded pointer, we can use a setcc of any
1206 // field.
Chris Lattner222ef4c2008-12-17 05:28:49 +00001207 Value *NPtr = GetHeapSROAValue(SCI->getOperand(0), 0,
Chris Lattner46b5c642009-11-06 04:27:31 +00001208 InsertedScalarizedValues, PHIsToRewrite);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001209
Owen Anderson1e5f00e2009-07-09 23:48:35 +00001210 Value *New = new ICmpInst(SCI, SCI->getPredicate(), NPtr,
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001211 Constant::getNullValue(NPtr->getType()),
Owen Anderson1e5f00e2009-07-09 23:48:35 +00001212 SCI->getName());
Chris Lattnerf315d4f2007-09-13 17:29:05 +00001213 SCI->replaceAllUsesWith(New);
1214 SCI->eraseFromParent();
1215 return;
1216 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001217
Chris Lattner222ef4c2008-12-17 05:28:49 +00001218 // Handle 'getelementptr Ptr, Idx, i32 FieldNo ...'
Chris Lattnerba98f892007-09-13 18:00:31 +00001219 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(LoadUser)) {
1220 assert(GEPI->getNumOperands() >= 3 && isa<ConstantInt>(GEPI->getOperand(2))
1221 && "Unexpected GEPI!");
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001222
Chris Lattnerba98f892007-09-13 18:00:31 +00001223 // Load the pointer for this field.
1224 unsigned FieldNo = cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue();
Chris Lattner222ef4c2008-12-17 05:28:49 +00001225 Value *NewPtr = GetHeapSROAValue(GEPI->getOperand(0), FieldNo,
Chris Lattner46b5c642009-11-06 04:27:31 +00001226 InsertedScalarizedValues, PHIsToRewrite);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001227
Chris Lattnerba98f892007-09-13 18:00:31 +00001228 // Create the new GEP idx vector.
1229 SmallVector<Value*, 8> GEPIdx;
1230 GEPIdx.push_back(GEPI->getOperand(1));
1231 GEPIdx.append(GEPI->op_begin()+3, GEPI->op_end());
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001232
Jay Foadd1b78492011-07-25 09:48:08 +00001233 Value *NGEPI = GetElementPtrInst::Create(NewPtr, GEPIdx,
Gabor Greife9ecc682008-04-06 20:25:17 +00001234 GEPI->getName(), GEPI);
Chris Lattnerba98f892007-09-13 18:00:31 +00001235 GEPI->replaceAllUsesWith(NGEPI);
1236 GEPI->eraseFromParent();
1237 return;
1238 }
Chris Lattner011f91b2007-09-13 21:31:36 +00001239
Chris Lattner222ef4c2008-12-17 05:28:49 +00001240 // Recursively transform the users of PHI nodes. This will lazily create the
1241 // PHIs that are needed for individual elements. Keep track of what PHIs we
1242 // see in InsertedScalarizedValues so that we don't get infinite loops (very
1243 // antisocial). If the PHI is already in InsertedScalarizedValues, it has
1244 // already been seen first by another load, so its uses have already been
1245 // processed.
1246 PHINode *PN = cast<PHINode>(LoadUser);
Chris Lattner5cf753c2011-07-21 06:21:31 +00001247 if (!InsertedScalarizedValues.insert(std::make_pair(PN,
1248 std::vector<Value*>())).second)
1249 return;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001250
Chris Lattner222ef4c2008-12-17 05:28:49 +00001251 // If this is the first time we've seen this PHI, recursively process all
1252 // users.
Chris Lattner0cdf5232008-12-17 05:42:08 +00001253 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end(); UI != E; ) {
1254 Instruction *User = cast<Instruction>(*UI++);
Chris Lattner46b5c642009-11-06 04:27:31 +00001255 RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite);
Chris Lattner0cdf5232008-12-17 05:42:08 +00001256 }
Chris Lattnerf315d4f2007-09-13 17:29:05 +00001257}
1258
Chris Lattner24d3d422006-09-30 23:32:09 +00001259/// RewriteUsesOfLoadForHeapSRoA - We are performing Heap SRoA on a global. Ptr
1260/// is a value loaded from the global. Eliminate all uses of Ptr, making them
1261/// use FieldGlobals instead. All uses of loaded values satisfy
Chris Lattner56b55382008-12-16 21:24:51 +00001262/// AllGlobalLoadUsesSimpleEnoughForHeapSRA.
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001263static void RewriteUsesOfLoadForHeapSRoA(LoadInst *Load,
Chris Lattner222ef4c2008-12-17 05:28:49 +00001264 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Chris Lattner46b5c642009-11-06 04:27:31 +00001265 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
Chris Lattner222ef4c2008-12-17 05:28:49 +00001266 for (Value::use_iterator UI = Load->use_begin(), E = Load->use_end();
Chris Lattner0cdf5232008-12-17 05:42:08 +00001267 UI != E; ) {
1268 Instruction *User = cast<Instruction>(*UI++);
Chris Lattner46b5c642009-11-06 04:27:31 +00001269 RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite);
Chris Lattner0cdf5232008-12-17 05:42:08 +00001270 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001271
Chris Lattner222ef4c2008-12-17 05:28:49 +00001272 if (Load->use_empty()) {
1273 Load->eraseFromParent();
1274 InsertedScalarizedValues.erase(Load);
1275 }
Chris Lattner24d3d422006-09-30 23:32:09 +00001276}
1277
Victor Hernandez5d034492009-09-18 22:35:49 +00001278/// PerformHeapAllocSRoA - CI is an allocation of an array of structures. Break
1279/// it up into multiple allocations of arrays of the fields.
Victor Hernandezf3db9152009-11-07 00:16:28 +00001280static GlobalVariable *PerformHeapAllocSRoA(GlobalVariable *GV, CallInst *CI,
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001281 Value *NElems, DataLayout *TD,
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00001282 const TargetLibraryInfo *TLI) {
David Greene44cb8ad2010-01-05 01:28:05 +00001283 DEBUG(dbgs() << "SROA HEAP ALLOC: " << *GV << " MALLOC = " << *CI << '\n');
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00001284 Type *MAT = getMallocAllocatedType(CI, TLI);
Chris Lattner229907c2011-07-18 04:54:35 +00001285 StructType *STy = cast<StructType>(MAT);
Victor Hernandez5d034492009-09-18 22:35:49 +00001286
1287 // There is guaranteed to be at least one use of the malloc (storing
1288 // it into GV). If there are other uses, change them to be uses of
1289 // the global to simplify later code. This also deletes the store
1290 // into GV.
Victor Hernandezf3db9152009-11-07 00:16:28 +00001291 ReplaceUsesOfMallocWithGlobal(CI, GV);
1292
Victor Hernandez5d034492009-09-18 22:35:49 +00001293 // Okay, at this point, there are no users of the malloc. Insert N
1294 // new mallocs at the same place as CI, and N globals.
1295 std::vector<Value*> FieldGlobals;
1296 std::vector<Value*> FieldMallocs;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001297
Victor Hernandez5d034492009-09-18 22:35:49 +00001298 for (unsigned FieldNo = 0, e = STy->getNumElements(); FieldNo != e;++FieldNo){
Chris Lattner229907c2011-07-18 04:54:35 +00001299 Type *FieldTy = STy->getElementType(FieldNo);
1300 PointerType *PFieldTy = PointerType::getUnqual(FieldTy);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001301
Victor Hernandez5d034492009-09-18 22:35:49 +00001302 GlobalVariable *NGV =
1303 new GlobalVariable(*GV->getParent(),
1304 PFieldTy, false, GlobalValue::InternalLinkage,
1305 Constant::getNullValue(PFieldTy),
1306 GV->getName() + ".f" + Twine(FieldNo), GV,
Hans Wennborgcbe34b42012-06-23 11:37:03 +00001307 GV->getThreadLocalMode());
Victor Hernandez5d034492009-09-18 22:35:49 +00001308 FieldGlobals.push_back(NGV);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001309
Victor Hernandezf3db9152009-11-07 00:16:28 +00001310 unsigned TypeSize = TD->getTypeAllocSize(FieldTy);
Chris Lattner229907c2011-07-18 04:54:35 +00001311 if (StructType *ST = dyn_cast<StructType>(FieldTy))
Victor Hernandezf3db9152009-11-07 00:16:28 +00001312 TypeSize = TD->getStructLayout(ST)->getSizeInBytes();
Matt Arsenaultd3471e92013-09-11 07:29:40 +00001313 Type *IntPtrTy = TD->getIntPtrType(CI->getType());
Victor Hernandezf3db9152009-11-07 00:16:28 +00001314 Value *NMI = CallInst::CreateMalloc(CI, IntPtrTy, FieldTy,
1315 ConstantInt::get(IntPtrTy, TypeSize),
Chris Lattner601e390a2010-07-12 00:57:28 +00001316 NElems, 0,
Victor Hernandezf3db9152009-11-07 00:16:28 +00001317 CI->getName() + ".f" + Twine(FieldNo));
Chris Lattner0521c092010-02-26 18:23:13 +00001318 FieldMallocs.push_back(NMI);
Victor Hernandezf3db9152009-11-07 00:16:28 +00001319 new StoreInst(NMI, NGV, CI);
Victor Hernandez5d034492009-09-18 22:35:49 +00001320 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001321
Victor Hernandez5d034492009-09-18 22:35:49 +00001322 // The tricky aspect of this transformation is handling the case when malloc
1323 // fails. In the original code, malloc failing would set the result pointer
1324 // of malloc to null. In this case, some mallocs could succeed and others
1325 // could fail. As such, we emit code that looks like this:
1326 // F0 = malloc(field0)
1327 // F1 = malloc(field1)
1328 // F2 = malloc(field2)
1329 // if (F0 == 0 || F1 == 0 || F2 == 0) {
1330 // if (F0) { free(F0); F0 = 0; }
1331 // if (F1) { free(F1); F1 = 0; }
1332 // if (F2) { free(F2); F2 = 0; }
1333 // }
Victor Hernandezfcc77b12009-11-10 08:32:25 +00001334 // The malloc can also fail if its argument is too large.
Gabor Greif218f5542010-06-24 14:42:01 +00001335 Constant *ConstantZero = ConstantInt::get(CI->getArgOperand(0)->getType(), 0);
1336 Value *RunningOr = new ICmpInst(CI, ICmpInst::ICMP_SLT, CI->getArgOperand(0),
Victor Hernandezfcc77b12009-11-10 08:32:25 +00001337 ConstantZero, "isneg");
Victor Hernandez5d034492009-09-18 22:35:49 +00001338 for (unsigned i = 0, e = FieldMallocs.size(); i != e; ++i) {
Victor Hernandezf3db9152009-11-07 00:16:28 +00001339 Value *Cond = new ICmpInst(CI, ICmpInst::ICMP_EQ, FieldMallocs[i],
1340 Constant::getNullValue(FieldMallocs[i]->getType()),
1341 "isnull");
Victor Hernandezfcc77b12009-11-10 08:32:25 +00001342 RunningOr = BinaryOperator::CreateOr(RunningOr, Cond, "tmp", CI);
Victor Hernandez5d034492009-09-18 22:35:49 +00001343 }
1344
1345 // Split the basic block at the old malloc.
Victor Hernandezf3db9152009-11-07 00:16:28 +00001346 BasicBlock *OrigBB = CI->getParent();
1347 BasicBlock *ContBB = OrigBB->splitBasicBlock(CI, "malloc_cont");
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001348
Victor Hernandez5d034492009-09-18 22:35:49 +00001349 // Create the block to check the first condition. Put all these blocks at the
1350 // end of the function as they are unlikely to be executed.
Chris Lattner46b5c642009-11-06 04:27:31 +00001351 BasicBlock *NullPtrBlock = BasicBlock::Create(OrigBB->getContext(),
1352 "malloc_ret_null",
Victor Hernandez5d034492009-09-18 22:35:49 +00001353 OrigBB->getParent());
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001354
Victor Hernandez5d034492009-09-18 22:35:49 +00001355 // Remove the uncond branch from OrigBB to ContBB, turning it into a cond
1356 // branch on RunningOr.
1357 OrigBB->getTerminator()->eraseFromParent();
1358 BranchInst::Create(NullPtrBlock, ContBB, RunningOr, OrigBB);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001359
Victor Hernandez5d034492009-09-18 22:35:49 +00001360 // Within the NullPtrBlock, we need to emit a comparison and branch for each
1361 // pointer, because some may be null while others are not.
1362 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
1363 Value *GVVal = new LoadInst(FieldGlobals[i], "tmp", NullPtrBlock);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001364 Value *Cmp = new ICmpInst(*NullPtrBlock, ICmpInst::ICMP_NE, GVVal,
Benjamin Kramer547b6c52011-09-27 20:39:19 +00001365 Constant::getNullValue(GVVal->getType()));
Chris Lattner46b5c642009-11-06 04:27:31 +00001366 BasicBlock *FreeBlock = BasicBlock::Create(Cmp->getContext(), "free_it",
Victor Hernandez5d034492009-09-18 22:35:49 +00001367 OrigBB->getParent());
Chris Lattner46b5c642009-11-06 04:27:31 +00001368 BasicBlock *NextBlock = BasicBlock::Create(Cmp->getContext(), "next",
Victor Hernandez5d034492009-09-18 22:35:49 +00001369 OrigBB->getParent());
Victor Hernandeze2971492009-10-24 04:23:03 +00001370 Instruction *BI = BranchInst::Create(FreeBlock, NextBlock,
1371 Cmp, NullPtrBlock);
Victor Hernandez5d034492009-09-18 22:35:49 +00001372
1373 // Fill in FreeBlock.
Victor Hernandeze2971492009-10-24 04:23:03 +00001374 CallInst::CreateFree(GVVal, BI);
Victor Hernandez5d034492009-09-18 22:35:49 +00001375 new StoreInst(Constant::getNullValue(GVVal->getType()), FieldGlobals[i],
1376 FreeBlock);
1377 BranchInst::Create(NextBlock, FreeBlock);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001378
Victor Hernandez5d034492009-09-18 22:35:49 +00001379 NullPtrBlock = NextBlock;
1380 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001381
Victor Hernandez5d034492009-09-18 22:35:49 +00001382 BranchInst::Create(ContBB, NullPtrBlock);
Victor Hernandezf3db9152009-11-07 00:16:28 +00001383
1384 // CI is no longer needed, remove it.
Victor Hernandez5d034492009-09-18 22:35:49 +00001385 CI->eraseFromParent();
1386
1387 /// InsertedScalarizedLoads - As we process loads, if we can't immediately
1388 /// update all uses of the load, keep track of what scalarized loads are
1389 /// inserted for a given load.
1390 DenseMap<Value*, std::vector<Value*> > InsertedScalarizedValues;
1391 InsertedScalarizedValues[GV] = FieldGlobals;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001392
Victor Hernandez5d034492009-09-18 22:35:49 +00001393 std::vector<std::pair<PHINode*, unsigned> > PHIsToRewrite;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001394
Victor Hernandez5d034492009-09-18 22:35:49 +00001395 // Okay, the malloc site is completely handled. All of the uses of GV are now
1396 // loads, and all uses of those loads are simple. Rewrite them to use loads
1397 // of the per-field globals instead.
1398 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI != E;) {
1399 Instruction *User = cast<Instruction>(*UI++);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001400
Victor Hernandez5d034492009-09-18 22:35:49 +00001401 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Chris Lattner46b5c642009-11-06 04:27:31 +00001402 RewriteUsesOfLoadForHeapSRoA(LI, InsertedScalarizedValues, PHIsToRewrite);
Victor Hernandez5d034492009-09-18 22:35:49 +00001403 continue;
1404 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001405
Victor Hernandez5d034492009-09-18 22:35:49 +00001406 // Must be a store of null.
1407 StoreInst *SI = cast<StoreInst>(User);
1408 assert(isa<ConstantPointerNull>(SI->getOperand(0)) &&
1409 "Unexpected heap-sra user!");
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001410
Victor Hernandez5d034492009-09-18 22:35:49 +00001411 // Insert a store of null into each global.
1412 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
Chris Lattner229907c2011-07-18 04:54:35 +00001413 PointerType *PT = cast<PointerType>(FieldGlobals[i]->getType());
Victor Hernandez5d034492009-09-18 22:35:49 +00001414 Constant *Null = Constant::getNullValue(PT->getElementType());
1415 new StoreInst(Null, FieldGlobals[i], SI);
1416 }
1417 // Erase the original store.
1418 SI->eraseFromParent();
1419 }
1420
1421 // While we have PHIs that are interesting to rewrite, do it.
1422 while (!PHIsToRewrite.empty()) {
1423 PHINode *PN = PHIsToRewrite.back().first;
1424 unsigned FieldNo = PHIsToRewrite.back().second;
1425 PHIsToRewrite.pop_back();
1426 PHINode *FieldPN = cast<PHINode>(InsertedScalarizedValues[PN][FieldNo]);
1427 assert(FieldPN->getNumIncomingValues() == 0 &&"Already processed this phi");
1428
1429 // Add all the incoming values. This can materialize more phis.
1430 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1431 Value *InVal = PN->getIncomingValue(i);
1432 InVal = GetHeapSROAValue(InVal, FieldNo, InsertedScalarizedValues,
Chris Lattner46b5c642009-11-06 04:27:31 +00001433 PHIsToRewrite);
Victor Hernandez5d034492009-09-18 22:35:49 +00001434 FieldPN->addIncoming(InVal, PN->getIncomingBlock(i));
1435 }
1436 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001437
Victor Hernandez5d034492009-09-18 22:35:49 +00001438 // Drop all inter-phi links and any loads that made it this far.
1439 for (DenseMap<Value*, std::vector<Value*> >::iterator
1440 I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
1441 I != E; ++I) {
1442 if (PHINode *PN = dyn_cast<PHINode>(I->first))
1443 PN->dropAllReferences();
1444 else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
1445 LI->dropAllReferences();
1446 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001447
Victor Hernandez5d034492009-09-18 22:35:49 +00001448 // Delete all the phis and loads now that inter-references are dead.
1449 for (DenseMap<Value*, std::vector<Value*> >::iterator
1450 I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
1451 I != E; ++I) {
1452 if (PHINode *PN = dyn_cast<PHINode>(I->first))
1453 PN->eraseFromParent();
1454 else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
1455 LI->eraseFromParent();
1456 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001457
Victor Hernandez5d034492009-09-18 22:35:49 +00001458 // The old global is now dead, remove it.
1459 GV->eraseFromParent();
1460
1461 ++NumHeapSRA;
1462 return cast<GlobalVariable>(FieldGlobals[0]);
1463}
1464
Chris Lattnerc4274a72008-12-15 21:02:25 +00001465/// TryToOptimizeStoreOfMallocToGlobal - This function is called when we see a
1466/// pointer global variable with a single value stored it that is a malloc or
1467/// cast of malloc.
1468static bool TryToOptimizeStoreOfMallocToGlobal(GlobalVariable *GV,
Victor Hernandez5d034492009-09-18 22:35:49 +00001469 CallInst *CI,
Chris Lattner229907c2011-07-18 04:54:35 +00001470 Type *AllocTy,
Nick Lewycky52da72b2012-02-05 19:56:38 +00001471 AtomicOrdering Ordering,
Victor Hernandez5d034492009-09-18 22:35:49 +00001472 Module::global_iterator &GVI,
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001473 DataLayout *TD,
Nick Lewyckycf6aae62012-02-12 01:13:18 +00001474 TargetLibraryInfo *TLI) {
Evan Cheng21b588b2010-04-14 20:52:55 +00001475 if (!TD)
1476 return false;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001477
Victor Hernandez5d034492009-09-18 22:35:49 +00001478 // If this is a malloc of an abstract type, don't touch it.
1479 if (!AllocTy->isSized())
1480 return false;
1481
1482 // We can't optimize this global unless all uses of it are *known* to be
1483 // of the malloc value, not of the null initializer value (consider a use
1484 // that compares the global's value against zero to see if the malloc has
1485 // been reached). To do this, we check to see if all uses of the global
1486 // would trap if the global were null: this proves that they must all
1487 // happen after the malloc.
1488 if (!AllUsesOfLoadedValueWillTrapIfNull(GV))
1489 return false;
1490
1491 // We can't optimize this if the malloc itself is used in a complex way,
1492 // for example, being stored into multiple globals. This allows the
Nick Lewyckybbd11562012-02-05 19:48:37 +00001493 // malloc to be stored into the specified global, loaded icmp'd, and
Victor Hernandez5d034492009-09-18 22:35:49 +00001494 // GEP'd. These are all things we could transform to using the global
1495 // for.
Evan Cheng21b588b2010-04-14 20:52:55 +00001496 SmallPtrSet<const PHINode*, 8> PHIs;
1497 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(CI, GV, PHIs))
1498 return false;
Victor Hernandez5d034492009-09-18 22:35:49 +00001499
1500 // If we have a global that is only initialized with a fixed size malloc,
1501 // transform the program to use global memory instead of malloc'd memory.
1502 // This eliminates dynamic allocation, avoids an indirection accessing the
1503 // data, and exposes the resultant global to further GlobalOpt.
Victor Hernandez264da322009-10-16 23:12:25 +00001504 // We cannot optimize the malloc if we cannot determine malloc array size.
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00001505 Value *NElems = getMallocArraySize(CI, TD, TLI, true);
Evan Cheng21b588b2010-04-14 20:52:55 +00001506 if (!NElems)
1507 return false;
Victor Hernandez5d034492009-09-18 22:35:49 +00001508
Evan Cheng21b588b2010-04-14 20:52:55 +00001509 if (ConstantInt *NElements = dyn_cast<ConstantInt>(NElems))
1510 // Restrict this transformation to only working on small allocations
1511 // (2048 bytes currently), as we don't want to introduce a 16M global or
1512 // something.
1513 if (NElements->getZExtValue() * TD->getTypeAllocSize(AllocTy) < 2048) {
Nick Lewyckycf6aae62012-02-12 01:13:18 +00001514 GVI = OptimizeGlobalAddressOfMalloc(GV, CI, AllocTy, NElements, TD, TLI);
Evan Cheng21b588b2010-04-14 20:52:55 +00001515 return true;
Victor Hernandez5d034492009-09-18 22:35:49 +00001516 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001517
Evan Cheng21b588b2010-04-14 20:52:55 +00001518 // If the allocation is an array of structures, consider transforming this
1519 // into multiple malloc'd arrays, one for each field. This is basically
1520 // SRoA for malloc'd memory.
1521
Nick Lewycky52da72b2012-02-05 19:56:38 +00001522 if (Ordering != NotAtomic)
1523 return false;
1524
Evan Cheng21b588b2010-04-14 20:52:55 +00001525 // If this is an allocation of a fixed size array of structs, analyze as a
1526 // variable size array. malloc [100 x struct],1 -> malloc struct, 100
Gabor Greif218f5542010-06-24 14:42:01 +00001527 if (NElems == ConstantInt::get(CI->getArgOperand(0)->getType(), 1))
Chris Lattner229907c2011-07-18 04:54:35 +00001528 if (ArrayType *AT = dyn_cast<ArrayType>(AllocTy))
Evan Cheng21b588b2010-04-14 20:52:55 +00001529 AllocTy = AT->getElementType();
Gabor Greif218f5542010-06-24 14:42:01 +00001530
Chris Lattner229907c2011-07-18 04:54:35 +00001531 StructType *AllocSTy = dyn_cast<StructType>(AllocTy);
Evan Cheng21b588b2010-04-14 20:52:55 +00001532 if (!AllocSTy)
1533 return false;
1534
1535 // This the structure has an unreasonable number of fields, leave it
1536 // alone.
1537 if (AllocSTy->getNumElements() <= 16 && AllocSTy->getNumElements() != 0 &&
1538 AllGlobalLoadUsesSimpleEnoughForHeapSRA(GV, CI)) {
1539
1540 // If this is a fixed size array, transform the Malloc to be an alloc of
1541 // structs. malloc [100 x struct],1 -> malloc struct, 100
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00001542 if (ArrayType *AT = dyn_cast<ArrayType>(getMallocAllocatedType(CI, TLI))) {
Matt Arsenaultd3471e92013-09-11 07:29:40 +00001543 Type *IntPtrTy = TD->getIntPtrType(CI->getType());
Evan Cheng21b588b2010-04-14 20:52:55 +00001544 unsigned TypeSize = TD->getStructLayout(AllocSTy)->getSizeInBytes();
1545 Value *AllocSize = ConstantInt::get(IntPtrTy, TypeSize);
1546 Value *NumElements = ConstantInt::get(IntPtrTy, AT->getNumElements());
1547 Instruction *Malloc = CallInst::CreateMalloc(CI, IntPtrTy, AllocSTy,
1548 AllocSize, NumElements,
Chris Lattner601e390a2010-07-12 00:57:28 +00001549 0, CI->getName());
Evan Cheng21b588b2010-04-14 20:52:55 +00001550 Instruction *Cast = new BitCastInst(Malloc, CI->getType(), "tmp", CI);
1551 CI->replaceAllUsesWith(Cast);
1552 CI->eraseFromParent();
Nuno Lopes9792d682012-06-22 00:25:01 +00001553 if (BitCastInst *BCI = dyn_cast<BitCastInst>(Malloc))
1554 CI = cast<CallInst>(BCI->getOperand(0));
1555 else
Nuno Lopes0b60ebb2012-06-22 00:29:58 +00001556 CI = cast<CallInst>(Malloc);
Evan Cheng21b588b2010-04-14 20:52:55 +00001557 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001558
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00001559 GVI = PerformHeapAllocSRoA(GV, CI, getMallocArraySize(CI, TD, TLI, true),
1560 TD, TLI);
Evan Cheng21b588b2010-04-14 20:52:55 +00001561 return true;
Victor Hernandez5d034492009-09-18 22:35:49 +00001562 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001563
Victor Hernandez5d034492009-09-18 22:35:49 +00001564 return false;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001565}
Victor Hernandez5d034492009-09-18 22:35:49 +00001566
Chris Lattner09a52722004-10-09 21:48:45 +00001567// OptimizeOnceStoredGlobal - Try to optimize globals based on the knowledge
1568// that only one value (besides its initializer) is ever stored to the global.
Chris Lattner004e2502004-10-11 05:54:41 +00001569static bool OptimizeOnceStoredGlobal(GlobalVariable *GV, Value *StoredOnceVal,
Nick Lewycky52da72b2012-02-05 19:56:38 +00001570 AtomicOrdering Ordering,
Chris Lattnerc2d3d312006-08-27 22:42:52 +00001571 Module::global_iterator &GVI,
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001572 DataLayout *TD, TargetLibraryInfo *TLI) {
Chris Lattner1c731fa2008-12-15 21:20:32 +00001573 // Ignore no-op GEPs and bitcasts.
1574 StoredOnceVal = StoredOnceVal->stripPointerCasts();
Chris Lattner09a52722004-10-09 21:48:45 +00001575
Chris Lattnere42eb312004-10-10 23:14:11 +00001576 // If we are dealing with a pointer global that is initialized to null and
1577 // only has one (non-null) value stored into it, then we can optimize any
1578 // users of the loaded value (often calls and loads) that would trap if the
1579 // value was null.
Duncan Sands19d0b472010-02-16 11:11:14 +00001580 if (GV->getInitializer()->getType()->isPointerTy() &&
Chris Lattner09a52722004-10-09 21:48:45 +00001581 GV->getInitializer()->isNullValue()) {
Chris Lattnere42eb312004-10-10 23:14:11 +00001582 if (Constant *SOVC = dyn_cast<Constant>(StoredOnceVal)) {
1583 if (GV->getInitializer()->getType() != SOVC->getType())
Chris Lattner1a1acc22011-05-22 07:15:13 +00001584 SOVC = ConstantExpr::getBitCast(SOVC, GV->getInitializer()->getType());
Misha Brukmanb1c93172005-04-21 23:48:37 +00001585
Chris Lattnere42eb312004-10-10 23:14:11 +00001586 // Optimize away any trapping uses of the loaded value.
Nick Lewyckycf6aae62012-02-12 01:13:18 +00001587 if (OptimizeAwayTrappingUsesOfLoads(GV, SOVC, TD, TLI))
Chris Lattner604ed7a2004-10-10 17:07:12 +00001588 return true;
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00001589 } else if (CallInst *CI = extractMallocCall(StoredOnceVal, TLI)) {
1590 Type *MallocType = getMallocAllocatedType(CI, TLI);
Nick Lewyckycf6aae62012-02-12 01:13:18 +00001591 if (MallocType &&
1592 TryToOptimizeStoreOfMallocToGlobal(GV, CI, MallocType, Ordering, GVI,
1593 TD, TLI))
Victor Hernandezf3db9152009-11-07 00:16:28 +00001594 return true;
Chris Lattnere42eb312004-10-10 23:14:11 +00001595 }
Chris Lattner09a52722004-10-09 21:48:45 +00001596 }
Chris Lattner004e2502004-10-11 05:54:41 +00001597
Chris Lattner09a52722004-10-09 21:48:45 +00001598 return false;
1599}
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001600
Chris Lattner20bbac32008-01-14 01:17:44 +00001601/// TryToShrinkGlobalToBoolean - At this point, we have learned that the only
1602/// two values ever stored into GV are its initializer and OtherVal. See if we
1603/// can shrink the global into a boolean and select between the two values
1604/// whenever it is used. This exposes the values to other scalar optimizations.
Chris Lattner46b5c642009-11-06 04:27:31 +00001605static bool TryToShrinkGlobalToBoolean(GlobalVariable *GV, Constant *OtherVal) {
Chris Lattner229907c2011-07-18 04:54:35 +00001606 Type *GVElType = GV->getType()->getElementType();
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001607
Chris Lattner20bbac32008-01-14 01:17:44 +00001608 // If GVElType is already i1, it is already shrunk. If the type of the GV is
Chris Lattnere3132832009-03-07 23:32:02 +00001609 // an FP value, pointer or vector, don't do this optimization because a select
1610 // between them is very expensive and unlikely to lead to later
1611 // simplification. In these cases, we typically end up with "cond ? v1 : v2"
1612 // where v1 and v2 both require constant pool loads, a big loss.
Chris Lattner46b5c642009-11-06 04:27:31 +00001613 if (GVElType == Type::getInt1Ty(GV->getContext()) ||
Duncan Sands9dff9be2010-02-15 16:12:20 +00001614 GVElType->isFloatingPointTy() ||
Duncan Sands19d0b472010-02-16 11:11:14 +00001615 GVElType->isPointerTy() || GVElType->isVectorTy())
Chris Lattner20bbac32008-01-14 01:17:44 +00001616 return false;
Gabor Greifa75ed762010-07-12 14:13:15 +00001617
Chris Lattner20bbac32008-01-14 01:17:44 +00001618 // Walk the use list of the global seeing if all the uses are load or store.
1619 // If there is anything else, bail out.
Gabor Greifa75ed762010-07-12 14:13:15 +00001620 for (Value::use_iterator I = GV->use_begin(), E = GV->use_end(); I != E; ++I){
1621 User *U = *I;
1622 if (!isa<LoadInst>(U) && !isa<StoreInst>(U))
Chris Lattner20bbac32008-01-14 01:17:44 +00001623 return false;
Gabor Greifa75ed762010-07-12 14:13:15 +00001624 }
1625
David Greene44cb8ad2010-01-05 01:28:05 +00001626 DEBUG(dbgs() << " *** SHRINKING TO BOOL: " << *GV);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001627
Chris Lattner40e4cec2004-12-12 05:53:50 +00001628 // Create the new global, initializing it to false.
Chris Lattner46b5c642009-11-06 04:27:31 +00001629 GlobalVariable *NewGV = new GlobalVariable(Type::getInt1Ty(GV->getContext()),
1630 false,
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001631 GlobalValue::InternalLinkage,
Chris Lattner46b5c642009-11-06 04:27:31 +00001632 ConstantInt::getFalse(GV->getContext()),
Nick Lewycky431f97e2009-05-03 03:49:08 +00001633 GV->getName()+".b",
Joey Gouly58bf9512013-01-10 10:31:11 +00001634 GV->getThreadLocalMode(),
1635 GV->getType()->getAddressSpace());
Chris Lattner40e4cec2004-12-12 05:53:50 +00001636 GV->getParent()->getGlobalList().insert(GV, NewGV);
1637
1638 Constant *InitVal = GV->getInitializer();
Chris Lattner46b5c642009-11-06 04:27:31 +00001639 assert(InitVal->getType() != Type::getInt1Ty(GV->getContext()) &&
Owen Anderson55f1c092009-08-13 21:58:54 +00001640 "No reason to shrink to bool!");
Chris Lattner40e4cec2004-12-12 05:53:50 +00001641
1642 // If initialized to zero and storing one into the global, we can use a cast
1643 // instead of a select to synthesize the desired value.
1644 bool IsOneZero = false;
1645 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal))
Reid Spencer2e54a152007-03-02 00:28:52 +00001646 IsOneZero = InitVal->isNullValue() && CI->isOne();
Chris Lattner40e4cec2004-12-12 05:53:50 +00001647
1648 while (!GV->use_empty()) {
Devang Patelfc507a12009-03-06 01:39:36 +00001649 Instruction *UI = cast<Instruction>(GV->use_back());
1650 if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
Chris Lattner40e4cec2004-12-12 05:53:50 +00001651 // Change the store into a boolean store.
1652 bool StoringOther = SI->getOperand(0) == OtherVal;
1653 // Only do this if we weren't storing a loaded value.
Chris Lattner745196a2004-12-12 19:34:41 +00001654 Value *StoreVal;
Bill Wendling7297b862013-02-13 23:00:51 +00001655 if (StoringOther || SI->getOperand(0) == InitVal) {
Chris Lattner46b5c642009-11-06 04:27:31 +00001656 StoreVal = ConstantInt::get(Type::getInt1Ty(GV->getContext()),
1657 StoringOther);
Bill Wendling7297b862013-02-13 23:00:51 +00001658 } else {
Chris Lattner745196a2004-12-12 19:34:41 +00001659 // Otherwise, we are storing a previously loaded copy. To do this,
1660 // change the copy from copying the original value to just copying the
1661 // bool.
1662 Instruction *StoredVal = cast<Instruction>(SI->getOperand(0));
1663
Gabor Greif218f5542010-06-24 14:42:01 +00001664 // If we've already replaced the input, StoredVal will be a cast or
Chris Lattner745196a2004-12-12 19:34:41 +00001665 // select instruction. If not, it will be a load of the original
1666 // global.
1667 if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
1668 assert(LI->getOperand(0) == GV && "Not a copy!");
1669 // Insert a new load, to preserve the saved value.
Nick Lewycky52da72b2012-02-05 19:56:38 +00001670 StoreVal = new LoadInst(NewGV, LI->getName()+".b", false, 0,
1671 LI->getOrdering(), LI->getSynchScope(), LI);
Chris Lattner745196a2004-12-12 19:34:41 +00001672 } else {
1673 assert((isa<CastInst>(StoredVal) || isa<SelectInst>(StoredVal)) &&
1674 "This is not a form that we understand!");
1675 StoreVal = StoredVal->getOperand(0);
1676 assert(isa<LoadInst>(StoreVal) && "Not a load of NewGV!");
1677 }
1678 }
Nick Lewycky52da72b2012-02-05 19:56:38 +00001679 new StoreInst(StoreVal, NewGV, false, 0,
1680 SI->getOrdering(), SI->getSynchScope(), SI);
Devang Patelfc507a12009-03-06 01:39:36 +00001681 } else {
Chris Lattner40e4cec2004-12-12 05:53:50 +00001682 // Change the load into a load of bool then a select.
Devang Patelfc507a12009-03-06 01:39:36 +00001683 LoadInst *LI = cast<LoadInst>(UI);
Nick Lewycky52da72b2012-02-05 19:56:38 +00001684 LoadInst *NLI = new LoadInst(NewGV, LI->getName()+".b", false, 0,
1685 LI->getOrdering(), LI->getSynchScope(), LI);
Chris Lattner40e4cec2004-12-12 05:53:50 +00001686 Value *NSI;
1687 if (IsOneZero)
Chris Lattner8d4c36b2007-02-11 01:08:35 +00001688 NSI = new ZExtInst(NLI, LI->getType(), "", LI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001689 else
Gabor Greife9ecc682008-04-06 20:25:17 +00001690 NSI = SelectInst::Create(NLI, OtherVal, InitVal, "", LI);
Chris Lattner8d4c36b2007-02-11 01:08:35 +00001691 NSI->takeName(LI);
Chris Lattner40e4cec2004-12-12 05:53:50 +00001692 LI->replaceAllUsesWith(NSI);
Devang Patelfc507a12009-03-06 01:39:36 +00001693 }
1694 UI->eraseFromParent();
Chris Lattner40e4cec2004-12-12 05:53:50 +00001695 }
1696
Bill Wendling7297b862013-02-13 23:00:51 +00001697 // Retain the name of the old global variable. People who are debugging their
1698 // programs may expect these variables to be named the same.
1699 NewGV->takeName(GV);
Chris Lattner40e4cec2004-12-12 05:53:50 +00001700 GV->eraseFromParent();
Chris Lattner20bbac32008-01-14 01:17:44 +00001701 return true;
Chris Lattner40e4cec2004-12-12 05:53:50 +00001702}
1703
1704
Nick Lewycky1480f1d2012-02-12 00:52:26 +00001705/// ProcessGlobal - Analyze the specified global variable and optimize it if
1706/// possible. If we make a change, return true.
Rafael Espindolafc355bc2011-01-19 16:32:21 +00001707bool GlobalOpt::ProcessGlobal(GlobalVariable *GV,
1708 Module::global_iterator &GVI) {
Rafael Espindoladef1b092012-06-14 22:48:13 +00001709 if (!GV->isDiscardableIfUnused())
Rafael Espindolafc355bc2011-01-19 16:32:21 +00001710 return false;
1711
1712 // Do more involved optimizations if the global is internal.
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001713 GV->removeDeadConstantUsers();
1714
1715 if (GV->use_empty()) {
David Greene44cb8ad2010-01-05 01:28:05 +00001716 DEBUG(dbgs() << "GLOBAL DEAD: " << *GV);
Chris Lattner8e71c6a2004-10-16 18:09:00 +00001717 GV->eraseFromParent();
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001718 ++NumDeleted;
1719 return true;
1720 }
1721
Rafael Espindola1821c6c2012-06-15 18:00:24 +00001722 if (!GV->hasLocalLinkage())
1723 return false;
1724
Rafael Espindolafc355bc2011-01-19 16:32:21 +00001725 GlobalStatus GS;
1726
Rafael Espindola3d7fc252013-10-21 17:14:55 +00001727 if (GlobalStatus::analyzeGlobal(GV, GS))
Rafael Espindolaecd5b9a2011-01-18 04:36:06 +00001728 return false;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001729
Rafael Espindola045a78f2013-10-17 18:18:52 +00001730 if (!GS.IsCompared && !GV->hasUnnamedAddr()) {
Rafael Espindolafc355bc2011-01-19 16:32:21 +00001731 GV->setUnnamedAddr(true);
1732 NumUnnamed++;
1733 }
1734
1735 if (GV->isConstant() || !GV->hasInitializer())
1736 return false;
1737
Rafael Espindolad21ac192013-09-05 19:15:21 +00001738 return ProcessInternalGlobal(GV, GVI, GS);
Rafael Espindolafc355bc2011-01-19 16:32:21 +00001739}
1740
1741/// ProcessInternalGlobal - Analyze the specified global variable and optimize
1742/// it if possible. If we make a change, return true.
1743bool GlobalOpt::ProcessInternalGlobal(GlobalVariable *GV,
1744 Module::global_iterator &GVI,
Rafael Espindolafc355bc2011-01-19 16:32:21 +00001745 const GlobalStatus &GS) {
Alexey Samsonova1944e62013-10-07 19:03:24 +00001746 // If this is a first class global and has only one accessing function
1747 // and this function is main (which we know is not recursive), we replace
1748 // the global with a local alloca in this function.
1749 //
Alp Tokerf907b892013-12-05 05:44:44 +00001750 // NOTE: It doesn't make sense to promote non-single-value types since we
Alexey Samsonova1944e62013-10-07 19:03:24 +00001751 // are just replacing static memory to stack memory.
1752 //
1753 // If the global is in different address space, don't bring it to stack.
1754 if (!GS.HasMultipleAccessingFunctions &&
1755 GS.AccessingFunction && !GS.HasNonInstructionUser &&
1756 GV->getType()->getElementType()->isSingleValueType() &&
1757 GS.AccessingFunction->getName() == "main" &&
1758 GS.AccessingFunction->hasExternalLinkage() &&
1759 GV->getType()->getAddressSpace() == 0) {
1760 DEBUG(dbgs() << "LOCALIZING GLOBAL: " << *GV);
1761 Instruction &FirstI = const_cast<Instruction&>(*GS.AccessingFunction
1762 ->getEntryBlock().begin());
1763 Type *ElemTy = GV->getType()->getElementType();
1764 // FIXME: Pass Global's alignment when globals have alignment
1765 AllocaInst *Alloca = new AllocaInst(ElemTy, NULL, GV->getName(), &FirstI);
1766 if (!isa<UndefValue>(GV->getInitializer()))
1767 new StoreInst(GV->getInitializer(), Alloca, &FirstI);
1768
1769 GV->replaceAllUsesWith(Alloca);
1770 GV->eraseFromParent();
1771 ++NumLocalized;
1772 return true;
1773 }
1774
Rafael Espindolaecd5b9a2011-01-18 04:36:06 +00001775 // If the global is never loaded (but may be stored to), it is dead.
1776 // Delete it now.
Rafael Espindola045a78f2013-10-17 18:18:52 +00001777 if (!GS.IsLoaded) {
Rafael Espindolaecd5b9a2011-01-18 04:36:06 +00001778 DEBUG(dbgs() << "GLOBAL NEVER LOADED: " << *GV);
1779
Nick Lewyckyfaa9c3b02012-07-24 07:21:08 +00001780 bool Changed;
1781 if (isLeakCheckerRoot(GV)) {
1782 // Delete any constant stores to the global.
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00001783 Changed = CleanupPointerRootUsers(GV, TLI);
Nick Lewyckyfaa9c3b02012-07-24 07:21:08 +00001784 } else {
1785 // Delete any stores we can find to the global. We may not be able to
1786 // make it completely dead though.
1787 Changed = CleanupConstantGlobalUsers(GV, GV->getInitializer(), TD, TLI);
1788 }
Rafael Espindolaecd5b9a2011-01-18 04:36:06 +00001789
1790 // If the global is dead now, delete it.
1791 if (GV->use_empty()) {
1792 GV->eraseFromParent();
1793 ++NumDeleted;
1794 Changed = true;
1795 }
1796 return Changed;
1797
Rafael Espindola045a78f2013-10-17 18:18:52 +00001798 } else if (GS.StoredType <= GlobalStatus::InitializerStored) {
Michael Gottesmand1a46f22013-01-11 20:07:53 +00001799 DEBUG(dbgs() << "MARKING CONSTANT: " << *GV << "\n");
Rafael Espindolaecd5b9a2011-01-18 04:36:06 +00001800 GV->setConstant(true);
1801
1802 // Clean up any obviously simplifiable users now.
Nick Lewyckycf6aae62012-02-12 01:13:18 +00001803 CleanupConstantGlobalUsers(GV, GV->getInitializer(), TD, TLI);
Rafael Espindolaecd5b9a2011-01-18 04:36:06 +00001804
1805 // If the global is dead now, just nuke it.
1806 if (GV->use_empty()) {
1807 DEBUG(dbgs() << " *** Marking constant allowed us to simplify "
1808 << "all users and delete global!\n");
1809 GV->eraseFromParent();
1810 ++NumDeleted;
1811 }
1812
1813 ++NumMarked;
1814 return true;
1815 } else if (!GV->getInitializer()->getType()->isSingleValueType()) {
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001816 if (DataLayout *TD = getAnalysisIfAvailable<DataLayout>())
Rafael Espindolaecd5b9a2011-01-18 04:36:06 +00001817 if (GlobalVariable *FirstNewGV = SRAGlobal(GV, *TD)) {
1818 GVI = FirstNewGV; // Don't skip the newly produced globals!
1819 return true;
1820 }
Rafael Espindola045a78f2013-10-17 18:18:52 +00001821 } else if (GS.StoredType == GlobalStatus::StoredOnce) {
Rafael Espindolaecd5b9a2011-01-18 04:36:06 +00001822 // If the initial value for the global was an undef value, and if only
1823 // one other value was stored into it, we can just change the
1824 // initializer to be the stored value, then delete all stores to the
1825 // global. This allows us to mark it constant.
1826 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
1827 if (isa<UndefValue>(GV->getInitializer())) {
1828 // Change the initial value here.
1829 GV->setInitializer(SOVConstant);
1830
1831 // Clean up any obviously simplifiable users now.
Nick Lewyckycf6aae62012-02-12 01:13:18 +00001832 CleanupConstantGlobalUsers(GV, GV->getInitializer(), TD, TLI);
Rafael Espindolaecd5b9a2011-01-18 04:36:06 +00001833
1834 if (GV->use_empty()) {
1835 DEBUG(dbgs() << " *** Substituting initializer allowed us to "
Nick Lewyckyfaa9c3b02012-07-24 07:21:08 +00001836 << "simplify all users and delete global!\n");
Rafael Espindolaecd5b9a2011-01-18 04:36:06 +00001837 GV->eraseFromParent();
1838 ++NumDeleted;
1839 } else {
1840 GVI = GV;
1841 }
1842 ++NumSubstitute;
1843 return true;
1844 }
1845
1846 // Try to optimize globals based on the knowledge that only one value
1847 // (besides its initializer) is ever stored to the global.
Nick Lewycky52da72b2012-02-05 19:56:38 +00001848 if (OptimizeOnceStoredGlobal(GV, GS.StoredOnceValue, GS.Ordering, GVI,
Nick Lewyckycf6aae62012-02-12 01:13:18 +00001849 TD, TLI))
Rafael Espindolaecd5b9a2011-01-18 04:36:06 +00001850 return true;
1851
1852 // Otherwise, if the global was not a boolean, we can shrink it to be a
1853 // boolean.
Eli Friedman33d37002013-09-09 22:00:13 +00001854 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue)) {
1855 if (GS.Ordering == NotAtomic) {
1856 if (TryToShrinkGlobalToBoolean(GV, SOVConstant)) {
1857 ++NumShrunkToBool;
1858 return true;
1859 }
Rafael Espindolaecd5b9a2011-01-18 04:36:06 +00001860 }
Eli Friedman33d37002013-09-09 22:00:13 +00001861 }
Rafael Espindolaecd5b9a2011-01-18 04:36:06 +00001862 }
1863
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001864 return false;
1865}
1866
Chris Lattnera4c80222005-05-08 22:18:06 +00001867/// ChangeCalleesToFastCall - Walk all of the direct calls of the specified
1868/// function, changing them to FastCC.
1869static void ChangeCalleesToFastCall(Function *F) {
1870 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
Jay Foadca0c4992012-05-12 08:30:16 +00001871 if (isa<BlockAddress>(*UI))
1872 continue;
Duncan Sands85fab3a2008-02-18 17:32:13 +00001873 CallSite User(cast<Instruction>(*UI));
1874 User.setCallingConv(CallingConv::Fast);
Chris Lattnera4c80222005-05-08 22:18:06 +00001875 }
1876}
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001877
Bill Wendlinge94d8432012-12-07 23:16:57 +00001878static AttributeSet StripNest(LLVMContext &C, const AttributeSet &Attrs) {
Chris Lattner8a923e72008-03-12 17:45:29 +00001879 for (unsigned i = 0, e = Attrs.getNumSlots(); i != e; ++i) {
Bill Wendling57625a42013-01-25 23:09:36 +00001880 unsigned Index = Attrs.getSlotIndex(i);
1881 if (!Attrs.getSlotAttributes(i).hasAttribute(Index, Attribute::Nest))
Duncan Sands85fab3a2008-02-18 17:32:13 +00001882 continue;
1883
Duncan Sands85fab3a2008-02-18 17:32:13 +00001884 // There can be only one.
Bill Wendling57625a42013-01-25 23:09:36 +00001885 return Attrs.removeAttribute(C, Index, Attribute::Nest);
Duncan Sands573b3f82008-02-16 20:56:04 +00001886 }
1887
1888 return Attrs;
1889}
1890
1891static void RemoveNestAttribute(Function *F) {
Bill Wendling85a64c22012-10-14 06:39:53 +00001892 F->setAttributes(StripNest(F->getContext(), F->getAttributes()));
Duncan Sands573b3f82008-02-16 20:56:04 +00001893 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
Jay Foadca0c4992012-05-12 08:30:16 +00001894 if (isa<BlockAddress>(*UI))
1895 continue;
Duncan Sands85fab3a2008-02-18 17:32:13 +00001896 CallSite User(cast<Instruction>(*UI));
Bill Wendling85a64c22012-10-14 06:39:53 +00001897 User.setAttributes(StripNest(F->getContext(), User.getAttributes()));
Duncan Sands573b3f82008-02-16 20:56:04 +00001898 }
1899}
1900
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001901bool GlobalOpt::OptimizeFunctions(Module &M) {
1902 bool Changed = false;
1903 // Optimize functions.
1904 for (Module::iterator FI = M.begin(), E = M.end(); FI != E; ) {
1905 Function *F = FI++;
Duncan Sandsed722832009-03-06 10:21:56 +00001906 // Functions without names cannot be referenced outside this module.
1907 if (!F->hasName() && !F->isDeclaration())
1908 F->setLinkage(GlobalValue::InternalLinkage);
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001909 F->removeDeadConstantUsers();
Eli Friedman1923a332011-10-20 05:23:42 +00001910 if (F->isDefTriviallyDead()) {
Chris Lattnerb5d9c8c2009-11-01 19:03:42 +00001911 F->eraseFromParent();
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001912 Changed = true;
1913 ++NumFnDeleted;
Rafael Espindola6de96a12009-01-15 20:18:42 +00001914 } else if (F->hasLocalLinkage()) {
Duncan Sands573b3f82008-02-16 20:56:04 +00001915 if (F->getCallingConv() == CallingConv::C && !F->isVarArg() &&
Jay Foad557169d2009-06-10 08:41:11 +00001916 !F->hasAddressTaken()) {
Duncan Sands573b3f82008-02-16 20:56:04 +00001917 // If this function has C calling conventions, is not a varargs
1918 // function, and is only called directly, promote it to use the Fast
1919 // calling convention.
1920 F->setCallingConv(CallingConv::Fast);
1921 ChangeCalleesToFastCall(F);
1922 ++NumFastCallFns;
1923 Changed = true;
1924 }
1925
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001926 if (F->getAttributes().hasAttrSomewhere(Attribute::Nest) &&
Jay Foad557169d2009-06-10 08:41:11 +00001927 !F->hasAddressTaken()) {
Duncan Sands573b3f82008-02-16 20:56:04 +00001928 // The function is not used by a trampoline intrinsic, so it is safe
1929 // to remove the 'nest' attribute.
1930 RemoveNestAttribute(F);
1931 ++NumNestRemoved;
1932 Changed = true;
1933 }
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001934 }
1935 }
1936 return Changed;
1937}
1938
1939bool GlobalOpt::OptimizeGlobalVars(Module &M) {
1940 bool Changed = false;
1941 for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
1942 GVI != E; ) {
1943 GlobalVariable *GV = GVI++;
Duncan Sandsed722832009-03-06 10:21:56 +00001944 // Global variables without names cannot be referenced outside this module.
1945 if (!GV->hasName() && !GV->isDeclaration())
1946 GV->setLinkage(GlobalValue::InternalLinkage);
Dan Gohman580b80d2009-11-23 16:22:21 +00001947 // Simplify the initializer.
1948 if (GV->hasInitializer())
1949 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GV->getInitializer())) {
Chad Rosier43a33062011-12-02 01:26:24 +00001950 Constant *New = ConstantFoldConstantExpression(CE, TD, TLI);
Dan Gohman580b80d2009-11-23 16:22:21 +00001951 if (New && New != CE)
1952 GV->setInitializer(New);
1953 }
Rafael Espindolafc355bc2011-01-19 16:32:21 +00001954
1955 Changed |= ProcessGlobal(GV, GVI);
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001956 }
1957 return Changed;
1958}
1959
Nick Lewycky466d0c12011-04-08 07:30:21 +00001960/// FindGlobalCtors - Find the llvm.global_ctors list, verifying that all
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001961/// initializers have an init priority of 65535.
1962GlobalVariable *GlobalOpt::FindGlobalCtors(Module &M) {
Chris Lattner7ff0ba42010-12-06 21:53:07 +00001963 GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
1964 if (GV == 0) return 0;
Jakub Staszak9525a772012-12-06 21:57:16 +00001965
Chris Lattner7ff0ba42010-12-06 21:53:07 +00001966 // Verify that the initializer is simple enough for us to handle. We are
1967 // only allowed to optimize the initializer if it is unique.
1968 if (!GV->hasUniqueInitializer()) return 0;
Nick Lewycky0f857892011-04-11 22:11:20 +00001969
1970 if (isa<ConstantAggregateZero>(GV->getInitializer()))
1971 return GV;
1972 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
Eli Friedman9cca0712011-04-09 09:11:09 +00001973
Chris Lattner7ff0ba42010-12-06 21:53:07 +00001974 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i) {
Nick Lewycky0f857892011-04-11 22:11:20 +00001975 if (isa<ConstantAggregateZero>(*i))
1976 continue;
1977 ConstantStruct *CS = cast<ConstantStruct>(*i);
Chris Lattner7ff0ba42010-12-06 21:53:07 +00001978 if (isa<ConstantPointerNull>(CS->getOperand(1)))
1979 continue;
Chris Lattner838bdc12005-09-26 02:19:27 +00001980
Chris Lattner7ff0ba42010-12-06 21:53:07 +00001981 // Must have a function or null ptr.
1982 if (!isa<Function>(CS->getOperand(1)))
1983 return 0;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001984
Chris Lattner7ff0ba42010-12-06 21:53:07 +00001985 // Init priority must be standard.
Nick Lewycky466d0c12011-04-08 07:30:21 +00001986 ConstantInt *CI = cast<ConstantInt>(CS->getOperand(0));
1987 if (CI->getZExtValue() != 65535)
Chris Lattner7ff0ba42010-12-06 21:53:07 +00001988 return 0;
1989 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001990
Chris Lattner7ff0ba42010-12-06 21:53:07 +00001991 return GV;
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001992}
1993
Chris Lattner696beef2005-09-26 02:31:18 +00001994/// ParseGlobalCtors - Given a llvm.global_ctors list that we can understand,
1995/// return a list of the functions and null terminator as a vector.
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001996static std::vector<Function*> ParseGlobalCtors(GlobalVariable *GV) {
Nick Lewycky0f857892011-04-11 22:11:20 +00001997 if (GV->getInitializer()->isNullValue())
1998 return std::vector<Function*>();
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001999 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
2000 std::vector<Function*> Result;
2001 Result.reserve(CA->getNumOperands());
Gabor Greif3a9fba52008-05-29 01:59:18 +00002002 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i) {
2003 ConstantStruct *CS = cast<ConstantStruct>(*i);
Chris Lattner41b6a5a2005-09-26 01:43:45 +00002004 Result.push_back(dyn_cast<Function>(CS->getOperand(1)));
2005 }
2006 return Result;
2007}
2008
Chris Lattner696beef2005-09-26 02:31:18 +00002009/// InstallGlobalCtors - Given a specified llvm.global_ctors list, install the
2010/// specified array, returning the new global to use.
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002011static GlobalVariable *InstallGlobalCtors(GlobalVariable *GCL,
Chris Lattner46b5c642009-11-06 04:27:31 +00002012 const std::vector<Function*> &Ctors) {
Chris Lattner696beef2005-09-26 02:31:18 +00002013 // If we made a change, reassemble the initializer list.
Chris Lattnercc19efa2011-06-20 04:01:31 +00002014 Constant *CSVals[2];
2015 CSVals[0] = ConstantInt::get(Type::getInt32Ty(GCL->getContext()), 65535);
2016 CSVals[1] = 0;
2017
Chris Lattner229907c2011-07-18 04:54:35 +00002018 StructType *StructTy =
Matt Arsenault404c60a2013-10-21 19:43:56 +00002019 cast<StructType>(GCL->getType()->getElementType()->getArrayElementType());
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002020
Chris Lattner696beef2005-09-26 02:31:18 +00002021 // Create the new init list.
2022 std::vector<Constant*> CAList;
2023 for (unsigned i = 0, e = Ctors.size(); i != e; ++i) {
Chris Lattner99e23fa2005-09-26 04:44:35 +00002024 if (Ctors[i]) {
Chris Lattner696beef2005-09-26 02:31:18 +00002025 CSVals[1] = Ctors[i];
Chris Lattner99e23fa2005-09-26 04:44:35 +00002026 } else {
Chris Lattner229907c2011-07-18 04:54:35 +00002027 Type *FTy = FunctionType::get(Type::getVoidTy(GCL->getContext()),
Chris Lattner46b5c642009-11-06 04:27:31 +00002028 false);
Chris Lattner229907c2011-07-18 04:54:35 +00002029 PointerType *PFTy = PointerType::getUnqual(FTy);
Owen Anderson5a1acd92009-07-31 20:28:14 +00002030 CSVals[1] = Constant::getNullValue(PFTy);
Chris Lattner46b5c642009-11-06 04:27:31 +00002031 CSVals[0] = ConstantInt::get(Type::getInt32Ty(GCL->getContext()),
Nick Lewycky0f857892011-04-11 22:11:20 +00002032 0x7fffffff);
Chris Lattner696beef2005-09-26 02:31:18 +00002033 }
Chris Lattnercc19efa2011-06-20 04:01:31 +00002034 CAList.push_back(ConstantStruct::get(StructTy, CSVals));
Chris Lattner696beef2005-09-26 02:31:18 +00002035 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002036
Chris Lattner696beef2005-09-26 02:31:18 +00002037 // Create the array initializer.
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002038 Constant *CA = ConstantArray::get(ArrayType::get(StructTy,
Nick Lewycky1303c0a2009-09-19 20:30:26 +00002039 CAList.size()), CAList);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002040
Chris Lattner696beef2005-09-26 02:31:18 +00002041 // If we didn't change the number of elements, don't create a new GV.
2042 if (CA->getType() == GCL->getInitializer()->getType()) {
2043 GCL->setInitializer(CA);
2044 return GCL;
2045 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002046
Chris Lattner696beef2005-09-26 02:31:18 +00002047 // Create the new global and insert it next to the existing list.
Chris Lattner46b5c642009-11-06 04:27:31 +00002048 GlobalVariable *NGV = new GlobalVariable(CA->getType(), GCL->isConstant(),
Lauro Ramos Venancio749e4662007-04-12 18:32:50 +00002049 GCL->getLinkage(), CA, "",
Hans Wennborgcbe34b42012-06-23 11:37:03 +00002050 GCL->getThreadLocalMode());
Chris Lattner696beef2005-09-26 02:31:18 +00002051 GCL->getParent()->getGlobalList().insert(GCL, NGV);
Chris Lattner8d4c36b2007-02-11 01:08:35 +00002052 NGV->takeName(GCL);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002053
Chris Lattner696beef2005-09-26 02:31:18 +00002054 // Nuke the old list, replacing any uses with the new one.
2055 if (!GCL->use_empty()) {
2056 Constant *V = NGV;
2057 if (V->getType() != GCL->getType())
Owen Anderson487375e2009-07-29 18:55:55 +00002058 V = ConstantExpr::getBitCast(V, GCL->getType());
Chris Lattner696beef2005-09-26 02:31:18 +00002059 GCL->replaceAllUsesWith(V);
2060 }
2061 GCL->eraseFromParent();
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002062
Chris Lattner696beef2005-09-26 02:31:18 +00002063 if (Ctors.size())
2064 return NGV;
2065 else
2066 return 0;
2067}
Chris Lattner99e23fa2005-09-26 04:44:35 +00002068
2069
Jakub Staszak9525a772012-12-06 21:57:16 +00002070static inline bool
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002071isSimpleEnoughValueToCommit(Constant *C,
Eli Friedman55fa49f32012-01-05 23:03:32 +00002072 SmallPtrSet<Constant*, 8> &SimpleConstants,
Micah Villmowcdfe20b2012-10-08 16:38:25 +00002073 const DataLayout *TD);
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002074
2075
2076/// isSimpleEnoughValueToCommit - Return true if the specified constant can be
2077/// handled by the code generator. We don't want to generate something like:
2078/// void *X = &X/42;
2079/// because the code generator doesn't have a relocation that can handle that.
2080///
2081/// This function should be called if C was not found (but just got inserted)
2082/// in SimpleConstants to avoid having to rescan the same constants all the
2083/// time.
2084static bool isSimpleEnoughValueToCommitHelper(Constant *C,
Eli Friedman55fa49f32012-01-05 23:03:32 +00002085 SmallPtrSet<Constant*, 8> &SimpleConstants,
Micah Villmowcdfe20b2012-10-08 16:38:25 +00002086 const DataLayout *TD) {
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002087 // Simple integer, undef, constant aggregate zero, global addresses, etc are
2088 // all supported.
2089 if (C->getNumOperands() == 0 || isa<BlockAddress>(C) ||
2090 isa<GlobalValue>(C))
2091 return true;
Jakub Staszak9525a772012-12-06 21:57:16 +00002092
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002093 // Aggregate values are safe if all their elements are.
2094 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C) ||
2095 isa<ConstantVector>(C)) {
2096 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i) {
2097 Constant *Op = cast<Constant>(C->getOperand(i));
Eli Friedman55fa49f32012-01-05 23:03:32 +00002098 if (!isSimpleEnoughValueToCommit(Op, SimpleConstants, TD))
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002099 return false;
2100 }
2101 return true;
2102 }
Jakub Staszak9525a772012-12-06 21:57:16 +00002103
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002104 // We don't know exactly what relocations are allowed in constant expressions,
2105 // so we allow &global+constantoffset, which is safe and uniformly supported
2106 // across targets.
2107 ConstantExpr *CE = cast<ConstantExpr>(C);
2108 switch (CE->getOpcode()) {
2109 case Instruction::BitCast:
Eli Friedman55fa49f32012-01-05 23:03:32 +00002110 // Bitcast is fine if the casted value is fine.
2111 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, TD);
2112
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002113 case Instruction::IntToPtr:
2114 case Instruction::PtrToInt:
Eli Friedman55fa49f32012-01-05 23:03:32 +00002115 // int <=> ptr is fine if the int type is the same size as the
2116 // pointer type.
2117 if (!TD || TD->getTypeSizeInBits(CE->getType()) !=
2118 TD->getTypeSizeInBits(CE->getOperand(0)->getType()))
2119 return false;
2120 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, TD);
Jakub Staszak9525a772012-12-06 21:57:16 +00002121
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002122 // GEP is fine if it is simple + constant offset.
2123 case Instruction::GetElementPtr:
2124 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
2125 if (!isa<ConstantInt>(CE->getOperand(i)))
2126 return false;
Eli Friedman55fa49f32012-01-05 23:03:32 +00002127 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, TD);
Jakub Staszak9525a772012-12-06 21:57:16 +00002128
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002129 case Instruction::Add:
2130 // We allow simple+cst.
2131 if (!isa<ConstantInt>(CE->getOperand(1)))
2132 return false;
Eli Friedman55fa49f32012-01-05 23:03:32 +00002133 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, TD);
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002134 }
2135 return false;
2136}
2137
Jakub Staszak9525a772012-12-06 21:57:16 +00002138static inline bool
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002139isSimpleEnoughValueToCommit(Constant *C,
Eli Friedman55fa49f32012-01-05 23:03:32 +00002140 SmallPtrSet<Constant*, 8> &SimpleConstants,
Micah Villmowcdfe20b2012-10-08 16:38:25 +00002141 const DataLayout *TD) {
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002142 // If we already checked this constant, we win.
2143 if (!SimpleConstants.insert(C)) return true;
2144 // Check the constant.
Eli Friedman55fa49f32012-01-05 23:03:32 +00002145 return isSimpleEnoughValueToCommitHelper(C, SimpleConstants, TD);
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002146}
2147
2148
Chris Lattner99e23fa2005-09-26 04:44:35 +00002149/// isSimpleEnoughPointerToCommit - Return true if this constant is simple
Owen Anderson9eb7cb482011-01-14 22:19:20 +00002150/// enough for us to understand. In particular, if it is a cast to anything
2151/// other than from one pointer type to another pointer type, we punt.
2152/// We basically just support direct accesses to globals and GEP's of
Chris Lattner99e23fa2005-09-26 04:44:35 +00002153/// globals. This should be kept up to date with CommitValueTo.
Chris Lattner46b5c642009-11-06 04:27:31 +00002154static bool isSimpleEnoughPointerToCommit(Constant *C) {
Dan Gohman82e74752009-09-07 22:42:05 +00002155 // Conservatively, avoid aggregate types. This is because we don't
2156 // want to worry about them partially overlapping other stores.
2157 if (!cast<PointerType>(C->getType())->getElementType()->isSingleValueType())
2158 return false;
2159
Dan Gohmanf7f3fb12009-09-07 22:31:26 +00002160 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
Mikhail Glushenkov2072db22010-10-19 16:47:23 +00002161 // Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or
Dan Gohmanf7f3fb12009-09-07 22:31:26 +00002162 // external globals.
Mikhail Glushenkov2072db22010-10-19 16:47:23 +00002163 return GV->hasUniqueInitializer();
Dan Gohmanf7f3fb12009-09-07 22:31:26 +00002164
Owen Anderson3e2f6cf2011-01-14 22:31:13 +00002165 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
Chris Lattner46af55e2005-09-26 06:52:44 +00002166 // Handle a constantexpr gep.
2167 if (CE->getOpcode() == Instruction::GetElementPtr &&
Dan Gohmanbeee35a2009-09-07 22:40:13 +00002168 isa<GlobalVariable>(CE->getOperand(0)) &&
2169 cast<GEPOperator>(CE)->isInBounds()) {
Chris Lattner46af55e2005-09-26 06:52:44 +00002170 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
Mikhail Glushenkov2072db22010-10-19 16:47:23 +00002171 // Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or
Dan Gohmanf7f3fb12009-09-07 22:31:26 +00002172 // external globals.
Mikhail Glushenkov2072db22010-10-19 16:47:23 +00002173 if (!GV->hasUniqueInitializer())
Dan Gohmanf7f3fb12009-09-07 22:31:26 +00002174 return false;
Dan Gohman161429f2009-09-07 22:44:55 +00002175
Dan Gohman161429f2009-09-07 22:44:55 +00002176 // The first index must be zero.
Oscar Fuentes40b31ad2010-08-02 06:00:15 +00002177 ConstantInt *CI = dyn_cast<ConstantInt>(*llvm::next(CE->op_begin()));
Dan Gohman161429f2009-09-07 22:44:55 +00002178 if (!CI || !CI->isZero()) return false;
Dan Gohman161429f2009-09-07 22:44:55 +00002179
2180 // The remaining indices must be compile-time known integers within the
Dan Gohman7190d482009-09-10 23:37:55 +00002181 // notional bounds of the corresponding static array types.
2182 if (!CE->isGEPWithNoNotionalOverIndexing())
2183 return false;
Dan Gohman161429f2009-09-07 22:44:55 +00002184
Dan Gohmane525d9d2009-10-05 16:36:26 +00002185 return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
Jakub Staszak9525a772012-12-06 21:57:16 +00002186
Owen Anderson9eb7cb482011-01-14 22:19:20 +00002187 // A constantexpr bitcast from a pointer to another pointer is a no-op,
2188 // and we know how to evaluate it by moving the bitcast from the pointer
2189 // operand to the value operand.
2190 } else if (CE->getOpcode() == Instruction::BitCast &&
Chris Lattner8b4952f2011-01-16 02:05:10 +00002191 isa<GlobalVariable>(CE->getOperand(0))) {
Owen Anderson9eb7cb482011-01-14 22:19:20 +00002192 // Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or
2193 // external globals.
Chris Lattner8b4952f2011-01-16 02:05:10 +00002194 return cast<GlobalVariable>(CE->getOperand(0))->hasUniqueInitializer();
Chris Lattner46af55e2005-09-26 06:52:44 +00002195 }
Owen Anderson3e2f6cf2011-01-14 22:31:13 +00002196 }
Jakub Staszak9525a772012-12-06 21:57:16 +00002197
Chris Lattner99e23fa2005-09-26 04:44:35 +00002198 return false;
2199}
2200
Chris Lattner46af55e2005-09-26 06:52:44 +00002201/// EvaluateStoreInto - Evaluate a piece of a constantexpr store into a global
2202/// initializer. This returns 'Init' modified to reflect 'Val' stored into it.
2203/// At this point, the GEP operands of Addr [0, OpNo) have been stepped into.
2204static Constant *EvaluateStoreInto(Constant *Init, Constant *Val,
Zhou Sheng8e6d64a2012-12-01 10:54:28 +00002205 ConstantExpr *Addr, unsigned OpNo) {
Chris Lattner46af55e2005-09-26 06:52:44 +00002206 // Base case of the recursion.
2207 if (OpNo == Addr->getNumOperands()) {
2208 assert(Val->getType() == Init->getType() && "Type mismatch!");
2209 return Val;
2210 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002211
Chris Lattner0256be92012-01-27 03:08:05 +00002212 SmallVector<Constant*, 32> Elts;
Chris Lattner229907c2011-07-18 04:54:35 +00002213 if (StructType *STy = dyn_cast<StructType>(Init->getType())) {
Chris Lattner46af55e2005-09-26 06:52:44 +00002214 // Break up the constant into its elements.
Chris Lattnerfa775002012-01-26 02:32:04 +00002215 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
2216 Elts.push_back(Init->getAggregateElement(i));
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002217
Chris Lattner46af55e2005-09-26 06:52:44 +00002218 // Replace the element that we are supposed to.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002219 ConstantInt *CU = cast<ConstantInt>(Addr->getOperand(OpNo));
2220 unsigned Idx = CU->getZExtValue();
2221 assert(Idx < STy->getNumElements() && "Struct index out of range!");
Zhou Sheng8e6d64a2012-12-01 10:54:28 +00002222 Elts[Idx] = EvaluateStoreInto(Elts[Idx], Val, Addr, OpNo+1);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002223
Chris Lattner46af55e2005-09-26 06:52:44 +00002224 // Return the modified struct.
Chris Lattnercc19efa2011-06-20 04:01:31 +00002225 return ConstantStruct::get(STy, Elts);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002226 }
Jakub Staszak9525a772012-12-06 21:57:16 +00002227
Chris Lattnercc19efa2011-06-20 04:01:31 +00002228 ConstantInt *CI = cast<ConstantInt>(Addr->getOperand(OpNo));
Chris Lattner229907c2011-07-18 04:54:35 +00002229 SequentialType *InitTy = cast<SequentialType>(Init->getType());
Chris Lattnercc19efa2011-06-20 04:01:31 +00002230
2231 uint64_t NumElts;
Chris Lattner229907c2011-07-18 04:54:35 +00002232 if (ArrayType *ATy = dyn_cast<ArrayType>(InitTy))
Chris Lattnercc19efa2011-06-20 04:01:31 +00002233 NumElts = ATy->getNumElements();
2234 else
Chris Lattnerfa775002012-01-26 02:32:04 +00002235 NumElts = InitTy->getVectorNumElements();
Chris Lattnercc19efa2011-06-20 04:01:31 +00002236
2237 // Break up the array into elements.
Chris Lattnerfa775002012-01-26 02:32:04 +00002238 for (uint64_t i = 0, e = NumElts; i != e; ++i)
2239 Elts.push_back(Init->getAggregateElement(i));
Chris Lattnercc19efa2011-06-20 04:01:31 +00002240
2241 assert(CI->getZExtValue() < NumElts);
2242 Elts[CI->getZExtValue()] =
Zhou Sheng8e6d64a2012-12-01 10:54:28 +00002243 EvaluateStoreInto(Elts[CI->getZExtValue()], Val, Addr, OpNo+1);
Chris Lattnercc19efa2011-06-20 04:01:31 +00002244
2245 if (Init->getType()->isArrayTy())
2246 return ConstantArray::get(cast<ArrayType>(InitTy), Elts);
2247 return ConstantVector::get(Elts);
Chris Lattner46af55e2005-09-26 06:52:44 +00002248}
2249
Chris Lattner99e23fa2005-09-26 04:44:35 +00002250/// CommitValueTo - We have decided that Addr (which satisfies the predicate
2251/// isSimpleEnoughPointerToCommit) should get Val as its value. Make it happen.
Chris Lattner46b5c642009-11-06 04:27:31 +00002252static void CommitValueTo(Constant *Val, Constant *Addr) {
Chris Lattner46af55e2005-09-26 06:52:44 +00002253 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Addr)) {
2254 assert(GV->hasInitializer());
2255 GV->setInitializer(Val);
2256 return;
2257 }
Chris Lattner64ecc462010-01-07 01:16:21 +00002258
Chris Lattner46af55e2005-09-26 06:52:44 +00002259 ConstantExpr *CE = cast<ConstantExpr>(Addr);
2260 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
Zhou Sheng8e6d64a2012-12-01 10:54:28 +00002261 GV->setInitializer(EvaluateStoreInto(GV->getInitializer(), Val, CE, 2));
Chris Lattner99e23fa2005-09-26 04:44:35 +00002262}
2263
Nick Lewycky60829a582012-02-20 03:25:59 +00002264namespace {
2265
2266/// Evaluator - This class evaluates LLVM IR, producing the Constant
2267/// representing each SSA instruction. Changes to global variables are stored
2268/// in a mapping that can be iterated over after the evaluation is complete.
2269/// Once an evaluation call fails, the evaluation object should not be reused.
2270class Evaluator {
Nick Lewycky73be5e32012-02-19 23:26:27 +00002271public:
Micah Villmowcdfe20b2012-10-08 16:38:25 +00002272 Evaluator(const DataLayout *TD, const TargetLibraryInfo *TLI)
Nick Lewycky73be5e32012-02-19 23:26:27 +00002273 : TD(TD), TLI(TLI) {
2274 ValueStack.push_back(new DenseMap<Value*, Constant*>);
2275 }
2276
Nick Lewycky60829a582012-02-20 03:25:59 +00002277 ~Evaluator() {
Nick Lewycky73be5e32012-02-19 23:26:27 +00002278 DeleteContainerPointers(ValueStack);
2279 while (!AllocaTmps.empty()) {
2280 GlobalVariable *Tmp = AllocaTmps.back();
2281 AllocaTmps.pop_back();
2282
2283 // If there are still users of the alloca, the program is doing something
2284 // silly, e.g. storing the address of the alloca somewhere and using it
2285 // later. Since this is undefined, we'll just make it be null.
2286 if (!Tmp->use_empty())
2287 Tmp->replaceAllUsesWith(Constant::getNullValue(Tmp->getType()));
2288 delete Tmp;
2289 }
2290 }
2291
2292 /// EvaluateFunction - Evaluate a call to function F, returning true if
2293 /// successful, false if we can't evaluate it. ActualArgs contains the formal
2294 /// arguments for the function.
2295 bool EvaluateFunction(Function *F, Constant *&RetVal,
2296 const SmallVectorImpl<Constant*> &ActualArgs);
2297
2298 /// EvaluateBlock - Evaluate all instructions in block BB, returning true if
2299 /// successful, false if we can't evaluate it. NewBB returns the next BB that
2300 /// control flows into, or null upon return.
2301 bool EvaluateBlock(BasicBlock::iterator CurInst, BasicBlock *&NextBB);
2302
2303 Constant *getVal(Value *V) {
2304 if (Constant *CV = dyn_cast<Constant>(V)) return CV;
2305 Constant *R = ValueStack.back()->lookup(V);
2306 assert(R && "Reference to an uncomputed value!");
2307 return R;
2308 }
2309
2310 void setVal(Value *V, Constant *C) {
2311 ValueStack.back()->operator[](V) = C;
2312 }
2313
2314 const DenseMap<Constant*, Constant*> &getMutatedMemory() const {
2315 return MutatedMemory;
2316 }
2317
2318 const SmallPtrSet<GlobalVariable*, 8> &getInvariants() const {
2319 return Invariants;
2320 }
2321
2322private:
2323 Constant *ComputeLoadResult(Constant *P);
2324
2325 /// ValueStack - As we compute SSA register values, we store their contents
2326 /// here. The back of the vector contains the current function and the stack
2327 /// contains the values in the calling frames.
2328 SmallVector<DenseMap<Value*, Constant*>*, 4> ValueStack;
2329
2330 /// CallStack - This is used to detect recursion. In pathological situations
2331 /// we could hit exponential behavior, but at least there is nothing
2332 /// unbounded.
2333 SmallVector<Function*, 4> CallStack;
2334
2335 /// MutatedMemory - For each store we execute, we update this map. Loads
2336 /// check this to get the most up-to-date value. If evaluation is successful,
2337 /// this state is committed to the process.
2338 DenseMap<Constant*, Constant*> MutatedMemory;
2339
2340 /// AllocaTmps - To 'execute' an alloca, we create a temporary global variable
2341 /// to represent its body. This vector is needed so we can delete the
2342 /// temporary globals when we are done.
2343 SmallVector<GlobalVariable*, 32> AllocaTmps;
2344
2345 /// Invariants - These global variables have been marked invariant by the
2346 /// static constructor.
2347 SmallPtrSet<GlobalVariable*, 8> Invariants;
2348
2349 /// SimpleConstants - These are constants we have checked and know to be
2350 /// simple enough to live in a static initializer of a global.
2351 SmallPtrSet<Constant*, 8> SimpleConstants;
2352
Micah Villmowcdfe20b2012-10-08 16:38:25 +00002353 const DataLayout *TD;
Nick Lewycky73be5e32012-02-19 23:26:27 +00002354 const TargetLibraryInfo *TLI;
2355};
2356
Nick Lewycky60829a582012-02-20 03:25:59 +00002357} // anonymous namespace
2358
Chris Lattnerb0096632005-09-26 05:16:34 +00002359/// ComputeLoadResult - Return the value that would be computed by a load from
2360/// P after the stores reflected by 'memory' have been performed. If we can't
2361/// decide, return null.
Nick Lewycky60829a582012-02-20 03:25:59 +00002362Constant *Evaluator::ComputeLoadResult(Constant *P) {
Chris Lattner4b05c322005-09-26 05:15:37 +00002363 // If this memory location has been recently stored, use the stored value: it
2364 // is the most up-to-date.
Nick Lewycky73be5e32012-02-19 23:26:27 +00002365 DenseMap<Constant*, Constant*>::const_iterator I = MutatedMemory.find(P);
2366 if (I != MutatedMemory.end()) return I->second;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002367
Chris Lattner4b05c322005-09-26 05:15:37 +00002368 // Access it.
2369 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(P)) {
Dan Gohman5d5bc6d2009-08-19 18:20:44 +00002370 if (GV->hasDefinitiveInitializer())
Chris Lattner4b05c322005-09-26 05:15:37 +00002371 return GV->getInitializer();
2372 return 0;
Chris Lattner4b05c322005-09-26 05:15:37 +00002373 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002374
Chris Lattner46af55e2005-09-26 06:52:44 +00002375 // Handle a constantexpr getelementptr.
2376 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(P))
2377 if (CE->getOpcode() == Instruction::GetElementPtr &&
2378 isa<GlobalVariable>(CE->getOperand(0))) {
2379 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
Dan Gohman5d5bc6d2009-08-19 18:20:44 +00002380 if (GV->hasDefinitiveInitializer())
Dan Gohmane525d9d2009-10-05 16:36:26 +00002381 return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
Chris Lattner46af55e2005-09-26 06:52:44 +00002382 }
2383
2384 return 0; // don't know how to evaluate.
Chris Lattner4b05c322005-09-26 05:15:37 +00002385}
2386
Nick Lewycky239fdf02012-02-06 08:24:44 +00002387/// EvaluateBlock - Evaluate all instructions in block BB, returning true if
2388/// successful, false if we can't evaluate it. NewBB returns the next BB that
2389/// control flows into, or null upon return.
Nick Lewycky60829a582012-02-20 03:25:59 +00002390bool Evaluator::EvaluateBlock(BasicBlock::iterator CurInst,
2391 BasicBlock *&NextBB) {
Chris Lattner99e23fa2005-09-26 04:44:35 +00002392 // This is the main evaluation loop.
2393 while (1) {
2394 Constant *InstResult = 0;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002395
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002396 DEBUG(dbgs() << "Evaluating Instruction: " << *CurInst << "\n");
2397
Chris Lattner99e23fa2005-09-26 04:44:35 +00002398 if (StoreInst *SI = dyn_cast<StoreInst>(CurInst)) {
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002399 if (!SI->isSimple()) {
Michael Gottesman2a654272013-01-11 23:08:52 +00002400 DEBUG(dbgs() << "Store is not simple! Can not evaluate.\n");
2401 return false; // no volatile/atomic accesses.
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002402 }
Nick Lewycky73be5e32012-02-19 23:26:27 +00002403 Constant *Ptr = getVal(SI->getOperand(1));
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002404 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
Michael Gottesman2a654272013-01-11 23:08:52 +00002405 DEBUG(dbgs() << "Folding constant ptr expression: " << *Ptr);
Nick Lewycky9d0da182012-02-21 22:08:06 +00002406 Ptr = ConstantFoldConstantExpression(CE, TD, TLI);
Michael Gottesman2a654272013-01-11 23:08:52 +00002407 DEBUG(dbgs() << "; To: " << *Ptr << "\n");
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002408 }
2409 if (!isSimpleEnoughPointerToCommit(Ptr)) {
Chris Lattner99e23fa2005-09-26 04:44:35 +00002410 // If this is too complex for us to commit, reject it.
Michael Gottesman2a654272013-01-11 23:08:52 +00002411 DEBUG(dbgs() << "Pointer is too complex for us to evaluate store.");
Chris Lattner65a3a092005-09-27 04:45:34 +00002412 return false;
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002413 }
Jakub Staszak9525a772012-12-06 21:57:16 +00002414
Nick Lewycky73be5e32012-02-19 23:26:27 +00002415 Constant *Val = getVal(SI->getOperand(0));
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002416
2417 // If this might be too difficult for the backend to handle (e.g. the addr
2418 // of one global variable divided by another) then we can't commit it.
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002419 if (!isSimpleEnoughValueToCommit(Val, SimpleConstants, TD)) {
Michael Gottesman2a654272013-01-11 23:08:52 +00002420 DEBUG(dbgs() << "Store value is too complex to evaluate store. " << *Val
2421 << "\n");
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002422 return false;
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002423 }
Jakub Staszak9525a772012-12-06 21:57:16 +00002424
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002425 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
Owen Anderson9eb7cb482011-01-14 22:19:20 +00002426 if (CE->getOpcode() == Instruction::BitCast) {
Michael Gottesman2a654272013-01-11 23:08:52 +00002427 DEBUG(dbgs() << "Attempting to resolve bitcast on constant ptr.\n");
Owen Anderson9eb7cb482011-01-14 22:19:20 +00002428 // If we're evaluating a store through a bitcast, then we need
2429 // to pull the bitcast off the pointer type and push it onto the
2430 // stored value.
Chris Lattner8b4952f2011-01-16 02:05:10 +00002431 Ptr = CE->getOperand(0);
Jakub Staszak9525a772012-12-06 21:57:16 +00002432
Nick Lewycky239fdf02012-02-06 08:24:44 +00002433 Type *NewTy = cast<PointerType>(Ptr->getType())->getElementType();
Jakub Staszak9525a772012-12-06 21:57:16 +00002434
Owen Anderson4e54efd2011-01-16 04:33:33 +00002435 // In order to push the bitcast onto the stored value, a bitcast
2436 // from NewTy to Val's type must be legal. If it's not, we can try
2437 // introspecting NewTy to find a legal conversion.
2438 while (!Val->getType()->canLosslesslyBitCastTo(NewTy)) {
2439 // If NewTy is a struct, we can convert the pointer to the struct
2440 // into a pointer to its first member.
2441 // FIXME: This could be extended to support arrays as well.
Chris Lattner229907c2011-07-18 04:54:35 +00002442 if (StructType *STy = dyn_cast<StructType>(NewTy)) {
Owen Anderson4e54efd2011-01-16 04:33:33 +00002443 NewTy = STy->getTypeAtIndex(0U);
2444
Nick Lewycky239fdf02012-02-06 08:24:44 +00002445 IntegerType *IdxTy = IntegerType::get(NewTy->getContext(), 32);
Owen Anderson4e54efd2011-01-16 04:33:33 +00002446 Constant *IdxZero = ConstantInt::get(IdxTy, 0, false);
2447 Constant * const IdxList[] = {IdxZero, IdxZero};
2448
Jay Foad17bab442011-07-22 08:52:50 +00002449 Ptr = ConstantExpr::getGetElementPtr(Ptr, IdxList);
Nick Lewycky9d0da182012-02-21 22:08:06 +00002450 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
2451 Ptr = ConstantFoldConstantExpression(CE, TD, TLI);
2452
Owen Anderson4e54efd2011-01-16 04:33:33 +00002453 // If we can't improve the situation by introspecting NewTy,
2454 // we have to give up.
2455 } else {
Michael Gottesman2a654272013-01-11 23:08:52 +00002456 DEBUG(dbgs() << "Failed to bitcast constant ptr, can not "
2457 "evaluate.\n");
Nick Lewycky239fdf02012-02-06 08:24:44 +00002458 return false;
Owen Anderson4e54efd2011-01-16 04:33:33 +00002459 }
Owen Anderson9eb7cb482011-01-14 22:19:20 +00002460 }
Jakub Staszak9525a772012-12-06 21:57:16 +00002461
Owen Anderson4e54efd2011-01-16 04:33:33 +00002462 // If we found compatible types, go ahead and push the bitcast
2463 // onto the stored value.
Owen Anderson9eb7cb482011-01-14 22:19:20 +00002464 Val = ConstantExpr::getBitCast(Val, NewTy);
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002465
Michael Gottesman2a654272013-01-11 23:08:52 +00002466 DEBUG(dbgs() << "Evaluated bitcast: " << *Val << "\n");
Owen Anderson9eb7cb482011-01-14 22:19:20 +00002467 }
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002468 }
Jakub Staszak9525a772012-12-06 21:57:16 +00002469
Chris Lattner99e23fa2005-09-26 04:44:35 +00002470 MutatedMemory[Ptr] = Val;
2471 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CurInst)) {
Owen Anderson487375e2009-07-29 18:55:55 +00002472 InstResult = ConstantExpr::get(BO->getOpcode(),
Nick Lewycky73be5e32012-02-19 23:26:27 +00002473 getVal(BO->getOperand(0)),
2474 getVal(BO->getOperand(1)));
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002475 DEBUG(dbgs() << "Found a BinaryOperator! Simplifying: " << *InstResult
Michael Gottesman2a654272013-01-11 23:08:52 +00002476 << "\n");
Reid Spencer266e42b2006-12-23 06:05:41 +00002477 } else if (CmpInst *CI = dyn_cast<CmpInst>(CurInst)) {
Owen Anderson487375e2009-07-29 18:55:55 +00002478 InstResult = ConstantExpr::getCompare(CI->getPredicate(),
Nick Lewycky73be5e32012-02-19 23:26:27 +00002479 getVal(CI->getOperand(0)),
2480 getVal(CI->getOperand(1)));
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002481 DEBUG(dbgs() << "Found a CmpInst! Simplifying: " << *InstResult
Michael Gottesman2a654272013-01-11 23:08:52 +00002482 << "\n");
Chris Lattner99e23fa2005-09-26 04:44:35 +00002483 } else if (CastInst *CI = dyn_cast<CastInst>(CurInst)) {
Owen Anderson487375e2009-07-29 18:55:55 +00002484 InstResult = ConstantExpr::getCast(CI->getOpcode(),
Nick Lewycky73be5e32012-02-19 23:26:27 +00002485 getVal(CI->getOperand(0)),
Chris Lattner99e23fa2005-09-26 04:44:35 +00002486 CI->getType());
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002487 DEBUG(dbgs() << "Found a Cast! Simplifying: " << *InstResult
Michael Gottesman2a654272013-01-11 23:08:52 +00002488 << "\n");
Chris Lattner99e23fa2005-09-26 04:44:35 +00002489 } else if (SelectInst *SI = dyn_cast<SelectInst>(CurInst)) {
Nick Lewycky73be5e32012-02-19 23:26:27 +00002490 InstResult = ConstantExpr::getSelect(getVal(SI->getOperand(0)),
2491 getVal(SI->getOperand(1)),
2492 getVal(SI->getOperand(2)));
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002493 DEBUG(dbgs() << "Found a Select! Simplifying: " << *InstResult
Michael Gottesman2a654272013-01-11 23:08:52 +00002494 << "\n");
Chris Lattner4b05c322005-09-26 05:15:37 +00002495 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurInst)) {
Nick Lewycky73be5e32012-02-19 23:26:27 +00002496 Constant *P = getVal(GEP->getOperand(0));
Chris Lattnerf96f4a82007-01-31 04:40:53 +00002497 SmallVector<Constant*, 8> GEPOps;
Gabor Greif3a9fba52008-05-29 01:59:18 +00002498 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end();
2499 i != e; ++i)
Nick Lewycky73be5e32012-02-19 23:26:27 +00002500 GEPOps.push_back(getVal(*i));
Jay Foad2f5fc8c2011-07-21 15:15:37 +00002501 InstResult =
2502 ConstantExpr::getGetElementPtr(P, GEPOps,
2503 cast<GEPOperator>(GEP)->isInBounds());
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002504 DEBUG(dbgs() << "Found a GEP! Simplifying: " << *InstResult
Michael Gottesman2a654272013-01-11 23:08:52 +00002505 << "\n");
Chris Lattner4b05c322005-09-26 05:15:37 +00002506 } else if (LoadInst *LI = dyn_cast<LoadInst>(CurInst)) {
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002507
2508 if (!LI->isSimple()) {
Michael Gottesman2a654272013-01-11 23:08:52 +00002509 DEBUG(dbgs() << "Found a Load! Not a simple load, can not evaluate.\n");
2510 return false; // no volatile/atomic accesses.
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002511 }
2512
Nick Lewycky9d0da182012-02-21 22:08:06 +00002513 Constant *Ptr = getVal(LI->getOperand(0));
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002514 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
Nick Lewycky9d0da182012-02-21 22:08:06 +00002515 Ptr = ConstantFoldConstantExpression(CE, TD, TLI);
Michael Gottesman2a654272013-01-11 23:08:52 +00002516 DEBUG(dbgs() << "Found a constant pointer expression, constant "
2517 "folding: " << *Ptr << "\n");
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002518 }
Nick Lewycky9d0da182012-02-21 22:08:06 +00002519 InstResult = ComputeLoadResult(Ptr);
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002520 if (InstResult == 0) {
Michael Gottesman2a654272013-01-11 23:08:52 +00002521 DEBUG(dbgs() << "Failed to compute load result. Can not evaluate load."
2522 "\n");
2523 return false; // Could not evaluate load.
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002524 }
2525
2526 DEBUG(dbgs() << "Evaluated load: " << *InstResult << "\n");
Chris Lattner6bf2cd52005-09-26 17:07:09 +00002527 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(CurInst)) {
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002528 if (AI->isArrayAllocation()) {
Michael Gottesman2a654272013-01-11 23:08:52 +00002529 DEBUG(dbgs() << "Found an array alloca. Can not evaluate.\n");
2530 return false; // Cannot handle array allocs.
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002531 }
Chris Lattner229907c2011-07-18 04:54:35 +00002532 Type *Ty = AI->getType()->getElementType();
Chris Lattner46b5c642009-11-06 04:27:31 +00002533 AllocaTmps.push_back(new GlobalVariable(Ty, false,
Chris Lattner6bf2cd52005-09-26 17:07:09 +00002534 GlobalValue::InternalLinkage,
Owen Andersonb292b8c2009-07-30 23:03:37 +00002535 UndefValue::get(Ty),
Chris Lattner6bf2cd52005-09-26 17:07:09 +00002536 AI->getName()));
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002537 InstResult = AllocaTmps.back();
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002538 DEBUG(dbgs() << "Found an alloca. Result: " << *InstResult << "\n");
Nick Lewyckyc1572e42012-02-12 05:09:35 +00002539 } else if (isa<CallInst>(CurInst) || isa<InvokeInst>(CurInst)) {
2540 CallSite CS(CurInst);
Devang Patel04852aa2009-03-09 23:04:12 +00002541
2542 // Debug info can safely be ignored here.
Nick Lewyckyc1572e42012-02-12 05:09:35 +00002543 if (isa<DbgInfoIntrinsic>(CS.getInstruction())) {
Michael Gottesman2a654272013-01-11 23:08:52 +00002544 DEBUG(dbgs() << "Ignoring debug info.\n");
Devang Patel04852aa2009-03-09 23:04:12 +00002545 ++CurInst;
2546 continue;
2547 }
2548
Chris Lattnerfd2e13b2006-07-07 21:37:01 +00002549 // Cannot handle inline asm.
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002550 if (isa<InlineAsm>(CS.getCalledValue())) {
Michael Gottesman2a654272013-01-11 23:08:52 +00002551 DEBUG(dbgs() << "Found inline asm, can not evaluate.\n");
2552 return false;
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002553 }
Chris Lattnerfd2e13b2006-07-07 21:37:01 +00002554
Nick Lewycky68f9f9d2012-02-17 06:59:21 +00002555 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CS.getInstruction())) {
2556 if (MemSetInst *MSI = dyn_cast<MemSetInst>(II)) {
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002557 if (MSI->isVolatile()) {
Michael Gottesman2a654272013-01-11 23:08:52 +00002558 DEBUG(dbgs() << "Can not optimize a volatile memset " <<
2559 "intrinsic.\n");
2560 return false;
2561 }
Nick Lewycky73be5e32012-02-19 23:26:27 +00002562 Constant *Ptr = getVal(MSI->getDest());
2563 Constant *Val = getVal(MSI->getValue());
2564 Constant *DestVal = ComputeLoadResult(getVal(Ptr));
Nick Lewycky68f9f9d2012-02-17 06:59:21 +00002565 if (Val->isNullValue() && DestVal && DestVal->isNullValue()) {
2566 // This memset is a no-op.
Michael Gottesman2a654272013-01-11 23:08:52 +00002567 DEBUG(dbgs() << "Ignoring no-op memset.\n");
Nick Lewycky68f9f9d2012-02-17 06:59:21 +00002568 ++CurInst;
2569 continue;
2570 }
2571 }
2572
2573 if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
2574 II->getIntrinsicID() == Intrinsic::lifetime_end) {
Michael Gottesman2a654272013-01-11 23:08:52 +00002575 DEBUG(dbgs() << "Ignoring lifetime intrinsic.\n");
Nick Lewycky68f9f9d2012-02-17 06:59:21 +00002576 ++CurInst;
2577 continue;
2578 }
2579
2580 if (II->getIntrinsicID() == Intrinsic::invariant_start) {
2581 // We don't insert an entry into Values, as it doesn't have a
2582 // meaningful return value.
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002583 if (!II->use_empty()) {
Alp Tokerf907b892013-12-05 05:44:44 +00002584 DEBUG(dbgs() << "Found unused invariant_start. Can't evaluate.\n");
Nick Lewycky68f9f9d2012-02-17 06:59:21 +00002585 return false;
Michael Gottesman2a654272013-01-11 23:08:52 +00002586 }
Nick Lewycky68f9f9d2012-02-17 06:59:21 +00002587 ConstantInt *Size = cast<ConstantInt>(II->getArgOperand(0));
Nick Lewycky519561f2012-02-20 23:32:26 +00002588 Value *PtrArg = getVal(II->getArgOperand(1));
2589 Value *Ptr = PtrArg->stripPointerCasts();
2590 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr)) {
2591 Type *ElemTy = cast<PointerType>(GV->getType())->getElementType();
Nick Lewycky5b150372013-07-25 02:55:14 +00002592 if (TD && !Size->isAllOnesValue() &&
Nick Lewycky519561f2012-02-20 23:32:26 +00002593 Size->getValue().getLimitedValue() >=
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002594 TD->getTypeStoreSize(ElemTy)) {
Nick Lewycky68f9f9d2012-02-17 06:59:21 +00002595 Invariants.insert(GV);
Michael Gottesman2a654272013-01-11 23:08:52 +00002596 DEBUG(dbgs() << "Found a global var that is an invariant: " << *GV
2597 << "\n");
2598 } else {
2599 DEBUG(dbgs() << "Found a global var, but can not treat it as an "
2600 "invariant.\n");
2601 }
Nick Lewycky68f9f9d2012-02-17 06:59:21 +00002602 }
2603 // Continue even if we do nothing.
Nick Lewyckya3bb03e2011-05-29 18:41:56 +00002604 ++CurInst;
2605 continue;
2606 }
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002607
Michael Gottesman2a654272013-01-11 23:08:52 +00002608 DEBUG(dbgs() << "Unknown intrinsic. Can not evaluate.\n");
Nick Lewyckya3bb03e2011-05-29 18:41:56 +00002609 return false;
2610 }
2611
Chris Lattner65a3a092005-09-27 04:45:34 +00002612 // Resolve function pointers.
Nick Lewycky73be5e32012-02-19 23:26:27 +00002613 Function *Callee = dyn_cast<Function>(getVal(CS.getCalledValue()));
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002614 if (!Callee || Callee->mayBeOverridden()) {
Michael Gottesman2a654272013-01-11 23:08:52 +00002615 DEBUG(dbgs() << "Can not resolve function pointer.\n");
Nick Lewyckyc1572e42012-02-12 05:09:35 +00002616 return false; // Cannot resolve.
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002617 }
Chris Lattner3d27e7f2005-09-27 05:02:43 +00002618
Duncan Sandsc4ce58d82009-08-17 14:33:27 +00002619 SmallVector<Constant*, 8> Formals;
Nick Lewyckyc1572e42012-02-12 05:09:35 +00002620 for (User::op_iterator i = CS.arg_begin(), e = CS.arg_end(); i != e; ++i)
Nick Lewycky73be5e32012-02-19 23:26:27 +00002621 Formals.push_back(getVal(*i));
Duncan Sandsc4ce58d82009-08-17 14:33:27 +00002622
Reid Spencer5301e7c2007-01-30 20:08:39 +00002623 if (Callee->isDeclaration()) {
Chris Lattner3d27e7f2005-09-27 05:02:43 +00002624 // If this is a function we can constant fold, do it.
Chad Rosiere6de63d2011-12-01 21:29:16 +00002625 if (Constant *C = ConstantFoldCall(Callee, Formals, TLI)) {
Chris Lattner3d27e7f2005-09-27 05:02:43 +00002626 InstResult = C;
Michael Gottesman2a654272013-01-11 23:08:52 +00002627 DEBUG(dbgs() << "Constant folded function call. Result: " <<
2628 *InstResult << "\n");
Chris Lattner3d27e7f2005-09-27 05:02:43 +00002629 } else {
Michael Gottesman2a654272013-01-11 23:08:52 +00002630 DEBUG(dbgs() << "Can not constant fold function call.\n");
Chris Lattner3d27e7f2005-09-27 05:02:43 +00002631 return false;
2632 }
2633 } else {
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002634 if (Callee->getFunctionType()->isVarArg()) {
Michael Gottesman2a654272013-01-11 23:08:52 +00002635 DEBUG(dbgs() << "Can not constant fold vararg function call.\n");
Chris Lattner3d27e7f2005-09-27 05:02:43 +00002636 return false;
Michael Gottesman2a654272013-01-11 23:08:52 +00002637 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002638
Benjamin Kramer64a857a2013-01-12 15:34:31 +00002639 Constant *RetVal = 0;
Chris Lattner3d27e7f2005-09-27 05:02:43 +00002640 // Execute the call, if successful, use the return value.
Nick Lewycky73be5e32012-02-19 23:26:27 +00002641 ValueStack.push_back(new DenseMap<Value*, Constant*>);
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002642 if (!EvaluateFunction(Callee, RetVal, Formals)) {
Michael Gottesman2a654272013-01-11 23:08:52 +00002643 DEBUG(dbgs() << "Failed to evaluate function.\n");
Chris Lattner3d27e7f2005-09-27 05:02:43 +00002644 return false;
Michael Gottesman2a654272013-01-11 23:08:52 +00002645 }
Benjamin Kramer93887632012-02-27 12:48:24 +00002646 delete ValueStack.pop_back_val();
Chris Lattner3d27e7f2005-09-27 05:02:43 +00002647 InstResult = RetVal;
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002648
Michael Gottesman2a654272013-01-11 23:08:52 +00002649 if (InstResult != NULL) {
2650 DEBUG(dbgs() << "Successfully evaluated function. Result: " <<
2651 InstResult << "\n\n");
2652 } else {
2653 DEBUG(dbgs() << "Successfully evaluated function. Result: 0\n\n");
2654 }
Chris Lattner3d27e7f2005-09-27 05:02:43 +00002655 }
Reid Spencerde46e482006-11-02 20:25:50 +00002656 } else if (isa<TerminatorInst>(CurInst)) {
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002657 DEBUG(dbgs() << "Found a terminator instruction.\n");
2658
Chris Lattner3e9ea5f2005-09-26 04:57:38 +00002659 if (BranchInst *BI = dyn_cast<BranchInst>(CurInst)) {
2660 if (BI->isUnconditional()) {
Nick Lewycky239fdf02012-02-06 08:24:44 +00002661 NextBB = BI->getSuccessor(0);
Chris Lattner3e9ea5f2005-09-26 04:57:38 +00002662 } else {
Zhou Sheng75b871f2007-01-11 12:24:14 +00002663 ConstantInt *Cond =
Nick Lewycky73be5e32012-02-19 23:26:27 +00002664 dyn_cast<ConstantInt>(getVal(BI->getCondition()));
Chris Lattner15649082007-01-12 18:30:11 +00002665 if (!Cond) return false; // Cannot determine.
Zhou Sheng75b871f2007-01-11 12:24:14 +00002666
Nick Lewycky239fdf02012-02-06 08:24:44 +00002667 NextBB = BI->getSuccessor(!Cond->getZExtValue());
Chris Lattner3e9ea5f2005-09-26 04:57:38 +00002668 }
2669 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(CurInst)) {
2670 ConstantInt *Val =
Nick Lewycky73be5e32012-02-19 23:26:27 +00002671 dyn_cast<ConstantInt>(getVal(SI->getCondition()));
Chris Lattner65a3a092005-09-27 04:45:34 +00002672 if (!Val) return false; // Cannot determine.
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00002673 NextBB = SI->findCaseValue(Val).getCaseSuccessor();
Chris Lattner31274882009-10-29 05:51:50 +00002674 } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(CurInst)) {
Nick Lewycky73be5e32012-02-19 23:26:27 +00002675 Value *Val = getVal(IBI->getAddress())->stripPointerCasts();
Chris Lattner31274882009-10-29 05:51:50 +00002676 if (BlockAddress *BA = dyn_cast<BlockAddress>(Val))
Nick Lewycky239fdf02012-02-06 08:24:44 +00002677 NextBB = BA->getBasicBlock();
Chris Lattneraa99c942009-11-01 01:27:45 +00002678 else
2679 return false; // Cannot determine.
Nick Lewycky239fdf02012-02-06 08:24:44 +00002680 } else if (isa<ReturnInst>(CurInst)) {
2681 NextBB = 0;
Chris Lattner3e9ea5f2005-09-26 04:57:38 +00002682 } else {
Bill Wendlingf891bf82011-07-31 06:30:59 +00002683 // invoke, unwind, resume, unreachable.
Michael Gottesman2a654272013-01-11 23:08:52 +00002684 DEBUG(dbgs() << "Can not handle terminator.");
Chris Lattner65a3a092005-09-27 04:45:34 +00002685 return false; // Cannot handle this terminator.
Chris Lattner3e9ea5f2005-09-26 04:57:38 +00002686 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002687
Nick Lewycky239fdf02012-02-06 08:24:44 +00002688 // We succeeded at evaluating this block!
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002689 DEBUG(dbgs() << "Successfully evaluated block.\n");
Nick Lewycky239fdf02012-02-06 08:24:44 +00002690 return true;
Chris Lattner99e23fa2005-09-26 04:44:35 +00002691 } else {
Chris Lattner99e23fa2005-09-26 04:44:35 +00002692 // Did not know how to evaluate this!
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002693 DEBUG(dbgs() << "Failed to evaluate block due to unhandled instruction."
Michael Gottesman2a654272013-01-11 23:08:52 +00002694 "\n");
Chris Lattner65a3a092005-09-27 04:45:34 +00002695 return false;
Chris Lattner99e23fa2005-09-26 04:44:35 +00002696 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002697
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002698 if (!CurInst->use_empty()) {
2699 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(InstResult))
Chad Rosier43a33062011-12-02 01:26:24 +00002700 InstResult = ConstantFoldConstantExpression(CE, TD, TLI);
Jakub Staszak9525a772012-12-06 21:57:16 +00002701
Nick Lewycky73be5e32012-02-19 23:26:27 +00002702 setVal(CurInst, InstResult);
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002703 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002704
Dan Gohmaneab06fa2012-03-13 18:01:37 +00002705 // If we just processed an invoke, we finished evaluating the block.
2706 if (InvokeInst *II = dyn_cast<InvokeInst>(CurInst)) {
2707 NextBB = II->getNormalDest();
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002708 DEBUG(dbgs() << "Found an invoke instruction. Finished Block.\n\n");
Dan Gohmaneab06fa2012-03-13 18:01:37 +00002709 return true;
2710 }
2711
Chris Lattner99e23fa2005-09-26 04:44:35 +00002712 // Advance program counter.
2713 ++CurInst;
2714 }
Chris Lattnerda1889b2005-09-27 04:27:01 +00002715}
2716
Nick Lewycky239fdf02012-02-06 08:24:44 +00002717/// EvaluateFunction - Evaluate a call to function F, returning true if
2718/// successful, false if we can't evaluate it. ActualArgs contains the formal
2719/// arguments for the function.
Nick Lewycky60829a582012-02-20 03:25:59 +00002720bool Evaluator::EvaluateFunction(Function *F, Constant *&RetVal,
2721 const SmallVectorImpl<Constant*> &ActualArgs) {
Nick Lewycky239fdf02012-02-06 08:24:44 +00002722 // Check to see if this function is already executing (recursion). If so,
2723 // bail out. TODO: we might want to accept limited recursion.
2724 if (std::find(CallStack.begin(), CallStack.end(), F) != CallStack.end())
2725 return false;
2726
2727 CallStack.push_back(F);
2728
Nick Lewycky239fdf02012-02-06 08:24:44 +00002729 // Initialize arguments to the incoming values specified.
2730 unsigned ArgNo = 0;
2731 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); AI != E;
2732 ++AI, ++ArgNo)
Nick Lewycky73be5e32012-02-19 23:26:27 +00002733 setVal(AI, ActualArgs[ArgNo]);
Nick Lewycky239fdf02012-02-06 08:24:44 +00002734
2735 // ExecutedBlocks - We only handle non-looping, non-recursive code. As such,
2736 // we can only evaluate any one basic block at most once. This set keeps
2737 // track of what we have executed so we can detect recursive cases etc.
2738 SmallPtrSet<BasicBlock*, 32> ExecutedBlocks;
2739
2740 // CurBB - The current basic block we're evaluating.
2741 BasicBlock *CurBB = F->begin();
2742
Nick Lewycky4231c412012-02-12 00:47:24 +00002743 BasicBlock::iterator CurInst = CurBB->begin();
2744
Nick Lewycky239fdf02012-02-06 08:24:44 +00002745 while (1) {
Duncan Sands4730cb92012-02-23 08:23:06 +00002746 BasicBlock *NextBB = 0; // Initialized to avoid compiler warnings.
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002747 DEBUG(dbgs() << "Trying to evaluate BB: " << *CurBB << "\n");
2748
Nick Lewycky73be5e32012-02-19 23:26:27 +00002749 if (!EvaluateBlock(CurInst, NextBB))
Nick Lewycky239fdf02012-02-06 08:24:44 +00002750 return false;
2751
2752 if (NextBB == 0) {
2753 // Successfully running until there's no next block means that we found
2754 // the return. Fill it the return value and pop the call stack.
2755 ReturnInst *RI = cast<ReturnInst>(CurBB->getTerminator());
2756 if (RI->getNumOperands())
Nick Lewycky73be5e32012-02-19 23:26:27 +00002757 RetVal = getVal(RI->getOperand(0));
Nick Lewycky239fdf02012-02-06 08:24:44 +00002758 CallStack.pop_back();
2759 return true;
2760 }
2761
2762 // Okay, we succeeded in evaluating this control flow. See if we have
2763 // executed the new block before. If so, we have a looping function,
2764 // which we cannot evaluate in reasonable time.
2765 if (!ExecutedBlocks.insert(NextBB))
2766 return false; // looped!
2767
2768 // Okay, we have never been in this block before. Check to see if there
2769 // are any PHI nodes. If so, evaluate them with information about where
2770 // we came from.
2771 PHINode *PN = 0;
Nick Lewycky4231c412012-02-12 00:47:24 +00002772 for (CurInst = NextBB->begin();
2773 (PN = dyn_cast<PHINode>(CurInst)); ++CurInst)
Nick Lewycky73be5e32012-02-19 23:26:27 +00002774 setVal(PN, getVal(PN->getIncomingValueForBlock(CurBB)));
Nick Lewycky239fdf02012-02-06 08:24:44 +00002775
2776 // Advance to the next block.
2777 CurBB = NextBB;
2778 }
2779}
2780
Chris Lattnerda1889b2005-09-27 04:27:01 +00002781/// EvaluateStaticConstructor - Evaluate static constructors in the function, if
2782/// we can. Return true if we can, false otherwise.
Micah Villmowcdfe20b2012-10-08 16:38:25 +00002783static bool EvaluateStaticConstructor(Function *F, const DataLayout *TD,
Chad Rosiere6de63d2011-12-01 21:29:16 +00002784 const TargetLibraryInfo *TLI) {
Chris Lattnerda1889b2005-09-27 04:27:01 +00002785 // Call the function.
Nick Lewycky60829a582012-02-20 03:25:59 +00002786 Evaluator Eval(TD, TLI);
Chris Lattner65a3a092005-09-27 04:45:34 +00002787 Constant *RetValDummy;
Nick Lewycky73be5e32012-02-19 23:26:27 +00002788 bool EvalSuccess = Eval.EvaluateFunction(F, RetValDummy,
2789 SmallVector<Constant*, 0>());
Jakub Staszak9525a772012-12-06 21:57:16 +00002790
Chris Lattnerda1889b2005-09-27 04:27:01 +00002791 if (EvalSuccess) {
Chris Lattner6bf2cd52005-09-26 17:07:09 +00002792 // We succeeded at evaluation: commit the result.
David Greene44cb8ad2010-01-05 01:28:05 +00002793 DEBUG(dbgs() << "FULLY EVALUATED GLOBAL CTOR FUNCTION '"
Nick Lewycky73be5e32012-02-19 23:26:27 +00002794 << F->getName() << "' to " << Eval.getMutatedMemory().size()
Daniel Dunbar0dd5e1e2009-07-25 00:23:56 +00002795 << " stores.\n");
Nick Lewycky73be5e32012-02-19 23:26:27 +00002796 for (DenseMap<Constant*, Constant*>::const_iterator I =
2797 Eval.getMutatedMemory().begin(), E = Eval.getMutatedMemory().end();
Nick Lewyckyb74ae9c2012-06-24 04:07:14 +00002798 I != E; ++I)
Chris Lattner46b5c642009-11-06 04:27:31 +00002799 CommitValueTo(I->second, I->first);
Nick Lewycky73be5e32012-02-19 23:26:27 +00002800 for (SmallPtrSet<GlobalVariable*, 8>::const_iterator I =
2801 Eval.getInvariants().begin(), E = Eval.getInvariants().end();
2802 I != E; ++I)
Nick Lewycky68f9f9d2012-02-17 06:59:21 +00002803 (*I)->setConstant(true);
Chris Lattner6bf2cd52005-09-26 17:07:09 +00002804 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002805
Chris Lattnerda1889b2005-09-27 04:27:01 +00002806 return EvalSuccess;
Chris Lattner99e23fa2005-09-26 04:44:35 +00002807}
2808
Chris Lattner41b6a5a2005-09-26 01:43:45 +00002809/// OptimizeGlobalCtorsList - Simplify and evaluation global ctors if possible.
2810/// Return true if anything changed.
2811bool GlobalOpt::OptimizeGlobalCtorsList(GlobalVariable *&GCL) {
2812 std::vector<Function*> Ctors = ParseGlobalCtors(GCL);
2813 bool MadeChange = false;
2814 if (Ctors.empty()) return false;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002815
Chris Lattner41b6a5a2005-09-26 01:43:45 +00002816 // Loop over global ctors, optimizing them when we can.
2817 for (unsigned i = 0; i != Ctors.size(); ++i) {
2818 Function *F = Ctors[i];
2819 // Found a null terminator in the middle of the list, prune off the rest of
2820 // the list.
Chris Lattner838bdc12005-09-26 02:19:27 +00002821 if (F == 0) {
2822 if (i != Ctors.size()-1) {
2823 Ctors.resize(i+1);
2824 MadeChange = true;
2825 }
Chris Lattner41b6a5a2005-09-26 01:43:45 +00002826 break;
2827 }
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002828 DEBUG(dbgs() << "Optimizing Global Constructor: " << *F << "\n");
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002829
Chris Lattner99e23fa2005-09-26 04:44:35 +00002830 // We cannot simplify external ctor functions.
2831 if (F->empty()) continue;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002832
Chris Lattner99e23fa2005-09-26 04:44:35 +00002833 // If we can evaluate the ctor at compile time, do.
Chad Rosiere6de63d2011-12-01 21:29:16 +00002834 if (EvaluateStaticConstructor(F, TD, TLI)) {
Chris Lattner99e23fa2005-09-26 04:44:35 +00002835 Ctors.erase(Ctors.begin()+i);
2836 MadeChange = true;
2837 --i;
2838 ++NumCtorsEvaluated;
2839 continue;
2840 }
Chris Lattner41b6a5a2005-09-26 01:43:45 +00002841 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002842
Chris Lattner41b6a5a2005-09-26 01:43:45 +00002843 if (!MadeChange) return false;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002844
Chris Lattner46b5c642009-11-06 04:27:31 +00002845 GCL = InstallGlobalCtors(GCL, Ctors);
Chris Lattner41b6a5a2005-09-26 01:43:45 +00002846 return true;
2847}
2848
Benjamin Kramer8817cca2013-09-22 14:09:50 +00002849static int compareNames(Constant *const *A, Constant *const *B) {
2850 return (*A)->getName().compare((*B)->getName());
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002851}
Rafael Espindola00752162013-05-09 17:22:59 +00002852
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002853static void setUsedInitializer(GlobalVariable &V,
2854 SmallPtrSet<GlobalValue *, 8> Init) {
Rafael Espindolac2bb73f2013-07-20 23:33:15 +00002855 if (Init.empty()) {
2856 V.eraseFromParent();
2857 return;
2858 }
2859
Matt Arsenaultda1deab2014-01-02 19:53:49 +00002860 // Type of pointer to the array of pointers.
2861 PointerType *Int8PtrTy = Type::getInt8PtrTy(V.getContext(), 0);
Rafael Espindola00752162013-05-09 17:22:59 +00002862
Matt Arsenaultda1deab2014-01-02 19:53:49 +00002863 SmallVector<llvm::Constant *, 8> UsedArray;
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002864 for (SmallPtrSet<GlobalValue *, 8>::iterator I = Init.begin(), E = Init.end();
2865 I != E; ++I) {
Matt Arsenaultda1deab2014-01-02 19:53:49 +00002866 Constant *Cast
2867 = ConstantExpr::getPointerBitCastOrAddrSpaceCast(*I, Int8PtrTy);
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002868 UsedArray.push_back(Cast);
Rafael Espindola00752162013-05-09 17:22:59 +00002869 }
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002870 // Sort to get deterministic order.
2871 array_pod_sort(UsedArray.begin(), UsedArray.end(), compareNames);
2872 ArrayType *ATy = ArrayType::get(Int8PtrTy, UsedArray.size());
Rafael Espindola00752162013-05-09 17:22:59 +00002873
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002874 Module *M = V.getParent();
2875 V.removeFromParent();
2876 GlobalVariable *NV =
2877 new GlobalVariable(*M, ATy, false, llvm::GlobalValue::AppendingLinkage,
2878 llvm::ConstantArray::get(ATy, UsedArray), "");
2879 NV->takeName(&V);
2880 NV->setSection("llvm.metadata");
2881 delete &V;
Rafael Espindola00752162013-05-09 17:22:59 +00002882}
2883
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002884namespace {
Rafael Espindola9aadcc42013-07-19 18:44:51 +00002885/// \brief An easy to access representation of llvm.used and llvm.compiler.used.
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002886class LLVMUsed {
2887 SmallPtrSet<GlobalValue *, 8> Used;
2888 SmallPtrSet<GlobalValue *, 8> CompilerUsed;
2889 GlobalVariable *UsedV;
2890 GlobalVariable *CompilerUsedV;
2891
2892public:
Rafael Espindolaec2375f2013-07-25 02:50:08 +00002893 LLVMUsed(Module &M) {
Rafael Espindola17600e22013-07-25 03:23:25 +00002894 UsedV = collectUsedGlobalVariables(M, Used, false);
2895 CompilerUsedV = collectUsedGlobalVariables(M, CompilerUsed, true);
Rafael Espindola00752162013-05-09 17:22:59 +00002896 }
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002897 typedef SmallPtrSet<GlobalValue *, 8>::iterator iterator;
2898 iterator usedBegin() { return Used.begin(); }
2899 iterator usedEnd() { return Used.end(); }
2900 iterator compilerUsedBegin() { return CompilerUsed.begin(); }
2901 iterator compilerUsedEnd() { return CompilerUsed.end(); }
2902 bool usedCount(GlobalValue *GV) const { return Used.count(GV); }
2903 bool compilerUsedCount(GlobalValue *GV) const {
2904 return CompilerUsed.count(GV);
2905 }
2906 bool usedErase(GlobalValue *GV) { return Used.erase(GV); }
2907 bool compilerUsedErase(GlobalValue *GV) { return CompilerUsed.erase(GV); }
2908 bool usedInsert(GlobalValue *GV) { return Used.insert(GV); }
2909 bool compilerUsedInsert(GlobalValue *GV) { return CompilerUsed.insert(GV); }
Rafael Espindola00752162013-05-09 17:22:59 +00002910
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002911 void syncVariablesAndSets() {
2912 if (UsedV)
2913 setUsedInitializer(*UsedV, Used);
2914 if (CompilerUsedV)
2915 setUsedInitializer(*CompilerUsedV, CompilerUsed);
2916 }
2917};
Rafael Espindola00752162013-05-09 17:22:59 +00002918}
2919
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002920static bool hasUseOtherThanLLVMUsed(GlobalAlias &GA, const LLVMUsed &U) {
2921 if (GA.use_empty()) // No use at all.
2922 return false;
2923
2924 assert((!U.usedCount(&GA) || !U.compilerUsedCount(&GA)) &&
2925 "We should have removed the duplicated "
Rafael Espindola9aadcc42013-07-19 18:44:51 +00002926 "element from llvm.compiler.used");
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002927 if (!GA.hasOneUse())
2928 // Strictly more than one use. So at least one is not in llvm.used and
Rafael Espindola9aadcc42013-07-19 18:44:51 +00002929 // llvm.compiler.used.
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002930 return true;
2931
Rafael Espindola9aadcc42013-07-19 18:44:51 +00002932 // Exactly one use. Check if it is in llvm.used or llvm.compiler.used.
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002933 return !U.usedCount(&GA) && !U.compilerUsedCount(&GA);
Rafael Espindola00752162013-05-09 17:22:59 +00002934}
2935
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002936static bool hasMoreThanOneUseOtherThanLLVMUsed(GlobalValue &V,
2937 const LLVMUsed &U) {
2938 unsigned N = 2;
2939 assert((!U.usedCount(&V) || !U.compilerUsedCount(&V)) &&
2940 "We should have removed the duplicated "
Rafael Espindola9aadcc42013-07-19 18:44:51 +00002941 "element from llvm.compiler.used");
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002942 if (U.usedCount(&V) || U.compilerUsedCount(&V))
2943 ++N;
2944 return V.hasNUsesOrMore(N);
2945}
2946
2947static bool mayHaveOtherReferences(GlobalAlias &GA, const LLVMUsed &U) {
2948 if (!GA.hasLocalLinkage())
2949 return true;
2950
2951 return U.usedCount(&GA) || U.compilerUsedCount(&GA);
2952}
2953
2954static bool hasUsesToReplace(GlobalAlias &GA, LLVMUsed &U, bool &RenameTarget) {
2955 RenameTarget = false;
Rafael Espindola00752162013-05-09 17:22:59 +00002956 bool Ret = false;
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002957 if (hasUseOtherThanLLVMUsed(GA, U))
Rafael Espindola00752162013-05-09 17:22:59 +00002958 Ret = true;
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002959
2960 // If the alias is externally visible, we may still be able to simplify it.
2961 if (!mayHaveOtherReferences(GA, U))
2962 return Ret;
2963
2964 // If the aliasee has internal linkage, give it the name and linkage
2965 // of the alias, and delete the alias. This turns:
2966 // define internal ... @f(...)
2967 // @a = alias ... @f
2968 // into:
2969 // define ... @a(...)
2970 Constant *Aliasee = GA.getAliasee();
2971 GlobalValue *Target = cast<GlobalValue>(Aliasee->stripPointerCasts());
2972 if (!Target->hasLocalLinkage())
2973 return Ret;
2974
2975 // Do not perform the transform if multiple aliases potentially target the
2976 // aliasee. This check also ensures that it is safe to replace the section
2977 // and other attributes of the aliasee with those of the alias.
2978 if (hasMoreThanOneUseOtherThanLLVMUsed(*Target, U))
2979 return Ret;
2980
2981 RenameTarget = true;
2982 return true;
Rafael Espindola00752162013-05-09 17:22:59 +00002983}
2984
Duncan Sandsed722832009-03-06 10:21:56 +00002985bool GlobalOpt::OptimizeGlobalAliases(Module &M) {
Anton Korobeynikova9b60ee2008-09-09 19:04:59 +00002986 bool Changed = false;
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002987 LLVMUsed Used(M);
2988
2989 for (SmallPtrSet<GlobalValue *, 8>::iterator I = Used.usedBegin(),
2990 E = Used.usedEnd();
2991 I != E; ++I)
2992 Used.compilerUsedErase(*I);
Anton Korobeynikova9b60ee2008-09-09 19:04:59 +00002993
Duncan Sands0bcf0852009-01-07 20:01:06 +00002994 for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end();
Duncan Sandsb3f27882009-02-15 09:56:08 +00002995 I != E;) {
2996 Module::alias_iterator J = I++;
Duncan Sandsed722832009-03-06 10:21:56 +00002997 // Aliases without names cannot be referenced outside this module.
2998 if (!J->hasName() && !J->isDeclaration())
2999 J->setLinkage(GlobalValue::InternalLinkage);
Duncan Sandsb3f27882009-02-15 09:56:08 +00003000 // If the aliasee may change at link time, nothing can be done - bail out.
3001 if (J->mayBeOverridden())
Anton Korobeynikova9b60ee2008-09-09 19:04:59 +00003002 continue;
3003
Duncan Sandsb3f27882009-02-15 09:56:08 +00003004 Constant *Aliasee = J->getAliasee();
3005 GlobalValue *Target = cast<GlobalValue>(Aliasee->stripPointerCasts());
Duncan Sands7a1db332009-02-18 17:55:38 +00003006 Target->removeDeadConstantUsers();
Duncan Sandsb3f27882009-02-15 09:56:08 +00003007
3008 // Make all users of the alias use the aliasee instead.
Rafael Espindolaa82555c2013-06-11 17:48:06 +00003009 bool RenameTarget;
3010 if (!hasUsesToReplace(*J, Used, RenameTarget))
Rafael Espindola00752162013-05-09 17:22:59 +00003011 continue;
Duncan Sandsb3f27882009-02-15 09:56:08 +00003012
Rafael Espindolaa82555c2013-06-11 17:48:06 +00003013 J->replaceAllUsesWith(Aliasee);
3014 ++NumAliasesResolved;
3015 Changed = true;
Duncan Sandsb3f27882009-02-15 09:56:08 +00003016
Rafael Espindolaa82555c2013-06-11 17:48:06 +00003017 if (RenameTarget) {
Duncan Sands6a3df7b2009-12-08 10:10:20 +00003018 // Give the aliasee the name, linkage and other attributes of the alias.
3019 Target->takeName(J);
3020 Target->setLinkage(J->getLinkage());
Reid Kleckner22b19da2014-02-13 02:18:36 +00003021 Target->setVisibility(J->getVisibility());
3022 Target->setDLLStorageClass(J->getDLLStorageClass());
Rafael Espindolaa82555c2013-06-11 17:48:06 +00003023
3024 if (Used.usedErase(J))
3025 Used.usedInsert(Target);
3026
3027 if (Used.compilerUsedErase(J))
3028 Used.compilerUsedInsert(Target);
Rafael Espindola8d304802013-06-12 16:45:47 +00003029 } else if (mayHaveOtherReferences(*J, Used))
Rafael Espindolaa82555c2013-06-11 17:48:06 +00003030 continue;
3031
Duncan Sandsb3f27882009-02-15 09:56:08 +00003032 // Delete the alias.
3033 M.getAliasList().erase(J);
3034 ++NumAliasesRemoved;
3035 Changed = true;
Anton Korobeynikova9b60ee2008-09-09 19:04:59 +00003036 }
3037
Rafael Espindolaa82555c2013-06-11 17:48:06 +00003038 Used.syncVariablesAndSets();
3039
Anton Korobeynikova9b60ee2008-09-09 19:04:59 +00003040 return Changed;
3041}
Chris Lattner41b6a5a2005-09-26 01:43:45 +00003042
Nick Lewycky4b273cb2012-02-12 02:15:20 +00003043static Function *FindCXAAtExit(Module &M, TargetLibraryInfo *TLI) {
3044 if (!TLI->has(LibFunc::cxa_atexit))
Nick Lewyckyf2852562012-02-12 02:17:18 +00003045 return 0;
Nick Lewycky4b273cb2012-02-12 02:15:20 +00003046
3047 Function *Fn = M.getFunction(TLI->getName(LibFunc::cxa_atexit));
Jakub Staszak9525a772012-12-06 21:57:16 +00003048
Anders Carlssonee6bc702011-03-20 17:59:11 +00003049 if (!Fn)
3050 return 0;
Nick Lewycky4b273cb2012-02-12 02:15:20 +00003051
Chris Lattner229907c2011-07-18 04:54:35 +00003052 FunctionType *FTy = Fn->getFunctionType();
Jakub Staszak9525a772012-12-06 21:57:16 +00003053
3054 // Checking that the function has the right return type, the right number of
Anders Carlsson48a44912011-03-20 19:51:13 +00003055 // parameters and that they all have pointer types should be enough.
3056 if (!FTy->getReturnType()->isIntegerTy() ||
3057 FTy->getNumParams() != 3 ||
Anders Carlssonee6bc702011-03-20 17:59:11 +00003058 !FTy->getParamType(0)->isPointerTy() ||
3059 !FTy->getParamType(1)->isPointerTy() ||
3060 !FTy->getParamType(2)->isPointerTy())
3061 return 0;
3062
3063 return Fn;
3064}
3065
3066/// cxxDtorIsEmpty - Returns whether the given function is an empty C++
3067/// destructor and can therefore be eliminated.
3068/// Note that we assume that other optimization passes have already simplified
3069/// the code so we only look for a function with a single basic block, where
Benjamin Kramer1a4695a2012-02-09 16:28:15 +00003070/// the only allowed instructions are 'ret', 'call' to an empty C++ dtor and
3071/// other side-effect free instructions.
Anders Carlssonfcec2f52011-03-20 20:16:43 +00003072static bool cxxDtorIsEmpty(const Function &Fn,
3073 SmallPtrSet<const Function *, 8> &CalledFunctions) {
Anders Carlsson48a44912011-03-20 19:51:13 +00003074 // FIXME: We could eliminate C++ destructors if they're readonly/readnone and
Nick Lewyckyd0781832011-03-21 02:26:01 +00003075 // nounwind, but that doesn't seem worth doing.
Anders Carlsson48a44912011-03-20 19:51:13 +00003076 if (Fn.isDeclaration())
3077 return false;
Anders Carlssonee6bc702011-03-20 17:59:11 +00003078
3079 if (++Fn.begin() != Fn.end())
3080 return false;
3081
3082 const BasicBlock &EntryBlock = Fn.getEntryBlock();
3083 for (BasicBlock::const_iterator I = EntryBlock.begin(), E = EntryBlock.end();
3084 I != E; ++I) {
3085 if (const CallInst *CI = dyn_cast<CallInst>(I)) {
Anders Carlsson4dd420f2011-03-21 14:54:40 +00003086 // Ignore debug intrinsics.
3087 if (isa<DbgInfoIntrinsic>(CI))
3088 continue;
3089
Anders Carlssonee6bc702011-03-20 17:59:11 +00003090 const Function *CalledFn = CI->getCalledFunction();
3091
3092 if (!CalledFn)
3093 return false;
3094
Anders Carlsson1cc80732011-03-22 03:21:01 +00003095 SmallPtrSet<const Function *, 8> NewCalledFunctions(CalledFunctions);
3096
Anders Carlsson48a44912011-03-20 19:51:13 +00003097 // Don't treat recursive functions as empty.
Anders Carlsson1cc80732011-03-22 03:21:01 +00003098 if (!NewCalledFunctions.insert(CalledFn))
Anders Carlsson48a44912011-03-20 19:51:13 +00003099 return false;
3100
Anders Carlsson1cc80732011-03-22 03:21:01 +00003101 if (!cxxDtorIsEmpty(*CalledFn, NewCalledFunctions))
Anders Carlssonee6bc702011-03-20 17:59:11 +00003102 return false;
3103 } else if (isa<ReturnInst>(*I))
Benjamin Kramer487a3962012-02-09 14:26:06 +00003104 return true; // We're done.
3105 else if (I->mayHaveSideEffects())
3106 return false; // Destructor with side effects, bail.
Anders Carlssonee6bc702011-03-20 17:59:11 +00003107 }
3108
3109 return false;
3110}
3111
3112bool GlobalOpt::OptimizeEmptyGlobalCXXDtors(Function *CXAAtExitFn) {
3113 /// Itanium C++ ABI p3.3.5:
3114 ///
3115 /// After constructing a global (or local static) object, that will require
3116 /// destruction on exit, a termination function is registered as follows:
3117 ///
3118 /// extern "C" int __cxa_atexit ( void (*f)(void *), void *p, void *d );
3119 ///
3120 /// This registration, e.g. __cxa_atexit(f,p,d), is intended to cause the
3121 /// call f(p) when DSO d is unloaded, before all such termination calls
3122 /// registered before this one. It returns zero if registration is
Nick Lewyckyd0781832011-03-21 02:26:01 +00003123 /// successful, nonzero on failure.
Anders Carlssonee6bc702011-03-20 17:59:11 +00003124
3125 // This pass will look for calls to __cxa_atexit where the function is trivial
3126 // and remove them.
3127 bool Changed = false;
3128
Jakub Staszak9525a772012-12-06 21:57:16 +00003129 for (Function::use_iterator I = CXAAtExitFn->use_begin(),
Anders Carlssonee6bc702011-03-20 17:59:11 +00003130 E = CXAAtExitFn->use_end(); I != E;) {
Anders Carlsson336fd902011-03-20 20:21:33 +00003131 // We're only interested in calls. Theoretically, we could handle invoke
3132 // instructions as well, but neither llvm-gcc nor clang generate invokes
3133 // to __cxa_atexit.
Anders Carlsson4dd420f2011-03-21 14:54:40 +00003134 CallInst *CI = dyn_cast<CallInst>(*I++);
3135 if (!CI)
Anders Carlsson336fd902011-03-20 20:21:33 +00003136 continue;
3137
Jakub Staszak9525a772012-12-06 21:57:16 +00003138 Function *DtorFn =
Anders Carlsson4dd420f2011-03-21 14:54:40 +00003139 dyn_cast<Function>(CI->getArgOperand(0)->stripPointerCasts());
Anders Carlssonee6bc702011-03-20 17:59:11 +00003140 if (!DtorFn)
3141 continue;
3142
Anders Carlssonfcec2f52011-03-20 20:16:43 +00003143 SmallPtrSet<const Function *, 8> CalledFunctions;
3144 if (!cxxDtorIsEmpty(*DtorFn, CalledFunctions))
Anders Carlssonee6bc702011-03-20 17:59:11 +00003145 continue;
3146
3147 // Just remove the call.
Anders Carlsson4dd420f2011-03-21 14:54:40 +00003148 CI->replaceAllUsesWith(Constant::getNullValue(CI->getType()));
3149 CI->eraseFromParent();
Anders Carlsson48a44912011-03-20 19:51:13 +00003150
Anders Carlssonee6bc702011-03-20 17:59:11 +00003151 ++NumCXXDtorsRemoved;
3152
3153 Changed |= true;
3154 }
3155
3156 return Changed;
3157}
3158
Chris Lattner25db5802004-10-07 04:16:33 +00003159bool GlobalOpt::runOnModule(Module &M) {
3160 bool Changed = false;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00003161
Micah Villmowcdfe20b2012-10-08 16:38:25 +00003162 TD = getAnalysisIfAvailable<DataLayout>();
Nick Lewycky4b273cb2012-02-12 02:15:20 +00003163 TLI = &getAnalysis<TargetLibraryInfo>();
Nick Lewyckycf6aae62012-02-12 01:13:18 +00003164
Chris Lattner41b6a5a2005-09-26 01:43:45 +00003165 // Try to find the llvm.globalctors list.
3166 GlobalVariable *GlobalCtors = FindGlobalCtors(M);
Chris Lattner25db5802004-10-07 04:16:33 +00003167
Chris Lattner25db5802004-10-07 04:16:33 +00003168 bool LocalChange = true;
3169 while (LocalChange) {
3170 LocalChange = false;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00003171
Chris Lattner41b6a5a2005-09-26 01:43:45 +00003172 // Delete functions that are trivially dead, ccc -> fastcc
3173 LocalChange |= OptimizeFunctions(M);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00003174
Chris Lattner41b6a5a2005-09-26 01:43:45 +00003175 // Optimize global_ctors list.
3176 if (GlobalCtors)
3177 LocalChange |= OptimizeGlobalCtorsList(GlobalCtors);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00003178
Chris Lattner41b6a5a2005-09-26 01:43:45 +00003179 // Optimize non-address-taken globals.
3180 LocalChange |= OptimizeGlobalVars(M);
Anton Korobeynikova9b60ee2008-09-09 19:04:59 +00003181
3182 // Resolve aliases, when possible.
Duncan Sandsed722832009-03-06 10:21:56 +00003183 LocalChange |= OptimizeGlobalAliases(M);
Anders Carlssonee6bc702011-03-20 17:59:11 +00003184
Manman Renb3c52fb2013-05-14 21:52:44 +00003185 // Try to remove trivial global destructors if they are not removed
3186 // already.
3187 Function *CXAAtExitFn = FindCXAAtExit(M, TLI);
Anders Carlssonee6bc702011-03-20 17:59:11 +00003188 if (CXAAtExitFn)
3189 LocalChange |= OptimizeEmptyGlobalCXXDtors(CXAAtExitFn);
3190
Anton Korobeynikova9b60ee2008-09-09 19:04:59 +00003191 Changed |= LocalChange;
Chris Lattner25db5802004-10-07 04:16:33 +00003192 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00003193
Chris Lattner41b6a5a2005-09-26 01:43:45 +00003194 // TODO: Move all global ctors functions to the end of the module for code
3195 // layout.
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00003196
Chris Lattner25db5802004-10-07 04:16:33 +00003197 return Changed;
3198}