blob: 7bd0d70198361d47113a779a76f91b2247d23cd9 [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"
David Majnemerdad0a642014-06-27 18:19:56 +000020#include "llvm/ADT/SmallSet.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000021#include "llvm/ADT/SmallVector.h"
22#include "llvm/ADT/Statistic.h"
23#include "llvm/Analysis/ConstantFolding.h"
24#include "llvm/Analysis/MemoryBuiltins.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000025#include "llvm/Analysis/TargetLibraryInfo.h"
Chandler Carruth219b89b2014-03-04 11:01:28 +000026#include "llvm/IR/CallSite.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000027#include "llvm/IR/CallingConv.h"
28#include "llvm/IR/Constants.h"
29#include "llvm/IR/DataLayout.h"
30#include "llvm/IR/DerivedTypes.h"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000031#include "llvm/IR/GetElementPtrTypeIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000032#include "llvm/IR/Instructions.h"
33#include "llvm/IR/IntrinsicInst.h"
34#include "llvm/IR/Module.h"
35#include "llvm/IR/Operator.h"
Chandler Carruth4220e9c2014-03-04 11:17:44 +000036#include "llvm/IR/ValueHandle.h"
Chris Lattner25db5802004-10-07 04:16:33 +000037#include "llvm/Pass.h"
Chris Lattner024f4ab2007-01-30 23:46:24 +000038#include "llvm/Support/Debug.h"
Torok Edwin56d06592009-07-11 20:10:48 +000039#include "llvm/Support/ErrorHandling.h"
Chris Lattner67ca6f632008-04-26 07:40:11 +000040#include "llvm/Support/MathExtras.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000041#include "llvm/Support/raw_ostream.h"
Nico Weber4b2acde2014-05-02 18:35:25 +000042#include "llvm/Transforms/Utils/CtorUtils.h"
Rafael Espindola3d7fc252013-10-21 17:14:55 +000043#include "llvm/Transforms/Utils/GlobalStatus.h"
Rafael Espindola17600e22013-07-25 03:23:25 +000044#include "llvm/Transforms/Utils/ModuleUtils.h"
Chris Lattner25db5802004-10-07 04:16:33 +000045#include <algorithm>
Benjamin Kramer64425fe2014-05-03 15:50:37 +000046#include <deque>
Chris Lattner25db5802004-10-07 04:16:33 +000047using namespace llvm;
48
Chandler Carruth964daaa2014-04-22 02:55:47 +000049#define DEBUG_TYPE "globalopt"
50
Chris Lattner1631bcb2006-12-19 22:09:18 +000051STATISTIC(NumMarked , "Number of globals marked constant");
Rafael Espindolafc355bc2011-01-19 16:32:21 +000052STATISTIC(NumUnnamed , "Number of globals marked unnamed_addr");
Chris Lattner1631bcb2006-12-19 22:09:18 +000053STATISTIC(NumSRA , "Number of aggregate globals broken into scalars");
54STATISTIC(NumHeapSRA , "Number of heap objects SRA'd");
55STATISTIC(NumSubstitute,"Number of globals with initializers stored into them");
56STATISTIC(NumDeleted , "Number of globals deleted");
57STATISTIC(NumFnDeleted , "Number of functions deleted");
58STATISTIC(NumGlobUses , "Number of global uses devirtualized");
Alexey Samsonova1944e62013-10-07 19:03:24 +000059STATISTIC(NumLocalized , "Number of globals localized");
Chris Lattner1631bcb2006-12-19 22:09:18 +000060STATISTIC(NumShrunkToBool , "Number of global vars shrunk to booleans");
61STATISTIC(NumFastCallFns , "Number of functions converted to fastcc");
62STATISTIC(NumCtorsEvaluated, "Number of static ctors evaluated");
Duncan Sands573b3f82008-02-16 20:56:04 +000063STATISTIC(NumNestRemoved , "Number of nest attributes removed");
Duncan Sandsb3f27882009-02-15 09:56:08 +000064STATISTIC(NumAliasesResolved, "Number of global aliases resolved");
65STATISTIC(NumAliasesRemoved, "Number of global aliases eliminated");
Anders Carlssonee6bc702011-03-20 17:59:11 +000066STATISTIC(NumCXXDtorsRemoved, "Number of global C++ destructors removed");
Chris Lattner25db5802004-10-07 04:16:33 +000067
Chris Lattner1631bcb2006-12-19 22:09:18 +000068namespace {
Nick Lewycky02d5f772009-10-25 06:33:48 +000069 struct GlobalOpt : public ModulePass {
Craig Topper3e4c6972014-03-05 09:10:37 +000070 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chandler Carruthb98f63d2015-01-15 10:41:28 +000071 AU.addRequired<TargetLibraryInfoWrapperPass>();
Chris Lattner004e2502004-10-11 05:54:41 +000072 }
Nick Lewyckye7da2d62007-05-06 13:37:16 +000073 static char ID; // Pass identification, replacement for typeid
Owen Anderson6c18d1a2010-10-19 17:21:58 +000074 GlobalOpt() : ModulePass(ID) {
75 initializeGlobalOptPass(*PassRegistry::getPassRegistry());
76 }
Misha Brukmanb1c93172005-04-21 23:48:37 +000077
Craig Topper3e4c6972014-03-05 09:10:37 +000078 bool runOnModule(Module &M) override;
Chris Lattner004e2502004-10-11 05:54:41 +000079
80 private:
Chris Lattner41b6a5a2005-09-26 01:43:45 +000081 bool OptimizeFunctions(Module &M);
82 bool OptimizeGlobalVars(Module &M);
Duncan Sandsed722832009-03-06 10:21:56 +000083 bool OptimizeGlobalAliases(Module &M);
Rafael Espindolafc355bc2011-01-19 16:32:21 +000084 bool ProcessGlobal(GlobalVariable *GV,Module::global_iterator &GVI);
85 bool ProcessInternalGlobal(GlobalVariable *GV,Module::global_iterator &GVI,
Rafael Espindolafc355bc2011-01-19 16:32:21 +000086 const GlobalStatus &GS);
Anders Carlssonee6bc702011-03-20 17:59:11 +000087 bool OptimizeEmptyGlobalCXXDtors(Function *CXAAtExitFn);
Nick Lewyckycf6aae62012-02-12 01:13:18 +000088
Nick Lewyckycf6aae62012-02-12 01:13:18 +000089 TargetLibraryInfo *TLI;
David Majnemer1b3b70e2014-10-08 07:23:31 +000090 SmallSet<const Comdat *, 8> NotDiscardableComdats;
Chris Lattner25db5802004-10-07 04:16:33 +000091 };
Alexander Kornienkof00654e2015-06-23 09:49:53 +000092}
Chris Lattner25db5802004-10-07 04:16:33 +000093
Dan Gohmand78c4002008-05-13 00:00:25 +000094char GlobalOpt::ID = 0;
Chad Rosiere6de63d2011-12-01 21:29:16 +000095INITIALIZE_PASS_BEGIN(GlobalOpt, "globalopt",
96 "Global Variable Optimizer", false, false)
Chandler Carruthb98f63d2015-01-15 10:41:28 +000097INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Chad Rosiere6de63d2011-12-01 21:29:16 +000098INITIALIZE_PASS_END(GlobalOpt, "globalopt",
Owen Andersondf7a4f22010-10-07 22:25:06 +000099 "Global Variable Optimizer", false, false)
Dan Gohmand78c4002008-05-13 00:00:25 +0000100
Chris Lattner25db5802004-10-07 04:16:33 +0000101ModulePass *llvm::createGlobalOptimizerPass() { return new GlobalOpt(); }
102
James Molloyea31ad32015-11-13 11:05:07 +0000103/// Is this global variable possibly used by a leak checker as a root? If so,
104/// we might not really want to eliminate the stores to it.
Nick Lewyckyfaa9c3b02012-07-24 07:21:08 +0000105static bool isLeakCheckerRoot(GlobalVariable *GV) {
106 // A global variable is a root if it is a pointer, or could plausibly contain
107 // a pointer. There are two challenges; one is that we could have a struct
108 // the has an inner member which is a pointer. We recurse through the type to
109 // detect these (up to a point). The other is that we may actually be a union
110 // of a pointer and another type, and so our LLVM type is an integer which
111 // gets converted into a pointer, or our type is an [i8 x #] with a pointer
112 // potentially contained here.
113
114 if (GV->hasPrivateLinkage())
115 return false;
116
117 SmallVector<Type *, 4> Types;
118 Types.push_back(cast<PointerType>(GV->getType())->getElementType());
119
120 unsigned Limit = 20;
121 do {
122 Type *Ty = Types.pop_back_val();
123 switch (Ty->getTypeID()) {
124 default: break;
125 case Type::PointerTyID: return true;
126 case Type::ArrayTyID:
127 case Type::VectorTyID: {
128 SequentialType *STy = cast<SequentialType>(Ty);
129 Types.push_back(STy->getElementType());
130 break;
131 }
132 case Type::StructTyID: {
133 StructType *STy = cast<StructType>(Ty);
134 if (STy->isOpaque()) return true;
135 for (StructType::element_iterator I = STy->element_begin(),
136 E = STy->element_end(); I != E; ++I) {
137 Type *InnerTy = *I;
138 if (isa<PointerType>(InnerTy)) return true;
139 if (isa<CompositeType>(InnerTy))
140 Types.push_back(InnerTy);
141 }
142 break;
143 }
144 }
145 if (--Limit == 0) return true;
146 } while (!Types.empty());
147 return false;
148}
149
150/// Given a value that is stored to a global but never read, determine whether
151/// it's safe to remove the store and the chain of computation that feeds the
152/// store.
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000153static bool IsSafeComputationToRemove(Value *V, const TargetLibraryInfo *TLI) {
Nick Lewyckyfaa9c3b02012-07-24 07:21:08 +0000154 do {
155 if (isa<Constant>(V))
156 return true;
157 if (!V->hasOneUse())
158 return false;
Nick Lewycky7d0f1102012-07-25 21:19:40 +0000159 if (isa<LoadInst>(V) || isa<InvokeInst>(V) || isa<Argument>(V) ||
160 isa<GlobalValue>(V))
Nick Lewyckyfaa9c3b02012-07-24 07:21:08 +0000161 return false;
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000162 if (isAllocationFn(V, TLI))
Nick Lewyckyfaa9c3b02012-07-24 07:21:08 +0000163 return true;
164
165 Instruction *I = cast<Instruction>(V);
166 if (I->mayHaveSideEffects())
167 return false;
168 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
169 if (!GEP->hasAllConstantIndices())
170 return false;
171 } else if (I->getNumOperands() != 1) {
172 return false;
173 }
174
175 V = I->getOperand(0);
176 } while (1);
177}
178
James Molloyea31ad32015-11-13 11:05:07 +0000179/// This GV is a pointer root. Loop over all users of the global and clean up
180/// any that obviously don't assign the global a value that isn't dynamically
181/// allocated.
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
James Molloyea31ad32015-11-13 11:05:07 +0000265/// We just marked GV constant. Loop over all users of the global, cleaning up
266/// the obvious ones. This is largely just a quick scan over the use list to
267/// clean up the easy and obvious cruft. This returns true if it made a change.
Nick Lewyckycf6aae62012-02-12 01:13:18 +0000268static bool CleanupConstantGlobalUsers(Value *V, Constant *Init,
Mehdi Amini46a43552015-03-04 18:43:29 +0000269 const DataLayout &DL,
Rafael Espindolaaeff8a92014-02-24 23:12:18 +0000270 TargetLibraryInfo *TLI) {
Chris Lattnercb9f1522004-10-10 16:43:46 +0000271 bool Changed = false;
Hal Finkelf59fd7d2013-12-12 20:45:24 +0000272 // Note that we need to use a weak value handle for the worklist items. When
273 // we delete a constant array, we may also be holding pointer to one of its
274 // elements (or an element of one of its elements if we're dealing with an
275 // array of arrays) in the worklist.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000276 SmallVector<WeakVH, 8> WorkList(V->user_begin(), V->user_end());
Bill Wendling88d06c32013-04-02 08:16:45 +0000277 while (!WorkList.empty()) {
Hal Finkelf59fd7d2013-12-12 20:45:24 +0000278 Value *UV = WorkList.pop_back_val();
279 if (!UV)
280 continue;
281
282 User *U = cast<User>(UV);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000283
Chris Lattner25db5802004-10-07 04:16:33 +0000284 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
Chris Lattner7561ca12005-02-27 18:58:52 +0000285 if (Init) {
286 // Replace the load with the initializer.
287 LI->replaceAllUsesWith(Init);
288 LI->eraseFromParent();
289 Changed = true;
290 }
Chris Lattner25db5802004-10-07 04:16:33 +0000291 } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
292 // Store must be unreachable or storing Init into the global.
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000293 SI->eraseFromParent();
Chris Lattnercb9f1522004-10-10 16:43:46 +0000294 Changed = true;
Chris Lattner25db5802004-10-07 04:16:33 +0000295 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
296 if (CE->getOpcode() == Instruction::GetElementPtr) {
Craig Topperf40110f2014-04-25 05:29:35 +0000297 Constant *SubInit = nullptr;
Chris Lattner46d9ff082005-09-26 07:34:35 +0000298 if (Init)
Dan Gohmane525d9d2009-10-05 16:36:26 +0000299 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000300 Changed |= CleanupConstantGlobalUsers(CE, SubInit, DL, TLI);
Matt Arsenault461c8e02014-01-02 20:01:43 +0000301 } else if ((CE->getOpcode() == Instruction::BitCast &&
302 CE->getType()->isPointerTy()) ||
303 CE->getOpcode() == Instruction::AddrSpaceCast) {
Chris Lattner7561ca12005-02-27 18:58:52 +0000304 // Pointer cast, delete any stores and memsets to the global.
Craig Topperf40110f2014-04-25 05:29:35 +0000305 Changed |= CleanupConstantGlobalUsers(CE, nullptr, DL, TLI);
Chris Lattner7561ca12005-02-27 18:58:52 +0000306 }
307
308 if (CE->use_empty()) {
309 CE->destroyConstant();
310 Changed = true;
Chris Lattner25db5802004-10-07 04:16:33 +0000311 }
312 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
Chris Lattnerf9c0fd72007-11-09 17:33:02 +0000313 // Do not transform "gepinst (gep constexpr (GV))" here, because forming
314 // "gepconstexpr (gep constexpr (GV))" will cause the two gep's to fold
315 // and will invalidate our notion of what Init is.
Craig Topperf40110f2014-04-25 05:29:35 +0000316 Constant *SubInit = nullptr;
Chris Lattnerf9c0fd72007-11-09 17:33:02 +0000317 if (!isa<ConstantExpr>(GEP->getOperand(0))) {
Mehdi Amini46a43552015-03-04 18:43:29 +0000318 ConstantExpr *CE = dyn_cast_or_null<ConstantExpr>(
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000319 ConstantFoldInstruction(GEP, DL, TLI));
Chris Lattnerf9c0fd72007-11-09 17:33:02 +0000320 if (Init && CE && CE->getOpcode() == Instruction::GetElementPtr)
Dan Gohmane525d9d2009-10-05 16:36:26 +0000321 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
Benjamin Krameraa9e4a52012-03-28 14:50:09 +0000322
323 // If the initializer is an all-null value and we have an inbounds GEP,
324 // we already know what the result of any load from that GEP is.
325 // TODO: Handle splats.
326 if (Init && isa<ConstantAggregateZero>(Init) && GEP->isInBounds())
327 SubInit = Constant::getNullValue(GEP->getType()->getElementType());
Chris Lattnerf9c0fd72007-11-09 17:33:02 +0000328 }
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000329 Changed |= CleanupConstantGlobalUsers(GEP, SubInit, DL, TLI);
Chris Lattnera0e769c2004-10-10 16:47:33 +0000330
Chris Lattnercb9f1522004-10-10 16:43:46 +0000331 if (GEP->use_empty()) {
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000332 GEP->eraseFromParent();
Chris Lattnercb9f1522004-10-10 16:43:46 +0000333 Changed = true;
334 }
Chris Lattner7561ca12005-02-27 18:58:52 +0000335 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U)) { // memset/cpy/mv
336 if (MI->getRawDest() == V) {
337 MI->eraseFromParent();
338 Changed = true;
339 }
340
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000341 } else if (Constant *C = dyn_cast<Constant>(U)) {
342 // If we have a chain of dead constantexprs or other things dangling from
343 // us, and if they are all dead, nuke them without remorse.
Rafael Espindola27797ba2013-10-17 18:06:32 +0000344 if (isSafeToDestroyConstant(C)) {
Devang Pateld926aaa2009-03-06 01:37:41 +0000345 C->destroyConstant();
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000346 CleanupConstantGlobalUsers(V, Init, DL, TLI);
Chris Lattnercb9f1522004-10-10 16:43:46 +0000347 return true;
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000348 }
Chris Lattner25db5802004-10-07 04:16:33 +0000349 }
350 }
Chris Lattnercb9f1522004-10-10 16:43:46 +0000351 return Changed;
Chris Lattner25db5802004-10-07 04:16:33 +0000352}
353
James Molloyea31ad32015-11-13 11:05:07 +0000354/// Return true if the specified instruction is a safe user of a derived
355/// expression from a global that we want to SROA.
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000356static bool isSafeSROAElementUse(Value *V) {
357 // We might have a dead and dangling constant hanging off of here.
358 if (Constant *C = dyn_cast<Constant>(V))
Rafael Espindola27797ba2013-10-17 18:06:32 +0000359 return isSafeToDestroyConstant(C);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000360
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000361 Instruction *I = dyn_cast<Instruction>(V);
362 if (!I) return false;
363
364 // Loads are ok.
365 if (isa<LoadInst>(I)) return true;
366
367 // Stores *to* the pointer are ok.
368 if (StoreInst *SI = dyn_cast<StoreInst>(I))
369 return SI->getOperand(0) != V;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000370
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000371 // Otherwise, it must be a GEP.
372 GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I);
Craig Topperf40110f2014-04-25 05:29:35 +0000373 if (!GEPI) return false;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000374
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000375 if (GEPI->getNumOperands() < 3 || !isa<Constant>(GEPI->getOperand(1)) ||
376 !cast<Constant>(GEPI->getOperand(1))->isNullValue())
377 return false;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000378
Chandler Carruthcdf47882014-03-09 03:16:01 +0000379 for (User *U : GEPI->users())
380 if (!isSafeSROAElementUse(U))
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000381 return false;
Chris Lattnerab053722008-01-14 01:31:05 +0000382 return true;
383}
384
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000385
James Molloyea31ad32015-11-13 11:05:07 +0000386/// U is a direct user of the specified global value. Look at it and its uses
387/// and decide whether it is safe to SROA this global.
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000388static bool IsUserOfGlobalSafeForSRA(User *U, GlobalValue *GV) {
389 // The user of the global must be a GEP Inst or a ConstantExpr GEP.
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000390 if (!isa<GetElementPtrInst>(U) &&
391 (!isa<ConstantExpr>(U) ||
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000392 cast<ConstantExpr>(U)->getOpcode() != Instruction::GetElementPtr))
393 return false;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000394
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000395 // Check to see if this ConstantExpr GEP is SRA'able. In particular, we
396 // don't like < 3 operand CE's, and we don't like non-constant integer
397 // indices. This enforces that all uses are 'gep GV, 0, C, ...' for some
398 // value of C.
399 if (U->getNumOperands() < 3 || !isa<Constant>(U->getOperand(1)) ||
400 !cast<Constant>(U->getOperand(1))->isNullValue() ||
401 !isa<ConstantInt>(U->getOperand(2)))
402 return false;
403
404 gep_type_iterator GEPI = gep_type_begin(U), E = gep_type_end(U);
405 ++GEPI; // Skip over the pointer index.
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000406
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000407 // If this is a use of an array allocation, do a bit more checking for sanity.
Chris Lattner229907c2011-07-18 04:54:35 +0000408 if (ArrayType *AT = dyn_cast<ArrayType>(*GEPI)) {
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000409 uint64_t NumElements = AT->getNumElements();
410 ConstantInt *Idx = cast<ConstantInt>(U->getOperand(2));
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000411
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000412 // Check to make sure that index falls within the array. If not,
413 // something funny is going on, so we won't do the optimization.
414 //
415 if (Idx->getZExtValue() >= NumElements)
416 return false;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000417
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000418 // We cannot scalar repl this level of the array unless any array
419 // sub-indices are in-range constants. In particular, consider:
420 // A[0][i]. We cannot know that the user isn't doing invalid things like
421 // allowing i to index an out-of-range subscript that accesses A[1].
422 //
423 // Scalar replacing *just* the outer index of the array is probably not
424 // going to be a win anyway, so just give up.
425 for (++GEPI; // Skip array index.
Dan Gohman82ac81b2009-08-18 14:58:19 +0000426 GEPI != E;
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000427 ++GEPI) {
428 uint64_t NumElements;
Chris Lattner229907c2011-07-18 04:54:35 +0000429 if (ArrayType *SubArrayTy = dyn_cast<ArrayType>(*GEPI))
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000430 NumElements = SubArrayTy->getNumElements();
Chris Lattner229907c2011-07-18 04:54:35 +0000431 else if (VectorType *SubVectorTy = dyn_cast<VectorType>(*GEPI))
Dan Gohman82ac81b2009-08-18 14:58:19 +0000432 NumElements = SubVectorTy->getNumElements();
433 else {
Duncan Sands19d0b472010-02-16 11:11:14 +0000434 assert((*GEPI)->isStructTy() &&
Dan Gohman82ac81b2009-08-18 14:58:19 +0000435 "Indexed GEP type is not array, vector, or struct!");
436 continue;
437 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000438
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000439 ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPI.getOperand());
440 if (!IdxVal || IdxVal->getZExtValue() >= NumElements)
441 return false;
442 }
443 }
444
Chandler Carruthcdf47882014-03-09 03:16:01 +0000445 for (User *UU : U->users())
446 if (!isSafeSROAElementUse(UU))
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000447 return false;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000448
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000449 return true;
450}
451
James Molloyea31ad32015-11-13 11:05:07 +0000452/// Look at all uses of the global and decide whether it is safe for us to
453/// perform this transformation.
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000454static bool GlobalUsersSafeToSRA(GlobalValue *GV) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000455 for (User *U : GV->users())
456 if (!IsUserOfGlobalSafeForSRA(U, GV))
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000457 return false;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000458
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000459 return true;
460}
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000461
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000462
James Molloyea31ad32015-11-13 11:05:07 +0000463/// Perform scalar replacement of aggregates on the specified global variable.
464/// This opens the door for other optimizations by exposing the behavior of the
465/// program in a more fine-grained way. We have determined that this
466/// transformation is safe already. We return the first global variable we
Chris Lattnerabab0712004-10-08 17:32:09 +0000467/// insert so that the caller can reprocess it.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000468static GlobalVariable *SRAGlobal(GlobalVariable *GV, const DataLayout &DL) {
Chris Lattnerab053722008-01-14 01:31:05 +0000469 // Make sure this global only has simple uses that we can SRA.
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000470 if (!GlobalUsersSafeToSRA(GV))
Craig Topperf40110f2014-04-25 05:29:35 +0000471 return nullptr;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000472
Rafael Espindola6de96a12009-01-15 20:18:42 +0000473 assert(GV->hasLocalLinkage() && !GV->isConstant());
Chris Lattnerabab0712004-10-08 17:32:09 +0000474 Constant *Init = GV->getInitializer();
Chris Lattner229907c2011-07-18 04:54:35 +0000475 Type *Ty = Init->getType();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000476
Chris Lattnerabab0712004-10-08 17:32:09 +0000477 std::vector<GlobalVariable*> NewGlobals;
478 Module::GlobalListType &Globals = GV->getParent()->getGlobalList();
479
Chris Lattner67ca6f632008-04-26 07:40:11 +0000480 // Get the alignment of the global, either explicit or target-specific.
481 unsigned StartAlignment = GV->getAlignment();
482 if (StartAlignment == 0)
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000483 StartAlignment = DL.getABITypeAlignment(GV->getType());
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000484
Chris Lattner229907c2011-07-18 04:54:35 +0000485 if (StructType *STy = dyn_cast<StructType>(Ty)) {
Chris Lattnerabab0712004-10-08 17:32:09 +0000486 NewGlobals.reserve(STy->getNumElements());
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000487 const StructLayout &Layout = *DL.getStructLayout(STy);
Chris Lattnerabab0712004-10-08 17:32:09 +0000488 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
Chris Lattner67058832012-01-25 06:48:06 +0000489 Constant *In = Init->getAggregateElement(i);
Chris Lattnerabab0712004-10-08 17:32:09 +0000490 assert(In && "Couldn't get element of initializer?");
Chris Lattner46b5c642009-11-06 04:27:31 +0000491 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(i), false,
Chris Lattnerabab0712004-10-08 17:32:09 +0000492 GlobalVariable::InternalLinkage,
Daniel Dunbar132f7832009-07-30 17:37:43 +0000493 In, GV->getName()+"."+Twine(i),
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000494 GV->getThreadLocalMode(),
Owen Anderson5948fdf2009-07-08 01:26:06 +0000495 GV->getType()->getAddressSpace());
Oliver Stannardc1103392015-11-09 16:47:16 +0000496 NGV->setExternallyInitialized(GV->isExternallyInitialized());
Duncan P. N. Exon Smith17323402015-10-13 17:51:03 +0000497 Globals.insert(GV->getIterator(), NGV);
Chris Lattnerabab0712004-10-08 17:32:09 +0000498 NewGlobals.push_back(NGV);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000499
Chris Lattner67ca6f632008-04-26 07:40:11 +0000500 // Calculate the known alignment of the field. If the original aggregate
501 // had 256 byte alignment for example, something might depend on that:
502 // propagate info to each field.
503 uint64_t FieldOffset = Layout.getElementOffset(i);
504 unsigned NewAlign = (unsigned)MinAlign(StartAlignment, FieldOffset);
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000505 if (NewAlign > DL.getABITypeAlignment(STy->getElementType(i)))
Chris Lattner67ca6f632008-04-26 07:40:11 +0000506 NGV->setAlignment(NewAlign);
Chris Lattnerabab0712004-10-08 17:32:09 +0000507 }
Chris Lattner229907c2011-07-18 04:54:35 +0000508 } else if (SequentialType *STy = dyn_cast<SequentialType>(Ty)) {
Chris Lattnerabab0712004-10-08 17:32:09 +0000509 unsigned NumElements = 0;
Chris Lattner229907c2011-07-18 04:54:35 +0000510 if (ArrayType *ATy = dyn_cast<ArrayType>(STy))
Chris Lattnerabab0712004-10-08 17:32:09 +0000511 NumElements = ATy->getNumElements();
Chris Lattnerabab0712004-10-08 17:32:09 +0000512 else
Chris Lattner67ca6f632008-04-26 07:40:11 +0000513 NumElements = cast<VectorType>(STy)->getNumElements();
Chris Lattnerabab0712004-10-08 17:32:09 +0000514
Chris Lattner25169ca2005-02-23 16:53:04 +0000515 if (NumElements > 16 && GV->hasNUsesOrMore(16))
Craig Topperf40110f2014-04-25 05:29:35 +0000516 return nullptr; // It's not worth it.
Chris Lattnerabab0712004-10-08 17:32:09 +0000517 NewGlobals.reserve(NumElements);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000518
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000519 uint64_t EltSize = DL.getTypeAllocSize(STy->getElementType());
520 unsigned EltAlign = DL.getABITypeAlignment(STy->getElementType());
Chris Lattnerabab0712004-10-08 17:32:09 +0000521 for (unsigned i = 0, e = NumElements; i != e; ++i) {
Chris Lattner67058832012-01-25 06:48:06 +0000522 Constant *In = Init->getAggregateElement(i);
Chris Lattnerabab0712004-10-08 17:32:09 +0000523 assert(In && "Couldn't get element of initializer?");
524
Chris Lattner46b5c642009-11-06 04:27:31 +0000525 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(), false,
Chris Lattnerabab0712004-10-08 17:32:09 +0000526 GlobalVariable::InternalLinkage,
Daniel Dunbar132f7832009-07-30 17:37:43 +0000527 In, GV->getName()+"."+Twine(i),
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000528 GV->getThreadLocalMode(),
Owen Andersonb17f3292009-07-08 19:03:57 +0000529 GV->getType()->getAddressSpace());
Oliver Stannardc1103392015-11-09 16:47:16 +0000530 NGV->setExternallyInitialized(GV->isExternallyInitialized());
Duncan P. N. Exon Smith17323402015-10-13 17:51:03 +0000531 Globals.insert(GV->getIterator(), NGV);
Chris Lattnerabab0712004-10-08 17:32:09 +0000532 NewGlobals.push_back(NGV);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000533
Chris Lattner67ca6f632008-04-26 07:40:11 +0000534 // Calculate the known alignment of the field. If the original aggregate
535 // had 256 byte alignment for example, something might depend on that:
536 // propagate info to each field.
537 unsigned NewAlign = (unsigned)MinAlign(StartAlignment, EltSize*i);
538 if (NewAlign > EltAlign)
539 NGV->setAlignment(NewAlign);
Chris Lattnerabab0712004-10-08 17:32:09 +0000540 }
541 }
542
543 if (NewGlobals.empty())
Craig Topperf40110f2014-04-25 05:29:35 +0000544 return nullptr;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000545
James Molloyef607a22015-10-28 14:30:53 +0000546 DEBUG(dbgs() << "PERFORMING GLOBAL SRA ON: " << *GV << "\n");
Chris Lattner004e2502004-10-11 05:54:41 +0000547
Chris Lattner46b5c642009-11-06 04:27:31 +0000548 Constant *NullInt =Constant::getNullValue(Type::getInt32Ty(GV->getContext()));
Chris Lattnerabab0712004-10-08 17:32:09 +0000549
550 // Loop over all of the uses of the global, replacing the constantexpr geps,
551 // with smaller constantexpr geps or direct references.
552 while (!GV->use_empty()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000553 User *GEP = GV->user_back();
Chris Lattner004e2502004-10-11 05:54:41 +0000554 assert(((isa<ConstantExpr>(GEP) &&
555 cast<ConstantExpr>(GEP)->getOpcode()==Instruction::GetElementPtr)||
556 isa<GetElementPtrInst>(GEP)) && "NonGEP CE's are not SRAable!");
Misha Brukmanb1c93172005-04-21 23:48:37 +0000557
Chris Lattnerabab0712004-10-08 17:32:09 +0000558 // Ignore the 1th operand, which has to be zero or else the program is quite
559 // broken (undefined). Get the 2nd operand, which is the structure or array
560 // index.
Reid Spencere0fc4df2006-10-20 07:07:24 +0000561 unsigned Val = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
Chris Lattnerabab0712004-10-08 17:32:09 +0000562 if (Val >= NewGlobals.size()) Val = 0; // Out of bound array access.
563
Chris Lattner004e2502004-10-11 05:54:41 +0000564 Value *NewPtr = NewGlobals[Val];
David Blaikied9d900c2015-05-07 17:28:58 +0000565 Type *NewTy = NewGlobals[Val]->getValueType();
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));
David Blaikie4a2e73b2015-04-02 18:55:32 +0000574 NewPtr =
575 ConstantExpr::getGetElementPtr(NewTy, cast<Constant>(NewPtr), Idxs);
Chris Lattner004e2502004-10-11 05:54:41 +0000576 } else {
577 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(GEP);
Chris Lattner927653f2007-01-31 19:59:55 +0000578 SmallVector<Value*, 8> Idxs;
Chris Lattner004e2502004-10-11 05:54:41 +0000579 Idxs.push_back(NullInt);
580 for (unsigned i = 3, e = GEPI->getNumOperands(); i != e; ++i)
581 Idxs.push_back(GEPI->getOperand(i));
David Blaikie741c8f82015-03-14 01:53:18 +0000582 NewPtr = GetElementPtrInst::Create(
David Blaikied9d900c2015-05-07 17:28:58 +0000583 NewTy, NewPtr, Idxs, GEPI->getName() + "." + Twine(Val), GEPI);
Chris Lattner004e2502004-10-11 05:54:41 +0000584 }
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +0000585 }
Chris Lattner004e2502004-10-11 05:54:41 +0000586 GEP->replaceAllUsesWith(NewPtr);
587
588 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(GEP))
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000589 GEPI->eraseFromParent();
Chris Lattner004e2502004-10-11 05:54:41 +0000590 else
591 cast<ConstantExpr>(GEP)->destroyConstant();
Chris Lattnerabab0712004-10-08 17:32:09 +0000592 }
593
Chris Lattner73ad73e2004-10-08 20:25:55 +0000594 // Delete the old global, now that it is dead.
595 Globals.erase(GV);
Chris Lattnerabab0712004-10-08 17:32:09 +0000596 ++NumSRA;
Chris Lattner004e2502004-10-11 05:54:41 +0000597
598 // Loop over the new globals array deleting any globals that are obviously
599 // dead. This can arise due to scalarization of a structure or an array that
600 // has elements that are dead.
601 unsigned FirstGlobal = 0;
602 for (unsigned i = 0, e = NewGlobals.size(); i != e; ++i)
603 if (NewGlobals[i]->use_empty()) {
604 Globals.erase(NewGlobals[i]);
605 if (FirstGlobal == i) ++FirstGlobal;
606 }
607
Craig Topperf40110f2014-04-25 05:29:35 +0000608 return FirstGlobal != NewGlobals.size() ? NewGlobals[FirstGlobal] : nullptr;
Chris Lattnerabab0712004-10-08 17:32:09 +0000609}
610
James Molloyea31ad32015-11-13 11:05:07 +0000611/// Return true if all users of the specified value will trap if the value is
612/// dynamically null. PHIs keeps track of any phi nodes we've seen to avoid
613/// reprocessing them.
Gabor Greif67972872010-04-06 19:24:18 +0000614static bool AllUsesOfValueWillTrapIfNull(const Value *V,
Craig Topper71b7b682014-08-21 05:55:13 +0000615 SmallPtrSetImpl<const PHINode*> &PHIs) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000616 for (const User *U : V->users())
Gabor Greif08355d62010-04-06 19:14:05 +0000617 if (isa<LoadInst>(U)) {
Chris Lattner09a52722004-10-09 21:48:45 +0000618 // Will trap.
Gabor Greif67972872010-04-06 19:24:18 +0000619 } else if (const StoreInst *SI = dyn_cast<StoreInst>(U)) {
Chris Lattner09a52722004-10-09 21:48:45 +0000620 if (SI->getOperand(0) == V) {
Gabor Greif08355d62010-04-06 19:14:05 +0000621 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner09a52722004-10-09 21:48:45 +0000622 return false; // Storing the value.
623 }
Gabor Greif67972872010-04-06 19:24:18 +0000624 } else if (const CallInst *CI = dyn_cast<CallInst>(U)) {
Gabor Greiffebf6ab2010-03-20 21:00:25 +0000625 if (CI->getCalledValue() != V) {
Gabor Greif08355d62010-04-06 19:14:05 +0000626 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner09a52722004-10-09 21:48:45 +0000627 return false; // Not calling the ptr
628 }
Gabor Greif67972872010-04-06 19:24:18 +0000629 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(U)) {
Gabor Greiffebf6ab2010-03-20 21:00:25 +0000630 if (II->getCalledValue() != V) {
Gabor Greif08355d62010-04-06 19:14:05 +0000631 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner09a52722004-10-09 21:48:45 +0000632 return false; // Not calling the ptr
633 }
Gabor Greif67972872010-04-06 19:24:18 +0000634 } else if (const BitCastInst *CI = dyn_cast<BitCastInst>(U)) {
Chris Lattner2d2892e2007-09-13 16:30:19 +0000635 if (!AllUsesOfValueWillTrapIfNull(CI, PHIs)) return false;
Gabor Greif67972872010-04-06 19:24:18 +0000636 } else if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
Chris Lattner2d2892e2007-09-13 16:30:19 +0000637 if (!AllUsesOfValueWillTrapIfNull(GEPI, PHIs)) return false;
Gabor Greif67972872010-04-06 19:24:18 +0000638 } else if (const PHINode *PN = dyn_cast<PHINode>(U)) {
Chris Lattner2d2892e2007-09-13 16:30:19 +0000639 // If we've already seen this phi node, ignore it, it has already been
640 // checked.
David Blaikie70573dc2014-11-19 07:49:26 +0000641 if (PHIs.insert(PN).second && !AllUsesOfValueWillTrapIfNull(PN, PHIs))
Jakob Stoklund Olesene27dc722010-01-29 23:54:14 +0000642 return false;
Gabor Greif08355d62010-04-06 19:14:05 +0000643 } else if (isa<ICmpInst>(U) &&
Chandler Carruthcdf47882014-03-09 03:16:01 +0000644 isa<ConstantPointerNull>(U->getOperand(1))) {
Nick Lewycky614fb942010-02-25 06:39:10 +0000645 // Ignore icmp X, null
Chris Lattner09a52722004-10-09 21:48:45 +0000646 } else {
Gabor Greif08355d62010-04-06 19:14:05 +0000647 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner09a52722004-10-09 21:48:45 +0000648 return false;
649 }
Chandler Carruthcdf47882014-03-09 03:16:01 +0000650
Chris Lattner09a52722004-10-09 21:48:45 +0000651 return true;
652}
653
James Molloyea31ad32015-11-13 11:05:07 +0000654/// Return true if all uses of any loads from GV will trap if the loaded value
655/// is null. Note that this also permits comparisons of the loaded value
656/// against null, as a special case.
Gabor Greif67972872010-04-06 19:24:18 +0000657static bool AllUsesOfLoadedValueWillTrapIfNull(const GlobalVariable *GV) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000658 for (const User *U : GV->users())
Gabor Greif67972872010-04-06 19:24:18 +0000659 if (const LoadInst *LI = dyn_cast<LoadInst>(U)) {
660 SmallPtrSet<const PHINode*, 8> PHIs;
Chris Lattner2d2892e2007-09-13 16:30:19 +0000661 if (!AllUsesOfValueWillTrapIfNull(LI, PHIs))
Chris Lattner09a52722004-10-09 21:48:45 +0000662 return false;
Gabor Greif08355d62010-04-06 19:14:05 +0000663 } else if (isa<StoreInst>(U)) {
Chris Lattner09a52722004-10-09 21:48:45 +0000664 // Ignore stores to the global.
665 } else {
666 // We don't know or understand this user, bail out.
Gabor Greif08355d62010-04-06 19:14:05 +0000667 //cerr << "UNKNOWN USER OF GLOBAL!: " << *U;
Chris Lattner09a52722004-10-09 21:48:45 +0000668 return false;
669 }
Chris Lattner09a52722004-10-09 21:48:45 +0000670 return true;
671}
672
Chris Lattner46b5c642009-11-06 04:27:31 +0000673static bool OptimizeAwayTrappingUsesOfValue(Value *V, Constant *NewV) {
Chris Lattnere42eb312004-10-10 23:14:11 +0000674 bool Changed = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000675 for (auto UI = V->user_begin(), E = V->user_end(); UI != E; ) {
Chris Lattnere42eb312004-10-10 23:14:11 +0000676 Instruction *I = cast<Instruction>(*UI++);
677 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
678 LI->setOperand(0, NewV);
679 Changed = true;
680 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
681 if (SI->getOperand(1) == V) {
682 SI->setOperand(1, NewV);
683 Changed = true;
684 }
685 } else if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
Gabor Greif04397892010-04-06 18:45:08 +0000686 CallSite CS(I);
687 if (CS.getCalledValue() == V) {
Chris Lattnere42eb312004-10-10 23:14:11 +0000688 // Calling through the pointer! Turn into a direct call, but be careful
689 // that the pointer is not also being passed as an argument.
Gabor Greif04397892010-04-06 18:45:08 +0000690 CS.setCalledFunction(NewV);
Chris Lattnere42eb312004-10-10 23:14:11 +0000691 Changed = true;
692 bool PassedAsArg = false;
Gabor Greif04397892010-04-06 18:45:08 +0000693 for (unsigned i = 0, e = CS.arg_size(); i != e; ++i)
694 if (CS.getArgument(i) == V) {
Chris Lattnere42eb312004-10-10 23:14:11 +0000695 PassedAsArg = true;
Gabor Greif04397892010-04-06 18:45:08 +0000696 CS.setArgument(i, NewV);
Chris Lattnere42eb312004-10-10 23:14:11 +0000697 }
698
699 if (PassedAsArg) {
700 // Being passed as an argument also. Be careful to not invalidate UI!
Chandler Carruthcdf47882014-03-09 03:16:01 +0000701 UI = V->user_begin();
Chris Lattnere42eb312004-10-10 23:14:11 +0000702 }
703 }
704 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
705 Changed |= OptimizeAwayTrappingUsesOfValue(CI,
Owen Anderson487375e2009-07-29 18:55:55 +0000706 ConstantExpr::getCast(CI->getOpcode(),
Chris Lattner46b5c642009-11-06 04:27:31 +0000707 NewV, CI->getType()));
Chris Lattnere42eb312004-10-10 23:14:11 +0000708 if (CI->use_empty()) {
709 Changed = true;
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000710 CI->eraseFromParent();
Chris Lattnere42eb312004-10-10 23:14:11 +0000711 }
712 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
713 // Should handle GEP here.
Chris Lattnerf96f4a82007-01-31 04:40:53 +0000714 SmallVector<Constant*, 8> Idxs;
715 Idxs.reserve(GEPI->getNumOperands()-1);
Gabor Greif3a9fba52008-05-29 01:59:18 +0000716 for (User::op_iterator i = GEPI->op_begin() + 1, e = GEPI->op_end();
717 i != e; ++i)
718 if (Constant *C = dyn_cast<Constant>(*i))
Chris Lattnerf96f4a82007-01-31 04:40:53 +0000719 Idxs.push_back(C);
Chris Lattnere42eb312004-10-10 23:14:11 +0000720 else
721 break;
Chris Lattnerf96f4a82007-01-31 04:40:53 +0000722 if (Idxs.size() == GEPI->getNumOperands()-1)
David Blaikie4a2e73b2015-04-02 18:55:32 +0000723 Changed |= OptimizeAwayTrappingUsesOfValue(
724 GEPI, ConstantExpr::getGetElementPtr(nullptr, NewV, Idxs));
Chris Lattnere42eb312004-10-10 23:14:11 +0000725 if (GEPI->use_empty()) {
726 Changed = true;
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000727 GEPI->eraseFromParent();
Chris Lattnere42eb312004-10-10 23:14:11 +0000728 }
729 }
730 }
731
732 return Changed;
733}
734
735
James Molloyea31ad32015-11-13 11:05:07 +0000736/// The specified global has only one non-null value stored into it. If there
737/// are uses of the loaded value that would trap if the loaded value is
738/// dynamically null, then we know that they cannot be reachable with a null
739/// optimize away the load.
Nick Lewyckycf6aae62012-02-12 01:13:18 +0000740static bool OptimizeAwayTrappingUsesOfLoads(GlobalVariable *GV, Constant *LV,
Mehdi Amini46a43552015-03-04 18:43:29 +0000741 const DataLayout &DL,
Nick Lewyckycf6aae62012-02-12 01:13:18 +0000742 TargetLibraryInfo *TLI) {
Chris Lattnere42eb312004-10-10 23:14:11 +0000743 bool Changed = false;
744
Chris Lattner2538eb62009-01-14 00:12:58 +0000745 // Keep track of whether we are able to remove all the uses of the global
746 // other than the store that defines it.
747 bool AllNonStoreUsesGone = true;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000748
Chris Lattnere42eb312004-10-10 23:14:11 +0000749 // Replace all uses of loads with uses of uses of the stored value.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000750 for (Value::user_iterator GUI = GV->user_begin(), E = GV->user_end(); GUI != E;){
Chris Lattner2538eb62009-01-14 00:12:58 +0000751 User *GlobalUser = *GUI++;
752 if (LoadInst *LI = dyn_cast<LoadInst>(GlobalUser)) {
Chris Lattner46b5c642009-11-06 04:27:31 +0000753 Changed |= OptimizeAwayTrappingUsesOfValue(LI, LV);
Chris Lattner2538eb62009-01-14 00:12:58 +0000754 // If we were able to delete all uses of the loads
755 if (LI->use_empty()) {
756 LI->eraseFromParent();
757 Changed = true;
758 } else {
759 AllNonStoreUsesGone = false;
760 }
761 } else if (isa<StoreInst>(GlobalUser)) {
762 // Ignore the store that stores "LV" to the global.
763 assert(GlobalUser->getOperand(1) == GV &&
764 "Must be storing *to* the global");
Chris Lattnere42eb312004-10-10 23:14:11 +0000765 } else {
Chris Lattner2538eb62009-01-14 00:12:58 +0000766 AllNonStoreUsesGone = false;
767
768 // If we get here we could have other crazy uses that are transitively
769 // loaded.
770 assert((isa<PHINode>(GlobalUser) || isa<SelectInst>(GlobalUser) ||
Benjamin Kramered843602012-09-28 10:01:27 +0000771 isa<ConstantExpr>(GlobalUser) || isa<CmpInst>(GlobalUser) ||
772 isa<BitCastInst>(GlobalUser) ||
773 isa<GetElementPtrInst>(GlobalUser)) &&
Chris Lattner1a1acc22011-05-22 07:15:13 +0000774 "Only expect load and stores!");
Chris Lattnere42eb312004-10-10 23:14:11 +0000775 }
Chris Lattner2538eb62009-01-14 00:12:58 +0000776 }
Chris Lattnere42eb312004-10-10 23:14:11 +0000777
778 if (Changed) {
James Molloyef607a22015-10-28 14:30:53 +0000779 DEBUG(dbgs() << "OPTIMIZED LOADS FROM STORED ONCE POINTER: " << *GV << "\n");
Chris Lattnere42eb312004-10-10 23:14:11 +0000780 ++NumGlobUses;
781 }
782
Chris Lattnere42eb312004-10-10 23:14:11 +0000783 // If we nuked all of the loads, then none of the stores are needed either,
784 // nor is the global.
Chris Lattner2538eb62009-01-14 00:12:58 +0000785 if (AllNonStoreUsesGone) {
Nick Lewyckyfaa9c3b02012-07-24 07:21:08 +0000786 if (isLeakCheckerRoot(GV)) {
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000787 Changed |= CleanupPointerRootUsers(GV, TLI);
Nick Lewyckyfaa9c3b02012-07-24 07:21:08 +0000788 } else {
789 Changed = true;
Craig Topperf40110f2014-04-25 05:29:35 +0000790 CleanupConstantGlobalUsers(GV, nullptr, DL, TLI);
Nick Lewyckyfaa9c3b02012-07-24 07:21:08 +0000791 }
Chris Lattnere42eb312004-10-10 23:14:11 +0000792 if (GV->use_empty()) {
Nick Lewyckyfaa9c3b02012-07-24 07:21:08 +0000793 DEBUG(dbgs() << " *** GLOBAL NOW DEAD!\n");
794 Changed = true;
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000795 GV->eraseFromParent();
Chris Lattnere42eb312004-10-10 23:14:11 +0000796 ++NumDeleted;
797 }
Chris Lattnere42eb312004-10-10 23:14:11 +0000798 }
799 return Changed;
800}
801
James Molloyea31ad32015-11-13 11:05:07 +0000802/// Walk the use list of V, constant folding all of the instructions that are
803/// foldable.
Mehdi Amini46a43552015-03-04 18:43:29 +0000804static void ConstantPropUsersOf(Value *V, const DataLayout &DL,
Rafael Espindolaaeff8a92014-02-24 23:12:18 +0000805 TargetLibraryInfo *TLI) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000806 for (Value::user_iterator UI = V->user_begin(), E = V->user_end(); UI != E; )
Chris Lattner004e2502004-10-11 05:54:41 +0000807 if (Instruction *I = dyn_cast<Instruction>(*UI++))
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000808 if (Constant *NewC = ConstantFoldInstruction(I, DL, TLI)) {
Chris Lattner004e2502004-10-11 05:54:41 +0000809 I->replaceAllUsesWith(NewC);
810
Chris Lattnerd6a44922005-02-01 01:23:31 +0000811 // Advance UI to the next non-I use to avoid invalidating it!
812 // Instructions could multiply use V.
813 while (UI != E && *UI == I)
Chris Lattner004e2502004-10-11 05:54:41 +0000814 ++UI;
Chris Lattnerd6a44922005-02-01 01:23:31 +0000815 I->eraseFromParent();
Chris Lattner004e2502004-10-11 05:54:41 +0000816 }
817}
818
James Molloyea31ad32015-11-13 11:05:07 +0000819/// This function takes the specified global variable, and transforms the
820/// program as if it always contained the result of the specified malloc.
821/// Because it is always the result of the specified malloc, there is no reason
822/// to actually DO the malloc. Instead, turn the malloc into a global, and any
823/// loads of GV as uses of the new global.
Mehdi Amini46a43552015-03-04 18:43:29 +0000824static GlobalVariable *
825OptimizeGlobalAddressOfMalloc(GlobalVariable *GV, CallInst *CI, Type *AllocTy,
826 ConstantInt *NElements, const DataLayout &DL,
827 TargetLibraryInfo *TLI) {
Chris Lattner7939f792010-02-25 22:33:52 +0000828 DEBUG(errs() << "PROMOTING GLOBAL: " << *GV << " CALL = " << *CI << '\n');
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000829
Chris Lattner229907c2011-07-18 04:54:35 +0000830 Type *GlobalType;
Chris Lattner7939f792010-02-25 22:33:52 +0000831 if (NElements->getZExtValue() == 1)
832 GlobalType = AllocTy;
833 else
834 // If we have an array allocation, the global variable is of an array.
835 GlobalType = ArrayType::get(AllocTy, NElements->getZExtValue());
Victor Hernandez5d034492009-09-18 22:35:49 +0000836
837 // Create the new global variable. The contents of the malloc'd memory is
838 // undefined, so initialize with an undef value.
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000839 GlobalVariable *NewGV = new GlobalVariable(*GV->getParent(),
Chris Lattner65d3a0a2010-02-26 23:42:13 +0000840 GlobalType, false,
Chris Lattner7939f792010-02-25 22:33:52 +0000841 GlobalValue::InternalLinkage,
Chris Lattner65d3a0a2010-02-26 23:42:13 +0000842 UndefValue::get(GlobalType),
Victor Hernandez5d034492009-09-18 22:35:49 +0000843 GV->getName()+".body",
844 GV,
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000845 GV->getThreadLocalMode());
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000846
Chris Lattner7939f792010-02-25 22:33:52 +0000847 // If there are bitcast users of the malloc (which is typical, usually we have
848 // a malloc + bitcast) then replace them with uses of the new global. Update
849 // other users to use the global as well.
Craig Topperf40110f2014-04-25 05:29:35 +0000850 BitCastInst *TheBC = nullptr;
Chris Lattner7939f792010-02-25 22:33:52 +0000851 while (!CI->use_empty()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000852 Instruction *User = cast<Instruction>(CI->user_back());
Chris Lattner7939f792010-02-25 22:33:52 +0000853 if (BitCastInst *BCI = dyn_cast<BitCastInst>(User)) {
854 if (BCI->getType() == NewGV->getType()) {
855 BCI->replaceAllUsesWith(NewGV);
856 BCI->eraseFromParent();
857 } else {
858 BCI->setOperand(0, NewGV);
859 }
860 } else {
Craig Topperf40110f2014-04-25 05:29:35 +0000861 if (!TheBC)
Chris Lattner7939f792010-02-25 22:33:52 +0000862 TheBC = new BitCastInst(NewGV, CI->getType(), "newgv", CI);
863 User->replaceUsesOfWith(CI, TheBC);
864 }
865 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000866
Victor Hernandez5d034492009-09-18 22:35:49 +0000867 Constant *RepValue = NewGV;
868 if (NewGV->getType() != GV->getType()->getElementType())
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000869 RepValue = ConstantExpr::getBitCast(RepValue,
Victor Hernandez5d034492009-09-18 22:35:49 +0000870 GV->getType()->getElementType());
871
872 // If there is a comparison against null, we will insert a global bool to
873 // keep track of whether the global was initialized yet or not.
874 GlobalVariable *InitBool =
Chris Lattner46b5c642009-11-06 04:27:31 +0000875 new GlobalVariable(Type::getInt1Ty(GV->getContext()), false,
Victor Hernandez5d034492009-09-18 22:35:49 +0000876 GlobalValue::InternalLinkage,
Chris Lattner46b5c642009-11-06 04:27:31 +0000877 ConstantInt::getFalse(GV->getContext()),
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000878 GV->getName()+".init", GV->getThreadLocalMode());
Victor Hernandez5d034492009-09-18 22:35:49 +0000879 bool InitBoolUsed = false;
880
881 // Loop over all uses of GV, processing them in turn.
Chris Lattner7939f792010-02-25 22:33:52 +0000882 while (!GV->use_empty()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000883 if (StoreInst *SI = dyn_cast<StoreInst>(GV->user_back())) {
Victor Hernandez5d034492009-09-18 22:35:49 +0000884 // The global is initialized when the store to it occurs.
Nick Lewycky52da72b2012-02-05 19:56:38 +0000885 new StoreInst(ConstantInt::getTrue(GV->getContext()), InitBool, false, 0,
886 SI->getOrdering(), SI->getSynchScope(), SI);
Victor Hernandez5d034492009-09-18 22:35:49 +0000887 SI->eraseFromParent();
Chris Lattner7939f792010-02-25 22:33:52 +0000888 continue;
Victor Hernandez5d034492009-09-18 22:35:49 +0000889 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000890
Chandler Carruthcdf47882014-03-09 03:16:01 +0000891 LoadInst *LI = cast<LoadInst>(GV->user_back());
Chris Lattner7939f792010-02-25 22:33:52 +0000892 while (!LI->use_empty()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000893 Use &LoadUse = *LI->use_begin();
894 ICmpInst *ICI = dyn_cast<ICmpInst>(LoadUse.getUser());
895 if (!ICI) {
Chris Lattner7939f792010-02-25 22:33:52 +0000896 LoadUse = RepValue;
897 continue;
898 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000899
Chris Lattner7939f792010-02-25 22:33:52 +0000900 // Replace the cmp X, 0 with a use of the bool value.
Nick Lewycky52da72b2012-02-05 19:56:38 +0000901 // Sink the load to where the compare was, if atomic rules allow us to.
902 Value *LV = new LoadInst(InitBool, InitBool->getName()+".val", false, 0,
903 LI->getOrdering(), LI->getSynchScope(),
904 LI->isUnordered() ? (Instruction*)ICI : LI);
Chris Lattner7939f792010-02-25 22:33:52 +0000905 InitBoolUsed = true;
906 switch (ICI->getPredicate()) {
907 default: llvm_unreachable("Unknown ICmp Predicate!");
908 case ICmpInst::ICMP_ULT:
909 case ICmpInst::ICMP_SLT: // X < null -> always false
910 LV = ConstantInt::getFalse(GV->getContext());
911 break;
912 case ICmpInst::ICMP_ULE:
913 case ICmpInst::ICMP_SLE:
914 case ICmpInst::ICMP_EQ:
915 LV = BinaryOperator::CreateNot(LV, "notinit", ICI);
916 break;
917 case ICmpInst::ICMP_NE:
918 case ICmpInst::ICMP_UGE:
919 case ICmpInst::ICMP_SGE:
920 case ICmpInst::ICMP_UGT:
921 case ICmpInst::ICMP_SGT:
922 break; // no change.
923 }
924 ICI->replaceAllUsesWith(LV);
925 ICI->eraseFromParent();
926 }
927 LI->eraseFromParent();
928 }
Victor Hernandez5d034492009-09-18 22:35:49 +0000929
930 // If the initialization boolean was used, insert it, otherwise delete it.
931 if (!InitBoolUsed) {
932 while (!InitBool->use_empty()) // Delete initializations
Chandler Carruthcdf47882014-03-09 03:16:01 +0000933 cast<StoreInst>(InitBool->user_back())->eraseFromParent();
Victor Hernandez5d034492009-09-18 22:35:49 +0000934 delete InitBool;
935 } else
Duncan P. N. Exon Smith17323402015-10-13 17:51:03 +0000936 GV->getParent()->getGlobalList().insert(GV->getIterator(), InitBool);
Victor Hernandez5d034492009-09-18 22:35:49 +0000937
Chris Lattner7939f792010-02-25 22:33:52 +0000938 // Now the GV is dead, nuke it and the malloc..
Victor Hernandez5d034492009-09-18 22:35:49 +0000939 GV->eraseFromParent();
Victor Hernandez5d034492009-09-18 22:35:49 +0000940 CI->eraseFromParent();
941
942 // To further other optimizations, loop over all users of NewGV and try to
943 // constant prop them. This will promote GEP instructions with constant
944 // indices into GEP constant-exprs, which will allow global-opt to hack on it.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000945 ConstantPropUsersOf(NewGV, DL, TLI);
Victor Hernandez5d034492009-09-18 22:35:49 +0000946 if (RepValue != NewGV)
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000947 ConstantPropUsersOf(RepValue, DL, TLI);
Victor Hernandez5d034492009-09-18 22:35:49 +0000948
949 return NewGV;
950}
951
James Molloyea31ad32015-11-13 11:05:07 +0000952/// Scan the use-list of V checking to make sure that there are no complex uses
953/// of V. We permit simple things like dereferencing the pointer, but not
954/// storing through the address, unless it is to the specified global.
Gabor Greifa21bc0f2010-04-06 18:58:22 +0000955static bool ValueIsOnlyUsedLocallyOrStoredToOneGlobal(const Instruction *V,
956 const GlobalVariable *GV,
Craig Topper71b7b682014-08-21 05:55:13 +0000957 SmallPtrSetImpl<const PHINode*> &PHIs) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000958 for (const User *U : V->users()) {
959 const Instruction *Inst = cast<Instruction>(U);
Gabor Greif08355d62010-04-06 19:14:05 +0000960
Chris Lattnerf0eb5682008-12-15 21:08:54 +0000961 if (isa<LoadInst>(Inst) || isa<CmpInst>(Inst)) {
962 continue; // Fine, ignore.
963 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000964
Gabor Greifa21bc0f2010-04-06 18:58:22 +0000965 if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
Chris Lattnerc0677c02004-12-02 07:11:07 +0000966 if (SI->getOperand(0) == V && SI->getOperand(1) != GV)
967 return false; // Storing the pointer itself... bad.
Chris Lattnerf0eb5682008-12-15 21:08:54 +0000968 continue; // Otherwise, storing through it, or storing into GV... fine.
969 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000970
Chris Lattnerb9801ff2010-04-10 18:19:22 +0000971 // Must index into the array and into the struct.
972 if (isa<GetElementPtrInst>(Inst) && Inst->getNumOperands() >= 3) {
Chris Lattnerf0eb5682008-12-15 21:08:54 +0000973 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(Inst, GV, PHIs))
Chris Lattnerc0677c02004-12-02 07:11:07 +0000974 return false;
Chris Lattnerf0eb5682008-12-15 21:08:54 +0000975 continue;
976 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000977
Gabor Greifa21bc0f2010-04-06 18:58:22 +0000978 if (const PHINode *PN = dyn_cast<PHINode>(Inst)) {
Chris Lattner6eed0e72007-09-13 16:37:20 +0000979 // PHIs are ok if all uses are ok. Don't infinitely recurse through PHI
980 // cycles.
David Blaikie70573dc2014-11-19 07:49:26 +0000981 if (PHIs.insert(PN).second)
Chris Lattner5d13fb532007-09-14 03:41:21 +0000982 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(PN, GV, PHIs))
983 return false;
Chris Lattnerf0eb5682008-12-15 21:08:54 +0000984 continue;
Chris Lattnerc0677c02004-12-02 07:11:07 +0000985 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000986
Gabor Greifa21bc0f2010-04-06 18:58:22 +0000987 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Inst)) {
Chris Lattnerf0eb5682008-12-15 21:08:54 +0000988 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(BCI, GV, PHIs))
989 return false;
990 continue;
991 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000992
Chris Lattnerf0eb5682008-12-15 21:08:54 +0000993 return false;
994 }
Chris Lattnerc0677c02004-12-02 07:11:07 +0000995 return true;
Chris Lattnerc0677c02004-12-02 07:11:07 +0000996}
997
James Molloyea31ad32015-11-13 11:05:07 +0000998/// The Alloc pointer is stored into GV somewhere. Transform all uses of the
999/// allocation into loads from the global and uses of the resultant pointer.
1000/// Further, delete the store into GV. This assumes that these value pass the
Chris Lattner24d3d422006-09-30 23:32:09 +00001001/// 'ValueIsOnlyUsedLocallyOrStoredToOneGlobal' predicate.
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001002static void ReplaceUsesOfMallocWithGlobal(Instruction *Alloc,
Chris Lattner24d3d422006-09-30 23:32:09 +00001003 GlobalVariable *GV) {
1004 while (!Alloc->use_empty()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00001005 Instruction *U = cast<Instruction>(*Alloc->user_begin());
Chris Lattnerba98f892007-09-13 18:00:31 +00001006 Instruction *InsertPt = U;
Chris Lattner24d3d422006-09-30 23:32:09 +00001007 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
1008 // If this is the store of the allocation into the global, remove it.
1009 if (SI->getOperand(1) == GV) {
1010 SI->eraseFromParent();
1011 continue;
1012 }
Chris Lattnerba98f892007-09-13 18:00:31 +00001013 } else if (PHINode *PN = dyn_cast<PHINode>(U)) {
1014 // Insert the load in the corresponding predecessor, not right before the
1015 // PHI.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001016 InsertPt = PN->getIncomingBlock(*Alloc->use_begin())->getTerminator();
Chris Lattner49e3bdc2008-12-15 21:44:34 +00001017 } else if (isa<BitCastInst>(U)) {
1018 // Must be bitcast between the malloc and store to initialize the global.
1019 ReplaceUsesOfMallocWithGlobal(U, GV);
1020 U->eraseFromParent();
1021 continue;
1022 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
1023 // If this is a "GEP bitcast" and the user is a store to the global, then
1024 // just process it as a bitcast.
1025 if (GEPI->hasAllZeroIndices() && GEPI->hasOneUse())
Chandler Carruthcdf47882014-03-09 03:16:01 +00001026 if (StoreInst *SI = dyn_cast<StoreInst>(GEPI->user_back()))
Chris Lattner49e3bdc2008-12-15 21:44:34 +00001027 if (SI->getOperand(1) == GV) {
1028 // Must be bitcast GEP between the malloc and store to initialize
1029 // the global.
1030 ReplaceUsesOfMallocWithGlobal(GEPI, GV);
1031 GEPI->eraseFromParent();
1032 continue;
1033 }
Chris Lattner24d3d422006-09-30 23:32:09 +00001034 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001035
Chris Lattner24d3d422006-09-30 23:32:09 +00001036 // Insert a load from the global, and use it instead of the malloc.
Chris Lattnerba98f892007-09-13 18:00:31 +00001037 Value *NL = new LoadInst(GV, GV->getName()+".val", InsertPt);
Chris Lattner24d3d422006-09-30 23:32:09 +00001038 U->replaceUsesOfWith(Alloc, NL);
1039 }
1040}
1041
James Molloyea31ad32015-11-13 11:05:07 +00001042/// Verify that all uses of V (a load, or a phi of a load) are simple enough to
1043/// perform heap SRA on. This permits GEP's that index through the array and
1044/// struct field, icmps of null, and PHIs.
Gabor Greif5d5db532010-04-01 08:21:08 +00001045static bool LoadUsesSimpleEnoughForHeapSRA(const Value *V,
Craig Topper71b7b682014-08-21 05:55:13 +00001046 SmallPtrSetImpl<const PHINode*> &LoadUsingPHIs,
1047 SmallPtrSetImpl<const PHINode*> &LoadUsingPHIsPerLoad) {
Chris Lattner56b55382008-12-16 21:24:51 +00001048 // We permit two users of the load: setcc comparing against the null
1049 // pointer, and a getelementptr of a specific form.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001050 for (const User *U : V->users()) {
1051 const Instruction *UI = cast<Instruction>(U);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001052
Chris Lattner56b55382008-12-16 21:24:51 +00001053 // Comparison against null is ok.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001054 if (const ICmpInst *ICI = dyn_cast<ICmpInst>(UI)) {
Chris Lattner56b55382008-12-16 21:24:51 +00001055 if (!isa<ConstantPointerNull>(ICI->getOperand(1)))
1056 return false;
1057 continue;
1058 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001059
Chris Lattner56b55382008-12-16 21:24:51 +00001060 // getelementptr is also ok, but only a simple form.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001061 if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(UI)) {
Chris Lattner56b55382008-12-16 21:24:51 +00001062 // Must index into the array and into the struct.
1063 if (GEPI->getNumOperands() < 3)
1064 return false;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001065
Chris Lattner56b55382008-12-16 21:24:51 +00001066 // Otherwise the GEP is ok.
1067 continue;
1068 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001069
Chandler Carruthcdf47882014-03-09 03:16:01 +00001070 if (const PHINode *PN = dyn_cast<PHINode>(UI)) {
David Blaikie70573dc2014-11-19 07:49:26 +00001071 if (!LoadUsingPHIsPerLoad.insert(PN).second)
Evan Cheng83689442009-06-02 00:56:07 +00001072 // This means some phi nodes are dependent on each other.
1073 // Avoid infinite looping!
1074 return false;
David Blaikie70573dc2014-11-19 07:49:26 +00001075 if (!LoadUsingPHIs.insert(PN).second)
Evan Cheng83689442009-06-02 00:56:07 +00001076 // If we have already analyzed this PHI, then it is safe.
Chris Lattner56b55382008-12-16 21:24:51 +00001077 continue;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001078
Chris Lattner222ef4c2008-12-17 05:28:49 +00001079 // Make sure all uses of the PHI are simple enough to transform.
Evan Cheng83689442009-06-02 00:56:07 +00001080 if (!LoadUsesSimpleEnoughForHeapSRA(PN,
1081 LoadUsingPHIs, LoadUsingPHIsPerLoad))
Chris Lattner56b55382008-12-16 21:24:51 +00001082 return false;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001083
Chris Lattner56b55382008-12-16 21:24:51 +00001084 continue;
Chris Lattner24d3d422006-09-30 23:32:09 +00001085 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001086
Chris Lattner56b55382008-12-16 21:24:51 +00001087 // Otherwise we don't know what this is, not ok.
1088 return false;
1089 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001090
Chris Lattner56b55382008-12-16 21:24:51 +00001091 return true;
1092}
1093
1094
James Molloyea31ad32015-11-13 11:05:07 +00001095/// If all users of values loaded from GV are simple enough to perform HeapSRA,
1096/// return true.
Gabor Greif5d5db532010-04-01 08:21:08 +00001097static bool AllGlobalLoadUsesSimpleEnoughForHeapSRA(const GlobalVariable *GV,
Victor Hernandez5d034492009-09-18 22:35:49 +00001098 Instruction *StoredVal) {
Gabor Greif5d5db532010-04-01 08:21:08 +00001099 SmallPtrSet<const PHINode*, 32> LoadUsingPHIs;
1100 SmallPtrSet<const PHINode*, 32> LoadUsingPHIsPerLoad;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001101 for (const User *U : GV->users())
1102 if (const LoadInst *LI = dyn_cast<LoadInst>(U)) {
Evan Cheng83689442009-06-02 00:56:07 +00001103 if (!LoadUsesSimpleEnoughForHeapSRA(LI, LoadUsingPHIs,
1104 LoadUsingPHIsPerLoad))
Chris Lattner56b55382008-12-16 21:24:51 +00001105 return false;
Evan Cheng83689442009-06-02 00:56:07 +00001106 LoadUsingPHIsPerLoad.clear();
1107 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001108
Chris Lattner222ef4c2008-12-17 05:28:49 +00001109 // If we reach here, we know that all uses of the loads and transitive uses
1110 // (through PHI nodes) are simple enough to transform. However, we don't know
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001111 // that all inputs the to the PHI nodes are in the same equivalence sets.
Chris Lattner222ef4c2008-12-17 05:28:49 +00001112 // Check to verify that all operands of the PHIs are either PHIS that can be
1113 // transformed, loads from GV, or MI itself.
Craig Topper46276792014-08-24 23:23:06 +00001114 for (const PHINode *PN : LoadUsingPHIs) {
Chris Lattner222ef4c2008-12-17 05:28:49 +00001115 for (unsigned op = 0, e = PN->getNumIncomingValues(); op != e; ++op) {
1116 Value *InVal = PN->getIncomingValue(op);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001117
Chris Lattner222ef4c2008-12-17 05:28:49 +00001118 // PHI of the stored value itself is ok.
Victor Hernandez5d034492009-09-18 22:35:49 +00001119 if (InVal == StoredVal) continue;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001120
Gabor Greif5d5db532010-04-01 08:21:08 +00001121 if (const PHINode *InPN = dyn_cast<PHINode>(InVal)) {
Chris Lattner222ef4c2008-12-17 05:28:49 +00001122 // One of the PHIs in our set is (optimistically) ok.
1123 if (LoadUsingPHIs.count(InPN))
1124 continue;
1125 return false;
1126 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001127
Chris Lattner222ef4c2008-12-17 05:28:49 +00001128 // Load from GV is ok.
Gabor Greif5d5db532010-04-01 08:21:08 +00001129 if (const LoadInst *LI = dyn_cast<LoadInst>(InVal))
Chris Lattner222ef4c2008-12-17 05:28:49 +00001130 if (LI->getOperand(0) == GV)
1131 continue;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001132
Chris Lattner222ef4c2008-12-17 05:28:49 +00001133 // UNDEF? NULL?
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001134
Chris Lattner222ef4c2008-12-17 05:28:49 +00001135 // Anything else is rejected.
1136 return false;
1137 }
1138 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001139
Chris Lattner24d3d422006-09-30 23:32:09 +00001140 return true;
1141}
1142
Chris Lattner222ef4c2008-12-17 05:28:49 +00001143static Value *GetHeapSROAValue(Value *V, unsigned FieldNo,
1144 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Chris Lattner46b5c642009-11-06 04:27:31 +00001145 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
Chris Lattner222ef4c2008-12-17 05:28:49 +00001146 std::vector<Value*> &FieldVals = InsertedScalarizedValues[V];
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001147
Chris Lattner222ef4c2008-12-17 05:28:49 +00001148 if (FieldNo >= FieldVals.size())
1149 FieldVals.resize(FieldNo+1);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001150
Chris Lattner222ef4c2008-12-17 05:28:49 +00001151 // If we already have this value, just reuse the previously scalarized
1152 // version.
1153 if (Value *FieldVal = FieldVals[FieldNo])
1154 return FieldVal;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001155
Chris Lattner222ef4c2008-12-17 05:28:49 +00001156 // Depending on what instruction this is, we have several cases.
1157 Value *Result;
1158 if (LoadInst *LI = dyn_cast<LoadInst>(V)) {
1159 // This is a scalarized version of the load from the global. Just create
1160 // a new Load of the scalarized global.
1161 Result = new LoadInst(GetHeapSROAValue(LI->getOperand(0), FieldNo,
1162 InsertedScalarizedValues,
Chris Lattner46b5c642009-11-06 04:27:31 +00001163 PHIsToRewrite),
Daniel Dunbar132f7832009-07-30 17:37:43 +00001164 LI->getName()+".f"+Twine(FieldNo), LI);
David Blaikie741c8f82015-03-14 01:53:18 +00001165 } else {
1166 PHINode *PN = cast<PHINode>(V);
Chris Lattner222ef4c2008-12-17 05:28:49 +00001167 // PN's type is pointer to struct. Make a new PHI of pointer to struct
1168 // field.
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001169
Matt Arsenaultfcd74012014-04-23 20:36:10 +00001170 PointerType *PTy = cast<PointerType>(PN->getType());
1171 StructType *ST = cast<StructType>(PTy->getElementType());
1172
1173 unsigned AS = PTy->getAddressSpace();
Jay Foade0938d82011-03-30 11:19:20 +00001174 PHINode *NewPN =
Matt Arsenaultfcd74012014-04-23 20:36:10 +00001175 PHINode::Create(PointerType::get(ST->getElementType(FieldNo), AS),
Jay Foad52131342011-03-30 11:28:46 +00001176 PN->getNumIncomingValues(),
Daniel Dunbar132f7832009-07-30 17:37:43 +00001177 PN->getName()+".f"+Twine(FieldNo), PN);
Jay Foade0938d82011-03-30 11:19:20 +00001178 Result = NewPN;
Chris Lattner222ef4c2008-12-17 05:28:49 +00001179 PHIsToRewrite.push_back(std::make_pair(PN, FieldNo));
Chris Lattner222ef4c2008-12-17 05:28:49 +00001180 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001181
Chris Lattner222ef4c2008-12-17 05:28:49 +00001182 return FieldVals[FieldNo] = Result;
Chris Lattnerba98f892007-09-13 18:00:31 +00001183}
1184
James Molloyea31ad32015-11-13 11:05:07 +00001185/// Given a load instruction and a value derived from the load, rewrite the
1186/// derived value to use the HeapSRoA'd load.
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001187static void RewriteHeapSROALoadUser(Instruction *LoadUser,
Chris Lattner222ef4c2008-12-17 05:28:49 +00001188 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Chris Lattner46b5c642009-11-06 04:27:31 +00001189 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
Chris Lattnerf315d4f2007-09-13 17:29:05 +00001190 // If this is a comparison against null, handle it.
1191 if (ICmpInst *SCI = dyn_cast<ICmpInst>(LoadUser)) {
1192 assert(isa<ConstantPointerNull>(SCI->getOperand(1)));
1193 // If we have a setcc of the loaded pointer, we can use a setcc of any
1194 // field.
Chris Lattner222ef4c2008-12-17 05:28:49 +00001195 Value *NPtr = GetHeapSROAValue(SCI->getOperand(0), 0,
Chris Lattner46b5c642009-11-06 04:27:31 +00001196 InsertedScalarizedValues, PHIsToRewrite);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001197
Owen Anderson1e5f00e2009-07-09 23:48:35 +00001198 Value *New = new ICmpInst(SCI, SCI->getPredicate(), NPtr,
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001199 Constant::getNullValue(NPtr->getType()),
Owen Anderson1e5f00e2009-07-09 23:48:35 +00001200 SCI->getName());
Chris Lattnerf315d4f2007-09-13 17:29:05 +00001201 SCI->replaceAllUsesWith(New);
1202 SCI->eraseFromParent();
1203 return;
1204 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001205
Chris Lattner222ef4c2008-12-17 05:28:49 +00001206 // Handle 'getelementptr Ptr, Idx, i32 FieldNo ...'
Chris Lattnerba98f892007-09-13 18:00:31 +00001207 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(LoadUser)) {
1208 assert(GEPI->getNumOperands() >= 3 && isa<ConstantInt>(GEPI->getOperand(2))
1209 && "Unexpected GEPI!");
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001210
Chris Lattnerba98f892007-09-13 18:00:31 +00001211 // Load the pointer for this field.
1212 unsigned FieldNo = cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue();
Chris Lattner222ef4c2008-12-17 05:28:49 +00001213 Value *NewPtr = GetHeapSROAValue(GEPI->getOperand(0), FieldNo,
Chris Lattner46b5c642009-11-06 04:27:31 +00001214 InsertedScalarizedValues, PHIsToRewrite);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001215
Chris Lattnerba98f892007-09-13 18:00:31 +00001216 // Create the new GEP idx vector.
1217 SmallVector<Value*, 8> GEPIdx;
1218 GEPIdx.push_back(GEPI->getOperand(1));
1219 GEPIdx.append(GEPI->op_begin()+3, GEPI->op_end());
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001220
David Blaikie22319eb2015-03-14 19:24:04 +00001221 Value *NGEPI = GetElementPtrInst::Create(GEPI->getResultElementType(), NewPtr, GEPIdx,
Gabor Greife9ecc682008-04-06 20:25:17 +00001222 GEPI->getName(), GEPI);
Chris Lattnerba98f892007-09-13 18:00:31 +00001223 GEPI->replaceAllUsesWith(NGEPI);
1224 GEPI->eraseFromParent();
1225 return;
1226 }
Chris Lattner011f91b2007-09-13 21:31:36 +00001227
Chris Lattner222ef4c2008-12-17 05:28:49 +00001228 // Recursively transform the users of PHI nodes. This will lazily create the
1229 // PHIs that are needed for individual elements. Keep track of what PHIs we
1230 // see in InsertedScalarizedValues so that we don't get infinite loops (very
1231 // antisocial). If the PHI is already in InsertedScalarizedValues, it has
1232 // already been seen first by another load, so its uses have already been
1233 // processed.
1234 PHINode *PN = cast<PHINode>(LoadUser);
Chris Lattner5cf753c2011-07-21 06:21:31 +00001235 if (!InsertedScalarizedValues.insert(std::make_pair(PN,
1236 std::vector<Value*>())).second)
1237 return;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001238
Chris Lattner222ef4c2008-12-17 05:28:49 +00001239 // If this is the first time we've seen this PHI, recursively process all
1240 // users.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001241 for (auto UI = PN->user_begin(), E = PN->user_end(); UI != E;) {
Chris Lattner0cdf5232008-12-17 05:42:08 +00001242 Instruction *User = cast<Instruction>(*UI++);
Chris Lattner46b5c642009-11-06 04:27:31 +00001243 RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite);
Chris Lattner0cdf5232008-12-17 05:42:08 +00001244 }
Chris Lattnerf315d4f2007-09-13 17:29:05 +00001245}
1246
James Molloyea31ad32015-11-13 11:05:07 +00001247/// We are performing Heap SRoA on a global. Ptr is a value loaded from the
1248/// global. Eliminate all uses of Ptr, making them use FieldGlobals instead.
1249/// All uses of loaded values satisfy AllGlobalLoadUsesSimpleEnoughForHeapSRA.
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001250static void RewriteUsesOfLoadForHeapSRoA(LoadInst *Load,
Chris Lattner222ef4c2008-12-17 05:28:49 +00001251 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Chris Lattner46b5c642009-11-06 04:27:31 +00001252 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00001253 for (auto UI = Load->user_begin(), E = Load->user_end(); UI != E;) {
Chris Lattner0cdf5232008-12-17 05:42:08 +00001254 Instruction *User = cast<Instruction>(*UI++);
Chris Lattner46b5c642009-11-06 04:27:31 +00001255 RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite);
Chris Lattner0cdf5232008-12-17 05:42:08 +00001256 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001257
Chris Lattner222ef4c2008-12-17 05:28:49 +00001258 if (Load->use_empty()) {
1259 Load->eraseFromParent();
1260 InsertedScalarizedValues.erase(Load);
1261 }
Chris Lattner24d3d422006-09-30 23:32:09 +00001262}
1263
James Molloyea31ad32015-11-13 11:05:07 +00001264/// CI is an allocation of an array of structures. Break it up into multiple
1265/// allocations of arrays of the fields.
Victor Hernandezf3db9152009-11-07 00:16:28 +00001266static GlobalVariable *PerformHeapAllocSRoA(GlobalVariable *GV, CallInst *CI,
Mehdi Amini46a43552015-03-04 18:43:29 +00001267 Value *NElems, const DataLayout &DL,
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00001268 const TargetLibraryInfo *TLI) {
David Greene44cb8ad2010-01-05 01:28:05 +00001269 DEBUG(dbgs() << "SROA HEAP ALLOC: " << *GV << " MALLOC = " << *CI << '\n');
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00001270 Type *MAT = getMallocAllocatedType(CI, TLI);
Chris Lattner229907c2011-07-18 04:54:35 +00001271 StructType *STy = cast<StructType>(MAT);
Victor Hernandez5d034492009-09-18 22:35:49 +00001272
1273 // There is guaranteed to be at least one use of the malloc (storing
1274 // it into GV). If there are other uses, change them to be uses of
1275 // the global to simplify later code. This also deletes the store
1276 // into GV.
Victor Hernandezf3db9152009-11-07 00:16:28 +00001277 ReplaceUsesOfMallocWithGlobal(CI, GV);
1278
Victor Hernandez5d034492009-09-18 22:35:49 +00001279 // Okay, at this point, there are no users of the malloc. Insert N
1280 // new mallocs at the same place as CI, and N globals.
1281 std::vector<Value*> FieldGlobals;
1282 std::vector<Value*> FieldMallocs;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001283
Matt Arsenaultfcd74012014-04-23 20:36:10 +00001284 unsigned AS = GV->getType()->getPointerAddressSpace();
Victor Hernandez5d034492009-09-18 22:35:49 +00001285 for (unsigned FieldNo = 0, e = STy->getNumElements(); FieldNo != e;++FieldNo){
Chris Lattner229907c2011-07-18 04:54:35 +00001286 Type *FieldTy = STy->getElementType(FieldNo);
Matt Arsenaultfcd74012014-04-23 20:36:10 +00001287 PointerType *PFieldTy = PointerType::get(FieldTy, AS);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001288
Victor Hernandez5d034492009-09-18 22:35:49 +00001289 GlobalVariable *NGV =
1290 new GlobalVariable(*GV->getParent(),
1291 PFieldTy, false, GlobalValue::InternalLinkage,
1292 Constant::getNullValue(PFieldTy),
1293 GV->getName() + ".f" + Twine(FieldNo), GV,
Hans Wennborgcbe34b42012-06-23 11:37:03 +00001294 GV->getThreadLocalMode());
Victor Hernandez5d034492009-09-18 22:35:49 +00001295 FieldGlobals.push_back(NGV);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001296
Mehdi Amini46a43552015-03-04 18:43:29 +00001297 unsigned TypeSize = DL.getTypeAllocSize(FieldTy);
Chris Lattner229907c2011-07-18 04:54:35 +00001298 if (StructType *ST = dyn_cast<StructType>(FieldTy))
Mehdi Amini46a43552015-03-04 18:43:29 +00001299 TypeSize = DL.getStructLayout(ST)->getSizeInBytes();
1300 Type *IntPtrTy = DL.getIntPtrType(CI->getType());
Victor Hernandezf3db9152009-11-07 00:16:28 +00001301 Value *NMI = CallInst::CreateMalloc(CI, IntPtrTy, FieldTy,
1302 ConstantInt::get(IntPtrTy, TypeSize),
Craig Topperf40110f2014-04-25 05:29:35 +00001303 NElems, nullptr,
Victor Hernandezf3db9152009-11-07 00:16:28 +00001304 CI->getName() + ".f" + Twine(FieldNo));
Chris Lattner0521c092010-02-26 18:23:13 +00001305 FieldMallocs.push_back(NMI);
Victor Hernandezf3db9152009-11-07 00:16:28 +00001306 new StoreInst(NMI, NGV, CI);
Victor Hernandez5d034492009-09-18 22:35:49 +00001307 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001308
Victor Hernandez5d034492009-09-18 22:35:49 +00001309 // The tricky aspect of this transformation is handling the case when malloc
1310 // fails. In the original code, malloc failing would set the result pointer
1311 // of malloc to null. In this case, some mallocs could succeed and others
1312 // could fail. As such, we emit code that looks like this:
1313 // F0 = malloc(field0)
1314 // F1 = malloc(field1)
1315 // F2 = malloc(field2)
1316 // if (F0 == 0 || F1 == 0 || F2 == 0) {
1317 // if (F0) { free(F0); F0 = 0; }
1318 // if (F1) { free(F1); F1 = 0; }
1319 // if (F2) { free(F2); F2 = 0; }
1320 // }
Victor Hernandezfcc77b12009-11-10 08:32:25 +00001321 // The malloc can also fail if its argument is too large.
Gabor Greif218f5542010-06-24 14:42:01 +00001322 Constant *ConstantZero = ConstantInt::get(CI->getArgOperand(0)->getType(), 0);
1323 Value *RunningOr = new ICmpInst(CI, ICmpInst::ICMP_SLT, CI->getArgOperand(0),
Victor Hernandezfcc77b12009-11-10 08:32:25 +00001324 ConstantZero, "isneg");
Victor Hernandez5d034492009-09-18 22:35:49 +00001325 for (unsigned i = 0, e = FieldMallocs.size(); i != e; ++i) {
Victor Hernandezf3db9152009-11-07 00:16:28 +00001326 Value *Cond = new ICmpInst(CI, ICmpInst::ICMP_EQ, FieldMallocs[i],
1327 Constant::getNullValue(FieldMallocs[i]->getType()),
1328 "isnull");
Victor Hernandezfcc77b12009-11-10 08:32:25 +00001329 RunningOr = BinaryOperator::CreateOr(RunningOr, Cond, "tmp", CI);
Victor Hernandez5d034492009-09-18 22:35:49 +00001330 }
1331
1332 // Split the basic block at the old malloc.
Victor Hernandezf3db9152009-11-07 00:16:28 +00001333 BasicBlock *OrigBB = CI->getParent();
Duncan P. N. Exon Smith17323402015-10-13 17:51:03 +00001334 BasicBlock *ContBB =
1335 OrigBB->splitBasicBlock(CI->getIterator(), "malloc_cont");
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001336
Victor Hernandez5d034492009-09-18 22:35:49 +00001337 // Create the block to check the first condition. Put all these blocks at the
1338 // end of the function as they are unlikely to be executed.
Chris Lattner46b5c642009-11-06 04:27:31 +00001339 BasicBlock *NullPtrBlock = BasicBlock::Create(OrigBB->getContext(),
1340 "malloc_ret_null",
Victor Hernandez5d034492009-09-18 22:35:49 +00001341 OrigBB->getParent());
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001342
Victor Hernandez5d034492009-09-18 22:35:49 +00001343 // Remove the uncond branch from OrigBB to ContBB, turning it into a cond
1344 // branch on RunningOr.
1345 OrigBB->getTerminator()->eraseFromParent();
1346 BranchInst::Create(NullPtrBlock, ContBB, RunningOr, OrigBB);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001347
Victor Hernandez5d034492009-09-18 22:35:49 +00001348 // Within the NullPtrBlock, we need to emit a comparison and branch for each
1349 // pointer, because some may be null while others are not.
1350 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
1351 Value *GVVal = new LoadInst(FieldGlobals[i], "tmp", NullPtrBlock);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001352 Value *Cmp = new ICmpInst(*NullPtrBlock, ICmpInst::ICMP_NE, GVVal,
Benjamin Kramer547b6c52011-09-27 20:39:19 +00001353 Constant::getNullValue(GVVal->getType()));
Chris Lattner46b5c642009-11-06 04:27:31 +00001354 BasicBlock *FreeBlock = BasicBlock::Create(Cmp->getContext(), "free_it",
Victor Hernandez5d034492009-09-18 22:35:49 +00001355 OrigBB->getParent());
Chris Lattner46b5c642009-11-06 04:27:31 +00001356 BasicBlock *NextBlock = BasicBlock::Create(Cmp->getContext(), "next",
Victor Hernandez5d034492009-09-18 22:35:49 +00001357 OrigBB->getParent());
Victor Hernandeze2971492009-10-24 04:23:03 +00001358 Instruction *BI = BranchInst::Create(FreeBlock, NextBlock,
1359 Cmp, NullPtrBlock);
Victor Hernandez5d034492009-09-18 22:35:49 +00001360
1361 // Fill in FreeBlock.
Victor Hernandeze2971492009-10-24 04:23:03 +00001362 CallInst::CreateFree(GVVal, BI);
Victor Hernandez5d034492009-09-18 22:35:49 +00001363 new StoreInst(Constant::getNullValue(GVVal->getType()), FieldGlobals[i],
1364 FreeBlock);
1365 BranchInst::Create(NextBlock, FreeBlock);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001366
Victor Hernandez5d034492009-09-18 22:35:49 +00001367 NullPtrBlock = NextBlock;
1368 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001369
Victor Hernandez5d034492009-09-18 22:35:49 +00001370 BranchInst::Create(ContBB, NullPtrBlock);
Victor Hernandezf3db9152009-11-07 00:16:28 +00001371
1372 // CI is no longer needed, remove it.
Victor Hernandez5d034492009-09-18 22:35:49 +00001373 CI->eraseFromParent();
1374
James Molloyea31ad32015-11-13 11:05:07 +00001375 /// As we process loads, if we can't immediately update all uses of the load,
1376 /// keep track of what scalarized loads are inserted for a given load.
Victor Hernandez5d034492009-09-18 22:35:49 +00001377 DenseMap<Value*, std::vector<Value*> > InsertedScalarizedValues;
1378 InsertedScalarizedValues[GV] = FieldGlobals;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001379
Victor Hernandez5d034492009-09-18 22:35:49 +00001380 std::vector<std::pair<PHINode*, unsigned> > PHIsToRewrite;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001381
Victor Hernandez5d034492009-09-18 22:35:49 +00001382 // Okay, the malloc site is completely handled. All of the uses of GV are now
1383 // loads, and all uses of those loads are simple. Rewrite them to use loads
1384 // of the per-field globals instead.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001385 for (auto UI = GV->user_begin(), E = GV->user_end(); UI != E;) {
Victor Hernandez5d034492009-09-18 22:35:49 +00001386 Instruction *User = cast<Instruction>(*UI++);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001387
Victor Hernandez5d034492009-09-18 22:35:49 +00001388 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Chris Lattner46b5c642009-11-06 04:27:31 +00001389 RewriteUsesOfLoadForHeapSRoA(LI, InsertedScalarizedValues, PHIsToRewrite);
Victor Hernandez5d034492009-09-18 22:35:49 +00001390 continue;
1391 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001392
Victor Hernandez5d034492009-09-18 22:35:49 +00001393 // Must be a store of null.
1394 StoreInst *SI = cast<StoreInst>(User);
1395 assert(isa<ConstantPointerNull>(SI->getOperand(0)) &&
1396 "Unexpected heap-sra user!");
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001397
Victor Hernandez5d034492009-09-18 22:35:49 +00001398 // Insert a store of null into each global.
1399 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
Chris Lattner229907c2011-07-18 04:54:35 +00001400 PointerType *PT = cast<PointerType>(FieldGlobals[i]->getType());
Victor Hernandez5d034492009-09-18 22:35:49 +00001401 Constant *Null = Constant::getNullValue(PT->getElementType());
1402 new StoreInst(Null, FieldGlobals[i], SI);
1403 }
1404 // Erase the original store.
1405 SI->eraseFromParent();
1406 }
1407
1408 // While we have PHIs that are interesting to rewrite, do it.
1409 while (!PHIsToRewrite.empty()) {
1410 PHINode *PN = PHIsToRewrite.back().first;
1411 unsigned FieldNo = PHIsToRewrite.back().second;
1412 PHIsToRewrite.pop_back();
1413 PHINode *FieldPN = cast<PHINode>(InsertedScalarizedValues[PN][FieldNo]);
1414 assert(FieldPN->getNumIncomingValues() == 0 &&"Already processed this phi");
1415
1416 // Add all the incoming values. This can materialize more phis.
1417 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1418 Value *InVal = PN->getIncomingValue(i);
1419 InVal = GetHeapSROAValue(InVal, FieldNo, InsertedScalarizedValues,
Chris Lattner46b5c642009-11-06 04:27:31 +00001420 PHIsToRewrite);
Victor Hernandez5d034492009-09-18 22:35:49 +00001421 FieldPN->addIncoming(InVal, PN->getIncomingBlock(i));
1422 }
1423 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001424
Victor Hernandez5d034492009-09-18 22:35:49 +00001425 // Drop all inter-phi links and any loads that made it this far.
1426 for (DenseMap<Value*, std::vector<Value*> >::iterator
1427 I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
1428 I != E; ++I) {
1429 if (PHINode *PN = dyn_cast<PHINode>(I->first))
1430 PN->dropAllReferences();
1431 else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
1432 LI->dropAllReferences();
1433 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001434
Victor Hernandez5d034492009-09-18 22:35:49 +00001435 // Delete all the phis and loads now that inter-references are dead.
1436 for (DenseMap<Value*, std::vector<Value*> >::iterator
1437 I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
1438 I != E; ++I) {
1439 if (PHINode *PN = dyn_cast<PHINode>(I->first))
1440 PN->eraseFromParent();
1441 else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
1442 LI->eraseFromParent();
1443 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001444
Victor Hernandez5d034492009-09-18 22:35:49 +00001445 // The old global is now dead, remove it.
1446 GV->eraseFromParent();
1447
1448 ++NumHeapSRA;
1449 return cast<GlobalVariable>(FieldGlobals[0]);
1450}
1451
James Molloyea31ad32015-11-13 11:05:07 +00001452/// This function is called when we see a pointer global variable with a single
1453/// value stored it that is a malloc or cast of malloc.
Mehdi Amini46a43552015-03-04 18:43:29 +00001454static bool TryToOptimizeStoreOfMallocToGlobal(GlobalVariable *GV, CallInst *CI,
Chris Lattner229907c2011-07-18 04:54:35 +00001455 Type *AllocTy,
Nick Lewycky52da72b2012-02-05 19:56:38 +00001456 AtomicOrdering Ordering,
Victor Hernandez5d034492009-09-18 22:35:49 +00001457 Module::global_iterator &GVI,
Mehdi Amini46a43552015-03-04 18:43:29 +00001458 const DataLayout &DL,
Nick Lewyckycf6aae62012-02-12 01:13:18 +00001459 TargetLibraryInfo *TLI) {
Victor Hernandez5d034492009-09-18 22:35:49 +00001460 // If this is a malloc of an abstract type, don't touch it.
1461 if (!AllocTy->isSized())
1462 return false;
1463
1464 // We can't optimize this global unless all uses of it are *known* to be
1465 // of the malloc value, not of the null initializer value (consider a use
1466 // that compares the global's value against zero to see if the malloc has
1467 // been reached). To do this, we check to see if all uses of the global
1468 // would trap if the global were null: this proves that they must all
1469 // happen after the malloc.
1470 if (!AllUsesOfLoadedValueWillTrapIfNull(GV))
1471 return false;
1472
1473 // We can't optimize this if the malloc itself is used in a complex way,
1474 // for example, being stored into multiple globals. This allows the
Nick Lewyckybbd11562012-02-05 19:48:37 +00001475 // malloc to be stored into the specified global, loaded icmp'd, and
Victor Hernandez5d034492009-09-18 22:35:49 +00001476 // GEP'd. These are all things we could transform to using the global
1477 // for.
Evan Cheng21b588b2010-04-14 20:52:55 +00001478 SmallPtrSet<const PHINode*, 8> PHIs;
1479 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(CI, GV, PHIs))
1480 return false;
Victor Hernandez5d034492009-09-18 22:35:49 +00001481
1482 // If we have a global that is only initialized with a fixed size malloc,
1483 // transform the program to use global memory instead of malloc'd memory.
1484 // This eliminates dynamic allocation, avoids an indirection accessing the
1485 // data, and exposes the resultant global to further GlobalOpt.
Victor Hernandez264da322009-10-16 23:12:25 +00001486 // We cannot optimize the malloc if we cannot determine malloc array size.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001487 Value *NElems = getMallocArraySize(CI, DL, TLI, true);
Evan Cheng21b588b2010-04-14 20:52:55 +00001488 if (!NElems)
1489 return false;
Victor Hernandez5d034492009-09-18 22:35:49 +00001490
Evan Cheng21b588b2010-04-14 20:52:55 +00001491 if (ConstantInt *NElements = dyn_cast<ConstantInt>(NElems))
1492 // Restrict this transformation to only working on small allocations
1493 // (2048 bytes currently), as we don't want to introduce a 16M global or
1494 // something.
Mehdi Amini46a43552015-03-04 18:43:29 +00001495 if (NElements->getZExtValue() * DL.getTypeAllocSize(AllocTy) < 2048) {
Duncan P. N. Exon Smith17323402015-10-13 17:51:03 +00001496 GVI = OptimizeGlobalAddressOfMalloc(GV, CI, AllocTy, NElements, DL, TLI)
1497 ->getIterator();
Evan Cheng21b588b2010-04-14 20:52:55 +00001498 return true;
Victor Hernandez5d034492009-09-18 22:35:49 +00001499 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001500
Evan Cheng21b588b2010-04-14 20:52:55 +00001501 // If the allocation is an array of structures, consider transforming this
1502 // into multiple malloc'd arrays, one for each field. This is basically
1503 // SRoA for malloc'd memory.
1504
Nick Lewycky52da72b2012-02-05 19:56:38 +00001505 if (Ordering != NotAtomic)
1506 return false;
1507
Evan Cheng21b588b2010-04-14 20:52:55 +00001508 // If this is an allocation of a fixed size array of structs, analyze as a
1509 // variable size array. malloc [100 x struct],1 -> malloc struct, 100
Gabor Greif218f5542010-06-24 14:42:01 +00001510 if (NElems == ConstantInt::get(CI->getArgOperand(0)->getType(), 1))
Chris Lattner229907c2011-07-18 04:54:35 +00001511 if (ArrayType *AT = dyn_cast<ArrayType>(AllocTy))
Evan Cheng21b588b2010-04-14 20:52:55 +00001512 AllocTy = AT->getElementType();
Gabor Greif218f5542010-06-24 14:42:01 +00001513
Chris Lattner229907c2011-07-18 04:54:35 +00001514 StructType *AllocSTy = dyn_cast<StructType>(AllocTy);
Evan Cheng21b588b2010-04-14 20:52:55 +00001515 if (!AllocSTy)
1516 return false;
1517
1518 // This the structure has an unreasonable number of fields, leave it
1519 // alone.
1520 if (AllocSTy->getNumElements() <= 16 && AllocSTy->getNumElements() != 0 &&
1521 AllGlobalLoadUsesSimpleEnoughForHeapSRA(GV, CI)) {
1522
1523 // If this is a fixed size array, transform the Malloc to be an alloc of
1524 // structs. malloc [100 x struct],1 -> malloc struct, 100
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00001525 if (ArrayType *AT = dyn_cast<ArrayType>(getMallocAllocatedType(CI, TLI))) {
Mehdi Amini46a43552015-03-04 18:43:29 +00001526 Type *IntPtrTy = DL.getIntPtrType(CI->getType());
1527 unsigned TypeSize = DL.getStructLayout(AllocSTy)->getSizeInBytes();
Evan Cheng21b588b2010-04-14 20:52:55 +00001528 Value *AllocSize = ConstantInt::get(IntPtrTy, TypeSize);
1529 Value *NumElements = ConstantInt::get(IntPtrTy, AT->getNumElements());
1530 Instruction *Malloc = CallInst::CreateMalloc(CI, IntPtrTy, AllocSTy,
1531 AllocSize, NumElements,
Craig Topperf40110f2014-04-25 05:29:35 +00001532 nullptr, CI->getName());
Evan Cheng21b588b2010-04-14 20:52:55 +00001533 Instruction *Cast = new BitCastInst(Malloc, CI->getType(), "tmp", CI);
1534 CI->replaceAllUsesWith(Cast);
1535 CI->eraseFromParent();
Nuno Lopes9792d682012-06-22 00:25:01 +00001536 if (BitCastInst *BCI = dyn_cast<BitCastInst>(Malloc))
1537 CI = cast<CallInst>(BCI->getOperand(0));
1538 else
Nuno Lopes0b60ebb2012-06-22 00:29:58 +00001539 CI = cast<CallInst>(Malloc);
Evan Cheng21b588b2010-04-14 20:52:55 +00001540 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001541
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001542 GVI = PerformHeapAllocSRoA(GV, CI, getMallocArraySize(CI, DL, TLI, true),
Duncan P. N. Exon Smith17323402015-10-13 17:51:03 +00001543 DL, TLI)
1544 ->getIterator();
Evan Cheng21b588b2010-04-14 20:52:55 +00001545 return true;
Victor Hernandez5d034492009-09-18 22:35:49 +00001546 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001547
Victor Hernandez5d034492009-09-18 22:35:49 +00001548 return false;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001549}
Victor Hernandez5d034492009-09-18 22:35:49 +00001550
Chris Lattner09a52722004-10-09 21:48:45 +00001551// OptimizeOnceStoredGlobal - Try to optimize globals based on the knowledge
1552// that only one value (besides its initializer) is ever stored to the global.
Chris Lattner004e2502004-10-11 05:54:41 +00001553static bool OptimizeOnceStoredGlobal(GlobalVariable *GV, Value *StoredOnceVal,
Nick Lewycky52da72b2012-02-05 19:56:38 +00001554 AtomicOrdering Ordering,
Chris Lattnerc2d3d312006-08-27 22:42:52 +00001555 Module::global_iterator &GVI,
Mehdi Amini46a43552015-03-04 18:43:29 +00001556 const DataLayout &DL,
Rafael Espindolaaeff8a92014-02-24 23:12:18 +00001557 TargetLibraryInfo *TLI) {
Chris Lattner1c731fa2008-12-15 21:20:32 +00001558 // Ignore no-op GEPs and bitcasts.
1559 StoredOnceVal = StoredOnceVal->stripPointerCasts();
Chris Lattner09a52722004-10-09 21:48:45 +00001560
Chris Lattnere42eb312004-10-10 23:14:11 +00001561 // If we are dealing with a pointer global that is initialized to null and
1562 // only has one (non-null) value stored into it, then we can optimize any
1563 // users of the loaded value (often calls and loads) that would trap if the
1564 // value was null.
Duncan Sands19d0b472010-02-16 11:11:14 +00001565 if (GV->getInitializer()->getType()->isPointerTy() &&
Chris Lattner09a52722004-10-09 21:48:45 +00001566 GV->getInitializer()->isNullValue()) {
Chris Lattnere42eb312004-10-10 23:14:11 +00001567 if (Constant *SOVC = dyn_cast<Constant>(StoredOnceVal)) {
1568 if (GV->getInitializer()->getType() != SOVC->getType())
Chris Lattner1a1acc22011-05-22 07:15:13 +00001569 SOVC = ConstantExpr::getBitCast(SOVC, GV->getInitializer()->getType());
Misha Brukmanb1c93172005-04-21 23:48:37 +00001570
Chris Lattnere42eb312004-10-10 23:14:11 +00001571 // Optimize away any trapping uses of the loaded value.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001572 if (OptimizeAwayTrappingUsesOfLoads(GV, SOVC, DL, TLI))
Chris Lattner604ed7a2004-10-10 17:07:12 +00001573 return true;
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00001574 } else if (CallInst *CI = extractMallocCall(StoredOnceVal, TLI)) {
1575 Type *MallocType = getMallocAllocatedType(CI, TLI);
Nick Lewyckycf6aae62012-02-12 01:13:18 +00001576 if (MallocType &&
1577 TryToOptimizeStoreOfMallocToGlobal(GV, CI, MallocType, Ordering, GVI,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001578 DL, TLI))
Victor Hernandezf3db9152009-11-07 00:16:28 +00001579 return true;
Chris Lattnere42eb312004-10-10 23:14:11 +00001580 }
Chris Lattner09a52722004-10-09 21:48:45 +00001581 }
Chris Lattner004e2502004-10-11 05:54:41 +00001582
Chris Lattner09a52722004-10-09 21:48:45 +00001583 return false;
1584}
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001585
James Molloyea31ad32015-11-13 11:05:07 +00001586/// At this point, we have learned that the only two values ever stored into GV
1587/// are its initializer and OtherVal. See if we can shrink the global into a
1588/// boolean and select between the two values whenever it is used. This exposes
1589/// the values to other scalar optimizations.
Lang Hames459b5dc2014-03-23 04:22:31 +00001590static bool TryToShrinkGlobalToBoolean(GlobalVariable *GV, Constant *OtherVal) {
Chris Lattner229907c2011-07-18 04:54:35 +00001591 Type *GVElType = GV->getType()->getElementType();
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001592
Lang Hames459b5dc2014-03-23 04:22:31 +00001593 // If GVElType is already i1, it is already shrunk. If the type of the GV is
1594 // an FP value, pointer or vector, don't do this optimization because a select
1595 // between them is very expensive and unlikely to lead to later
1596 // simplification. In these cases, we typically end up with "cond ? v1 : v2"
1597 // where v1 and v2 both require constant pool loads, a big loss.
Chris Lattner46b5c642009-11-06 04:27:31 +00001598 if (GVElType == Type::getInt1Ty(GV->getContext()) ||
Duncan Sands9dff9be2010-02-15 16:12:20 +00001599 GVElType->isFloatingPointTy() ||
Duncan Sands19d0b472010-02-16 11:11:14 +00001600 GVElType->isPointerTy() || GVElType->isVectorTy())
Chris Lattner20bbac32008-01-14 01:17:44 +00001601 return false;
Gabor Greifa75ed762010-07-12 14:13:15 +00001602
Chris Lattner20bbac32008-01-14 01:17:44 +00001603 // Walk the use list of the global seeing if all the uses are load or store.
1604 // If there is anything else, bail out.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001605 for (User *U : GV->users())
Gabor Greifa75ed762010-07-12 14:13:15 +00001606 if (!isa<LoadInst>(U) && !isa<StoreInst>(U))
Chris Lattner20bbac32008-01-14 01:17:44 +00001607 return false;
Gabor Greifa75ed762010-07-12 14:13:15 +00001608
James Molloyef607a22015-10-28 14:30:53 +00001609 DEBUG(dbgs() << " *** SHRINKING TO BOOL: " << *GV << "\n");
Lang Hames459b5dc2014-03-23 04:22:31 +00001610
1611 // Create the new global, initializing it to false.
1612 GlobalVariable *NewGV = new GlobalVariable(Type::getInt1Ty(GV->getContext()),
1613 false,
1614 GlobalValue::InternalLinkage,
1615 ConstantInt::getFalse(GV->getContext()),
1616 GV->getName()+".b",
1617 GV->getThreadLocalMode(),
1618 GV->getType()->getAddressSpace());
Duncan P. N. Exon Smith17323402015-10-13 17:51:03 +00001619 GV->getParent()->getGlobalList().insert(GV->getIterator(), NewGV);
Lang Hames459b5dc2014-03-23 04:22:31 +00001620
Chris Lattner40e4cec2004-12-12 05:53:50 +00001621 Constant *InitVal = GV->getInitializer();
Chris Lattner46b5c642009-11-06 04:27:31 +00001622 assert(InitVal->getType() != Type::getInt1Ty(GV->getContext()) &&
Lang Hames459b5dc2014-03-23 04:22:31 +00001623 "No reason to shrink to bool!");
Chris Lattner40e4cec2004-12-12 05:53:50 +00001624
Lang Hames459b5dc2014-03-23 04:22:31 +00001625 // If initialized to zero and storing one into the global, we can use a cast
1626 // instead of a select to synthesize the desired value.
1627 bool IsOneZero = false;
1628 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal))
1629 IsOneZero = InitVal->isNullValue() && CI->isOne();
Chris Lattner40e4cec2004-12-12 05:53:50 +00001630
Lang Hames459b5dc2014-03-23 04:22:31 +00001631 while (!GV->use_empty()) {
1632 Instruction *UI = cast<Instruction>(GV->user_back());
1633 if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
1634 // Change the store into a boolean store.
1635 bool StoringOther = SI->getOperand(0) == OtherVal;
1636 // Only do this if we weren't storing a loaded value.
1637 Value *StoreVal;
1638 if (StoringOther || SI->getOperand(0) == InitVal) {
1639 StoreVal = ConstantInt::get(Type::getInt1Ty(GV->getContext()),
1640 StoringOther);
Bill Wendling7297b862013-02-13 23:00:51 +00001641 } else {
Lang Hames459b5dc2014-03-23 04:22:31 +00001642 // Otherwise, we are storing a previously loaded copy. To do this,
1643 // change the copy from copying the original value to just copying the
1644 // bool.
1645 Instruction *StoredVal = cast<Instruction>(SI->getOperand(0));
1646
1647 // If we've already replaced the input, StoredVal will be a cast or
1648 // select instruction. If not, it will be a load of the original
1649 // global.
1650 if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
1651 assert(LI->getOperand(0) == GV && "Not a copy!");
1652 // Insert a new load, to preserve the saved value.
1653 StoreVal = new LoadInst(NewGV, LI->getName()+".b", false, 0,
1654 LI->getOrdering(), LI->getSynchScope(), LI);
1655 } else {
1656 assert((isa<CastInst>(StoredVal) || isa<SelectInst>(StoredVal)) &&
1657 "This is not a form that we understand!");
1658 StoreVal = StoredVal->getOperand(0);
1659 assert(isa<LoadInst>(StoreVal) && "Not a load of NewGV!");
1660 }
Chris Lattner745196a2004-12-12 19:34:41 +00001661 }
Lang Hames459b5dc2014-03-23 04:22:31 +00001662 new StoreInst(StoreVal, NewGV, false, 0,
1663 SI->getOrdering(), SI->getSynchScope(), SI);
1664 } else {
1665 // Change the load into a load of bool then a select.
1666 LoadInst *LI = cast<LoadInst>(UI);
1667 LoadInst *NLI = new LoadInst(NewGV, LI->getName()+".b", false, 0,
1668 LI->getOrdering(), LI->getSynchScope(), LI);
1669 Value *NSI;
1670 if (IsOneZero)
1671 NSI = new ZExtInst(NLI, LI->getType(), "", LI);
1672 else
1673 NSI = SelectInst::Create(NLI, OtherVal, InitVal, "", LI);
1674 NSI->takeName(LI);
1675 LI->replaceAllUsesWith(NSI);
Devang Patelfc507a12009-03-06 01:39:36 +00001676 }
Lang Hames459b5dc2014-03-23 04:22:31 +00001677 UI->eraseFromParent();
Chris Lattner40e4cec2004-12-12 05:53:50 +00001678 }
1679
Lang Hames459b5dc2014-03-23 04:22:31 +00001680 // Retain the name of the old global variable. People who are debugging their
1681 // programs may expect these variables to be named the same.
1682 NewGV->takeName(GV);
1683 GV->eraseFromParent();
Chris Lattner20bbac32008-01-14 01:17:44 +00001684 return true;
Chris Lattner40e4cec2004-12-12 05:53:50 +00001685}
1686
1687
James Molloyea31ad32015-11-13 11:05:07 +00001688/// Analyze the specified global variable and optimize it if possible. If we
1689/// make a change, return true.
Rafael Espindolafc355bc2011-01-19 16:32:21 +00001690bool GlobalOpt::ProcessGlobal(GlobalVariable *GV,
1691 Module::global_iterator &GVI) {
Rafael Espindolafc355bc2011-01-19 16:32:21 +00001692 // Do more involved optimizations if the global is internal.
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001693 GV->removeDeadConstantUsers();
1694
1695 if (GV->use_empty()) {
James Molloyef607a22015-10-28 14:30:53 +00001696 DEBUG(dbgs() << "GLOBAL DEAD: " << *GV << "\n");
Chris Lattner8e71c6a2004-10-16 18:09:00 +00001697 GV->eraseFromParent();
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001698 ++NumDeleted;
1699 return true;
1700 }
1701
Rafael Espindola1821c6c2012-06-15 18:00:24 +00001702 if (!GV->hasLocalLinkage())
1703 return false;
1704
Rafael Espindolafc355bc2011-01-19 16:32:21 +00001705 GlobalStatus GS;
1706
Rafael Espindola3d7fc252013-10-21 17:14:55 +00001707 if (GlobalStatus::analyzeGlobal(GV, GS))
Rafael Espindolaecd5b9a2011-01-18 04:36:06 +00001708 return false;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001709
Rafael Espindola045a78f2013-10-17 18:18:52 +00001710 if (!GS.IsCompared && !GV->hasUnnamedAddr()) {
Rafael Espindolafc355bc2011-01-19 16:32:21 +00001711 GV->setUnnamedAddr(true);
1712 NumUnnamed++;
1713 }
1714
1715 if (GV->isConstant() || !GV->hasInitializer())
1716 return false;
1717
Rafael Espindolad21ac192013-09-05 19:15:21 +00001718 return ProcessInternalGlobal(GV, GVI, GS);
Rafael Espindolafc355bc2011-01-19 16:32:21 +00001719}
1720
James Molloyea31ad32015-11-13 11:05:07 +00001721/// Analyze the specified global variable and optimize
Rafael Espindolafc355bc2011-01-19 16:32:21 +00001722/// it if possible. If we make a change, return true.
1723bool GlobalOpt::ProcessInternalGlobal(GlobalVariable *GV,
1724 Module::global_iterator &GVI,
Rafael Espindolafc355bc2011-01-19 16:32:21 +00001725 const GlobalStatus &GS) {
Mehdi Amini46a43552015-03-04 18:43:29 +00001726 auto &DL = GV->getParent()->getDataLayout();
Alexey Samsonova1944e62013-10-07 19:03:24 +00001727 // If this is a first class global and has only one accessing function
1728 // and this function is main (which we know is not recursive), we replace
1729 // the global with a local alloca in this function.
1730 //
Alp Tokerf907b892013-12-05 05:44:44 +00001731 // NOTE: It doesn't make sense to promote non-single-value types since we
Alexey Samsonova1944e62013-10-07 19:03:24 +00001732 // are just replacing static memory to stack memory.
1733 //
1734 // If the global is in different address space, don't bring it to stack.
1735 if (!GS.HasMultipleAccessingFunctions &&
1736 GS.AccessingFunction && !GS.HasNonInstructionUser &&
1737 GV->getType()->getElementType()->isSingleValueType() &&
1738 GS.AccessingFunction->getName() == "main" &&
1739 GS.AccessingFunction->hasExternalLinkage() &&
1740 GV->getType()->getAddressSpace() == 0) {
James Molloy33e73452015-11-13 11:05:13 +00001741 DEBUG(dbgs() << "LOCALIZING GLOBAL: " << *GV << "\n");
Alexey Samsonova1944e62013-10-07 19:03:24 +00001742 Instruction &FirstI = const_cast<Instruction&>(*GS.AccessingFunction
1743 ->getEntryBlock().begin());
1744 Type *ElemTy = GV->getType()->getElementType();
1745 // FIXME: Pass Global's alignment when globals have alignment
Craig Topperf40110f2014-04-25 05:29:35 +00001746 AllocaInst *Alloca = new AllocaInst(ElemTy, nullptr,
1747 GV->getName(), &FirstI);
Alexey Samsonova1944e62013-10-07 19:03:24 +00001748 if (!isa<UndefValue>(GV->getInitializer()))
1749 new StoreInst(GV->getInitializer(), Alloca, &FirstI);
1750
1751 GV->replaceAllUsesWith(Alloca);
1752 GV->eraseFromParent();
1753 ++NumLocalized;
1754 return true;
1755 }
1756
Rafael Espindolaecd5b9a2011-01-18 04:36:06 +00001757 // If the global is never loaded (but may be stored to), it is dead.
1758 // Delete it now.
Rafael Espindola045a78f2013-10-17 18:18:52 +00001759 if (!GS.IsLoaded) {
James Molloy33e73452015-11-13 11:05:13 +00001760 DEBUG(dbgs() << "GLOBAL NEVER LOADED: " << *GV << "\n");
Rafael Espindolaecd5b9a2011-01-18 04:36:06 +00001761
Nick Lewyckyfaa9c3b02012-07-24 07:21:08 +00001762 bool Changed;
1763 if (isLeakCheckerRoot(GV)) {
1764 // Delete any constant stores to the global.
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00001765 Changed = CleanupPointerRootUsers(GV, TLI);
Nick Lewyckyfaa9c3b02012-07-24 07:21:08 +00001766 } else {
1767 // Delete any stores we can find to the global. We may not be able to
1768 // make it completely dead though.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001769 Changed = CleanupConstantGlobalUsers(GV, GV->getInitializer(), DL, TLI);
Nick Lewyckyfaa9c3b02012-07-24 07:21:08 +00001770 }
Rafael Espindolaecd5b9a2011-01-18 04:36:06 +00001771
1772 // If the global is dead now, delete it.
1773 if (GV->use_empty()) {
1774 GV->eraseFromParent();
1775 ++NumDeleted;
1776 Changed = true;
1777 }
1778 return Changed;
1779
Rafael Espindola045a78f2013-10-17 18:18:52 +00001780 } else if (GS.StoredType <= GlobalStatus::InitializerStored) {
Michael Gottesmand1a46f22013-01-11 20:07:53 +00001781 DEBUG(dbgs() << "MARKING CONSTANT: " << *GV << "\n");
Rafael Espindolaecd5b9a2011-01-18 04:36:06 +00001782 GV->setConstant(true);
1783
1784 // Clean up any obviously simplifiable users now.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001785 CleanupConstantGlobalUsers(GV, GV->getInitializer(), DL, TLI);
Rafael Espindolaecd5b9a2011-01-18 04:36:06 +00001786
1787 // If the global is dead now, just nuke it.
1788 if (GV->use_empty()) {
1789 DEBUG(dbgs() << " *** Marking constant allowed us to simplify "
1790 << "all users and delete global!\n");
1791 GV->eraseFromParent();
1792 ++NumDeleted;
1793 }
1794
1795 ++NumMarked;
1796 return true;
1797 } else if (!GV->getInitializer()->getType()->isSingleValueType()) {
Mehdi Amini46a43552015-03-04 18:43:29 +00001798 const DataLayout &DL = GV->getParent()->getDataLayout();
1799 if (GlobalVariable *FirstNewGV = SRAGlobal(GV, DL)) {
Duncan P. N. Exon Smith17323402015-10-13 17:51:03 +00001800 GVI = FirstNewGV->getIterator(); // Don't skip the newly produced globals!
Mehdi Amini46a43552015-03-04 18:43:29 +00001801 return true;
Rafael Espindola93512512014-02-25 17:30:31 +00001802 }
Oliver Stannard939724c2015-10-12 13:20:52 +00001803 } else if (GS.StoredType == GlobalStatus::StoredOnce && GS.StoredOnceValue) {
Rafael Espindolaecd5b9a2011-01-18 04:36:06 +00001804 // If the initial value for the global was an undef value, and if only
1805 // one other value was stored into it, we can just change the
1806 // initializer to be the stored value, then delete all stores to the
1807 // global. This allows us to mark it constant.
1808 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
1809 if (isa<UndefValue>(GV->getInitializer())) {
1810 // Change the initial value here.
1811 GV->setInitializer(SOVConstant);
1812
1813 // Clean up any obviously simplifiable users now.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001814 CleanupConstantGlobalUsers(GV, GV->getInitializer(), DL, TLI);
Rafael Espindolaecd5b9a2011-01-18 04:36:06 +00001815
1816 if (GV->use_empty()) {
1817 DEBUG(dbgs() << " *** Substituting initializer allowed us to "
Nick Lewyckyfaa9c3b02012-07-24 07:21:08 +00001818 << "simplify all users and delete global!\n");
Rafael Espindolaecd5b9a2011-01-18 04:36:06 +00001819 GV->eraseFromParent();
1820 ++NumDeleted;
1821 } else {
Duncan P. N. Exon Smith17323402015-10-13 17:51:03 +00001822 GVI = GV->getIterator();
Rafael Espindolaecd5b9a2011-01-18 04:36:06 +00001823 }
1824 ++NumSubstitute;
1825 return true;
1826 }
1827
1828 // Try to optimize globals based on the knowledge that only one value
1829 // (besides its initializer) is ever stored to the global.
Nick Lewycky52da72b2012-02-05 19:56:38 +00001830 if (OptimizeOnceStoredGlobal(GV, GS.StoredOnceValue, GS.Ordering, GVI,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001831 DL, TLI))
Rafael Espindolaecd5b9a2011-01-18 04:36:06 +00001832 return true;
1833
Lang Hames459b5dc2014-03-23 04:22:31 +00001834 // Otherwise, if the global was not a boolean, we can shrink it to be a
1835 // boolean.
Eli Friedman33d37002013-09-09 22:00:13 +00001836 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue)) {
1837 if (GS.Ordering == NotAtomic) {
Lang Hames459b5dc2014-03-23 04:22:31 +00001838 if (TryToShrinkGlobalToBoolean(GV, SOVConstant)) {
Eli Friedman33d37002013-09-09 22:00:13 +00001839 ++NumShrunkToBool;
1840 return true;
1841 }
Rafael Espindolaecd5b9a2011-01-18 04:36:06 +00001842 }
Eli Friedman33d37002013-09-09 22:00:13 +00001843 }
Rafael Espindolaecd5b9a2011-01-18 04:36:06 +00001844 }
1845
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001846 return false;
1847}
1848
James Molloyea31ad32015-11-13 11:05:07 +00001849/// Walk all of the direct calls of the specified function, changing them to
1850/// FastCC.
Chris Lattnera4c80222005-05-08 22:18:06 +00001851static void ChangeCalleesToFastCall(Function *F) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00001852 for (User *U : F->users()) {
1853 if (isa<BlockAddress>(U))
Jay Foadca0c4992012-05-12 08:30:16 +00001854 continue;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001855 CallSite CS(cast<Instruction>(U));
1856 CS.setCallingConv(CallingConv::Fast);
Chris Lattnera4c80222005-05-08 22:18:06 +00001857 }
1858}
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001859
Bill Wendlinge94d8432012-12-07 23:16:57 +00001860static AttributeSet StripNest(LLVMContext &C, const AttributeSet &Attrs) {
Chris Lattner8a923e72008-03-12 17:45:29 +00001861 for (unsigned i = 0, e = Attrs.getNumSlots(); i != e; ++i) {
Bill Wendling57625a42013-01-25 23:09:36 +00001862 unsigned Index = Attrs.getSlotIndex(i);
1863 if (!Attrs.getSlotAttributes(i).hasAttribute(Index, Attribute::Nest))
Duncan Sands85fab3a2008-02-18 17:32:13 +00001864 continue;
1865
Duncan Sands85fab3a2008-02-18 17:32:13 +00001866 // There can be only one.
Bill Wendling57625a42013-01-25 23:09:36 +00001867 return Attrs.removeAttribute(C, Index, Attribute::Nest);
Duncan Sands573b3f82008-02-16 20:56:04 +00001868 }
1869
1870 return Attrs;
1871}
1872
1873static void RemoveNestAttribute(Function *F) {
Bill Wendling85a64c22012-10-14 06:39:53 +00001874 F->setAttributes(StripNest(F->getContext(), F->getAttributes()));
Chandler Carruthcdf47882014-03-09 03:16:01 +00001875 for (User *U : F->users()) {
1876 if (isa<BlockAddress>(U))
Jay Foadca0c4992012-05-12 08:30:16 +00001877 continue;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001878 CallSite CS(cast<Instruction>(U));
1879 CS.setAttributes(StripNest(F->getContext(), CS.getAttributes()));
Duncan Sands573b3f82008-02-16 20:56:04 +00001880 }
1881}
1882
Reid Kleckner22869372014-02-26 19:57:30 +00001883/// Return true if this is a calling convention that we'd like to change. The
1884/// idea here is that we don't want to mess with the convention if the user
1885/// explicitly requested something with performance implications like coldcc,
1886/// GHC, or anyregcc.
1887static bool isProfitableToMakeFastCC(Function *F) {
1888 CallingConv::ID CC = F->getCallingConv();
1889 // FIXME: Is it worth transforming x86_stdcallcc and x86_fastcallcc?
1890 return CC == CallingConv::C || CC == CallingConv::X86_ThisCall;
1891}
1892
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001893bool GlobalOpt::OptimizeFunctions(Module &M) {
1894 bool Changed = false;
1895 // Optimize functions.
1896 for (Module::iterator FI = M.begin(), E = M.end(); FI != E; ) {
Duncan P. N. Exon Smith17323402015-10-13 17:51:03 +00001897 Function *F = &*FI++;
Duncan Sandsed722832009-03-06 10:21:56 +00001898 // Functions without names cannot be referenced outside this module.
David Majnemer5c921152014-07-01 15:26:50 +00001899 if (!F->hasName() && !F->isDeclaration() && !F->hasLocalLinkage())
Duncan Sandsed722832009-03-06 10:21:56 +00001900 F->setLinkage(GlobalValue::InternalLinkage);
David Majnemer1b3b70e2014-10-08 07:23:31 +00001901
1902 const Comdat *C = F->getComdat();
1903 bool inComdat = C && NotDiscardableComdats.count(C);
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001904 F->removeDeadConstantUsers();
David Majnemer1b3b70e2014-10-08 07:23:31 +00001905 if ((!inComdat || F->hasLocalLinkage()) && F->isDefTriviallyDead()) {
Chris Lattnerb5d9c8c2009-11-01 19:03:42 +00001906 F->eraseFromParent();
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001907 Changed = true;
1908 ++NumFnDeleted;
Rafael Espindola6de96a12009-01-15 20:18:42 +00001909 } else if (F->hasLocalLinkage()) {
Reid Klecknere6ff5c52014-02-28 22:50:08 +00001910 if (isProfitableToMakeFastCC(F) && !F->isVarArg() &&
1911 !F->hasAddressTaken()) {
Reid Kleckner22869372014-02-26 19:57:30 +00001912 // If this function has a calling convention worth changing, is not a
1913 // varargs function, and is only called directly, promote it to use the
1914 // Fast calling convention.
Duncan Sands573b3f82008-02-16 20:56:04 +00001915 F->setCallingConv(CallingConv::Fast);
1916 ChangeCalleesToFastCall(F);
1917 ++NumFastCallFns;
1918 Changed = true;
1919 }
1920
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001921 if (F->getAttributes().hasAttrSomewhere(Attribute::Nest) &&
Jay Foad557169d2009-06-10 08:41:11 +00001922 !F->hasAddressTaken()) {
Duncan Sands573b3f82008-02-16 20:56:04 +00001923 // The function is not used by a trampoline intrinsic, so it is safe
1924 // to remove the 'nest' attribute.
1925 RemoveNestAttribute(F);
1926 ++NumNestRemoved;
1927 Changed = true;
1928 }
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001929 }
1930 }
1931 return Changed;
1932}
1933
1934bool GlobalOpt::OptimizeGlobalVars(Module &M) {
1935 bool Changed = false;
David Majnemerdad0a642014-06-27 18:19:56 +00001936
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001937 for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
1938 GVI != E; ) {
Duncan P. N. Exon Smith17323402015-10-13 17:51:03 +00001939 GlobalVariable *GV = &*GVI++;
Duncan Sandsed722832009-03-06 10:21:56 +00001940 // Global variables without names cannot be referenced outside this module.
David Majnemer5c921152014-07-01 15:26:50 +00001941 if (!GV->hasName() && !GV->isDeclaration() && !GV->hasLocalLinkage())
Duncan Sandsed722832009-03-06 10:21:56 +00001942 GV->setLinkage(GlobalValue::InternalLinkage);
Dan Gohman580b80d2009-11-23 16:22:21 +00001943 // Simplify the initializer.
1944 if (GV->hasInitializer())
1945 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GV->getInitializer())) {
Mehdi Amini46a43552015-03-04 18:43:29 +00001946 auto &DL = M.getDataLayout();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001947 Constant *New = ConstantFoldConstantExpression(CE, DL, TLI);
Dan Gohman580b80d2009-11-23 16:22:21 +00001948 if (New && New != CE)
1949 GV->setInitializer(New);
1950 }
Rafael Espindolafc355bc2011-01-19 16:32:21 +00001951
David Majnemerdad0a642014-06-27 18:19:56 +00001952 if (GV->isDiscardableIfUnused()) {
1953 if (const Comdat *C = GV->getComdat())
David Majnemer1b3b70e2014-10-08 07:23:31 +00001954 if (NotDiscardableComdats.count(C) && !GV->hasLocalLinkage())
David Majnemerdad0a642014-06-27 18:19:56 +00001955 continue;
1956 Changed |= ProcessGlobal(GV, GVI);
1957 }
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001958 }
1959 return Changed;
1960}
1961
Jakub Staszak9525a772012-12-06 21:57:16 +00001962static inline bool
Chris Lattner0d71c4f2010-12-07 04:33:29 +00001963isSimpleEnoughValueToCommit(Constant *C,
Mehdi Amini46a43552015-03-04 18:43:29 +00001964 SmallPtrSetImpl<Constant *> &SimpleConstants,
1965 const DataLayout &DL);
Chris Lattner0d71c4f2010-12-07 04:33:29 +00001966
James Molloyea31ad32015-11-13 11:05:07 +00001967/// Return true if the specified constant can be handled by the code generator.
1968/// We don't want to generate something like:
Chris Lattner0d71c4f2010-12-07 04:33:29 +00001969/// void *X = &X/42;
1970/// because the code generator doesn't have a relocation that can handle that.
1971///
1972/// This function should be called if C was not found (but just got inserted)
1973/// in SimpleConstants to avoid having to rescan the same constants all the
1974/// time.
Mehdi Amini46a43552015-03-04 18:43:29 +00001975static bool
1976isSimpleEnoughValueToCommitHelper(Constant *C,
1977 SmallPtrSetImpl<Constant *> &SimpleConstants,
1978 const DataLayout &DL) {
David Majnemer6098b2f2014-06-26 03:02:19 +00001979 // Simple global addresses are supported, do not allow dllimport or
1980 // thread-local globals.
David Majnemer23fc9af2014-06-24 06:53:45 +00001981 if (auto *GV = dyn_cast<GlobalValue>(C))
David Majnemer6098b2f2014-06-26 03:02:19 +00001982 return !GV->hasDLLImportStorageClass() && !GV->isThreadLocal();
David Majnemer23fc9af2014-06-24 06:53:45 +00001983
1984 // Simple integer, undef, constant aggregate zero, etc are all supported.
1985 if (C->getNumOperands() == 0 || isa<BlockAddress>(C))
Chris Lattner0d71c4f2010-12-07 04:33:29 +00001986 return true;
Jakub Staszak9525a772012-12-06 21:57:16 +00001987
Chris Lattner0d71c4f2010-12-07 04:33:29 +00001988 // Aggregate values are safe if all their elements are.
1989 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C) ||
1990 isa<ConstantVector>(C)) {
Pete Cooper125ad172015-06-25 20:51:38 +00001991 for (Value *Op : C->operands())
1992 if (!isSimpleEnoughValueToCommit(cast<Constant>(Op), SimpleConstants, DL))
Chris Lattner0d71c4f2010-12-07 04:33:29 +00001993 return false;
Chris Lattner0d71c4f2010-12-07 04:33:29 +00001994 return true;
1995 }
Jakub Staszak9525a772012-12-06 21:57:16 +00001996
Chris Lattner0d71c4f2010-12-07 04:33:29 +00001997 // We don't know exactly what relocations are allowed in constant expressions,
1998 // so we allow &global+constantoffset, which is safe and uniformly supported
1999 // across targets.
2000 ConstantExpr *CE = cast<ConstantExpr>(C);
2001 switch (CE->getOpcode()) {
2002 case Instruction::BitCast:
Eli Friedman55fa49f32012-01-05 23:03:32 +00002003 // Bitcast is fine if the casted value is fine.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002004 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, DL);
Eli Friedman55fa49f32012-01-05 23:03:32 +00002005
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002006 case Instruction::IntToPtr:
2007 case Instruction::PtrToInt:
Eli Friedman55fa49f32012-01-05 23:03:32 +00002008 // int <=> ptr is fine if the int type is the same size as the
2009 // pointer type.
Mehdi Amini46a43552015-03-04 18:43:29 +00002010 if (DL.getTypeSizeInBits(CE->getType()) !=
2011 DL.getTypeSizeInBits(CE->getOperand(0)->getType()))
Eli Friedman55fa49f32012-01-05 23:03:32 +00002012 return false;
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002013 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, DL);
Jakub Staszak9525a772012-12-06 21:57:16 +00002014
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002015 // GEP is fine if it is simple + constant offset.
2016 case Instruction::GetElementPtr:
2017 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
2018 if (!isa<ConstantInt>(CE->getOperand(i)))
2019 return false;
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002020 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, DL);
Jakub Staszak9525a772012-12-06 21:57:16 +00002021
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002022 case Instruction::Add:
2023 // We allow simple+cst.
2024 if (!isa<ConstantInt>(CE->getOperand(1)))
2025 return false;
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002026 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, DL);
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002027 }
2028 return false;
2029}
2030
Jakub Staszak9525a772012-12-06 21:57:16 +00002031static inline bool
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002032isSimpleEnoughValueToCommit(Constant *C,
Mehdi Amini46a43552015-03-04 18:43:29 +00002033 SmallPtrSetImpl<Constant *> &SimpleConstants,
2034 const DataLayout &DL) {
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002035 // If we already checked this constant, we win.
David Blaikie70573dc2014-11-19 07:49:26 +00002036 if (!SimpleConstants.insert(C).second)
2037 return true;
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002038 // Check the constant.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002039 return isSimpleEnoughValueToCommitHelper(C, SimpleConstants, DL);
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002040}
2041
2042
James Molloyea31ad32015-11-13 11:05:07 +00002043/// Return true if this constant is simple enough for us to understand. In
2044/// particular, if it is a cast to anything other than from one pointer type to
2045/// another pointer type, we punt. We basically just support direct accesses to
2046/// globals and GEP's of globals. This should be kept up to date with
2047/// CommitValueTo.
Chris Lattner46b5c642009-11-06 04:27:31 +00002048static bool isSimpleEnoughPointerToCommit(Constant *C) {
Dan Gohman82e74752009-09-07 22:42:05 +00002049 // Conservatively, avoid aggregate types. This is because we don't
2050 // want to worry about them partially overlapping other stores.
2051 if (!cast<PointerType>(C->getType())->getElementType()->isSingleValueType())
2052 return false;
2053
Dan Gohmanf7f3fb12009-09-07 22:31:26 +00002054 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
David Majnemer23fc9af2014-06-24 06:53:45 +00002055 // Do not allow weak/*_odr/linkonce linkage or external globals.
Mikhail Glushenkov2072db22010-10-19 16:47:23 +00002056 return GV->hasUniqueInitializer();
Dan Gohmanf7f3fb12009-09-07 22:31:26 +00002057
Owen Anderson3e2f6cf2011-01-14 22:31:13 +00002058 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
Chris Lattner46af55e2005-09-26 06:52:44 +00002059 // Handle a constantexpr gep.
2060 if (CE->getOpcode() == Instruction::GetElementPtr &&
Dan Gohmanbeee35a2009-09-07 22:40:13 +00002061 isa<GlobalVariable>(CE->getOperand(0)) &&
2062 cast<GEPOperator>(CE)->isInBounds()) {
Chris Lattner46af55e2005-09-26 06:52:44 +00002063 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
Mikhail Glushenkov2072db22010-10-19 16:47:23 +00002064 // Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or
Dan Gohmanf7f3fb12009-09-07 22:31:26 +00002065 // external globals.
Mikhail Glushenkov2072db22010-10-19 16:47:23 +00002066 if (!GV->hasUniqueInitializer())
Dan Gohmanf7f3fb12009-09-07 22:31:26 +00002067 return false;
Dan Gohman161429f2009-09-07 22:44:55 +00002068
Dan Gohman161429f2009-09-07 22:44:55 +00002069 // The first index must be zero.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00002070 ConstantInt *CI = dyn_cast<ConstantInt>(*std::next(CE->op_begin()));
Dan Gohman161429f2009-09-07 22:44:55 +00002071 if (!CI || !CI->isZero()) return false;
Dan Gohman161429f2009-09-07 22:44:55 +00002072
2073 // The remaining indices must be compile-time known integers within the
Dan Gohman7190d482009-09-10 23:37:55 +00002074 // notional bounds of the corresponding static array types.
2075 if (!CE->isGEPWithNoNotionalOverIndexing())
2076 return false;
Dan Gohman161429f2009-09-07 22:44:55 +00002077
Dan Gohmane525d9d2009-10-05 16:36:26 +00002078 return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
Jakub Staszak9525a772012-12-06 21:57:16 +00002079
Owen Anderson9eb7cb482011-01-14 22:19:20 +00002080 // A constantexpr bitcast from a pointer to another pointer is a no-op,
2081 // and we know how to evaluate it by moving the bitcast from the pointer
2082 // operand to the value operand.
2083 } else if (CE->getOpcode() == Instruction::BitCast &&
Chris Lattner8b4952f2011-01-16 02:05:10 +00002084 isa<GlobalVariable>(CE->getOperand(0))) {
Owen Anderson9eb7cb482011-01-14 22:19:20 +00002085 // Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or
2086 // external globals.
Chris Lattner8b4952f2011-01-16 02:05:10 +00002087 return cast<GlobalVariable>(CE->getOperand(0))->hasUniqueInitializer();
Chris Lattner46af55e2005-09-26 06:52:44 +00002088 }
Owen Anderson3e2f6cf2011-01-14 22:31:13 +00002089 }
Jakub Staszak9525a772012-12-06 21:57:16 +00002090
Chris Lattner99e23fa2005-09-26 04:44:35 +00002091 return false;
2092}
2093
James Molloyea31ad32015-11-13 11:05:07 +00002094/// Evaluate a piece of a constantexpr store into a global initializer. This
2095/// returns 'Init' modified to reflect 'Val' stored into it. At this point, the
2096/// GEP operands of Addr [0, OpNo) have been stepped into.
Anthony Pesche92ae2d2015-07-22 22:26:54 +00002097static Constant *EvaluateStoreInto(Constant *Init, Constant *Val,
2098 ConstantExpr *Addr, unsigned OpNo) {
2099 // Base case of the recursion.
2100 if (OpNo == Addr->getNumOperands()) {
2101 assert(Val->getType() == Init->getType() && "Type mismatch!");
2102 return Val;
2103 }
2104
2105 SmallVector<Constant*, 32> Elts;
2106 if (StructType *STy = dyn_cast<StructType>(Init->getType())) {
2107 // Break up the constant into its elements.
2108 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
2109 Elts.push_back(Init->getAggregateElement(i));
2110
2111 // Replace the element that we are supposed to.
2112 ConstantInt *CU = cast<ConstantInt>(Addr->getOperand(OpNo));
2113 unsigned Idx = CU->getZExtValue();
2114 assert(Idx < STy->getNumElements() && "Struct index out of range!");
2115 Elts[Idx] = EvaluateStoreInto(Elts[Idx], Val, Addr, OpNo+1);
2116
2117 // Return the modified struct.
2118 return ConstantStruct::get(STy, Elts);
2119 }
2120
2121 ConstantInt *CI = cast<ConstantInt>(Addr->getOperand(OpNo));
2122 SequentialType *InitTy = cast<SequentialType>(Init->getType());
2123
2124 uint64_t NumElts;
2125 if (ArrayType *ATy = dyn_cast<ArrayType>(InitTy))
2126 NumElts = ATy->getNumElements();
2127 else
2128 NumElts = InitTy->getVectorNumElements();
2129
2130 // Break up the array into elements.
2131 for (uint64_t i = 0, e = NumElts; i != e; ++i)
2132 Elts.push_back(Init->getAggregateElement(i));
2133
2134 assert(CI->getZExtValue() < NumElts);
2135 Elts[CI->getZExtValue()] =
2136 EvaluateStoreInto(Elts[CI->getZExtValue()], Val, Addr, OpNo+1);
2137
2138 if (Init->getType()->isArrayTy())
2139 return ConstantArray::get(cast<ArrayType>(InitTy), Elts);
2140 return ConstantVector::get(Elts);
2141}
2142
James Molloyea31ad32015-11-13 11:05:07 +00002143/// We have decided that Addr (which satisfies the predicate
Anthony Pesche92ae2d2015-07-22 22:26:54 +00002144/// isSimpleEnoughPointerToCommit) should get Val as its value. Make it happen.
2145static void CommitValueTo(Constant *Val, Constant *Addr) {
2146 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Addr)) {
2147 assert(GV->hasInitializer());
2148 GV->setInitializer(Val);
2149 return;
2150 }
2151
2152 ConstantExpr *CE = cast<ConstantExpr>(Addr);
2153 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
2154 GV->setInitializer(EvaluateStoreInto(GV->getInitializer(), Val, CE, 2));
2155}
2156
Nick Lewycky60829a582012-02-20 03:25:59 +00002157namespace {
2158
James Molloyea31ad32015-11-13 11:05:07 +00002159/// This class evaluates LLVM IR, producing the Constant representing each SSA
2160/// instruction. Changes to global variables are stored in a mapping that can
2161/// be iterated over after the evaluation is complete. Once an evaluation call
2162/// fails, the evaluation object should not be reused.
Nick Lewycky60829a582012-02-20 03:25:59 +00002163class Evaluator {
Nick Lewycky73be5e32012-02-19 23:26:27 +00002164public:
Mehdi Amini46a43552015-03-04 18:43:29 +00002165 Evaluator(const DataLayout &DL, const TargetLibraryInfo *TLI)
2166 : DL(DL), TLI(TLI) {
Benjamin Kramer64425fe2014-05-03 15:50:37 +00002167 ValueStack.emplace_back();
Nick Lewycky73be5e32012-02-19 23:26:27 +00002168 }
2169
Nick Lewycky60829a582012-02-20 03:25:59 +00002170 ~Evaluator() {
David Blaikiebc442202014-04-21 20:49:36 +00002171 for (auto &Tmp : AllocaTmps)
Nick Lewycky73be5e32012-02-19 23:26:27 +00002172 // If there are still users of the alloca, the program is doing something
2173 // silly, e.g. storing the address of the alloca somewhere and using it
2174 // later. Since this is undefined, we'll just make it be null.
2175 if (!Tmp->use_empty())
2176 Tmp->replaceAllUsesWith(Constant::getNullValue(Tmp->getType()));
Nick Lewycky73be5e32012-02-19 23:26:27 +00002177 }
2178
James Molloyea31ad32015-11-13 11:05:07 +00002179 /// Evaluate a call to function F, returning true if successful, false if we
2180 /// can't evaluate it. ActualArgs contains the formal arguments for the
2181 /// function.
Nick Lewycky73be5e32012-02-19 23:26:27 +00002182 bool EvaluateFunction(Function *F, Constant *&RetVal,
2183 const SmallVectorImpl<Constant*> &ActualArgs);
2184
James Molloyea31ad32015-11-13 11:05:07 +00002185 /// Evaluate all instructions in block BB, returning true if successful, false
2186 /// if we can't evaluate it. NewBB returns the next BB that control flows
2187 /// into, or null upon return.
Nick Lewycky73be5e32012-02-19 23:26:27 +00002188 bool EvaluateBlock(BasicBlock::iterator CurInst, BasicBlock *&NextBB);
2189
2190 Constant *getVal(Value *V) {
2191 if (Constant *CV = dyn_cast<Constant>(V)) return CV;
Benjamin Kramer64425fe2014-05-03 15:50:37 +00002192 Constant *R = ValueStack.back().lookup(V);
Nick Lewycky73be5e32012-02-19 23:26:27 +00002193 assert(R && "Reference to an uncomputed value!");
2194 return R;
2195 }
2196
2197 void setVal(Value *V, Constant *C) {
Benjamin Kramer64425fe2014-05-03 15:50:37 +00002198 ValueStack.back()[V] = C;
Nick Lewycky73be5e32012-02-19 23:26:27 +00002199 }
2200
Anthony Pesche92ae2d2015-07-22 22:26:54 +00002201 const DenseMap<Constant*, Constant*> &getMutatedMemory() const {
2202 return MutatedMemory;
Nick Lewycky73be5e32012-02-19 23:26:27 +00002203 }
2204
Craig Topper71b7b682014-08-21 05:55:13 +00002205 const SmallPtrSetImpl<GlobalVariable*> &getInvariants() const {
Nick Lewycky73be5e32012-02-19 23:26:27 +00002206 return Invariants;
2207 }
2208
2209private:
2210 Constant *ComputeLoadResult(Constant *P);
2211
James Molloyea31ad32015-11-13 11:05:07 +00002212 /// As we compute SSA register values, we store their contents here. The back
2213 /// of the deque contains the current function and the stack contains the
2214 /// values in the calling frames.
Benjamin Kramer64425fe2014-05-03 15:50:37 +00002215 std::deque<DenseMap<Value*, Constant*>> ValueStack;
Nick Lewycky73be5e32012-02-19 23:26:27 +00002216
James Molloyea31ad32015-11-13 11:05:07 +00002217 /// This is used to detect recursion. In pathological situations we could hit
2218 /// exponential behavior, but at least there is nothing unbounded.
Nick Lewycky73be5e32012-02-19 23:26:27 +00002219 SmallVector<Function*, 4> CallStack;
2220
James Molloyea31ad32015-11-13 11:05:07 +00002221 /// For each store we execute, we update this map. Loads check this to get
2222 /// the most up-to-date value. If evaluation is successful, this state is
2223 /// committed to the process.
Anthony Pesche92ae2d2015-07-22 22:26:54 +00002224 DenseMap<Constant*, Constant*> MutatedMemory;
Nick Lewycky73be5e32012-02-19 23:26:27 +00002225
James Molloyea31ad32015-11-13 11:05:07 +00002226 /// To 'execute' an alloca, we create a temporary global variable to represent
2227 /// its body. This vector is needed so we can delete the temporary globals
2228 /// when we are done.
David Blaikiebc442202014-04-21 20:49:36 +00002229 SmallVector<std::unique_ptr<GlobalVariable>, 32> AllocaTmps;
Nick Lewycky73be5e32012-02-19 23:26:27 +00002230
James Molloyea31ad32015-11-13 11:05:07 +00002231 /// These global variables have been marked invariant by the static
2232 /// constructor.
Nick Lewycky73be5e32012-02-19 23:26:27 +00002233 SmallPtrSet<GlobalVariable*, 8> Invariants;
2234
James Molloyea31ad32015-11-13 11:05:07 +00002235 /// These are constants we have checked and know to be simple enough to live
2236 /// in a static initializer of a global.
Nick Lewycky73be5e32012-02-19 23:26:27 +00002237 SmallPtrSet<Constant*, 8> SimpleConstants;
2238
Mehdi Amini46a43552015-03-04 18:43:29 +00002239 const DataLayout &DL;
Nick Lewycky73be5e32012-02-19 23:26:27 +00002240 const TargetLibraryInfo *TLI;
2241};
2242
Nick Lewycky60829a582012-02-20 03:25:59 +00002243} // anonymous namespace
2244
James Molloyea31ad32015-11-13 11:05:07 +00002245/// Return the value that would be computed by a load from P after the stores
2246/// reflected by 'memory' have been performed. If we can't decide, return null.
Nick Lewycky60829a582012-02-20 03:25:59 +00002247Constant *Evaluator::ComputeLoadResult(Constant *P) {
Chris Lattner4b05c322005-09-26 05:15:37 +00002248 // If this memory location has been recently stored, use the stored value: it
2249 // is the most up-to-date.
Anthony Pesche92ae2d2015-07-22 22:26:54 +00002250 DenseMap<Constant*, Constant*>::const_iterator I = MutatedMemory.find(P);
2251 if (I != MutatedMemory.end()) return I->second;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002252
Chris Lattner4b05c322005-09-26 05:15:37 +00002253 // Access it.
2254 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(P)) {
Dan Gohman5d5bc6d2009-08-19 18:20:44 +00002255 if (GV->hasDefinitiveInitializer())
Chris Lattner4b05c322005-09-26 05:15:37 +00002256 return GV->getInitializer();
Craig Topperf40110f2014-04-25 05:29:35 +00002257 return nullptr;
Chris Lattner4b05c322005-09-26 05:15:37 +00002258 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002259
Chris Lattner46af55e2005-09-26 06:52:44 +00002260 // Handle a constantexpr getelementptr.
2261 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(P))
2262 if (CE->getOpcode() == Instruction::GetElementPtr &&
2263 isa<GlobalVariable>(CE->getOperand(0))) {
2264 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
Dan Gohman5d5bc6d2009-08-19 18:20:44 +00002265 if (GV->hasDefinitiveInitializer())
Dan Gohmane525d9d2009-10-05 16:36:26 +00002266 return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
Chris Lattner46af55e2005-09-26 06:52:44 +00002267 }
2268
Craig Topperf40110f2014-04-25 05:29:35 +00002269 return nullptr; // don't know how to evaluate.
Chris Lattner4b05c322005-09-26 05:15:37 +00002270}
2271
James Molloyea31ad32015-11-13 11:05:07 +00002272/// Evaluate all instructions in block BB, returning true if successful, false
2273/// if we can't evaluate it. NewBB returns the next BB that control flows into,
2274/// or null upon return.
Nick Lewycky60829a582012-02-20 03:25:59 +00002275bool Evaluator::EvaluateBlock(BasicBlock::iterator CurInst,
2276 BasicBlock *&NextBB) {
Chris Lattner99e23fa2005-09-26 04:44:35 +00002277 // This is the main evaluation loop.
2278 while (1) {
Craig Topperf40110f2014-04-25 05:29:35 +00002279 Constant *InstResult = nullptr;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002280
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002281 DEBUG(dbgs() << "Evaluating Instruction: " << *CurInst << "\n");
2282
Chris Lattner99e23fa2005-09-26 04:44:35 +00002283 if (StoreInst *SI = dyn_cast<StoreInst>(CurInst)) {
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002284 if (!SI->isSimple()) {
Michael Gottesman2a654272013-01-11 23:08:52 +00002285 DEBUG(dbgs() << "Store is not simple! Can not evaluate.\n");
2286 return false; // no volatile/atomic accesses.
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002287 }
Nick Lewycky73be5e32012-02-19 23:26:27 +00002288 Constant *Ptr = getVal(SI->getOperand(1));
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002289 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
Michael Gottesman2a654272013-01-11 23:08:52 +00002290 DEBUG(dbgs() << "Folding constant ptr expression: " << *Ptr);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002291 Ptr = ConstantFoldConstantExpression(CE, DL, TLI);
Michael Gottesman2a654272013-01-11 23:08:52 +00002292 DEBUG(dbgs() << "; To: " << *Ptr << "\n");
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002293 }
2294 if (!isSimpleEnoughPointerToCommit(Ptr)) {
Chris Lattner99e23fa2005-09-26 04:44:35 +00002295 // If this is too complex for us to commit, reject it.
Michael Gottesman2a654272013-01-11 23:08:52 +00002296 DEBUG(dbgs() << "Pointer is too complex for us to evaluate store.");
Chris Lattner65a3a092005-09-27 04:45:34 +00002297 return false;
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002298 }
Jakub Staszak9525a772012-12-06 21:57:16 +00002299
Nick Lewycky73be5e32012-02-19 23:26:27 +00002300 Constant *Val = getVal(SI->getOperand(0));
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002301
2302 // If this might be too difficult for the backend to handle (e.g. the addr
2303 // of one global variable divided by another) then we can't commit it.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002304 if (!isSimpleEnoughValueToCommit(Val, SimpleConstants, DL)) {
Michael Gottesman2a654272013-01-11 23:08:52 +00002305 DEBUG(dbgs() << "Store value is too complex to evaluate store. " << *Val
2306 << "\n");
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002307 return false;
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002308 }
Jakub Staszak9525a772012-12-06 21:57:16 +00002309
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002310 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
Owen Anderson9eb7cb482011-01-14 22:19:20 +00002311 if (CE->getOpcode() == Instruction::BitCast) {
Michael Gottesman2a654272013-01-11 23:08:52 +00002312 DEBUG(dbgs() << "Attempting to resolve bitcast on constant ptr.\n");
Owen Anderson9eb7cb482011-01-14 22:19:20 +00002313 // If we're evaluating a store through a bitcast, then we need
2314 // to pull the bitcast off the pointer type and push it onto the
2315 // stored value.
Chris Lattner8b4952f2011-01-16 02:05:10 +00002316 Ptr = CE->getOperand(0);
Jakub Staszak9525a772012-12-06 21:57:16 +00002317
Nick Lewycky239fdf02012-02-06 08:24:44 +00002318 Type *NewTy = cast<PointerType>(Ptr->getType())->getElementType();
Jakub Staszak9525a772012-12-06 21:57:16 +00002319
Owen Anderson4e54efd2011-01-16 04:33:33 +00002320 // In order to push the bitcast onto the stored value, a bitcast
2321 // from NewTy to Val's type must be legal. If it's not, we can try
2322 // introspecting NewTy to find a legal conversion.
2323 while (!Val->getType()->canLosslesslyBitCastTo(NewTy)) {
2324 // If NewTy is a struct, we can convert the pointer to the struct
2325 // into a pointer to its first member.
2326 // FIXME: This could be extended to support arrays as well.
Chris Lattner229907c2011-07-18 04:54:35 +00002327 if (StructType *STy = dyn_cast<StructType>(NewTy)) {
Owen Anderson4e54efd2011-01-16 04:33:33 +00002328 NewTy = STy->getTypeAtIndex(0U);
2329
Nick Lewycky239fdf02012-02-06 08:24:44 +00002330 IntegerType *IdxTy = IntegerType::get(NewTy->getContext(), 32);
Owen Anderson4e54efd2011-01-16 04:33:33 +00002331 Constant *IdxZero = ConstantInt::get(IdxTy, 0, false);
2332 Constant * const IdxList[] = {IdxZero, IdxZero};
2333
David Blaikie4a2e73b2015-04-02 18:55:32 +00002334 Ptr = ConstantExpr::getGetElementPtr(nullptr, Ptr, IdxList);
Nick Lewycky9d0da182012-02-21 22:08:06 +00002335 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002336 Ptr = ConstantFoldConstantExpression(CE, DL, TLI);
Nick Lewycky9d0da182012-02-21 22:08:06 +00002337
Owen Anderson4e54efd2011-01-16 04:33:33 +00002338 // If we can't improve the situation by introspecting NewTy,
2339 // we have to give up.
2340 } else {
Michael Gottesman2a654272013-01-11 23:08:52 +00002341 DEBUG(dbgs() << "Failed to bitcast constant ptr, can not "
2342 "evaluate.\n");
Nick Lewycky239fdf02012-02-06 08:24:44 +00002343 return false;
Owen Anderson4e54efd2011-01-16 04:33:33 +00002344 }
Owen Anderson9eb7cb482011-01-14 22:19:20 +00002345 }
Jakub Staszak9525a772012-12-06 21:57:16 +00002346
Owen Anderson4e54efd2011-01-16 04:33:33 +00002347 // If we found compatible types, go ahead and push the bitcast
2348 // onto the stored value.
Owen Anderson9eb7cb482011-01-14 22:19:20 +00002349 Val = ConstantExpr::getBitCast(Val, NewTy);
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002350
Michael Gottesman2a654272013-01-11 23:08:52 +00002351 DEBUG(dbgs() << "Evaluated bitcast: " << *Val << "\n");
Owen Anderson9eb7cb482011-01-14 22:19:20 +00002352 }
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002353 }
Jakub Staszak9525a772012-12-06 21:57:16 +00002354
Anthony Pesche92ae2d2015-07-22 22:26:54 +00002355 MutatedMemory[Ptr] = Val;
Chris Lattner99e23fa2005-09-26 04:44:35 +00002356 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CurInst)) {
Owen Anderson487375e2009-07-29 18:55:55 +00002357 InstResult = ConstantExpr::get(BO->getOpcode(),
Nick Lewycky73be5e32012-02-19 23:26:27 +00002358 getVal(BO->getOperand(0)),
2359 getVal(BO->getOperand(1)));
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002360 DEBUG(dbgs() << "Found a BinaryOperator! Simplifying: " << *InstResult
Michael Gottesman2a654272013-01-11 23:08:52 +00002361 << "\n");
Reid Spencer266e42b2006-12-23 06:05:41 +00002362 } else if (CmpInst *CI = dyn_cast<CmpInst>(CurInst)) {
Owen Anderson487375e2009-07-29 18:55:55 +00002363 InstResult = ConstantExpr::getCompare(CI->getPredicate(),
Nick Lewycky73be5e32012-02-19 23:26:27 +00002364 getVal(CI->getOperand(0)),
2365 getVal(CI->getOperand(1)));
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002366 DEBUG(dbgs() << "Found a CmpInst! Simplifying: " << *InstResult
Michael Gottesman2a654272013-01-11 23:08:52 +00002367 << "\n");
Chris Lattner99e23fa2005-09-26 04:44:35 +00002368 } else if (CastInst *CI = dyn_cast<CastInst>(CurInst)) {
Owen Anderson487375e2009-07-29 18:55:55 +00002369 InstResult = ConstantExpr::getCast(CI->getOpcode(),
Nick Lewycky73be5e32012-02-19 23:26:27 +00002370 getVal(CI->getOperand(0)),
Chris Lattner99e23fa2005-09-26 04:44:35 +00002371 CI->getType());
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002372 DEBUG(dbgs() << "Found a Cast! Simplifying: " << *InstResult
Michael Gottesman2a654272013-01-11 23:08:52 +00002373 << "\n");
Chris Lattner99e23fa2005-09-26 04:44:35 +00002374 } else if (SelectInst *SI = dyn_cast<SelectInst>(CurInst)) {
Nick Lewycky73be5e32012-02-19 23:26:27 +00002375 InstResult = ConstantExpr::getSelect(getVal(SI->getOperand(0)),
2376 getVal(SI->getOperand(1)),
2377 getVal(SI->getOperand(2)));
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002378 DEBUG(dbgs() << "Found a Select! Simplifying: " << *InstResult
Michael Gottesman2a654272013-01-11 23:08:52 +00002379 << "\n");
David Majnemerfe8c7542014-08-08 05:50:43 +00002380 } else if (auto *EVI = dyn_cast<ExtractValueInst>(CurInst)) {
2381 InstResult = ConstantExpr::getExtractValue(
2382 getVal(EVI->getAggregateOperand()), EVI->getIndices());
2383 DEBUG(dbgs() << "Found an ExtractValueInst! Simplifying: " << *InstResult
2384 << "\n");
2385 } else if (auto *IVI = dyn_cast<InsertValueInst>(CurInst)) {
2386 InstResult = ConstantExpr::getInsertValue(
2387 getVal(IVI->getAggregateOperand()),
2388 getVal(IVI->getInsertedValueOperand()), IVI->getIndices());
2389 DEBUG(dbgs() << "Found an InsertValueInst! Simplifying: " << *InstResult
2390 << "\n");
Chris Lattner4b05c322005-09-26 05:15:37 +00002391 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurInst)) {
Nick Lewycky73be5e32012-02-19 23:26:27 +00002392 Constant *P = getVal(GEP->getOperand(0));
Chris Lattnerf96f4a82007-01-31 04:40:53 +00002393 SmallVector<Constant*, 8> GEPOps;
Gabor Greif3a9fba52008-05-29 01:59:18 +00002394 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end();
2395 i != e; ++i)
Nick Lewycky73be5e32012-02-19 23:26:27 +00002396 GEPOps.push_back(getVal(*i));
Jay Foad2f5fc8c2011-07-21 15:15:37 +00002397 InstResult =
David Blaikie4a2e73b2015-04-02 18:55:32 +00002398 ConstantExpr::getGetElementPtr(GEP->getSourceElementType(), P, GEPOps,
2399 cast<GEPOperator>(GEP)->isInBounds());
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002400 DEBUG(dbgs() << "Found a GEP! Simplifying: " << *InstResult
Michael Gottesman2a654272013-01-11 23:08:52 +00002401 << "\n");
Chris Lattner4b05c322005-09-26 05:15:37 +00002402 } else if (LoadInst *LI = dyn_cast<LoadInst>(CurInst)) {
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002403
2404 if (!LI->isSimple()) {
Michael Gottesman2a654272013-01-11 23:08:52 +00002405 DEBUG(dbgs() << "Found a Load! Not a simple load, can not evaluate.\n");
2406 return false; // no volatile/atomic accesses.
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002407 }
2408
Nick Lewycky9d0da182012-02-21 22:08:06 +00002409 Constant *Ptr = getVal(LI->getOperand(0));
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002410 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002411 Ptr = ConstantFoldConstantExpression(CE, DL, TLI);
Michael Gottesman2a654272013-01-11 23:08:52 +00002412 DEBUG(dbgs() << "Found a constant pointer expression, constant "
2413 "folding: " << *Ptr << "\n");
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002414 }
Nick Lewycky9d0da182012-02-21 22:08:06 +00002415 InstResult = ComputeLoadResult(Ptr);
Craig Topperf40110f2014-04-25 05:29:35 +00002416 if (!InstResult) {
Michael Gottesman2a654272013-01-11 23:08:52 +00002417 DEBUG(dbgs() << "Failed to compute load result. Can not evaluate load."
2418 "\n");
2419 return false; // Could not evaluate load.
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002420 }
2421
2422 DEBUG(dbgs() << "Evaluated load: " << *InstResult << "\n");
Chris Lattner6bf2cd52005-09-26 17:07:09 +00002423 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(CurInst)) {
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002424 if (AI->isArrayAllocation()) {
Michael Gottesman2a654272013-01-11 23:08:52 +00002425 DEBUG(dbgs() << "Found an array alloca. Can not evaluate.\n");
2426 return false; // Cannot handle array allocs.
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002427 }
Chris Lattner229907c2011-07-18 04:54:35 +00002428 Type *Ty = AI->getType()->getElementType();
David Blaikiebc442202014-04-21 20:49:36 +00002429 AllocaTmps.push_back(
2430 make_unique<GlobalVariable>(Ty, false, GlobalValue::InternalLinkage,
2431 UndefValue::get(Ty), AI->getName()));
2432 InstResult = AllocaTmps.back().get();
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002433 DEBUG(dbgs() << "Found an alloca. Result: " << *InstResult << "\n");
Nick Lewyckyc1572e42012-02-12 05:09:35 +00002434 } else if (isa<CallInst>(CurInst) || isa<InvokeInst>(CurInst)) {
Duncan P. N. Exon Smith17323402015-10-13 17:51:03 +00002435 CallSite CS(&*CurInst);
Devang Patel04852aa2009-03-09 23:04:12 +00002436
2437 // Debug info can safely be ignored here.
Nick Lewyckyc1572e42012-02-12 05:09:35 +00002438 if (isa<DbgInfoIntrinsic>(CS.getInstruction())) {
Michael Gottesman2a654272013-01-11 23:08:52 +00002439 DEBUG(dbgs() << "Ignoring debug info.\n");
Devang Patel04852aa2009-03-09 23:04:12 +00002440 ++CurInst;
2441 continue;
2442 }
2443
Chris Lattnerfd2e13b2006-07-07 21:37:01 +00002444 // Cannot handle inline asm.
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002445 if (isa<InlineAsm>(CS.getCalledValue())) {
Michael Gottesman2a654272013-01-11 23:08:52 +00002446 DEBUG(dbgs() << "Found inline asm, can not evaluate.\n");
2447 return false;
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002448 }
Chris Lattnerfd2e13b2006-07-07 21:37:01 +00002449
Nick Lewycky68f9f9d2012-02-17 06:59:21 +00002450 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CS.getInstruction())) {
2451 if (MemSetInst *MSI = dyn_cast<MemSetInst>(II)) {
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002452 if (MSI->isVolatile()) {
Michael Gottesman2a654272013-01-11 23:08:52 +00002453 DEBUG(dbgs() << "Can not optimize a volatile memset " <<
2454 "intrinsic.\n");
2455 return false;
2456 }
Nick Lewycky73be5e32012-02-19 23:26:27 +00002457 Constant *Ptr = getVal(MSI->getDest());
2458 Constant *Val = getVal(MSI->getValue());
2459 Constant *DestVal = ComputeLoadResult(getVal(Ptr));
Nick Lewycky68f9f9d2012-02-17 06:59:21 +00002460 if (Val->isNullValue() && DestVal && DestVal->isNullValue()) {
2461 // This memset is a no-op.
Michael Gottesman2a654272013-01-11 23:08:52 +00002462 DEBUG(dbgs() << "Ignoring no-op memset.\n");
Nick Lewycky68f9f9d2012-02-17 06:59:21 +00002463 ++CurInst;
2464 continue;
2465 }
2466 }
2467
2468 if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
2469 II->getIntrinsicID() == Intrinsic::lifetime_end) {
Michael Gottesman2a654272013-01-11 23:08:52 +00002470 DEBUG(dbgs() << "Ignoring lifetime intrinsic.\n");
Nick Lewycky68f9f9d2012-02-17 06:59:21 +00002471 ++CurInst;
2472 continue;
2473 }
2474
2475 if (II->getIntrinsicID() == Intrinsic::invariant_start) {
2476 // We don't insert an entry into Values, as it doesn't have a
2477 // meaningful return value.
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002478 if (!II->use_empty()) {
Alp Tokerf907b892013-12-05 05:44:44 +00002479 DEBUG(dbgs() << "Found unused invariant_start. Can't evaluate.\n");
Nick Lewycky68f9f9d2012-02-17 06:59:21 +00002480 return false;
Michael Gottesman2a654272013-01-11 23:08:52 +00002481 }
Nick Lewycky68f9f9d2012-02-17 06:59:21 +00002482 ConstantInt *Size = cast<ConstantInt>(II->getArgOperand(0));
Nick Lewycky519561f2012-02-20 23:32:26 +00002483 Value *PtrArg = getVal(II->getArgOperand(1));
2484 Value *Ptr = PtrArg->stripPointerCasts();
2485 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr)) {
2486 Type *ElemTy = cast<PointerType>(GV->getType())->getElementType();
Mehdi Amini46a43552015-03-04 18:43:29 +00002487 if (!Size->isAllOnesValue() &&
Nick Lewycky519561f2012-02-20 23:32:26 +00002488 Size->getValue().getLimitedValue() >=
Mehdi Amini46a43552015-03-04 18:43:29 +00002489 DL.getTypeStoreSize(ElemTy)) {
Nick Lewycky68f9f9d2012-02-17 06:59:21 +00002490 Invariants.insert(GV);
Michael Gottesman2a654272013-01-11 23:08:52 +00002491 DEBUG(dbgs() << "Found a global var that is an invariant: " << *GV
2492 << "\n");
2493 } else {
2494 DEBUG(dbgs() << "Found a global var, but can not treat it as an "
2495 "invariant.\n");
2496 }
Nick Lewycky68f9f9d2012-02-17 06:59:21 +00002497 }
2498 // Continue even if we do nothing.
Nick Lewyckya3bb03e2011-05-29 18:41:56 +00002499 ++CurInst;
2500 continue;
Piotr Padlewski4e7f7522015-08-25 01:34:15 +00002501 } else if (II->getIntrinsicID() == Intrinsic::assume) {
2502 DEBUG(dbgs() << "Skipping assume intrinsic.\n");
2503 ++CurInst;
2504 continue;
Nick Lewyckya3bb03e2011-05-29 18:41:56 +00002505 }
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002506
Michael Gottesman2a654272013-01-11 23:08:52 +00002507 DEBUG(dbgs() << "Unknown intrinsic. Can not evaluate.\n");
Nick Lewyckya3bb03e2011-05-29 18:41:56 +00002508 return false;
2509 }
2510
Chris Lattner65a3a092005-09-27 04:45:34 +00002511 // Resolve function pointers.
Nick Lewycky73be5e32012-02-19 23:26:27 +00002512 Function *Callee = dyn_cast<Function>(getVal(CS.getCalledValue()));
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002513 if (!Callee || Callee->mayBeOverridden()) {
Michael Gottesman2a654272013-01-11 23:08:52 +00002514 DEBUG(dbgs() << "Can not resolve function pointer.\n");
Nick Lewyckyc1572e42012-02-12 05:09:35 +00002515 return false; // Cannot resolve.
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002516 }
Chris Lattner3d27e7f2005-09-27 05:02:43 +00002517
Duncan Sandsc4ce58d82009-08-17 14:33:27 +00002518 SmallVector<Constant*, 8> Formals;
Nick Lewyckyc1572e42012-02-12 05:09:35 +00002519 for (User::op_iterator i = CS.arg_begin(), e = CS.arg_end(); i != e; ++i)
Nick Lewycky73be5e32012-02-19 23:26:27 +00002520 Formals.push_back(getVal(*i));
Duncan Sandsc4ce58d82009-08-17 14:33:27 +00002521
Reid Spencer5301e7c2007-01-30 20:08:39 +00002522 if (Callee->isDeclaration()) {
Chris Lattner3d27e7f2005-09-27 05:02:43 +00002523 // If this is a function we can constant fold, do it.
Chad Rosiere6de63d2011-12-01 21:29:16 +00002524 if (Constant *C = ConstantFoldCall(Callee, Formals, TLI)) {
Chris Lattner3d27e7f2005-09-27 05:02:43 +00002525 InstResult = C;
Michael Gottesman2a654272013-01-11 23:08:52 +00002526 DEBUG(dbgs() << "Constant folded function call. Result: " <<
2527 *InstResult << "\n");
Chris Lattner3d27e7f2005-09-27 05:02:43 +00002528 } else {
Michael Gottesman2a654272013-01-11 23:08:52 +00002529 DEBUG(dbgs() << "Can not constant fold function call.\n");
Chris Lattner3d27e7f2005-09-27 05:02:43 +00002530 return false;
2531 }
2532 } else {
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002533 if (Callee->getFunctionType()->isVarArg()) {
Michael Gottesman2a654272013-01-11 23:08:52 +00002534 DEBUG(dbgs() << "Can not constant fold vararg function call.\n");
Chris Lattner3d27e7f2005-09-27 05:02:43 +00002535 return false;
Michael Gottesman2a654272013-01-11 23:08:52 +00002536 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002537
Craig Topperf40110f2014-04-25 05:29:35 +00002538 Constant *RetVal = nullptr;
Chris Lattner3d27e7f2005-09-27 05:02:43 +00002539 // Execute the call, if successful, use the return value.
Benjamin Kramer64425fe2014-05-03 15:50:37 +00002540 ValueStack.emplace_back();
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002541 if (!EvaluateFunction(Callee, RetVal, Formals)) {
Michael Gottesman2a654272013-01-11 23:08:52 +00002542 DEBUG(dbgs() << "Failed to evaluate function.\n");
Chris Lattner3d27e7f2005-09-27 05:02:43 +00002543 return false;
Michael Gottesman2a654272013-01-11 23:08:52 +00002544 }
David Blaikiebc442202014-04-21 20:49:36 +00002545 ValueStack.pop_back();
Chris Lattner3d27e7f2005-09-27 05:02:43 +00002546 InstResult = RetVal;
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002547
Craig Topperf40110f2014-04-25 05:29:35 +00002548 if (InstResult) {
Michael Gottesman2a654272013-01-11 23:08:52 +00002549 DEBUG(dbgs() << "Successfully evaluated function. Result: " <<
2550 InstResult << "\n\n");
2551 } else {
2552 DEBUG(dbgs() << "Successfully evaluated function. Result: 0\n\n");
2553 }
Chris Lattner3d27e7f2005-09-27 05:02:43 +00002554 }
Reid Spencerde46e482006-11-02 20:25:50 +00002555 } else if (isa<TerminatorInst>(CurInst)) {
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002556 DEBUG(dbgs() << "Found a terminator instruction.\n");
2557
Chris Lattner3e9ea5f2005-09-26 04:57:38 +00002558 if (BranchInst *BI = dyn_cast<BranchInst>(CurInst)) {
2559 if (BI->isUnconditional()) {
Nick Lewycky239fdf02012-02-06 08:24:44 +00002560 NextBB = BI->getSuccessor(0);
Chris Lattner3e9ea5f2005-09-26 04:57:38 +00002561 } else {
Zhou Sheng75b871f2007-01-11 12:24:14 +00002562 ConstantInt *Cond =
Nick Lewycky73be5e32012-02-19 23:26:27 +00002563 dyn_cast<ConstantInt>(getVal(BI->getCondition()));
Chris Lattner15649082007-01-12 18:30:11 +00002564 if (!Cond) return false; // Cannot determine.
Zhou Sheng75b871f2007-01-11 12:24:14 +00002565
Nick Lewycky239fdf02012-02-06 08:24:44 +00002566 NextBB = BI->getSuccessor(!Cond->getZExtValue());
Chris Lattner3e9ea5f2005-09-26 04:57:38 +00002567 }
2568 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(CurInst)) {
2569 ConstantInt *Val =
Nick Lewycky73be5e32012-02-19 23:26:27 +00002570 dyn_cast<ConstantInt>(getVal(SI->getCondition()));
Chris Lattner65a3a092005-09-27 04:45:34 +00002571 if (!Val) return false; // Cannot determine.
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00002572 NextBB = SI->findCaseValue(Val).getCaseSuccessor();
Chris Lattner31274882009-10-29 05:51:50 +00002573 } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(CurInst)) {
Nick Lewycky73be5e32012-02-19 23:26:27 +00002574 Value *Val = getVal(IBI->getAddress())->stripPointerCasts();
Chris Lattner31274882009-10-29 05:51:50 +00002575 if (BlockAddress *BA = dyn_cast<BlockAddress>(Val))
Nick Lewycky239fdf02012-02-06 08:24:44 +00002576 NextBB = BA->getBasicBlock();
Chris Lattneraa99c942009-11-01 01:27:45 +00002577 else
2578 return false; // Cannot determine.
Nick Lewycky239fdf02012-02-06 08:24:44 +00002579 } else if (isa<ReturnInst>(CurInst)) {
Craig Topperf40110f2014-04-25 05:29:35 +00002580 NextBB = nullptr;
Chris Lattner3e9ea5f2005-09-26 04:57:38 +00002581 } else {
Bill Wendlingf891bf82011-07-31 06:30:59 +00002582 // invoke, unwind, resume, unreachable.
Michael Gottesman2a654272013-01-11 23:08:52 +00002583 DEBUG(dbgs() << "Can not handle terminator.");
Chris Lattner65a3a092005-09-27 04:45:34 +00002584 return false; // Cannot handle this terminator.
Chris Lattner3e9ea5f2005-09-26 04:57:38 +00002585 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002586
Nick Lewycky239fdf02012-02-06 08:24:44 +00002587 // We succeeded at evaluating this block!
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002588 DEBUG(dbgs() << "Successfully evaluated block.\n");
Nick Lewycky239fdf02012-02-06 08:24:44 +00002589 return true;
Chris Lattner99e23fa2005-09-26 04:44:35 +00002590 } else {
Chris Lattner99e23fa2005-09-26 04:44:35 +00002591 // Did not know how to evaluate this!
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002592 DEBUG(dbgs() << "Failed to evaluate block due to unhandled instruction."
Michael Gottesman2a654272013-01-11 23:08:52 +00002593 "\n");
Chris Lattner65a3a092005-09-27 04:45:34 +00002594 return false;
Chris Lattner99e23fa2005-09-26 04:44:35 +00002595 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002596
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002597 if (!CurInst->use_empty()) {
2598 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(InstResult))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002599 InstResult = ConstantFoldConstantExpression(CE, DL, TLI);
Jakub Staszak9525a772012-12-06 21:57:16 +00002600
Duncan P. N. Exon Smith17323402015-10-13 17:51:03 +00002601 setVal(&*CurInst, InstResult);
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002602 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002603
Dan Gohmaneab06fa2012-03-13 18:01:37 +00002604 // If we just processed an invoke, we finished evaluating the block.
2605 if (InvokeInst *II = dyn_cast<InvokeInst>(CurInst)) {
2606 NextBB = II->getNormalDest();
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002607 DEBUG(dbgs() << "Found an invoke instruction. Finished Block.\n\n");
Dan Gohmaneab06fa2012-03-13 18:01:37 +00002608 return true;
2609 }
2610
Chris Lattner99e23fa2005-09-26 04:44:35 +00002611 // Advance program counter.
2612 ++CurInst;
2613 }
Chris Lattnerda1889b2005-09-27 04:27:01 +00002614}
2615
James Molloyea31ad32015-11-13 11:05:07 +00002616/// Evaluate a call to function F, returning true if successful, false if we
2617/// can't evaluate it. ActualArgs contains the formal arguments for the
2618/// function.
Nick Lewycky60829a582012-02-20 03:25:59 +00002619bool Evaluator::EvaluateFunction(Function *F, Constant *&RetVal,
2620 const SmallVectorImpl<Constant*> &ActualArgs) {
Nick Lewycky239fdf02012-02-06 08:24:44 +00002621 // Check to see if this function is already executing (recursion). If so,
2622 // bail out. TODO: we might want to accept limited recursion.
2623 if (std::find(CallStack.begin(), CallStack.end(), F) != CallStack.end())
2624 return false;
2625
2626 CallStack.push_back(F);
2627
Nick Lewycky239fdf02012-02-06 08:24:44 +00002628 // Initialize arguments to the incoming values specified.
2629 unsigned ArgNo = 0;
2630 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); AI != E;
2631 ++AI, ++ArgNo)
Duncan P. N. Exon Smith17323402015-10-13 17:51:03 +00002632 setVal(&*AI, ActualArgs[ArgNo]);
Nick Lewycky239fdf02012-02-06 08:24:44 +00002633
2634 // ExecutedBlocks - We only handle non-looping, non-recursive code. As such,
2635 // we can only evaluate any one basic block at most once. This set keeps
2636 // track of what we have executed so we can detect recursive cases etc.
2637 SmallPtrSet<BasicBlock*, 32> ExecutedBlocks;
2638
2639 // CurBB - The current basic block we're evaluating.
Duncan P. N. Exon Smith17323402015-10-13 17:51:03 +00002640 BasicBlock *CurBB = &F->front();
Nick Lewycky239fdf02012-02-06 08:24:44 +00002641
Nick Lewycky4231c412012-02-12 00:47:24 +00002642 BasicBlock::iterator CurInst = CurBB->begin();
2643
Nick Lewycky239fdf02012-02-06 08:24:44 +00002644 while (1) {
Craig Topperf40110f2014-04-25 05:29:35 +00002645 BasicBlock *NextBB = nullptr; // Initialized to avoid compiler warnings.
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002646 DEBUG(dbgs() << "Trying to evaluate BB: " << *CurBB << "\n");
2647
Nick Lewycky73be5e32012-02-19 23:26:27 +00002648 if (!EvaluateBlock(CurInst, NextBB))
Nick Lewycky239fdf02012-02-06 08:24:44 +00002649 return false;
2650
Craig Topperf40110f2014-04-25 05:29:35 +00002651 if (!NextBB) {
Nick Lewycky239fdf02012-02-06 08:24:44 +00002652 // Successfully running until there's no next block means that we found
2653 // the return. Fill it the return value and pop the call stack.
2654 ReturnInst *RI = cast<ReturnInst>(CurBB->getTerminator());
2655 if (RI->getNumOperands())
Nick Lewycky73be5e32012-02-19 23:26:27 +00002656 RetVal = getVal(RI->getOperand(0));
Nick Lewycky239fdf02012-02-06 08:24:44 +00002657 CallStack.pop_back();
2658 return true;
2659 }
2660
2661 // Okay, we succeeded in evaluating this control flow. See if we have
2662 // executed the new block before. If so, we have a looping function,
2663 // which we cannot evaluate in reasonable time.
David Blaikie70573dc2014-11-19 07:49:26 +00002664 if (!ExecutedBlocks.insert(NextBB).second)
Nick Lewycky239fdf02012-02-06 08:24:44 +00002665 return false; // looped!
2666
2667 // Okay, we have never been in this block before. Check to see if there
2668 // are any PHI nodes. If so, evaluate them with information about where
2669 // we came from.
Craig Topperf40110f2014-04-25 05:29:35 +00002670 PHINode *PN = nullptr;
Nick Lewycky4231c412012-02-12 00:47:24 +00002671 for (CurInst = NextBB->begin();
2672 (PN = dyn_cast<PHINode>(CurInst)); ++CurInst)
Nick Lewycky73be5e32012-02-19 23:26:27 +00002673 setVal(PN, getVal(PN->getIncomingValueForBlock(CurBB)));
Nick Lewycky239fdf02012-02-06 08:24:44 +00002674
2675 // Advance to the next block.
2676 CurBB = NextBB;
2677 }
2678}
2679
James Molloyea31ad32015-11-13 11:05:07 +00002680/// Evaluate static constructors in the function, if we can. Return true if we
2681/// can, false otherwise.
Mehdi Amini46a43552015-03-04 18:43:29 +00002682static bool EvaluateStaticConstructor(Function *F, const DataLayout &DL,
Chad Rosiere6de63d2011-12-01 21:29:16 +00002683 const TargetLibraryInfo *TLI) {
Chris Lattnerda1889b2005-09-27 04:27:01 +00002684 // Call the function.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002685 Evaluator Eval(DL, TLI);
Chris Lattner65a3a092005-09-27 04:45:34 +00002686 Constant *RetValDummy;
Nick Lewycky73be5e32012-02-19 23:26:27 +00002687 bool EvalSuccess = Eval.EvaluateFunction(F, RetValDummy,
2688 SmallVector<Constant*, 0>());
Jakub Staszak9525a772012-12-06 21:57:16 +00002689
Chris Lattnerda1889b2005-09-27 04:27:01 +00002690 if (EvalSuccess) {
Nico Weber4b2acde2014-05-02 18:35:25 +00002691 ++NumCtorsEvaluated;
2692
Chris Lattner6bf2cd52005-09-26 17:07:09 +00002693 // We succeeded at evaluation: commit the result.
David Greene44cb8ad2010-01-05 01:28:05 +00002694 DEBUG(dbgs() << "FULLY EVALUATED GLOBAL CTOR FUNCTION '"
Anthony Pesche92ae2d2015-07-22 22:26:54 +00002695 << F->getName() << "' to " << Eval.getMutatedMemory().size()
2696 << " stores.\n");
2697 for (DenseMap<Constant*, Constant*>::const_iterator I =
2698 Eval.getMutatedMemory().begin(), E = Eval.getMutatedMemory().end();
2699 I != E; ++I)
2700 CommitValueTo(I->second, I->first);
Craig Topper46276792014-08-24 23:23:06 +00002701 for (GlobalVariable *GV : Eval.getInvariants())
2702 GV->setConstant(true);
Chris Lattner6bf2cd52005-09-26 17:07:09 +00002703 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002704
Chris Lattnerda1889b2005-09-27 04:27:01 +00002705 return EvalSuccess;
Chris Lattner99e23fa2005-09-26 04:44:35 +00002706}
2707
Benjamin Krameradf1ea82014-03-07 21:52:38 +00002708static int compareNames(Constant *const *A, Constant *const *B) {
Sean Silvaace78182015-09-28 19:02:11 +00002709 return (*A)->stripPointerCasts()->getName().compare(
2710 (*B)->stripPointerCasts()->getName());
Benjamin Krameradf1ea82014-03-07 21:52:38 +00002711}
2712
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002713static void setUsedInitializer(GlobalVariable &V,
Craig Topper97ebe532014-08-19 07:44:27 +00002714 const SmallPtrSet<GlobalValue *, 8> &Init) {
Rafael Espindolac2bb73f2013-07-20 23:33:15 +00002715 if (Init.empty()) {
2716 V.eraseFromParent();
2717 return;
2718 }
2719
Matt Arsenaultda1deab2014-01-02 19:53:49 +00002720 // Type of pointer to the array of pointers.
2721 PointerType *Int8PtrTy = Type::getInt8PtrTy(V.getContext(), 0);
Rafael Espindola00752162013-05-09 17:22:59 +00002722
Matt Arsenaultda1deab2014-01-02 19:53:49 +00002723 SmallVector<llvm::Constant *, 8> UsedArray;
Craig Topper71b7b682014-08-21 05:55:13 +00002724 for (GlobalValue *GV : Init) {
Matt Arsenaultda1deab2014-01-02 19:53:49 +00002725 Constant *Cast
Craig Topper71b7b682014-08-21 05:55:13 +00002726 = ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, Int8PtrTy);
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002727 UsedArray.push_back(Cast);
Rafael Espindola00752162013-05-09 17:22:59 +00002728 }
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002729 // Sort to get deterministic order.
Benjamin Krameradf1ea82014-03-07 21:52:38 +00002730 array_pod_sort(UsedArray.begin(), UsedArray.end(), compareNames);
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002731 ArrayType *ATy = ArrayType::get(Int8PtrTy, UsedArray.size());
Rafael Espindola00752162013-05-09 17:22:59 +00002732
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002733 Module *M = V.getParent();
2734 V.removeFromParent();
2735 GlobalVariable *NV =
2736 new GlobalVariable(*M, ATy, false, llvm::GlobalValue::AppendingLinkage,
2737 llvm::ConstantArray::get(ATy, UsedArray), "");
2738 NV->takeName(&V);
2739 NV->setSection("llvm.metadata");
2740 delete &V;
Rafael Espindola00752162013-05-09 17:22:59 +00002741}
2742
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002743namespace {
James Molloyea31ad32015-11-13 11:05:07 +00002744/// An easy to access representation of llvm.used and llvm.compiler.used.
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002745class LLVMUsed {
2746 SmallPtrSet<GlobalValue *, 8> Used;
2747 SmallPtrSet<GlobalValue *, 8> CompilerUsed;
2748 GlobalVariable *UsedV;
2749 GlobalVariable *CompilerUsedV;
2750
2751public:
Rafael Espindolaec2375f2013-07-25 02:50:08 +00002752 LLVMUsed(Module &M) {
Rafael Espindola17600e22013-07-25 03:23:25 +00002753 UsedV = collectUsedGlobalVariables(M, Used, false);
2754 CompilerUsedV = collectUsedGlobalVariables(M, CompilerUsed, true);
Rafael Espindola00752162013-05-09 17:22:59 +00002755 }
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002756 typedef SmallPtrSet<GlobalValue *, 8>::iterator iterator;
Craig Topper46276792014-08-24 23:23:06 +00002757 typedef iterator_range<iterator> used_iterator_range;
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002758 iterator usedBegin() { return Used.begin(); }
2759 iterator usedEnd() { return Used.end(); }
Craig Topper46276792014-08-24 23:23:06 +00002760 used_iterator_range used() {
2761 return used_iterator_range(usedBegin(), usedEnd());
2762 }
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002763 iterator compilerUsedBegin() { return CompilerUsed.begin(); }
2764 iterator compilerUsedEnd() { return CompilerUsed.end(); }
Craig Topper46276792014-08-24 23:23:06 +00002765 used_iterator_range compilerUsed() {
2766 return used_iterator_range(compilerUsedBegin(), compilerUsedEnd());
2767 }
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002768 bool usedCount(GlobalValue *GV) const { return Used.count(GV); }
2769 bool compilerUsedCount(GlobalValue *GV) const {
2770 return CompilerUsed.count(GV);
2771 }
2772 bool usedErase(GlobalValue *GV) { return Used.erase(GV); }
2773 bool compilerUsedErase(GlobalValue *GV) { return CompilerUsed.erase(GV); }
David Blaikie70573dc2014-11-19 07:49:26 +00002774 bool usedInsert(GlobalValue *GV) { return Used.insert(GV).second; }
2775 bool compilerUsedInsert(GlobalValue *GV) {
2776 return CompilerUsed.insert(GV).second;
2777 }
Rafael Espindola00752162013-05-09 17:22:59 +00002778
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002779 void syncVariablesAndSets() {
2780 if (UsedV)
2781 setUsedInitializer(*UsedV, Used);
2782 if (CompilerUsedV)
2783 setUsedInitializer(*CompilerUsedV, CompilerUsed);
2784 }
2785};
Alexander Kornienkof00654e2015-06-23 09:49:53 +00002786}
Rafael Espindola00752162013-05-09 17:22:59 +00002787
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002788static bool hasUseOtherThanLLVMUsed(GlobalAlias &GA, const LLVMUsed &U) {
2789 if (GA.use_empty()) // No use at all.
2790 return false;
2791
2792 assert((!U.usedCount(&GA) || !U.compilerUsedCount(&GA)) &&
2793 "We should have removed the duplicated "
Rafael Espindola9aadcc42013-07-19 18:44:51 +00002794 "element from llvm.compiler.used");
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002795 if (!GA.hasOneUse())
2796 // Strictly more than one use. So at least one is not in llvm.used and
Rafael Espindola9aadcc42013-07-19 18:44:51 +00002797 // llvm.compiler.used.
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002798 return true;
2799
Rafael Espindola9aadcc42013-07-19 18:44:51 +00002800 // Exactly one use. Check if it is in llvm.used or llvm.compiler.used.
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002801 return !U.usedCount(&GA) && !U.compilerUsedCount(&GA);
Rafael Espindola00752162013-05-09 17:22:59 +00002802}
2803
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002804static bool hasMoreThanOneUseOtherThanLLVMUsed(GlobalValue &V,
2805 const LLVMUsed &U) {
2806 unsigned N = 2;
2807 assert((!U.usedCount(&V) || !U.compilerUsedCount(&V)) &&
2808 "We should have removed the duplicated "
Rafael Espindola9aadcc42013-07-19 18:44:51 +00002809 "element from llvm.compiler.used");
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002810 if (U.usedCount(&V) || U.compilerUsedCount(&V))
2811 ++N;
2812 return V.hasNUsesOrMore(N);
2813}
2814
2815static bool mayHaveOtherReferences(GlobalAlias &GA, const LLVMUsed &U) {
2816 if (!GA.hasLocalLinkage())
2817 return true;
2818
2819 return U.usedCount(&GA) || U.compilerUsedCount(&GA);
2820}
2821
Craig Topper71b7b682014-08-21 05:55:13 +00002822static bool hasUsesToReplace(GlobalAlias &GA, const LLVMUsed &U,
2823 bool &RenameTarget) {
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002824 RenameTarget = false;
Rafael Espindola00752162013-05-09 17:22:59 +00002825 bool Ret = false;
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002826 if (hasUseOtherThanLLVMUsed(GA, U))
Rafael Espindola00752162013-05-09 17:22:59 +00002827 Ret = true;
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002828
2829 // If the alias is externally visible, we may still be able to simplify it.
2830 if (!mayHaveOtherReferences(GA, U))
2831 return Ret;
2832
2833 // If the aliasee has internal linkage, give it the name and linkage
2834 // of the alias, and delete the alias. This turns:
2835 // define internal ... @f(...)
2836 // @a = alias ... @f
2837 // into:
2838 // define ... @a(...)
2839 Constant *Aliasee = GA.getAliasee();
2840 GlobalValue *Target = cast<GlobalValue>(Aliasee->stripPointerCasts());
2841 if (!Target->hasLocalLinkage())
2842 return Ret;
2843
2844 // Do not perform the transform if multiple aliases potentially target the
2845 // aliasee. This check also ensures that it is safe to replace the section
2846 // and other attributes of the aliasee with those of the alias.
2847 if (hasMoreThanOneUseOtherThanLLVMUsed(*Target, U))
2848 return Ret;
2849
2850 RenameTarget = true;
2851 return true;
Rafael Espindola00752162013-05-09 17:22:59 +00002852}
2853
Duncan Sandsed722832009-03-06 10:21:56 +00002854bool GlobalOpt::OptimizeGlobalAliases(Module &M) {
Anton Korobeynikova9b60ee2008-09-09 19:04:59 +00002855 bool Changed = false;
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002856 LLVMUsed Used(M);
2857
Craig Topper46276792014-08-24 23:23:06 +00002858 for (GlobalValue *GV : Used.used())
2859 Used.compilerUsedErase(GV);
Anton Korobeynikova9b60ee2008-09-09 19:04:59 +00002860
Duncan Sands0bcf0852009-01-07 20:01:06 +00002861 for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end();
Duncan Sandsb3f27882009-02-15 09:56:08 +00002862 I != E;) {
2863 Module::alias_iterator J = I++;
Duncan Sandsed722832009-03-06 10:21:56 +00002864 // Aliases without names cannot be referenced outside this module.
David Majnemer5c921152014-07-01 15:26:50 +00002865 if (!J->hasName() && !J->isDeclaration() && !J->hasLocalLinkage())
Duncan Sandsed722832009-03-06 10:21:56 +00002866 J->setLinkage(GlobalValue::InternalLinkage);
Duncan Sandsb3f27882009-02-15 09:56:08 +00002867 // If the aliasee may change at link time, nothing can be done - bail out.
2868 if (J->mayBeOverridden())
Anton Korobeynikova9b60ee2008-09-09 19:04:59 +00002869 continue;
2870
Duncan Sandsb3f27882009-02-15 09:56:08 +00002871 Constant *Aliasee = J->getAliasee();
David Majnemer0e2cc2a2014-07-01 00:30:56 +00002872 GlobalValue *Target = dyn_cast<GlobalValue>(Aliasee->stripPointerCasts());
2873 // We can't trivially replace the alias with the aliasee if the aliasee is
2874 // non-trivial in some way.
2875 // TODO: Try to handle non-zero GEPs of local aliasees.
2876 if (!Target)
2877 continue;
Duncan Sands7a1db332009-02-18 17:55:38 +00002878 Target->removeDeadConstantUsers();
Duncan Sandsb3f27882009-02-15 09:56:08 +00002879
2880 // Make all users of the alias use the aliasee instead.
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002881 bool RenameTarget;
2882 if (!hasUsesToReplace(*J, Used, RenameTarget))
Rafael Espindola00752162013-05-09 17:22:59 +00002883 continue;
Duncan Sandsb3f27882009-02-15 09:56:08 +00002884
Rafael Espindola6b238632014-05-16 19:35:39 +00002885 J->replaceAllUsesWith(ConstantExpr::getBitCast(Aliasee, J->getType()));
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002886 ++NumAliasesResolved;
2887 Changed = true;
Duncan Sandsb3f27882009-02-15 09:56:08 +00002888
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002889 if (RenameTarget) {
Duncan Sands6a3df7b2009-12-08 10:10:20 +00002890 // Give the aliasee the name, linkage and other attributes of the alias.
Duncan P. N. Exon Smith17323402015-10-13 17:51:03 +00002891 Target->takeName(&*J);
Duncan Sands6a3df7b2009-12-08 10:10:20 +00002892 Target->setLinkage(J->getLinkage());
Reid Kleckner22b19da2014-02-13 02:18:36 +00002893 Target->setVisibility(J->getVisibility());
2894 Target->setDLLStorageClass(J->getDLLStorageClass());
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002895
Duncan P. N. Exon Smith17323402015-10-13 17:51:03 +00002896 if (Used.usedErase(&*J))
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002897 Used.usedInsert(Target);
2898
Duncan P. N. Exon Smith17323402015-10-13 17:51:03 +00002899 if (Used.compilerUsedErase(&*J))
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002900 Used.compilerUsedInsert(Target);
Rafael Espindola8d304802013-06-12 16:45:47 +00002901 } else if (mayHaveOtherReferences(*J, Used))
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002902 continue;
2903
Duncan Sandsb3f27882009-02-15 09:56:08 +00002904 // Delete the alias.
2905 M.getAliasList().erase(J);
2906 ++NumAliasesRemoved;
2907 Changed = true;
Anton Korobeynikova9b60ee2008-09-09 19:04:59 +00002908 }
2909
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002910 Used.syncVariablesAndSets();
2911
Anton Korobeynikova9b60ee2008-09-09 19:04:59 +00002912 return Changed;
2913}
Chris Lattner41b6a5a2005-09-26 01:43:45 +00002914
Nick Lewycky4b273cb2012-02-12 02:15:20 +00002915static Function *FindCXAAtExit(Module &M, TargetLibraryInfo *TLI) {
2916 if (!TLI->has(LibFunc::cxa_atexit))
Craig Topperf40110f2014-04-25 05:29:35 +00002917 return nullptr;
Nick Lewycky4b273cb2012-02-12 02:15:20 +00002918
2919 Function *Fn = M.getFunction(TLI->getName(LibFunc::cxa_atexit));
Jakub Staszak9525a772012-12-06 21:57:16 +00002920
Anders Carlssonee6bc702011-03-20 17:59:11 +00002921 if (!Fn)
Craig Topperf40110f2014-04-25 05:29:35 +00002922 return nullptr;
Nick Lewycky4b273cb2012-02-12 02:15:20 +00002923
Chris Lattner229907c2011-07-18 04:54:35 +00002924 FunctionType *FTy = Fn->getFunctionType();
Jakub Staszak9525a772012-12-06 21:57:16 +00002925
2926 // Checking that the function has the right return type, the right number of
Anders Carlsson48a44912011-03-20 19:51:13 +00002927 // parameters and that they all have pointer types should be enough.
2928 if (!FTy->getReturnType()->isIntegerTy() ||
2929 FTy->getNumParams() != 3 ||
Anders Carlssonee6bc702011-03-20 17:59:11 +00002930 !FTy->getParamType(0)->isPointerTy() ||
2931 !FTy->getParamType(1)->isPointerTy() ||
2932 !FTy->getParamType(2)->isPointerTy())
Craig Topperf40110f2014-04-25 05:29:35 +00002933 return nullptr;
Anders Carlssonee6bc702011-03-20 17:59:11 +00002934
2935 return Fn;
2936}
2937
James Molloyea31ad32015-11-13 11:05:07 +00002938/// Returns whether the given function is an empty C++ destructor and can
2939/// therefore be eliminated.
Anders Carlssonee6bc702011-03-20 17:59:11 +00002940/// Note that we assume that other optimization passes have already simplified
2941/// the code so we only look for a function with a single basic block, where
Benjamin Kramer1a4695a2012-02-09 16:28:15 +00002942/// the only allowed instructions are 'ret', 'call' to an empty C++ dtor and
2943/// other side-effect free instructions.
Anders Carlssonfcec2f52011-03-20 20:16:43 +00002944static bool cxxDtorIsEmpty(const Function &Fn,
2945 SmallPtrSet<const Function *, 8> &CalledFunctions) {
Anders Carlsson48a44912011-03-20 19:51:13 +00002946 // FIXME: We could eliminate C++ destructors if they're readonly/readnone and
Nick Lewyckyd0781832011-03-21 02:26:01 +00002947 // nounwind, but that doesn't seem worth doing.
Anders Carlsson48a44912011-03-20 19:51:13 +00002948 if (Fn.isDeclaration())
2949 return false;
Anders Carlssonee6bc702011-03-20 17:59:11 +00002950
2951 if (++Fn.begin() != Fn.end())
2952 return false;
2953
2954 const BasicBlock &EntryBlock = Fn.getEntryBlock();
2955 for (BasicBlock::const_iterator I = EntryBlock.begin(), E = EntryBlock.end();
2956 I != E; ++I) {
2957 if (const CallInst *CI = dyn_cast<CallInst>(I)) {
Anders Carlsson4dd420f2011-03-21 14:54:40 +00002958 // Ignore debug intrinsics.
2959 if (isa<DbgInfoIntrinsic>(CI))
2960 continue;
2961
Anders Carlssonee6bc702011-03-20 17:59:11 +00002962 const Function *CalledFn = CI->getCalledFunction();
2963
2964 if (!CalledFn)
2965 return false;
2966
Anders Carlsson1cc80732011-03-22 03:21:01 +00002967 SmallPtrSet<const Function *, 8> NewCalledFunctions(CalledFunctions);
2968
Anders Carlsson48a44912011-03-20 19:51:13 +00002969 // Don't treat recursive functions as empty.
David Blaikie70573dc2014-11-19 07:49:26 +00002970 if (!NewCalledFunctions.insert(CalledFn).second)
Anders Carlsson48a44912011-03-20 19:51:13 +00002971 return false;
2972
Anders Carlsson1cc80732011-03-22 03:21:01 +00002973 if (!cxxDtorIsEmpty(*CalledFn, NewCalledFunctions))
Anders Carlssonee6bc702011-03-20 17:59:11 +00002974 return false;
2975 } else if (isa<ReturnInst>(*I))
Benjamin Kramer487a3962012-02-09 14:26:06 +00002976 return true; // We're done.
2977 else if (I->mayHaveSideEffects())
2978 return false; // Destructor with side effects, bail.
Anders Carlssonee6bc702011-03-20 17:59:11 +00002979 }
2980
2981 return false;
2982}
2983
2984bool GlobalOpt::OptimizeEmptyGlobalCXXDtors(Function *CXAAtExitFn) {
2985 /// Itanium C++ ABI p3.3.5:
2986 ///
2987 /// After constructing a global (or local static) object, that will require
2988 /// destruction on exit, a termination function is registered as follows:
2989 ///
2990 /// extern "C" int __cxa_atexit ( void (*f)(void *), void *p, void *d );
2991 ///
2992 /// This registration, e.g. __cxa_atexit(f,p,d), is intended to cause the
2993 /// call f(p) when DSO d is unloaded, before all such termination calls
2994 /// registered before this one. It returns zero if registration is
Nick Lewyckyd0781832011-03-21 02:26:01 +00002995 /// successful, nonzero on failure.
Anders Carlssonee6bc702011-03-20 17:59:11 +00002996
2997 // This pass will look for calls to __cxa_atexit where the function is trivial
2998 // and remove them.
2999 bool Changed = false;
3000
Chandler Carruthcdf47882014-03-09 03:16:01 +00003001 for (auto I = CXAAtExitFn->user_begin(), E = CXAAtExitFn->user_end();
3002 I != E;) {
Anders Carlsson336fd902011-03-20 20:21:33 +00003003 // We're only interested in calls. Theoretically, we could handle invoke
3004 // instructions as well, but neither llvm-gcc nor clang generate invokes
3005 // to __cxa_atexit.
Anders Carlsson4dd420f2011-03-21 14:54:40 +00003006 CallInst *CI = dyn_cast<CallInst>(*I++);
3007 if (!CI)
Anders Carlsson336fd902011-03-20 20:21:33 +00003008 continue;
3009
Jakub Staszak9525a772012-12-06 21:57:16 +00003010 Function *DtorFn =
Anders Carlsson4dd420f2011-03-21 14:54:40 +00003011 dyn_cast<Function>(CI->getArgOperand(0)->stripPointerCasts());
Anders Carlssonee6bc702011-03-20 17:59:11 +00003012 if (!DtorFn)
3013 continue;
3014
Anders Carlssonfcec2f52011-03-20 20:16:43 +00003015 SmallPtrSet<const Function *, 8> CalledFunctions;
3016 if (!cxxDtorIsEmpty(*DtorFn, CalledFunctions))
Anders Carlssonee6bc702011-03-20 17:59:11 +00003017 continue;
3018
3019 // Just remove the call.
Anders Carlsson4dd420f2011-03-21 14:54:40 +00003020 CI->replaceAllUsesWith(Constant::getNullValue(CI->getType()));
3021 CI->eraseFromParent();
Anders Carlsson48a44912011-03-20 19:51:13 +00003022
Anders Carlssonee6bc702011-03-20 17:59:11 +00003023 ++NumCXXDtorsRemoved;
3024
3025 Changed |= true;
3026 }
3027
3028 return Changed;
3029}
3030
Chris Lattner25db5802004-10-07 04:16:33 +00003031bool GlobalOpt::runOnModule(Module &M) {
3032 bool Changed = false;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00003033
Mehdi Amini46a43552015-03-04 18:43:29 +00003034 auto &DL = M.getDataLayout();
Chandler Carruthb98f63d2015-01-15 10:41:28 +00003035 TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Nick Lewyckycf6aae62012-02-12 01:13:18 +00003036
Chris Lattner25db5802004-10-07 04:16:33 +00003037 bool LocalChange = true;
3038 while (LocalChange) {
3039 LocalChange = false;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00003040
David Majnemer1b3b70e2014-10-08 07:23:31 +00003041 NotDiscardableComdats.clear();
3042 for (const GlobalVariable &GV : M.globals())
3043 if (const Comdat *C = GV.getComdat())
3044 if (!GV.isDiscardableIfUnused() || !GV.use_empty())
3045 NotDiscardableComdats.insert(C);
3046 for (Function &F : M)
3047 if (const Comdat *C = F.getComdat())
3048 if (!F.isDefTriviallyDead())
3049 NotDiscardableComdats.insert(C);
3050 for (GlobalAlias &GA : M.aliases())
3051 if (const Comdat *C = GA.getComdat())
3052 if (!GA.isDiscardableIfUnused() || !GA.use_empty())
3053 NotDiscardableComdats.insert(C);
3054
Chris Lattner41b6a5a2005-09-26 01:43:45 +00003055 // Delete functions that are trivially dead, ccc -> fastcc
3056 LocalChange |= OptimizeFunctions(M);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00003057
Chris Lattner41b6a5a2005-09-26 01:43:45 +00003058 // Optimize global_ctors list.
Richard Smithc167d652014-05-06 01:44:26 +00003059 LocalChange |= optimizeGlobalCtorsList(M, [&](Function *F) {
3060 return EvaluateStaticConstructor(F, DL, TLI);
3061 });
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00003062
Chris Lattner41b6a5a2005-09-26 01:43:45 +00003063 // Optimize non-address-taken globals.
3064 LocalChange |= OptimizeGlobalVars(M);
Anton Korobeynikova9b60ee2008-09-09 19:04:59 +00003065
3066 // Resolve aliases, when possible.
Duncan Sandsed722832009-03-06 10:21:56 +00003067 LocalChange |= OptimizeGlobalAliases(M);
Anders Carlssonee6bc702011-03-20 17:59:11 +00003068
Manman Renb3c52fb2013-05-14 21:52:44 +00003069 // Try to remove trivial global destructors if they are not removed
3070 // already.
3071 Function *CXAAtExitFn = FindCXAAtExit(M, TLI);
Anders Carlssonee6bc702011-03-20 17:59:11 +00003072 if (CXAAtExitFn)
3073 LocalChange |= OptimizeEmptyGlobalCXXDtors(CXAAtExitFn);
3074
Anton Korobeynikova9b60ee2008-09-09 19:04:59 +00003075 Changed |= LocalChange;
Chris Lattner25db5802004-10-07 04:16:33 +00003076 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00003077
Chris Lattner41b6a5a2005-09-26 01:43:45 +00003078 // TODO: Move all global ctors functions to the end of the module for code
3079 // layout.
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00003080
Chris Lattner25db5802004-10-07 04:16:33 +00003081 return Changed;
3082}
Anthony Pescha2d93692015-07-22 18:50:10 +00003083