blob: cc7e2abd809bbd01dde7d1fd55093c877eec5890 [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
Chris Lattner25db5802004-10-07 04:16:33 +000016#include "llvm/Transforms/IPO.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000017#include "llvm/ADT/DenseMap.h"
18#include "llvm/ADT/STLExtras.h"
19#include "llvm/ADT/SmallPtrSet.h"
20#include "llvm/ADT/SmallVector.h"
21#include "llvm/ADT/Statistic.h"
22#include "llvm/Analysis/ConstantFolding.h"
23#include "llvm/Analysis/MemoryBuiltins.h"
Chandler Carruth219b89b2014-03-04 11:01:28 +000024#include "llvm/IR/CallSite.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"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000029#include "llvm/IR/GetElementPtrTypeIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000030#include "llvm/IR/Instructions.h"
31#include "llvm/IR/IntrinsicInst.h"
32#include "llvm/IR/Module.h"
33#include "llvm/IR/Operator.h"
Chandler Carruth4220e9c2014-03-04 11:17:44 +000034#include "llvm/IR/ValueHandle.h"
Chris Lattner25db5802004-10-07 04:16:33 +000035#include "llvm/Pass.h"
Chris Lattner024f4ab2007-01-30 23:46:24 +000036#include "llvm/Support/Debug.h"
Torok Edwin56d06592009-07-11 20:10:48 +000037#include "llvm/Support/ErrorHandling.h"
Chris Lattner67ca6f632008-04-26 07:40:11 +000038#include "llvm/Support/MathExtras.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000039#include "llvm/Support/raw_ostream.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000040#include "llvm/Target/TargetLibraryInfo.h"
Rafael Espindola3d7fc252013-10-21 17:14:55 +000041#include "llvm/Transforms/Utils/GlobalStatus.h"
Rafael Espindola17600e22013-07-25 03:23:25 +000042#include "llvm/Transforms/Utils/ModuleUtils.h"
Chris Lattner25db5802004-10-07 04:16:33 +000043#include <algorithm>
44using namespace llvm;
45
Chandler Carruth964daaa2014-04-22 02:55:47 +000046#define DEBUG_TYPE "globalopt"
47
Chris Lattner1631bcb2006-12-19 22:09:18 +000048STATISTIC(NumMarked , "Number of globals marked constant");
Rafael Espindolafc355bc2011-01-19 16:32:21 +000049STATISTIC(NumUnnamed , "Number of globals marked unnamed_addr");
Chris Lattner1631bcb2006-12-19 22:09:18 +000050STATISTIC(NumSRA , "Number of aggregate globals broken into scalars");
51STATISTIC(NumHeapSRA , "Number of heap objects SRA'd");
52STATISTIC(NumSubstitute,"Number of globals with initializers stored into them");
53STATISTIC(NumDeleted , "Number of globals deleted");
54STATISTIC(NumFnDeleted , "Number of functions deleted");
55STATISTIC(NumGlobUses , "Number of global uses devirtualized");
Alexey Samsonova1944e62013-10-07 19:03:24 +000056STATISTIC(NumLocalized , "Number of globals localized");
Chris Lattner1631bcb2006-12-19 22:09:18 +000057STATISTIC(NumShrunkToBool , "Number of global vars shrunk to booleans");
58STATISTIC(NumFastCallFns , "Number of functions converted to fastcc");
59STATISTIC(NumCtorsEvaluated, "Number of static ctors evaluated");
Duncan Sands573b3f82008-02-16 20:56:04 +000060STATISTIC(NumNestRemoved , "Number of nest attributes removed");
Duncan Sandsb3f27882009-02-15 09:56:08 +000061STATISTIC(NumAliasesResolved, "Number of global aliases resolved");
62STATISTIC(NumAliasesRemoved, "Number of global aliases eliminated");
Anders Carlssonee6bc702011-03-20 17:59:11 +000063STATISTIC(NumCXXDtorsRemoved, "Number of global C++ destructors removed");
Chris Lattner25db5802004-10-07 04:16:33 +000064
Chris Lattner1631bcb2006-12-19 22:09:18 +000065namespace {
Nick Lewycky02d5f772009-10-25 06:33:48 +000066 struct GlobalOpt : public ModulePass {
Craig Topper3e4c6972014-03-05 09:10:37 +000067 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chad Rosiere6de63d2011-12-01 21:29:16 +000068 AU.addRequired<TargetLibraryInfo>();
Chris Lattner004e2502004-10-11 05:54:41 +000069 }
Nick Lewyckye7da2d62007-05-06 13:37:16 +000070 static char ID; // Pass identification, replacement for typeid
Owen Anderson6c18d1a2010-10-19 17:21:58 +000071 GlobalOpt() : ModulePass(ID) {
72 initializeGlobalOptPass(*PassRegistry::getPassRegistry());
73 }
Misha Brukmanb1c93172005-04-21 23:48:37 +000074
Craig Topper3e4c6972014-03-05 09:10:37 +000075 bool runOnModule(Module &M) override;
Chris Lattner004e2502004-10-11 05:54:41 +000076
77 private:
Chris Lattner41b6a5a2005-09-26 01:43:45 +000078 GlobalVariable *FindGlobalCtors(Module &M);
79 bool OptimizeFunctions(Module &M);
80 bool OptimizeGlobalVars(Module &M);
Duncan Sandsed722832009-03-06 10:21:56 +000081 bool OptimizeGlobalAliases(Module &M);
Chris Lattner41b6a5a2005-09-26 01:43:45 +000082 bool OptimizeGlobalCtorsList(GlobalVariable *&GCL);
Rafael Espindolafc355bc2011-01-19 16:32:21 +000083 bool ProcessGlobal(GlobalVariable *GV,Module::global_iterator &GVI);
84 bool ProcessInternalGlobal(GlobalVariable *GV,Module::global_iterator &GVI,
Rafael Espindolafc355bc2011-01-19 16:32:21 +000085 const GlobalStatus &GS);
Anders Carlssonee6bc702011-03-20 17:59:11 +000086 bool OptimizeEmptyGlobalCXXDtors(Function *CXAAtExitFn);
Nick Lewyckycf6aae62012-02-12 01:13:18 +000087
Rafael Espindolaaeff8a92014-02-24 23:12:18 +000088 const DataLayout *DL;
Nick Lewyckycf6aae62012-02-12 01:13:18 +000089 TargetLibraryInfo *TLI;
Chris Lattner25db5802004-10-07 04:16:33 +000090 };
Chris Lattner25db5802004-10-07 04:16:33 +000091}
92
Dan Gohmand78c4002008-05-13 00:00:25 +000093char GlobalOpt::ID = 0;
Chad Rosiere6de63d2011-12-01 21:29:16 +000094INITIALIZE_PASS_BEGIN(GlobalOpt, "globalopt",
95 "Global Variable Optimizer", false, false)
96INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
97INITIALIZE_PASS_END(GlobalOpt, "globalopt",
Owen Andersondf7a4f22010-10-07 22:25:06 +000098 "Global Variable Optimizer", false, false)
Dan Gohmand78c4002008-05-13 00:00:25 +000099
Chris Lattner25db5802004-10-07 04:16:33 +0000100ModulePass *llvm::createGlobalOptimizerPass() { return new GlobalOpt(); }
101
Nick Lewyckyfaa9c3b02012-07-24 07:21:08 +0000102/// isLeakCheckerRoot - Is this global variable possibly used by a leak checker
103/// as a root? If so, we might not really want to eliminate the stores to it.
104static bool isLeakCheckerRoot(GlobalVariable *GV) {
105 // A global variable is a root if it is a pointer, or could plausibly contain
106 // a pointer. There are two challenges; one is that we could have a struct
107 // the has an inner member which is a pointer. We recurse through the type to
108 // detect these (up to a point). The other is that we may actually be a union
109 // of a pointer and another type, and so our LLVM type is an integer which
110 // gets converted into a pointer, or our type is an [i8 x #] with a pointer
111 // potentially contained here.
112
113 if (GV->hasPrivateLinkage())
114 return false;
115
116 SmallVector<Type *, 4> Types;
117 Types.push_back(cast<PointerType>(GV->getType())->getElementType());
118
119 unsigned Limit = 20;
120 do {
121 Type *Ty = Types.pop_back_val();
122 switch (Ty->getTypeID()) {
123 default: break;
124 case Type::PointerTyID: return true;
125 case Type::ArrayTyID:
126 case Type::VectorTyID: {
127 SequentialType *STy = cast<SequentialType>(Ty);
128 Types.push_back(STy->getElementType());
129 break;
130 }
131 case Type::StructTyID: {
132 StructType *STy = cast<StructType>(Ty);
133 if (STy->isOpaque()) return true;
134 for (StructType::element_iterator I = STy->element_begin(),
135 E = STy->element_end(); I != E; ++I) {
136 Type *InnerTy = *I;
137 if (isa<PointerType>(InnerTy)) return true;
138 if (isa<CompositeType>(InnerTy))
139 Types.push_back(InnerTy);
140 }
141 break;
142 }
143 }
144 if (--Limit == 0) return true;
145 } while (!Types.empty());
146 return false;
147}
148
149/// Given a value that is stored to a global but never read, determine whether
150/// it's safe to remove the store and the chain of computation that feeds the
151/// store.
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000152static bool IsSafeComputationToRemove(Value *V, const TargetLibraryInfo *TLI) {
Nick Lewyckyfaa9c3b02012-07-24 07:21:08 +0000153 do {
154 if (isa<Constant>(V))
155 return true;
156 if (!V->hasOneUse())
157 return false;
Nick Lewycky7d0f1102012-07-25 21:19:40 +0000158 if (isa<LoadInst>(V) || isa<InvokeInst>(V) || isa<Argument>(V) ||
159 isa<GlobalValue>(V))
Nick Lewyckyfaa9c3b02012-07-24 07:21:08 +0000160 return false;
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000161 if (isAllocationFn(V, TLI))
Nick Lewyckyfaa9c3b02012-07-24 07:21:08 +0000162 return true;
163
164 Instruction *I = cast<Instruction>(V);
165 if (I->mayHaveSideEffects())
166 return false;
167 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
168 if (!GEP->hasAllConstantIndices())
169 return false;
170 } else if (I->getNumOperands() != 1) {
171 return false;
172 }
173
174 V = I->getOperand(0);
175 } while (1);
176}
177
178/// CleanupPointerRootUsers - This GV is a pointer root. Loop over all users
179/// of the global and clean up any that obviously don't assign the global a
180/// value that isn't dynamically allocated.
181///
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000182static bool CleanupPointerRootUsers(GlobalVariable *GV,
183 const TargetLibraryInfo *TLI) {
Nick Lewyckyfaa9c3b02012-07-24 07:21:08 +0000184 // A brief explanation of leak checkers. The goal is to find bugs where
185 // pointers are forgotten, causing an accumulating growth in memory
186 // usage over time. The common strategy for leak checkers is to whitelist the
187 // memory pointed to by globals at exit. This is popular because it also
188 // solves another problem where the main thread of a C++ program may shut down
189 // before other threads that are still expecting to use those globals. To
190 // handle that case, we expect the program may create a singleton and never
191 // destroy it.
192
193 bool Changed = false;
194
195 // If Dead[n].first is the only use of a malloc result, we can delete its
196 // chain of computation and the store to the global in Dead[n].second.
197 SmallVector<std::pair<Instruction *, Instruction *>, 32> Dead;
198
199 // Constants can't be pointers to dynamically allocated memory.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000200 for (Value::user_iterator UI = GV->user_begin(), E = GV->user_end();
Nick Lewyckyfaa9c3b02012-07-24 07:21:08 +0000201 UI != E;) {
202 User *U = *UI++;
203 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
204 Value *V = SI->getValueOperand();
205 if (isa<Constant>(V)) {
206 Changed = true;
207 SI->eraseFromParent();
208 } else if (Instruction *I = dyn_cast<Instruction>(V)) {
209 if (I->hasOneUse())
210 Dead.push_back(std::make_pair(I, SI));
211 }
212 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(U)) {
213 if (isa<Constant>(MSI->getValue())) {
214 Changed = true;
215 MSI->eraseFromParent();
216 } else if (Instruction *I = dyn_cast<Instruction>(MSI->getValue())) {
217 if (I->hasOneUse())
218 Dead.push_back(std::make_pair(I, MSI));
219 }
220 } else if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(U)) {
221 GlobalVariable *MemSrc = dyn_cast<GlobalVariable>(MTI->getSource());
222 if (MemSrc && MemSrc->isConstant()) {
223 Changed = true;
224 MTI->eraseFromParent();
225 } else if (Instruction *I = dyn_cast<Instruction>(MemSrc)) {
226 if (I->hasOneUse())
227 Dead.push_back(std::make_pair(I, MTI));
228 }
229 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
230 if (CE->use_empty()) {
231 CE->destroyConstant();
232 Changed = true;
233 }
234 } else if (Constant *C = dyn_cast<Constant>(U)) {
Rafael Espindola27797ba2013-10-17 18:06:32 +0000235 if (isSafeToDestroyConstant(C)) {
Nick Lewyckyfaa9c3b02012-07-24 07:21:08 +0000236 C->destroyConstant();
237 // This could have invalidated UI, start over from scratch.
238 Dead.clear();
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000239 CleanupPointerRootUsers(GV, TLI);
Nick Lewyckyfaa9c3b02012-07-24 07:21:08 +0000240 return true;
241 }
242 }
243 }
244
245 for (int i = 0, e = Dead.size(); i != e; ++i) {
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000246 if (IsSafeComputationToRemove(Dead[i].first, TLI)) {
Nick Lewyckyfaa9c3b02012-07-24 07:21:08 +0000247 Dead[i].second->eraseFromParent();
248 Instruction *I = Dead[i].first;
249 do {
Michael Gottesman2a654272013-01-11 23:08:52 +0000250 if (isAllocationFn(I, TLI))
251 break;
Nick Lewyckyfaa9c3b02012-07-24 07:21:08 +0000252 Instruction *J = dyn_cast<Instruction>(I->getOperand(0));
253 if (!J)
254 break;
255 I->eraseFromParent();
256 I = J;
Nick Lewycky38be9312012-07-24 21:33:00 +0000257 } while (1);
Nick Lewyckyfaa9c3b02012-07-24 07:21:08 +0000258 I->eraseFromParent();
259 }
260 }
261
262 return Changed;
263}
264
Chris Lattner25db5802004-10-07 04:16:33 +0000265/// CleanupConstantGlobalUsers - We just marked GV constant. Loop over all
266/// users of the global, cleaning up the obvious ones. This is largely just a
Chris Lattnercb9f1522004-10-10 16:43:46 +0000267/// quick scan over the use list to clean up the easy and obvious cruft. This
268/// returns true if it made a change.
Nick Lewyckycf6aae62012-02-12 01:13:18 +0000269static bool CleanupConstantGlobalUsers(Value *V, Constant *Init,
Rafael Espindolaaeff8a92014-02-24 23:12:18 +0000270 const DataLayout *DL,
271 TargetLibraryInfo *TLI) {
Chris Lattnercb9f1522004-10-10 16:43:46 +0000272 bool Changed = false;
Hal Finkelf59fd7d2013-12-12 20:45:24 +0000273 // Note that we need to use a weak value handle for the worklist items. When
274 // we delete a constant array, we may also be holding pointer to one of its
275 // elements (or an element of one of its elements if we're dealing with an
276 // array of arrays) in the worklist.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000277 SmallVector<WeakVH, 8> WorkList(V->user_begin(), V->user_end());
Bill Wendling88d06c32013-04-02 08:16:45 +0000278 while (!WorkList.empty()) {
Hal Finkelf59fd7d2013-12-12 20:45:24 +0000279 Value *UV = WorkList.pop_back_val();
280 if (!UV)
281 continue;
282
283 User *U = cast<User>(UV);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000284
Chris Lattner25db5802004-10-07 04:16:33 +0000285 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
Chris Lattner7561ca12005-02-27 18:58:52 +0000286 if (Init) {
287 // Replace the load with the initializer.
288 LI->replaceAllUsesWith(Init);
289 LI->eraseFromParent();
290 Changed = true;
291 }
Chris Lattner25db5802004-10-07 04:16:33 +0000292 } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
293 // Store must be unreachable or storing Init into the global.
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000294 SI->eraseFromParent();
Chris Lattnercb9f1522004-10-10 16:43:46 +0000295 Changed = true;
Chris Lattner25db5802004-10-07 04:16:33 +0000296 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
297 if (CE->getOpcode() == Instruction::GetElementPtr) {
Craig Topperf40110f2014-04-25 05:29:35 +0000298 Constant *SubInit = nullptr;
Chris Lattner46d9ff082005-09-26 07:34:35 +0000299 if (Init)
Dan Gohmane525d9d2009-10-05 16:36:26 +0000300 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000301 Changed |= CleanupConstantGlobalUsers(CE, SubInit, DL, TLI);
Matt Arsenault461c8e02014-01-02 20:01:43 +0000302 } else if ((CE->getOpcode() == Instruction::BitCast &&
303 CE->getType()->isPointerTy()) ||
304 CE->getOpcode() == Instruction::AddrSpaceCast) {
Chris Lattner7561ca12005-02-27 18:58:52 +0000305 // Pointer cast, delete any stores and memsets to the global.
Craig Topperf40110f2014-04-25 05:29:35 +0000306 Changed |= CleanupConstantGlobalUsers(CE, nullptr, DL, TLI);
Chris Lattner7561ca12005-02-27 18:58:52 +0000307 }
308
309 if (CE->use_empty()) {
310 CE->destroyConstant();
311 Changed = true;
Chris Lattner25db5802004-10-07 04:16:33 +0000312 }
313 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
Chris Lattnerf9c0fd72007-11-09 17:33:02 +0000314 // Do not transform "gepinst (gep constexpr (GV))" here, because forming
315 // "gepconstexpr (gep constexpr (GV))" will cause the two gep's to fold
316 // and will invalidate our notion of what Init is.
Craig Topperf40110f2014-04-25 05:29:35 +0000317 Constant *SubInit = nullptr;
Chris Lattnerf9c0fd72007-11-09 17:33:02 +0000318 if (!isa<ConstantExpr>(GEP->getOperand(0))) {
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000319 ConstantExpr *CE =
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000320 dyn_cast_or_null<ConstantExpr>(ConstantFoldInstruction(GEP, DL, TLI));
Chris Lattnerf9c0fd72007-11-09 17:33:02 +0000321 if (Init && CE && CE->getOpcode() == Instruction::GetElementPtr)
Dan Gohmane525d9d2009-10-05 16:36:26 +0000322 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
Benjamin Krameraa9e4a52012-03-28 14:50:09 +0000323
324 // If the initializer is an all-null value and we have an inbounds GEP,
325 // we already know what the result of any load from that GEP is.
326 // TODO: Handle splats.
327 if (Init && isa<ConstantAggregateZero>(Init) && GEP->isInBounds())
328 SubInit = Constant::getNullValue(GEP->getType()->getElementType());
Chris Lattnerf9c0fd72007-11-09 17:33:02 +0000329 }
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000330 Changed |= CleanupConstantGlobalUsers(GEP, SubInit, DL, TLI);
Chris Lattnera0e769c2004-10-10 16:47:33 +0000331
Chris Lattnercb9f1522004-10-10 16:43:46 +0000332 if (GEP->use_empty()) {
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000333 GEP->eraseFromParent();
Chris Lattnercb9f1522004-10-10 16:43:46 +0000334 Changed = true;
335 }
Chris Lattner7561ca12005-02-27 18:58:52 +0000336 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U)) { // memset/cpy/mv
337 if (MI->getRawDest() == V) {
338 MI->eraseFromParent();
339 Changed = true;
340 }
341
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000342 } else if (Constant *C = dyn_cast<Constant>(U)) {
343 // If we have a chain of dead constantexprs or other things dangling from
344 // us, and if they are all dead, nuke them without remorse.
Rafael Espindola27797ba2013-10-17 18:06:32 +0000345 if (isSafeToDestroyConstant(C)) {
Devang Pateld926aaa2009-03-06 01:37:41 +0000346 C->destroyConstant();
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000347 CleanupConstantGlobalUsers(V, Init, DL, TLI);
Chris Lattnercb9f1522004-10-10 16:43:46 +0000348 return true;
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000349 }
Chris Lattner25db5802004-10-07 04:16:33 +0000350 }
351 }
Chris Lattnercb9f1522004-10-10 16:43:46 +0000352 return Changed;
Chris Lattner25db5802004-10-07 04:16:33 +0000353}
354
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000355/// isSafeSROAElementUse - Return true if the specified instruction is a safe
356/// user of a derived expression from a global that we want to SROA.
357static bool isSafeSROAElementUse(Value *V) {
358 // We might have a dead and dangling constant hanging off of here.
359 if (Constant *C = dyn_cast<Constant>(V))
Rafael Espindola27797ba2013-10-17 18:06:32 +0000360 return isSafeToDestroyConstant(C);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000361
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000362 Instruction *I = dyn_cast<Instruction>(V);
363 if (!I) return false;
364
365 // Loads are ok.
366 if (isa<LoadInst>(I)) return true;
367
368 // Stores *to* the pointer are ok.
369 if (StoreInst *SI = dyn_cast<StoreInst>(I))
370 return SI->getOperand(0) != V;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000371
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000372 // Otherwise, it must be a GEP.
373 GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I);
Craig Topperf40110f2014-04-25 05:29:35 +0000374 if (!GEPI) return false;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000375
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000376 if (GEPI->getNumOperands() < 3 || !isa<Constant>(GEPI->getOperand(1)) ||
377 !cast<Constant>(GEPI->getOperand(1))->isNullValue())
378 return false;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000379
Chandler Carruthcdf47882014-03-09 03:16:01 +0000380 for (User *U : GEPI->users())
381 if (!isSafeSROAElementUse(U))
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000382 return false;
Chris Lattnerab053722008-01-14 01:31:05 +0000383 return true;
384}
385
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000386
387/// IsUserOfGlobalSafeForSRA - U is a direct user of the specified global value.
388/// Look at it and its uses and decide whether it is safe to SROA this global.
389///
390static bool IsUserOfGlobalSafeForSRA(User *U, GlobalValue *GV) {
391 // The user of the global must be a GEP Inst or a ConstantExpr GEP.
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000392 if (!isa<GetElementPtrInst>(U) &&
393 (!isa<ConstantExpr>(U) ||
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000394 cast<ConstantExpr>(U)->getOpcode() != Instruction::GetElementPtr))
395 return false;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000396
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000397 // Check to see if this ConstantExpr GEP is SRA'able. In particular, we
398 // don't like < 3 operand CE's, and we don't like non-constant integer
399 // indices. This enforces that all uses are 'gep GV, 0, C, ...' for some
400 // value of C.
401 if (U->getNumOperands() < 3 || !isa<Constant>(U->getOperand(1)) ||
402 !cast<Constant>(U->getOperand(1))->isNullValue() ||
403 !isa<ConstantInt>(U->getOperand(2)))
404 return false;
405
406 gep_type_iterator GEPI = gep_type_begin(U), E = gep_type_end(U);
407 ++GEPI; // Skip over the pointer index.
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000408
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000409 // If this is a use of an array allocation, do a bit more checking for sanity.
Chris Lattner229907c2011-07-18 04:54:35 +0000410 if (ArrayType *AT = dyn_cast<ArrayType>(*GEPI)) {
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000411 uint64_t NumElements = AT->getNumElements();
412 ConstantInt *Idx = cast<ConstantInt>(U->getOperand(2));
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000413
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000414 // Check to make sure that index falls within the array. If not,
415 // something funny is going on, so we won't do the optimization.
416 //
417 if (Idx->getZExtValue() >= NumElements)
418 return false;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000419
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000420 // We cannot scalar repl this level of the array unless any array
421 // sub-indices are in-range constants. In particular, consider:
422 // A[0][i]. We cannot know that the user isn't doing invalid things like
423 // allowing i to index an out-of-range subscript that accesses A[1].
424 //
425 // Scalar replacing *just* the outer index of the array is probably not
426 // going to be a win anyway, so just give up.
427 for (++GEPI; // Skip array index.
Dan Gohman82ac81b2009-08-18 14:58:19 +0000428 GEPI != E;
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000429 ++GEPI) {
430 uint64_t NumElements;
Chris Lattner229907c2011-07-18 04:54:35 +0000431 if (ArrayType *SubArrayTy = dyn_cast<ArrayType>(*GEPI))
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000432 NumElements = SubArrayTy->getNumElements();
Chris Lattner229907c2011-07-18 04:54:35 +0000433 else if (VectorType *SubVectorTy = dyn_cast<VectorType>(*GEPI))
Dan Gohman82ac81b2009-08-18 14:58:19 +0000434 NumElements = SubVectorTy->getNumElements();
435 else {
Duncan Sands19d0b472010-02-16 11:11:14 +0000436 assert((*GEPI)->isStructTy() &&
Dan Gohman82ac81b2009-08-18 14:58:19 +0000437 "Indexed GEP type is not array, vector, or struct!");
438 continue;
439 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000440
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000441 ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPI.getOperand());
442 if (!IdxVal || IdxVal->getZExtValue() >= NumElements)
443 return false;
444 }
445 }
446
Chandler Carruthcdf47882014-03-09 03:16:01 +0000447 for (User *UU : U->users())
448 if (!isSafeSROAElementUse(UU))
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000449 return false;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000450
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000451 return true;
452}
453
454/// GlobalUsersSafeToSRA - Look at all uses of the global and decide whether it
455/// is safe for us to perform this transformation.
456///
457static bool GlobalUsersSafeToSRA(GlobalValue *GV) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000458 for (User *U : GV->users())
459 if (!IsUserOfGlobalSafeForSRA(U, GV))
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000460 return false;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000461
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000462 return true;
463}
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000464
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000465
Chris Lattnerabab0712004-10-08 17:32:09 +0000466/// SRAGlobal - Perform scalar replacement of aggregates on the specified global
467/// variable. This opens the door for other optimizations by exposing the
468/// behavior of the program in a more fine-grained way. We have determined that
469/// this transformation is safe already. We return the first global variable we
470/// insert so that the caller can reprocess it.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000471static GlobalVariable *SRAGlobal(GlobalVariable *GV, const DataLayout &DL) {
Chris Lattnerab053722008-01-14 01:31:05 +0000472 // Make sure this global only has simple uses that we can SRA.
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000473 if (!GlobalUsersSafeToSRA(GV))
Craig Topperf40110f2014-04-25 05:29:35 +0000474 return nullptr;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000475
Rafael Espindola6de96a12009-01-15 20:18:42 +0000476 assert(GV->hasLocalLinkage() && !GV->isConstant());
Chris Lattnerabab0712004-10-08 17:32:09 +0000477 Constant *Init = GV->getInitializer();
Chris Lattner229907c2011-07-18 04:54:35 +0000478 Type *Ty = Init->getType();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000479
Chris Lattnerabab0712004-10-08 17:32:09 +0000480 std::vector<GlobalVariable*> NewGlobals;
481 Module::GlobalListType &Globals = GV->getParent()->getGlobalList();
482
Chris Lattner67ca6f632008-04-26 07:40:11 +0000483 // Get the alignment of the global, either explicit or target-specific.
484 unsigned StartAlignment = GV->getAlignment();
485 if (StartAlignment == 0)
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000486 StartAlignment = DL.getABITypeAlignment(GV->getType());
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000487
Chris Lattner229907c2011-07-18 04:54:35 +0000488 if (StructType *STy = dyn_cast<StructType>(Ty)) {
Chris Lattnerabab0712004-10-08 17:32:09 +0000489 NewGlobals.reserve(STy->getNumElements());
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000490 const StructLayout &Layout = *DL.getStructLayout(STy);
Chris Lattnerabab0712004-10-08 17:32:09 +0000491 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
Chris Lattner67058832012-01-25 06:48:06 +0000492 Constant *In = Init->getAggregateElement(i);
Chris Lattnerabab0712004-10-08 17:32:09 +0000493 assert(In && "Couldn't get element of initializer?");
Chris Lattner46b5c642009-11-06 04:27:31 +0000494 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(i), false,
Chris Lattnerabab0712004-10-08 17:32:09 +0000495 GlobalVariable::InternalLinkage,
Daniel Dunbar132f7832009-07-30 17:37:43 +0000496 In, GV->getName()+"."+Twine(i),
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000497 GV->getThreadLocalMode(),
Owen Anderson5948fdf2009-07-08 01:26:06 +0000498 GV->getType()->getAddressSpace());
Chris Lattnerabab0712004-10-08 17:32:09 +0000499 Globals.insert(GV, NGV);
500 NewGlobals.push_back(NGV);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000501
Chris Lattner67ca6f632008-04-26 07:40:11 +0000502 // Calculate the known alignment of the field. If the original aggregate
503 // had 256 byte alignment for example, something might depend on that:
504 // propagate info to each field.
505 uint64_t FieldOffset = Layout.getElementOffset(i);
506 unsigned NewAlign = (unsigned)MinAlign(StartAlignment, FieldOffset);
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000507 if (NewAlign > DL.getABITypeAlignment(STy->getElementType(i)))
Chris Lattner67ca6f632008-04-26 07:40:11 +0000508 NGV->setAlignment(NewAlign);
Chris Lattnerabab0712004-10-08 17:32:09 +0000509 }
Chris Lattner229907c2011-07-18 04:54:35 +0000510 } else if (SequentialType *STy = dyn_cast<SequentialType>(Ty)) {
Chris Lattnerabab0712004-10-08 17:32:09 +0000511 unsigned NumElements = 0;
Chris Lattner229907c2011-07-18 04:54:35 +0000512 if (ArrayType *ATy = dyn_cast<ArrayType>(STy))
Chris Lattnerabab0712004-10-08 17:32:09 +0000513 NumElements = ATy->getNumElements();
Chris Lattnerabab0712004-10-08 17:32:09 +0000514 else
Chris Lattner67ca6f632008-04-26 07:40:11 +0000515 NumElements = cast<VectorType>(STy)->getNumElements();
Chris Lattnerabab0712004-10-08 17:32:09 +0000516
Chris Lattner25169ca2005-02-23 16:53:04 +0000517 if (NumElements > 16 && GV->hasNUsesOrMore(16))
Craig Topperf40110f2014-04-25 05:29:35 +0000518 return nullptr; // It's not worth it.
Chris Lattnerabab0712004-10-08 17:32:09 +0000519 NewGlobals.reserve(NumElements);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000520
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000521 uint64_t EltSize = DL.getTypeAllocSize(STy->getElementType());
522 unsigned EltAlign = DL.getABITypeAlignment(STy->getElementType());
Chris Lattnerabab0712004-10-08 17:32:09 +0000523 for (unsigned i = 0, e = NumElements; i != e; ++i) {
Chris Lattner67058832012-01-25 06:48:06 +0000524 Constant *In = Init->getAggregateElement(i);
Chris Lattnerabab0712004-10-08 17:32:09 +0000525 assert(In && "Couldn't get element of initializer?");
526
Chris Lattner46b5c642009-11-06 04:27:31 +0000527 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(), false,
Chris Lattnerabab0712004-10-08 17:32:09 +0000528 GlobalVariable::InternalLinkage,
Daniel Dunbar132f7832009-07-30 17:37:43 +0000529 In, GV->getName()+"."+Twine(i),
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000530 GV->getThreadLocalMode(),
Owen Andersonb17f3292009-07-08 19:03:57 +0000531 GV->getType()->getAddressSpace());
Chris Lattnerabab0712004-10-08 17:32:09 +0000532 Globals.insert(GV, NGV);
533 NewGlobals.push_back(NGV);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000534
Chris Lattner67ca6f632008-04-26 07:40:11 +0000535 // Calculate the known alignment of the field. If the original aggregate
536 // had 256 byte alignment for example, something might depend on that:
537 // propagate info to each field.
538 unsigned NewAlign = (unsigned)MinAlign(StartAlignment, EltSize*i);
539 if (NewAlign > EltAlign)
540 NGV->setAlignment(NewAlign);
Chris Lattnerabab0712004-10-08 17:32:09 +0000541 }
542 }
543
544 if (NewGlobals.empty())
Craig Topperf40110f2014-04-25 05:29:35 +0000545 return nullptr;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000546
David Greene44cb8ad2010-01-05 01:28:05 +0000547 DEBUG(dbgs() << "PERFORMING GLOBAL SRA ON: " << *GV);
Chris Lattner004e2502004-10-11 05:54:41 +0000548
Chris Lattner46b5c642009-11-06 04:27:31 +0000549 Constant *NullInt =Constant::getNullValue(Type::getInt32Ty(GV->getContext()));
Chris Lattnerabab0712004-10-08 17:32:09 +0000550
551 // Loop over all of the uses of the global, replacing the constantexpr geps,
552 // with smaller constantexpr geps or direct references.
553 while (!GV->use_empty()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000554 User *GEP = GV->user_back();
Chris Lattner004e2502004-10-11 05:54:41 +0000555 assert(((isa<ConstantExpr>(GEP) &&
556 cast<ConstantExpr>(GEP)->getOpcode()==Instruction::GetElementPtr)||
557 isa<GetElementPtrInst>(GEP)) && "NonGEP CE's are not SRAable!");
Misha Brukmanb1c93172005-04-21 23:48:37 +0000558
Chris Lattnerabab0712004-10-08 17:32:09 +0000559 // Ignore the 1th operand, which has to be zero or else the program is quite
560 // broken (undefined). Get the 2nd operand, which is the structure or array
561 // index.
Reid Spencere0fc4df2006-10-20 07:07:24 +0000562 unsigned Val = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
Chris Lattnerabab0712004-10-08 17:32:09 +0000563 if (Val >= NewGlobals.size()) Val = 0; // Out of bound array access.
564
Chris Lattner004e2502004-10-11 05:54:41 +0000565 Value *NewPtr = NewGlobals[Val];
Chris Lattnerabab0712004-10-08 17:32:09 +0000566
567 // Form a shorter GEP if needed.
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +0000568 if (GEP->getNumOperands() > 3) {
Chris Lattner004e2502004-10-11 05:54:41 +0000569 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEP)) {
Chris Lattnerf96f4a82007-01-31 04:40:53 +0000570 SmallVector<Constant*, 8> Idxs;
Chris Lattner004e2502004-10-11 05:54:41 +0000571 Idxs.push_back(NullInt);
572 for (unsigned i = 3, e = CE->getNumOperands(); i != e; ++i)
573 Idxs.push_back(CE->getOperand(i));
Jay Foaded8db7d2011-07-21 14:31:17 +0000574 NewPtr = ConstantExpr::getGetElementPtr(cast<Constant>(NewPtr), Idxs);
Chris Lattner004e2502004-10-11 05:54:41 +0000575 } else {
576 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(GEP);
Chris Lattner927653f2007-01-31 19:59:55 +0000577 SmallVector<Value*, 8> Idxs;
Chris Lattner004e2502004-10-11 05:54:41 +0000578 Idxs.push_back(NullInt);
579 for (unsigned i = 3, e = GEPI->getNumOperands(); i != e; ++i)
580 Idxs.push_back(GEPI->getOperand(i));
Jay Foadd1b78492011-07-25 09:48:08 +0000581 NewPtr = GetElementPtrInst::Create(NewPtr, Idxs,
Daniel Dunbar132f7832009-07-30 17:37:43 +0000582 GEPI->getName()+"."+Twine(Val),GEPI);
Chris Lattner004e2502004-10-11 05:54:41 +0000583 }
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +0000584 }
Chris Lattner004e2502004-10-11 05:54:41 +0000585 GEP->replaceAllUsesWith(NewPtr);
586
587 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(GEP))
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000588 GEPI->eraseFromParent();
Chris Lattner004e2502004-10-11 05:54:41 +0000589 else
590 cast<ConstantExpr>(GEP)->destroyConstant();
Chris Lattnerabab0712004-10-08 17:32:09 +0000591 }
592
Chris Lattner73ad73e2004-10-08 20:25:55 +0000593 // Delete the old global, now that it is dead.
594 Globals.erase(GV);
Chris Lattnerabab0712004-10-08 17:32:09 +0000595 ++NumSRA;
Chris Lattner004e2502004-10-11 05:54:41 +0000596
597 // Loop over the new globals array deleting any globals that are obviously
598 // dead. This can arise due to scalarization of a structure or an array that
599 // has elements that are dead.
600 unsigned FirstGlobal = 0;
601 for (unsigned i = 0, e = NewGlobals.size(); i != e; ++i)
602 if (NewGlobals[i]->use_empty()) {
603 Globals.erase(NewGlobals[i]);
604 if (FirstGlobal == i) ++FirstGlobal;
605 }
606
Craig Topperf40110f2014-04-25 05:29:35 +0000607 return FirstGlobal != NewGlobals.size() ? NewGlobals[FirstGlobal] : nullptr;
Chris Lattnerabab0712004-10-08 17:32:09 +0000608}
609
Chris Lattner09a52722004-10-09 21:48:45 +0000610/// AllUsesOfValueWillTrapIfNull - Return true if all users of the specified
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000611/// value will trap if the value is dynamically null. PHIs keeps track of any
Chris Lattner2d2892e2007-09-13 16:30:19 +0000612/// phi nodes we've seen to avoid reprocessing them.
Gabor Greif67972872010-04-06 19:24:18 +0000613static bool AllUsesOfValueWillTrapIfNull(const Value *V,
614 SmallPtrSet<const PHINode*, 8> &PHIs) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000615 for (const User *U : V->users())
Gabor Greif08355d62010-04-06 19:14:05 +0000616 if (isa<LoadInst>(U)) {
Chris Lattner09a52722004-10-09 21:48:45 +0000617 // Will trap.
Gabor Greif67972872010-04-06 19:24:18 +0000618 } else if (const StoreInst *SI = dyn_cast<StoreInst>(U)) {
Chris Lattner09a52722004-10-09 21:48:45 +0000619 if (SI->getOperand(0) == V) {
Gabor Greif08355d62010-04-06 19:14:05 +0000620 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner09a52722004-10-09 21:48:45 +0000621 return false; // Storing the value.
622 }
Gabor Greif67972872010-04-06 19:24:18 +0000623 } else if (const CallInst *CI = dyn_cast<CallInst>(U)) {
Gabor Greiffebf6ab2010-03-20 21:00:25 +0000624 if (CI->getCalledValue() != V) {
Gabor Greif08355d62010-04-06 19:14:05 +0000625 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner09a52722004-10-09 21:48:45 +0000626 return false; // Not calling the ptr
627 }
Gabor Greif67972872010-04-06 19:24:18 +0000628 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(U)) {
Gabor Greiffebf6ab2010-03-20 21:00:25 +0000629 if (II->getCalledValue() != V) {
Gabor Greif08355d62010-04-06 19:14:05 +0000630 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner09a52722004-10-09 21:48:45 +0000631 return false; // Not calling the ptr
632 }
Gabor Greif67972872010-04-06 19:24:18 +0000633 } else if (const BitCastInst *CI = dyn_cast<BitCastInst>(U)) {
Chris Lattner2d2892e2007-09-13 16:30:19 +0000634 if (!AllUsesOfValueWillTrapIfNull(CI, PHIs)) return false;
Gabor Greif67972872010-04-06 19:24:18 +0000635 } else if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
Chris Lattner2d2892e2007-09-13 16:30:19 +0000636 if (!AllUsesOfValueWillTrapIfNull(GEPI, PHIs)) return false;
Gabor Greif67972872010-04-06 19:24:18 +0000637 } else if (const PHINode *PN = dyn_cast<PHINode>(U)) {
Chris Lattner2d2892e2007-09-13 16:30:19 +0000638 // If we've already seen this phi node, ignore it, it has already been
639 // checked.
Jakob Stoklund Olesene27dc722010-01-29 23:54:14 +0000640 if (PHIs.insert(PN) && !AllUsesOfValueWillTrapIfNull(PN, PHIs))
641 return false;
Gabor Greif08355d62010-04-06 19:14:05 +0000642 } else if (isa<ICmpInst>(U) &&
Chandler Carruthcdf47882014-03-09 03:16:01 +0000643 isa<ConstantPointerNull>(U->getOperand(1))) {
Nick Lewycky614fb942010-02-25 06:39:10 +0000644 // Ignore icmp X, null
Chris Lattner09a52722004-10-09 21:48:45 +0000645 } else {
Gabor Greif08355d62010-04-06 19:14:05 +0000646 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner09a52722004-10-09 21:48:45 +0000647 return false;
648 }
Chandler Carruthcdf47882014-03-09 03:16:01 +0000649
Chris Lattner09a52722004-10-09 21:48:45 +0000650 return true;
651}
652
653/// AllUsesOfLoadedValueWillTrapIfNull - Return true if all uses of any loads
Chris Lattnerfe9abf92004-10-22 06:43:28 +0000654/// from GV will trap if the loaded value is null. Note that this also permits
655/// comparisons of the loaded value against null, as a special case.
Gabor Greif67972872010-04-06 19:24:18 +0000656static bool AllUsesOfLoadedValueWillTrapIfNull(const GlobalVariable *GV) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000657 for (const User *U : GV->users())
Gabor Greif67972872010-04-06 19:24:18 +0000658 if (const LoadInst *LI = dyn_cast<LoadInst>(U)) {
659 SmallPtrSet<const PHINode*, 8> PHIs;
Chris Lattner2d2892e2007-09-13 16:30:19 +0000660 if (!AllUsesOfValueWillTrapIfNull(LI, PHIs))
Chris Lattner09a52722004-10-09 21:48:45 +0000661 return false;
Gabor Greif08355d62010-04-06 19:14:05 +0000662 } else if (isa<StoreInst>(U)) {
Chris Lattner09a52722004-10-09 21:48:45 +0000663 // Ignore stores to the global.
664 } else {
665 // We don't know or understand this user, bail out.
Gabor Greif08355d62010-04-06 19:14:05 +0000666 //cerr << "UNKNOWN USER OF GLOBAL!: " << *U;
Chris Lattner09a52722004-10-09 21:48:45 +0000667 return false;
668 }
Chris Lattner09a52722004-10-09 21:48:45 +0000669 return true;
670}
671
Chris Lattner46b5c642009-11-06 04:27:31 +0000672static bool OptimizeAwayTrappingUsesOfValue(Value *V, Constant *NewV) {
Chris Lattnere42eb312004-10-10 23:14:11 +0000673 bool Changed = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000674 for (auto UI = V->user_begin(), E = V->user_end(); UI != E; ) {
Chris Lattnere42eb312004-10-10 23:14:11 +0000675 Instruction *I = cast<Instruction>(*UI++);
676 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
677 LI->setOperand(0, NewV);
678 Changed = true;
679 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
680 if (SI->getOperand(1) == V) {
681 SI->setOperand(1, NewV);
682 Changed = true;
683 }
684 } else if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
Gabor Greif04397892010-04-06 18:45:08 +0000685 CallSite CS(I);
686 if (CS.getCalledValue() == V) {
Chris Lattnere42eb312004-10-10 23:14:11 +0000687 // Calling through the pointer! Turn into a direct call, but be careful
688 // that the pointer is not also being passed as an argument.
Gabor Greif04397892010-04-06 18:45:08 +0000689 CS.setCalledFunction(NewV);
Chris Lattnere42eb312004-10-10 23:14:11 +0000690 Changed = true;
691 bool PassedAsArg = false;
Gabor Greif04397892010-04-06 18:45:08 +0000692 for (unsigned i = 0, e = CS.arg_size(); i != e; ++i)
693 if (CS.getArgument(i) == V) {
Chris Lattnere42eb312004-10-10 23:14:11 +0000694 PassedAsArg = true;
Gabor Greif04397892010-04-06 18:45:08 +0000695 CS.setArgument(i, NewV);
Chris Lattnere42eb312004-10-10 23:14:11 +0000696 }
697
698 if (PassedAsArg) {
699 // Being passed as an argument also. Be careful to not invalidate UI!
Chandler Carruthcdf47882014-03-09 03:16:01 +0000700 UI = V->user_begin();
Chris Lattnere42eb312004-10-10 23:14:11 +0000701 }
702 }
703 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
704 Changed |= OptimizeAwayTrappingUsesOfValue(CI,
Owen Anderson487375e2009-07-29 18:55:55 +0000705 ConstantExpr::getCast(CI->getOpcode(),
Chris Lattner46b5c642009-11-06 04:27:31 +0000706 NewV, CI->getType()));
Chris Lattnere42eb312004-10-10 23:14:11 +0000707 if (CI->use_empty()) {
708 Changed = true;
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000709 CI->eraseFromParent();
Chris Lattnere42eb312004-10-10 23:14:11 +0000710 }
711 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
712 // Should handle GEP here.
Chris Lattnerf96f4a82007-01-31 04:40:53 +0000713 SmallVector<Constant*, 8> Idxs;
714 Idxs.reserve(GEPI->getNumOperands()-1);
Gabor Greif3a9fba52008-05-29 01:59:18 +0000715 for (User::op_iterator i = GEPI->op_begin() + 1, e = GEPI->op_end();
716 i != e; ++i)
717 if (Constant *C = dyn_cast<Constant>(*i))
Chris Lattnerf96f4a82007-01-31 04:40:53 +0000718 Idxs.push_back(C);
Chris Lattnere42eb312004-10-10 23:14:11 +0000719 else
720 break;
Chris Lattnerf96f4a82007-01-31 04:40:53 +0000721 if (Idxs.size() == GEPI->getNumOperands()-1)
Chris Lattnere42eb312004-10-10 23:14:11 +0000722 Changed |= OptimizeAwayTrappingUsesOfValue(GEPI,
Jay Foaded8db7d2011-07-21 14:31:17 +0000723 ConstantExpr::getGetElementPtr(NewV, Idxs));
Chris Lattnere42eb312004-10-10 23:14:11 +0000724 if (GEPI->use_empty()) {
725 Changed = true;
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000726 GEPI->eraseFromParent();
Chris Lattnere42eb312004-10-10 23:14:11 +0000727 }
728 }
729 }
730
731 return Changed;
732}
733
734
735/// OptimizeAwayTrappingUsesOfLoads - The specified global has only one non-null
736/// value stored into it. If there are uses of the loaded value that would trap
737/// if the loaded value is dynamically null, then we know that they cannot be
738/// reachable with a null optimize away the load.
Nick Lewyckycf6aae62012-02-12 01:13:18 +0000739static bool OptimizeAwayTrappingUsesOfLoads(GlobalVariable *GV, Constant *LV,
Rafael Espindolaaeff8a92014-02-24 23:12:18 +0000740 const DataLayout *DL,
Nick Lewyckycf6aae62012-02-12 01:13:18 +0000741 TargetLibraryInfo *TLI) {
Chris Lattnere42eb312004-10-10 23:14:11 +0000742 bool Changed = false;
743
Chris Lattner2538eb62009-01-14 00:12:58 +0000744 // Keep track of whether we are able to remove all the uses of the global
745 // other than the store that defines it.
746 bool AllNonStoreUsesGone = true;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000747
Chris Lattnere42eb312004-10-10 23:14:11 +0000748 // Replace all uses of loads with uses of uses of the stored value.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000749 for (Value::user_iterator GUI = GV->user_begin(), E = GV->user_end(); GUI != E;){
Chris Lattner2538eb62009-01-14 00:12:58 +0000750 User *GlobalUser = *GUI++;
751 if (LoadInst *LI = dyn_cast<LoadInst>(GlobalUser)) {
Chris Lattner46b5c642009-11-06 04:27:31 +0000752 Changed |= OptimizeAwayTrappingUsesOfValue(LI, LV);
Chris Lattner2538eb62009-01-14 00:12:58 +0000753 // If we were able to delete all uses of the loads
754 if (LI->use_empty()) {
755 LI->eraseFromParent();
756 Changed = true;
757 } else {
758 AllNonStoreUsesGone = false;
759 }
760 } else if (isa<StoreInst>(GlobalUser)) {
761 // Ignore the store that stores "LV" to the global.
762 assert(GlobalUser->getOperand(1) == GV &&
763 "Must be storing *to* the global");
Chris Lattnere42eb312004-10-10 23:14:11 +0000764 } else {
Chris Lattner2538eb62009-01-14 00:12:58 +0000765 AllNonStoreUsesGone = false;
766
767 // If we get here we could have other crazy uses that are transitively
768 // loaded.
769 assert((isa<PHINode>(GlobalUser) || isa<SelectInst>(GlobalUser) ||
Benjamin Kramered843602012-09-28 10:01:27 +0000770 isa<ConstantExpr>(GlobalUser) || isa<CmpInst>(GlobalUser) ||
771 isa<BitCastInst>(GlobalUser) ||
772 isa<GetElementPtrInst>(GlobalUser)) &&
Chris Lattner1a1acc22011-05-22 07:15:13 +0000773 "Only expect load and stores!");
Chris Lattnere42eb312004-10-10 23:14:11 +0000774 }
Chris Lattner2538eb62009-01-14 00:12:58 +0000775 }
Chris Lattnere42eb312004-10-10 23:14:11 +0000776
777 if (Changed) {
David Greene44cb8ad2010-01-05 01:28:05 +0000778 DEBUG(dbgs() << "OPTIMIZED LOADS FROM STORED ONCE POINTER: " << *GV);
Chris Lattnere42eb312004-10-10 23:14:11 +0000779 ++NumGlobUses;
780 }
781
Chris Lattnere42eb312004-10-10 23:14:11 +0000782 // If we nuked all of the loads, then none of the stores are needed either,
783 // nor is the global.
Chris Lattner2538eb62009-01-14 00:12:58 +0000784 if (AllNonStoreUsesGone) {
Nick Lewyckyfaa9c3b02012-07-24 07:21:08 +0000785 if (isLeakCheckerRoot(GV)) {
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000786 Changed |= CleanupPointerRootUsers(GV, TLI);
Nick Lewyckyfaa9c3b02012-07-24 07:21:08 +0000787 } else {
788 Changed = true;
Craig Topperf40110f2014-04-25 05:29:35 +0000789 CleanupConstantGlobalUsers(GV, nullptr, DL, TLI);
Nick Lewyckyfaa9c3b02012-07-24 07:21:08 +0000790 }
Chris Lattnere42eb312004-10-10 23:14:11 +0000791 if (GV->use_empty()) {
Nick Lewyckyfaa9c3b02012-07-24 07:21:08 +0000792 DEBUG(dbgs() << " *** GLOBAL NOW DEAD!\n");
793 Changed = true;
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000794 GV->eraseFromParent();
Chris Lattnere42eb312004-10-10 23:14:11 +0000795 ++NumDeleted;
796 }
Chris Lattnere42eb312004-10-10 23:14:11 +0000797 }
798 return Changed;
799}
800
Chris Lattner004e2502004-10-11 05:54:41 +0000801/// ConstantPropUsersOf - Walk the use list of V, constant folding all of the
802/// instructions that are foldable.
Rafael Espindolaaeff8a92014-02-24 23:12:18 +0000803static void ConstantPropUsersOf(Value *V, const DataLayout *DL,
804 TargetLibraryInfo *TLI) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000805 for (Value::user_iterator UI = V->user_begin(), E = V->user_end(); UI != E; )
Chris Lattner004e2502004-10-11 05:54:41 +0000806 if (Instruction *I = dyn_cast<Instruction>(*UI++))
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000807 if (Constant *NewC = ConstantFoldInstruction(I, DL, TLI)) {
Chris Lattner004e2502004-10-11 05:54:41 +0000808 I->replaceAllUsesWith(NewC);
809
Chris Lattnerd6a44922005-02-01 01:23:31 +0000810 // Advance UI to the next non-I use to avoid invalidating it!
811 // Instructions could multiply use V.
812 while (UI != E && *UI == I)
Chris Lattner004e2502004-10-11 05:54:41 +0000813 ++UI;
Chris Lattnerd6a44922005-02-01 01:23:31 +0000814 I->eraseFromParent();
Chris Lattner004e2502004-10-11 05:54:41 +0000815 }
816}
817
818/// OptimizeGlobalAddressOfMalloc - This function takes the specified global
819/// variable, and transforms the program as if it always contained the result of
820/// the specified malloc. Because it is always the result of the specified
821/// malloc, there is no reason to actually DO the malloc. Instead, turn the
Chris Lattner3ede00b2006-11-30 17:32:29 +0000822/// malloc into a global, and any loads of GV as uses of the new global.
Chris Lattner004e2502004-10-11 05:54:41 +0000823static GlobalVariable *OptimizeGlobalAddressOfMalloc(GlobalVariable *GV,
Victor Hernandez5d034492009-09-18 22:35:49 +0000824 CallInst *CI,
Chris Lattner229907c2011-07-18 04:54:35 +0000825 Type *AllocTy,
Chris Lattner7939f792010-02-25 22:33:52 +0000826 ConstantInt *NElements,
Rafael Espindolaaeff8a92014-02-24 23:12:18 +0000827 const DataLayout *DL,
Nick Lewyckycf6aae62012-02-12 01:13:18 +0000828 TargetLibraryInfo *TLI) {
Chris Lattner7939f792010-02-25 22:33:52 +0000829 DEBUG(errs() << "PROMOTING GLOBAL: " << *GV << " CALL = " << *CI << '\n');
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000830
Chris Lattner229907c2011-07-18 04:54:35 +0000831 Type *GlobalType;
Chris Lattner7939f792010-02-25 22:33:52 +0000832 if (NElements->getZExtValue() == 1)
833 GlobalType = AllocTy;
834 else
835 // If we have an array allocation, the global variable is of an array.
836 GlobalType = ArrayType::get(AllocTy, NElements->getZExtValue());
Victor Hernandez5d034492009-09-18 22:35:49 +0000837
838 // Create the new global variable. The contents of the malloc'd memory is
839 // undefined, so initialize with an undef value.
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000840 GlobalVariable *NewGV = new GlobalVariable(*GV->getParent(),
Chris Lattner65d3a0a2010-02-26 23:42:13 +0000841 GlobalType, false,
Chris Lattner7939f792010-02-25 22:33:52 +0000842 GlobalValue::InternalLinkage,
Chris Lattner65d3a0a2010-02-26 23:42:13 +0000843 UndefValue::get(GlobalType),
Victor Hernandez5d034492009-09-18 22:35:49 +0000844 GV->getName()+".body",
845 GV,
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000846 GV->getThreadLocalMode());
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000847
Chris Lattner7939f792010-02-25 22:33:52 +0000848 // If there are bitcast users of the malloc (which is typical, usually we have
849 // a malloc + bitcast) then replace them with uses of the new global. Update
850 // other users to use the global as well.
Craig Topperf40110f2014-04-25 05:29:35 +0000851 BitCastInst *TheBC = nullptr;
Chris Lattner7939f792010-02-25 22:33:52 +0000852 while (!CI->use_empty()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000853 Instruction *User = cast<Instruction>(CI->user_back());
Chris Lattner7939f792010-02-25 22:33:52 +0000854 if (BitCastInst *BCI = dyn_cast<BitCastInst>(User)) {
855 if (BCI->getType() == NewGV->getType()) {
856 BCI->replaceAllUsesWith(NewGV);
857 BCI->eraseFromParent();
858 } else {
859 BCI->setOperand(0, NewGV);
860 }
861 } else {
Craig Topperf40110f2014-04-25 05:29:35 +0000862 if (!TheBC)
Chris Lattner7939f792010-02-25 22:33:52 +0000863 TheBC = new BitCastInst(NewGV, CI->getType(), "newgv", CI);
864 User->replaceUsesOfWith(CI, TheBC);
865 }
866 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000867
Victor Hernandez5d034492009-09-18 22:35:49 +0000868 Constant *RepValue = NewGV;
869 if (NewGV->getType() != GV->getType()->getElementType())
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000870 RepValue = ConstantExpr::getBitCast(RepValue,
Victor Hernandez5d034492009-09-18 22:35:49 +0000871 GV->getType()->getElementType());
872
873 // If there is a comparison against null, we will insert a global bool to
874 // keep track of whether the global was initialized yet or not.
875 GlobalVariable *InitBool =
Chris Lattner46b5c642009-11-06 04:27:31 +0000876 new GlobalVariable(Type::getInt1Ty(GV->getContext()), false,
Victor Hernandez5d034492009-09-18 22:35:49 +0000877 GlobalValue::InternalLinkage,
Chris Lattner46b5c642009-11-06 04:27:31 +0000878 ConstantInt::getFalse(GV->getContext()),
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000879 GV->getName()+".init", GV->getThreadLocalMode());
Victor Hernandez5d034492009-09-18 22:35:49 +0000880 bool InitBoolUsed = false;
881
882 // Loop over all uses of GV, processing them in turn.
Chris Lattner7939f792010-02-25 22:33:52 +0000883 while (!GV->use_empty()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000884 if (StoreInst *SI = dyn_cast<StoreInst>(GV->user_back())) {
Victor Hernandez5d034492009-09-18 22:35:49 +0000885 // The global is initialized when the store to it occurs.
Nick Lewycky52da72b2012-02-05 19:56:38 +0000886 new StoreInst(ConstantInt::getTrue(GV->getContext()), InitBool, false, 0,
887 SI->getOrdering(), SI->getSynchScope(), SI);
Victor Hernandez5d034492009-09-18 22:35:49 +0000888 SI->eraseFromParent();
Chris Lattner7939f792010-02-25 22:33:52 +0000889 continue;
Victor Hernandez5d034492009-09-18 22:35:49 +0000890 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000891
Chandler Carruthcdf47882014-03-09 03:16:01 +0000892 LoadInst *LI = cast<LoadInst>(GV->user_back());
Chris Lattner7939f792010-02-25 22:33:52 +0000893 while (!LI->use_empty()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000894 Use &LoadUse = *LI->use_begin();
895 ICmpInst *ICI = dyn_cast<ICmpInst>(LoadUse.getUser());
896 if (!ICI) {
Chris Lattner7939f792010-02-25 22:33:52 +0000897 LoadUse = RepValue;
898 continue;
899 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000900
Chris Lattner7939f792010-02-25 22:33:52 +0000901 // Replace the cmp X, 0 with a use of the bool value.
Nick Lewycky52da72b2012-02-05 19:56:38 +0000902 // Sink the load to where the compare was, if atomic rules allow us to.
903 Value *LV = new LoadInst(InitBool, InitBool->getName()+".val", false, 0,
904 LI->getOrdering(), LI->getSynchScope(),
905 LI->isUnordered() ? (Instruction*)ICI : LI);
Chris Lattner7939f792010-02-25 22:33:52 +0000906 InitBoolUsed = true;
907 switch (ICI->getPredicate()) {
908 default: llvm_unreachable("Unknown ICmp Predicate!");
909 case ICmpInst::ICMP_ULT:
910 case ICmpInst::ICMP_SLT: // X < null -> always false
911 LV = ConstantInt::getFalse(GV->getContext());
912 break;
913 case ICmpInst::ICMP_ULE:
914 case ICmpInst::ICMP_SLE:
915 case ICmpInst::ICMP_EQ:
916 LV = BinaryOperator::CreateNot(LV, "notinit", ICI);
917 break;
918 case ICmpInst::ICMP_NE:
919 case ICmpInst::ICMP_UGE:
920 case ICmpInst::ICMP_SGE:
921 case ICmpInst::ICMP_UGT:
922 case ICmpInst::ICMP_SGT:
923 break; // no change.
924 }
925 ICI->replaceAllUsesWith(LV);
926 ICI->eraseFromParent();
927 }
928 LI->eraseFromParent();
929 }
Victor Hernandez5d034492009-09-18 22:35:49 +0000930
931 // If the initialization boolean was used, insert it, otherwise delete it.
932 if (!InitBoolUsed) {
933 while (!InitBool->use_empty()) // Delete initializations
Chandler Carruthcdf47882014-03-09 03:16:01 +0000934 cast<StoreInst>(InitBool->user_back())->eraseFromParent();
Victor Hernandez5d034492009-09-18 22:35:49 +0000935 delete InitBool;
936 } else
937 GV->getParent()->getGlobalList().insert(GV, InitBool);
938
Chris Lattner7939f792010-02-25 22:33:52 +0000939 // Now the GV is dead, nuke it and the malloc..
Victor Hernandez5d034492009-09-18 22:35:49 +0000940 GV->eraseFromParent();
Victor Hernandez5d034492009-09-18 22:35:49 +0000941 CI->eraseFromParent();
942
943 // To further other optimizations, loop over all users of NewGV and try to
944 // constant prop them. This will promote GEP instructions with constant
945 // indices into GEP constant-exprs, which will allow global-opt to hack on it.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000946 ConstantPropUsersOf(NewGV, DL, TLI);
Victor Hernandez5d034492009-09-18 22:35:49 +0000947 if (RepValue != NewGV)
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000948 ConstantPropUsersOf(RepValue, DL, TLI);
Victor Hernandez5d034492009-09-18 22:35:49 +0000949
950 return NewGV;
951}
952
Chris Lattnerc0677c02004-12-02 07:11:07 +0000953/// ValueIsOnlyUsedLocallyOrStoredToOneGlobal - Scan the use-list of V checking
954/// to make sure that there are no complex uses of V. We permit simple things
955/// like dereferencing the pointer, but not storing through the address, unless
956/// it is to the specified global.
Gabor Greifa21bc0f2010-04-06 18:58:22 +0000957static bool ValueIsOnlyUsedLocallyOrStoredToOneGlobal(const Instruction *V,
958 const GlobalVariable *GV,
Gabor Greif08355d62010-04-06 19:14:05 +0000959 SmallPtrSet<const PHINode*, 8> &PHIs) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000960 for (const User *U : V->users()) {
961 const Instruction *Inst = cast<Instruction>(U);
Gabor Greif08355d62010-04-06 19:14:05 +0000962
Chris Lattnerf0eb5682008-12-15 21:08:54 +0000963 if (isa<LoadInst>(Inst) || isa<CmpInst>(Inst)) {
964 continue; // Fine, ignore.
965 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000966
Gabor Greifa21bc0f2010-04-06 18:58:22 +0000967 if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
Chris Lattnerc0677c02004-12-02 07:11:07 +0000968 if (SI->getOperand(0) == V && SI->getOperand(1) != GV)
969 return false; // Storing the pointer itself... bad.
Chris Lattnerf0eb5682008-12-15 21:08:54 +0000970 continue; // Otherwise, storing through it, or storing into GV... fine.
971 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000972
Chris Lattnerb9801ff2010-04-10 18:19:22 +0000973 // Must index into the array and into the struct.
974 if (isa<GetElementPtrInst>(Inst) && Inst->getNumOperands() >= 3) {
Chris Lattnerf0eb5682008-12-15 21:08:54 +0000975 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(Inst, GV, PHIs))
Chris Lattnerc0677c02004-12-02 07:11:07 +0000976 return false;
Chris Lattnerf0eb5682008-12-15 21:08:54 +0000977 continue;
978 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000979
Gabor Greifa21bc0f2010-04-06 18:58:22 +0000980 if (const PHINode *PN = dyn_cast<PHINode>(Inst)) {
Chris Lattner6eed0e72007-09-13 16:37:20 +0000981 // PHIs are ok if all uses are ok. Don't infinitely recurse through PHI
982 // cycles.
983 if (PHIs.insert(PN))
Chris Lattner5d13fb532007-09-14 03:41:21 +0000984 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(PN, GV, PHIs))
985 return false;
Chris Lattnerf0eb5682008-12-15 21:08:54 +0000986 continue;
Chris Lattnerc0677c02004-12-02 07:11:07 +0000987 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000988
Gabor Greifa21bc0f2010-04-06 18:58:22 +0000989 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Inst)) {
Chris Lattnerf0eb5682008-12-15 21:08:54 +0000990 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(BCI, GV, PHIs))
991 return false;
992 continue;
993 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000994
Chris Lattnerf0eb5682008-12-15 21:08:54 +0000995 return false;
996 }
Chris Lattnerc0677c02004-12-02 07:11:07 +0000997 return true;
Chris Lattnerc0677c02004-12-02 07:11:07 +0000998}
999
Chris Lattner24d3d422006-09-30 23:32:09 +00001000/// ReplaceUsesOfMallocWithGlobal - The Alloc pointer is stored into GV
1001/// somewhere. Transform all uses of the allocation into loads from the
1002/// global and uses of the resultant pointer. Further, delete the store into
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001003/// GV. This assumes that these value pass the
Chris Lattner24d3d422006-09-30 23:32:09 +00001004/// 'ValueIsOnlyUsedLocallyOrStoredToOneGlobal' predicate.
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001005static void ReplaceUsesOfMallocWithGlobal(Instruction *Alloc,
Chris Lattner24d3d422006-09-30 23:32:09 +00001006 GlobalVariable *GV) {
1007 while (!Alloc->use_empty()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00001008 Instruction *U = cast<Instruction>(*Alloc->user_begin());
Chris Lattnerba98f892007-09-13 18:00:31 +00001009 Instruction *InsertPt = U;
Chris Lattner24d3d422006-09-30 23:32:09 +00001010 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
1011 // If this is the store of the allocation into the global, remove it.
1012 if (SI->getOperand(1) == GV) {
1013 SI->eraseFromParent();
1014 continue;
1015 }
Chris Lattnerba98f892007-09-13 18:00:31 +00001016 } else if (PHINode *PN = dyn_cast<PHINode>(U)) {
1017 // Insert the load in the corresponding predecessor, not right before the
1018 // PHI.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001019 InsertPt = PN->getIncomingBlock(*Alloc->use_begin())->getTerminator();
Chris Lattner49e3bdc2008-12-15 21:44:34 +00001020 } else if (isa<BitCastInst>(U)) {
1021 // Must be bitcast between the malloc and store to initialize the global.
1022 ReplaceUsesOfMallocWithGlobal(U, GV);
1023 U->eraseFromParent();
1024 continue;
1025 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
1026 // If this is a "GEP bitcast" and the user is a store to the global, then
1027 // just process it as a bitcast.
1028 if (GEPI->hasAllZeroIndices() && GEPI->hasOneUse())
Chandler Carruthcdf47882014-03-09 03:16:01 +00001029 if (StoreInst *SI = dyn_cast<StoreInst>(GEPI->user_back()))
Chris Lattner49e3bdc2008-12-15 21:44:34 +00001030 if (SI->getOperand(1) == GV) {
1031 // Must be bitcast GEP between the malloc and store to initialize
1032 // the global.
1033 ReplaceUsesOfMallocWithGlobal(GEPI, GV);
1034 GEPI->eraseFromParent();
1035 continue;
1036 }
Chris Lattner24d3d422006-09-30 23:32:09 +00001037 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001038
Chris Lattner24d3d422006-09-30 23:32:09 +00001039 // Insert a load from the global, and use it instead of the malloc.
Chris Lattnerba98f892007-09-13 18:00:31 +00001040 Value *NL = new LoadInst(GV, GV->getName()+".val", InsertPt);
Chris Lattner24d3d422006-09-30 23:32:09 +00001041 U->replaceUsesOfWith(Alloc, NL);
1042 }
1043}
1044
Chris Lattner56b55382008-12-16 21:24:51 +00001045/// LoadUsesSimpleEnoughForHeapSRA - Verify that all uses of V (a load, or a phi
1046/// of a load) are simple enough to perform heap SRA on. This permits GEP's
1047/// that index through the array and struct field, icmps of null, and PHIs.
Gabor Greif5d5db532010-04-01 08:21:08 +00001048static bool LoadUsesSimpleEnoughForHeapSRA(const Value *V,
Gabor Greif08d85da2010-04-07 18:59:26 +00001049 SmallPtrSet<const PHINode*, 32> &LoadUsingPHIs,
1050 SmallPtrSet<const PHINode*, 32> &LoadUsingPHIsPerLoad) {
Chris Lattner56b55382008-12-16 21:24:51 +00001051 // We permit two users of the load: setcc comparing against the null
1052 // pointer, and a getelementptr of a specific form.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001053 for (const User *U : V->users()) {
1054 const Instruction *UI = cast<Instruction>(U);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001055
Chris Lattner56b55382008-12-16 21:24:51 +00001056 // Comparison against null is ok.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001057 if (const ICmpInst *ICI = dyn_cast<ICmpInst>(UI)) {
Chris Lattner56b55382008-12-16 21:24:51 +00001058 if (!isa<ConstantPointerNull>(ICI->getOperand(1)))
1059 return false;
1060 continue;
1061 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001062
Chris Lattner56b55382008-12-16 21:24:51 +00001063 // getelementptr is also ok, but only a simple form.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001064 if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(UI)) {
Chris Lattner56b55382008-12-16 21:24:51 +00001065 // Must index into the array and into the struct.
1066 if (GEPI->getNumOperands() < 3)
1067 return false;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001068
Chris Lattner56b55382008-12-16 21:24:51 +00001069 // Otherwise the GEP is ok.
1070 continue;
1071 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001072
Chandler Carruthcdf47882014-03-09 03:16:01 +00001073 if (const PHINode *PN = dyn_cast<PHINode>(UI)) {
Evan Cheng83689442009-06-02 00:56:07 +00001074 if (!LoadUsingPHIsPerLoad.insert(PN))
1075 // This means some phi nodes are dependent on each other.
1076 // Avoid infinite looping!
1077 return false;
1078 if (!LoadUsingPHIs.insert(PN))
1079 // If we have already analyzed this PHI, then it is safe.
Chris Lattner56b55382008-12-16 21:24:51 +00001080 continue;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001081
Chris Lattner222ef4c2008-12-17 05:28:49 +00001082 // Make sure all uses of the PHI are simple enough to transform.
Evan Cheng83689442009-06-02 00:56:07 +00001083 if (!LoadUsesSimpleEnoughForHeapSRA(PN,
1084 LoadUsingPHIs, LoadUsingPHIsPerLoad))
Chris Lattner56b55382008-12-16 21:24:51 +00001085 return false;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001086
Chris Lattner56b55382008-12-16 21:24:51 +00001087 continue;
Chris Lattner24d3d422006-09-30 23:32:09 +00001088 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001089
Chris Lattner56b55382008-12-16 21:24:51 +00001090 // Otherwise we don't know what this is, not ok.
1091 return false;
1092 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001093
Chris Lattner56b55382008-12-16 21:24:51 +00001094 return true;
1095}
1096
1097
1098/// AllGlobalLoadUsesSimpleEnoughForHeapSRA - If all users of values loaded from
1099/// GV are simple enough to perform HeapSRA, return true.
Gabor Greif5d5db532010-04-01 08:21:08 +00001100static bool AllGlobalLoadUsesSimpleEnoughForHeapSRA(const GlobalVariable *GV,
Victor Hernandez5d034492009-09-18 22:35:49 +00001101 Instruction *StoredVal) {
Gabor Greif5d5db532010-04-01 08:21:08 +00001102 SmallPtrSet<const PHINode*, 32> LoadUsingPHIs;
1103 SmallPtrSet<const PHINode*, 32> LoadUsingPHIsPerLoad;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001104 for (const User *U : GV->users())
1105 if (const LoadInst *LI = dyn_cast<LoadInst>(U)) {
Evan Cheng83689442009-06-02 00:56:07 +00001106 if (!LoadUsesSimpleEnoughForHeapSRA(LI, LoadUsingPHIs,
1107 LoadUsingPHIsPerLoad))
Chris Lattner56b55382008-12-16 21:24:51 +00001108 return false;
Evan Cheng83689442009-06-02 00:56:07 +00001109 LoadUsingPHIsPerLoad.clear();
1110 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001111
Chris Lattner222ef4c2008-12-17 05:28:49 +00001112 // If we reach here, we know that all uses of the loads and transitive uses
1113 // (through PHI nodes) are simple enough to transform. However, we don't know
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001114 // that all inputs the to the PHI nodes are in the same equivalence sets.
Chris Lattner222ef4c2008-12-17 05:28:49 +00001115 // Check to verify that all operands of the PHIs are either PHIS that can be
1116 // transformed, loads from GV, or MI itself.
Gabor Greif08d85da2010-04-07 18:59:26 +00001117 for (SmallPtrSet<const PHINode*, 32>::const_iterator I = LoadUsingPHIs.begin()
1118 , E = LoadUsingPHIs.end(); I != E; ++I) {
Gabor Greif5d5db532010-04-01 08:21:08 +00001119 const PHINode *PN = *I;
Chris Lattner222ef4c2008-12-17 05:28:49 +00001120 for (unsigned op = 0, e = PN->getNumIncomingValues(); op != e; ++op) {
1121 Value *InVal = PN->getIncomingValue(op);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001122
Chris Lattner222ef4c2008-12-17 05:28:49 +00001123 // PHI of the stored value itself is ok.
Victor Hernandez5d034492009-09-18 22:35:49 +00001124 if (InVal == StoredVal) continue;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001125
Gabor Greif5d5db532010-04-01 08:21:08 +00001126 if (const PHINode *InPN = dyn_cast<PHINode>(InVal)) {
Chris Lattner222ef4c2008-12-17 05:28:49 +00001127 // One of the PHIs in our set is (optimistically) ok.
1128 if (LoadUsingPHIs.count(InPN))
1129 continue;
1130 return false;
1131 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001132
Chris Lattner222ef4c2008-12-17 05:28:49 +00001133 // Load from GV is ok.
Gabor Greif5d5db532010-04-01 08:21:08 +00001134 if (const LoadInst *LI = dyn_cast<LoadInst>(InVal))
Chris Lattner222ef4c2008-12-17 05:28:49 +00001135 if (LI->getOperand(0) == GV)
1136 continue;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001137
Chris Lattner222ef4c2008-12-17 05:28:49 +00001138 // UNDEF? NULL?
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001139
Chris Lattner222ef4c2008-12-17 05:28:49 +00001140 // Anything else is rejected.
1141 return false;
1142 }
1143 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001144
Chris Lattner24d3d422006-09-30 23:32:09 +00001145 return true;
1146}
1147
Chris Lattner222ef4c2008-12-17 05:28:49 +00001148static Value *GetHeapSROAValue(Value *V, unsigned FieldNo,
1149 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Chris Lattner46b5c642009-11-06 04:27:31 +00001150 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
Chris Lattner222ef4c2008-12-17 05:28:49 +00001151 std::vector<Value*> &FieldVals = InsertedScalarizedValues[V];
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001152
Chris Lattner222ef4c2008-12-17 05:28:49 +00001153 if (FieldNo >= FieldVals.size())
1154 FieldVals.resize(FieldNo+1);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001155
Chris Lattner222ef4c2008-12-17 05:28:49 +00001156 // If we already have this value, just reuse the previously scalarized
1157 // version.
1158 if (Value *FieldVal = FieldVals[FieldNo])
1159 return FieldVal;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001160
Chris Lattner222ef4c2008-12-17 05:28:49 +00001161 // Depending on what instruction this is, we have several cases.
1162 Value *Result;
1163 if (LoadInst *LI = dyn_cast<LoadInst>(V)) {
1164 // This is a scalarized version of the load from the global. Just create
1165 // a new Load of the scalarized global.
1166 Result = new LoadInst(GetHeapSROAValue(LI->getOperand(0), FieldNo,
1167 InsertedScalarizedValues,
Chris Lattner46b5c642009-11-06 04:27:31 +00001168 PHIsToRewrite),
Daniel Dunbar132f7832009-07-30 17:37:43 +00001169 LI->getName()+".f"+Twine(FieldNo), LI);
Chris Lattner222ef4c2008-12-17 05:28:49 +00001170 } else if (PHINode *PN = dyn_cast<PHINode>(V)) {
1171 // PN's type is pointer to struct. Make a new PHI of pointer to struct
1172 // field.
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001173
Matt Arsenaultfcd74012014-04-23 20:36:10 +00001174 PointerType *PTy = cast<PointerType>(PN->getType());
1175 StructType *ST = cast<StructType>(PTy->getElementType());
1176
1177 unsigned AS = PTy->getAddressSpace();
Jay Foade0938d82011-03-30 11:19:20 +00001178 PHINode *NewPN =
Matt Arsenaultfcd74012014-04-23 20:36:10 +00001179 PHINode::Create(PointerType::get(ST->getElementType(FieldNo), AS),
Jay Foad52131342011-03-30 11:28:46 +00001180 PN->getNumIncomingValues(),
Daniel Dunbar132f7832009-07-30 17:37:43 +00001181 PN->getName()+".f"+Twine(FieldNo), PN);
Jay Foade0938d82011-03-30 11:19:20 +00001182 Result = NewPN;
Chris Lattner222ef4c2008-12-17 05:28:49 +00001183 PHIsToRewrite.push_back(std::make_pair(PN, FieldNo));
1184 } else {
Torok Edwinfbcc6632009-07-14 16:55:14 +00001185 llvm_unreachable("Unknown usable value");
Chris Lattner222ef4c2008-12-17 05:28:49 +00001186 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001187
Chris Lattner222ef4c2008-12-17 05:28:49 +00001188 return FieldVals[FieldNo] = Result;
Chris Lattnerba98f892007-09-13 18:00:31 +00001189}
1190
Chris Lattnerf315d4f2007-09-13 17:29:05 +00001191/// RewriteHeapSROALoadUser - Given a load instruction and a value derived from
1192/// the load, rewrite the derived value to use the HeapSRoA'd load.
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001193static void RewriteHeapSROALoadUser(Instruction *LoadUser,
Chris Lattner222ef4c2008-12-17 05:28:49 +00001194 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Chris Lattner46b5c642009-11-06 04:27:31 +00001195 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
Chris Lattnerf315d4f2007-09-13 17:29:05 +00001196 // If this is a comparison against null, handle it.
1197 if (ICmpInst *SCI = dyn_cast<ICmpInst>(LoadUser)) {
1198 assert(isa<ConstantPointerNull>(SCI->getOperand(1)));
1199 // If we have a setcc of the loaded pointer, we can use a setcc of any
1200 // field.
Chris Lattner222ef4c2008-12-17 05:28:49 +00001201 Value *NPtr = GetHeapSROAValue(SCI->getOperand(0), 0,
Chris Lattner46b5c642009-11-06 04:27:31 +00001202 InsertedScalarizedValues, PHIsToRewrite);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001203
Owen Anderson1e5f00e2009-07-09 23:48:35 +00001204 Value *New = new ICmpInst(SCI, SCI->getPredicate(), NPtr,
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001205 Constant::getNullValue(NPtr->getType()),
Owen Anderson1e5f00e2009-07-09 23:48:35 +00001206 SCI->getName());
Chris Lattnerf315d4f2007-09-13 17:29:05 +00001207 SCI->replaceAllUsesWith(New);
1208 SCI->eraseFromParent();
1209 return;
1210 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001211
Chris Lattner222ef4c2008-12-17 05:28:49 +00001212 // Handle 'getelementptr Ptr, Idx, i32 FieldNo ...'
Chris Lattnerba98f892007-09-13 18:00:31 +00001213 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(LoadUser)) {
1214 assert(GEPI->getNumOperands() >= 3 && isa<ConstantInt>(GEPI->getOperand(2))
1215 && "Unexpected GEPI!");
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001216
Chris Lattnerba98f892007-09-13 18:00:31 +00001217 // Load the pointer for this field.
1218 unsigned FieldNo = cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue();
Chris Lattner222ef4c2008-12-17 05:28:49 +00001219 Value *NewPtr = GetHeapSROAValue(GEPI->getOperand(0), FieldNo,
Chris Lattner46b5c642009-11-06 04:27:31 +00001220 InsertedScalarizedValues, PHIsToRewrite);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001221
Chris Lattnerba98f892007-09-13 18:00:31 +00001222 // Create the new GEP idx vector.
1223 SmallVector<Value*, 8> GEPIdx;
1224 GEPIdx.push_back(GEPI->getOperand(1));
1225 GEPIdx.append(GEPI->op_begin()+3, GEPI->op_end());
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001226
Jay Foadd1b78492011-07-25 09:48:08 +00001227 Value *NGEPI = GetElementPtrInst::Create(NewPtr, GEPIdx,
Gabor Greife9ecc682008-04-06 20:25:17 +00001228 GEPI->getName(), GEPI);
Chris Lattnerba98f892007-09-13 18:00:31 +00001229 GEPI->replaceAllUsesWith(NGEPI);
1230 GEPI->eraseFromParent();
1231 return;
1232 }
Chris Lattner011f91b2007-09-13 21:31:36 +00001233
Chris Lattner222ef4c2008-12-17 05:28:49 +00001234 // Recursively transform the users of PHI nodes. This will lazily create the
1235 // PHIs that are needed for individual elements. Keep track of what PHIs we
1236 // see in InsertedScalarizedValues so that we don't get infinite loops (very
1237 // antisocial). If the PHI is already in InsertedScalarizedValues, it has
1238 // already been seen first by another load, so its uses have already been
1239 // processed.
1240 PHINode *PN = cast<PHINode>(LoadUser);
Chris Lattner5cf753c2011-07-21 06:21:31 +00001241 if (!InsertedScalarizedValues.insert(std::make_pair(PN,
1242 std::vector<Value*>())).second)
1243 return;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001244
Chris Lattner222ef4c2008-12-17 05:28:49 +00001245 // If this is the first time we've seen this PHI, recursively process all
1246 // users.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001247 for (auto UI = PN->user_begin(), E = PN->user_end(); UI != E;) {
Chris Lattner0cdf5232008-12-17 05:42:08 +00001248 Instruction *User = cast<Instruction>(*UI++);
Chris Lattner46b5c642009-11-06 04:27:31 +00001249 RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite);
Chris Lattner0cdf5232008-12-17 05:42:08 +00001250 }
Chris Lattnerf315d4f2007-09-13 17:29:05 +00001251}
1252
Chris Lattner24d3d422006-09-30 23:32:09 +00001253/// RewriteUsesOfLoadForHeapSRoA - We are performing Heap SRoA on a global. Ptr
1254/// is a value loaded from the global. Eliminate all uses of Ptr, making them
1255/// use FieldGlobals instead. All uses of loaded values satisfy
Chris Lattner56b55382008-12-16 21:24:51 +00001256/// AllGlobalLoadUsesSimpleEnoughForHeapSRA.
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001257static void RewriteUsesOfLoadForHeapSRoA(LoadInst *Load,
Chris Lattner222ef4c2008-12-17 05:28:49 +00001258 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Chris Lattner46b5c642009-11-06 04:27:31 +00001259 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00001260 for (auto UI = Load->user_begin(), E = Load->user_end(); UI != E;) {
Chris Lattner0cdf5232008-12-17 05:42:08 +00001261 Instruction *User = cast<Instruction>(*UI++);
Chris Lattner46b5c642009-11-06 04:27:31 +00001262 RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite);
Chris Lattner0cdf5232008-12-17 05:42:08 +00001263 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001264
Chris Lattner222ef4c2008-12-17 05:28:49 +00001265 if (Load->use_empty()) {
1266 Load->eraseFromParent();
1267 InsertedScalarizedValues.erase(Load);
1268 }
Chris Lattner24d3d422006-09-30 23:32:09 +00001269}
1270
Victor Hernandez5d034492009-09-18 22:35:49 +00001271/// PerformHeapAllocSRoA - CI is an allocation of an array of structures. Break
1272/// it up into multiple allocations of arrays of the fields.
Victor Hernandezf3db9152009-11-07 00:16:28 +00001273static GlobalVariable *PerformHeapAllocSRoA(GlobalVariable *GV, CallInst *CI,
Rafael Espindolaaeff8a92014-02-24 23:12:18 +00001274 Value *NElems, const DataLayout *DL,
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00001275 const TargetLibraryInfo *TLI) {
David Greene44cb8ad2010-01-05 01:28:05 +00001276 DEBUG(dbgs() << "SROA HEAP ALLOC: " << *GV << " MALLOC = " << *CI << '\n');
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00001277 Type *MAT = getMallocAllocatedType(CI, TLI);
Chris Lattner229907c2011-07-18 04:54:35 +00001278 StructType *STy = cast<StructType>(MAT);
Victor Hernandez5d034492009-09-18 22:35:49 +00001279
1280 // There is guaranteed to be at least one use of the malloc (storing
1281 // it into GV). If there are other uses, change them to be uses of
1282 // the global to simplify later code. This also deletes the store
1283 // into GV.
Victor Hernandezf3db9152009-11-07 00:16:28 +00001284 ReplaceUsesOfMallocWithGlobal(CI, GV);
1285
Victor Hernandez5d034492009-09-18 22:35:49 +00001286 // Okay, at this point, there are no users of the malloc. Insert N
1287 // new mallocs at the same place as CI, and N globals.
1288 std::vector<Value*> FieldGlobals;
1289 std::vector<Value*> FieldMallocs;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001290
Matt Arsenaultfcd74012014-04-23 20:36:10 +00001291 unsigned AS = GV->getType()->getPointerAddressSpace();
Victor Hernandez5d034492009-09-18 22:35:49 +00001292 for (unsigned FieldNo = 0, e = STy->getNumElements(); FieldNo != e;++FieldNo){
Chris Lattner229907c2011-07-18 04:54:35 +00001293 Type *FieldTy = STy->getElementType(FieldNo);
Matt Arsenaultfcd74012014-04-23 20:36:10 +00001294 PointerType *PFieldTy = PointerType::get(FieldTy, AS);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001295
Victor Hernandez5d034492009-09-18 22:35:49 +00001296 GlobalVariable *NGV =
1297 new GlobalVariable(*GV->getParent(),
1298 PFieldTy, false, GlobalValue::InternalLinkage,
1299 Constant::getNullValue(PFieldTy),
1300 GV->getName() + ".f" + Twine(FieldNo), GV,
Hans Wennborgcbe34b42012-06-23 11:37:03 +00001301 GV->getThreadLocalMode());
Victor Hernandez5d034492009-09-18 22:35:49 +00001302 FieldGlobals.push_back(NGV);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001303
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001304 unsigned TypeSize = DL->getTypeAllocSize(FieldTy);
Chris Lattner229907c2011-07-18 04:54:35 +00001305 if (StructType *ST = dyn_cast<StructType>(FieldTy))
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001306 TypeSize = DL->getStructLayout(ST)->getSizeInBytes();
1307 Type *IntPtrTy = DL->getIntPtrType(CI->getType());
Victor Hernandezf3db9152009-11-07 00:16:28 +00001308 Value *NMI = CallInst::CreateMalloc(CI, IntPtrTy, FieldTy,
1309 ConstantInt::get(IntPtrTy, TypeSize),
Craig Topperf40110f2014-04-25 05:29:35 +00001310 NElems, nullptr,
Victor Hernandezf3db9152009-11-07 00:16:28 +00001311 CI->getName() + ".f" + Twine(FieldNo));
Chris Lattner0521c092010-02-26 18:23:13 +00001312 FieldMallocs.push_back(NMI);
Victor Hernandezf3db9152009-11-07 00:16:28 +00001313 new StoreInst(NMI, NGV, CI);
Victor Hernandez5d034492009-09-18 22:35:49 +00001314 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001315
Victor Hernandez5d034492009-09-18 22:35:49 +00001316 // The tricky aspect of this transformation is handling the case when malloc
1317 // fails. In the original code, malloc failing would set the result pointer
1318 // of malloc to null. In this case, some mallocs could succeed and others
1319 // could fail. As such, we emit code that looks like this:
1320 // F0 = malloc(field0)
1321 // F1 = malloc(field1)
1322 // F2 = malloc(field2)
1323 // if (F0 == 0 || F1 == 0 || F2 == 0) {
1324 // if (F0) { free(F0); F0 = 0; }
1325 // if (F1) { free(F1); F1 = 0; }
1326 // if (F2) { free(F2); F2 = 0; }
1327 // }
Victor Hernandezfcc77b12009-11-10 08:32:25 +00001328 // The malloc can also fail if its argument is too large.
Gabor Greif218f5542010-06-24 14:42:01 +00001329 Constant *ConstantZero = ConstantInt::get(CI->getArgOperand(0)->getType(), 0);
1330 Value *RunningOr = new ICmpInst(CI, ICmpInst::ICMP_SLT, CI->getArgOperand(0),
Victor Hernandezfcc77b12009-11-10 08:32:25 +00001331 ConstantZero, "isneg");
Victor Hernandez5d034492009-09-18 22:35:49 +00001332 for (unsigned i = 0, e = FieldMallocs.size(); i != e; ++i) {
Victor Hernandezf3db9152009-11-07 00:16:28 +00001333 Value *Cond = new ICmpInst(CI, ICmpInst::ICMP_EQ, FieldMallocs[i],
1334 Constant::getNullValue(FieldMallocs[i]->getType()),
1335 "isnull");
Victor Hernandezfcc77b12009-11-10 08:32:25 +00001336 RunningOr = BinaryOperator::CreateOr(RunningOr, Cond, "tmp", CI);
Victor Hernandez5d034492009-09-18 22:35:49 +00001337 }
1338
1339 // Split the basic block at the old malloc.
Victor Hernandezf3db9152009-11-07 00:16:28 +00001340 BasicBlock *OrigBB = CI->getParent();
1341 BasicBlock *ContBB = OrigBB->splitBasicBlock(CI, "malloc_cont");
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001342
Victor Hernandez5d034492009-09-18 22:35:49 +00001343 // Create the block to check the first condition. Put all these blocks at the
1344 // end of the function as they are unlikely to be executed.
Chris Lattner46b5c642009-11-06 04:27:31 +00001345 BasicBlock *NullPtrBlock = BasicBlock::Create(OrigBB->getContext(),
1346 "malloc_ret_null",
Victor Hernandez5d034492009-09-18 22:35:49 +00001347 OrigBB->getParent());
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001348
Victor Hernandez5d034492009-09-18 22:35:49 +00001349 // Remove the uncond branch from OrigBB to ContBB, turning it into a cond
1350 // branch on RunningOr.
1351 OrigBB->getTerminator()->eraseFromParent();
1352 BranchInst::Create(NullPtrBlock, ContBB, RunningOr, OrigBB);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001353
Victor Hernandez5d034492009-09-18 22:35:49 +00001354 // Within the NullPtrBlock, we need to emit a comparison and branch for each
1355 // pointer, because some may be null while others are not.
1356 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
1357 Value *GVVal = new LoadInst(FieldGlobals[i], "tmp", NullPtrBlock);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001358 Value *Cmp = new ICmpInst(*NullPtrBlock, ICmpInst::ICMP_NE, GVVal,
Benjamin Kramer547b6c52011-09-27 20:39:19 +00001359 Constant::getNullValue(GVVal->getType()));
Chris Lattner46b5c642009-11-06 04:27:31 +00001360 BasicBlock *FreeBlock = BasicBlock::Create(Cmp->getContext(), "free_it",
Victor Hernandez5d034492009-09-18 22:35:49 +00001361 OrigBB->getParent());
Chris Lattner46b5c642009-11-06 04:27:31 +00001362 BasicBlock *NextBlock = BasicBlock::Create(Cmp->getContext(), "next",
Victor Hernandez5d034492009-09-18 22:35:49 +00001363 OrigBB->getParent());
Victor Hernandeze2971492009-10-24 04:23:03 +00001364 Instruction *BI = BranchInst::Create(FreeBlock, NextBlock,
1365 Cmp, NullPtrBlock);
Victor Hernandez5d034492009-09-18 22:35:49 +00001366
1367 // Fill in FreeBlock.
Victor Hernandeze2971492009-10-24 04:23:03 +00001368 CallInst::CreateFree(GVVal, BI);
Victor Hernandez5d034492009-09-18 22:35:49 +00001369 new StoreInst(Constant::getNullValue(GVVal->getType()), FieldGlobals[i],
1370 FreeBlock);
1371 BranchInst::Create(NextBlock, FreeBlock);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001372
Victor Hernandez5d034492009-09-18 22:35:49 +00001373 NullPtrBlock = NextBlock;
1374 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001375
Victor Hernandez5d034492009-09-18 22:35:49 +00001376 BranchInst::Create(ContBB, NullPtrBlock);
Victor Hernandezf3db9152009-11-07 00:16:28 +00001377
1378 // CI is no longer needed, remove it.
Victor Hernandez5d034492009-09-18 22:35:49 +00001379 CI->eraseFromParent();
1380
1381 /// InsertedScalarizedLoads - As we process loads, if we can't immediately
1382 /// update all uses of the load, keep track of what scalarized loads are
1383 /// inserted for a given load.
1384 DenseMap<Value*, std::vector<Value*> > InsertedScalarizedValues;
1385 InsertedScalarizedValues[GV] = FieldGlobals;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001386
Victor Hernandez5d034492009-09-18 22:35:49 +00001387 std::vector<std::pair<PHINode*, unsigned> > PHIsToRewrite;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001388
Victor Hernandez5d034492009-09-18 22:35:49 +00001389 // Okay, the malloc site is completely handled. All of the uses of GV are now
1390 // loads, and all uses of those loads are simple. Rewrite them to use loads
1391 // of the per-field globals instead.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001392 for (auto UI = GV->user_begin(), E = GV->user_end(); UI != E;) {
Victor Hernandez5d034492009-09-18 22:35:49 +00001393 Instruction *User = cast<Instruction>(*UI++);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001394
Victor Hernandez5d034492009-09-18 22:35:49 +00001395 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Chris Lattner46b5c642009-11-06 04:27:31 +00001396 RewriteUsesOfLoadForHeapSRoA(LI, InsertedScalarizedValues, PHIsToRewrite);
Victor Hernandez5d034492009-09-18 22:35:49 +00001397 continue;
1398 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001399
Victor Hernandez5d034492009-09-18 22:35:49 +00001400 // Must be a store of null.
1401 StoreInst *SI = cast<StoreInst>(User);
1402 assert(isa<ConstantPointerNull>(SI->getOperand(0)) &&
1403 "Unexpected heap-sra user!");
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001404
Victor Hernandez5d034492009-09-18 22:35:49 +00001405 // Insert a store of null into each global.
1406 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
Chris Lattner229907c2011-07-18 04:54:35 +00001407 PointerType *PT = cast<PointerType>(FieldGlobals[i]->getType());
Victor Hernandez5d034492009-09-18 22:35:49 +00001408 Constant *Null = Constant::getNullValue(PT->getElementType());
1409 new StoreInst(Null, FieldGlobals[i], SI);
1410 }
1411 // Erase the original store.
1412 SI->eraseFromParent();
1413 }
1414
1415 // While we have PHIs that are interesting to rewrite, do it.
1416 while (!PHIsToRewrite.empty()) {
1417 PHINode *PN = PHIsToRewrite.back().first;
1418 unsigned FieldNo = PHIsToRewrite.back().second;
1419 PHIsToRewrite.pop_back();
1420 PHINode *FieldPN = cast<PHINode>(InsertedScalarizedValues[PN][FieldNo]);
1421 assert(FieldPN->getNumIncomingValues() == 0 &&"Already processed this phi");
1422
1423 // Add all the incoming values. This can materialize more phis.
1424 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1425 Value *InVal = PN->getIncomingValue(i);
1426 InVal = GetHeapSROAValue(InVal, FieldNo, InsertedScalarizedValues,
Chris Lattner46b5c642009-11-06 04:27:31 +00001427 PHIsToRewrite);
Victor Hernandez5d034492009-09-18 22:35:49 +00001428 FieldPN->addIncoming(InVal, PN->getIncomingBlock(i));
1429 }
1430 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001431
Victor Hernandez5d034492009-09-18 22:35:49 +00001432 // Drop all inter-phi links and any loads that made it this far.
1433 for (DenseMap<Value*, std::vector<Value*> >::iterator
1434 I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
1435 I != E; ++I) {
1436 if (PHINode *PN = dyn_cast<PHINode>(I->first))
1437 PN->dropAllReferences();
1438 else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
1439 LI->dropAllReferences();
1440 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001441
Victor Hernandez5d034492009-09-18 22:35:49 +00001442 // Delete all the phis and loads now that inter-references are dead.
1443 for (DenseMap<Value*, std::vector<Value*> >::iterator
1444 I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
1445 I != E; ++I) {
1446 if (PHINode *PN = dyn_cast<PHINode>(I->first))
1447 PN->eraseFromParent();
1448 else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
1449 LI->eraseFromParent();
1450 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001451
Victor Hernandez5d034492009-09-18 22:35:49 +00001452 // The old global is now dead, remove it.
1453 GV->eraseFromParent();
1454
1455 ++NumHeapSRA;
1456 return cast<GlobalVariable>(FieldGlobals[0]);
1457}
1458
Chris Lattnerc4274a72008-12-15 21:02:25 +00001459/// TryToOptimizeStoreOfMallocToGlobal - This function is called when we see a
1460/// pointer global variable with a single value stored it that is a malloc or
1461/// cast of malloc.
1462static bool TryToOptimizeStoreOfMallocToGlobal(GlobalVariable *GV,
Victor Hernandez5d034492009-09-18 22:35:49 +00001463 CallInst *CI,
Chris Lattner229907c2011-07-18 04:54:35 +00001464 Type *AllocTy,
Nick Lewycky52da72b2012-02-05 19:56:38 +00001465 AtomicOrdering Ordering,
Victor Hernandez5d034492009-09-18 22:35:49 +00001466 Module::global_iterator &GVI,
Rafael Espindolaaeff8a92014-02-24 23:12:18 +00001467 const DataLayout *DL,
Nick Lewyckycf6aae62012-02-12 01:13:18 +00001468 TargetLibraryInfo *TLI) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001469 if (!DL)
Evan Cheng21b588b2010-04-14 20:52:55 +00001470 return false;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001471
Victor Hernandez5d034492009-09-18 22:35:49 +00001472 // If this is a malloc of an abstract type, don't touch it.
1473 if (!AllocTy->isSized())
1474 return false;
1475
1476 // We can't optimize this global unless all uses of it are *known* to be
1477 // of the malloc value, not of the null initializer value (consider a use
1478 // that compares the global's value against zero to see if the malloc has
1479 // been reached). To do this, we check to see if all uses of the global
1480 // would trap if the global were null: this proves that they must all
1481 // happen after the malloc.
1482 if (!AllUsesOfLoadedValueWillTrapIfNull(GV))
1483 return false;
1484
1485 // We can't optimize this if the malloc itself is used in a complex way,
1486 // for example, being stored into multiple globals. This allows the
Nick Lewyckybbd11562012-02-05 19:48:37 +00001487 // malloc to be stored into the specified global, loaded icmp'd, and
Victor Hernandez5d034492009-09-18 22:35:49 +00001488 // GEP'd. These are all things we could transform to using the global
1489 // for.
Evan Cheng21b588b2010-04-14 20:52:55 +00001490 SmallPtrSet<const PHINode*, 8> PHIs;
1491 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(CI, GV, PHIs))
1492 return false;
Victor Hernandez5d034492009-09-18 22:35:49 +00001493
1494 // If we have a global that is only initialized with a fixed size malloc,
1495 // transform the program to use global memory instead of malloc'd memory.
1496 // This eliminates dynamic allocation, avoids an indirection accessing the
1497 // data, and exposes the resultant global to further GlobalOpt.
Victor Hernandez264da322009-10-16 23:12:25 +00001498 // We cannot optimize the malloc if we cannot determine malloc array size.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001499 Value *NElems = getMallocArraySize(CI, DL, TLI, true);
Evan Cheng21b588b2010-04-14 20:52:55 +00001500 if (!NElems)
1501 return false;
Victor Hernandez5d034492009-09-18 22:35:49 +00001502
Evan Cheng21b588b2010-04-14 20:52:55 +00001503 if (ConstantInt *NElements = dyn_cast<ConstantInt>(NElems))
1504 // Restrict this transformation to only working on small allocations
1505 // (2048 bytes currently), as we don't want to introduce a 16M global or
1506 // something.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001507 if (NElements->getZExtValue() * DL->getTypeAllocSize(AllocTy) < 2048) {
1508 GVI = OptimizeGlobalAddressOfMalloc(GV, CI, AllocTy, NElements, DL, TLI);
Evan Cheng21b588b2010-04-14 20:52:55 +00001509 return true;
Victor Hernandez5d034492009-09-18 22:35:49 +00001510 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001511
Evan Cheng21b588b2010-04-14 20:52:55 +00001512 // If the allocation is an array of structures, consider transforming this
1513 // into multiple malloc'd arrays, one for each field. This is basically
1514 // SRoA for malloc'd memory.
1515
Nick Lewycky52da72b2012-02-05 19:56:38 +00001516 if (Ordering != NotAtomic)
1517 return false;
1518
Evan Cheng21b588b2010-04-14 20:52:55 +00001519 // If this is an allocation of a fixed size array of structs, analyze as a
1520 // variable size array. malloc [100 x struct],1 -> malloc struct, 100
Gabor Greif218f5542010-06-24 14:42:01 +00001521 if (NElems == ConstantInt::get(CI->getArgOperand(0)->getType(), 1))
Chris Lattner229907c2011-07-18 04:54:35 +00001522 if (ArrayType *AT = dyn_cast<ArrayType>(AllocTy))
Evan Cheng21b588b2010-04-14 20:52:55 +00001523 AllocTy = AT->getElementType();
Gabor Greif218f5542010-06-24 14:42:01 +00001524
Chris Lattner229907c2011-07-18 04:54:35 +00001525 StructType *AllocSTy = dyn_cast<StructType>(AllocTy);
Evan Cheng21b588b2010-04-14 20:52:55 +00001526 if (!AllocSTy)
1527 return false;
1528
1529 // This the structure has an unreasonable number of fields, leave it
1530 // alone.
1531 if (AllocSTy->getNumElements() <= 16 && AllocSTy->getNumElements() != 0 &&
1532 AllGlobalLoadUsesSimpleEnoughForHeapSRA(GV, CI)) {
1533
1534 // If this is a fixed size array, transform the Malloc to be an alloc of
1535 // structs. malloc [100 x struct],1 -> malloc struct, 100
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00001536 if (ArrayType *AT = dyn_cast<ArrayType>(getMallocAllocatedType(CI, TLI))) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001537 Type *IntPtrTy = DL->getIntPtrType(CI->getType());
1538 unsigned TypeSize = DL->getStructLayout(AllocSTy)->getSizeInBytes();
Evan Cheng21b588b2010-04-14 20:52:55 +00001539 Value *AllocSize = ConstantInt::get(IntPtrTy, TypeSize);
1540 Value *NumElements = ConstantInt::get(IntPtrTy, AT->getNumElements());
1541 Instruction *Malloc = CallInst::CreateMalloc(CI, IntPtrTy, AllocSTy,
1542 AllocSize, NumElements,
Craig Topperf40110f2014-04-25 05:29:35 +00001543 nullptr, CI->getName());
Evan Cheng21b588b2010-04-14 20:52:55 +00001544 Instruction *Cast = new BitCastInst(Malloc, CI->getType(), "tmp", CI);
1545 CI->replaceAllUsesWith(Cast);
1546 CI->eraseFromParent();
Nuno Lopes9792d682012-06-22 00:25:01 +00001547 if (BitCastInst *BCI = dyn_cast<BitCastInst>(Malloc))
1548 CI = cast<CallInst>(BCI->getOperand(0));
1549 else
Nuno Lopes0b60ebb2012-06-22 00:29:58 +00001550 CI = cast<CallInst>(Malloc);
Evan Cheng21b588b2010-04-14 20:52:55 +00001551 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001552
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001553 GVI = PerformHeapAllocSRoA(GV, CI, getMallocArraySize(CI, DL, TLI, true),
1554 DL, TLI);
Evan Cheng21b588b2010-04-14 20:52:55 +00001555 return true;
Victor Hernandez5d034492009-09-18 22:35:49 +00001556 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001557
Victor Hernandez5d034492009-09-18 22:35:49 +00001558 return false;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001559}
Victor Hernandez5d034492009-09-18 22:35:49 +00001560
Chris Lattner09a52722004-10-09 21:48:45 +00001561// OptimizeOnceStoredGlobal - Try to optimize globals based on the knowledge
1562// that only one value (besides its initializer) is ever stored to the global.
Chris Lattner004e2502004-10-11 05:54:41 +00001563static bool OptimizeOnceStoredGlobal(GlobalVariable *GV, Value *StoredOnceVal,
Nick Lewycky52da72b2012-02-05 19:56:38 +00001564 AtomicOrdering Ordering,
Chris Lattnerc2d3d312006-08-27 22:42:52 +00001565 Module::global_iterator &GVI,
Rafael Espindolaaeff8a92014-02-24 23:12:18 +00001566 const DataLayout *DL,
1567 TargetLibraryInfo *TLI) {
Chris Lattner1c731fa2008-12-15 21:20:32 +00001568 // Ignore no-op GEPs and bitcasts.
1569 StoredOnceVal = StoredOnceVal->stripPointerCasts();
Chris Lattner09a52722004-10-09 21:48:45 +00001570
Chris Lattnere42eb312004-10-10 23:14:11 +00001571 // If we are dealing with a pointer global that is initialized to null and
1572 // only has one (non-null) value stored into it, then we can optimize any
1573 // users of the loaded value (often calls and loads) that would trap if the
1574 // value was null.
Duncan Sands19d0b472010-02-16 11:11:14 +00001575 if (GV->getInitializer()->getType()->isPointerTy() &&
Chris Lattner09a52722004-10-09 21:48:45 +00001576 GV->getInitializer()->isNullValue()) {
Chris Lattnere42eb312004-10-10 23:14:11 +00001577 if (Constant *SOVC = dyn_cast<Constant>(StoredOnceVal)) {
1578 if (GV->getInitializer()->getType() != SOVC->getType())
Chris Lattner1a1acc22011-05-22 07:15:13 +00001579 SOVC = ConstantExpr::getBitCast(SOVC, GV->getInitializer()->getType());
Misha Brukmanb1c93172005-04-21 23:48:37 +00001580
Chris Lattnere42eb312004-10-10 23:14:11 +00001581 // Optimize away any trapping uses of the loaded value.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001582 if (OptimizeAwayTrappingUsesOfLoads(GV, SOVC, DL, TLI))
Chris Lattner604ed7a2004-10-10 17:07:12 +00001583 return true;
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00001584 } else if (CallInst *CI = extractMallocCall(StoredOnceVal, TLI)) {
1585 Type *MallocType = getMallocAllocatedType(CI, TLI);
Nick Lewyckycf6aae62012-02-12 01:13:18 +00001586 if (MallocType &&
1587 TryToOptimizeStoreOfMallocToGlobal(GV, CI, MallocType, Ordering, GVI,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001588 DL, TLI))
Victor Hernandezf3db9152009-11-07 00:16:28 +00001589 return true;
Chris Lattnere42eb312004-10-10 23:14:11 +00001590 }
Chris Lattner09a52722004-10-09 21:48:45 +00001591 }
Chris Lattner004e2502004-10-11 05:54:41 +00001592
Chris Lattner09a52722004-10-09 21:48:45 +00001593 return false;
1594}
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001595
Lang Hames459b5dc2014-03-23 04:22:31 +00001596/// TryToShrinkGlobalToBoolean - At this point, we have learned that the only
Chris Lattner20bbac32008-01-14 01:17:44 +00001597/// two values ever stored into GV are its initializer and OtherVal. See if we
Lang Hames459b5dc2014-03-23 04:22:31 +00001598/// can shrink the global into a boolean and select between the two values
1599/// whenever it is used. This exposes the values to other scalar optimizations.
1600static bool TryToShrinkGlobalToBoolean(GlobalVariable *GV, Constant *OtherVal) {
Chris Lattner229907c2011-07-18 04:54:35 +00001601 Type *GVElType = GV->getType()->getElementType();
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001602
Lang Hames459b5dc2014-03-23 04:22:31 +00001603 // If GVElType is already i1, it is already shrunk. If the type of the GV is
1604 // an FP value, pointer or vector, don't do this optimization because a select
1605 // between them is very expensive and unlikely to lead to later
1606 // simplification. In these cases, we typically end up with "cond ? v1 : v2"
1607 // where v1 and v2 both require constant pool loads, a big loss.
Chris Lattner46b5c642009-11-06 04:27:31 +00001608 if (GVElType == Type::getInt1Ty(GV->getContext()) ||
Duncan Sands9dff9be2010-02-15 16:12:20 +00001609 GVElType->isFloatingPointTy() ||
Duncan Sands19d0b472010-02-16 11:11:14 +00001610 GVElType->isPointerTy() || GVElType->isVectorTy())
Chris Lattner20bbac32008-01-14 01:17:44 +00001611 return false;
Gabor Greifa75ed762010-07-12 14:13:15 +00001612
Chris Lattner20bbac32008-01-14 01:17:44 +00001613 // Walk the use list of the global seeing if all the uses are load or store.
1614 // If there is anything else, bail out.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001615 for (User *U : GV->users())
Gabor Greifa75ed762010-07-12 14:13:15 +00001616 if (!isa<LoadInst>(U) && !isa<StoreInst>(U))
Chris Lattner20bbac32008-01-14 01:17:44 +00001617 return false;
Gabor Greifa75ed762010-07-12 14:13:15 +00001618
Lang Hames459b5dc2014-03-23 04:22:31 +00001619 DEBUG(dbgs() << " *** SHRINKING TO BOOL: " << *GV);
1620
1621 // Create the new global, initializing it to false.
1622 GlobalVariable *NewGV = new GlobalVariable(Type::getInt1Ty(GV->getContext()),
1623 false,
1624 GlobalValue::InternalLinkage,
1625 ConstantInt::getFalse(GV->getContext()),
1626 GV->getName()+".b",
1627 GV->getThreadLocalMode(),
1628 GV->getType()->getAddressSpace());
1629 GV->getParent()->getGlobalList().insert(GV, NewGV);
1630
Chris Lattner40e4cec2004-12-12 05:53:50 +00001631 Constant *InitVal = GV->getInitializer();
Chris Lattner46b5c642009-11-06 04:27:31 +00001632 assert(InitVal->getType() != Type::getInt1Ty(GV->getContext()) &&
Lang Hames459b5dc2014-03-23 04:22:31 +00001633 "No reason to shrink to bool!");
Chris Lattner40e4cec2004-12-12 05:53:50 +00001634
Lang Hames459b5dc2014-03-23 04:22:31 +00001635 // If initialized to zero and storing one into the global, we can use a cast
1636 // instead of a select to synthesize the desired value.
1637 bool IsOneZero = false;
1638 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal))
1639 IsOneZero = InitVal->isNullValue() && CI->isOne();
Chris Lattner40e4cec2004-12-12 05:53:50 +00001640
Lang Hames459b5dc2014-03-23 04:22:31 +00001641 while (!GV->use_empty()) {
1642 Instruction *UI = cast<Instruction>(GV->user_back());
1643 if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
1644 // Change the store into a boolean store.
1645 bool StoringOther = SI->getOperand(0) == OtherVal;
1646 // Only do this if we weren't storing a loaded value.
1647 Value *StoreVal;
1648 if (StoringOther || SI->getOperand(0) == InitVal) {
1649 StoreVal = ConstantInt::get(Type::getInt1Ty(GV->getContext()),
1650 StoringOther);
Bill Wendling7297b862013-02-13 23:00:51 +00001651 } else {
Lang Hames459b5dc2014-03-23 04:22:31 +00001652 // Otherwise, we are storing a previously loaded copy. To do this,
1653 // change the copy from copying the original value to just copying the
1654 // bool.
1655 Instruction *StoredVal = cast<Instruction>(SI->getOperand(0));
1656
1657 // If we've already replaced the input, StoredVal will be a cast or
1658 // select instruction. If not, it will be a load of the original
1659 // global.
1660 if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
1661 assert(LI->getOperand(0) == GV && "Not a copy!");
1662 // Insert a new load, to preserve the saved value.
1663 StoreVal = new LoadInst(NewGV, LI->getName()+".b", false, 0,
1664 LI->getOrdering(), LI->getSynchScope(), LI);
1665 } else {
1666 assert((isa<CastInst>(StoredVal) || isa<SelectInst>(StoredVal)) &&
1667 "This is not a form that we understand!");
1668 StoreVal = StoredVal->getOperand(0);
1669 assert(isa<LoadInst>(StoreVal) && "Not a load of NewGV!");
1670 }
Chris Lattner745196a2004-12-12 19:34:41 +00001671 }
Lang Hames459b5dc2014-03-23 04:22:31 +00001672 new StoreInst(StoreVal, NewGV, false, 0,
1673 SI->getOrdering(), SI->getSynchScope(), SI);
1674 } else {
1675 // Change the load into a load of bool then a select.
1676 LoadInst *LI = cast<LoadInst>(UI);
1677 LoadInst *NLI = new LoadInst(NewGV, LI->getName()+".b", false, 0,
1678 LI->getOrdering(), LI->getSynchScope(), LI);
1679 Value *NSI;
1680 if (IsOneZero)
1681 NSI = new ZExtInst(NLI, LI->getType(), "", LI);
1682 else
1683 NSI = SelectInst::Create(NLI, OtherVal, InitVal, "", LI);
1684 NSI->takeName(LI);
1685 LI->replaceAllUsesWith(NSI);
Devang Patelfc507a12009-03-06 01:39:36 +00001686 }
Lang Hames459b5dc2014-03-23 04:22:31 +00001687 UI->eraseFromParent();
Chris Lattner40e4cec2004-12-12 05:53:50 +00001688 }
1689
Lang Hames459b5dc2014-03-23 04:22:31 +00001690 // Retain the name of the old global variable. People who are debugging their
1691 // programs may expect these variables to be named the same.
1692 NewGV->takeName(GV);
1693 GV->eraseFromParent();
Chris Lattner20bbac32008-01-14 01:17:44 +00001694 return true;
Chris Lattner40e4cec2004-12-12 05:53:50 +00001695}
1696
1697
Nick Lewycky1480f1d2012-02-12 00:52:26 +00001698/// ProcessGlobal - Analyze the specified global variable and optimize it if
1699/// possible. If we make a change, return true.
Rafael Espindolafc355bc2011-01-19 16:32:21 +00001700bool GlobalOpt::ProcessGlobal(GlobalVariable *GV,
1701 Module::global_iterator &GVI) {
Rafael Espindoladef1b092012-06-14 22:48:13 +00001702 if (!GV->isDiscardableIfUnused())
Rafael Espindolafc355bc2011-01-19 16:32:21 +00001703 return false;
1704
1705 // Do more involved optimizations if the global is internal.
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001706 GV->removeDeadConstantUsers();
1707
1708 if (GV->use_empty()) {
David Greene44cb8ad2010-01-05 01:28:05 +00001709 DEBUG(dbgs() << "GLOBAL DEAD: " << *GV);
Chris Lattner8e71c6a2004-10-16 18:09:00 +00001710 GV->eraseFromParent();
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001711 ++NumDeleted;
1712 return true;
1713 }
1714
Rafael Espindola1821c6c2012-06-15 18:00:24 +00001715 if (!GV->hasLocalLinkage())
1716 return false;
1717
Rafael Espindolafc355bc2011-01-19 16:32:21 +00001718 GlobalStatus GS;
1719
Rafael Espindola3d7fc252013-10-21 17:14:55 +00001720 if (GlobalStatus::analyzeGlobal(GV, GS))
Rafael Espindolaecd5b9a2011-01-18 04:36:06 +00001721 return false;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001722
Rafael Espindola045a78f2013-10-17 18:18:52 +00001723 if (!GS.IsCompared && !GV->hasUnnamedAddr()) {
Rafael Espindolafc355bc2011-01-19 16:32:21 +00001724 GV->setUnnamedAddr(true);
1725 NumUnnamed++;
1726 }
1727
1728 if (GV->isConstant() || !GV->hasInitializer())
1729 return false;
1730
Rafael Espindolad21ac192013-09-05 19:15:21 +00001731 return ProcessInternalGlobal(GV, GVI, GS);
Rafael Espindolafc355bc2011-01-19 16:32:21 +00001732}
1733
1734/// ProcessInternalGlobal - Analyze the specified global variable and optimize
1735/// it if possible. If we make a change, return true.
1736bool GlobalOpt::ProcessInternalGlobal(GlobalVariable *GV,
1737 Module::global_iterator &GVI,
Rafael Espindolafc355bc2011-01-19 16:32:21 +00001738 const GlobalStatus &GS) {
Alexey Samsonova1944e62013-10-07 19:03:24 +00001739 // If this is a first class global and has only one accessing function
1740 // and this function is main (which we know is not recursive), we replace
1741 // the global with a local alloca in this function.
1742 //
Alp Tokerf907b892013-12-05 05:44:44 +00001743 // NOTE: It doesn't make sense to promote non-single-value types since we
Alexey Samsonova1944e62013-10-07 19:03:24 +00001744 // are just replacing static memory to stack memory.
1745 //
1746 // If the global is in different address space, don't bring it to stack.
1747 if (!GS.HasMultipleAccessingFunctions &&
1748 GS.AccessingFunction && !GS.HasNonInstructionUser &&
1749 GV->getType()->getElementType()->isSingleValueType() &&
1750 GS.AccessingFunction->getName() == "main" &&
1751 GS.AccessingFunction->hasExternalLinkage() &&
1752 GV->getType()->getAddressSpace() == 0) {
1753 DEBUG(dbgs() << "LOCALIZING GLOBAL: " << *GV);
1754 Instruction &FirstI = const_cast<Instruction&>(*GS.AccessingFunction
1755 ->getEntryBlock().begin());
1756 Type *ElemTy = GV->getType()->getElementType();
1757 // FIXME: Pass Global's alignment when globals have alignment
Craig Topperf40110f2014-04-25 05:29:35 +00001758 AllocaInst *Alloca = new AllocaInst(ElemTy, nullptr,
1759 GV->getName(), &FirstI);
Alexey Samsonova1944e62013-10-07 19:03:24 +00001760 if (!isa<UndefValue>(GV->getInitializer()))
1761 new StoreInst(GV->getInitializer(), Alloca, &FirstI);
1762
1763 GV->replaceAllUsesWith(Alloca);
1764 GV->eraseFromParent();
1765 ++NumLocalized;
1766 return true;
1767 }
1768
Rafael Espindolaecd5b9a2011-01-18 04:36:06 +00001769 // If the global is never loaded (but may be stored to), it is dead.
1770 // Delete it now.
Rafael Espindola045a78f2013-10-17 18:18:52 +00001771 if (!GS.IsLoaded) {
Rafael Espindolaecd5b9a2011-01-18 04:36:06 +00001772 DEBUG(dbgs() << "GLOBAL NEVER LOADED: " << *GV);
1773
Nick Lewyckyfaa9c3b02012-07-24 07:21:08 +00001774 bool Changed;
1775 if (isLeakCheckerRoot(GV)) {
1776 // Delete any constant stores to the global.
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00001777 Changed = CleanupPointerRootUsers(GV, TLI);
Nick Lewyckyfaa9c3b02012-07-24 07:21:08 +00001778 } else {
1779 // Delete any stores we can find to the global. We may not be able to
1780 // make it completely dead though.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001781 Changed = CleanupConstantGlobalUsers(GV, GV->getInitializer(), DL, TLI);
Nick Lewyckyfaa9c3b02012-07-24 07:21:08 +00001782 }
Rafael Espindolaecd5b9a2011-01-18 04:36:06 +00001783
1784 // If the global is dead now, delete it.
1785 if (GV->use_empty()) {
1786 GV->eraseFromParent();
1787 ++NumDeleted;
1788 Changed = true;
1789 }
1790 return Changed;
1791
Rafael Espindola045a78f2013-10-17 18:18:52 +00001792 } else if (GS.StoredType <= GlobalStatus::InitializerStored) {
Michael Gottesmand1a46f22013-01-11 20:07:53 +00001793 DEBUG(dbgs() << "MARKING CONSTANT: " << *GV << "\n");
Rafael Espindolaecd5b9a2011-01-18 04:36:06 +00001794 GV->setConstant(true);
1795
1796 // Clean up any obviously simplifiable users now.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001797 CleanupConstantGlobalUsers(GV, GV->getInitializer(), DL, TLI);
Rafael Espindolaecd5b9a2011-01-18 04:36:06 +00001798
1799 // If the global is dead now, just nuke it.
1800 if (GV->use_empty()) {
1801 DEBUG(dbgs() << " *** Marking constant allowed us to simplify "
1802 << "all users and delete global!\n");
1803 GV->eraseFromParent();
1804 ++NumDeleted;
1805 }
1806
1807 ++NumMarked;
1808 return true;
1809 } else if (!GV->getInitializer()->getType()->isSingleValueType()) {
Rafael Espindola93512512014-02-25 17:30:31 +00001810 if (DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>()) {
1811 const DataLayout &DL = DLP->getDataLayout();
1812 if (GlobalVariable *FirstNewGV = SRAGlobal(GV, DL)) {
Rafael Espindolaecd5b9a2011-01-18 04:36:06 +00001813 GVI = FirstNewGV; // Don't skip the newly produced globals!
1814 return true;
1815 }
Rafael Espindola93512512014-02-25 17:30:31 +00001816 }
Rafael Espindola045a78f2013-10-17 18:18:52 +00001817 } else if (GS.StoredType == GlobalStatus::StoredOnce) {
Rafael Espindolaecd5b9a2011-01-18 04:36:06 +00001818 // If the initial value for the global was an undef value, and if only
1819 // one other value was stored into it, we can just change the
1820 // initializer to be the stored value, then delete all stores to the
1821 // global. This allows us to mark it constant.
1822 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
1823 if (isa<UndefValue>(GV->getInitializer())) {
1824 // Change the initial value here.
1825 GV->setInitializer(SOVConstant);
1826
1827 // Clean up any obviously simplifiable users now.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001828 CleanupConstantGlobalUsers(GV, GV->getInitializer(), DL, TLI);
Rafael Espindolaecd5b9a2011-01-18 04:36:06 +00001829
1830 if (GV->use_empty()) {
1831 DEBUG(dbgs() << " *** Substituting initializer allowed us to "
Nick Lewyckyfaa9c3b02012-07-24 07:21:08 +00001832 << "simplify all users and delete global!\n");
Rafael Espindolaecd5b9a2011-01-18 04:36:06 +00001833 GV->eraseFromParent();
1834 ++NumDeleted;
1835 } else {
1836 GVI = GV;
1837 }
1838 ++NumSubstitute;
1839 return true;
1840 }
1841
1842 // Try to optimize globals based on the knowledge that only one value
1843 // (besides its initializer) is ever stored to the global.
Nick Lewycky52da72b2012-02-05 19:56:38 +00001844 if (OptimizeOnceStoredGlobal(GV, GS.StoredOnceValue, GS.Ordering, GVI,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001845 DL, TLI))
Rafael Espindolaecd5b9a2011-01-18 04:36:06 +00001846 return true;
1847
Lang Hames459b5dc2014-03-23 04:22:31 +00001848 // Otherwise, if the global was not a boolean, we can shrink it to be a
1849 // boolean.
Eli Friedman33d37002013-09-09 22:00:13 +00001850 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue)) {
1851 if (GS.Ordering == NotAtomic) {
Lang Hames459b5dc2014-03-23 04:22:31 +00001852 if (TryToShrinkGlobalToBoolean(GV, SOVConstant)) {
Eli Friedman33d37002013-09-09 22:00:13 +00001853 ++NumShrunkToBool;
1854 return true;
1855 }
Rafael Espindolaecd5b9a2011-01-18 04:36:06 +00001856 }
Eli Friedman33d37002013-09-09 22:00:13 +00001857 }
Rafael Espindolaecd5b9a2011-01-18 04:36:06 +00001858 }
1859
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001860 return false;
1861}
1862
Chris Lattnera4c80222005-05-08 22:18:06 +00001863/// ChangeCalleesToFastCall - Walk all of the direct calls of the specified
1864/// function, changing them to FastCC.
1865static void ChangeCalleesToFastCall(Function *F) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00001866 for (User *U : F->users()) {
1867 if (isa<BlockAddress>(U))
Jay Foadca0c4992012-05-12 08:30:16 +00001868 continue;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001869 CallSite CS(cast<Instruction>(U));
1870 CS.setCallingConv(CallingConv::Fast);
Chris Lattnera4c80222005-05-08 22:18:06 +00001871 }
1872}
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001873
Bill Wendlinge94d8432012-12-07 23:16:57 +00001874static AttributeSet StripNest(LLVMContext &C, const AttributeSet &Attrs) {
Chris Lattner8a923e72008-03-12 17:45:29 +00001875 for (unsigned i = 0, e = Attrs.getNumSlots(); i != e; ++i) {
Bill Wendling57625a42013-01-25 23:09:36 +00001876 unsigned Index = Attrs.getSlotIndex(i);
1877 if (!Attrs.getSlotAttributes(i).hasAttribute(Index, Attribute::Nest))
Duncan Sands85fab3a2008-02-18 17:32:13 +00001878 continue;
1879
Duncan Sands85fab3a2008-02-18 17:32:13 +00001880 // There can be only one.
Bill Wendling57625a42013-01-25 23:09:36 +00001881 return Attrs.removeAttribute(C, Index, Attribute::Nest);
Duncan Sands573b3f82008-02-16 20:56:04 +00001882 }
1883
1884 return Attrs;
1885}
1886
1887static void RemoveNestAttribute(Function *F) {
Bill Wendling85a64c22012-10-14 06:39:53 +00001888 F->setAttributes(StripNest(F->getContext(), F->getAttributes()));
Chandler Carruthcdf47882014-03-09 03:16:01 +00001889 for (User *U : F->users()) {
1890 if (isa<BlockAddress>(U))
Jay Foadca0c4992012-05-12 08:30:16 +00001891 continue;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001892 CallSite CS(cast<Instruction>(U));
1893 CS.setAttributes(StripNest(F->getContext(), CS.getAttributes()));
Duncan Sands573b3f82008-02-16 20:56:04 +00001894 }
1895}
1896
Reid Kleckner22869372014-02-26 19:57:30 +00001897/// Return true if this is a calling convention that we'd like to change. The
1898/// idea here is that we don't want to mess with the convention if the user
1899/// explicitly requested something with performance implications like coldcc,
1900/// GHC, or anyregcc.
1901static bool isProfitableToMakeFastCC(Function *F) {
1902 CallingConv::ID CC = F->getCallingConv();
1903 // FIXME: Is it worth transforming x86_stdcallcc and x86_fastcallcc?
1904 return CC == CallingConv::C || CC == CallingConv::X86_ThisCall;
1905}
1906
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001907bool GlobalOpt::OptimizeFunctions(Module &M) {
1908 bool Changed = false;
1909 // Optimize functions.
1910 for (Module::iterator FI = M.begin(), E = M.end(); FI != E; ) {
1911 Function *F = FI++;
Duncan Sandsed722832009-03-06 10:21:56 +00001912 // Functions without names cannot be referenced outside this module.
1913 if (!F->hasName() && !F->isDeclaration())
1914 F->setLinkage(GlobalValue::InternalLinkage);
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001915 F->removeDeadConstantUsers();
Eli Friedman1923a332011-10-20 05:23:42 +00001916 if (F->isDefTriviallyDead()) {
Chris Lattnerb5d9c8c2009-11-01 19:03:42 +00001917 F->eraseFromParent();
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001918 Changed = true;
1919 ++NumFnDeleted;
Rafael Espindola6de96a12009-01-15 20:18:42 +00001920 } else if (F->hasLocalLinkage()) {
Reid Klecknere6ff5c52014-02-28 22:50:08 +00001921 if (isProfitableToMakeFastCC(F) && !F->isVarArg() &&
1922 !F->hasAddressTaken()) {
Reid Kleckner22869372014-02-26 19:57:30 +00001923 // If this function has a calling convention worth changing, is not a
1924 // varargs function, and is only called directly, promote it to use the
1925 // Fast calling convention.
Duncan Sands573b3f82008-02-16 20:56:04 +00001926 F->setCallingConv(CallingConv::Fast);
1927 ChangeCalleesToFastCall(F);
1928 ++NumFastCallFns;
1929 Changed = true;
1930 }
1931
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001932 if (F->getAttributes().hasAttrSomewhere(Attribute::Nest) &&
Jay Foad557169d2009-06-10 08:41:11 +00001933 !F->hasAddressTaken()) {
Duncan Sands573b3f82008-02-16 20:56:04 +00001934 // The function is not used by a trampoline intrinsic, so it is safe
1935 // to remove the 'nest' attribute.
1936 RemoveNestAttribute(F);
1937 ++NumNestRemoved;
1938 Changed = true;
1939 }
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001940 }
1941 }
1942 return Changed;
1943}
1944
1945bool GlobalOpt::OptimizeGlobalVars(Module &M) {
1946 bool Changed = false;
1947 for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
1948 GVI != E; ) {
1949 GlobalVariable *GV = GVI++;
Duncan Sandsed722832009-03-06 10:21:56 +00001950 // Global variables without names cannot be referenced outside this module.
1951 if (!GV->hasName() && !GV->isDeclaration())
1952 GV->setLinkage(GlobalValue::InternalLinkage);
Dan Gohman580b80d2009-11-23 16:22:21 +00001953 // Simplify the initializer.
1954 if (GV->hasInitializer())
1955 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GV->getInitializer())) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001956 Constant *New = ConstantFoldConstantExpression(CE, DL, TLI);
Dan Gohman580b80d2009-11-23 16:22:21 +00001957 if (New && New != CE)
1958 GV->setInitializer(New);
1959 }
Rafael Espindolafc355bc2011-01-19 16:32:21 +00001960
1961 Changed |= ProcessGlobal(GV, GVI);
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001962 }
1963 return Changed;
1964}
1965
Nick Lewycky466d0c12011-04-08 07:30:21 +00001966/// FindGlobalCtors - Find the llvm.global_ctors list, verifying that all
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001967/// initializers have an init priority of 65535.
1968GlobalVariable *GlobalOpt::FindGlobalCtors(Module &M) {
Chris Lattner7ff0ba42010-12-06 21:53:07 +00001969 GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
Craig Topperf40110f2014-04-25 05:29:35 +00001970 if (!GV) return nullptr;
Jakub Staszak9525a772012-12-06 21:57:16 +00001971
Chris Lattner7ff0ba42010-12-06 21:53:07 +00001972 // Verify that the initializer is simple enough for us to handle. We are
1973 // only allowed to optimize the initializer if it is unique.
Craig Topperf40110f2014-04-25 05:29:35 +00001974 if (!GV->hasUniqueInitializer()) return nullptr;
Nick Lewycky0f857892011-04-11 22:11:20 +00001975
1976 if (isa<ConstantAggregateZero>(GV->getInitializer()))
1977 return GV;
1978 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
Eli Friedman9cca0712011-04-09 09:11:09 +00001979
Chris Lattner7ff0ba42010-12-06 21:53:07 +00001980 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i) {
Nick Lewycky0f857892011-04-11 22:11:20 +00001981 if (isa<ConstantAggregateZero>(*i))
1982 continue;
1983 ConstantStruct *CS = cast<ConstantStruct>(*i);
Chris Lattner7ff0ba42010-12-06 21:53:07 +00001984 if (isa<ConstantPointerNull>(CS->getOperand(1)))
1985 continue;
Chris Lattner838bdc12005-09-26 02:19:27 +00001986
Chris Lattner7ff0ba42010-12-06 21:53:07 +00001987 // Must have a function or null ptr.
1988 if (!isa<Function>(CS->getOperand(1)))
Craig Topperf40110f2014-04-25 05:29:35 +00001989 return nullptr;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001990
Chris Lattner7ff0ba42010-12-06 21:53:07 +00001991 // Init priority must be standard.
Nick Lewycky466d0c12011-04-08 07:30:21 +00001992 ConstantInt *CI = cast<ConstantInt>(CS->getOperand(0));
1993 if (CI->getZExtValue() != 65535)
Craig Topperf40110f2014-04-25 05:29:35 +00001994 return nullptr;
Chris Lattner7ff0ba42010-12-06 21:53:07 +00001995 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001996
Chris Lattner7ff0ba42010-12-06 21:53:07 +00001997 return GV;
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001998}
1999
Chris Lattner696beef2005-09-26 02:31:18 +00002000/// ParseGlobalCtors - Given a llvm.global_ctors list that we can understand,
2001/// return a list of the functions and null terminator as a vector.
Chris Lattner41b6a5a2005-09-26 01:43:45 +00002002static std::vector<Function*> ParseGlobalCtors(GlobalVariable *GV) {
Nick Lewycky0f857892011-04-11 22:11:20 +00002003 if (GV->getInitializer()->isNullValue())
2004 return std::vector<Function*>();
Chris Lattner41b6a5a2005-09-26 01:43:45 +00002005 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
2006 std::vector<Function*> Result;
2007 Result.reserve(CA->getNumOperands());
Gabor Greif3a9fba52008-05-29 01:59:18 +00002008 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i) {
2009 ConstantStruct *CS = cast<ConstantStruct>(*i);
Chris Lattner41b6a5a2005-09-26 01:43:45 +00002010 Result.push_back(dyn_cast<Function>(CS->getOperand(1)));
2011 }
2012 return Result;
2013}
2014
Chris Lattner696beef2005-09-26 02:31:18 +00002015/// InstallGlobalCtors - Given a specified llvm.global_ctors list, install the
2016/// specified array, returning the new global to use.
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002017static GlobalVariable *InstallGlobalCtors(GlobalVariable *GCL,
Chris Lattner46b5c642009-11-06 04:27:31 +00002018 const std::vector<Function*> &Ctors) {
Chris Lattner696beef2005-09-26 02:31:18 +00002019 // If we made a change, reassemble the initializer list.
Chris Lattnercc19efa2011-06-20 04:01:31 +00002020 Constant *CSVals[2];
2021 CSVals[0] = ConstantInt::get(Type::getInt32Ty(GCL->getContext()), 65535);
Craig Topperf40110f2014-04-25 05:29:35 +00002022 CSVals[1] = nullptr;
Chris Lattnercc19efa2011-06-20 04:01:31 +00002023
Chris Lattner229907c2011-07-18 04:54:35 +00002024 StructType *StructTy =
Matt Arsenault404c60a2013-10-21 19:43:56 +00002025 cast<StructType>(GCL->getType()->getElementType()->getArrayElementType());
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002026
Chris Lattner696beef2005-09-26 02:31:18 +00002027 // Create the new init list.
2028 std::vector<Constant*> CAList;
2029 for (unsigned i = 0, e = Ctors.size(); i != e; ++i) {
Chris Lattner99e23fa2005-09-26 04:44:35 +00002030 if (Ctors[i]) {
Chris Lattner696beef2005-09-26 02:31:18 +00002031 CSVals[1] = Ctors[i];
Chris Lattner99e23fa2005-09-26 04:44:35 +00002032 } else {
Chris Lattner229907c2011-07-18 04:54:35 +00002033 Type *FTy = FunctionType::get(Type::getVoidTy(GCL->getContext()),
Chris Lattner46b5c642009-11-06 04:27:31 +00002034 false);
Chris Lattner229907c2011-07-18 04:54:35 +00002035 PointerType *PFTy = PointerType::getUnqual(FTy);
Owen Anderson5a1acd92009-07-31 20:28:14 +00002036 CSVals[1] = Constant::getNullValue(PFTy);
Chris Lattner46b5c642009-11-06 04:27:31 +00002037 CSVals[0] = ConstantInt::get(Type::getInt32Ty(GCL->getContext()),
Nick Lewycky0f857892011-04-11 22:11:20 +00002038 0x7fffffff);
Chris Lattner696beef2005-09-26 02:31:18 +00002039 }
Chris Lattnercc19efa2011-06-20 04:01:31 +00002040 CAList.push_back(ConstantStruct::get(StructTy, CSVals));
Chris Lattner696beef2005-09-26 02:31:18 +00002041 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002042
Chris Lattner696beef2005-09-26 02:31:18 +00002043 // Create the array initializer.
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002044 Constant *CA = ConstantArray::get(ArrayType::get(StructTy,
Nick Lewycky1303c0a2009-09-19 20:30:26 +00002045 CAList.size()), CAList);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002046
Chris Lattner696beef2005-09-26 02:31:18 +00002047 // If we didn't change the number of elements, don't create a new GV.
2048 if (CA->getType() == GCL->getInitializer()->getType()) {
2049 GCL->setInitializer(CA);
2050 return GCL;
2051 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002052
Chris Lattner696beef2005-09-26 02:31:18 +00002053 // Create the new global and insert it next to the existing list.
Chris Lattner46b5c642009-11-06 04:27:31 +00002054 GlobalVariable *NGV = new GlobalVariable(CA->getType(), GCL->isConstant(),
Lauro Ramos Venancio749e4662007-04-12 18:32:50 +00002055 GCL->getLinkage(), CA, "",
Hans Wennborgcbe34b42012-06-23 11:37:03 +00002056 GCL->getThreadLocalMode());
Chris Lattner696beef2005-09-26 02:31:18 +00002057 GCL->getParent()->getGlobalList().insert(GCL, NGV);
Chris Lattner8d4c36b2007-02-11 01:08:35 +00002058 NGV->takeName(GCL);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002059
Chris Lattner696beef2005-09-26 02:31:18 +00002060 // Nuke the old list, replacing any uses with the new one.
2061 if (!GCL->use_empty()) {
2062 Constant *V = NGV;
2063 if (V->getType() != GCL->getType())
Owen Anderson487375e2009-07-29 18:55:55 +00002064 V = ConstantExpr::getBitCast(V, GCL->getType());
Chris Lattner696beef2005-09-26 02:31:18 +00002065 GCL->replaceAllUsesWith(V);
2066 }
2067 GCL->eraseFromParent();
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002068
Chris Lattner696beef2005-09-26 02:31:18 +00002069 if (Ctors.size())
2070 return NGV;
2071 else
Craig Topperf40110f2014-04-25 05:29:35 +00002072 return nullptr;
Chris Lattner696beef2005-09-26 02:31:18 +00002073}
Chris Lattner99e23fa2005-09-26 04:44:35 +00002074
2075
Jakub Staszak9525a772012-12-06 21:57:16 +00002076static inline bool
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002077isSimpleEnoughValueToCommit(Constant *C,
Eli Friedman55fa49f32012-01-05 23:03:32 +00002078 SmallPtrSet<Constant*, 8> &SimpleConstants,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002079 const DataLayout *DL);
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002080
2081
2082/// isSimpleEnoughValueToCommit - Return true if the specified constant can be
2083/// handled by the code generator. We don't want to generate something like:
2084/// void *X = &X/42;
2085/// because the code generator doesn't have a relocation that can handle that.
2086///
2087/// This function should be called if C was not found (but just got inserted)
2088/// in SimpleConstants to avoid having to rescan the same constants all the
2089/// time.
2090static bool isSimpleEnoughValueToCommitHelper(Constant *C,
Eli Friedman55fa49f32012-01-05 23:03:32 +00002091 SmallPtrSet<Constant*, 8> &SimpleConstants,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002092 const DataLayout *DL) {
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002093 // Simple integer, undef, constant aggregate zero, global addresses, etc are
2094 // all supported.
2095 if (C->getNumOperands() == 0 || isa<BlockAddress>(C) ||
2096 isa<GlobalValue>(C))
2097 return true;
Jakub Staszak9525a772012-12-06 21:57:16 +00002098
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002099 // Aggregate values are safe if all their elements are.
2100 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C) ||
2101 isa<ConstantVector>(C)) {
2102 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i) {
2103 Constant *Op = cast<Constant>(C->getOperand(i));
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002104 if (!isSimpleEnoughValueToCommit(Op, SimpleConstants, DL))
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002105 return false;
2106 }
2107 return true;
2108 }
Jakub Staszak9525a772012-12-06 21:57:16 +00002109
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002110 // We don't know exactly what relocations are allowed in constant expressions,
2111 // so we allow &global+constantoffset, which is safe and uniformly supported
2112 // across targets.
2113 ConstantExpr *CE = cast<ConstantExpr>(C);
2114 switch (CE->getOpcode()) {
2115 case Instruction::BitCast:
Eli Friedman55fa49f32012-01-05 23:03:32 +00002116 // Bitcast is fine if the casted value is fine.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002117 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, DL);
Eli Friedman55fa49f32012-01-05 23:03:32 +00002118
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002119 case Instruction::IntToPtr:
2120 case Instruction::PtrToInt:
Eli Friedman55fa49f32012-01-05 23:03:32 +00002121 // int <=> ptr is fine if the int type is the same size as the
2122 // pointer type.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002123 if (!DL || DL->getTypeSizeInBits(CE->getType()) !=
2124 DL->getTypeSizeInBits(CE->getOperand(0)->getType()))
Eli Friedman55fa49f32012-01-05 23:03:32 +00002125 return false;
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002126 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, DL);
Jakub Staszak9525a772012-12-06 21:57:16 +00002127
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002128 // GEP is fine if it is simple + constant offset.
2129 case Instruction::GetElementPtr:
2130 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
2131 if (!isa<ConstantInt>(CE->getOperand(i)))
2132 return false;
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002133 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, DL);
Jakub Staszak9525a772012-12-06 21:57:16 +00002134
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002135 case Instruction::Add:
2136 // We allow simple+cst.
2137 if (!isa<ConstantInt>(CE->getOperand(1)))
2138 return false;
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002139 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, DL);
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002140 }
2141 return false;
2142}
2143
Jakub Staszak9525a772012-12-06 21:57:16 +00002144static inline bool
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002145isSimpleEnoughValueToCommit(Constant *C,
Eli Friedman55fa49f32012-01-05 23:03:32 +00002146 SmallPtrSet<Constant*, 8> &SimpleConstants,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002147 const DataLayout *DL) {
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002148 // If we already checked this constant, we win.
2149 if (!SimpleConstants.insert(C)) return true;
2150 // Check the constant.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002151 return isSimpleEnoughValueToCommitHelper(C, SimpleConstants, DL);
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002152}
2153
2154
Chris Lattner99e23fa2005-09-26 04:44:35 +00002155/// isSimpleEnoughPointerToCommit - Return true if this constant is simple
Owen Anderson9eb7cb482011-01-14 22:19:20 +00002156/// enough for us to understand. In particular, if it is a cast to anything
2157/// other than from one pointer type to another pointer type, we punt.
2158/// We basically just support direct accesses to globals and GEP's of
Chris Lattner99e23fa2005-09-26 04:44:35 +00002159/// globals. This should be kept up to date with CommitValueTo.
Chris Lattner46b5c642009-11-06 04:27:31 +00002160static bool isSimpleEnoughPointerToCommit(Constant *C) {
Dan Gohman82e74752009-09-07 22:42:05 +00002161 // Conservatively, avoid aggregate types. This is because we don't
2162 // want to worry about them partially overlapping other stores.
2163 if (!cast<PointerType>(C->getType())->getElementType()->isSingleValueType())
2164 return false;
2165
Dan Gohmanf7f3fb12009-09-07 22:31:26 +00002166 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
Mikhail Glushenkov2072db22010-10-19 16:47:23 +00002167 // Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or
Dan Gohmanf7f3fb12009-09-07 22:31:26 +00002168 // external globals.
Mikhail Glushenkov2072db22010-10-19 16:47:23 +00002169 return GV->hasUniqueInitializer();
Dan Gohmanf7f3fb12009-09-07 22:31:26 +00002170
Owen Anderson3e2f6cf2011-01-14 22:31:13 +00002171 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
Chris Lattner46af55e2005-09-26 06:52:44 +00002172 // Handle a constantexpr gep.
2173 if (CE->getOpcode() == Instruction::GetElementPtr &&
Dan Gohmanbeee35a2009-09-07 22:40:13 +00002174 isa<GlobalVariable>(CE->getOperand(0)) &&
2175 cast<GEPOperator>(CE)->isInBounds()) {
Chris Lattner46af55e2005-09-26 06:52:44 +00002176 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
Mikhail Glushenkov2072db22010-10-19 16:47:23 +00002177 // Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or
Dan Gohmanf7f3fb12009-09-07 22:31:26 +00002178 // external globals.
Mikhail Glushenkov2072db22010-10-19 16:47:23 +00002179 if (!GV->hasUniqueInitializer())
Dan Gohmanf7f3fb12009-09-07 22:31:26 +00002180 return false;
Dan Gohman161429f2009-09-07 22:44:55 +00002181
Dan Gohman161429f2009-09-07 22:44:55 +00002182 // The first index must be zero.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00002183 ConstantInt *CI = dyn_cast<ConstantInt>(*std::next(CE->op_begin()));
Dan Gohman161429f2009-09-07 22:44:55 +00002184 if (!CI || !CI->isZero()) return false;
Dan Gohman161429f2009-09-07 22:44:55 +00002185
2186 // The remaining indices must be compile-time known integers within the
Dan Gohman7190d482009-09-10 23:37:55 +00002187 // notional bounds of the corresponding static array types.
2188 if (!CE->isGEPWithNoNotionalOverIndexing())
2189 return false;
Dan Gohman161429f2009-09-07 22:44:55 +00002190
Dan Gohmane525d9d2009-10-05 16:36:26 +00002191 return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
Jakub Staszak9525a772012-12-06 21:57:16 +00002192
Owen Anderson9eb7cb482011-01-14 22:19:20 +00002193 // A constantexpr bitcast from a pointer to another pointer is a no-op,
2194 // and we know how to evaluate it by moving the bitcast from the pointer
2195 // operand to the value operand.
2196 } else if (CE->getOpcode() == Instruction::BitCast &&
Chris Lattner8b4952f2011-01-16 02:05:10 +00002197 isa<GlobalVariable>(CE->getOperand(0))) {
Owen Anderson9eb7cb482011-01-14 22:19:20 +00002198 // Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or
2199 // external globals.
Chris Lattner8b4952f2011-01-16 02:05:10 +00002200 return cast<GlobalVariable>(CE->getOperand(0))->hasUniqueInitializer();
Chris Lattner46af55e2005-09-26 06:52:44 +00002201 }
Owen Anderson3e2f6cf2011-01-14 22:31:13 +00002202 }
Jakub Staszak9525a772012-12-06 21:57:16 +00002203
Chris Lattner99e23fa2005-09-26 04:44:35 +00002204 return false;
2205}
2206
Chris Lattner46af55e2005-09-26 06:52:44 +00002207/// EvaluateStoreInto - Evaluate a piece of a constantexpr store into a global
2208/// initializer. This returns 'Init' modified to reflect 'Val' stored into it.
2209/// At this point, the GEP operands of Addr [0, OpNo) have been stepped into.
2210static Constant *EvaluateStoreInto(Constant *Init, Constant *Val,
Zhou Sheng8e6d64a2012-12-01 10:54:28 +00002211 ConstantExpr *Addr, unsigned OpNo) {
Chris Lattner46af55e2005-09-26 06:52:44 +00002212 // Base case of the recursion.
2213 if (OpNo == Addr->getNumOperands()) {
2214 assert(Val->getType() == Init->getType() && "Type mismatch!");
2215 return Val;
2216 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002217
Chris Lattner0256be92012-01-27 03:08:05 +00002218 SmallVector<Constant*, 32> Elts;
Chris Lattner229907c2011-07-18 04:54:35 +00002219 if (StructType *STy = dyn_cast<StructType>(Init->getType())) {
Chris Lattner46af55e2005-09-26 06:52:44 +00002220 // Break up the constant into its elements.
Chris Lattnerfa775002012-01-26 02:32:04 +00002221 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
2222 Elts.push_back(Init->getAggregateElement(i));
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002223
Chris Lattner46af55e2005-09-26 06:52:44 +00002224 // Replace the element that we are supposed to.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002225 ConstantInt *CU = cast<ConstantInt>(Addr->getOperand(OpNo));
2226 unsigned Idx = CU->getZExtValue();
2227 assert(Idx < STy->getNumElements() && "Struct index out of range!");
Zhou Sheng8e6d64a2012-12-01 10:54:28 +00002228 Elts[Idx] = EvaluateStoreInto(Elts[Idx], Val, Addr, OpNo+1);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002229
Chris Lattner46af55e2005-09-26 06:52:44 +00002230 // Return the modified struct.
Chris Lattnercc19efa2011-06-20 04:01:31 +00002231 return ConstantStruct::get(STy, Elts);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002232 }
Jakub Staszak9525a772012-12-06 21:57:16 +00002233
Chris Lattnercc19efa2011-06-20 04:01:31 +00002234 ConstantInt *CI = cast<ConstantInt>(Addr->getOperand(OpNo));
Chris Lattner229907c2011-07-18 04:54:35 +00002235 SequentialType *InitTy = cast<SequentialType>(Init->getType());
Chris Lattnercc19efa2011-06-20 04:01:31 +00002236
2237 uint64_t NumElts;
Chris Lattner229907c2011-07-18 04:54:35 +00002238 if (ArrayType *ATy = dyn_cast<ArrayType>(InitTy))
Chris Lattnercc19efa2011-06-20 04:01:31 +00002239 NumElts = ATy->getNumElements();
2240 else
Chris Lattnerfa775002012-01-26 02:32:04 +00002241 NumElts = InitTy->getVectorNumElements();
Chris Lattnercc19efa2011-06-20 04:01:31 +00002242
2243 // Break up the array into elements.
Chris Lattnerfa775002012-01-26 02:32:04 +00002244 for (uint64_t i = 0, e = NumElts; i != e; ++i)
2245 Elts.push_back(Init->getAggregateElement(i));
Chris Lattnercc19efa2011-06-20 04:01:31 +00002246
2247 assert(CI->getZExtValue() < NumElts);
2248 Elts[CI->getZExtValue()] =
Zhou Sheng8e6d64a2012-12-01 10:54:28 +00002249 EvaluateStoreInto(Elts[CI->getZExtValue()], Val, Addr, OpNo+1);
Chris Lattnercc19efa2011-06-20 04:01:31 +00002250
2251 if (Init->getType()->isArrayTy())
2252 return ConstantArray::get(cast<ArrayType>(InitTy), Elts);
2253 return ConstantVector::get(Elts);
Chris Lattner46af55e2005-09-26 06:52:44 +00002254}
2255
Chris Lattner99e23fa2005-09-26 04:44:35 +00002256/// CommitValueTo - We have decided that Addr (which satisfies the predicate
2257/// isSimpleEnoughPointerToCommit) should get Val as its value. Make it happen.
Chris Lattner46b5c642009-11-06 04:27:31 +00002258static void CommitValueTo(Constant *Val, Constant *Addr) {
Chris Lattner46af55e2005-09-26 06:52:44 +00002259 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Addr)) {
2260 assert(GV->hasInitializer());
2261 GV->setInitializer(Val);
2262 return;
2263 }
Chris Lattner64ecc462010-01-07 01:16:21 +00002264
Chris Lattner46af55e2005-09-26 06:52:44 +00002265 ConstantExpr *CE = cast<ConstantExpr>(Addr);
2266 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
Zhou Sheng8e6d64a2012-12-01 10:54:28 +00002267 GV->setInitializer(EvaluateStoreInto(GV->getInitializer(), Val, CE, 2));
Chris Lattner99e23fa2005-09-26 04:44:35 +00002268}
2269
Nick Lewycky60829a582012-02-20 03:25:59 +00002270namespace {
2271
2272/// Evaluator - This class evaluates LLVM IR, producing the Constant
2273/// representing each SSA instruction. Changes to global variables are stored
2274/// in a mapping that can be iterated over after the evaluation is complete.
2275/// Once an evaluation call fails, the evaluation object should not be reused.
2276class Evaluator {
Nick Lewycky73be5e32012-02-19 23:26:27 +00002277public:
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002278 Evaluator(const DataLayout *DL, const TargetLibraryInfo *TLI)
2279 : DL(DL), TLI(TLI) {
David Blaikiebc442202014-04-21 20:49:36 +00002280 ValueStack.push_back(make_unique<DenseMap<Value*, Constant*>>());
Nick Lewycky73be5e32012-02-19 23:26:27 +00002281 }
2282
Nick Lewycky60829a582012-02-20 03:25:59 +00002283 ~Evaluator() {
David Blaikiebc442202014-04-21 20:49:36 +00002284 for (auto &Tmp : AllocaTmps)
Nick Lewycky73be5e32012-02-19 23:26:27 +00002285 // If there are still users of the alloca, the program is doing something
2286 // silly, e.g. storing the address of the alloca somewhere and using it
2287 // later. Since this is undefined, we'll just make it be null.
2288 if (!Tmp->use_empty())
2289 Tmp->replaceAllUsesWith(Constant::getNullValue(Tmp->getType()));
Nick Lewycky73be5e32012-02-19 23:26:27 +00002290 }
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) {
David Blaikieeb038912014-04-21 20:43:51 +00002311 (*ValueStack.back())[V] = C;
Nick Lewycky73be5e32012-02-19 23:26:27 +00002312 }
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.
David Blaikiebc442202014-04-21 20:49:36 +00002328 SmallVector<std::unique_ptr<DenseMap<Value*, Constant*>>, 4> ValueStack;
Nick Lewycky73be5e32012-02-19 23:26:27 +00002329
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.
David Blaikiebc442202014-04-21 20:49:36 +00002343 SmallVector<std::unique_ptr<GlobalVariable>, 32> AllocaTmps;
Nick Lewycky73be5e32012-02-19 23:26:27 +00002344
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
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002353 const DataLayout *DL;
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();
Craig Topperf40110f2014-04-25 05:29:35 +00002372 return nullptr;
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
Craig Topperf40110f2014-04-25 05:29:35 +00002384 return nullptr; // 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) {
Craig Topperf40110f2014-04-25 05:29:35 +00002394 Constant *InstResult = nullptr;
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);
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002406 Ptr = ConstantFoldConstantExpression(CE, DL, 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.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002419 if (!isSimpleEnoughValueToCommit(Val, SimpleConstants, DL)) {
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))
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002451 Ptr = ConstantFoldConstantExpression(CE, DL, TLI);
Nick Lewycky9d0da182012-02-21 22:08:06 +00002452
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)) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002515 Ptr = ConstantFoldConstantExpression(CE, DL, 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);
Craig Topperf40110f2014-04-25 05:29:35 +00002520 if (!InstResult) {
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();
David Blaikiebc442202014-04-21 20:49:36 +00002533 AllocaTmps.push_back(
2534 make_unique<GlobalVariable>(Ty, false, GlobalValue::InternalLinkage,
2535 UndefValue::get(Ty), AI->getName()));
2536 InstResult = AllocaTmps.back().get();
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002537 DEBUG(dbgs() << "Found an alloca. Result: " << *InstResult << "\n");
Nick Lewyckyc1572e42012-02-12 05:09:35 +00002538 } else if (isa<CallInst>(CurInst) || isa<InvokeInst>(CurInst)) {
2539 CallSite CS(CurInst);
Devang Patel04852aa2009-03-09 23:04:12 +00002540
2541 // Debug info can safely be ignored here.
Nick Lewyckyc1572e42012-02-12 05:09:35 +00002542 if (isa<DbgInfoIntrinsic>(CS.getInstruction())) {
Michael Gottesman2a654272013-01-11 23:08:52 +00002543 DEBUG(dbgs() << "Ignoring debug info.\n");
Devang Patel04852aa2009-03-09 23:04:12 +00002544 ++CurInst;
2545 continue;
2546 }
2547
Chris Lattnerfd2e13b2006-07-07 21:37:01 +00002548 // Cannot handle inline asm.
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002549 if (isa<InlineAsm>(CS.getCalledValue())) {
Michael Gottesman2a654272013-01-11 23:08:52 +00002550 DEBUG(dbgs() << "Found inline asm, can not evaluate.\n");
2551 return false;
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002552 }
Chris Lattnerfd2e13b2006-07-07 21:37:01 +00002553
Nick Lewycky68f9f9d2012-02-17 06:59:21 +00002554 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CS.getInstruction())) {
2555 if (MemSetInst *MSI = dyn_cast<MemSetInst>(II)) {
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002556 if (MSI->isVolatile()) {
Michael Gottesman2a654272013-01-11 23:08:52 +00002557 DEBUG(dbgs() << "Can not optimize a volatile memset " <<
2558 "intrinsic.\n");
2559 return false;
2560 }
Nick Lewycky73be5e32012-02-19 23:26:27 +00002561 Constant *Ptr = getVal(MSI->getDest());
2562 Constant *Val = getVal(MSI->getValue());
2563 Constant *DestVal = ComputeLoadResult(getVal(Ptr));
Nick Lewycky68f9f9d2012-02-17 06:59:21 +00002564 if (Val->isNullValue() && DestVal && DestVal->isNullValue()) {
2565 // This memset is a no-op.
Michael Gottesman2a654272013-01-11 23:08:52 +00002566 DEBUG(dbgs() << "Ignoring no-op memset.\n");
Nick Lewycky68f9f9d2012-02-17 06:59:21 +00002567 ++CurInst;
2568 continue;
2569 }
2570 }
2571
2572 if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
2573 II->getIntrinsicID() == Intrinsic::lifetime_end) {
Michael Gottesman2a654272013-01-11 23:08:52 +00002574 DEBUG(dbgs() << "Ignoring lifetime intrinsic.\n");
Nick Lewycky68f9f9d2012-02-17 06:59:21 +00002575 ++CurInst;
2576 continue;
2577 }
2578
2579 if (II->getIntrinsicID() == Intrinsic::invariant_start) {
2580 // We don't insert an entry into Values, as it doesn't have a
2581 // meaningful return value.
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002582 if (!II->use_empty()) {
Alp Tokerf907b892013-12-05 05:44:44 +00002583 DEBUG(dbgs() << "Found unused invariant_start. Can't evaluate.\n");
Nick Lewycky68f9f9d2012-02-17 06:59:21 +00002584 return false;
Michael Gottesman2a654272013-01-11 23:08:52 +00002585 }
Nick Lewycky68f9f9d2012-02-17 06:59:21 +00002586 ConstantInt *Size = cast<ConstantInt>(II->getArgOperand(0));
Nick Lewycky519561f2012-02-20 23:32:26 +00002587 Value *PtrArg = getVal(II->getArgOperand(1));
2588 Value *Ptr = PtrArg->stripPointerCasts();
2589 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr)) {
2590 Type *ElemTy = cast<PointerType>(GV->getType())->getElementType();
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002591 if (DL && !Size->isAllOnesValue() &&
Nick Lewycky519561f2012-02-20 23:32:26 +00002592 Size->getValue().getLimitedValue() >=
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002593 DL->getTypeStoreSize(ElemTy)) {
Nick Lewycky68f9f9d2012-02-17 06:59:21 +00002594 Invariants.insert(GV);
Michael Gottesman2a654272013-01-11 23:08:52 +00002595 DEBUG(dbgs() << "Found a global var that is an invariant: " << *GV
2596 << "\n");
2597 } else {
2598 DEBUG(dbgs() << "Found a global var, but can not treat it as an "
2599 "invariant.\n");
2600 }
Nick Lewycky68f9f9d2012-02-17 06:59:21 +00002601 }
2602 // Continue even if we do nothing.
Nick Lewyckya3bb03e2011-05-29 18:41:56 +00002603 ++CurInst;
2604 continue;
2605 }
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002606
Michael Gottesman2a654272013-01-11 23:08:52 +00002607 DEBUG(dbgs() << "Unknown intrinsic. Can not evaluate.\n");
Nick Lewyckya3bb03e2011-05-29 18:41:56 +00002608 return false;
2609 }
2610
Chris Lattner65a3a092005-09-27 04:45:34 +00002611 // Resolve function pointers.
Nick Lewycky73be5e32012-02-19 23:26:27 +00002612 Function *Callee = dyn_cast<Function>(getVal(CS.getCalledValue()));
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002613 if (!Callee || Callee->mayBeOverridden()) {
Michael Gottesman2a654272013-01-11 23:08:52 +00002614 DEBUG(dbgs() << "Can not resolve function pointer.\n");
Nick Lewyckyc1572e42012-02-12 05:09:35 +00002615 return false; // Cannot resolve.
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002616 }
Chris Lattner3d27e7f2005-09-27 05:02:43 +00002617
Duncan Sandsc4ce58d82009-08-17 14:33:27 +00002618 SmallVector<Constant*, 8> Formals;
Nick Lewyckyc1572e42012-02-12 05:09:35 +00002619 for (User::op_iterator i = CS.arg_begin(), e = CS.arg_end(); i != e; ++i)
Nick Lewycky73be5e32012-02-19 23:26:27 +00002620 Formals.push_back(getVal(*i));
Duncan Sandsc4ce58d82009-08-17 14:33:27 +00002621
Reid Spencer5301e7c2007-01-30 20:08:39 +00002622 if (Callee->isDeclaration()) {
Chris Lattner3d27e7f2005-09-27 05:02:43 +00002623 // If this is a function we can constant fold, do it.
Chad Rosiere6de63d2011-12-01 21:29:16 +00002624 if (Constant *C = ConstantFoldCall(Callee, Formals, TLI)) {
Chris Lattner3d27e7f2005-09-27 05:02:43 +00002625 InstResult = C;
Michael Gottesman2a654272013-01-11 23:08:52 +00002626 DEBUG(dbgs() << "Constant folded function call. Result: " <<
2627 *InstResult << "\n");
Chris Lattner3d27e7f2005-09-27 05:02:43 +00002628 } else {
Michael Gottesman2a654272013-01-11 23:08:52 +00002629 DEBUG(dbgs() << "Can not constant fold function call.\n");
Chris Lattner3d27e7f2005-09-27 05:02:43 +00002630 return false;
2631 }
2632 } else {
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002633 if (Callee->getFunctionType()->isVarArg()) {
Michael Gottesman2a654272013-01-11 23:08:52 +00002634 DEBUG(dbgs() << "Can not constant fold vararg function call.\n");
Chris Lattner3d27e7f2005-09-27 05:02:43 +00002635 return false;
Michael Gottesman2a654272013-01-11 23:08:52 +00002636 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002637
Craig Topperf40110f2014-04-25 05:29:35 +00002638 Constant *RetVal = nullptr;
Chris Lattner3d27e7f2005-09-27 05:02:43 +00002639 // Execute the call, if successful, use the return value.
David Blaikiebc442202014-04-21 20:49:36 +00002640 ValueStack.push_back(make_unique<DenseMap<Value *, Constant *>>());
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002641 if (!EvaluateFunction(Callee, RetVal, Formals)) {
Michael Gottesman2a654272013-01-11 23:08:52 +00002642 DEBUG(dbgs() << "Failed to evaluate function.\n");
Chris Lattner3d27e7f2005-09-27 05:02:43 +00002643 return false;
Michael Gottesman2a654272013-01-11 23:08:52 +00002644 }
David Blaikiebc442202014-04-21 20:49:36 +00002645 ValueStack.pop_back();
Chris Lattner3d27e7f2005-09-27 05:02:43 +00002646 InstResult = RetVal;
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002647
Craig Topperf40110f2014-04-25 05:29:35 +00002648 if (InstResult) {
Michael Gottesman2a654272013-01-11 23:08:52 +00002649 DEBUG(dbgs() << "Successfully evaluated function. Result: " <<
2650 InstResult << "\n\n");
2651 } else {
2652 DEBUG(dbgs() << "Successfully evaluated function. Result: 0\n\n");
2653 }
Chris Lattner3d27e7f2005-09-27 05:02:43 +00002654 }
Reid Spencerde46e482006-11-02 20:25:50 +00002655 } else if (isa<TerminatorInst>(CurInst)) {
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002656 DEBUG(dbgs() << "Found a terminator instruction.\n");
2657
Chris Lattner3e9ea5f2005-09-26 04:57:38 +00002658 if (BranchInst *BI = dyn_cast<BranchInst>(CurInst)) {
2659 if (BI->isUnconditional()) {
Nick Lewycky239fdf02012-02-06 08:24:44 +00002660 NextBB = BI->getSuccessor(0);
Chris Lattner3e9ea5f2005-09-26 04:57:38 +00002661 } else {
Zhou Sheng75b871f2007-01-11 12:24:14 +00002662 ConstantInt *Cond =
Nick Lewycky73be5e32012-02-19 23:26:27 +00002663 dyn_cast<ConstantInt>(getVal(BI->getCondition()));
Chris Lattner15649082007-01-12 18:30:11 +00002664 if (!Cond) return false; // Cannot determine.
Zhou Sheng75b871f2007-01-11 12:24:14 +00002665
Nick Lewycky239fdf02012-02-06 08:24:44 +00002666 NextBB = BI->getSuccessor(!Cond->getZExtValue());
Chris Lattner3e9ea5f2005-09-26 04:57:38 +00002667 }
2668 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(CurInst)) {
2669 ConstantInt *Val =
Nick Lewycky73be5e32012-02-19 23:26:27 +00002670 dyn_cast<ConstantInt>(getVal(SI->getCondition()));
Chris Lattner65a3a092005-09-27 04:45:34 +00002671 if (!Val) return false; // Cannot determine.
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00002672 NextBB = SI->findCaseValue(Val).getCaseSuccessor();
Chris Lattner31274882009-10-29 05:51:50 +00002673 } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(CurInst)) {
Nick Lewycky73be5e32012-02-19 23:26:27 +00002674 Value *Val = getVal(IBI->getAddress())->stripPointerCasts();
Chris Lattner31274882009-10-29 05:51:50 +00002675 if (BlockAddress *BA = dyn_cast<BlockAddress>(Val))
Nick Lewycky239fdf02012-02-06 08:24:44 +00002676 NextBB = BA->getBasicBlock();
Chris Lattneraa99c942009-11-01 01:27:45 +00002677 else
2678 return false; // Cannot determine.
Nick Lewycky239fdf02012-02-06 08:24:44 +00002679 } else if (isa<ReturnInst>(CurInst)) {
Craig Topperf40110f2014-04-25 05:29:35 +00002680 NextBB = nullptr;
Chris Lattner3e9ea5f2005-09-26 04:57:38 +00002681 } else {
Bill Wendlingf891bf82011-07-31 06:30:59 +00002682 // invoke, unwind, resume, unreachable.
Michael Gottesman2a654272013-01-11 23:08:52 +00002683 DEBUG(dbgs() << "Can not handle terminator.");
Chris Lattner65a3a092005-09-27 04:45:34 +00002684 return false; // Cannot handle this terminator.
Chris Lattner3e9ea5f2005-09-26 04:57:38 +00002685 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002686
Nick Lewycky239fdf02012-02-06 08:24:44 +00002687 // We succeeded at evaluating this block!
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002688 DEBUG(dbgs() << "Successfully evaluated block.\n");
Nick Lewycky239fdf02012-02-06 08:24:44 +00002689 return true;
Chris Lattner99e23fa2005-09-26 04:44:35 +00002690 } else {
Chris Lattner99e23fa2005-09-26 04:44:35 +00002691 // Did not know how to evaluate this!
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002692 DEBUG(dbgs() << "Failed to evaluate block due to unhandled instruction."
Michael Gottesman2a654272013-01-11 23:08:52 +00002693 "\n");
Chris Lattner65a3a092005-09-27 04:45:34 +00002694 return false;
Chris Lattner99e23fa2005-09-26 04:44:35 +00002695 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002696
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002697 if (!CurInst->use_empty()) {
2698 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(InstResult))
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002699 InstResult = ConstantFoldConstantExpression(CE, DL, TLI);
Jakub Staszak9525a772012-12-06 21:57:16 +00002700
Nick Lewycky73be5e32012-02-19 23:26:27 +00002701 setVal(CurInst, InstResult);
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002702 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002703
Dan Gohmaneab06fa2012-03-13 18:01:37 +00002704 // If we just processed an invoke, we finished evaluating the block.
2705 if (InvokeInst *II = dyn_cast<InvokeInst>(CurInst)) {
2706 NextBB = II->getNormalDest();
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002707 DEBUG(dbgs() << "Found an invoke instruction. Finished Block.\n\n");
Dan Gohmaneab06fa2012-03-13 18:01:37 +00002708 return true;
2709 }
2710
Chris Lattner99e23fa2005-09-26 04:44:35 +00002711 // Advance program counter.
2712 ++CurInst;
2713 }
Chris Lattnerda1889b2005-09-27 04:27:01 +00002714}
2715
Nick Lewycky239fdf02012-02-06 08:24:44 +00002716/// EvaluateFunction - Evaluate a call to function F, returning true if
2717/// successful, false if we can't evaluate it. ActualArgs contains the formal
2718/// arguments for the function.
Nick Lewycky60829a582012-02-20 03:25:59 +00002719bool Evaluator::EvaluateFunction(Function *F, Constant *&RetVal,
2720 const SmallVectorImpl<Constant*> &ActualArgs) {
Nick Lewycky239fdf02012-02-06 08:24:44 +00002721 // Check to see if this function is already executing (recursion). If so,
2722 // bail out. TODO: we might want to accept limited recursion.
2723 if (std::find(CallStack.begin(), CallStack.end(), F) != CallStack.end())
2724 return false;
2725
2726 CallStack.push_back(F);
2727
Nick Lewycky239fdf02012-02-06 08:24:44 +00002728 // Initialize arguments to the incoming values specified.
2729 unsigned ArgNo = 0;
2730 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); AI != E;
2731 ++AI, ++ArgNo)
Nick Lewycky73be5e32012-02-19 23:26:27 +00002732 setVal(AI, ActualArgs[ArgNo]);
Nick Lewycky239fdf02012-02-06 08:24:44 +00002733
2734 // ExecutedBlocks - We only handle non-looping, non-recursive code. As such,
2735 // we can only evaluate any one basic block at most once. This set keeps
2736 // track of what we have executed so we can detect recursive cases etc.
2737 SmallPtrSet<BasicBlock*, 32> ExecutedBlocks;
2738
2739 // CurBB - The current basic block we're evaluating.
2740 BasicBlock *CurBB = F->begin();
2741
Nick Lewycky4231c412012-02-12 00:47:24 +00002742 BasicBlock::iterator CurInst = CurBB->begin();
2743
Nick Lewycky239fdf02012-02-06 08:24:44 +00002744 while (1) {
Craig Topperf40110f2014-04-25 05:29:35 +00002745 BasicBlock *NextBB = nullptr; // Initialized to avoid compiler warnings.
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002746 DEBUG(dbgs() << "Trying to evaluate BB: " << *CurBB << "\n");
2747
Nick Lewycky73be5e32012-02-19 23:26:27 +00002748 if (!EvaluateBlock(CurInst, NextBB))
Nick Lewycky239fdf02012-02-06 08:24:44 +00002749 return false;
2750
Craig Topperf40110f2014-04-25 05:29:35 +00002751 if (!NextBB) {
Nick Lewycky239fdf02012-02-06 08:24:44 +00002752 // Successfully running until there's no next block means that we found
2753 // the return. Fill it the return value and pop the call stack.
2754 ReturnInst *RI = cast<ReturnInst>(CurBB->getTerminator());
2755 if (RI->getNumOperands())
Nick Lewycky73be5e32012-02-19 23:26:27 +00002756 RetVal = getVal(RI->getOperand(0));
Nick Lewycky239fdf02012-02-06 08:24:44 +00002757 CallStack.pop_back();
2758 return true;
2759 }
2760
2761 // Okay, we succeeded in evaluating this control flow. See if we have
2762 // executed the new block before. If so, we have a looping function,
2763 // which we cannot evaluate in reasonable time.
2764 if (!ExecutedBlocks.insert(NextBB))
2765 return false; // looped!
2766
2767 // Okay, we have never been in this block before. Check to see if there
2768 // are any PHI nodes. If so, evaluate them with information about where
2769 // we came from.
Craig Topperf40110f2014-04-25 05:29:35 +00002770 PHINode *PN = nullptr;
Nick Lewycky4231c412012-02-12 00:47:24 +00002771 for (CurInst = NextBB->begin();
2772 (PN = dyn_cast<PHINode>(CurInst)); ++CurInst)
Nick Lewycky73be5e32012-02-19 23:26:27 +00002773 setVal(PN, getVal(PN->getIncomingValueForBlock(CurBB)));
Nick Lewycky239fdf02012-02-06 08:24:44 +00002774
2775 // Advance to the next block.
2776 CurBB = NextBB;
2777 }
2778}
2779
Chris Lattnerda1889b2005-09-27 04:27:01 +00002780/// EvaluateStaticConstructor - Evaluate static constructors in the function, if
2781/// we can. Return true if we can, false otherwise.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002782static bool EvaluateStaticConstructor(Function *F, const DataLayout *DL,
Chad Rosiere6de63d2011-12-01 21:29:16 +00002783 const TargetLibraryInfo *TLI) {
Chris Lattnerda1889b2005-09-27 04:27:01 +00002784 // Call the function.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002785 Evaluator Eval(DL, TLI);
Chris Lattner65a3a092005-09-27 04:45:34 +00002786 Constant *RetValDummy;
Nick Lewycky73be5e32012-02-19 23:26:27 +00002787 bool EvalSuccess = Eval.EvaluateFunction(F, RetValDummy,
2788 SmallVector<Constant*, 0>());
Jakub Staszak9525a772012-12-06 21:57:16 +00002789
Chris Lattnerda1889b2005-09-27 04:27:01 +00002790 if (EvalSuccess) {
Chris Lattner6bf2cd52005-09-26 17:07:09 +00002791 // We succeeded at evaluation: commit the result.
David Greene44cb8ad2010-01-05 01:28:05 +00002792 DEBUG(dbgs() << "FULLY EVALUATED GLOBAL CTOR FUNCTION '"
Nick Lewycky73be5e32012-02-19 23:26:27 +00002793 << F->getName() << "' to " << Eval.getMutatedMemory().size()
Daniel Dunbar0dd5e1e2009-07-25 00:23:56 +00002794 << " stores.\n");
Nick Lewycky73be5e32012-02-19 23:26:27 +00002795 for (DenseMap<Constant*, Constant*>::const_iterator I =
2796 Eval.getMutatedMemory().begin(), E = Eval.getMutatedMemory().end();
Nick Lewyckyb74ae9c2012-06-24 04:07:14 +00002797 I != E; ++I)
Chris Lattner46b5c642009-11-06 04:27:31 +00002798 CommitValueTo(I->second, I->first);
Nick Lewycky73be5e32012-02-19 23:26:27 +00002799 for (SmallPtrSet<GlobalVariable*, 8>::const_iterator I =
2800 Eval.getInvariants().begin(), E = Eval.getInvariants().end();
2801 I != E; ++I)
Nick Lewycky68f9f9d2012-02-17 06:59:21 +00002802 (*I)->setConstant(true);
Chris Lattner6bf2cd52005-09-26 17:07:09 +00002803 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002804
Chris Lattnerda1889b2005-09-27 04:27:01 +00002805 return EvalSuccess;
Chris Lattner99e23fa2005-09-26 04:44:35 +00002806}
2807
Chris Lattner41b6a5a2005-09-26 01:43:45 +00002808/// OptimizeGlobalCtorsList - Simplify and evaluation global ctors if possible.
2809/// Return true if anything changed.
2810bool GlobalOpt::OptimizeGlobalCtorsList(GlobalVariable *&GCL) {
2811 std::vector<Function*> Ctors = ParseGlobalCtors(GCL);
2812 bool MadeChange = false;
2813 if (Ctors.empty()) return false;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002814
Chris Lattner41b6a5a2005-09-26 01:43:45 +00002815 // Loop over global ctors, optimizing them when we can.
2816 for (unsigned i = 0; i != Ctors.size(); ++i) {
2817 Function *F = Ctors[i];
2818 // Found a null terminator in the middle of the list, prune off the rest of
2819 // the list.
Craig Topperf40110f2014-04-25 05:29:35 +00002820 if (!F) {
Chris Lattner838bdc12005-09-26 02:19:27 +00002821 if (i != Ctors.size()-1) {
2822 Ctors.resize(i+1);
2823 MadeChange = true;
2824 }
Chris Lattner41b6a5a2005-09-26 01:43:45 +00002825 break;
2826 }
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002827 DEBUG(dbgs() << "Optimizing Global Constructor: " << *F << "\n");
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002828
Chris Lattner99e23fa2005-09-26 04:44:35 +00002829 // We cannot simplify external ctor functions.
2830 if (F->empty()) continue;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002831
Chris Lattner99e23fa2005-09-26 04:44:35 +00002832 // If we can evaluate the ctor at compile time, do.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002833 if (EvaluateStaticConstructor(F, DL, TLI)) {
Chris Lattner99e23fa2005-09-26 04:44:35 +00002834 Ctors.erase(Ctors.begin()+i);
2835 MadeChange = true;
2836 --i;
2837 ++NumCtorsEvaluated;
2838 continue;
2839 }
Chris Lattner41b6a5a2005-09-26 01:43:45 +00002840 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002841
Chris Lattner41b6a5a2005-09-26 01:43:45 +00002842 if (!MadeChange) return false;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002843
Chris Lattner46b5c642009-11-06 04:27:31 +00002844 GCL = InstallGlobalCtors(GCL, Ctors);
Chris Lattner41b6a5a2005-09-26 01:43:45 +00002845 return true;
2846}
2847
Benjamin Krameradf1ea82014-03-07 21:52:38 +00002848static int compareNames(Constant *const *A, Constant *const *B) {
2849 return (*A)->getName().compare((*B)->getName());
2850}
2851
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002852static void setUsedInitializer(GlobalVariable &V,
2853 SmallPtrSet<GlobalValue *, 8> Init) {
Rafael Espindolac2bb73f2013-07-20 23:33:15 +00002854 if (Init.empty()) {
2855 V.eraseFromParent();
2856 return;
2857 }
2858
Matt Arsenaultda1deab2014-01-02 19:53:49 +00002859 // Type of pointer to the array of pointers.
2860 PointerType *Int8PtrTy = Type::getInt8PtrTy(V.getContext(), 0);
Rafael Espindola00752162013-05-09 17:22:59 +00002861
Matt Arsenaultda1deab2014-01-02 19:53:49 +00002862 SmallVector<llvm::Constant *, 8> UsedArray;
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002863 for (SmallPtrSet<GlobalValue *, 8>::iterator I = Init.begin(), E = Init.end();
2864 I != E; ++I) {
Matt Arsenaultda1deab2014-01-02 19:53:49 +00002865 Constant *Cast
2866 = ConstantExpr::getPointerBitCastOrAddrSpaceCast(*I, Int8PtrTy);
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002867 UsedArray.push_back(Cast);
Rafael Espindola00752162013-05-09 17:22:59 +00002868 }
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002869 // Sort to get deterministic order.
Benjamin Krameradf1ea82014-03-07 21:52:38 +00002870 array_pod_sort(UsedArray.begin(), UsedArray.end(), compareNames);
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002871 ArrayType *ATy = ArrayType::get(Int8PtrTy, UsedArray.size());
Rafael Espindola00752162013-05-09 17:22:59 +00002872
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002873 Module *M = V.getParent();
2874 V.removeFromParent();
2875 GlobalVariable *NV =
2876 new GlobalVariable(*M, ATy, false, llvm::GlobalValue::AppendingLinkage,
2877 llvm::ConstantArray::get(ATy, UsedArray), "");
2878 NV->takeName(&V);
2879 NV->setSection("llvm.metadata");
2880 delete &V;
Rafael Espindola00752162013-05-09 17:22:59 +00002881}
2882
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002883namespace {
Rafael Espindola9aadcc42013-07-19 18:44:51 +00002884/// \brief An easy to access representation of llvm.used and llvm.compiler.used.
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002885class LLVMUsed {
2886 SmallPtrSet<GlobalValue *, 8> Used;
2887 SmallPtrSet<GlobalValue *, 8> CompilerUsed;
2888 GlobalVariable *UsedV;
2889 GlobalVariable *CompilerUsedV;
2890
2891public:
Rafael Espindolaec2375f2013-07-25 02:50:08 +00002892 LLVMUsed(Module &M) {
Rafael Espindola17600e22013-07-25 03:23:25 +00002893 UsedV = collectUsedGlobalVariables(M, Used, false);
2894 CompilerUsedV = collectUsedGlobalVariables(M, CompilerUsed, true);
Rafael Espindola00752162013-05-09 17:22:59 +00002895 }
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002896 typedef SmallPtrSet<GlobalValue *, 8>::iterator iterator;
2897 iterator usedBegin() { return Used.begin(); }
2898 iterator usedEnd() { return Used.end(); }
2899 iterator compilerUsedBegin() { return CompilerUsed.begin(); }
2900 iterator compilerUsedEnd() { return CompilerUsed.end(); }
2901 bool usedCount(GlobalValue *GV) const { return Used.count(GV); }
2902 bool compilerUsedCount(GlobalValue *GV) const {
2903 return CompilerUsed.count(GV);
2904 }
2905 bool usedErase(GlobalValue *GV) { return Used.erase(GV); }
2906 bool compilerUsedErase(GlobalValue *GV) { return CompilerUsed.erase(GV); }
2907 bool usedInsert(GlobalValue *GV) { return Used.insert(GV); }
2908 bool compilerUsedInsert(GlobalValue *GV) { return CompilerUsed.insert(GV); }
Rafael Espindola00752162013-05-09 17:22:59 +00002909
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002910 void syncVariablesAndSets() {
2911 if (UsedV)
2912 setUsedInitializer(*UsedV, Used);
2913 if (CompilerUsedV)
2914 setUsedInitializer(*CompilerUsedV, CompilerUsed);
2915 }
2916};
Rafael Espindola00752162013-05-09 17:22:59 +00002917}
2918
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002919static bool hasUseOtherThanLLVMUsed(GlobalAlias &GA, const LLVMUsed &U) {
2920 if (GA.use_empty()) // No use at all.
2921 return false;
2922
2923 assert((!U.usedCount(&GA) || !U.compilerUsedCount(&GA)) &&
2924 "We should have removed the duplicated "
Rafael Espindola9aadcc42013-07-19 18:44:51 +00002925 "element from llvm.compiler.used");
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002926 if (!GA.hasOneUse())
2927 // Strictly more than one use. So at least one is not in llvm.used and
Rafael Espindola9aadcc42013-07-19 18:44:51 +00002928 // llvm.compiler.used.
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002929 return true;
2930
Rafael Espindola9aadcc42013-07-19 18:44:51 +00002931 // Exactly one use. Check if it is in llvm.used or llvm.compiler.used.
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002932 return !U.usedCount(&GA) && !U.compilerUsedCount(&GA);
Rafael Espindola00752162013-05-09 17:22:59 +00002933}
2934
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002935static bool hasMoreThanOneUseOtherThanLLVMUsed(GlobalValue &V,
2936 const LLVMUsed &U) {
2937 unsigned N = 2;
2938 assert((!U.usedCount(&V) || !U.compilerUsedCount(&V)) &&
2939 "We should have removed the duplicated "
Rafael Espindola9aadcc42013-07-19 18:44:51 +00002940 "element from llvm.compiler.used");
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002941 if (U.usedCount(&V) || U.compilerUsedCount(&V))
2942 ++N;
2943 return V.hasNUsesOrMore(N);
2944}
2945
2946static bool mayHaveOtherReferences(GlobalAlias &GA, const LLVMUsed &U) {
2947 if (!GA.hasLocalLinkage())
2948 return true;
2949
2950 return U.usedCount(&GA) || U.compilerUsedCount(&GA);
2951}
2952
2953static bool hasUsesToReplace(GlobalAlias &GA, LLVMUsed &U, bool &RenameTarget) {
2954 RenameTarget = false;
Rafael Espindola00752162013-05-09 17:22:59 +00002955 bool Ret = false;
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002956 if (hasUseOtherThanLLVMUsed(GA, U))
Rafael Espindola00752162013-05-09 17:22:59 +00002957 Ret = true;
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002958
2959 // If the alias is externally visible, we may still be able to simplify it.
2960 if (!mayHaveOtherReferences(GA, U))
2961 return Ret;
2962
2963 // If the aliasee has internal linkage, give it the name and linkage
2964 // of the alias, and delete the alias. This turns:
2965 // define internal ... @f(...)
2966 // @a = alias ... @f
2967 // into:
2968 // define ... @a(...)
2969 Constant *Aliasee = GA.getAliasee();
2970 GlobalValue *Target = cast<GlobalValue>(Aliasee->stripPointerCasts());
2971 if (!Target->hasLocalLinkage())
2972 return Ret;
2973
2974 // Do not perform the transform if multiple aliases potentially target the
2975 // aliasee. This check also ensures that it is safe to replace the section
2976 // and other attributes of the aliasee with those of the alias.
2977 if (hasMoreThanOneUseOtherThanLLVMUsed(*Target, U))
2978 return Ret;
2979
2980 RenameTarget = true;
2981 return true;
Rafael Espindola00752162013-05-09 17:22:59 +00002982}
2983
Duncan Sandsed722832009-03-06 10:21:56 +00002984bool GlobalOpt::OptimizeGlobalAliases(Module &M) {
Anton Korobeynikova9b60ee2008-09-09 19:04:59 +00002985 bool Changed = false;
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002986 LLVMUsed Used(M);
2987
2988 for (SmallPtrSet<GlobalValue *, 8>::iterator I = Used.usedBegin(),
2989 E = Used.usedEnd();
2990 I != E; ++I)
2991 Used.compilerUsedErase(*I);
Anton Korobeynikova9b60ee2008-09-09 19:04:59 +00002992
Duncan Sands0bcf0852009-01-07 20:01:06 +00002993 for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end();
Duncan Sandsb3f27882009-02-15 09:56:08 +00002994 I != E;) {
2995 Module::alias_iterator J = I++;
Duncan Sandsed722832009-03-06 10:21:56 +00002996 // Aliases without names cannot be referenced outside this module.
2997 if (!J->hasName() && !J->isDeclaration())
2998 J->setLinkage(GlobalValue::InternalLinkage);
Duncan Sandsb3f27882009-02-15 09:56:08 +00002999 // If the aliasee may change at link time, nothing can be done - bail out.
3000 if (J->mayBeOverridden())
Anton Korobeynikova9b60ee2008-09-09 19:04:59 +00003001 continue;
3002
Duncan Sandsb3f27882009-02-15 09:56:08 +00003003 Constant *Aliasee = J->getAliasee();
3004 GlobalValue *Target = cast<GlobalValue>(Aliasee->stripPointerCasts());
Duncan Sands7a1db332009-02-18 17:55:38 +00003005 Target->removeDeadConstantUsers();
Duncan Sandsb3f27882009-02-15 09:56:08 +00003006
3007 // Make all users of the alias use the aliasee instead.
Rafael Espindolaa82555c2013-06-11 17:48:06 +00003008 bool RenameTarget;
3009 if (!hasUsesToReplace(*J, Used, RenameTarget))
Rafael Espindola00752162013-05-09 17:22:59 +00003010 continue;
Duncan Sandsb3f27882009-02-15 09:56:08 +00003011
Rafael Espindolaa82555c2013-06-11 17:48:06 +00003012 J->replaceAllUsesWith(Aliasee);
3013 ++NumAliasesResolved;
3014 Changed = true;
Duncan Sandsb3f27882009-02-15 09:56:08 +00003015
Rafael Espindolaa82555c2013-06-11 17:48:06 +00003016 if (RenameTarget) {
Duncan Sands6a3df7b2009-12-08 10:10:20 +00003017 // Give the aliasee the name, linkage and other attributes of the alias.
3018 Target->takeName(J);
3019 Target->setLinkage(J->getLinkage());
Reid Kleckner22b19da2014-02-13 02:18:36 +00003020 Target->setVisibility(J->getVisibility());
3021 Target->setDLLStorageClass(J->getDLLStorageClass());
Rafael Espindolaa82555c2013-06-11 17:48:06 +00003022
3023 if (Used.usedErase(J))
3024 Used.usedInsert(Target);
3025
3026 if (Used.compilerUsedErase(J))
3027 Used.compilerUsedInsert(Target);
Rafael Espindola8d304802013-06-12 16:45:47 +00003028 } else if (mayHaveOtherReferences(*J, Used))
Rafael Espindolaa82555c2013-06-11 17:48:06 +00003029 continue;
3030
Duncan Sandsb3f27882009-02-15 09:56:08 +00003031 // Delete the alias.
3032 M.getAliasList().erase(J);
3033 ++NumAliasesRemoved;
3034 Changed = true;
Anton Korobeynikova9b60ee2008-09-09 19:04:59 +00003035 }
3036
Rafael Espindolaa82555c2013-06-11 17:48:06 +00003037 Used.syncVariablesAndSets();
3038
Anton Korobeynikova9b60ee2008-09-09 19:04:59 +00003039 return Changed;
3040}
Chris Lattner41b6a5a2005-09-26 01:43:45 +00003041
Nick Lewycky4b273cb2012-02-12 02:15:20 +00003042static Function *FindCXAAtExit(Module &M, TargetLibraryInfo *TLI) {
3043 if (!TLI->has(LibFunc::cxa_atexit))
Craig Topperf40110f2014-04-25 05:29:35 +00003044 return nullptr;
Nick Lewycky4b273cb2012-02-12 02:15:20 +00003045
3046 Function *Fn = M.getFunction(TLI->getName(LibFunc::cxa_atexit));
Jakub Staszak9525a772012-12-06 21:57:16 +00003047
Anders Carlssonee6bc702011-03-20 17:59:11 +00003048 if (!Fn)
Craig Topperf40110f2014-04-25 05:29:35 +00003049 return nullptr;
Nick Lewycky4b273cb2012-02-12 02:15:20 +00003050
Chris Lattner229907c2011-07-18 04:54:35 +00003051 FunctionType *FTy = Fn->getFunctionType();
Jakub Staszak9525a772012-12-06 21:57:16 +00003052
3053 // Checking that the function has the right return type, the right number of
Anders Carlsson48a44912011-03-20 19:51:13 +00003054 // parameters and that they all have pointer types should be enough.
3055 if (!FTy->getReturnType()->isIntegerTy() ||
3056 FTy->getNumParams() != 3 ||
Anders Carlssonee6bc702011-03-20 17:59:11 +00003057 !FTy->getParamType(0)->isPointerTy() ||
3058 !FTy->getParamType(1)->isPointerTy() ||
3059 !FTy->getParamType(2)->isPointerTy())
Craig Topperf40110f2014-04-25 05:29:35 +00003060 return nullptr;
Anders Carlssonee6bc702011-03-20 17:59:11 +00003061
3062 return Fn;
3063}
3064
3065/// cxxDtorIsEmpty - Returns whether the given function is an empty C++
3066/// destructor and can therefore be eliminated.
3067/// Note that we assume that other optimization passes have already simplified
3068/// the code so we only look for a function with a single basic block, where
Benjamin Kramer1a4695a2012-02-09 16:28:15 +00003069/// the only allowed instructions are 'ret', 'call' to an empty C++ dtor and
3070/// other side-effect free instructions.
Anders Carlssonfcec2f52011-03-20 20:16:43 +00003071static bool cxxDtorIsEmpty(const Function &Fn,
3072 SmallPtrSet<const Function *, 8> &CalledFunctions) {
Anders Carlsson48a44912011-03-20 19:51:13 +00003073 // FIXME: We could eliminate C++ destructors if they're readonly/readnone and
Nick Lewyckyd0781832011-03-21 02:26:01 +00003074 // nounwind, but that doesn't seem worth doing.
Anders Carlsson48a44912011-03-20 19:51:13 +00003075 if (Fn.isDeclaration())
3076 return false;
Anders Carlssonee6bc702011-03-20 17:59:11 +00003077
3078 if (++Fn.begin() != Fn.end())
3079 return false;
3080
3081 const BasicBlock &EntryBlock = Fn.getEntryBlock();
3082 for (BasicBlock::const_iterator I = EntryBlock.begin(), E = EntryBlock.end();
3083 I != E; ++I) {
3084 if (const CallInst *CI = dyn_cast<CallInst>(I)) {
Anders Carlsson4dd420f2011-03-21 14:54:40 +00003085 // Ignore debug intrinsics.
3086 if (isa<DbgInfoIntrinsic>(CI))
3087 continue;
3088
Anders Carlssonee6bc702011-03-20 17:59:11 +00003089 const Function *CalledFn = CI->getCalledFunction();
3090
3091 if (!CalledFn)
3092 return false;
3093
Anders Carlsson1cc80732011-03-22 03:21:01 +00003094 SmallPtrSet<const Function *, 8> NewCalledFunctions(CalledFunctions);
3095
Anders Carlsson48a44912011-03-20 19:51:13 +00003096 // Don't treat recursive functions as empty.
Anders Carlsson1cc80732011-03-22 03:21:01 +00003097 if (!NewCalledFunctions.insert(CalledFn))
Anders Carlsson48a44912011-03-20 19:51:13 +00003098 return false;
3099
Anders Carlsson1cc80732011-03-22 03:21:01 +00003100 if (!cxxDtorIsEmpty(*CalledFn, NewCalledFunctions))
Anders Carlssonee6bc702011-03-20 17:59:11 +00003101 return false;
3102 } else if (isa<ReturnInst>(*I))
Benjamin Kramer487a3962012-02-09 14:26:06 +00003103 return true; // We're done.
3104 else if (I->mayHaveSideEffects())
3105 return false; // Destructor with side effects, bail.
Anders Carlssonee6bc702011-03-20 17:59:11 +00003106 }
3107
3108 return false;
3109}
3110
3111bool GlobalOpt::OptimizeEmptyGlobalCXXDtors(Function *CXAAtExitFn) {
3112 /// Itanium C++ ABI p3.3.5:
3113 ///
3114 /// After constructing a global (or local static) object, that will require
3115 /// destruction on exit, a termination function is registered as follows:
3116 ///
3117 /// extern "C" int __cxa_atexit ( void (*f)(void *), void *p, void *d );
3118 ///
3119 /// This registration, e.g. __cxa_atexit(f,p,d), is intended to cause the
3120 /// call f(p) when DSO d is unloaded, before all such termination calls
3121 /// registered before this one. It returns zero if registration is
Nick Lewyckyd0781832011-03-21 02:26:01 +00003122 /// successful, nonzero on failure.
Anders Carlssonee6bc702011-03-20 17:59:11 +00003123
3124 // This pass will look for calls to __cxa_atexit where the function is trivial
3125 // and remove them.
3126 bool Changed = false;
3127
Chandler Carruthcdf47882014-03-09 03:16:01 +00003128 for (auto I = CXAAtExitFn->user_begin(), E = CXAAtExitFn->user_end();
3129 I != E;) {
Anders Carlsson336fd902011-03-20 20:21:33 +00003130 // We're only interested in calls. Theoretically, we could handle invoke
3131 // instructions as well, but neither llvm-gcc nor clang generate invokes
3132 // to __cxa_atexit.
Anders Carlsson4dd420f2011-03-21 14:54:40 +00003133 CallInst *CI = dyn_cast<CallInst>(*I++);
3134 if (!CI)
Anders Carlsson336fd902011-03-20 20:21:33 +00003135 continue;
3136
Jakub Staszak9525a772012-12-06 21:57:16 +00003137 Function *DtorFn =
Anders Carlsson4dd420f2011-03-21 14:54:40 +00003138 dyn_cast<Function>(CI->getArgOperand(0)->stripPointerCasts());
Anders Carlssonee6bc702011-03-20 17:59:11 +00003139 if (!DtorFn)
3140 continue;
3141
Anders Carlssonfcec2f52011-03-20 20:16:43 +00003142 SmallPtrSet<const Function *, 8> CalledFunctions;
3143 if (!cxxDtorIsEmpty(*DtorFn, CalledFunctions))
Anders Carlssonee6bc702011-03-20 17:59:11 +00003144 continue;
3145
3146 // Just remove the call.
Anders Carlsson4dd420f2011-03-21 14:54:40 +00003147 CI->replaceAllUsesWith(Constant::getNullValue(CI->getType()));
3148 CI->eraseFromParent();
Anders Carlsson48a44912011-03-20 19:51:13 +00003149
Anders Carlssonee6bc702011-03-20 17:59:11 +00003150 ++NumCXXDtorsRemoved;
3151
3152 Changed |= true;
3153 }
3154
3155 return Changed;
3156}
3157
Chris Lattner25db5802004-10-07 04:16:33 +00003158bool GlobalOpt::runOnModule(Module &M) {
3159 bool Changed = false;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00003160
Rafael Espindola93512512014-02-25 17:30:31 +00003161 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
Craig Topperf40110f2014-04-25 05:29:35 +00003162 DL = DLP ? &DLP->getDataLayout() : nullptr;
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}