blob: 27be1b40a32af3174eeb30ec6e0e3037b8fd505e [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
Nick Lewyckyfaa9c3b02012-07-24 07:21:08 +0000103/// isLeakCheckerRoot - Is this global variable possibly used by a leak checker
104/// as a root? If so, we might not really want to eliminate the stores to it.
105static 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
179/// CleanupPointerRootUsers - This GV is a pointer root. Loop over all users
180/// of the global and clean up any that obviously don't assign the global a
181/// value that isn't dynamically allocated.
182///
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000183static bool CleanupPointerRootUsers(GlobalVariable *GV,
184 const TargetLibraryInfo *TLI) {
Nick Lewyckyfaa9c3b02012-07-24 07:21:08 +0000185 // A brief explanation of leak checkers. The goal is to find bugs where
186 // pointers are forgotten, causing an accumulating growth in memory
187 // usage over time. The common strategy for leak checkers is to whitelist the
188 // memory pointed to by globals at exit. This is popular because it also
189 // solves another problem where the main thread of a C++ program may shut down
190 // before other threads that are still expecting to use those globals. To
191 // handle that case, we expect the program may create a singleton and never
192 // destroy it.
193
194 bool Changed = false;
195
196 // If Dead[n].first is the only use of a malloc result, we can delete its
197 // chain of computation and the store to the global in Dead[n].second.
198 SmallVector<std::pair<Instruction *, Instruction *>, 32> Dead;
199
200 // Constants can't be pointers to dynamically allocated memory.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000201 for (Value::user_iterator UI = GV->user_begin(), E = GV->user_end();
Nick Lewyckyfaa9c3b02012-07-24 07:21:08 +0000202 UI != E;) {
203 User *U = *UI++;
204 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
205 Value *V = SI->getValueOperand();
206 if (isa<Constant>(V)) {
207 Changed = true;
208 SI->eraseFromParent();
209 } else if (Instruction *I = dyn_cast<Instruction>(V)) {
210 if (I->hasOneUse())
211 Dead.push_back(std::make_pair(I, SI));
212 }
213 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(U)) {
214 if (isa<Constant>(MSI->getValue())) {
215 Changed = true;
216 MSI->eraseFromParent();
217 } else if (Instruction *I = dyn_cast<Instruction>(MSI->getValue())) {
218 if (I->hasOneUse())
219 Dead.push_back(std::make_pair(I, MSI));
220 }
221 } else if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(U)) {
222 GlobalVariable *MemSrc = dyn_cast<GlobalVariable>(MTI->getSource());
223 if (MemSrc && MemSrc->isConstant()) {
224 Changed = true;
225 MTI->eraseFromParent();
226 } else if (Instruction *I = dyn_cast<Instruction>(MemSrc)) {
227 if (I->hasOneUse())
228 Dead.push_back(std::make_pair(I, MTI));
229 }
230 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
231 if (CE->use_empty()) {
232 CE->destroyConstant();
233 Changed = true;
234 }
235 } else if (Constant *C = dyn_cast<Constant>(U)) {
Rafael Espindola27797ba2013-10-17 18:06:32 +0000236 if (isSafeToDestroyConstant(C)) {
Nick Lewyckyfaa9c3b02012-07-24 07:21:08 +0000237 C->destroyConstant();
238 // This could have invalidated UI, start over from scratch.
239 Dead.clear();
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000240 CleanupPointerRootUsers(GV, TLI);
Nick Lewyckyfaa9c3b02012-07-24 07:21:08 +0000241 return true;
242 }
243 }
244 }
245
246 for (int i = 0, e = Dead.size(); i != e; ++i) {
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000247 if (IsSafeComputationToRemove(Dead[i].first, TLI)) {
Nick Lewyckyfaa9c3b02012-07-24 07:21:08 +0000248 Dead[i].second->eraseFromParent();
249 Instruction *I = Dead[i].first;
250 do {
Michael Gottesman2a654272013-01-11 23:08:52 +0000251 if (isAllocationFn(I, TLI))
252 break;
Nick Lewyckyfaa9c3b02012-07-24 07:21:08 +0000253 Instruction *J = dyn_cast<Instruction>(I->getOperand(0));
254 if (!J)
255 break;
256 I->eraseFromParent();
257 I = J;
Nick Lewycky38be9312012-07-24 21:33:00 +0000258 } while (1);
Nick Lewyckyfaa9c3b02012-07-24 07:21:08 +0000259 I->eraseFromParent();
260 }
261 }
262
263 return Changed;
264}
265
Chris Lattner25db5802004-10-07 04:16:33 +0000266/// CleanupConstantGlobalUsers - We just marked GV constant. Loop over all
267/// users of the global, cleaning up the obvious ones. This is largely just a
Chris Lattnercb9f1522004-10-10 16:43:46 +0000268/// quick scan over the use list to clean up the easy and obvious cruft. This
269/// returns true if it made a change.
Nick Lewyckycf6aae62012-02-12 01:13:18 +0000270static bool CleanupConstantGlobalUsers(Value *V, Constant *Init,
Mehdi Amini46a43552015-03-04 18:43:29 +0000271 const DataLayout &DL,
Rafael Espindolaaeff8a92014-02-24 23:12:18 +0000272 TargetLibraryInfo *TLI) {
Chris Lattnercb9f1522004-10-10 16:43:46 +0000273 bool Changed = false;
Hal Finkelf59fd7d2013-12-12 20:45:24 +0000274 // Note that we need to use a weak value handle for the worklist items. When
275 // we delete a constant array, we may also be holding pointer to one of its
276 // elements (or an element of one of its elements if we're dealing with an
277 // array of arrays) in the worklist.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000278 SmallVector<WeakVH, 8> WorkList(V->user_begin(), V->user_end());
Bill Wendling88d06c32013-04-02 08:16:45 +0000279 while (!WorkList.empty()) {
Hal Finkelf59fd7d2013-12-12 20:45:24 +0000280 Value *UV = WorkList.pop_back_val();
281 if (!UV)
282 continue;
283
284 User *U = cast<User>(UV);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000285
Chris Lattner25db5802004-10-07 04:16:33 +0000286 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
Chris Lattner7561ca12005-02-27 18:58:52 +0000287 if (Init) {
288 // Replace the load with the initializer.
289 LI->replaceAllUsesWith(Init);
290 LI->eraseFromParent();
291 Changed = true;
292 }
Chris Lattner25db5802004-10-07 04:16:33 +0000293 } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
294 // Store must be unreachable or storing Init into the global.
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000295 SI->eraseFromParent();
Chris Lattnercb9f1522004-10-10 16:43:46 +0000296 Changed = true;
Chris Lattner25db5802004-10-07 04:16:33 +0000297 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
298 if (CE->getOpcode() == Instruction::GetElementPtr) {
Craig Topperf40110f2014-04-25 05:29:35 +0000299 Constant *SubInit = nullptr;
Chris Lattner46d9ff082005-09-26 07:34:35 +0000300 if (Init)
Dan Gohmane525d9d2009-10-05 16:36:26 +0000301 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000302 Changed |= CleanupConstantGlobalUsers(CE, SubInit, DL, TLI);
Matt Arsenault461c8e02014-01-02 20:01:43 +0000303 } else if ((CE->getOpcode() == Instruction::BitCast &&
304 CE->getType()->isPointerTy()) ||
305 CE->getOpcode() == Instruction::AddrSpaceCast) {
Chris Lattner7561ca12005-02-27 18:58:52 +0000306 // Pointer cast, delete any stores and memsets to the global.
Craig Topperf40110f2014-04-25 05:29:35 +0000307 Changed |= CleanupConstantGlobalUsers(CE, nullptr, DL, TLI);
Chris Lattner7561ca12005-02-27 18:58:52 +0000308 }
309
310 if (CE->use_empty()) {
311 CE->destroyConstant();
312 Changed = true;
Chris Lattner25db5802004-10-07 04:16:33 +0000313 }
314 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
Chris Lattnerf9c0fd72007-11-09 17:33:02 +0000315 // Do not transform "gepinst (gep constexpr (GV))" here, because forming
316 // "gepconstexpr (gep constexpr (GV))" will cause the two gep's to fold
317 // and will invalidate our notion of what Init is.
Craig Topperf40110f2014-04-25 05:29:35 +0000318 Constant *SubInit = nullptr;
Chris Lattnerf9c0fd72007-11-09 17:33:02 +0000319 if (!isa<ConstantExpr>(GEP->getOperand(0))) {
Mehdi Amini46a43552015-03-04 18:43:29 +0000320 ConstantExpr *CE = dyn_cast_or_null<ConstantExpr>(
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000321 ConstantFoldInstruction(GEP, DL, TLI));
Chris Lattnerf9c0fd72007-11-09 17:33:02 +0000322 if (Init && CE && CE->getOpcode() == Instruction::GetElementPtr)
Dan Gohmane525d9d2009-10-05 16:36:26 +0000323 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
Benjamin Krameraa9e4a52012-03-28 14:50:09 +0000324
325 // If the initializer is an all-null value and we have an inbounds GEP,
326 // we already know what the result of any load from that GEP is.
327 // TODO: Handle splats.
328 if (Init && isa<ConstantAggregateZero>(Init) && GEP->isInBounds())
329 SubInit = Constant::getNullValue(GEP->getType()->getElementType());
Chris Lattnerf9c0fd72007-11-09 17:33:02 +0000330 }
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000331 Changed |= CleanupConstantGlobalUsers(GEP, SubInit, DL, TLI);
Chris Lattnera0e769c2004-10-10 16:47:33 +0000332
Chris Lattnercb9f1522004-10-10 16:43:46 +0000333 if (GEP->use_empty()) {
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000334 GEP->eraseFromParent();
Chris Lattnercb9f1522004-10-10 16:43:46 +0000335 Changed = true;
336 }
Chris Lattner7561ca12005-02-27 18:58:52 +0000337 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U)) { // memset/cpy/mv
338 if (MI->getRawDest() == V) {
339 MI->eraseFromParent();
340 Changed = true;
341 }
342
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000343 } else if (Constant *C = dyn_cast<Constant>(U)) {
344 // If we have a chain of dead constantexprs or other things dangling from
345 // us, and if they are all dead, nuke them without remorse.
Rafael Espindola27797ba2013-10-17 18:06:32 +0000346 if (isSafeToDestroyConstant(C)) {
Devang Pateld926aaa2009-03-06 01:37:41 +0000347 C->destroyConstant();
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000348 CleanupConstantGlobalUsers(V, Init, DL, TLI);
Chris Lattnercb9f1522004-10-10 16:43:46 +0000349 return true;
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000350 }
Chris Lattner25db5802004-10-07 04:16:33 +0000351 }
352 }
Chris Lattnercb9f1522004-10-10 16:43:46 +0000353 return Changed;
Chris Lattner25db5802004-10-07 04:16:33 +0000354}
355
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000356/// isSafeSROAElementUse - Return true if the specified instruction is a safe
357/// user of a derived expression from a global that we want to SROA.
358static bool isSafeSROAElementUse(Value *V) {
359 // We might have a dead and dangling constant hanging off of here.
360 if (Constant *C = dyn_cast<Constant>(V))
Rafael Espindola27797ba2013-10-17 18:06:32 +0000361 return isSafeToDestroyConstant(C);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000362
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000363 Instruction *I = dyn_cast<Instruction>(V);
364 if (!I) return false;
365
366 // Loads are ok.
367 if (isa<LoadInst>(I)) return true;
368
369 // Stores *to* the pointer are ok.
370 if (StoreInst *SI = dyn_cast<StoreInst>(I))
371 return SI->getOperand(0) != V;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000372
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000373 // Otherwise, it must be a GEP.
374 GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I);
Craig Topperf40110f2014-04-25 05:29:35 +0000375 if (!GEPI) return false;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000376
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000377 if (GEPI->getNumOperands() < 3 || !isa<Constant>(GEPI->getOperand(1)) ||
378 !cast<Constant>(GEPI->getOperand(1))->isNullValue())
379 return false;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000380
Chandler Carruthcdf47882014-03-09 03:16:01 +0000381 for (User *U : GEPI->users())
382 if (!isSafeSROAElementUse(U))
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000383 return false;
Chris Lattnerab053722008-01-14 01:31:05 +0000384 return true;
385}
386
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000387
388/// IsUserOfGlobalSafeForSRA - U is a direct user of the specified global value.
389/// Look at it and its uses and decide whether it is safe to SROA this global.
390///
391static bool IsUserOfGlobalSafeForSRA(User *U, GlobalValue *GV) {
392 // The user of the global must be a GEP Inst or a ConstantExpr GEP.
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000393 if (!isa<GetElementPtrInst>(U) &&
394 (!isa<ConstantExpr>(U) ||
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000395 cast<ConstantExpr>(U)->getOpcode() != Instruction::GetElementPtr))
396 return false;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000397
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000398 // Check to see if this ConstantExpr GEP is SRA'able. In particular, we
399 // don't like < 3 operand CE's, and we don't like non-constant integer
400 // indices. This enforces that all uses are 'gep GV, 0, C, ...' for some
401 // value of C.
402 if (U->getNumOperands() < 3 || !isa<Constant>(U->getOperand(1)) ||
403 !cast<Constant>(U->getOperand(1))->isNullValue() ||
404 !isa<ConstantInt>(U->getOperand(2)))
405 return false;
406
407 gep_type_iterator GEPI = gep_type_begin(U), E = gep_type_end(U);
408 ++GEPI; // Skip over the pointer index.
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000409
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000410 // If this is a use of an array allocation, do a bit more checking for sanity.
Chris Lattner229907c2011-07-18 04:54:35 +0000411 if (ArrayType *AT = dyn_cast<ArrayType>(*GEPI)) {
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000412 uint64_t NumElements = AT->getNumElements();
413 ConstantInt *Idx = cast<ConstantInt>(U->getOperand(2));
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000414
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000415 // Check to make sure that index falls within the array. If not,
416 // something funny is going on, so we won't do the optimization.
417 //
418 if (Idx->getZExtValue() >= NumElements)
419 return false;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000420
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000421 // We cannot scalar repl this level of the array unless any array
422 // sub-indices are in-range constants. In particular, consider:
423 // A[0][i]. We cannot know that the user isn't doing invalid things like
424 // allowing i to index an out-of-range subscript that accesses A[1].
425 //
426 // Scalar replacing *just* the outer index of the array is probably not
427 // going to be a win anyway, so just give up.
428 for (++GEPI; // Skip array index.
Dan Gohman82ac81b2009-08-18 14:58:19 +0000429 GEPI != E;
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000430 ++GEPI) {
431 uint64_t NumElements;
Chris Lattner229907c2011-07-18 04:54:35 +0000432 if (ArrayType *SubArrayTy = dyn_cast<ArrayType>(*GEPI))
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000433 NumElements = SubArrayTy->getNumElements();
Chris Lattner229907c2011-07-18 04:54:35 +0000434 else if (VectorType *SubVectorTy = dyn_cast<VectorType>(*GEPI))
Dan Gohman82ac81b2009-08-18 14:58:19 +0000435 NumElements = SubVectorTy->getNumElements();
436 else {
Duncan Sands19d0b472010-02-16 11:11:14 +0000437 assert((*GEPI)->isStructTy() &&
Dan Gohman82ac81b2009-08-18 14:58:19 +0000438 "Indexed GEP type is not array, vector, or struct!");
439 continue;
440 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000441
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000442 ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPI.getOperand());
443 if (!IdxVal || IdxVal->getZExtValue() >= NumElements)
444 return false;
445 }
446 }
447
Chandler Carruthcdf47882014-03-09 03:16:01 +0000448 for (User *UU : U->users())
449 if (!isSafeSROAElementUse(UU))
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000450 return false;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000451
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000452 return true;
453}
454
455/// GlobalUsersSafeToSRA - Look at all uses of the global and decide whether it
456/// is safe for us to perform this transformation.
457///
458static bool GlobalUsersSafeToSRA(GlobalValue *GV) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000459 for (User *U : GV->users())
460 if (!IsUserOfGlobalSafeForSRA(U, GV))
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000461 return false;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000462
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000463 return true;
464}
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000465
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000466
Chris Lattnerabab0712004-10-08 17:32:09 +0000467/// SRAGlobal - Perform scalar replacement of aggregates on the specified global
468/// variable. This opens the door for other optimizations by exposing the
469/// behavior of the program in a more fine-grained way. We have determined that
470/// this transformation is safe already. We return the first global variable we
471/// insert so that the caller can reprocess it.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000472static GlobalVariable *SRAGlobal(GlobalVariable *GV, const DataLayout &DL) {
Chris Lattnerab053722008-01-14 01:31:05 +0000473 // Make sure this global only has simple uses that we can SRA.
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000474 if (!GlobalUsersSafeToSRA(GV))
Craig Topperf40110f2014-04-25 05:29:35 +0000475 return nullptr;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000476
Rafael Espindola6de96a12009-01-15 20:18:42 +0000477 assert(GV->hasLocalLinkage() && !GV->isConstant());
Chris Lattnerabab0712004-10-08 17:32:09 +0000478 Constant *Init = GV->getInitializer();
Chris Lattner229907c2011-07-18 04:54:35 +0000479 Type *Ty = Init->getType();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000480
Chris Lattnerabab0712004-10-08 17:32:09 +0000481 std::vector<GlobalVariable*> NewGlobals;
482 Module::GlobalListType &Globals = GV->getParent()->getGlobalList();
483
Chris Lattner67ca6f632008-04-26 07:40:11 +0000484 // Get the alignment of the global, either explicit or target-specific.
485 unsigned StartAlignment = GV->getAlignment();
486 if (StartAlignment == 0)
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000487 StartAlignment = DL.getABITypeAlignment(GV->getType());
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000488
Chris Lattner229907c2011-07-18 04:54:35 +0000489 if (StructType *STy = dyn_cast<StructType>(Ty)) {
Chris Lattnerabab0712004-10-08 17:32:09 +0000490 NewGlobals.reserve(STy->getNumElements());
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000491 const StructLayout &Layout = *DL.getStructLayout(STy);
Chris Lattnerabab0712004-10-08 17:32:09 +0000492 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
Chris Lattner67058832012-01-25 06:48:06 +0000493 Constant *In = Init->getAggregateElement(i);
Chris Lattnerabab0712004-10-08 17:32:09 +0000494 assert(In && "Couldn't get element of initializer?");
Chris Lattner46b5c642009-11-06 04:27:31 +0000495 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(i), false,
Chris Lattnerabab0712004-10-08 17:32:09 +0000496 GlobalVariable::InternalLinkage,
Daniel Dunbar132f7832009-07-30 17:37:43 +0000497 In, GV->getName()+"."+Twine(i),
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000498 GV->getThreadLocalMode(),
Owen Anderson5948fdf2009-07-08 01:26:06 +0000499 GV->getType()->getAddressSpace());
Chris Lattnerabab0712004-10-08 17:32:09 +0000500 Globals.insert(GV, NGV);
501 NewGlobals.push_back(NGV);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000502
Chris Lattner67ca6f632008-04-26 07:40:11 +0000503 // Calculate the known alignment of the field. If the original aggregate
504 // had 256 byte alignment for example, something might depend on that:
505 // propagate info to each field.
506 uint64_t FieldOffset = Layout.getElementOffset(i);
507 unsigned NewAlign = (unsigned)MinAlign(StartAlignment, FieldOffset);
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000508 if (NewAlign > DL.getABITypeAlignment(STy->getElementType(i)))
Chris Lattner67ca6f632008-04-26 07:40:11 +0000509 NGV->setAlignment(NewAlign);
Chris Lattnerabab0712004-10-08 17:32:09 +0000510 }
Chris Lattner229907c2011-07-18 04:54:35 +0000511 } else if (SequentialType *STy = dyn_cast<SequentialType>(Ty)) {
Chris Lattnerabab0712004-10-08 17:32:09 +0000512 unsigned NumElements = 0;
Chris Lattner229907c2011-07-18 04:54:35 +0000513 if (ArrayType *ATy = dyn_cast<ArrayType>(STy))
Chris Lattnerabab0712004-10-08 17:32:09 +0000514 NumElements = ATy->getNumElements();
Chris Lattnerabab0712004-10-08 17:32:09 +0000515 else
Chris Lattner67ca6f632008-04-26 07:40:11 +0000516 NumElements = cast<VectorType>(STy)->getNumElements();
Chris Lattnerabab0712004-10-08 17:32:09 +0000517
Chris Lattner25169ca2005-02-23 16:53:04 +0000518 if (NumElements > 16 && GV->hasNUsesOrMore(16))
Craig Topperf40110f2014-04-25 05:29:35 +0000519 return nullptr; // It's not worth it.
Chris Lattnerabab0712004-10-08 17:32:09 +0000520 NewGlobals.reserve(NumElements);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000521
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000522 uint64_t EltSize = DL.getTypeAllocSize(STy->getElementType());
523 unsigned EltAlign = DL.getABITypeAlignment(STy->getElementType());
Chris Lattnerabab0712004-10-08 17:32:09 +0000524 for (unsigned i = 0, e = NumElements; i != e; ++i) {
Chris Lattner67058832012-01-25 06:48:06 +0000525 Constant *In = Init->getAggregateElement(i);
Chris Lattnerabab0712004-10-08 17:32:09 +0000526 assert(In && "Couldn't get element of initializer?");
527
Chris Lattner46b5c642009-11-06 04:27:31 +0000528 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(), false,
Chris Lattnerabab0712004-10-08 17:32:09 +0000529 GlobalVariable::InternalLinkage,
Daniel Dunbar132f7832009-07-30 17:37:43 +0000530 In, GV->getName()+"."+Twine(i),
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000531 GV->getThreadLocalMode(),
Owen Andersonb17f3292009-07-08 19:03:57 +0000532 GV->getType()->getAddressSpace());
Chris Lattnerabab0712004-10-08 17:32:09 +0000533 Globals.insert(GV, NGV);
534 NewGlobals.push_back(NGV);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000535
Chris Lattner67ca6f632008-04-26 07:40:11 +0000536 // Calculate the known alignment of the field. If the original aggregate
537 // had 256 byte alignment for example, something might depend on that:
538 // propagate info to each field.
539 unsigned NewAlign = (unsigned)MinAlign(StartAlignment, EltSize*i);
540 if (NewAlign > EltAlign)
541 NGV->setAlignment(NewAlign);
Chris Lattnerabab0712004-10-08 17:32:09 +0000542 }
543 }
544
545 if (NewGlobals.empty())
Craig Topperf40110f2014-04-25 05:29:35 +0000546 return nullptr;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000547
David Greene44cb8ad2010-01-05 01:28:05 +0000548 DEBUG(dbgs() << "PERFORMING GLOBAL SRA ON: " << *GV);
Chris Lattner004e2502004-10-11 05:54:41 +0000549
Chris Lattner46b5c642009-11-06 04:27:31 +0000550 Constant *NullInt =Constant::getNullValue(Type::getInt32Ty(GV->getContext()));
Chris Lattnerabab0712004-10-08 17:32:09 +0000551
552 // Loop over all of the uses of the global, replacing the constantexpr geps,
553 // with smaller constantexpr geps or direct references.
554 while (!GV->use_empty()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000555 User *GEP = GV->user_back();
Chris Lattner004e2502004-10-11 05:54:41 +0000556 assert(((isa<ConstantExpr>(GEP) &&
557 cast<ConstantExpr>(GEP)->getOpcode()==Instruction::GetElementPtr)||
558 isa<GetElementPtrInst>(GEP)) && "NonGEP CE's are not SRAable!");
Misha Brukmanb1c93172005-04-21 23:48:37 +0000559
Chris Lattnerabab0712004-10-08 17:32:09 +0000560 // Ignore the 1th operand, which has to be zero or else the program is quite
561 // broken (undefined). Get the 2nd operand, which is the structure or array
562 // index.
Reid Spencere0fc4df2006-10-20 07:07:24 +0000563 unsigned Val = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
Chris Lattnerabab0712004-10-08 17:32:09 +0000564 if (Val >= NewGlobals.size()) Val = 0; // Out of bound array access.
565
Chris Lattner004e2502004-10-11 05:54:41 +0000566 Value *NewPtr = NewGlobals[Val];
David Blaikied9d900c2015-05-07 17:28:58 +0000567 Type *NewTy = NewGlobals[Val]->getValueType();
Chris Lattnerabab0712004-10-08 17:32:09 +0000568
569 // Form a shorter GEP if needed.
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +0000570 if (GEP->getNumOperands() > 3) {
Chris Lattner004e2502004-10-11 05:54:41 +0000571 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEP)) {
Chris Lattnerf96f4a82007-01-31 04:40:53 +0000572 SmallVector<Constant*, 8> Idxs;
Chris Lattner004e2502004-10-11 05:54:41 +0000573 Idxs.push_back(NullInt);
574 for (unsigned i = 3, e = CE->getNumOperands(); i != e; ++i)
575 Idxs.push_back(CE->getOperand(i));
David Blaikie4a2e73b2015-04-02 18:55:32 +0000576 NewPtr =
577 ConstantExpr::getGetElementPtr(NewTy, cast<Constant>(NewPtr), Idxs);
Chris Lattner004e2502004-10-11 05:54:41 +0000578 } else {
579 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(GEP);
Chris Lattner927653f2007-01-31 19:59:55 +0000580 SmallVector<Value*, 8> Idxs;
Chris Lattner004e2502004-10-11 05:54:41 +0000581 Idxs.push_back(NullInt);
582 for (unsigned i = 3, e = GEPI->getNumOperands(); i != e; ++i)
583 Idxs.push_back(GEPI->getOperand(i));
David Blaikie741c8f82015-03-14 01:53:18 +0000584 NewPtr = GetElementPtrInst::Create(
David Blaikied9d900c2015-05-07 17:28:58 +0000585 NewTy, NewPtr, Idxs, GEPI->getName() + "." + Twine(Val), GEPI);
Chris Lattner004e2502004-10-11 05:54:41 +0000586 }
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +0000587 }
Chris Lattner004e2502004-10-11 05:54:41 +0000588 GEP->replaceAllUsesWith(NewPtr);
589
590 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(GEP))
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000591 GEPI->eraseFromParent();
Chris Lattner004e2502004-10-11 05:54:41 +0000592 else
593 cast<ConstantExpr>(GEP)->destroyConstant();
Chris Lattnerabab0712004-10-08 17:32:09 +0000594 }
595
Chris Lattner73ad73e2004-10-08 20:25:55 +0000596 // Delete the old global, now that it is dead.
597 Globals.erase(GV);
Chris Lattnerabab0712004-10-08 17:32:09 +0000598 ++NumSRA;
Chris Lattner004e2502004-10-11 05:54:41 +0000599
600 // Loop over the new globals array deleting any globals that are obviously
601 // dead. This can arise due to scalarization of a structure or an array that
602 // has elements that are dead.
603 unsigned FirstGlobal = 0;
604 for (unsigned i = 0, e = NewGlobals.size(); i != e; ++i)
605 if (NewGlobals[i]->use_empty()) {
606 Globals.erase(NewGlobals[i]);
607 if (FirstGlobal == i) ++FirstGlobal;
608 }
609
Craig Topperf40110f2014-04-25 05:29:35 +0000610 return FirstGlobal != NewGlobals.size() ? NewGlobals[FirstGlobal] : nullptr;
Chris Lattnerabab0712004-10-08 17:32:09 +0000611}
612
Chris Lattner09a52722004-10-09 21:48:45 +0000613/// AllUsesOfValueWillTrapIfNull - Return true if all users of the specified
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000614/// value will trap if the value is dynamically null. PHIs keeps track of any
Chris Lattner2d2892e2007-09-13 16:30:19 +0000615/// phi nodes we've seen to avoid reprocessing them.
Gabor Greif67972872010-04-06 19:24:18 +0000616static bool AllUsesOfValueWillTrapIfNull(const Value *V,
Craig Topper71b7b682014-08-21 05:55:13 +0000617 SmallPtrSetImpl<const PHINode*> &PHIs) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000618 for (const User *U : V->users())
Gabor Greif08355d62010-04-06 19:14:05 +0000619 if (isa<LoadInst>(U)) {
Chris Lattner09a52722004-10-09 21:48:45 +0000620 // Will trap.
Gabor Greif67972872010-04-06 19:24:18 +0000621 } else if (const StoreInst *SI = dyn_cast<StoreInst>(U)) {
Chris Lattner09a52722004-10-09 21:48:45 +0000622 if (SI->getOperand(0) == V) {
Gabor Greif08355d62010-04-06 19:14:05 +0000623 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner09a52722004-10-09 21:48:45 +0000624 return false; // Storing the value.
625 }
Gabor Greif67972872010-04-06 19:24:18 +0000626 } else if (const CallInst *CI = dyn_cast<CallInst>(U)) {
Gabor Greiffebf6ab2010-03-20 21:00:25 +0000627 if (CI->getCalledValue() != V) {
Gabor Greif08355d62010-04-06 19:14:05 +0000628 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner09a52722004-10-09 21:48:45 +0000629 return false; // Not calling the ptr
630 }
Gabor Greif67972872010-04-06 19:24:18 +0000631 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(U)) {
Gabor Greiffebf6ab2010-03-20 21:00:25 +0000632 if (II->getCalledValue() != V) {
Gabor Greif08355d62010-04-06 19:14:05 +0000633 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner09a52722004-10-09 21:48:45 +0000634 return false; // Not calling the ptr
635 }
Gabor Greif67972872010-04-06 19:24:18 +0000636 } else if (const BitCastInst *CI = dyn_cast<BitCastInst>(U)) {
Chris Lattner2d2892e2007-09-13 16:30:19 +0000637 if (!AllUsesOfValueWillTrapIfNull(CI, PHIs)) return false;
Gabor Greif67972872010-04-06 19:24:18 +0000638 } else if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
Chris Lattner2d2892e2007-09-13 16:30:19 +0000639 if (!AllUsesOfValueWillTrapIfNull(GEPI, PHIs)) return false;
Gabor Greif67972872010-04-06 19:24:18 +0000640 } else if (const PHINode *PN = dyn_cast<PHINode>(U)) {
Chris Lattner2d2892e2007-09-13 16:30:19 +0000641 // If we've already seen this phi node, ignore it, it has already been
642 // checked.
David Blaikie70573dc2014-11-19 07:49:26 +0000643 if (PHIs.insert(PN).second && !AllUsesOfValueWillTrapIfNull(PN, PHIs))
Jakob Stoklund Olesene27dc722010-01-29 23:54:14 +0000644 return false;
Gabor Greif08355d62010-04-06 19:14:05 +0000645 } else if (isa<ICmpInst>(U) &&
Chandler Carruthcdf47882014-03-09 03:16:01 +0000646 isa<ConstantPointerNull>(U->getOperand(1))) {
Nick Lewycky614fb942010-02-25 06:39:10 +0000647 // Ignore icmp X, null
Chris Lattner09a52722004-10-09 21:48:45 +0000648 } else {
Gabor Greif08355d62010-04-06 19:14:05 +0000649 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner09a52722004-10-09 21:48:45 +0000650 return false;
651 }
Chandler Carruthcdf47882014-03-09 03:16:01 +0000652
Chris Lattner09a52722004-10-09 21:48:45 +0000653 return true;
654}
655
656/// AllUsesOfLoadedValueWillTrapIfNull - Return true if all uses of any loads
Chris Lattnerfe9abf92004-10-22 06:43:28 +0000657/// from GV will trap if the loaded value is null. Note that this also permits
658/// comparisons of the loaded value against null, as a special case.
Gabor Greif67972872010-04-06 19:24:18 +0000659static bool AllUsesOfLoadedValueWillTrapIfNull(const GlobalVariable *GV) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000660 for (const User *U : GV->users())
Gabor Greif67972872010-04-06 19:24:18 +0000661 if (const LoadInst *LI = dyn_cast<LoadInst>(U)) {
662 SmallPtrSet<const PHINode*, 8> PHIs;
Chris Lattner2d2892e2007-09-13 16:30:19 +0000663 if (!AllUsesOfValueWillTrapIfNull(LI, PHIs))
Chris Lattner09a52722004-10-09 21:48:45 +0000664 return false;
Gabor Greif08355d62010-04-06 19:14:05 +0000665 } else if (isa<StoreInst>(U)) {
Chris Lattner09a52722004-10-09 21:48:45 +0000666 // Ignore stores to the global.
667 } else {
668 // We don't know or understand this user, bail out.
Gabor Greif08355d62010-04-06 19:14:05 +0000669 //cerr << "UNKNOWN USER OF GLOBAL!: " << *U;
Chris Lattner09a52722004-10-09 21:48:45 +0000670 return false;
671 }
Chris Lattner09a52722004-10-09 21:48:45 +0000672 return true;
673}
674
Chris Lattner46b5c642009-11-06 04:27:31 +0000675static bool OptimizeAwayTrappingUsesOfValue(Value *V, Constant *NewV) {
Chris Lattnere42eb312004-10-10 23:14:11 +0000676 bool Changed = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000677 for (auto UI = V->user_begin(), E = V->user_end(); UI != E; ) {
Chris Lattnere42eb312004-10-10 23:14:11 +0000678 Instruction *I = cast<Instruction>(*UI++);
679 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
680 LI->setOperand(0, NewV);
681 Changed = true;
682 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
683 if (SI->getOperand(1) == V) {
684 SI->setOperand(1, NewV);
685 Changed = true;
686 }
687 } else if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
Gabor Greif04397892010-04-06 18:45:08 +0000688 CallSite CS(I);
689 if (CS.getCalledValue() == V) {
Chris Lattnere42eb312004-10-10 23:14:11 +0000690 // Calling through the pointer! Turn into a direct call, but be careful
691 // that the pointer is not also being passed as an argument.
Gabor Greif04397892010-04-06 18:45:08 +0000692 CS.setCalledFunction(NewV);
Chris Lattnere42eb312004-10-10 23:14:11 +0000693 Changed = true;
694 bool PassedAsArg = false;
Gabor Greif04397892010-04-06 18:45:08 +0000695 for (unsigned i = 0, e = CS.arg_size(); i != e; ++i)
696 if (CS.getArgument(i) == V) {
Chris Lattnere42eb312004-10-10 23:14:11 +0000697 PassedAsArg = true;
Gabor Greif04397892010-04-06 18:45:08 +0000698 CS.setArgument(i, NewV);
Chris Lattnere42eb312004-10-10 23:14:11 +0000699 }
700
701 if (PassedAsArg) {
702 // Being passed as an argument also. Be careful to not invalidate UI!
Chandler Carruthcdf47882014-03-09 03:16:01 +0000703 UI = V->user_begin();
Chris Lattnere42eb312004-10-10 23:14:11 +0000704 }
705 }
706 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
707 Changed |= OptimizeAwayTrappingUsesOfValue(CI,
Owen Anderson487375e2009-07-29 18:55:55 +0000708 ConstantExpr::getCast(CI->getOpcode(),
Chris Lattner46b5c642009-11-06 04:27:31 +0000709 NewV, CI->getType()));
Chris Lattnere42eb312004-10-10 23:14:11 +0000710 if (CI->use_empty()) {
711 Changed = true;
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000712 CI->eraseFromParent();
Chris Lattnere42eb312004-10-10 23:14:11 +0000713 }
714 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
715 // Should handle GEP here.
Chris Lattnerf96f4a82007-01-31 04:40:53 +0000716 SmallVector<Constant*, 8> Idxs;
717 Idxs.reserve(GEPI->getNumOperands()-1);
Gabor Greif3a9fba52008-05-29 01:59:18 +0000718 for (User::op_iterator i = GEPI->op_begin() + 1, e = GEPI->op_end();
719 i != e; ++i)
720 if (Constant *C = dyn_cast<Constant>(*i))
Chris Lattnerf96f4a82007-01-31 04:40:53 +0000721 Idxs.push_back(C);
Chris Lattnere42eb312004-10-10 23:14:11 +0000722 else
723 break;
Chris Lattnerf96f4a82007-01-31 04:40:53 +0000724 if (Idxs.size() == GEPI->getNumOperands()-1)
David Blaikie4a2e73b2015-04-02 18:55:32 +0000725 Changed |= OptimizeAwayTrappingUsesOfValue(
726 GEPI, ConstantExpr::getGetElementPtr(nullptr, NewV, Idxs));
Chris Lattnere42eb312004-10-10 23:14:11 +0000727 if (GEPI->use_empty()) {
728 Changed = true;
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000729 GEPI->eraseFromParent();
Chris Lattnere42eb312004-10-10 23:14:11 +0000730 }
731 }
732 }
733
734 return Changed;
735}
736
737
738/// OptimizeAwayTrappingUsesOfLoads - The specified global has only one non-null
739/// value stored into it. If there are uses of the loaded value that would trap
740/// if the loaded value is dynamically null, then we know that they cannot be
741/// reachable with a null optimize away the load.
Nick Lewyckycf6aae62012-02-12 01:13:18 +0000742static bool OptimizeAwayTrappingUsesOfLoads(GlobalVariable *GV, Constant *LV,
Mehdi Amini46a43552015-03-04 18:43:29 +0000743 const DataLayout &DL,
Nick Lewyckycf6aae62012-02-12 01:13:18 +0000744 TargetLibraryInfo *TLI) {
Chris Lattnere42eb312004-10-10 23:14:11 +0000745 bool Changed = false;
746
Chris Lattner2538eb62009-01-14 00:12:58 +0000747 // Keep track of whether we are able to remove all the uses of the global
748 // other than the store that defines it.
749 bool AllNonStoreUsesGone = true;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000750
Chris Lattnere42eb312004-10-10 23:14:11 +0000751 // Replace all uses of loads with uses of uses of the stored value.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000752 for (Value::user_iterator GUI = GV->user_begin(), E = GV->user_end(); GUI != E;){
Chris Lattner2538eb62009-01-14 00:12:58 +0000753 User *GlobalUser = *GUI++;
754 if (LoadInst *LI = dyn_cast<LoadInst>(GlobalUser)) {
Chris Lattner46b5c642009-11-06 04:27:31 +0000755 Changed |= OptimizeAwayTrappingUsesOfValue(LI, LV);
Chris Lattner2538eb62009-01-14 00:12:58 +0000756 // If we were able to delete all uses of the loads
757 if (LI->use_empty()) {
758 LI->eraseFromParent();
759 Changed = true;
760 } else {
761 AllNonStoreUsesGone = false;
762 }
763 } else if (isa<StoreInst>(GlobalUser)) {
764 // Ignore the store that stores "LV" to the global.
765 assert(GlobalUser->getOperand(1) == GV &&
766 "Must be storing *to* the global");
Chris Lattnere42eb312004-10-10 23:14:11 +0000767 } else {
Chris Lattner2538eb62009-01-14 00:12:58 +0000768 AllNonStoreUsesGone = false;
769
770 // If we get here we could have other crazy uses that are transitively
771 // loaded.
772 assert((isa<PHINode>(GlobalUser) || isa<SelectInst>(GlobalUser) ||
Benjamin Kramered843602012-09-28 10:01:27 +0000773 isa<ConstantExpr>(GlobalUser) || isa<CmpInst>(GlobalUser) ||
774 isa<BitCastInst>(GlobalUser) ||
775 isa<GetElementPtrInst>(GlobalUser)) &&
Chris Lattner1a1acc22011-05-22 07:15:13 +0000776 "Only expect load and stores!");
Chris Lattnere42eb312004-10-10 23:14:11 +0000777 }
Chris Lattner2538eb62009-01-14 00:12:58 +0000778 }
Chris Lattnere42eb312004-10-10 23:14:11 +0000779
780 if (Changed) {
David Greene44cb8ad2010-01-05 01:28:05 +0000781 DEBUG(dbgs() << "OPTIMIZED LOADS FROM STORED ONCE POINTER: " << *GV);
Chris Lattnere42eb312004-10-10 23:14:11 +0000782 ++NumGlobUses;
783 }
784
Chris Lattnere42eb312004-10-10 23:14:11 +0000785 // If we nuked all of the loads, then none of the stores are needed either,
786 // nor is the global.
Chris Lattner2538eb62009-01-14 00:12:58 +0000787 if (AllNonStoreUsesGone) {
Nick Lewyckyfaa9c3b02012-07-24 07:21:08 +0000788 if (isLeakCheckerRoot(GV)) {
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000789 Changed |= CleanupPointerRootUsers(GV, TLI);
Nick Lewyckyfaa9c3b02012-07-24 07:21:08 +0000790 } else {
791 Changed = true;
Craig Topperf40110f2014-04-25 05:29:35 +0000792 CleanupConstantGlobalUsers(GV, nullptr, DL, TLI);
Nick Lewyckyfaa9c3b02012-07-24 07:21:08 +0000793 }
Chris Lattnere42eb312004-10-10 23:14:11 +0000794 if (GV->use_empty()) {
Nick Lewyckyfaa9c3b02012-07-24 07:21:08 +0000795 DEBUG(dbgs() << " *** GLOBAL NOW DEAD!\n");
796 Changed = true;
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000797 GV->eraseFromParent();
Chris Lattnere42eb312004-10-10 23:14:11 +0000798 ++NumDeleted;
799 }
Chris Lattnere42eb312004-10-10 23:14:11 +0000800 }
801 return Changed;
802}
803
Chris Lattner004e2502004-10-11 05:54:41 +0000804/// ConstantPropUsersOf - Walk the use list of V, constant folding all of the
805/// instructions that are foldable.
Mehdi Amini46a43552015-03-04 18:43:29 +0000806static void ConstantPropUsersOf(Value *V, const DataLayout &DL,
Rafael Espindolaaeff8a92014-02-24 23:12:18 +0000807 TargetLibraryInfo *TLI) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000808 for (Value::user_iterator UI = V->user_begin(), E = V->user_end(); UI != E; )
Chris Lattner004e2502004-10-11 05:54:41 +0000809 if (Instruction *I = dyn_cast<Instruction>(*UI++))
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000810 if (Constant *NewC = ConstantFoldInstruction(I, DL, TLI)) {
Chris Lattner004e2502004-10-11 05:54:41 +0000811 I->replaceAllUsesWith(NewC);
812
Chris Lattnerd6a44922005-02-01 01:23:31 +0000813 // Advance UI to the next non-I use to avoid invalidating it!
814 // Instructions could multiply use V.
815 while (UI != E && *UI == I)
Chris Lattner004e2502004-10-11 05:54:41 +0000816 ++UI;
Chris Lattnerd6a44922005-02-01 01:23:31 +0000817 I->eraseFromParent();
Chris Lattner004e2502004-10-11 05:54:41 +0000818 }
819}
820
821/// OptimizeGlobalAddressOfMalloc - This function takes the specified global
822/// variable, and transforms the program as if it always contained the result of
823/// the specified malloc. Because it is always the result of the specified
824/// malloc, there is no reason to actually DO the malloc. Instead, turn the
Chris Lattner3ede00b2006-11-30 17:32:29 +0000825/// malloc into a global, and any loads of GV as uses of the new global.
Mehdi Amini46a43552015-03-04 18:43:29 +0000826static GlobalVariable *
827OptimizeGlobalAddressOfMalloc(GlobalVariable *GV, CallInst *CI, Type *AllocTy,
828 ConstantInt *NElements, const DataLayout &DL,
829 TargetLibraryInfo *TLI) {
Chris Lattner7939f792010-02-25 22:33:52 +0000830 DEBUG(errs() << "PROMOTING GLOBAL: " << *GV << " CALL = " << *CI << '\n');
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000831
Chris Lattner229907c2011-07-18 04:54:35 +0000832 Type *GlobalType;
Chris Lattner7939f792010-02-25 22:33:52 +0000833 if (NElements->getZExtValue() == 1)
834 GlobalType = AllocTy;
835 else
836 // If we have an array allocation, the global variable is of an array.
837 GlobalType = ArrayType::get(AllocTy, NElements->getZExtValue());
Victor Hernandez5d034492009-09-18 22:35:49 +0000838
839 // Create the new global variable. The contents of the malloc'd memory is
840 // undefined, so initialize with an undef value.
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000841 GlobalVariable *NewGV = new GlobalVariable(*GV->getParent(),
Chris Lattner65d3a0a2010-02-26 23:42:13 +0000842 GlobalType, false,
Chris Lattner7939f792010-02-25 22:33:52 +0000843 GlobalValue::InternalLinkage,
Chris Lattner65d3a0a2010-02-26 23:42:13 +0000844 UndefValue::get(GlobalType),
Victor Hernandez5d034492009-09-18 22:35:49 +0000845 GV->getName()+".body",
846 GV,
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000847 GV->getThreadLocalMode());
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000848
Chris Lattner7939f792010-02-25 22:33:52 +0000849 // If there are bitcast users of the malloc (which is typical, usually we have
850 // a malloc + bitcast) then replace them with uses of the new global. Update
851 // other users to use the global as well.
Craig Topperf40110f2014-04-25 05:29:35 +0000852 BitCastInst *TheBC = nullptr;
Chris Lattner7939f792010-02-25 22:33:52 +0000853 while (!CI->use_empty()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000854 Instruction *User = cast<Instruction>(CI->user_back());
Chris Lattner7939f792010-02-25 22:33:52 +0000855 if (BitCastInst *BCI = dyn_cast<BitCastInst>(User)) {
856 if (BCI->getType() == NewGV->getType()) {
857 BCI->replaceAllUsesWith(NewGV);
858 BCI->eraseFromParent();
859 } else {
860 BCI->setOperand(0, NewGV);
861 }
862 } else {
Craig Topperf40110f2014-04-25 05:29:35 +0000863 if (!TheBC)
Chris Lattner7939f792010-02-25 22:33:52 +0000864 TheBC = new BitCastInst(NewGV, CI->getType(), "newgv", CI);
865 User->replaceUsesOfWith(CI, TheBC);
866 }
867 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000868
Victor Hernandez5d034492009-09-18 22:35:49 +0000869 Constant *RepValue = NewGV;
870 if (NewGV->getType() != GV->getType()->getElementType())
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000871 RepValue = ConstantExpr::getBitCast(RepValue,
Victor Hernandez5d034492009-09-18 22:35:49 +0000872 GV->getType()->getElementType());
873
874 // If there is a comparison against null, we will insert a global bool to
875 // keep track of whether the global was initialized yet or not.
876 GlobalVariable *InitBool =
Chris Lattner46b5c642009-11-06 04:27:31 +0000877 new GlobalVariable(Type::getInt1Ty(GV->getContext()), false,
Victor Hernandez5d034492009-09-18 22:35:49 +0000878 GlobalValue::InternalLinkage,
Chris Lattner46b5c642009-11-06 04:27:31 +0000879 ConstantInt::getFalse(GV->getContext()),
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000880 GV->getName()+".init", GV->getThreadLocalMode());
Victor Hernandez5d034492009-09-18 22:35:49 +0000881 bool InitBoolUsed = false;
882
883 // Loop over all uses of GV, processing them in turn.
Chris Lattner7939f792010-02-25 22:33:52 +0000884 while (!GV->use_empty()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000885 if (StoreInst *SI = dyn_cast<StoreInst>(GV->user_back())) {
Victor Hernandez5d034492009-09-18 22:35:49 +0000886 // The global is initialized when the store to it occurs.
Nick Lewycky52da72b2012-02-05 19:56:38 +0000887 new StoreInst(ConstantInt::getTrue(GV->getContext()), InitBool, false, 0,
888 SI->getOrdering(), SI->getSynchScope(), SI);
Victor Hernandez5d034492009-09-18 22:35:49 +0000889 SI->eraseFromParent();
Chris Lattner7939f792010-02-25 22:33:52 +0000890 continue;
Victor Hernandez5d034492009-09-18 22:35:49 +0000891 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000892
Chandler Carruthcdf47882014-03-09 03:16:01 +0000893 LoadInst *LI = cast<LoadInst>(GV->user_back());
Chris Lattner7939f792010-02-25 22:33:52 +0000894 while (!LI->use_empty()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000895 Use &LoadUse = *LI->use_begin();
896 ICmpInst *ICI = dyn_cast<ICmpInst>(LoadUse.getUser());
897 if (!ICI) {
Chris Lattner7939f792010-02-25 22:33:52 +0000898 LoadUse = RepValue;
899 continue;
900 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000901
Chris Lattner7939f792010-02-25 22:33:52 +0000902 // Replace the cmp X, 0 with a use of the bool value.
Nick Lewycky52da72b2012-02-05 19:56:38 +0000903 // Sink the load to where the compare was, if atomic rules allow us to.
904 Value *LV = new LoadInst(InitBool, InitBool->getName()+".val", false, 0,
905 LI->getOrdering(), LI->getSynchScope(),
906 LI->isUnordered() ? (Instruction*)ICI : LI);
Chris Lattner7939f792010-02-25 22:33:52 +0000907 InitBoolUsed = true;
908 switch (ICI->getPredicate()) {
909 default: llvm_unreachable("Unknown ICmp Predicate!");
910 case ICmpInst::ICMP_ULT:
911 case ICmpInst::ICMP_SLT: // X < null -> always false
912 LV = ConstantInt::getFalse(GV->getContext());
913 break;
914 case ICmpInst::ICMP_ULE:
915 case ICmpInst::ICMP_SLE:
916 case ICmpInst::ICMP_EQ:
917 LV = BinaryOperator::CreateNot(LV, "notinit", ICI);
918 break;
919 case ICmpInst::ICMP_NE:
920 case ICmpInst::ICMP_UGE:
921 case ICmpInst::ICMP_SGE:
922 case ICmpInst::ICMP_UGT:
923 case ICmpInst::ICMP_SGT:
924 break; // no change.
925 }
926 ICI->replaceAllUsesWith(LV);
927 ICI->eraseFromParent();
928 }
929 LI->eraseFromParent();
930 }
Victor Hernandez5d034492009-09-18 22:35:49 +0000931
932 // If the initialization boolean was used, insert it, otherwise delete it.
933 if (!InitBoolUsed) {
934 while (!InitBool->use_empty()) // Delete initializations
Chandler Carruthcdf47882014-03-09 03:16:01 +0000935 cast<StoreInst>(InitBool->user_back())->eraseFromParent();
Victor Hernandez5d034492009-09-18 22:35:49 +0000936 delete InitBool;
937 } else
938 GV->getParent()->getGlobalList().insert(GV, InitBool);
939
Chris Lattner7939f792010-02-25 22:33:52 +0000940 // Now the GV is dead, nuke it and the malloc..
Victor Hernandez5d034492009-09-18 22:35:49 +0000941 GV->eraseFromParent();
Victor Hernandez5d034492009-09-18 22:35:49 +0000942 CI->eraseFromParent();
943
944 // To further other optimizations, loop over all users of NewGV and try to
945 // constant prop them. This will promote GEP instructions with constant
946 // indices into GEP constant-exprs, which will allow global-opt to hack on it.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000947 ConstantPropUsersOf(NewGV, DL, TLI);
Victor Hernandez5d034492009-09-18 22:35:49 +0000948 if (RepValue != NewGV)
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000949 ConstantPropUsersOf(RepValue, DL, TLI);
Victor Hernandez5d034492009-09-18 22:35:49 +0000950
951 return NewGV;
952}
953
Chris Lattnerc0677c02004-12-02 07:11:07 +0000954/// ValueIsOnlyUsedLocallyOrStoredToOneGlobal - Scan the use-list of V checking
955/// to make sure that there are no complex uses of V. We permit simple things
956/// like dereferencing the pointer, but not storing through the address, unless
957/// it is to the specified global.
Gabor Greifa21bc0f2010-04-06 18:58:22 +0000958static bool ValueIsOnlyUsedLocallyOrStoredToOneGlobal(const Instruction *V,
959 const GlobalVariable *GV,
Craig Topper71b7b682014-08-21 05:55:13 +0000960 SmallPtrSetImpl<const PHINode*> &PHIs) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000961 for (const User *U : V->users()) {
962 const Instruction *Inst = cast<Instruction>(U);
Gabor Greif08355d62010-04-06 19:14:05 +0000963
Chris Lattnerf0eb5682008-12-15 21:08:54 +0000964 if (isa<LoadInst>(Inst) || isa<CmpInst>(Inst)) {
965 continue; // Fine, ignore.
966 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000967
Gabor Greifa21bc0f2010-04-06 18:58:22 +0000968 if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
Chris Lattnerc0677c02004-12-02 07:11:07 +0000969 if (SI->getOperand(0) == V && SI->getOperand(1) != GV)
970 return false; // Storing the pointer itself... bad.
Chris Lattnerf0eb5682008-12-15 21:08:54 +0000971 continue; // Otherwise, storing through it, or storing into GV... fine.
972 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000973
Chris Lattnerb9801ff2010-04-10 18:19:22 +0000974 // Must index into the array and into the struct.
975 if (isa<GetElementPtrInst>(Inst) && Inst->getNumOperands() >= 3) {
Chris Lattnerf0eb5682008-12-15 21:08:54 +0000976 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(Inst, GV, PHIs))
Chris Lattnerc0677c02004-12-02 07:11:07 +0000977 return false;
Chris Lattnerf0eb5682008-12-15 21:08:54 +0000978 continue;
979 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000980
Gabor Greifa21bc0f2010-04-06 18:58:22 +0000981 if (const PHINode *PN = dyn_cast<PHINode>(Inst)) {
Chris Lattner6eed0e72007-09-13 16:37:20 +0000982 // PHIs are ok if all uses are ok. Don't infinitely recurse through PHI
983 // cycles.
David Blaikie70573dc2014-11-19 07:49:26 +0000984 if (PHIs.insert(PN).second)
Chris Lattner5d13fb532007-09-14 03:41:21 +0000985 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(PN, GV, PHIs))
986 return false;
Chris Lattnerf0eb5682008-12-15 21:08:54 +0000987 continue;
Chris Lattnerc0677c02004-12-02 07:11:07 +0000988 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000989
Gabor Greifa21bc0f2010-04-06 18:58:22 +0000990 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Inst)) {
Chris Lattnerf0eb5682008-12-15 21:08:54 +0000991 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(BCI, GV, PHIs))
992 return false;
993 continue;
994 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000995
Chris Lattnerf0eb5682008-12-15 21:08:54 +0000996 return false;
997 }
Chris Lattnerc0677c02004-12-02 07:11:07 +0000998 return true;
Chris Lattnerc0677c02004-12-02 07:11:07 +0000999}
1000
Chris Lattner24d3d422006-09-30 23:32:09 +00001001/// ReplaceUsesOfMallocWithGlobal - The Alloc pointer is stored into GV
1002/// somewhere. Transform all uses of the allocation into loads from the
1003/// global and uses of the resultant pointer. Further, delete the store into
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001004/// GV. This assumes that these value pass the
Chris Lattner24d3d422006-09-30 23:32:09 +00001005/// 'ValueIsOnlyUsedLocallyOrStoredToOneGlobal' predicate.
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001006static void ReplaceUsesOfMallocWithGlobal(Instruction *Alloc,
Chris Lattner24d3d422006-09-30 23:32:09 +00001007 GlobalVariable *GV) {
1008 while (!Alloc->use_empty()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00001009 Instruction *U = cast<Instruction>(*Alloc->user_begin());
Chris Lattnerba98f892007-09-13 18:00:31 +00001010 Instruction *InsertPt = U;
Chris Lattner24d3d422006-09-30 23:32:09 +00001011 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
1012 // If this is the store of the allocation into the global, remove it.
1013 if (SI->getOperand(1) == GV) {
1014 SI->eraseFromParent();
1015 continue;
1016 }
Chris Lattnerba98f892007-09-13 18:00:31 +00001017 } else if (PHINode *PN = dyn_cast<PHINode>(U)) {
1018 // Insert the load in the corresponding predecessor, not right before the
1019 // PHI.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001020 InsertPt = PN->getIncomingBlock(*Alloc->use_begin())->getTerminator();
Chris Lattner49e3bdc2008-12-15 21:44:34 +00001021 } else if (isa<BitCastInst>(U)) {
1022 // Must be bitcast between the malloc and store to initialize the global.
1023 ReplaceUsesOfMallocWithGlobal(U, GV);
1024 U->eraseFromParent();
1025 continue;
1026 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
1027 // If this is a "GEP bitcast" and the user is a store to the global, then
1028 // just process it as a bitcast.
1029 if (GEPI->hasAllZeroIndices() && GEPI->hasOneUse())
Chandler Carruthcdf47882014-03-09 03:16:01 +00001030 if (StoreInst *SI = dyn_cast<StoreInst>(GEPI->user_back()))
Chris Lattner49e3bdc2008-12-15 21:44:34 +00001031 if (SI->getOperand(1) == GV) {
1032 // Must be bitcast GEP between the malloc and store to initialize
1033 // the global.
1034 ReplaceUsesOfMallocWithGlobal(GEPI, GV);
1035 GEPI->eraseFromParent();
1036 continue;
1037 }
Chris Lattner24d3d422006-09-30 23:32:09 +00001038 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001039
Chris Lattner24d3d422006-09-30 23:32:09 +00001040 // Insert a load from the global, and use it instead of the malloc.
Chris Lattnerba98f892007-09-13 18:00:31 +00001041 Value *NL = new LoadInst(GV, GV->getName()+".val", InsertPt);
Chris Lattner24d3d422006-09-30 23:32:09 +00001042 U->replaceUsesOfWith(Alloc, NL);
1043 }
1044}
1045
Chris Lattner56b55382008-12-16 21:24:51 +00001046/// LoadUsesSimpleEnoughForHeapSRA - Verify that all uses of V (a load, or a phi
1047/// of a load) are simple enough to perform heap SRA on. This permits GEP's
1048/// that index through the array and struct field, icmps of null, and PHIs.
Gabor Greif5d5db532010-04-01 08:21:08 +00001049static bool LoadUsesSimpleEnoughForHeapSRA(const Value *V,
Craig Topper71b7b682014-08-21 05:55:13 +00001050 SmallPtrSetImpl<const PHINode*> &LoadUsingPHIs,
1051 SmallPtrSetImpl<const PHINode*> &LoadUsingPHIsPerLoad) {
Chris Lattner56b55382008-12-16 21:24:51 +00001052 // We permit two users of the load: setcc comparing against the null
1053 // pointer, and a getelementptr of a specific form.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001054 for (const User *U : V->users()) {
1055 const Instruction *UI = cast<Instruction>(U);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001056
Chris Lattner56b55382008-12-16 21:24:51 +00001057 // Comparison against null is ok.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001058 if (const ICmpInst *ICI = dyn_cast<ICmpInst>(UI)) {
Chris Lattner56b55382008-12-16 21:24:51 +00001059 if (!isa<ConstantPointerNull>(ICI->getOperand(1)))
1060 return false;
1061 continue;
1062 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001063
Chris Lattner56b55382008-12-16 21:24:51 +00001064 // getelementptr is also ok, but only a simple form.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001065 if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(UI)) {
Chris Lattner56b55382008-12-16 21:24:51 +00001066 // Must index into the array and into the struct.
1067 if (GEPI->getNumOperands() < 3)
1068 return false;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001069
Chris Lattner56b55382008-12-16 21:24:51 +00001070 // Otherwise the GEP is ok.
1071 continue;
1072 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001073
Chandler Carruthcdf47882014-03-09 03:16:01 +00001074 if (const PHINode *PN = dyn_cast<PHINode>(UI)) {
David Blaikie70573dc2014-11-19 07:49:26 +00001075 if (!LoadUsingPHIsPerLoad.insert(PN).second)
Evan Cheng83689442009-06-02 00:56:07 +00001076 // This means some phi nodes are dependent on each other.
1077 // Avoid infinite looping!
1078 return false;
David Blaikie70573dc2014-11-19 07:49:26 +00001079 if (!LoadUsingPHIs.insert(PN).second)
Evan Cheng83689442009-06-02 00:56:07 +00001080 // If we have already analyzed this PHI, then it is safe.
Chris Lattner56b55382008-12-16 21:24:51 +00001081 continue;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001082
Chris Lattner222ef4c2008-12-17 05:28:49 +00001083 // Make sure all uses of the PHI are simple enough to transform.
Evan Cheng83689442009-06-02 00:56:07 +00001084 if (!LoadUsesSimpleEnoughForHeapSRA(PN,
1085 LoadUsingPHIs, LoadUsingPHIsPerLoad))
Chris Lattner56b55382008-12-16 21:24:51 +00001086 return false;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001087
Chris Lattner56b55382008-12-16 21:24:51 +00001088 continue;
Chris Lattner24d3d422006-09-30 23:32:09 +00001089 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001090
Chris Lattner56b55382008-12-16 21:24:51 +00001091 // Otherwise we don't know what this is, not ok.
1092 return false;
1093 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001094
Chris Lattner56b55382008-12-16 21:24:51 +00001095 return true;
1096}
1097
1098
1099/// AllGlobalLoadUsesSimpleEnoughForHeapSRA - If all users of values loaded from
1100/// GV are simple enough to perform HeapSRA, return true.
Gabor Greif5d5db532010-04-01 08:21:08 +00001101static bool AllGlobalLoadUsesSimpleEnoughForHeapSRA(const GlobalVariable *GV,
Victor Hernandez5d034492009-09-18 22:35:49 +00001102 Instruction *StoredVal) {
Gabor Greif5d5db532010-04-01 08:21:08 +00001103 SmallPtrSet<const PHINode*, 32> LoadUsingPHIs;
1104 SmallPtrSet<const PHINode*, 32> LoadUsingPHIsPerLoad;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001105 for (const User *U : GV->users())
1106 if (const LoadInst *LI = dyn_cast<LoadInst>(U)) {
Evan Cheng83689442009-06-02 00:56:07 +00001107 if (!LoadUsesSimpleEnoughForHeapSRA(LI, LoadUsingPHIs,
1108 LoadUsingPHIsPerLoad))
Chris Lattner56b55382008-12-16 21:24:51 +00001109 return false;
Evan Cheng83689442009-06-02 00:56:07 +00001110 LoadUsingPHIsPerLoad.clear();
1111 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001112
Chris Lattner222ef4c2008-12-17 05:28:49 +00001113 // If we reach here, we know that all uses of the loads and transitive uses
1114 // (through PHI nodes) are simple enough to transform. However, we don't know
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001115 // that all inputs the to the PHI nodes are in the same equivalence sets.
Chris Lattner222ef4c2008-12-17 05:28:49 +00001116 // Check to verify that all operands of the PHIs are either PHIS that can be
1117 // transformed, loads from GV, or MI itself.
Craig Topper46276792014-08-24 23:23:06 +00001118 for (const PHINode *PN : LoadUsingPHIs) {
Chris Lattner222ef4c2008-12-17 05:28:49 +00001119 for (unsigned op = 0, e = PN->getNumIncomingValues(); op != e; ++op) {
1120 Value *InVal = PN->getIncomingValue(op);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001121
Chris Lattner222ef4c2008-12-17 05:28:49 +00001122 // PHI of the stored value itself is ok.
Victor Hernandez5d034492009-09-18 22:35:49 +00001123 if (InVal == StoredVal) continue;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001124
Gabor Greif5d5db532010-04-01 08:21:08 +00001125 if (const PHINode *InPN = dyn_cast<PHINode>(InVal)) {
Chris Lattner222ef4c2008-12-17 05:28:49 +00001126 // One of the PHIs in our set is (optimistically) ok.
1127 if (LoadUsingPHIs.count(InPN))
1128 continue;
1129 return false;
1130 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001131
Chris Lattner222ef4c2008-12-17 05:28:49 +00001132 // Load from GV is ok.
Gabor Greif5d5db532010-04-01 08:21:08 +00001133 if (const LoadInst *LI = dyn_cast<LoadInst>(InVal))
Chris Lattner222ef4c2008-12-17 05:28:49 +00001134 if (LI->getOperand(0) == GV)
1135 continue;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001136
Chris Lattner222ef4c2008-12-17 05:28:49 +00001137 // UNDEF? NULL?
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001138
Chris Lattner222ef4c2008-12-17 05:28:49 +00001139 // Anything else is rejected.
1140 return false;
1141 }
1142 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001143
Chris Lattner24d3d422006-09-30 23:32:09 +00001144 return true;
1145}
1146
Chris Lattner222ef4c2008-12-17 05:28:49 +00001147static Value *GetHeapSROAValue(Value *V, unsigned FieldNo,
1148 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Chris Lattner46b5c642009-11-06 04:27:31 +00001149 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
Chris Lattner222ef4c2008-12-17 05:28:49 +00001150 std::vector<Value*> &FieldVals = InsertedScalarizedValues[V];
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001151
Chris Lattner222ef4c2008-12-17 05:28:49 +00001152 if (FieldNo >= FieldVals.size())
1153 FieldVals.resize(FieldNo+1);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001154
Chris Lattner222ef4c2008-12-17 05:28:49 +00001155 // If we already have this value, just reuse the previously scalarized
1156 // version.
1157 if (Value *FieldVal = FieldVals[FieldNo])
1158 return FieldVal;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001159
Chris Lattner222ef4c2008-12-17 05:28:49 +00001160 // Depending on what instruction this is, we have several cases.
1161 Value *Result;
1162 if (LoadInst *LI = dyn_cast<LoadInst>(V)) {
1163 // This is a scalarized version of the load from the global. Just create
1164 // a new Load of the scalarized global.
1165 Result = new LoadInst(GetHeapSROAValue(LI->getOperand(0), FieldNo,
1166 InsertedScalarizedValues,
Chris Lattner46b5c642009-11-06 04:27:31 +00001167 PHIsToRewrite),
Daniel Dunbar132f7832009-07-30 17:37:43 +00001168 LI->getName()+".f"+Twine(FieldNo), LI);
David Blaikie741c8f82015-03-14 01:53:18 +00001169 } else {
1170 PHINode *PN = cast<PHINode>(V);
Chris Lattner222ef4c2008-12-17 05:28:49 +00001171 // PN's type is pointer to struct. Make a new PHI of pointer to struct
1172 // field.
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001173
Matt Arsenaultfcd74012014-04-23 20:36:10 +00001174 PointerType *PTy = cast<PointerType>(PN->getType());
1175 StructType *ST = cast<StructType>(PTy->getElementType());
1176
1177 unsigned AS = PTy->getAddressSpace();
Jay Foade0938d82011-03-30 11:19:20 +00001178 PHINode *NewPN =
Matt Arsenaultfcd74012014-04-23 20:36:10 +00001179 PHINode::Create(PointerType::get(ST->getElementType(FieldNo), AS),
Jay Foad52131342011-03-30 11:28:46 +00001180 PN->getNumIncomingValues(),
Daniel Dunbar132f7832009-07-30 17:37:43 +00001181 PN->getName()+".f"+Twine(FieldNo), PN);
Jay Foade0938d82011-03-30 11:19:20 +00001182 Result = NewPN;
Chris Lattner222ef4c2008-12-17 05:28:49 +00001183 PHIsToRewrite.push_back(std::make_pair(PN, FieldNo));
Chris Lattner222ef4c2008-12-17 05:28:49 +00001184 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001185
Chris Lattner222ef4c2008-12-17 05:28:49 +00001186 return FieldVals[FieldNo] = Result;
Chris Lattnerba98f892007-09-13 18:00:31 +00001187}
1188
Chris Lattnerf315d4f2007-09-13 17:29:05 +00001189/// RewriteHeapSROALoadUser - Given a load instruction and a value derived from
1190/// the load, rewrite the derived value to use the HeapSRoA'd load.
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001191static void RewriteHeapSROALoadUser(Instruction *LoadUser,
Chris Lattner222ef4c2008-12-17 05:28:49 +00001192 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Chris Lattner46b5c642009-11-06 04:27:31 +00001193 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
Chris Lattnerf315d4f2007-09-13 17:29:05 +00001194 // If this is a comparison against null, handle it.
1195 if (ICmpInst *SCI = dyn_cast<ICmpInst>(LoadUser)) {
1196 assert(isa<ConstantPointerNull>(SCI->getOperand(1)));
1197 // If we have a setcc of the loaded pointer, we can use a setcc of any
1198 // field.
Chris Lattner222ef4c2008-12-17 05:28:49 +00001199 Value *NPtr = GetHeapSROAValue(SCI->getOperand(0), 0,
Chris Lattner46b5c642009-11-06 04:27:31 +00001200 InsertedScalarizedValues, PHIsToRewrite);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001201
Owen Anderson1e5f00e2009-07-09 23:48:35 +00001202 Value *New = new ICmpInst(SCI, SCI->getPredicate(), NPtr,
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001203 Constant::getNullValue(NPtr->getType()),
Owen Anderson1e5f00e2009-07-09 23:48:35 +00001204 SCI->getName());
Chris Lattnerf315d4f2007-09-13 17:29:05 +00001205 SCI->replaceAllUsesWith(New);
1206 SCI->eraseFromParent();
1207 return;
1208 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001209
Chris Lattner222ef4c2008-12-17 05:28:49 +00001210 // Handle 'getelementptr Ptr, Idx, i32 FieldNo ...'
Chris Lattnerba98f892007-09-13 18:00:31 +00001211 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(LoadUser)) {
1212 assert(GEPI->getNumOperands() >= 3 && isa<ConstantInt>(GEPI->getOperand(2))
1213 && "Unexpected GEPI!");
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001214
Chris Lattnerba98f892007-09-13 18:00:31 +00001215 // Load the pointer for this field.
1216 unsigned FieldNo = cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue();
Chris Lattner222ef4c2008-12-17 05:28:49 +00001217 Value *NewPtr = GetHeapSROAValue(GEPI->getOperand(0), FieldNo,
Chris Lattner46b5c642009-11-06 04:27:31 +00001218 InsertedScalarizedValues, PHIsToRewrite);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001219
Chris Lattnerba98f892007-09-13 18:00:31 +00001220 // Create the new GEP idx vector.
1221 SmallVector<Value*, 8> GEPIdx;
1222 GEPIdx.push_back(GEPI->getOperand(1));
1223 GEPIdx.append(GEPI->op_begin()+3, GEPI->op_end());
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001224
David Blaikie22319eb2015-03-14 19:24:04 +00001225 Value *NGEPI = GetElementPtrInst::Create(GEPI->getResultElementType(), NewPtr, GEPIdx,
Gabor Greife9ecc682008-04-06 20:25:17 +00001226 GEPI->getName(), GEPI);
Chris Lattnerba98f892007-09-13 18:00:31 +00001227 GEPI->replaceAllUsesWith(NGEPI);
1228 GEPI->eraseFromParent();
1229 return;
1230 }
Chris Lattner011f91b2007-09-13 21:31:36 +00001231
Chris Lattner222ef4c2008-12-17 05:28:49 +00001232 // Recursively transform the users of PHI nodes. This will lazily create the
1233 // PHIs that are needed for individual elements. Keep track of what PHIs we
1234 // see in InsertedScalarizedValues so that we don't get infinite loops (very
1235 // antisocial). If the PHI is already in InsertedScalarizedValues, it has
1236 // already been seen first by another load, so its uses have already been
1237 // processed.
1238 PHINode *PN = cast<PHINode>(LoadUser);
Chris Lattner5cf753c2011-07-21 06:21:31 +00001239 if (!InsertedScalarizedValues.insert(std::make_pair(PN,
1240 std::vector<Value*>())).second)
1241 return;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001242
Chris Lattner222ef4c2008-12-17 05:28:49 +00001243 // If this is the first time we've seen this PHI, recursively process all
1244 // users.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001245 for (auto UI = PN->user_begin(), E = PN->user_end(); UI != E;) {
Chris Lattner0cdf5232008-12-17 05:42:08 +00001246 Instruction *User = cast<Instruction>(*UI++);
Chris Lattner46b5c642009-11-06 04:27:31 +00001247 RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite);
Chris Lattner0cdf5232008-12-17 05:42:08 +00001248 }
Chris Lattnerf315d4f2007-09-13 17:29:05 +00001249}
1250
Chris Lattner24d3d422006-09-30 23:32:09 +00001251/// RewriteUsesOfLoadForHeapSRoA - We are performing Heap SRoA on a global. Ptr
1252/// is a value loaded from the global. Eliminate all uses of Ptr, making them
1253/// use FieldGlobals instead. All uses of loaded values satisfy
Chris Lattner56b55382008-12-16 21:24:51 +00001254/// AllGlobalLoadUsesSimpleEnoughForHeapSRA.
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001255static void RewriteUsesOfLoadForHeapSRoA(LoadInst *Load,
Chris Lattner222ef4c2008-12-17 05:28:49 +00001256 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Chris Lattner46b5c642009-11-06 04:27:31 +00001257 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00001258 for (auto UI = Load->user_begin(), E = Load->user_end(); UI != E;) {
Chris Lattner0cdf5232008-12-17 05:42:08 +00001259 Instruction *User = cast<Instruction>(*UI++);
Chris Lattner46b5c642009-11-06 04:27:31 +00001260 RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite);
Chris Lattner0cdf5232008-12-17 05:42:08 +00001261 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001262
Chris Lattner222ef4c2008-12-17 05:28:49 +00001263 if (Load->use_empty()) {
1264 Load->eraseFromParent();
1265 InsertedScalarizedValues.erase(Load);
1266 }
Chris Lattner24d3d422006-09-30 23:32:09 +00001267}
1268
Victor Hernandez5d034492009-09-18 22:35:49 +00001269/// PerformHeapAllocSRoA - CI is an allocation of an array of structures. Break
1270/// it up into multiple allocations of arrays of the fields.
Victor Hernandezf3db9152009-11-07 00:16:28 +00001271static GlobalVariable *PerformHeapAllocSRoA(GlobalVariable *GV, CallInst *CI,
Mehdi Amini46a43552015-03-04 18:43:29 +00001272 Value *NElems, const DataLayout &DL,
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00001273 const TargetLibraryInfo *TLI) {
David Greene44cb8ad2010-01-05 01:28:05 +00001274 DEBUG(dbgs() << "SROA HEAP ALLOC: " << *GV << " MALLOC = " << *CI << '\n');
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00001275 Type *MAT = getMallocAllocatedType(CI, TLI);
Chris Lattner229907c2011-07-18 04:54:35 +00001276 StructType *STy = cast<StructType>(MAT);
Victor Hernandez5d034492009-09-18 22:35:49 +00001277
1278 // There is guaranteed to be at least one use of the malloc (storing
1279 // it into GV). If there are other uses, change them to be uses of
1280 // the global to simplify later code. This also deletes the store
1281 // into GV.
Victor Hernandezf3db9152009-11-07 00:16:28 +00001282 ReplaceUsesOfMallocWithGlobal(CI, GV);
1283
Victor Hernandez5d034492009-09-18 22:35:49 +00001284 // Okay, at this point, there are no users of the malloc. Insert N
1285 // new mallocs at the same place as CI, and N globals.
1286 std::vector<Value*> FieldGlobals;
1287 std::vector<Value*> FieldMallocs;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001288
Matt Arsenaultfcd74012014-04-23 20:36:10 +00001289 unsigned AS = GV->getType()->getPointerAddressSpace();
Victor Hernandez5d034492009-09-18 22:35:49 +00001290 for (unsigned FieldNo = 0, e = STy->getNumElements(); FieldNo != e;++FieldNo){
Chris Lattner229907c2011-07-18 04:54:35 +00001291 Type *FieldTy = STy->getElementType(FieldNo);
Matt Arsenaultfcd74012014-04-23 20:36:10 +00001292 PointerType *PFieldTy = PointerType::get(FieldTy, AS);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001293
Victor Hernandez5d034492009-09-18 22:35:49 +00001294 GlobalVariable *NGV =
1295 new GlobalVariable(*GV->getParent(),
1296 PFieldTy, false, GlobalValue::InternalLinkage,
1297 Constant::getNullValue(PFieldTy),
1298 GV->getName() + ".f" + Twine(FieldNo), GV,
Hans Wennborgcbe34b42012-06-23 11:37:03 +00001299 GV->getThreadLocalMode());
Victor Hernandez5d034492009-09-18 22:35:49 +00001300 FieldGlobals.push_back(NGV);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001301
Mehdi Amini46a43552015-03-04 18:43:29 +00001302 unsigned TypeSize = DL.getTypeAllocSize(FieldTy);
Chris Lattner229907c2011-07-18 04:54:35 +00001303 if (StructType *ST = dyn_cast<StructType>(FieldTy))
Mehdi Amini46a43552015-03-04 18:43:29 +00001304 TypeSize = DL.getStructLayout(ST)->getSizeInBytes();
1305 Type *IntPtrTy = DL.getIntPtrType(CI->getType());
Victor Hernandezf3db9152009-11-07 00:16:28 +00001306 Value *NMI = CallInst::CreateMalloc(CI, IntPtrTy, FieldTy,
1307 ConstantInt::get(IntPtrTy, TypeSize),
Craig Topperf40110f2014-04-25 05:29:35 +00001308 NElems, nullptr,
Victor Hernandezf3db9152009-11-07 00:16:28 +00001309 CI->getName() + ".f" + Twine(FieldNo));
Chris Lattner0521c092010-02-26 18:23:13 +00001310 FieldMallocs.push_back(NMI);
Victor Hernandezf3db9152009-11-07 00:16:28 +00001311 new StoreInst(NMI, NGV, CI);
Victor Hernandez5d034492009-09-18 22:35:49 +00001312 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001313
Victor Hernandez5d034492009-09-18 22:35:49 +00001314 // The tricky aspect of this transformation is handling the case when malloc
1315 // fails. In the original code, malloc failing would set the result pointer
1316 // of malloc to null. In this case, some mallocs could succeed and others
1317 // could fail. As such, we emit code that looks like this:
1318 // F0 = malloc(field0)
1319 // F1 = malloc(field1)
1320 // F2 = malloc(field2)
1321 // if (F0 == 0 || F1 == 0 || F2 == 0) {
1322 // if (F0) { free(F0); F0 = 0; }
1323 // if (F1) { free(F1); F1 = 0; }
1324 // if (F2) { free(F2); F2 = 0; }
1325 // }
Victor Hernandezfcc77b12009-11-10 08:32:25 +00001326 // The malloc can also fail if its argument is too large.
Gabor Greif218f5542010-06-24 14:42:01 +00001327 Constant *ConstantZero = ConstantInt::get(CI->getArgOperand(0)->getType(), 0);
1328 Value *RunningOr = new ICmpInst(CI, ICmpInst::ICMP_SLT, CI->getArgOperand(0),
Victor Hernandezfcc77b12009-11-10 08:32:25 +00001329 ConstantZero, "isneg");
Victor Hernandez5d034492009-09-18 22:35:49 +00001330 for (unsigned i = 0, e = FieldMallocs.size(); i != e; ++i) {
Victor Hernandezf3db9152009-11-07 00:16:28 +00001331 Value *Cond = new ICmpInst(CI, ICmpInst::ICMP_EQ, FieldMallocs[i],
1332 Constant::getNullValue(FieldMallocs[i]->getType()),
1333 "isnull");
Victor Hernandezfcc77b12009-11-10 08:32:25 +00001334 RunningOr = BinaryOperator::CreateOr(RunningOr, Cond, "tmp", CI);
Victor Hernandez5d034492009-09-18 22:35:49 +00001335 }
1336
1337 // Split the basic block at the old malloc.
Victor Hernandezf3db9152009-11-07 00:16:28 +00001338 BasicBlock *OrigBB = CI->getParent();
1339 BasicBlock *ContBB = OrigBB->splitBasicBlock(CI, "malloc_cont");
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001340
Victor Hernandez5d034492009-09-18 22:35:49 +00001341 // Create the block to check the first condition. Put all these blocks at the
1342 // end of the function as they are unlikely to be executed.
Chris Lattner46b5c642009-11-06 04:27:31 +00001343 BasicBlock *NullPtrBlock = BasicBlock::Create(OrigBB->getContext(),
1344 "malloc_ret_null",
Victor Hernandez5d034492009-09-18 22:35:49 +00001345 OrigBB->getParent());
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001346
Victor Hernandez5d034492009-09-18 22:35:49 +00001347 // Remove the uncond branch from OrigBB to ContBB, turning it into a cond
1348 // branch on RunningOr.
1349 OrigBB->getTerminator()->eraseFromParent();
1350 BranchInst::Create(NullPtrBlock, ContBB, RunningOr, OrigBB);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001351
Victor Hernandez5d034492009-09-18 22:35:49 +00001352 // Within the NullPtrBlock, we need to emit a comparison and branch for each
1353 // pointer, because some may be null while others are not.
1354 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
1355 Value *GVVal = new LoadInst(FieldGlobals[i], "tmp", NullPtrBlock);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001356 Value *Cmp = new ICmpInst(*NullPtrBlock, ICmpInst::ICMP_NE, GVVal,
Benjamin Kramer547b6c52011-09-27 20:39:19 +00001357 Constant::getNullValue(GVVal->getType()));
Chris Lattner46b5c642009-11-06 04:27:31 +00001358 BasicBlock *FreeBlock = BasicBlock::Create(Cmp->getContext(), "free_it",
Victor Hernandez5d034492009-09-18 22:35:49 +00001359 OrigBB->getParent());
Chris Lattner46b5c642009-11-06 04:27:31 +00001360 BasicBlock *NextBlock = BasicBlock::Create(Cmp->getContext(), "next",
Victor Hernandez5d034492009-09-18 22:35:49 +00001361 OrigBB->getParent());
Victor Hernandeze2971492009-10-24 04:23:03 +00001362 Instruction *BI = BranchInst::Create(FreeBlock, NextBlock,
1363 Cmp, NullPtrBlock);
Victor Hernandez5d034492009-09-18 22:35:49 +00001364
1365 // Fill in FreeBlock.
Victor Hernandeze2971492009-10-24 04:23:03 +00001366 CallInst::CreateFree(GVVal, BI);
Victor Hernandez5d034492009-09-18 22:35:49 +00001367 new StoreInst(Constant::getNullValue(GVVal->getType()), FieldGlobals[i],
1368 FreeBlock);
1369 BranchInst::Create(NextBlock, FreeBlock);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001370
Victor Hernandez5d034492009-09-18 22:35:49 +00001371 NullPtrBlock = NextBlock;
1372 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001373
Victor Hernandez5d034492009-09-18 22:35:49 +00001374 BranchInst::Create(ContBB, NullPtrBlock);
Victor Hernandezf3db9152009-11-07 00:16:28 +00001375
1376 // CI is no longer needed, remove it.
Victor Hernandez5d034492009-09-18 22:35:49 +00001377 CI->eraseFromParent();
1378
1379 /// InsertedScalarizedLoads - As we process loads, if we can't immediately
1380 /// update all uses of the load, keep track of what scalarized loads are
1381 /// inserted for a given load.
1382 DenseMap<Value*, std::vector<Value*> > InsertedScalarizedValues;
1383 InsertedScalarizedValues[GV] = FieldGlobals;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001384
Victor Hernandez5d034492009-09-18 22:35:49 +00001385 std::vector<std::pair<PHINode*, unsigned> > PHIsToRewrite;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001386
Victor Hernandez5d034492009-09-18 22:35:49 +00001387 // Okay, the malloc site is completely handled. All of the uses of GV are now
1388 // loads, and all uses of those loads are simple. Rewrite them to use loads
1389 // of the per-field globals instead.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001390 for (auto UI = GV->user_begin(), E = GV->user_end(); UI != E;) {
Victor Hernandez5d034492009-09-18 22:35:49 +00001391 Instruction *User = cast<Instruction>(*UI++);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001392
Victor Hernandez5d034492009-09-18 22:35:49 +00001393 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Chris Lattner46b5c642009-11-06 04:27:31 +00001394 RewriteUsesOfLoadForHeapSRoA(LI, InsertedScalarizedValues, PHIsToRewrite);
Victor Hernandez5d034492009-09-18 22:35:49 +00001395 continue;
1396 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001397
Victor Hernandez5d034492009-09-18 22:35:49 +00001398 // Must be a store of null.
1399 StoreInst *SI = cast<StoreInst>(User);
1400 assert(isa<ConstantPointerNull>(SI->getOperand(0)) &&
1401 "Unexpected heap-sra user!");
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001402
Victor Hernandez5d034492009-09-18 22:35:49 +00001403 // Insert a store of null into each global.
1404 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
Chris Lattner229907c2011-07-18 04:54:35 +00001405 PointerType *PT = cast<PointerType>(FieldGlobals[i]->getType());
Victor Hernandez5d034492009-09-18 22:35:49 +00001406 Constant *Null = Constant::getNullValue(PT->getElementType());
1407 new StoreInst(Null, FieldGlobals[i], SI);
1408 }
1409 // Erase the original store.
1410 SI->eraseFromParent();
1411 }
1412
1413 // While we have PHIs that are interesting to rewrite, do it.
1414 while (!PHIsToRewrite.empty()) {
1415 PHINode *PN = PHIsToRewrite.back().first;
1416 unsigned FieldNo = PHIsToRewrite.back().second;
1417 PHIsToRewrite.pop_back();
1418 PHINode *FieldPN = cast<PHINode>(InsertedScalarizedValues[PN][FieldNo]);
1419 assert(FieldPN->getNumIncomingValues() == 0 &&"Already processed this phi");
1420
1421 // Add all the incoming values. This can materialize more phis.
1422 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1423 Value *InVal = PN->getIncomingValue(i);
1424 InVal = GetHeapSROAValue(InVal, FieldNo, InsertedScalarizedValues,
Chris Lattner46b5c642009-11-06 04:27:31 +00001425 PHIsToRewrite);
Victor Hernandez5d034492009-09-18 22:35:49 +00001426 FieldPN->addIncoming(InVal, PN->getIncomingBlock(i));
1427 }
1428 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001429
Victor Hernandez5d034492009-09-18 22:35:49 +00001430 // Drop all inter-phi links and any loads that made it this far.
1431 for (DenseMap<Value*, std::vector<Value*> >::iterator
1432 I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
1433 I != E; ++I) {
1434 if (PHINode *PN = dyn_cast<PHINode>(I->first))
1435 PN->dropAllReferences();
1436 else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
1437 LI->dropAllReferences();
1438 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001439
Victor Hernandez5d034492009-09-18 22:35:49 +00001440 // Delete all the phis and loads now that inter-references are dead.
1441 for (DenseMap<Value*, std::vector<Value*> >::iterator
1442 I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
1443 I != E; ++I) {
1444 if (PHINode *PN = dyn_cast<PHINode>(I->first))
1445 PN->eraseFromParent();
1446 else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
1447 LI->eraseFromParent();
1448 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001449
Victor Hernandez5d034492009-09-18 22:35:49 +00001450 // The old global is now dead, remove it.
1451 GV->eraseFromParent();
1452
1453 ++NumHeapSRA;
1454 return cast<GlobalVariable>(FieldGlobals[0]);
1455}
1456
Chris Lattnerc4274a72008-12-15 21:02:25 +00001457/// TryToOptimizeStoreOfMallocToGlobal - This function is called when we see a
1458/// pointer global variable with a single value stored it that is a malloc or
1459/// cast of malloc.
Mehdi Amini46a43552015-03-04 18:43:29 +00001460static bool TryToOptimizeStoreOfMallocToGlobal(GlobalVariable *GV, CallInst *CI,
Chris Lattner229907c2011-07-18 04:54:35 +00001461 Type *AllocTy,
Nick Lewycky52da72b2012-02-05 19:56:38 +00001462 AtomicOrdering Ordering,
Victor Hernandez5d034492009-09-18 22:35:49 +00001463 Module::global_iterator &GVI,
Mehdi Amini46a43552015-03-04 18:43:29 +00001464 const DataLayout &DL,
Nick Lewyckycf6aae62012-02-12 01:13:18 +00001465 TargetLibraryInfo *TLI) {
Victor Hernandez5d034492009-09-18 22:35:49 +00001466 // If this is a malloc of an abstract type, don't touch it.
1467 if (!AllocTy->isSized())
1468 return false;
1469
1470 // We can't optimize this global unless all uses of it are *known* to be
1471 // of the malloc value, not of the null initializer value (consider a use
1472 // that compares the global's value against zero to see if the malloc has
1473 // been reached). To do this, we check to see if all uses of the global
1474 // would trap if the global were null: this proves that they must all
1475 // happen after the malloc.
1476 if (!AllUsesOfLoadedValueWillTrapIfNull(GV))
1477 return false;
1478
1479 // We can't optimize this if the malloc itself is used in a complex way,
1480 // for example, being stored into multiple globals. This allows the
Nick Lewyckybbd11562012-02-05 19:48:37 +00001481 // malloc to be stored into the specified global, loaded icmp'd, and
Victor Hernandez5d034492009-09-18 22:35:49 +00001482 // GEP'd. These are all things we could transform to using the global
1483 // for.
Evan Cheng21b588b2010-04-14 20:52:55 +00001484 SmallPtrSet<const PHINode*, 8> PHIs;
1485 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(CI, GV, PHIs))
1486 return false;
Victor Hernandez5d034492009-09-18 22:35:49 +00001487
1488 // If we have a global that is only initialized with a fixed size malloc,
1489 // transform the program to use global memory instead of malloc'd memory.
1490 // This eliminates dynamic allocation, avoids an indirection accessing the
1491 // data, and exposes the resultant global to further GlobalOpt.
Victor Hernandez264da322009-10-16 23:12:25 +00001492 // We cannot optimize the malloc if we cannot determine malloc array size.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001493 Value *NElems = getMallocArraySize(CI, DL, TLI, true);
Evan Cheng21b588b2010-04-14 20:52:55 +00001494 if (!NElems)
1495 return false;
Victor Hernandez5d034492009-09-18 22:35:49 +00001496
Evan Cheng21b588b2010-04-14 20:52:55 +00001497 if (ConstantInt *NElements = dyn_cast<ConstantInt>(NElems))
1498 // Restrict this transformation to only working on small allocations
1499 // (2048 bytes currently), as we don't want to introduce a 16M global or
1500 // something.
Mehdi Amini46a43552015-03-04 18:43:29 +00001501 if (NElements->getZExtValue() * DL.getTypeAllocSize(AllocTy) < 2048) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001502 GVI = OptimizeGlobalAddressOfMalloc(GV, CI, AllocTy, NElements, DL, TLI);
Evan Cheng21b588b2010-04-14 20:52:55 +00001503 return true;
Victor Hernandez5d034492009-09-18 22:35:49 +00001504 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001505
Evan Cheng21b588b2010-04-14 20:52:55 +00001506 // If the allocation is an array of structures, consider transforming this
1507 // into multiple malloc'd arrays, one for each field. This is basically
1508 // SRoA for malloc'd memory.
1509
Nick Lewycky52da72b2012-02-05 19:56:38 +00001510 if (Ordering != NotAtomic)
1511 return false;
1512
Evan Cheng21b588b2010-04-14 20:52:55 +00001513 // If this is an allocation of a fixed size array of structs, analyze as a
1514 // variable size array. malloc [100 x struct],1 -> malloc struct, 100
Gabor Greif218f5542010-06-24 14:42:01 +00001515 if (NElems == ConstantInt::get(CI->getArgOperand(0)->getType(), 1))
Chris Lattner229907c2011-07-18 04:54:35 +00001516 if (ArrayType *AT = dyn_cast<ArrayType>(AllocTy))
Evan Cheng21b588b2010-04-14 20:52:55 +00001517 AllocTy = AT->getElementType();
Gabor Greif218f5542010-06-24 14:42:01 +00001518
Chris Lattner229907c2011-07-18 04:54:35 +00001519 StructType *AllocSTy = dyn_cast<StructType>(AllocTy);
Evan Cheng21b588b2010-04-14 20:52:55 +00001520 if (!AllocSTy)
1521 return false;
1522
1523 // This the structure has an unreasonable number of fields, leave it
1524 // alone.
1525 if (AllocSTy->getNumElements() <= 16 && AllocSTy->getNumElements() != 0 &&
1526 AllGlobalLoadUsesSimpleEnoughForHeapSRA(GV, CI)) {
1527
1528 // If this is a fixed size array, transform the Malloc to be an alloc of
1529 // structs. malloc [100 x struct],1 -> malloc struct, 100
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00001530 if (ArrayType *AT = dyn_cast<ArrayType>(getMallocAllocatedType(CI, TLI))) {
Mehdi Amini46a43552015-03-04 18:43:29 +00001531 Type *IntPtrTy = DL.getIntPtrType(CI->getType());
1532 unsigned TypeSize = DL.getStructLayout(AllocSTy)->getSizeInBytes();
Evan Cheng21b588b2010-04-14 20:52:55 +00001533 Value *AllocSize = ConstantInt::get(IntPtrTy, TypeSize);
1534 Value *NumElements = ConstantInt::get(IntPtrTy, AT->getNumElements());
1535 Instruction *Malloc = CallInst::CreateMalloc(CI, IntPtrTy, AllocSTy,
1536 AllocSize, NumElements,
Craig Topperf40110f2014-04-25 05:29:35 +00001537 nullptr, CI->getName());
Evan Cheng21b588b2010-04-14 20:52:55 +00001538 Instruction *Cast = new BitCastInst(Malloc, CI->getType(), "tmp", CI);
1539 CI->replaceAllUsesWith(Cast);
1540 CI->eraseFromParent();
Nuno Lopes9792d682012-06-22 00:25:01 +00001541 if (BitCastInst *BCI = dyn_cast<BitCastInst>(Malloc))
1542 CI = cast<CallInst>(BCI->getOperand(0));
1543 else
Nuno Lopes0b60ebb2012-06-22 00:29:58 +00001544 CI = cast<CallInst>(Malloc);
Evan Cheng21b588b2010-04-14 20:52:55 +00001545 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001546
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001547 GVI = PerformHeapAllocSRoA(GV, CI, getMallocArraySize(CI, DL, TLI, true),
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001548 DL, TLI);
Evan Cheng21b588b2010-04-14 20:52:55 +00001549 return true;
Victor Hernandez5d034492009-09-18 22:35:49 +00001550 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001551
Victor Hernandez5d034492009-09-18 22:35:49 +00001552 return false;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001553}
Victor Hernandez5d034492009-09-18 22:35:49 +00001554
Chris Lattner09a52722004-10-09 21:48:45 +00001555// OptimizeOnceStoredGlobal - Try to optimize globals based on the knowledge
1556// that only one value (besides its initializer) is ever stored to the global.
Chris Lattner004e2502004-10-11 05:54:41 +00001557static bool OptimizeOnceStoredGlobal(GlobalVariable *GV, Value *StoredOnceVal,
Nick Lewycky52da72b2012-02-05 19:56:38 +00001558 AtomicOrdering Ordering,
Chris Lattnerc2d3d312006-08-27 22:42:52 +00001559 Module::global_iterator &GVI,
Mehdi Amini46a43552015-03-04 18:43:29 +00001560 const DataLayout &DL,
Rafael Espindolaaeff8a92014-02-24 23:12:18 +00001561 TargetLibraryInfo *TLI) {
Chris Lattner1c731fa2008-12-15 21:20:32 +00001562 // Ignore no-op GEPs and bitcasts.
1563 StoredOnceVal = StoredOnceVal->stripPointerCasts();
Chris Lattner09a52722004-10-09 21:48:45 +00001564
Chris Lattnere42eb312004-10-10 23:14:11 +00001565 // If we are dealing with a pointer global that is initialized to null and
1566 // only has one (non-null) value stored into it, then we can optimize any
1567 // users of the loaded value (often calls and loads) that would trap if the
1568 // value was null.
Duncan Sands19d0b472010-02-16 11:11:14 +00001569 if (GV->getInitializer()->getType()->isPointerTy() &&
Chris Lattner09a52722004-10-09 21:48:45 +00001570 GV->getInitializer()->isNullValue()) {
Chris Lattnere42eb312004-10-10 23:14:11 +00001571 if (Constant *SOVC = dyn_cast<Constant>(StoredOnceVal)) {
1572 if (GV->getInitializer()->getType() != SOVC->getType())
Chris Lattner1a1acc22011-05-22 07:15:13 +00001573 SOVC = ConstantExpr::getBitCast(SOVC, GV->getInitializer()->getType());
Misha Brukmanb1c93172005-04-21 23:48:37 +00001574
Chris Lattnere42eb312004-10-10 23:14:11 +00001575 // Optimize away any trapping uses of the loaded value.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001576 if (OptimizeAwayTrappingUsesOfLoads(GV, SOVC, DL, TLI))
Chris Lattner604ed7a2004-10-10 17:07:12 +00001577 return true;
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00001578 } else if (CallInst *CI = extractMallocCall(StoredOnceVal, TLI)) {
1579 Type *MallocType = getMallocAllocatedType(CI, TLI);
Nick Lewyckycf6aae62012-02-12 01:13:18 +00001580 if (MallocType &&
1581 TryToOptimizeStoreOfMallocToGlobal(GV, CI, MallocType, Ordering, GVI,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001582 DL, TLI))
Victor Hernandezf3db9152009-11-07 00:16:28 +00001583 return true;
Chris Lattnere42eb312004-10-10 23:14:11 +00001584 }
Chris Lattner09a52722004-10-09 21:48:45 +00001585 }
Chris Lattner004e2502004-10-11 05:54:41 +00001586
Chris Lattner09a52722004-10-09 21:48:45 +00001587 return false;
1588}
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001589
Lang Hames459b5dc2014-03-23 04:22:31 +00001590/// TryToShrinkGlobalToBoolean - At this point, we have learned that the only
Chris Lattner20bbac32008-01-14 01:17:44 +00001591/// two values ever stored into GV are its initializer and OtherVal. See if we
Lang Hames459b5dc2014-03-23 04:22:31 +00001592/// can shrink the global into a boolean and select between the two values
1593/// whenever it is used. This exposes the values to other scalar optimizations.
1594static bool TryToShrinkGlobalToBoolean(GlobalVariable *GV, Constant *OtherVal) {
Chris Lattner229907c2011-07-18 04:54:35 +00001595 Type *GVElType = GV->getType()->getElementType();
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001596
Lang Hames459b5dc2014-03-23 04:22:31 +00001597 // If GVElType is already i1, it is already shrunk. If the type of the GV is
1598 // an FP value, pointer or vector, don't do this optimization because a select
1599 // between them is very expensive and unlikely to lead to later
1600 // simplification. In these cases, we typically end up with "cond ? v1 : v2"
1601 // where v1 and v2 both require constant pool loads, a big loss.
Chris Lattner46b5c642009-11-06 04:27:31 +00001602 if (GVElType == Type::getInt1Ty(GV->getContext()) ||
Duncan Sands9dff9be2010-02-15 16:12:20 +00001603 GVElType->isFloatingPointTy() ||
Duncan Sands19d0b472010-02-16 11:11:14 +00001604 GVElType->isPointerTy() || GVElType->isVectorTy())
Chris Lattner20bbac32008-01-14 01:17:44 +00001605 return false;
Gabor Greifa75ed762010-07-12 14:13:15 +00001606
Chris Lattner20bbac32008-01-14 01:17:44 +00001607 // Walk the use list of the global seeing if all the uses are load or store.
1608 // If there is anything else, bail out.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001609 for (User *U : GV->users())
Gabor Greifa75ed762010-07-12 14:13:15 +00001610 if (!isa<LoadInst>(U) && !isa<StoreInst>(U))
Chris Lattner20bbac32008-01-14 01:17:44 +00001611 return false;
Gabor Greifa75ed762010-07-12 14:13:15 +00001612
Lang Hames459b5dc2014-03-23 04:22:31 +00001613 DEBUG(dbgs() << " *** SHRINKING TO BOOL: " << *GV);
1614
1615 // Create the new global, initializing it to false.
1616 GlobalVariable *NewGV = new GlobalVariable(Type::getInt1Ty(GV->getContext()),
1617 false,
1618 GlobalValue::InternalLinkage,
1619 ConstantInt::getFalse(GV->getContext()),
1620 GV->getName()+".b",
1621 GV->getThreadLocalMode(),
1622 GV->getType()->getAddressSpace());
1623 GV->getParent()->getGlobalList().insert(GV, NewGV);
1624
Chris Lattner40e4cec2004-12-12 05:53:50 +00001625 Constant *InitVal = GV->getInitializer();
Chris Lattner46b5c642009-11-06 04:27:31 +00001626 assert(InitVal->getType() != Type::getInt1Ty(GV->getContext()) &&
Lang Hames459b5dc2014-03-23 04:22:31 +00001627 "No reason to shrink to bool!");
Chris Lattner40e4cec2004-12-12 05:53:50 +00001628
Lang Hames459b5dc2014-03-23 04:22:31 +00001629 // If initialized to zero and storing one into the global, we can use a cast
1630 // instead of a select to synthesize the desired value.
1631 bool IsOneZero = false;
1632 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal))
1633 IsOneZero = InitVal->isNullValue() && CI->isOne();
Chris Lattner40e4cec2004-12-12 05:53:50 +00001634
Lang Hames459b5dc2014-03-23 04:22:31 +00001635 while (!GV->use_empty()) {
1636 Instruction *UI = cast<Instruction>(GV->user_back());
1637 if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
1638 // Change the store into a boolean store.
1639 bool StoringOther = SI->getOperand(0) == OtherVal;
1640 // Only do this if we weren't storing a loaded value.
1641 Value *StoreVal;
1642 if (StoringOther || SI->getOperand(0) == InitVal) {
1643 StoreVal = ConstantInt::get(Type::getInt1Ty(GV->getContext()),
1644 StoringOther);
Bill Wendling7297b862013-02-13 23:00:51 +00001645 } else {
Lang Hames459b5dc2014-03-23 04:22:31 +00001646 // Otherwise, we are storing a previously loaded copy. To do this,
1647 // change the copy from copying the original value to just copying the
1648 // bool.
1649 Instruction *StoredVal = cast<Instruction>(SI->getOperand(0));
1650
1651 // If we've already replaced the input, StoredVal will be a cast or
1652 // select instruction. If not, it will be a load of the original
1653 // global.
1654 if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
1655 assert(LI->getOperand(0) == GV && "Not a copy!");
1656 // Insert a new load, to preserve the saved value.
1657 StoreVal = new LoadInst(NewGV, LI->getName()+".b", false, 0,
1658 LI->getOrdering(), LI->getSynchScope(), LI);
1659 } else {
1660 assert((isa<CastInst>(StoredVal) || isa<SelectInst>(StoredVal)) &&
1661 "This is not a form that we understand!");
1662 StoreVal = StoredVal->getOperand(0);
1663 assert(isa<LoadInst>(StoreVal) && "Not a load of NewGV!");
1664 }
Chris Lattner745196a2004-12-12 19:34:41 +00001665 }
Lang Hames459b5dc2014-03-23 04:22:31 +00001666 new StoreInst(StoreVal, NewGV, false, 0,
1667 SI->getOrdering(), SI->getSynchScope(), SI);
1668 } else {
1669 // Change the load into a load of bool then a select.
1670 LoadInst *LI = cast<LoadInst>(UI);
1671 LoadInst *NLI = new LoadInst(NewGV, LI->getName()+".b", false, 0,
1672 LI->getOrdering(), LI->getSynchScope(), LI);
1673 Value *NSI;
1674 if (IsOneZero)
1675 NSI = new ZExtInst(NLI, LI->getType(), "", LI);
1676 else
1677 NSI = SelectInst::Create(NLI, OtherVal, InitVal, "", LI);
1678 NSI->takeName(LI);
1679 LI->replaceAllUsesWith(NSI);
Devang Patelfc507a12009-03-06 01:39:36 +00001680 }
Lang Hames459b5dc2014-03-23 04:22:31 +00001681 UI->eraseFromParent();
Chris Lattner40e4cec2004-12-12 05:53:50 +00001682 }
1683
Lang Hames459b5dc2014-03-23 04:22:31 +00001684 // Retain the name of the old global variable. People who are debugging their
1685 // programs may expect these variables to be named the same.
1686 NewGV->takeName(GV);
1687 GV->eraseFromParent();
Chris Lattner20bbac32008-01-14 01:17:44 +00001688 return true;
Chris Lattner40e4cec2004-12-12 05:53:50 +00001689}
1690
1691
Nick Lewycky1480f1d2012-02-12 00:52:26 +00001692/// ProcessGlobal - Analyze the specified global variable and optimize it if
1693/// possible. If we make a change, return true.
Rafael Espindolafc355bc2011-01-19 16:32:21 +00001694bool GlobalOpt::ProcessGlobal(GlobalVariable *GV,
1695 Module::global_iterator &GVI) {
Rafael Espindolafc355bc2011-01-19 16:32:21 +00001696 // Do more involved optimizations if the global is internal.
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001697 GV->removeDeadConstantUsers();
1698
1699 if (GV->use_empty()) {
David Greene44cb8ad2010-01-05 01:28:05 +00001700 DEBUG(dbgs() << "GLOBAL DEAD: " << *GV);
Chris Lattner8e71c6a2004-10-16 18:09:00 +00001701 GV->eraseFromParent();
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001702 ++NumDeleted;
1703 return true;
1704 }
1705
Rafael Espindola1821c6c2012-06-15 18:00:24 +00001706 if (!GV->hasLocalLinkage())
1707 return false;
1708
Rafael Espindolafc355bc2011-01-19 16:32:21 +00001709 GlobalStatus GS;
1710
Rafael Espindola3d7fc252013-10-21 17:14:55 +00001711 if (GlobalStatus::analyzeGlobal(GV, GS))
Rafael Espindolaecd5b9a2011-01-18 04:36:06 +00001712 return false;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001713
Rafael Espindola045a78f2013-10-17 18:18:52 +00001714 if (!GS.IsCompared && !GV->hasUnnamedAddr()) {
Rafael Espindolafc355bc2011-01-19 16:32:21 +00001715 GV->setUnnamedAddr(true);
1716 NumUnnamed++;
1717 }
1718
1719 if (GV->isConstant() || !GV->hasInitializer())
1720 return false;
1721
Rafael Espindolad21ac192013-09-05 19:15:21 +00001722 return ProcessInternalGlobal(GV, GVI, GS);
Rafael Espindolafc355bc2011-01-19 16:32:21 +00001723}
1724
1725/// ProcessInternalGlobal - Analyze the specified global variable and optimize
1726/// it if possible. If we make a change, return true.
1727bool GlobalOpt::ProcessInternalGlobal(GlobalVariable *GV,
1728 Module::global_iterator &GVI,
Rafael Espindolafc355bc2011-01-19 16:32:21 +00001729 const GlobalStatus &GS) {
Mehdi Amini46a43552015-03-04 18:43:29 +00001730 auto &DL = GV->getParent()->getDataLayout();
Alexey Samsonova1944e62013-10-07 19:03:24 +00001731 // If this is a first class global and has only one accessing function
1732 // and this function is main (which we know is not recursive), we replace
1733 // the global with a local alloca in this function.
1734 //
Alp Tokerf907b892013-12-05 05:44:44 +00001735 // NOTE: It doesn't make sense to promote non-single-value types since we
Alexey Samsonova1944e62013-10-07 19:03:24 +00001736 // are just replacing static memory to stack memory.
1737 //
1738 // If the global is in different address space, don't bring it to stack.
1739 if (!GS.HasMultipleAccessingFunctions &&
1740 GS.AccessingFunction && !GS.HasNonInstructionUser &&
1741 GV->getType()->getElementType()->isSingleValueType() &&
1742 GS.AccessingFunction->getName() == "main" &&
1743 GS.AccessingFunction->hasExternalLinkage() &&
1744 GV->getType()->getAddressSpace() == 0) {
1745 DEBUG(dbgs() << "LOCALIZING GLOBAL: " << *GV);
1746 Instruction &FirstI = const_cast<Instruction&>(*GS.AccessingFunction
1747 ->getEntryBlock().begin());
1748 Type *ElemTy = GV->getType()->getElementType();
1749 // FIXME: Pass Global's alignment when globals have alignment
Craig Topperf40110f2014-04-25 05:29:35 +00001750 AllocaInst *Alloca = new AllocaInst(ElemTy, nullptr,
1751 GV->getName(), &FirstI);
Alexey Samsonova1944e62013-10-07 19:03:24 +00001752 if (!isa<UndefValue>(GV->getInitializer()))
1753 new StoreInst(GV->getInitializer(), Alloca, &FirstI);
1754
1755 GV->replaceAllUsesWith(Alloca);
1756 GV->eraseFromParent();
1757 ++NumLocalized;
1758 return true;
1759 }
1760
Rafael Espindolaecd5b9a2011-01-18 04:36:06 +00001761 // If the global is never loaded (but may be stored to), it is dead.
1762 // Delete it now.
Rafael Espindola045a78f2013-10-17 18:18:52 +00001763 if (!GS.IsLoaded) {
Rafael Espindolaecd5b9a2011-01-18 04:36:06 +00001764 DEBUG(dbgs() << "GLOBAL NEVER LOADED: " << *GV);
1765
Nick Lewyckyfaa9c3b02012-07-24 07:21:08 +00001766 bool Changed;
1767 if (isLeakCheckerRoot(GV)) {
1768 // Delete any constant stores to the global.
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00001769 Changed = CleanupPointerRootUsers(GV, TLI);
Nick Lewyckyfaa9c3b02012-07-24 07:21:08 +00001770 } else {
1771 // Delete any stores we can find to the global. We may not be able to
1772 // make it completely dead though.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001773 Changed = CleanupConstantGlobalUsers(GV, GV->getInitializer(), DL, TLI);
Nick Lewyckyfaa9c3b02012-07-24 07:21:08 +00001774 }
Rafael Espindolaecd5b9a2011-01-18 04:36:06 +00001775
1776 // If the global is dead now, delete it.
1777 if (GV->use_empty()) {
1778 GV->eraseFromParent();
1779 ++NumDeleted;
1780 Changed = true;
1781 }
1782 return Changed;
1783
Rafael Espindola045a78f2013-10-17 18:18:52 +00001784 } else if (GS.StoredType <= GlobalStatus::InitializerStored) {
Michael Gottesmand1a46f22013-01-11 20:07:53 +00001785 DEBUG(dbgs() << "MARKING CONSTANT: " << *GV << "\n");
Rafael Espindolaecd5b9a2011-01-18 04:36:06 +00001786 GV->setConstant(true);
1787
1788 // Clean up any obviously simplifiable users now.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001789 CleanupConstantGlobalUsers(GV, GV->getInitializer(), DL, TLI);
Rafael Espindolaecd5b9a2011-01-18 04:36:06 +00001790
1791 // If the global is dead now, just nuke it.
1792 if (GV->use_empty()) {
1793 DEBUG(dbgs() << " *** Marking constant allowed us to simplify "
1794 << "all users and delete global!\n");
1795 GV->eraseFromParent();
1796 ++NumDeleted;
1797 }
1798
1799 ++NumMarked;
1800 return true;
1801 } else if (!GV->getInitializer()->getType()->isSingleValueType()) {
Mehdi Amini46a43552015-03-04 18:43:29 +00001802 const DataLayout &DL = GV->getParent()->getDataLayout();
1803 if (GlobalVariable *FirstNewGV = SRAGlobal(GV, DL)) {
1804 GVI = FirstNewGV; // Don't skip the newly produced globals!
1805 return true;
Rafael Espindola93512512014-02-25 17:30:31 +00001806 }
Rafael Espindola045a78f2013-10-17 18:18:52 +00001807 } else if (GS.StoredType == GlobalStatus::StoredOnce) {
Rafael Espindolaecd5b9a2011-01-18 04:36:06 +00001808 // If the initial value for the global was an undef value, and if only
1809 // one other value was stored into it, we can just change the
1810 // initializer to be the stored value, then delete all stores to the
1811 // global. This allows us to mark it constant.
1812 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
1813 if (isa<UndefValue>(GV->getInitializer())) {
1814 // Change the initial value here.
1815 GV->setInitializer(SOVConstant);
1816
1817 // Clean up any obviously simplifiable users now.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001818 CleanupConstantGlobalUsers(GV, GV->getInitializer(), DL, TLI);
Rafael Espindolaecd5b9a2011-01-18 04:36:06 +00001819
1820 if (GV->use_empty()) {
1821 DEBUG(dbgs() << " *** Substituting initializer allowed us to "
Nick Lewyckyfaa9c3b02012-07-24 07:21:08 +00001822 << "simplify all users and delete global!\n");
Rafael Espindolaecd5b9a2011-01-18 04:36:06 +00001823 GV->eraseFromParent();
1824 ++NumDeleted;
1825 } else {
1826 GVI = GV;
1827 }
1828 ++NumSubstitute;
1829 return true;
1830 }
1831
1832 // Try to optimize globals based on the knowledge that only one value
1833 // (besides its initializer) is ever stored to the global.
Nick Lewycky52da72b2012-02-05 19:56:38 +00001834 if (OptimizeOnceStoredGlobal(GV, GS.StoredOnceValue, GS.Ordering, GVI,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001835 DL, TLI))
Rafael Espindolaecd5b9a2011-01-18 04:36:06 +00001836 return true;
1837
Lang Hames459b5dc2014-03-23 04:22:31 +00001838 // Otherwise, if the global was not a boolean, we can shrink it to be a
1839 // boolean.
Eli Friedman33d37002013-09-09 22:00:13 +00001840 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue)) {
1841 if (GS.Ordering == NotAtomic) {
Lang Hames459b5dc2014-03-23 04:22:31 +00001842 if (TryToShrinkGlobalToBoolean(GV, SOVConstant)) {
Eli Friedman33d37002013-09-09 22:00:13 +00001843 ++NumShrunkToBool;
1844 return true;
1845 }
Rafael Espindolaecd5b9a2011-01-18 04:36:06 +00001846 }
Eli Friedman33d37002013-09-09 22:00:13 +00001847 }
Rafael Espindolaecd5b9a2011-01-18 04:36:06 +00001848 }
1849
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001850 return false;
1851}
1852
Chris Lattnera4c80222005-05-08 22:18:06 +00001853/// ChangeCalleesToFastCall - Walk all of the direct calls of the specified
1854/// function, changing them to FastCC.
1855static void ChangeCalleesToFastCall(Function *F) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00001856 for (User *U : F->users()) {
1857 if (isa<BlockAddress>(U))
Jay Foadca0c4992012-05-12 08:30:16 +00001858 continue;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001859 CallSite CS(cast<Instruction>(U));
1860 CS.setCallingConv(CallingConv::Fast);
Chris Lattnera4c80222005-05-08 22:18:06 +00001861 }
1862}
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001863
Bill Wendlinge94d8432012-12-07 23:16:57 +00001864static AttributeSet StripNest(LLVMContext &C, const AttributeSet &Attrs) {
Chris Lattner8a923e72008-03-12 17:45:29 +00001865 for (unsigned i = 0, e = Attrs.getNumSlots(); i != e; ++i) {
Bill Wendling57625a42013-01-25 23:09:36 +00001866 unsigned Index = Attrs.getSlotIndex(i);
1867 if (!Attrs.getSlotAttributes(i).hasAttribute(Index, Attribute::Nest))
Duncan Sands85fab3a2008-02-18 17:32:13 +00001868 continue;
1869
Duncan Sands85fab3a2008-02-18 17:32:13 +00001870 // There can be only one.
Bill Wendling57625a42013-01-25 23:09:36 +00001871 return Attrs.removeAttribute(C, Index, Attribute::Nest);
Duncan Sands573b3f82008-02-16 20:56:04 +00001872 }
1873
1874 return Attrs;
1875}
1876
1877static void RemoveNestAttribute(Function *F) {
Bill Wendling85a64c22012-10-14 06:39:53 +00001878 F->setAttributes(StripNest(F->getContext(), F->getAttributes()));
Chandler Carruthcdf47882014-03-09 03:16:01 +00001879 for (User *U : F->users()) {
1880 if (isa<BlockAddress>(U))
Jay Foadca0c4992012-05-12 08:30:16 +00001881 continue;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001882 CallSite CS(cast<Instruction>(U));
1883 CS.setAttributes(StripNest(F->getContext(), CS.getAttributes()));
Duncan Sands573b3f82008-02-16 20:56:04 +00001884 }
1885}
1886
Reid Kleckner22869372014-02-26 19:57:30 +00001887/// Return true if this is a calling convention that we'd like to change. The
1888/// idea here is that we don't want to mess with the convention if the user
1889/// explicitly requested something with performance implications like coldcc,
1890/// GHC, or anyregcc.
1891static bool isProfitableToMakeFastCC(Function *F) {
1892 CallingConv::ID CC = F->getCallingConv();
1893 // FIXME: Is it worth transforming x86_stdcallcc and x86_fastcallcc?
1894 return CC == CallingConv::C || CC == CallingConv::X86_ThisCall;
1895}
1896
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001897bool GlobalOpt::OptimizeFunctions(Module &M) {
1898 bool Changed = false;
1899 // Optimize functions.
1900 for (Module::iterator FI = M.begin(), E = M.end(); FI != E; ) {
1901 Function *F = FI++;
Duncan Sandsed722832009-03-06 10:21:56 +00001902 // Functions without names cannot be referenced outside this module.
David Majnemer5c921152014-07-01 15:26:50 +00001903 if (!F->hasName() && !F->isDeclaration() && !F->hasLocalLinkage())
Duncan Sandsed722832009-03-06 10:21:56 +00001904 F->setLinkage(GlobalValue::InternalLinkage);
David Majnemer1b3b70e2014-10-08 07:23:31 +00001905
1906 const Comdat *C = F->getComdat();
1907 bool inComdat = C && NotDiscardableComdats.count(C);
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001908 F->removeDeadConstantUsers();
David Majnemer1b3b70e2014-10-08 07:23:31 +00001909 if ((!inComdat || F->hasLocalLinkage()) && F->isDefTriviallyDead()) {
Chris Lattnerb5d9c8c2009-11-01 19:03:42 +00001910 F->eraseFromParent();
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001911 Changed = true;
1912 ++NumFnDeleted;
Rafael Espindola6de96a12009-01-15 20:18:42 +00001913 } else if (F->hasLocalLinkage()) {
Reid Klecknere6ff5c52014-02-28 22:50:08 +00001914 if (isProfitableToMakeFastCC(F) && !F->isVarArg() &&
1915 !F->hasAddressTaken()) {
Reid Kleckner22869372014-02-26 19:57:30 +00001916 // If this function has a calling convention worth changing, is not a
1917 // varargs function, and is only called directly, promote it to use the
1918 // Fast calling convention.
Duncan Sands573b3f82008-02-16 20:56:04 +00001919 F->setCallingConv(CallingConv::Fast);
1920 ChangeCalleesToFastCall(F);
1921 ++NumFastCallFns;
1922 Changed = true;
1923 }
1924
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001925 if (F->getAttributes().hasAttrSomewhere(Attribute::Nest) &&
Jay Foad557169d2009-06-10 08:41:11 +00001926 !F->hasAddressTaken()) {
Duncan Sands573b3f82008-02-16 20:56:04 +00001927 // The function is not used by a trampoline intrinsic, so it is safe
1928 // to remove the 'nest' attribute.
1929 RemoveNestAttribute(F);
1930 ++NumNestRemoved;
1931 Changed = true;
1932 }
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001933 }
1934 }
1935 return Changed;
1936}
1937
1938bool GlobalOpt::OptimizeGlobalVars(Module &M) {
1939 bool Changed = false;
David Majnemerdad0a642014-06-27 18:19:56 +00001940
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001941 for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
1942 GVI != E; ) {
1943 GlobalVariable *GV = GVI++;
Duncan Sandsed722832009-03-06 10:21:56 +00001944 // Global variables without names cannot be referenced outside this module.
David Majnemer5c921152014-07-01 15:26:50 +00001945 if (!GV->hasName() && !GV->isDeclaration() && !GV->hasLocalLinkage())
Duncan Sandsed722832009-03-06 10:21:56 +00001946 GV->setLinkage(GlobalValue::InternalLinkage);
Dan Gohman580b80d2009-11-23 16:22:21 +00001947 // Simplify the initializer.
1948 if (GV->hasInitializer())
1949 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GV->getInitializer())) {
Mehdi Amini46a43552015-03-04 18:43:29 +00001950 auto &DL = M.getDataLayout();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001951 Constant *New = ConstantFoldConstantExpression(CE, DL, TLI);
Dan Gohman580b80d2009-11-23 16:22:21 +00001952 if (New && New != CE)
1953 GV->setInitializer(New);
1954 }
Rafael Espindolafc355bc2011-01-19 16:32:21 +00001955
David Majnemerdad0a642014-06-27 18:19:56 +00001956 if (GV->isDiscardableIfUnused()) {
1957 if (const Comdat *C = GV->getComdat())
David Majnemer1b3b70e2014-10-08 07:23:31 +00001958 if (NotDiscardableComdats.count(C) && !GV->hasLocalLinkage())
David Majnemerdad0a642014-06-27 18:19:56 +00001959 continue;
1960 Changed |= ProcessGlobal(GV, GVI);
1961 }
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001962 }
1963 return Changed;
1964}
1965
Anthony Pesch3da0acd2015-07-22 21:10:45 +00001966namespace {
1967
1968/// Sorts GEP expressions in ascending order by their indexes.
1969struct GEPComparator {
1970 bool operator()(GEPOperator *A, GEPOperator *B) const {
1971 int NumOpA = A->getNumOperands();
1972 int NumOpB = B->getNumOperands();
1973
1974 // Globals are always pointers, the first index should be 0.
1975 assert(cast<ConstantInt>(A->getOperand(1))->isZero() &&
1976 "GEP A steps over object");
1977 assert(cast<ConstantInt>(B->getOperand(1))->isZero() &&
1978 "GEP B steps over object");
1979
1980 for (int i = 2; i < NumOpA && i < NumOpB; i++) {
1981 ConstantInt *IndexA = cast<ConstantInt>(A->getOperand(i));
1982 ConstantInt *IndexB = cast<ConstantInt>(B->getOperand(i));
1983
1984 if (IndexA->getZExtValue() < IndexB->getZExtValue()) {
1985 return true;
1986 }
1987 }
1988
1989 return NumOpA < NumOpB;
1990 }
1991};
1992
1993typedef std::map<GEPOperator *, Constant *, GEPComparator> StoreMap;
1994
1995/// MutatedGlobal - Holds mutations for a global. If a store overwrites the
1996/// the entire global, Initializer is updated with the new value. If a store
1997/// writes to a GEP of a global, the store is instead added to the Pending
1998/// map to be merged later during MergePendingStores.
1999struct MutatedGlobal {
2000 GlobalVariable *GV;
2001 Constant *Initializer;
2002 StoreMap Pending;
2003};
2004
2005/// MutatedGlobals - This class tracks and commits stores to globals as basic
2006/// blocks are evaluated.
2007class MutatedGlobals {
2008 DenseMap<GlobalVariable *, MutatedGlobal> Globals;
2009 typedef DenseMap<GlobalVariable *, MutatedGlobal>::const_iterator
2010 const_iterator;
2011
2012 GlobalVariable *GetGlobalForPointer(Constant *Ptr) {
2013 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr)) {
2014 return GV;
2015 }
2016
2017 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
2018 if (CE->getOpcode() == Instruction::GetElementPtr) {
2019 return cast<GlobalVariable>(CE->getOperand(0));
2020 }
2021 }
2022
2023 return nullptr;
2024 }
2025
2026 Constant *MergePendingStores(Constant *Init, StoreMap &Pending,
2027 uint64_t CurrentIdx, unsigned OpNum);
2028
2029public:
2030 const_iterator begin() const { return Globals.begin(); }
2031 const_iterator end() const { return Globals.end(); }
2032 size_t size() const { return Globals.size(); }
2033
2034 void AddStore(Constant *Ptr, Constant *Value);
2035 Constant *LookupStore(Constant *Ptr);
2036
2037 void Commit(MutatedGlobal &MG);
2038};
2039}
2040
2041/// AddStore - Add store for the global variable referenced by Ptr.
2042/// Currently, it's assumed that the incoming pointer is either the global
2043/// variable itself, or a GEP expression referencing the global.
2044void MutatedGlobals::AddStore(Constant *Ptr, Constant *Value) {
2045 GlobalVariable *GV = GetGlobalForPointer(Ptr);
2046 assert(GV && "Failed to resolve global for pointer");
2047
2048 auto I = Globals.find(GV);
2049 if (I == Globals.end()) {
2050 auto R = Globals.insert(std::make_pair(GV, MutatedGlobal{GV, nullptr, {}}));
2051 assert(R.second && "Global value already in the map?");
2052 I = R.first;
2053 }
2054
2055 MutatedGlobal &MG = I->second;
2056
2057 if (Ptr == GV) {
2058 MG.Initializer = Value;
2059 // Pending stores are no longer valid.
2060 MG.Pending.clear();
2061 } else if (GEPOperator *GEPOp = dyn_cast<GEPOperator>(Ptr)) {
2062 MG.Pending[GEPOp] = Value;
2063 } else {
2064 llvm_unreachable("Unexpected address type");
2065 }
2066}
2067
2068Constant *MutatedGlobals::LookupStore(Constant *Ptr) {
2069 GlobalVariable *GV = GetGlobalForPointer(Ptr);
2070 if (!GV) {
2071 return nullptr;
2072 }
2073
2074 auto I = Globals.find(GV);
2075 if (I == Globals.end()) {
2076 return nullptr;
2077 }
2078
2079 MutatedGlobal &MG = I->second;
2080
2081 if (Ptr == MG.GV) {
2082 if (MG.Initializer) {
2083 // If there are any pending stores, Initializer isn't valid, it would
2084 // need them merged in first. This situation currently doesn't occur
2085 // due to isSimpleEnoughPointerToCommit / isSimpleEnoughValueToCommit
2086 // not letting stores for aggregate types pass through. If this needs
2087 // to be supported, calling Commit() at this point should do the trick.
2088 assert(MG.Pending.empty() &&
2089 "Can't use pending initializer without merging pending stores.");
2090 return MG.Initializer;
2091 }
2092 } else if (GEPOperator *GEPOp = dyn_cast<GEPOperator>(Ptr)) {
2093 auto SI = MG.Pending.find(GEPOp);
2094 if (SI != MG.Pending.end()) {
2095 return SI->second;
2096 }
2097 }
2098
2099 return nullptr;
2100}
2101
2102/// MergePendingStores - Recursively merge stores to a global variable into its
2103/// initializer. Merging any number of stores into the initializer requires
2104/// cloning the entire initializer, so stores are batched up during evaluation
2105/// and processed all at once.
2106Constant *MutatedGlobals::MergePendingStores(Constant *Init, StoreMap &Pending,
2107 uint64_t CurrentIdx,
2108 unsigned OpNum) {
2109 if (Pending.empty()) {
2110 // Nothing left to merge.
2111 return Init;
2112 }
2113
2114 // If the GEP expression has been traversed completely, terminate.
2115 auto It = Pending.begin();
2116 GEPOperator *GEP = It->first;
2117
2118 if (OpNum >= GEP->getNumOperands()) {
2119 Constant *Val = It->second;
2120 assert(Val->getType() == Init->getType() && "Type mismatch!");
2121
2122 // Move on to the next expression.
2123 Pending.erase(It++);
2124
2125 return Val;
2126 }
2127
2128 // Clone the existing initializer so it can be merged into.
2129 Type *InitTy = Init->getType();
2130 ArrayType *ATy = dyn_cast<ArrayType>(InitTy);
2131 StructType *STy = dyn_cast<StructType>(InitTy);
2132 VectorType *VTy = dyn_cast<VectorType>(InitTy);
2133
2134 unsigned NumElts;
2135 if (ATy) {
2136 NumElts = ATy->getNumElements();
2137 } else if (STy) {
2138 NumElts = STy->getNumElements();
2139 } else if (VTy) {
2140 NumElts = VTy->getNumElements();
2141 } else {
2142 llvm_unreachable("Unexpected initializer type");
2143 }
2144
2145 SmallVector<Constant *, 32> Elts;
2146 for (unsigned i = 0; i < NumElts; ++i) {
2147 Elts.push_back(Init->getAggregateElement(i));
2148 }
2149
2150 // Iterate over the sorted stores, merging all stores for the current GEP
2151 // index.
2152 while (!Pending.empty()) {
2153 It = Pending.begin();
2154 GEP = It->first;
2155
2156 // If the store doesn't belong to the current index, we're done.
2157 ConstantInt *CI = cast<ConstantInt>(GEP->getOperand(OpNum - 1));
2158 uint64_t Idx = CI->getZExtValue();
2159 if (Idx != CurrentIdx) {
2160 break;
2161 }
2162
2163 // Recurse into the next index.
2164 CI = cast<ConstantInt>(GEP->getOperand(OpNum));
2165 Idx = CI->getZExtValue();
2166 assert(Idx < NumElts && "GEP index out of range!");
2167 Elts[Idx] = MergePendingStores(Elts[Idx], Pending, Idx, OpNum + 1);
2168 }
2169
2170 if (ATy) {
2171 return ConstantArray::get(ATy, Elts);
2172 } else if (STy) {
2173 return ConstantStruct::get(STy, Elts);
2174 } else if (VTy) {
2175 return ConstantVector::get(Elts);
2176 } else {
2177 llvm_unreachable("Unexpected initializer type");
2178 }
2179
2180 return nullptr;
2181};
2182
2183/// Commit - We have decided that stores to the global (which satisfy the
2184/// predicate isSimpleEnoughPointerToCommit) should be committed.
2185void MutatedGlobals::Commit(MutatedGlobal &MG) {
2186 Constant *Init = MG.Initializer ? MG.Initializer : MG.GV->getInitializer();
2187
2188 // Globals are always pointers, skip first GEP index assuming it's 0.
2189 Init = MergePendingStores(Init, MG.Pending, 0, 2);
2190
2191 // Reset pending state.
2192 MG.Initializer = nullptr;
2193 assert(MG.Pending.empty() &&
2194 "Expected pending stores to be empty after merging");
2195
2196 MG.GV->setInitializer(Init);
2197}
2198
2199
Jakub Staszak9525a772012-12-06 21:57:16 +00002200static inline bool
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002201isSimpleEnoughValueToCommit(Constant *C,
Mehdi Amini46a43552015-03-04 18:43:29 +00002202 SmallPtrSetImpl<Constant *> &SimpleConstants,
2203 const DataLayout &DL);
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002204
2205/// isSimpleEnoughValueToCommit - Return true if the specified constant can be
2206/// handled by the code generator. We don't want to generate something like:
2207/// void *X = &X/42;
2208/// because the code generator doesn't have a relocation that can handle that.
2209///
2210/// This function should be called if C was not found (but just got inserted)
2211/// in SimpleConstants to avoid having to rescan the same constants all the
2212/// time.
Mehdi Amini46a43552015-03-04 18:43:29 +00002213static bool
2214isSimpleEnoughValueToCommitHelper(Constant *C,
2215 SmallPtrSetImpl<Constant *> &SimpleConstants,
2216 const DataLayout &DL) {
David Majnemer6098b2f2014-06-26 03:02:19 +00002217 // Simple global addresses are supported, do not allow dllimport or
2218 // thread-local globals.
David Majnemer23fc9af2014-06-24 06:53:45 +00002219 if (auto *GV = dyn_cast<GlobalValue>(C))
David Majnemer6098b2f2014-06-26 03:02:19 +00002220 return !GV->hasDLLImportStorageClass() && !GV->isThreadLocal();
David Majnemer23fc9af2014-06-24 06:53:45 +00002221
2222 // Simple integer, undef, constant aggregate zero, etc are all supported.
2223 if (C->getNumOperands() == 0 || isa<BlockAddress>(C))
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002224 return true;
Jakub Staszak9525a772012-12-06 21:57:16 +00002225
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002226 // Aggregate values are safe if all their elements are.
2227 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C) ||
2228 isa<ConstantVector>(C)) {
Pete Cooper125ad172015-06-25 20:51:38 +00002229 for (Value *Op : C->operands())
2230 if (!isSimpleEnoughValueToCommit(cast<Constant>(Op), SimpleConstants, DL))
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002231 return false;
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002232 return true;
2233 }
Jakub Staszak9525a772012-12-06 21:57:16 +00002234
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002235 // We don't know exactly what relocations are allowed in constant expressions,
2236 // so we allow &global+constantoffset, which is safe and uniformly supported
2237 // across targets.
2238 ConstantExpr *CE = cast<ConstantExpr>(C);
2239 switch (CE->getOpcode()) {
2240 case Instruction::BitCast:
Eli Friedman55fa49f32012-01-05 23:03:32 +00002241 // Bitcast is fine if the casted value is fine.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002242 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, DL);
Eli Friedman55fa49f32012-01-05 23:03:32 +00002243
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002244 case Instruction::IntToPtr:
2245 case Instruction::PtrToInt:
Eli Friedman55fa49f32012-01-05 23:03:32 +00002246 // int <=> ptr is fine if the int type is the same size as the
2247 // pointer type.
Mehdi Amini46a43552015-03-04 18:43:29 +00002248 if (DL.getTypeSizeInBits(CE->getType()) !=
2249 DL.getTypeSizeInBits(CE->getOperand(0)->getType()))
Eli Friedman55fa49f32012-01-05 23:03:32 +00002250 return false;
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002251 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, DL);
Jakub Staszak9525a772012-12-06 21:57:16 +00002252
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002253 // GEP is fine if it is simple + constant offset.
2254 case Instruction::GetElementPtr:
2255 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
2256 if (!isa<ConstantInt>(CE->getOperand(i)))
2257 return false;
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002258 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, DL);
Jakub Staszak9525a772012-12-06 21:57:16 +00002259
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002260 case Instruction::Add:
2261 // We allow simple+cst.
2262 if (!isa<ConstantInt>(CE->getOperand(1)))
2263 return false;
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002264 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, DL);
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002265 }
2266 return false;
2267}
2268
Jakub Staszak9525a772012-12-06 21:57:16 +00002269static inline bool
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002270isSimpleEnoughValueToCommit(Constant *C,
Mehdi Amini46a43552015-03-04 18:43:29 +00002271 SmallPtrSetImpl<Constant *> &SimpleConstants,
2272 const DataLayout &DL) {
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002273 // If we already checked this constant, we win.
David Blaikie70573dc2014-11-19 07:49:26 +00002274 if (!SimpleConstants.insert(C).second)
2275 return true;
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002276 // Check the constant.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002277 return isSimpleEnoughValueToCommitHelper(C, SimpleConstants, DL);
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002278}
2279
2280
Chris Lattner99e23fa2005-09-26 04:44:35 +00002281/// isSimpleEnoughPointerToCommit - Return true if this constant is simple
Owen Anderson9eb7cb482011-01-14 22:19:20 +00002282/// enough for us to understand. In particular, if it is a cast to anything
2283/// other than from one pointer type to another pointer type, we punt.
2284/// We basically just support direct accesses to globals and GEP's of
Chris Lattner99e23fa2005-09-26 04:44:35 +00002285/// globals. This should be kept up to date with CommitValueTo.
Chris Lattner46b5c642009-11-06 04:27:31 +00002286static bool isSimpleEnoughPointerToCommit(Constant *C) {
Dan Gohman82e74752009-09-07 22:42:05 +00002287 // Conservatively, avoid aggregate types. This is because we don't
2288 // want to worry about them partially overlapping other stores.
2289 if (!cast<PointerType>(C->getType())->getElementType()->isSingleValueType())
2290 return false;
2291
Dan Gohmanf7f3fb12009-09-07 22:31:26 +00002292 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
David Majnemer23fc9af2014-06-24 06:53:45 +00002293 // Do not allow weak/*_odr/linkonce linkage or external globals.
Mikhail Glushenkov2072db22010-10-19 16:47:23 +00002294 return GV->hasUniqueInitializer();
Dan Gohmanf7f3fb12009-09-07 22:31:26 +00002295
Owen Anderson3e2f6cf2011-01-14 22:31:13 +00002296 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
Chris Lattner46af55e2005-09-26 06:52:44 +00002297 // Handle a constantexpr gep.
2298 if (CE->getOpcode() == Instruction::GetElementPtr &&
Dan Gohmanbeee35a2009-09-07 22:40:13 +00002299 isa<GlobalVariable>(CE->getOperand(0)) &&
2300 cast<GEPOperator>(CE)->isInBounds()) {
Chris Lattner46af55e2005-09-26 06:52:44 +00002301 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
Mikhail Glushenkov2072db22010-10-19 16:47:23 +00002302 // Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or
Dan Gohmanf7f3fb12009-09-07 22:31:26 +00002303 // external globals.
Mikhail Glushenkov2072db22010-10-19 16:47:23 +00002304 if (!GV->hasUniqueInitializer())
Dan Gohmanf7f3fb12009-09-07 22:31:26 +00002305 return false;
Dan Gohman161429f2009-09-07 22:44:55 +00002306
Dan Gohman161429f2009-09-07 22:44:55 +00002307 // The first index must be zero.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00002308 ConstantInt *CI = dyn_cast<ConstantInt>(*std::next(CE->op_begin()));
Dan Gohman161429f2009-09-07 22:44:55 +00002309 if (!CI || !CI->isZero()) return false;
Dan Gohman161429f2009-09-07 22:44:55 +00002310
2311 // The remaining indices must be compile-time known integers within the
Dan Gohman7190d482009-09-10 23:37:55 +00002312 // notional bounds of the corresponding static array types.
2313 if (!CE->isGEPWithNoNotionalOverIndexing())
2314 return false;
Dan Gohman161429f2009-09-07 22:44:55 +00002315
Dan Gohmane525d9d2009-10-05 16:36:26 +00002316 return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
Jakub Staszak9525a772012-12-06 21:57:16 +00002317
Owen Anderson9eb7cb482011-01-14 22:19:20 +00002318 // A constantexpr bitcast from a pointer to another pointer is a no-op,
2319 // and we know how to evaluate it by moving the bitcast from the pointer
2320 // operand to the value operand.
2321 } else if (CE->getOpcode() == Instruction::BitCast &&
Chris Lattner8b4952f2011-01-16 02:05:10 +00002322 isa<GlobalVariable>(CE->getOperand(0))) {
Owen Anderson9eb7cb482011-01-14 22:19:20 +00002323 // Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or
2324 // external globals.
Chris Lattner8b4952f2011-01-16 02:05:10 +00002325 return cast<GlobalVariable>(CE->getOperand(0))->hasUniqueInitializer();
Chris Lattner46af55e2005-09-26 06:52:44 +00002326 }
Owen Anderson3e2f6cf2011-01-14 22:31:13 +00002327 }
Jakub Staszak9525a772012-12-06 21:57:16 +00002328
Chris Lattner99e23fa2005-09-26 04:44:35 +00002329 return false;
2330}
2331
Nick Lewycky60829a582012-02-20 03:25:59 +00002332namespace {
2333
2334/// Evaluator - This class evaluates LLVM IR, producing the Constant
2335/// representing each SSA instruction. Changes to global variables are stored
2336/// in a mapping that can be iterated over after the evaluation is complete.
2337/// Once an evaluation call fails, the evaluation object should not be reused.
2338class Evaluator {
Nick Lewycky73be5e32012-02-19 23:26:27 +00002339public:
Mehdi Amini46a43552015-03-04 18:43:29 +00002340 Evaluator(const DataLayout &DL, const TargetLibraryInfo *TLI)
2341 : DL(DL), TLI(TLI) {
Benjamin Kramer64425fe2014-05-03 15:50:37 +00002342 ValueStack.emplace_back();
Nick Lewycky73be5e32012-02-19 23:26:27 +00002343 }
2344
Nick Lewycky60829a582012-02-20 03:25:59 +00002345 ~Evaluator() {
David Blaikiebc442202014-04-21 20:49:36 +00002346 for (auto &Tmp : AllocaTmps)
Nick Lewycky73be5e32012-02-19 23:26:27 +00002347 // If there are still users of the alloca, the program is doing something
2348 // silly, e.g. storing the address of the alloca somewhere and using it
2349 // later. Since this is undefined, we'll just make it be null.
2350 if (!Tmp->use_empty())
2351 Tmp->replaceAllUsesWith(Constant::getNullValue(Tmp->getType()));
Nick Lewycky73be5e32012-02-19 23:26:27 +00002352 }
2353
2354 /// EvaluateFunction - Evaluate a call to function F, returning true if
2355 /// successful, false if we can't evaluate it. ActualArgs contains the formal
2356 /// arguments for the function.
2357 bool EvaluateFunction(Function *F, Constant *&RetVal,
2358 const SmallVectorImpl<Constant*> &ActualArgs);
2359
2360 /// EvaluateBlock - Evaluate all instructions in block BB, returning true if
2361 /// successful, false if we can't evaluate it. NewBB returns the next BB that
2362 /// control flows into, or null upon return.
2363 bool EvaluateBlock(BasicBlock::iterator CurInst, BasicBlock *&NextBB);
2364
2365 Constant *getVal(Value *V) {
2366 if (Constant *CV = dyn_cast<Constant>(V)) return CV;
Benjamin Kramer64425fe2014-05-03 15:50:37 +00002367 Constant *R = ValueStack.back().lookup(V);
Nick Lewycky73be5e32012-02-19 23:26:27 +00002368 assert(R && "Reference to an uncomputed value!");
2369 return R;
2370 }
2371
2372 void setVal(Value *V, Constant *C) {
Benjamin Kramer64425fe2014-05-03 15:50:37 +00002373 ValueStack.back()[V] = C;
Nick Lewycky73be5e32012-02-19 23:26:27 +00002374 }
2375
Anthony Pesch3da0acd2015-07-22 21:10:45 +00002376 MutatedGlobals &getMutated() {
2377 return Mutated;
Nick Lewycky73be5e32012-02-19 23:26:27 +00002378 }
2379
Craig Topper71b7b682014-08-21 05:55:13 +00002380 const SmallPtrSetImpl<GlobalVariable*> &getInvariants() const {
Nick Lewycky73be5e32012-02-19 23:26:27 +00002381 return Invariants;
2382 }
2383
2384private:
2385 Constant *ComputeLoadResult(Constant *P);
2386
2387 /// ValueStack - As we compute SSA register values, we store their contents
Benjamin Kramer64425fe2014-05-03 15:50:37 +00002388 /// here. The back of the deque contains the current function and the stack
Nick Lewycky73be5e32012-02-19 23:26:27 +00002389 /// contains the values in the calling frames.
Benjamin Kramer64425fe2014-05-03 15:50:37 +00002390 std::deque<DenseMap<Value*, Constant*>> ValueStack;
Nick Lewycky73be5e32012-02-19 23:26:27 +00002391
2392 /// CallStack - This is used to detect recursion. In pathological situations
2393 /// we could hit exponential behavior, but at least there is nothing
2394 /// unbounded.
2395 SmallVector<Function*, 4> CallStack;
2396
Anthony Pesch3da0acd2015-07-22 21:10:45 +00002397 /// Mutated - For each store we execute, we update this map. Loads check
2398 /// this to get the most up-to-date value. If evaluation is successful,
Nick Lewycky73be5e32012-02-19 23:26:27 +00002399 /// this state is committed to the process.
Anthony Pesch3da0acd2015-07-22 21:10:45 +00002400 MutatedGlobals Mutated;
Nick Lewycky73be5e32012-02-19 23:26:27 +00002401
2402 /// AllocaTmps - To 'execute' an alloca, we create a temporary global variable
2403 /// to represent its body. This vector is needed so we can delete the
2404 /// temporary globals when we are done.
David Blaikiebc442202014-04-21 20:49:36 +00002405 SmallVector<std::unique_ptr<GlobalVariable>, 32> AllocaTmps;
Nick Lewycky73be5e32012-02-19 23:26:27 +00002406
2407 /// Invariants - These global variables have been marked invariant by the
2408 /// static constructor.
2409 SmallPtrSet<GlobalVariable*, 8> Invariants;
2410
2411 /// SimpleConstants - These are constants we have checked and know to be
2412 /// simple enough to live in a static initializer of a global.
2413 SmallPtrSet<Constant*, 8> SimpleConstants;
2414
Mehdi Amini46a43552015-03-04 18:43:29 +00002415 const DataLayout &DL;
Nick Lewycky73be5e32012-02-19 23:26:27 +00002416 const TargetLibraryInfo *TLI;
2417};
2418
Nick Lewycky60829a582012-02-20 03:25:59 +00002419} // anonymous namespace
2420
Chris Lattnerb0096632005-09-26 05:16:34 +00002421/// ComputeLoadResult - Return the value that would be computed by a load from
2422/// P after the stores reflected by 'memory' have been performed. If we can't
2423/// decide, return null.
Nick Lewycky60829a582012-02-20 03:25:59 +00002424Constant *Evaluator::ComputeLoadResult(Constant *P) {
Chris Lattner4b05c322005-09-26 05:15:37 +00002425 // If this memory location has been recently stored, use the stored value: it
2426 // is the most up-to-date.
Anthony Pesch3da0acd2015-07-22 21:10:45 +00002427 Constant *Val = Mutated.LookupStore(P);
2428 if (Val) return Val;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002429
Chris Lattner4b05c322005-09-26 05:15:37 +00002430 // Access it.
2431 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(P)) {
Dan Gohman5d5bc6d2009-08-19 18:20:44 +00002432 if (GV->hasDefinitiveInitializer())
Chris Lattner4b05c322005-09-26 05:15:37 +00002433 return GV->getInitializer();
Craig Topperf40110f2014-04-25 05:29:35 +00002434 return nullptr;
Chris Lattner4b05c322005-09-26 05:15:37 +00002435 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002436
Chris Lattner46af55e2005-09-26 06:52:44 +00002437 // Handle a constantexpr getelementptr.
2438 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(P))
2439 if (CE->getOpcode() == Instruction::GetElementPtr &&
2440 isa<GlobalVariable>(CE->getOperand(0))) {
2441 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
Dan Gohman5d5bc6d2009-08-19 18:20:44 +00002442 if (GV->hasDefinitiveInitializer())
Dan Gohmane525d9d2009-10-05 16:36:26 +00002443 return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
Chris Lattner46af55e2005-09-26 06:52:44 +00002444 }
2445
Craig Topperf40110f2014-04-25 05:29:35 +00002446 return nullptr; // don't know how to evaluate.
Chris Lattner4b05c322005-09-26 05:15:37 +00002447}
2448
Nick Lewycky239fdf02012-02-06 08:24:44 +00002449/// EvaluateBlock - Evaluate all instructions in block BB, returning true if
2450/// successful, false if we can't evaluate it. NewBB returns the next BB that
2451/// control flows into, or null upon return.
Nick Lewycky60829a582012-02-20 03:25:59 +00002452bool Evaluator::EvaluateBlock(BasicBlock::iterator CurInst,
2453 BasicBlock *&NextBB) {
Chris Lattner99e23fa2005-09-26 04:44:35 +00002454 // This is the main evaluation loop.
2455 while (1) {
Craig Topperf40110f2014-04-25 05:29:35 +00002456 Constant *InstResult = nullptr;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002457
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002458 DEBUG(dbgs() << "Evaluating Instruction: " << *CurInst << "\n");
2459
Chris Lattner99e23fa2005-09-26 04:44:35 +00002460 if (StoreInst *SI = dyn_cast<StoreInst>(CurInst)) {
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002461 if (!SI->isSimple()) {
Michael Gottesman2a654272013-01-11 23:08:52 +00002462 DEBUG(dbgs() << "Store is not simple! Can not evaluate.\n");
2463 return false; // no volatile/atomic accesses.
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002464 }
Nick Lewycky73be5e32012-02-19 23:26:27 +00002465 Constant *Ptr = getVal(SI->getOperand(1));
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002466 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
Michael Gottesman2a654272013-01-11 23:08:52 +00002467 DEBUG(dbgs() << "Folding constant ptr expression: " << *Ptr);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002468 Ptr = ConstantFoldConstantExpression(CE, DL, TLI);
Michael Gottesman2a654272013-01-11 23:08:52 +00002469 DEBUG(dbgs() << "; To: " << *Ptr << "\n");
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002470 }
2471 if (!isSimpleEnoughPointerToCommit(Ptr)) {
Chris Lattner99e23fa2005-09-26 04:44:35 +00002472 // If this is too complex for us to commit, reject it.
Michael Gottesman2a654272013-01-11 23:08:52 +00002473 DEBUG(dbgs() << "Pointer is too complex for us to evaluate store.");
Chris Lattner65a3a092005-09-27 04:45:34 +00002474 return false;
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002475 }
Jakub Staszak9525a772012-12-06 21:57:16 +00002476
Nick Lewycky73be5e32012-02-19 23:26:27 +00002477 Constant *Val = getVal(SI->getOperand(0));
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002478
2479 // If this might be too difficult for the backend to handle (e.g. the addr
2480 // of one global variable divided by another) then we can't commit it.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002481 if (!isSimpleEnoughValueToCommit(Val, SimpleConstants, DL)) {
Michael Gottesman2a654272013-01-11 23:08:52 +00002482 DEBUG(dbgs() << "Store value is too complex to evaluate store. " << *Val
2483 << "\n");
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002484 return false;
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002485 }
Jakub Staszak9525a772012-12-06 21:57:16 +00002486
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002487 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
Owen Anderson9eb7cb482011-01-14 22:19:20 +00002488 if (CE->getOpcode() == Instruction::BitCast) {
Michael Gottesman2a654272013-01-11 23:08:52 +00002489 DEBUG(dbgs() << "Attempting to resolve bitcast on constant ptr.\n");
Owen Anderson9eb7cb482011-01-14 22:19:20 +00002490 // If we're evaluating a store through a bitcast, then we need
2491 // to pull the bitcast off the pointer type and push it onto the
2492 // stored value.
Chris Lattner8b4952f2011-01-16 02:05:10 +00002493 Ptr = CE->getOperand(0);
Jakub Staszak9525a772012-12-06 21:57:16 +00002494
Nick Lewycky239fdf02012-02-06 08:24:44 +00002495 Type *NewTy = cast<PointerType>(Ptr->getType())->getElementType();
Jakub Staszak9525a772012-12-06 21:57:16 +00002496
Owen Anderson4e54efd2011-01-16 04:33:33 +00002497 // In order to push the bitcast onto the stored value, a bitcast
2498 // from NewTy to Val's type must be legal. If it's not, we can try
2499 // introspecting NewTy to find a legal conversion.
2500 while (!Val->getType()->canLosslesslyBitCastTo(NewTy)) {
2501 // If NewTy is a struct, we can convert the pointer to the struct
2502 // into a pointer to its first member.
2503 // FIXME: This could be extended to support arrays as well.
Chris Lattner229907c2011-07-18 04:54:35 +00002504 if (StructType *STy = dyn_cast<StructType>(NewTy)) {
Owen Anderson4e54efd2011-01-16 04:33:33 +00002505 NewTy = STy->getTypeAtIndex(0U);
2506
Nick Lewycky239fdf02012-02-06 08:24:44 +00002507 IntegerType *IdxTy = IntegerType::get(NewTy->getContext(), 32);
Owen Anderson4e54efd2011-01-16 04:33:33 +00002508 Constant *IdxZero = ConstantInt::get(IdxTy, 0, false);
2509 Constant * const IdxList[] = {IdxZero, IdxZero};
2510
David Blaikie4a2e73b2015-04-02 18:55:32 +00002511 Ptr = ConstantExpr::getGetElementPtr(nullptr, Ptr, IdxList);
Nick Lewycky9d0da182012-02-21 22:08:06 +00002512 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002513 Ptr = ConstantFoldConstantExpression(CE, DL, TLI);
Nick Lewycky9d0da182012-02-21 22:08:06 +00002514
Owen Anderson4e54efd2011-01-16 04:33:33 +00002515 // If we can't improve the situation by introspecting NewTy,
2516 // we have to give up.
2517 } else {
Michael Gottesman2a654272013-01-11 23:08:52 +00002518 DEBUG(dbgs() << "Failed to bitcast constant ptr, can not "
2519 "evaluate.\n");
Nick Lewycky239fdf02012-02-06 08:24:44 +00002520 return false;
Owen Anderson4e54efd2011-01-16 04:33:33 +00002521 }
Owen Anderson9eb7cb482011-01-14 22:19:20 +00002522 }
Jakub Staszak9525a772012-12-06 21:57:16 +00002523
Owen Anderson4e54efd2011-01-16 04:33:33 +00002524 // If we found compatible types, go ahead and push the bitcast
2525 // onto the stored value.
Owen Anderson9eb7cb482011-01-14 22:19:20 +00002526 Val = ConstantExpr::getBitCast(Val, NewTy);
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002527
Michael Gottesman2a654272013-01-11 23:08:52 +00002528 DEBUG(dbgs() << "Evaluated bitcast: " << *Val << "\n");
Owen Anderson9eb7cb482011-01-14 22:19:20 +00002529 }
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002530 }
Jakub Staszak9525a772012-12-06 21:57:16 +00002531
Anthony Pesch3da0acd2015-07-22 21:10:45 +00002532 Mutated.AddStore(Ptr, Val);
Chris Lattner99e23fa2005-09-26 04:44:35 +00002533 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CurInst)) {
Owen Anderson487375e2009-07-29 18:55:55 +00002534 InstResult = ConstantExpr::get(BO->getOpcode(),
Nick Lewycky73be5e32012-02-19 23:26:27 +00002535 getVal(BO->getOperand(0)),
2536 getVal(BO->getOperand(1)));
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002537 DEBUG(dbgs() << "Found a BinaryOperator! Simplifying: " << *InstResult
Michael Gottesman2a654272013-01-11 23:08:52 +00002538 << "\n");
Reid Spencer266e42b2006-12-23 06:05:41 +00002539 } else if (CmpInst *CI = dyn_cast<CmpInst>(CurInst)) {
Owen Anderson487375e2009-07-29 18:55:55 +00002540 InstResult = ConstantExpr::getCompare(CI->getPredicate(),
Nick Lewycky73be5e32012-02-19 23:26:27 +00002541 getVal(CI->getOperand(0)),
2542 getVal(CI->getOperand(1)));
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002543 DEBUG(dbgs() << "Found a CmpInst! Simplifying: " << *InstResult
Michael Gottesman2a654272013-01-11 23:08:52 +00002544 << "\n");
Chris Lattner99e23fa2005-09-26 04:44:35 +00002545 } else if (CastInst *CI = dyn_cast<CastInst>(CurInst)) {
Owen Anderson487375e2009-07-29 18:55:55 +00002546 InstResult = ConstantExpr::getCast(CI->getOpcode(),
Nick Lewycky73be5e32012-02-19 23:26:27 +00002547 getVal(CI->getOperand(0)),
Chris Lattner99e23fa2005-09-26 04:44:35 +00002548 CI->getType());
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002549 DEBUG(dbgs() << "Found a Cast! Simplifying: " << *InstResult
Michael Gottesman2a654272013-01-11 23:08:52 +00002550 << "\n");
Chris Lattner99e23fa2005-09-26 04:44:35 +00002551 } else if (SelectInst *SI = dyn_cast<SelectInst>(CurInst)) {
Nick Lewycky73be5e32012-02-19 23:26:27 +00002552 InstResult = ConstantExpr::getSelect(getVal(SI->getOperand(0)),
2553 getVal(SI->getOperand(1)),
2554 getVal(SI->getOperand(2)));
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002555 DEBUG(dbgs() << "Found a Select! Simplifying: " << *InstResult
Michael Gottesman2a654272013-01-11 23:08:52 +00002556 << "\n");
David Majnemerfe8c7542014-08-08 05:50:43 +00002557 } else if (auto *EVI = dyn_cast<ExtractValueInst>(CurInst)) {
2558 InstResult = ConstantExpr::getExtractValue(
2559 getVal(EVI->getAggregateOperand()), EVI->getIndices());
2560 DEBUG(dbgs() << "Found an ExtractValueInst! Simplifying: " << *InstResult
2561 << "\n");
2562 } else if (auto *IVI = dyn_cast<InsertValueInst>(CurInst)) {
2563 InstResult = ConstantExpr::getInsertValue(
2564 getVal(IVI->getAggregateOperand()),
2565 getVal(IVI->getInsertedValueOperand()), IVI->getIndices());
2566 DEBUG(dbgs() << "Found an InsertValueInst! Simplifying: " << *InstResult
2567 << "\n");
Chris Lattner4b05c322005-09-26 05:15:37 +00002568 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurInst)) {
Nick Lewycky73be5e32012-02-19 23:26:27 +00002569 Constant *P = getVal(GEP->getOperand(0));
Chris Lattnerf96f4a82007-01-31 04:40:53 +00002570 SmallVector<Constant*, 8> GEPOps;
Gabor Greif3a9fba52008-05-29 01:59:18 +00002571 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end();
2572 i != e; ++i)
Nick Lewycky73be5e32012-02-19 23:26:27 +00002573 GEPOps.push_back(getVal(*i));
Jay Foad2f5fc8c2011-07-21 15:15:37 +00002574 InstResult =
David Blaikie4a2e73b2015-04-02 18:55:32 +00002575 ConstantExpr::getGetElementPtr(GEP->getSourceElementType(), P, GEPOps,
2576 cast<GEPOperator>(GEP)->isInBounds());
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002577 DEBUG(dbgs() << "Found a GEP! Simplifying: " << *InstResult
Michael Gottesman2a654272013-01-11 23:08:52 +00002578 << "\n");
Chris Lattner4b05c322005-09-26 05:15:37 +00002579 } else if (LoadInst *LI = dyn_cast<LoadInst>(CurInst)) {
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002580
2581 if (!LI->isSimple()) {
Michael Gottesman2a654272013-01-11 23:08:52 +00002582 DEBUG(dbgs() << "Found a Load! Not a simple load, can not evaluate.\n");
2583 return false; // no volatile/atomic accesses.
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002584 }
2585
Nick Lewycky9d0da182012-02-21 22:08:06 +00002586 Constant *Ptr = getVal(LI->getOperand(0));
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002587 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002588 Ptr = ConstantFoldConstantExpression(CE, DL, TLI);
Michael Gottesman2a654272013-01-11 23:08:52 +00002589 DEBUG(dbgs() << "Found a constant pointer expression, constant "
2590 "folding: " << *Ptr << "\n");
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002591 }
Nick Lewycky9d0da182012-02-21 22:08:06 +00002592 InstResult = ComputeLoadResult(Ptr);
Craig Topperf40110f2014-04-25 05:29:35 +00002593 if (!InstResult) {
Michael Gottesman2a654272013-01-11 23:08:52 +00002594 DEBUG(dbgs() << "Failed to compute load result. Can not evaluate load."
2595 "\n");
2596 return false; // Could not evaluate load.
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002597 }
2598
2599 DEBUG(dbgs() << "Evaluated load: " << *InstResult << "\n");
Chris Lattner6bf2cd52005-09-26 17:07:09 +00002600 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(CurInst)) {
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002601 if (AI->isArrayAllocation()) {
Michael Gottesman2a654272013-01-11 23:08:52 +00002602 DEBUG(dbgs() << "Found an array alloca. Can not evaluate.\n");
2603 return false; // Cannot handle array allocs.
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002604 }
Chris Lattner229907c2011-07-18 04:54:35 +00002605 Type *Ty = AI->getType()->getElementType();
David Blaikiebc442202014-04-21 20:49:36 +00002606 AllocaTmps.push_back(
2607 make_unique<GlobalVariable>(Ty, false, GlobalValue::InternalLinkage,
2608 UndefValue::get(Ty), AI->getName()));
2609 InstResult = AllocaTmps.back().get();
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002610 DEBUG(dbgs() << "Found an alloca. Result: " << *InstResult << "\n");
Nick Lewyckyc1572e42012-02-12 05:09:35 +00002611 } else if (isa<CallInst>(CurInst) || isa<InvokeInst>(CurInst)) {
2612 CallSite CS(CurInst);
Devang Patel04852aa2009-03-09 23:04:12 +00002613
2614 // Debug info can safely be ignored here.
Nick Lewyckyc1572e42012-02-12 05:09:35 +00002615 if (isa<DbgInfoIntrinsic>(CS.getInstruction())) {
Michael Gottesman2a654272013-01-11 23:08:52 +00002616 DEBUG(dbgs() << "Ignoring debug info.\n");
Devang Patel04852aa2009-03-09 23:04:12 +00002617 ++CurInst;
2618 continue;
2619 }
2620
Chris Lattnerfd2e13b2006-07-07 21:37:01 +00002621 // Cannot handle inline asm.
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002622 if (isa<InlineAsm>(CS.getCalledValue())) {
Michael Gottesman2a654272013-01-11 23:08:52 +00002623 DEBUG(dbgs() << "Found inline asm, can not evaluate.\n");
2624 return false;
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002625 }
Chris Lattnerfd2e13b2006-07-07 21:37:01 +00002626
Nick Lewycky68f9f9d2012-02-17 06:59:21 +00002627 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CS.getInstruction())) {
2628 if (MemSetInst *MSI = dyn_cast<MemSetInst>(II)) {
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002629 if (MSI->isVolatile()) {
Michael Gottesman2a654272013-01-11 23:08:52 +00002630 DEBUG(dbgs() << "Can not optimize a volatile memset " <<
2631 "intrinsic.\n");
2632 return false;
2633 }
Nick Lewycky73be5e32012-02-19 23:26:27 +00002634 Constant *Ptr = getVal(MSI->getDest());
2635 Constant *Val = getVal(MSI->getValue());
2636 Constant *DestVal = ComputeLoadResult(getVal(Ptr));
Nick Lewycky68f9f9d2012-02-17 06:59:21 +00002637 if (Val->isNullValue() && DestVal && DestVal->isNullValue()) {
2638 // This memset is a no-op.
Michael Gottesman2a654272013-01-11 23:08:52 +00002639 DEBUG(dbgs() << "Ignoring no-op memset.\n");
Nick Lewycky68f9f9d2012-02-17 06:59:21 +00002640 ++CurInst;
2641 continue;
2642 }
2643 }
2644
2645 if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
2646 II->getIntrinsicID() == Intrinsic::lifetime_end) {
Michael Gottesman2a654272013-01-11 23:08:52 +00002647 DEBUG(dbgs() << "Ignoring lifetime intrinsic.\n");
Nick Lewycky68f9f9d2012-02-17 06:59:21 +00002648 ++CurInst;
2649 continue;
2650 }
2651
2652 if (II->getIntrinsicID() == Intrinsic::invariant_start) {
2653 // We don't insert an entry into Values, as it doesn't have a
2654 // meaningful return value.
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002655 if (!II->use_empty()) {
Alp Tokerf907b892013-12-05 05:44:44 +00002656 DEBUG(dbgs() << "Found unused invariant_start. Can't evaluate.\n");
Nick Lewycky68f9f9d2012-02-17 06:59:21 +00002657 return false;
Michael Gottesman2a654272013-01-11 23:08:52 +00002658 }
Nick Lewycky68f9f9d2012-02-17 06:59:21 +00002659 ConstantInt *Size = cast<ConstantInt>(II->getArgOperand(0));
Nick Lewycky519561f2012-02-20 23:32:26 +00002660 Value *PtrArg = getVal(II->getArgOperand(1));
2661 Value *Ptr = PtrArg->stripPointerCasts();
2662 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr)) {
2663 Type *ElemTy = cast<PointerType>(GV->getType())->getElementType();
Mehdi Amini46a43552015-03-04 18:43:29 +00002664 if (!Size->isAllOnesValue() &&
Nick Lewycky519561f2012-02-20 23:32:26 +00002665 Size->getValue().getLimitedValue() >=
Mehdi Amini46a43552015-03-04 18:43:29 +00002666 DL.getTypeStoreSize(ElemTy)) {
Nick Lewycky68f9f9d2012-02-17 06:59:21 +00002667 Invariants.insert(GV);
Michael Gottesman2a654272013-01-11 23:08:52 +00002668 DEBUG(dbgs() << "Found a global var that is an invariant: " << *GV
2669 << "\n");
2670 } else {
2671 DEBUG(dbgs() << "Found a global var, but can not treat it as an "
2672 "invariant.\n");
2673 }
Nick Lewycky68f9f9d2012-02-17 06:59:21 +00002674 }
2675 // Continue even if we do nothing.
Nick Lewyckya3bb03e2011-05-29 18:41:56 +00002676 ++CurInst;
2677 continue;
2678 }
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002679
Michael Gottesman2a654272013-01-11 23:08:52 +00002680 DEBUG(dbgs() << "Unknown intrinsic. Can not evaluate.\n");
Nick Lewyckya3bb03e2011-05-29 18:41:56 +00002681 return false;
2682 }
2683
Chris Lattner65a3a092005-09-27 04:45:34 +00002684 // Resolve function pointers.
Nick Lewycky73be5e32012-02-19 23:26:27 +00002685 Function *Callee = dyn_cast<Function>(getVal(CS.getCalledValue()));
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002686 if (!Callee || Callee->mayBeOverridden()) {
Michael Gottesman2a654272013-01-11 23:08:52 +00002687 DEBUG(dbgs() << "Can not resolve function pointer.\n");
Nick Lewyckyc1572e42012-02-12 05:09:35 +00002688 return false; // Cannot resolve.
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002689 }
Chris Lattner3d27e7f2005-09-27 05:02:43 +00002690
Duncan Sandsc4ce58d82009-08-17 14:33:27 +00002691 SmallVector<Constant*, 8> Formals;
Nick Lewyckyc1572e42012-02-12 05:09:35 +00002692 for (User::op_iterator i = CS.arg_begin(), e = CS.arg_end(); i != e; ++i)
Nick Lewycky73be5e32012-02-19 23:26:27 +00002693 Formals.push_back(getVal(*i));
Duncan Sandsc4ce58d82009-08-17 14:33:27 +00002694
Reid Spencer5301e7c2007-01-30 20:08:39 +00002695 if (Callee->isDeclaration()) {
Chris Lattner3d27e7f2005-09-27 05:02:43 +00002696 // If this is a function we can constant fold, do it.
Chad Rosiere6de63d2011-12-01 21:29:16 +00002697 if (Constant *C = ConstantFoldCall(Callee, Formals, TLI)) {
Chris Lattner3d27e7f2005-09-27 05:02:43 +00002698 InstResult = C;
Michael Gottesman2a654272013-01-11 23:08:52 +00002699 DEBUG(dbgs() << "Constant folded function call. Result: " <<
2700 *InstResult << "\n");
Chris Lattner3d27e7f2005-09-27 05:02:43 +00002701 } else {
Michael Gottesman2a654272013-01-11 23:08:52 +00002702 DEBUG(dbgs() << "Can not constant fold function call.\n");
Chris Lattner3d27e7f2005-09-27 05:02:43 +00002703 return false;
2704 }
2705 } else {
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002706 if (Callee->getFunctionType()->isVarArg()) {
Michael Gottesman2a654272013-01-11 23:08:52 +00002707 DEBUG(dbgs() << "Can not constant fold vararg function call.\n");
Chris Lattner3d27e7f2005-09-27 05:02:43 +00002708 return false;
Michael Gottesman2a654272013-01-11 23:08:52 +00002709 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002710
Craig Topperf40110f2014-04-25 05:29:35 +00002711 Constant *RetVal = nullptr;
Chris Lattner3d27e7f2005-09-27 05:02:43 +00002712 // Execute the call, if successful, use the return value.
Benjamin Kramer64425fe2014-05-03 15:50:37 +00002713 ValueStack.emplace_back();
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002714 if (!EvaluateFunction(Callee, RetVal, Formals)) {
Michael Gottesman2a654272013-01-11 23:08:52 +00002715 DEBUG(dbgs() << "Failed to evaluate function.\n");
Chris Lattner3d27e7f2005-09-27 05:02:43 +00002716 return false;
Michael Gottesman2a654272013-01-11 23:08:52 +00002717 }
David Blaikiebc442202014-04-21 20:49:36 +00002718 ValueStack.pop_back();
Chris Lattner3d27e7f2005-09-27 05:02:43 +00002719 InstResult = RetVal;
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002720
Craig Topperf40110f2014-04-25 05:29:35 +00002721 if (InstResult) {
Michael Gottesman2a654272013-01-11 23:08:52 +00002722 DEBUG(dbgs() << "Successfully evaluated function. Result: " <<
2723 InstResult << "\n\n");
2724 } else {
2725 DEBUG(dbgs() << "Successfully evaluated function. Result: 0\n\n");
2726 }
Chris Lattner3d27e7f2005-09-27 05:02:43 +00002727 }
Reid Spencerde46e482006-11-02 20:25:50 +00002728 } else if (isa<TerminatorInst>(CurInst)) {
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002729 DEBUG(dbgs() << "Found a terminator instruction.\n");
2730
Chris Lattner3e9ea5f2005-09-26 04:57:38 +00002731 if (BranchInst *BI = dyn_cast<BranchInst>(CurInst)) {
2732 if (BI->isUnconditional()) {
Nick Lewycky239fdf02012-02-06 08:24:44 +00002733 NextBB = BI->getSuccessor(0);
Chris Lattner3e9ea5f2005-09-26 04:57:38 +00002734 } else {
Zhou Sheng75b871f2007-01-11 12:24:14 +00002735 ConstantInt *Cond =
Nick Lewycky73be5e32012-02-19 23:26:27 +00002736 dyn_cast<ConstantInt>(getVal(BI->getCondition()));
Chris Lattner15649082007-01-12 18:30:11 +00002737 if (!Cond) return false; // Cannot determine.
Zhou Sheng75b871f2007-01-11 12:24:14 +00002738
Nick Lewycky239fdf02012-02-06 08:24:44 +00002739 NextBB = BI->getSuccessor(!Cond->getZExtValue());
Chris Lattner3e9ea5f2005-09-26 04:57:38 +00002740 }
2741 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(CurInst)) {
2742 ConstantInt *Val =
Nick Lewycky73be5e32012-02-19 23:26:27 +00002743 dyn_cast<ConstantInt>(getVal(SI->getCondition()));
Chris Lattner65a3a092005-09-27 04:45:34 +00002744 if (!Val) return false; // Cannot determine.
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00002745 NextBB = SI->findCaseValue(Val).getCaseSuccessor();
Chris Lattner31274882009-10-29 05:51:50 +00002746 } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(CurInst)) {
Nick Lewycky73be5e32012-02-19 23:26:27 +00002747 Value *Val = getVal(IBI->getAddress())->stripPointerCasts();
Chris Lattner31274882009-10-29 05:51:50 +00002748 if (BlockAddress *BA = dyn_cast<BlockAddress>(Val))
Nick Lewycky239fdf02012-02-06 08:24:44 +00002749 NextBB = BA->getBasicBlock();
Chris Lattneraa99c942009-11-01 01:27:45 +00002750 else
2751 return false; // Cannot determine.
Nick Lewycky239fdf02012-02-06 08:24:44 +00002752 } else if (isa<ReturnInst>(CurInst)) {
Craig Topperf40110f2014-04-25 05:29:35 +00002753 NextBB = nullptr;
Chris Lattner3e9ea5f2005-09-26 04:57:38 +00002754 } else {
Bill Wendlingf891bf82011-07-31 06:30:59 +00002755 // invoke, unwind, resume, unreachable.
Michael Gottesman2a654272013-01-11 23:08:52 +00002756 DEBUG(dbgs() << "Can not handle terminator.");
Chris Lattner65a3a092005-09-27 04:45:34 +00002757 return false; // Cannot handle this terminator.
Chris Lattner3e9ea5f2005-09-26 04:57:38 +00002758 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002759
Nick Lewycky239fdf02012-02-06 08:24:44 +00002760 // We succeeded at evaluating this block!
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002761 DEBUG(dbgs() << "Successfully evaluated block.\n");
Nick Lewycky239fdf02012-02-06 08:24:44 +00002762 return true;
Chris Lattner99e23fa2005-09-26 04:44:35 +00002763 } else {
Chris Lattner99e23fa2005-09-26 04:44:35 +00002764 // Did not know how to evaluate this!
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002765 DEBUG(dbgs() << "Failed to evaluate block due to unhandled instruction."
Michael Gottesman2a654272013-01-11 23:08:52 +00002766 "\n");
Chris Lattner65a3a092005-09-27 04:45:34 +00002767 return false;
Chris Lattner99e23fa2005-09-26 04:44:35 +00002768 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002769
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002770 if (!CurInst->use_empty()) {
2771 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(InstResult))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002772 InstResult = ConstantFoldConstantExpression(CE, DL, TLI);
Jakub Staszak9525a772012-12-06 21:57:16 +00002773
Nick Lewycky73be5e32012-02-19 23:26:27 +00002774 setVal(CurInst, InstResult);
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002775 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002776
Dan Gohmaneab06fa2012-03-13 18:01:37 +00002777 // If we just processed an invoke, we finished evaluating the block.
2778 if (InvokeInst *II = dyn_cast<InvokeInst>(CurInst)) {
2779 NextBB = II->getNormalDest();
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002780 DEBUG(dbgs() << "Found an invoke instruction. Finished Block.\n\n");
Dan Gohmaneab06fa2012-03-13 18:01:37 +00002781 return true;
2782 }
2783
Chris Lattner99e23fa2005-09-26 04:44:35 +00002784 // Advance program counter.
2785 ++CurInst;
2786 }
Chris Lattnerda1889b2005-09-27 04:27:01 +00002787}
2788
Nick Lewycky239fdf02012-02-06 08:24:44 +00002789/// EvaluateFunction - Evaluate a call to function F, returning true if
2790/// successful, false if we can't evaluate it. ActualArgs contains the formal
2791/// arguments for the function.
Nick Lewycky60829a582012-02-20 03:25:59 +00002792bool Evaluator::EvaluateFunction(Function *F, Constant *&RetVal,
2793 const SmallVectorImpl<Constant*> &ActualArgs) {
Nick Lewycky239fdf02012-02-06 08:24:44 +00002794 // Check to see if this function is already executing (recursion). If so,
2795 // bail out. TODO: we might want to accept limited recursion.
2796 if (std::find(CallStack.begin(), CallStack.end(), F) != CallStack.end())
2797 return false;
2798
2799 CallStack.push_back(F);
2800
Nick Lewycky239fdf02012-02-06 08:24:44 +00002801 // Initialize arguments to the incoming values specified.
2802 unsigned ArgNo = 0;
2803 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); AI != E;
2804 ++AI, ++ArgNo)
Nick Lewycky73be5e32012-02-19 23:26:27 +00002805 setVal(AI, ActualArgs[ArgNo]);
Nick Lewycky239fdf02012-02-06 08:24:44 +00002806
2807 // ExecutedBlocks - We only handle non-looping, non-recursive code. As such,
2808 // we can only evaluate any one basic block at most once. This set keeps
2809 // track of what we have executed so we can detect recursive cases etc.
2810 SmallPtrSet<BasicBlock*, 32> ExecutedBlocks;
2811
2812 // CurBB - The current basic block we're evaluating.
2813 BasicBlock *CurBB = F->begin();
2814
Nick Lewycky4231c412012-02-12 00:47:24 +00002815 BasicBlock::iterator CurInst = CurBB->begin();
2816
Nick Lewycky239fdf02012-02-06 08:24:44 +00002817 while (1) {
Craig Topperf40110f2014-04-25 05:29:35 +00002818 BasicBlock *NextBB = nullptr; // Initialized to avoid compiler warnings.
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002819 DEBUG(dbgs() << "Trying to evaluate BB: " << *CurBB << "\n");
2820
Nick Lewycky73be5e32012-02-19 23:26:27 +00002821 if (!EvaluateBlock(CurInst, NextBB))
Nick Lewycky239fdf02012-02-06 08:24:44 +00002822 return false;
2823
Craig Topperf40110f2014-04-25 05:29:35 +00002824 if (!NextBB) {
Nick Lewycky239fdf02012-02-06 08:24:44 +00002825 // Successfully running until there's no next block means that we found
2826 // the return. Fill it the return value and pop the call stack.
2827 ReturnInst *RI = cast<ReturnInst>(CurBB->getTerminator());
2828 if (RI->getNumOperands())
Nick Lewycky73be5e32012-02-19 23:26:27 +00002829 RetVal = getVal(RI->getOperand(0));
Nick Lewycky239fdf02012-02-06 08:24:44 +00002830 CallStack.pop_back();
2831 return true;
2832 }
2833
2834 // Okay, we succeeded in evaluating this control flow. See if we have
2835 // executed the new block before. If so, we have a looping function,
2836 // which we cannot evaluate in reasonable time.
David Blaikie70573dc2014-11-19 07:49:26 +00002837 if (!ExecutedBlocks.insert(NextBB).second)
Nick Lewycky239fdf02012-02-06 08:24:44 +00002838 return false; // looped!
2839
2840 // Okay, we have never been in this block before. Check to see if there
2841 // are any PHI nodes. If so, evaluate them with information about where
2842 // we came from.
Craig Topperf40110f2014-04-25 05:29:35 +00002843 PHINode *PN = nullptr;
Nick Lewycky4231c412012-02-12 00:47:24 +00002844 for (CurInst = NextBB->begin();
2845 (PN = dyn_cast<PHINode>(CurInst)); ++CurInst)
Nick Lewycky73be5e32012-02-19 23:26:27 +00002846 setVal(PN, getVal(PN->getIncomingValueForBlock(CurBB)));
Nick Lewycky239fdf02012-02-06 08:24:44 +00002847
2848 // Advance to the next block.
2849 CurBB = NextBB;
2850 }
2851}
2852
Chris Lattnerda1889b2005-09-27 04:27:01 +00002853/// EvaluateStaticConstructor - Evaluate static constructors in the function, if
2854/// we can. Return true if we can, false otherwise.
Mehdi Amini46a43552015-03-04 18:43:29 +00002855static bool EvaluateStaticConstructor(Function *F, const DataLayout &DL,
Chad Rosiere6de63d2011-12-01 21:29:16 +00002856 const TargetLibraryInfo *TLI) {
Chris Lattnerda1889b2005-09-27 04:27:01 +00002857 // Call the function.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002858 Evaluator Eval(DL, TLI);
Chris Lattner65a3a092005-09-27 04:45:34 +00002859 Constant *RetValDummy;
Nick Lewycky73be5e32012-02-19 23:26:27 +00002860 bool EvalSuccess = Eval.EvaluateFunction(F, RetValDummy,
2861 SmallVector<Constant*, 0>());
Jakub Staszak9525a772012-12-06 21:57:16 +00002862
Chris Lattnerda1889b2005-09-27 04:27:01 +00002863 if (EvalSuccess) {
Nico Weber4b2acde2014-05-02 18:35:25 +00002864 ++NumCtorsEvaluated;
2865
Chris Lattner6bf2cd52005-09-26 17:07:09 +00002866 // We succeeded at evaluation: commit the result.
David Greene44cb8ad2010-01-05 01:28:05 +00002867 DEBUG(dbgs() << "FULLY EVALUATED GLOBAL CTOR FUNCTION '"
Anthony Pesch3da0acd2015-07-22 21:10:45 +00002868 << F->getName() << "' to " << Eval.getMutated().size()
2869 << " mutated globals.\n");
2870
2871 MutatedGlobals &Mutated = Eval.getMutated();
2872 for (auto I : Mutated)
2873 Mutated.Commit(I.second);
2874
Craig Topper46276792014-08-24 23:23:06 +00002875 for (GlobalVariable *GV : Eval.getInvariants())
2876 GV->setConstant(true);
Chris Lattner6bf2cd52005-09-26 17:07:09 +00002877 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002878
Chris Lattnerda1889b2005-09-27 04:27:01 +00002879 return EvalSuccess;
Chris Lattner99e23fa2005-09-26 04:44:35 +00002880}
2881
Benjamin Krameradf1ea82014-03-07 21:52:38 +00002882static int compareNames(Constant *const *A, Constant *const *B) {
2883 return (*A)->getName().compare((*B)->getName());
2884}
2885
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002886static void setUsedInitializer(GlobalVariable &V,
Craig Topper97ebe532014-08-19 07:44:27 +00002887 const SmallPtrSet<GlobalValue *, 8> &Init) {
Rafael Espindolac2bb73f2013-07-20 23:33:15 +00002888 if (Init.empty()) {
2889 V.eraseFromParent();
2890 return;
2891 }
2892
Matt Arsenaultda1deab2014-01-02 19:53:49 +00002893 // Type of pointer to the array of pointers.
2894 PointerType *Int8PtrTy = Type::getInt8PtrTy(V.getContext(), 0);
Rafael Espindola00752162013-05-09 17:22:59 +00002895
Matt Arsenaultda1deab2014-01-02 19:53:49 +00002896 SmallVector<llvm::Constant *, 8> UsedArray;
Craig Topper71b7b682014-08-21 05:55:13 +00002897 for (GlobalValue *GV : Init) {
Matt Arsenaultda1deab2014-01-02 19:53:49 +00002898 Constant *Cast
Craig Topper71b7b682014-08-21 05:55:13 +00002899 = ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, Int8PtrTy);
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002900 UsedArray.push_back(Cast);
Rafael Espindola00752162013-05-09 17:22:59 +00002901 }
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002902 // Sort to get deterministic order.
Benjamin Krameradf1ea82014-03-07 21:52:38 +00002903 array_pod_sort(UsedArray.begin(), UsedArray.end(), compareNames);
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002904 ArrayType *ATy = ArrayType::get(Int8PtrTy, UsedArray.size());
Rafael Espindola00752162013-05-09 17:22:59 +00002905
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002906 Module *M = V.getParent();
2907 V.removeFromParent();
2908 GlobalVariable *NV =
2909 new GlobalVariable(*M, ATy, false, llvm::GlobalValue::AppendingLinkage,
2910 llvm::ConstantArray::get(ATy, UsedArray), "");
2911 NV->takeName(&V);
2912 NV->setSection("llvm.metadata");
2913 delete &V;
Rafael Espindola00752162013-05-09 17:22:59 +00002914}
2915
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002916namespace {
Rafael Espindola9aadcc42013-07-19 18:44:51 +00002917/// \brief An easy to access representation of llvm.used and llvm.compiler.used.
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002918class LLVMUsed {
2919 SmallPtrSet<GlobalValue *, 8> Used;
2920 SmallPtrSet<GlobalValue *, 8> CompilerUsed;
2921 GlobalVariable *UsedV;
2922 GlobalVariable *CompilerUsedV;
2923
2924public:
Rafael Espindolaec2375f2013-07-25 02:50:08 +00002925 LLVMUsed(Module &M) {
Rafael Espindola17600e22013-07-25 03:23:25 +00002926 UsedV = collectUsedGlobalVariables(M, Used, false);
2927 CompilerUsedV = collectUsedGlobalVariables(M, CompilerUsed, true);
Rafael Espindola00752162013-05-09 17:22:59 +00002928 }
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002929 typedef SmallPtrSet<GlobalValue *, 8>::iterator iterator;
Craig Topper46276792014-08-24 23:23:06 +00002930 typedef iterator_range<iterator> used_iterator_range;
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002931 iterator usedBegin() { return Used.begin(); }
2932 iterator usedEnd() { return Used.end(); }
Craig Topper46276792014-08-24 23:23:06 +00002933 used_iterator_range used() {
2934 return used_iterator_range(usedBegin(), usedEnd());
2935 }
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002936 iterator compilerUsedBegin() { return CompilerUsed.begin(); }
2937 iterator compilerUsedEnd() { return CompilerUsed.end(); }
Craig Topper46276792014-08-24 23:23:06 +00002938 used_iterator_range compilerUsed() {
2939 return used_iterator_range(compilerUsedBegin(), compilerUsedEnd());
2940 }
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002941 bool usedCount(GlobalValue *GV) const { return Used.count(GV); }
2942 bool compilerUsedCount(GlobalValue *GV) const {
2943 return CompilerUsed.count(GV);
2944 }
2945 bool usedErase(GlobalValue *GV) { return Used.erase(GV); }
2946 bool compilerUsedErase(GlobalValue *GV) { return CompilerUsed.erase(GV); }
David Blaikie70573dc2014-11-19 07:49:26 +00002947 bool usedInsert(GlobalValue *GV) { return Used.insert(GV).second; }
2948 bool compilerUsedInsert(GlobalValue *GV) {
2949 return CompilerUsed.insert(GV).second;
2950 }
Rafael Espindola00752162013-05-09 17:22:59 +00002951
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002952 void syncVariablesAndSets() {
2953 if (UsedV)
2954 setUsedInitializer(*UsedV, Used);
2955 if (CompilerUsedV)
2956 setUsedInitializer(*CompilerUsedV, CompilerUsed);
2957 }
2958};
Alexander Kornienkof00654e2015-06-23 09:49:53 +00002959}
Rafael Espindola00752162013-05-09 17:22:59 +00002960
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002961static bool hasUseOtherThanLLVMUsed(GlobalAlias &GA, const LLVMUsed &U) {
2962 if (GA.use_empty()) // No use at all.
2963 return false;
2964
2965 assert((!U.usedCount(&GA) || !U.compilerUsedCount(&GA)) &&
2966 "We should have removed the duplicated "
Rafael Espindola9aadcc42013-07-19 18:44:51 +00002967 "element from llvm.compiler.used");
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002968 if (!GA.hasOneUse())
2969 // Strictly more than one use. So at least one is not in llvm.used and
Rafael Espindola9aadcc42013-07-19 18:44:51 +00002970 // llvm.compiler.used.
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002971 return true;
2972
Rafael Espindola9aadcc42013-07-19 18:44:51 +00002973 // Exactly one use. Check if it is in llvm.used or llvm.compiler.used.
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002974 return !U.usedCount(&GA) && !U.compilerUsedCount(&GA);
Rafael Espindola00752162013-05-09 17:22:59 +00002975}
2976
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002977static bool hasMoreThanOneUseOtherThanLLVMUsed(GlobalValue &V,
2978 const LLVMUsed &U) {
2979 unsigned N = 2;
2980 assert((!U.usedCount(&V) || !U.compilerUsedCount(&V)) &&
2981 "We should have removed the duplicated "
Rafael Espindola9aadcc42013-07-19 18:44:51 +00002982 "element from llvm.compiler.used");
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002983 if (U.usedCount(&V) || U.compilerUsedCount(&V))
2984 ++N;
2985 return V.hasNUsesOrMore(N);
2986}
2987
2988static bool mayHaveOtherReferences(GlobalAlias &GA, const LLVMUsed &U) {
2989 if (!GA.hasLocalLinkage())
2990 return true;
2991
2992 return U.usedCount(&GA) || U.compilerUsedCount(&GA);
2993}
2994
Craig Topper71b7b682014-08-21 05:55:13 +00002995static bool hasUsesToReplace(GlobalAlias &GA, const LLVMUsed &U,
2996 bool &RenameTarget) {
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002997 RenameTarget = false;
Rafael Espindola00752162013-05-09 17:22:59 +00002998 bool Ret = false;
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002999 if (hasUseOtherThanLLVMUsed(GA, U))
Rafael Espindola00752162013-05-09 17:22:59 +00003000 Ret = true;
Rafael Espindolaa82555c2013-06-11 17:48:06 +00003001
3002 // If the alias is externally visible, we may still be able to simplify it.
3003 if (!mayHaveOtherReferences(GA, U))
3004 return Ret;
3005
3006 // If the aliasee has internal linkage, give it the name and linkage
3007 // of the alias, and delete the alias. This turns:
3008 // define internal ... @f(...)
3009 // @a = alias ... @f
3010 // into:
3011 // define ... @a(...)
3012 Constant *Aliasee = GA.getAliasee();
3013 GlobalValue *Target = cast<GlobalValue>(Aliasee->stripPointerCasts());
3014 if (!Target->hasLocalLinkage())
3015 return Ret;
3016
3017 // Do not perform the transform if multiple aliases potentially target the
3018 // aliasee. This check also ensures that it is safe to replace the section
3019 // and other attributes of the aliasee with those of the alias.
3020 if (hasMoreThanOneUseOtherThanLLVMUsed(*Target, U))
3021 return Ret;
3022
3023 RenameTarget = true;
3024 return true;
Rafael Espindola00752162013-05-09 17:22:59 +00003025}
3026
Duncan Sandsed722832009-03-06 10:21:56 +00003027bool GlobalOpt::OptimizeGlobalAliases(Module &M) {
Anton Korobeynikova9b60ee2008-09-09 19:04:59 +00003028 bool Changed = false;
Rafael Espindolaa82555c2013-06-11 17:48:06 +00003029 LLVMUsed Used(M);
3030
Craig Topper46276792014-08-24 23:23:06 +00003031 for (GlobalValue *GV : Used.used())
3032 Used.compilerUsedErase(GV);
Anton Korobeynikova9b60ee2008-09-09 19:04:59 +00003033
Duncan Sands0bcf0852009-01-07 20:01:06 +00003034 for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end();
Duncan Sandsb3f27882009-02-15 09:56:08 +00003035 I != E;) {
3036 Module::alias_iterator J = I++;
Duncan Sandsed722832009-03-06 10:21:56 +00003037 // Aliases without names cannot be referenced outside this module.
David Majnemer5c921152014-07-01 15:26:50 +00003038 if (!J->hasName() && !J->isDeclaration() && !J->hasLocalLinkage())
Duncan Sandsed722832009-03-06 10:21:56 +00003039 J->setLinkage(GlobalValue::InternalLinkage);
Duncan Sandsb3f27882009-02-15 09:56:08 +00003040 // If the aliasee may change at link time, nothing can be done - bail out.
3041 if (J->mayBeOverridden())
Anton Korobeynikova9b60ee2008-09-09 19:04:59 +00003042 continue;
3043
Duncan Sandsb3f27882009-02-15 09:56:08 +00003044 Constant *Aliasee = J->getAliasee();
David Majnemer0e2cc2a2014-07-01 00:30:56 +00003045 GlobalValue *Target = dyn_cast<GlobalValue>(Aliasee->stripPointerCasts());
3046 // We can't trivially replace the alias with the aliasee if the aliasee is
3047 // non-trivial in some way.
3048 // TODO: Try to handle non-zero GEPs of local aliasees.
3049 if (!Target)
3050 continue;
Duncan Sands7a1db332009-02-18 17:55:38 +00003051 Target->removeDeadConstantUsers();
Duncan Sandsb3f27882009-02-15 09:56:08 +00003052
3053 // Make all users of the alias use the aliasee instead.
Rafael Espindolaa82555c2013-06-11 17:48:06 +00003054 bool RenameTarget;
3055 if (!hasUsesToReplace(*J, Used, RenameTarget))
Rafael Espindola00752162013-05-09 17:22:59 +00003056 continue;
Duncan Sandsb3f27882009-02-15 09:56:08 +00003057
Rafael Espindola6b238632014-05-16 19:35:39 +00003058 J->replaceAllUsesWith(ConstantExpr::getBitCast(Aliasee, J->getType()));
Rafael Espindolaa82555c2013-06-11 17:48:06 +00003059 ++NumAliasesResolved;
3060 Changed = true;
Duncan Sandsb3f27882009-02-15 09:56:08 +00003061
Rafael Espindolaa82555c2013-06-11 17:48:06 +00003062 if (RenameTarget) {
Duncan Sands6a3df7b2009-12-08 10:10:20 +00003063 // Give the aliasee the name, linkage and other attributes of the alias.
3064 Target->takeName(J);
3065 Target->setLinkage(J->getLinkage());
Reid Kleckner22b19da2014-02-13 02:18:36 +00003066 Target->setVisibility(J->getVisibility());
3067 Target->setDLLStorageClass(J->getDLLStorageClass());
Rafael Espindolaa82555c2013-06-11 17:48:06 +00003068
3069 if (Used.usedErase(J))
3070 Used.usedInsert(Target);
3071
3072 if (Used.compilerUsedErase(J))
3073 Used.compilerUsedInsert(Target);
Rafael Espindola8d304802013-06-12 16:45:47 +00003074 } else if (mayHaveOtherReferences(*J, Used))
Rafael Espindolaa82555c2013-06-11 17:48:06 +00003075 continue;
3076
Duncan Sandsb3f27882009-02-15 09:56:08 +00003077 // Delete the alias.
3078 M.getAliasList().erase(J);
3079 ++NumAliasesRemoved;
3080 Changed = true;
Anton Korobeynikova9b60ee2008-09-09 19:04:59 +00003081 }
3082
Rafael Espindolaa82555c2013-06-11 17:48:06 +00003083 Used.syncVariablesAndSets();
3084
Anton Korobeynikova9b60ee2008-09-09 19:04:59 +00003085 return Changed;
3086}
Chris Lattner41b6a5a2005-09-26 01:43:45 +00003087
Nick Lewycky4b273cb2012-02-12 02:15:20 +00003088static Function *FindCXAAtExit(Module &M, TargetLibraryInfo *TLI) {
3089 if (!TLI->has(LibFunc::cxa_atexit))
Craig Topperf40110f2014-04-25 05:29:35 +00003090 return nullptr;
Nick Lewycky4b273cb2012-02-12 02:15:20 +00003091
3092 Function *Fn = M.getFunction(TLI->getName(LibFunc::cxa_atexit));
Jakub Staszak9525a772012-12-06 21:57:16 +00003093
Anders Carlssonee6bc702011-03-20 17:59:11 +00003094 if (!Fn)
Craig Topperf40110f2014-04-25 05:29:35 +00003095 return nullptr;
Nick Lewycky4b273cb2012-02-12 02:15:20 +00003096
Chris Lattner229907c2011-07-18 04:54:35 +00003097 FunctionType *FTy = Fn->getFunctionType();
Jakub Staszak9525a772012-12-06 21:57:16 +00003098
3099 // Checking that the function has the right return type, the right number of
Anders Carlsson48a44912011-03-20 19:51:13 +00003100 // parameters and that they all have pointer types should be enough.
3101 if (!FTy->getReturnType()->isIntegerTy() ||
3102 FTy->getNumParams() != 3 ||
Anders Carlssonee6bc702011-03-20 17:59:11 +00003103 !FTy->getParamType(0)->isPointerTy() ||
3104 !FTy->getParamType(1)->isPointerTy() ||
3105 !FTy->getParamType(2)->isPointerTy())
Craig Topperf40110f2014-04-25 05:29:35 +00003106 return nullptr;
Anders Carlssonee6bc702011-03-20 17:59:11 +00003107
3108 return Fn;
3109}
3110
3111/// cxxDtorIsEmpty - Returns whether the given function is an empty C++
3112/// destructor and can therefore be eliminated.
3113/// Note that we assume that other optimization passes have already simplified
3114/// the code so we only look for a function with a single basic block, where
Benjamin Kramer1a4695a2012-02-09 16:28:15 +00003115/// the only allowed instructions are 'ret', 'call' to an empty C++ dtor and
3116/// other side-effect free instructions.
Anders Carlssonfcec2f52011-03-20 20:16:43 +00003117static bool cxxDtorIsEmpty(const Function &Fn,
3118 SmallPtrSet<const Function *, 8> &CalledFunctions) {
Anders Carlsson48a44912011-03-20 19:51:13 +00003119 // FIXME: We could eliminate C++ destructors if they're readonly/readnone and
Nick Lewyckyd0781832011-03-21 02:26:01 +00003120 // nounwind, but that doesn't seem worth doing.
Anders Carlsson48a44912011-03-20 19:51:13 +00003121 if (Fn.isDeclaration())
3122 return false;
Anders Carlssonee6bc702011-03-20 17:59:11 +00003123
3124 if (++Fn.begin() != Fn.end())
3125 return false;
3126
3127 const BasicBlock &EntryBlock = Fn.getEntryBlock();
3128 for (BasicBlock::const_iterator I = EntryBlock.begin(), E = EntryBlock.end();
3129 I != E; ++I) {
3130 if (const CallInst *CI = dyn_cast<CallInst>(I)) {
Anders Carlsson4dd420f2011-03-21 14:54:40 +00003131 // Ignore debug intrinsics.
3132 if (isa<DbgInfoIntrinsic>(CI))
3133 continue;
3134
Anders Carlssonee6bc702011-03-20 17:59:11 +00003135 const Function *CalledFn = CI->getCalledFunction();
3136
3137 if (!CalledFn)
3138 return false;
3139
Anders Carlsson1cc80732011-03-22 03:21:01 +00003140 SmallPtrSet<const Function *, 8> NewCalledFunctions(CalledFunctions);
3141
Anders Carlsson48a44912011-03-20 19:51:13 +00003142 // Don't treat recursive functions as empty.
David Blaikie70573dc2014-11-19 07:49:26 +00003143 if (!NewCalledFunctions.insert(CalledFn).second)
Anders Carlsson48a44912011-03-20 19:51:13 +00003144 return false;
3145
Anders Carlsson1cc80732011-03-22 03:21:01 +00003146 if (!cxxDtorIsEmpty(*CalledFn, NewCalledFunctions))
Anders Carlssonee6bc702011-03-20 17:59:11 +00003147 return false;
3148 } else if (isa<ReturnInst>(*I))
Benjamin Kramer487a3962012-02-09 14:26:06 +00003149 return true; // We're done.
3150 else if (I->mayHaveSideEffects())
3151 return false; // Destructor with side effects, bail.
Anders Carlssonee6bc702011-03-20 17:59:11 +00003152 }
3153
3154 return false;
3155}
3156
3157bool GlobalOpt::OptimizeEmptyGlobalCXXDtors(Function *CXAAtExitFn) {
3158 /// Itanium C++ ABI p3.3.5:
3159 ///
3160 /// After constructing a global (or local static) object, that will require
3161 /// destruction on exit, a termination function is registered as follows:
3162 ///
3163 /// extern "C" int __cxa_atexit ( void (*f)(void *), void *p, void *d );
3164 ///
3165 /// This registration, e.g. __cxa_atexit(f,p,d), is intended to cause the
3166 /// call f(p) when DSO d is unloaded, before all such termination calls
3167 /// registered before this one. It returns zero if registration is
Nick Lewyckyd0781832011-03-21 02:26:01 +00003168 /// successful, nonzero on failure.
Anders Carlssonee6bc702011-03-20 17:59:11 +00003169
3170 // This pass will look for calls to __cxa_atexit where the function is trivial
3171 // and remove them.
3172 bool Changed = false;
3173
Chandler Carruthcdf47882014-03-09 03:16:01 +00003174 for (auto I = CXAAtExitFn->user_begin(), E = CXAAtExitFn->user_end();
3175 I != E;) {
Anders Carlsson336fd902011-03-20 20:21:33 +00003176 // We're only interested in calls. Theoretically, we could handle invoke
3177 // instructions as well, but neither llvm-gcc nor clang generate invokes
3178 // to __cxa_atexit.
Anders Carlsson4dd420f2011-03-21 14:54:40 +00003179 CallInst *CI = dyn_cast<CallInst>(*I++);
3180 if (!CI)
Anders Carlsson336fd902011-03-20 20:21:33 +00003181 continue;
3182
Jakub Staszak9525a772012-12-06 21:57:16 +00003183 Function *DtorFn =
Anders Carlsson4dd420f2011-03-21 14:54:40 +00003184 dyn_cast<Function>(CI->getArgOperand(0)->stripPointerCasts());
Anders Carlssonee6bc702011-03-20 17:59:11 +00003185 if (!DtorFn)
3186 continue;
3187
Anders Carlssonfcec2f52011-03-20 20:16:43 +00003188 SmallPtrSet<const Function *, 8> CalledFunctions;
3189 if (!cxxDtorIsEmpty(*DtorFn, CalledFunctions))
Anders Carlssonee6bc702011-03-20 17:59:11 +00003190 continue;
3191
3192 // Just remove the call.
Anders Carlsson4dd420f2011-03-21 14:54:40 +00003193 CI->replaceAllUsesWith(Constant::getNullValue(CI->getType()));
3194 CI->eraseFromParent();
Anders Carlsson48a44912011-03-20 19:51:13 +00003195
Anders Carlssonee6bc702011-03-20 17:59:11 +00003196 ++NumCXXDtorsRemoved;
3197
3198 Changed |= true;
3199 }
3200
3201 return Changed;
3202}
3203
Chris Lattner25db5802004-10-07 04:16:33 +00003204bool GlobalOpt::runOnModule(Module &M) {
3205 bool Changed = false;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00003206
Mehdi Amini46a43552015-03-04 18:43:29 +00003207 auto &DL = M.getDataLayout();
Chandler Carruthb98f63d2015-01-15 10:41:28 +00003208 TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Nick Lewyckycf6aae62012-02-12 01:13:18 +00003209
Chris Lattner25db5802004-10-07 04:16:33 +00003210 bool LocalChange = true;
3211 while (LocalChange) {
3212 LocalChange = false;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00003213
David Majnemer1b3b70e2014-10-08 07:23:31 +00003214 NotDiscardableComdats.clear();
3215 for (const GlobalVariable &GV : M.globals())
3216 if (const Comdat *C = GV.getComdat())
3217 if (!GV.isDiscardableIfUnused() || !GV.use_empty())
3218 NotDiscardableComdats.insert(C);
3219 for (Function &F : M)
3220 if (const Comdat *C = F.getComdat())
3221 if (!F.isDefTriviallyDead())
3222 NotDiscardableComdats.insert(C);
3223 for (GlobalAlias &GA : M.aliases())
3224 if (const Comdat *C = GA.getComdat())
3225 if (!GA.isDiscardableIfUnused() || !GA.use_empty())
3226 NotDiscardableComdats.insert(C);
3227
Chris Lattner41b6a5a2005-09-26 01:43:45 +00003228 // Delete functions that are trivially dead, ccc -> fastcc
3229 LocalChange |= OptimizeFunctions(M);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00003230
Chris Lattner41b6a5a2005-09-26 01:43:45 +00003231 // Optimize global_ctors list.
Richard Smithc167d652014-05-06 01:44:26 +00003232 LocalChange |= optimizeGlobalCtorsList(M, [&](Function *F) {
3233 return EvaluateStaticConstructor(F, DL, TLI);
3234 });
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00003235
Chris Lattner41b6a5a2005-09-26 01:43:45 +00003236 // Optimize non-address-taken globals.
3237 LocalChange |= OptimizeGlobalVars(M);
Anton Korobeynikova9b60ee2008-09-09 19:04:59 +00003238
3239 // Resolve aliases, when possible.
Duncan Sandsed722832009-03-06 10:21:56 +00003240 LocalChange |= OptimizeGlobalAliases(M);
Anders Carlssonee6bc702011-03-20 17:59:11 +00003241
Manman Renb3c52fb2013-05-14 21:52:44 +00003242 // Try to remove trivial global destructors if they are not removed
3243 // already.
3244 Function *CXAAtExitFn = FindCXAAtExit(M, TLI);
Anders Carlssonee6bc702011-03-20 17:59:11 +00003245 if (CXAAtExitFn)
3246 LocalChange |= OptimizeEmptyGlobalCXXDtors(CXAAtExitFn);
3247
Anton Korobeynikova9b60ee2008-09-09 19:04:59 +00003248 Changed |= LocalChange;
Chris Lattner25db5802004-10-07 04:16:33 +00003249 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00003250
Chris Lattner41b6a5a2005-09-26 01:43:45 +00003251 // TODO: Move all global ctors functions to the end of the module for code
3252 // layout.
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00003253
Chris Lattner25db5802004-10-07 04:16:33 +00003254 return Changed;
3255}
Anthony Pescha2d93692015-07-22 18:50:10 +00003256