blob: 083eb5de27a4ce932989970b10d086941fb046c9 [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"
James Molloy9c7d4d82015-11-15 14:21:37 +000031#include "llvm/IR/Dominators.h"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000032#include "llvm/IR/GetElementPtrTypeIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000033#include "llvm/IR/Instructions.h"
34#include "llvm/IR/IntrinsicInst.h"
35#include "llvm/IR/Module.h"
36#include "llvm/IR/Operator.h"
Chandler Carruth4220e9c2014-03-04 11:17:44 +000037#include "llvm/IR/ValueHandle.h"
Chris Lattner25db5802004-10-07 04:16:33 +000038#include "llvm/Pass.h"
Chris Lattner024f4ab2007-01-30 23:46:24 +000039#include "llvm/Support/Debug.h"
Torok Edwin56d06592009-07-11 20:10:48 +000040#include "llvm/Support/ErrorHandling.h"
Chris Lattner67ca6f632008-04-26 07:40:11 +000041#include "llvm/Support/MathExtras.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000042#include "llvm/Support/raw_ostream.h"
Nico Weber4b2acde2014-05-02 18:35:25 +000043#include "llvm/Transforms/Utils/CtorUtils.h"
Rafael Espindola3d7fc252013-10-21 17:14:55 +000044#include "llvm/Transforms/Utils/GlobalStatus.h"
Rafael Espindola17600e22013-07-25 03:23:25 +000045#include "llvm/Transforms/Utils/ModuleUtils.h"
Chris Lattner25db5802004-10-07 04:16:33 +000046#include <algorithm>
Benjamin Kramer64425fe2014-05-03 15:50:37 +000047#include <deque>
Chris Lattner25db5802004-10-07 04:16:33 +000048using namespace llvm;
49
Chandler Carruth964daaa2014-04-22 02:55:47 +000050#define DEBUG_TYPE "globalopt"
51
Chris Lattner1631bcb2006-12-19 22:09:18 +000052STATISTIC(NumMarked , "Number of globals marked constant");
Rafael Espindolafc355bc2011-01-19 16:32:21 +000053STATISTIC(NumUnnamed , "Number of globals marked unnamed_addr");
Chris Lattner1631bcb2006-12-19 22:09:18 +000054STATISTIC(NumSRA , "Number of aggregate globals broken into scalars");
55STATISTIC(NumHeapSRA , "Number of heap objects SRA'd");
56STATISTIC(NumSubstitute,"Number of globals with initializers stored into them");
57STATISTIC(NumDeleted , "Number of globals deleted");
58STATISTIC(NumFnDeleted , "Number of functions deleted");
59STATISTIC(NumGlobUses , "Number of global uses devirtualized");
Alexey Samsonova1944e62013-10-07 19:03:24 +000060STATISTIC(NumLocalized , "Number of globals localized");
Chris Lattner1631bcb2006-12-19 22:09:18 +000061STATISTIC(NumShrunkToBool , "Number of global vars shrunk to booleans");
62STATISTIC(NumFastCallFns , "Number of functions converted to fastcc");
63STATISTIC(NumCtorsEvaluated, "Number of static ctors evaluated");
Duncan Sands573b3f82008-02-16 20:56:04 +000064STATISTIC(NumNestRemoved , "Number of nest attributes removed");
Duncan Sandsb3f27882009-02-15 09:56:08 +000065STATISTIC(NumAliasesResolved, "Number of global aliases resolved");
66STATISTIC(NumAliasesRemoved, "Number of global aliases eliminated");
Anders Carlssonee6bc702011-03-20 17:59:11 +000067STATISTIC(NumCXXDtorsRemoved, "Number of global C++ destructors removed");
Chris Lattner25db5802004-10-07 04:16:33 +000068
Chris Lattner1631bcb2006-12-19 22:09:18 +000069namespace {
Nick Lewycky02d5f772009-10-25 06:33:48 +000070 struct GlobalOpt : public ModulePass {
Craig Topper3e4c6972014-03-05 09:10:37 +000071 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chandler Carruthb98f63d2015-01-15 10:41:28 +000072 AU.addRequired<TargetLibraryInfoWrapperPass>();
James Molloy9c7d4d82015-11-15 14:21:37 +000073 AU.addRequired<DominatorTreeWrapperPass>();
Chris Lattner004e2502004-10-11 05:54:41 +000074 }
Nick Lewyckye7da2d62007-05-06 13:37:16 +000075 static char ID; // Pass identification, replacement for typeid
Owen Anderson6c18d1a2010-10-19 17:21:58 +000076 GlobalOpt() : ModulePass(ID) {
77 initializeGlobalOptPass(*PassRegistry::getPassRegistry());
78 }
Misha Brukmanb1c93172005-04-21 23:48:37 +000079
Craig Topper3e4c6972014-03-05 09:10:37 +000080 bool runOnModule(Module &M) override;
Chris Lattner004e2502004-10-11 05:54:41 +000081
82 private:
Chris Lattner41b6a5a2005-09-26 01:43:45 +000083 bool OptimizeFunctions(Module &M);
84 bool OptimizeGlobalVars(Module &M);
Duncan Sandsed722832009-03-06 10:21:56 +000085 bool OptimizeGlobalAliases(Module &M);
Rafael Espindolafc355bc2011-01-19 16:32:21 +000086 bool ProcessGlobal(GlobalVariable *GV,Module::global_iterator &GVI);
87 bool ProcessInternalGlobal(GlobalVariable *GV,Module::global_iterator &GVI,
Rafael Espindolafc355bc2011-01-19 16:32:21 +000088 const GlobalStatus &GS);
Anders Carlssonee6bc702011-03-20 17:59:11 +000089 bool OptimizeEmptyGlobalCXXDtors(Function *CXAAtExitFn);
James Molloyd4d23572015-11-16 10:16:22 +000090
91 bool isPointerValueDeadOnEntryToFunction(const Function *F,
92 GlobalValue *GV);
93
Nick Lewyckycf6aae62012-02-12 01:13:18 +000094 TargetLibraryInfo *TLI;
David Majnemer1b3b70e2014-10-08 07:23:31 +000095 SmallSet<const Comdat *, 8> NotDiscardableComdats;
Chris Lattner25db5802004-10-07 04:16:33 +000096 };
Alexander Kornienkof00654e2015-06-23 09:49:53 +000097}
Chris Lattner25db5802004-10-07 04:16:33 +000098
Dan Gohmand78c4002008-05-13 00:00:25 +000099char GlobalOpt::ID = 0;
Chad Rosiere6de63d2011-12-01 21:29:16 +0000100INITIALIZE_PASS_BEGIN(GlobalOpt, "globalopt",
101 "Global Variable Optimizer", false, false)
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000102INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
James Molloy9c7d4d82015-11-15 14:21:37 +0000103INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Chad Rosiere6de63d2011-12-01 21:29:16 +0000104INITIALIZE_PASS_END(GlobalOpt, "globalopt",
Owen Andersondf7a4f22010-10-07 22:25:06 +0000105 "Global Variable Optimizer", false, false)
Dan Gohmand78c4002008-05-13 00:00:25 +0000106
Chris Lattner25db5802004-10-07 04:16:33 +0000107ModulePass *llvm::createGlobalOptimizerPass() { return new GlobalOpt(); }
108
James Molloyea31ad32015-11-13 11:05:07 +0000109/// Is this global variable possibly used by a leak checker as a root? If so,
110/// we might not really want to eliminate the stores to it.
Nick Lewyckyfaa9c3b02012-07-24 07:21:08 +0000111static bool isLeakCheckerRoot(GlobalVariable *GV) {
112 // A global variable is a root if it is a pointer, or could plausibly contain
113 // a pointer. There are two challenges; one is that we could have a struct
114 // the has an inner member which is a pointer. We recurse through the type to
115 // detect these (up to a point). The other is that we may actually be a union
116 // of a pointer and another type, and so our LLVM type is an integer which
117 // gets converted into a pointer, or our type is an [i8 x #] with a pointer
118 // potentially contained here.
119
120 if (GV->hasPrivateLinkage())
121 return false;
122
123 SmallVector<Type *, 4> Types;
124 Types.push_back(cast<PointerType>(GV->getType())->getElementType());
125
126 unsigned Limit = 20;
127 do {
128 Type *Ty = Types.pop_back_val();
129 switch (Ty->getTypeID()) {
130 default: break;
131 case Type::PointerTyID: return true;
132 case Type::ArrayTyID:
133 case Type::VectorTyID: {
134 SequentialType *STy = cast<SequentialType>(Ty);
135 Types.push_back(STy->getElementType());
136 break;
137 }
138 case Type::StructTyID: {
139 StructType *STy = cast<StructType>(Ty);
140 if (STy->isOpaque()) return true;
141 for (StructType::element_iterator I = STy->element_begin(),
142 E = STy->element_end(); I != E; ++I) {
143 Type *InnerTy = *I;
144 if (isa<PointerType>(InnerTy)) return true;
145 if (isa<CompositeType>(InnerTy))
146 Types.push_back(InnerTy);
147 }
148 break;
149 }
150 }
151 if (--Limit == 0) return true;
152 } while (!Types.empty());
153 return false;
154}
155
156/// Given a value that is stored to a global but never read, determine whether
157/// it's safe to remove the store and the chain of computation that feeds the
158/// store.
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000159static bool IsSafeComputationToRemove(Value *V, const TargetLibraryInfo *TLI) {
Nick Lewyckyfaa9c3b02012-07-24 07:21:08 +0000160 do {
161 if (isa<Constant>(V))
162 return true;
163 if (!V->hasOneUse())
164 return false;
Nick Lewycky7d0f1102012-07-25 21:19:40 +0000165 if (isa<LoadInst>(V) || isa<InvokeInst>(V) || isa<Argument>(V) ||
166 isa<GlobalValue>(V))
Nick Lewyckyfaa9c3b02012-07-24 07:21:08 +0000167 return false;
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000168 if (isAllocationFn(V, TLI))
Nick Lewyckyfaa9c3b02012-07-24 07:21:08 +0000169 return true;
170
171 Instruction *I = cast<Instruction>(V);
172 if (I->mayHaveSideEffects())
173 return false;
174 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
175 if (!GEP->hasAllConstantIndices())
176 return false;
177 } else if (I->getNumOperands() != 1) {
178 return false;
179 }
180
181 V = I->getOperand(0);
182 } while (1);
183}
184
James Molloyea31ad32015-11-13 11:05:07 +0000185/// This GV is a pointer root. Loop over all users of the global and clean up
186/// any that obviously don't assign the global a value that isn't dynamically
187/// allocated.
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000188static bool CleanupPointerRootUsers(GlobalVariable *GV,
189 const TargetLibraryInfo *TLI) {
Nick Lewyckyfaa9c3b02012-07-24 07:21:08 +0000190 // A brief explanation of leak checkers. The goal is to find bugs where
191 // pointers are forgotten, causing an accumulating growth in memory
192 // usage over time. The common strategy for leak checkers is to whitelist the
193 // memory pointed to by globals at exit. This is popular because it also
194 // solves another problem where the main thread of a C++ program may shut down
195 // before other threads that are still expecting to use those globals. To
196 // handle that case, we expect the program may create a singleton and never
197 // destroy it.
198
199 bool Changed = false;
200
201 // If Dead[n].first is the only use of a malloc result, we can delete its
202 // chain of computation and the store to the global in Dead[n].second.
203 SmallVector<std::pair<Instruction *, Instruction *>, 32> Dead;
204
205 // Constants can't be pointers to dynamically allocated memory.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000206 for (Value::user_iterator UI = GV->user_begin(), E = GV->user_end();
Nick Lewyckyfaa9c3b02012-07-24 07:21:08 +0000207 UI != E;) {
208 User *U = *UI++;
209 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
210 Value *V = SI->getValueOperand();
211 if (isa<Constant>(V)) {
212 Changed = true;
213 SI->eraseFromParent();
214 } else if (Instruction *I = dyn_cast<Instruction>(V)) {
215 if (I->hasOneUse())
216 Dead.push_back(std::make_pair(I, SI));
217 }
218 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(U)) {
219 if (isa<Constant>(MSI->getValue())) {
220 Changed = true;
221 MSI->eraseFromParent();
222 } else if (Instruction *I = dyn_cast<Instruction>(MSI->getValue())) {
223 if (I->hasOneUse())
224 Dead.push_back(std::make_pair(I, MSI));
225 }
226 } else if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(U)) {
227 GlobalVariable *MemSrc = dyn_cast<GlobalVariable>(MTI->getSource());
228 if (MemSrc && MemSrc->isConstant()) {
229 Changed = true;
230 MTI->eraseFromParent();
231 } else if (Instruction *I = dyn_cast<Instruction>(MemSrc)) {
232 if (I->hasOneUse())
233 Dead.push_back(std::make_pair(I, MTI));
234 }
235 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
236 if (CE->use_empty()) {
237 CE->destroyConstant();
238 Changed = true;
239 }
240 } else if (Constant *C = dyn_cast<Constant>(U)) {
Rafael Espindola27797ba2013-10-17 18:06:32 +0000241 if (isSafeToDestroyConstant(C)) {
Nick Lewyckyfaa9c3b02012-07-24 07:21:08 +0000242 C->destroyConstant();
243 // This could have invalidated UI, start over from scratch.
244 Dead.clear();
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000245 CleanupPointerRootUsers(GV, TLI);
Nick Lewyckyfaa9c3b02012-07-24 07:21:08 +0000246 return true;
247 }
248 }
249 }
250
251 for (int i = 0, e = Dead.size(); i != e; ++i) {
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000252 if (IsSafeComputationToRemove(Dead[i].first, TLI)) {
Nick Lewyckyfaa9c3b02012-07-24 07:21:08 +0000253 Dead[i].second->eraseFromParent();
254 Instruction *I = Dead[i].first;
255 do {
Michael Gottesman2a654272013-01-11 23:08:52 +0000256 if (isAllocationFn(I, TLI))
257 break;
Nick Lewyckyfaa9c3b02012-07-24 07:21:08 +0000258 Instruction *J = dyn_cast<Instruction>(I->getOperand(0));
259 if (!J)
260 break;
261 I->eraseFromParent();
262 I = J;
Nick Lewycky38be9312012-07-24 21:33:00 +0000263 } while (1);
Nick Lewyckyfaa9c3b02012-07-24 07:21:08 +0000264 I->eraseFromParent();
265 }
266 }
267
268 return Changed;
269}
270
James Molloyea31ad32015-11-13 11:05:07 +0000271/// We just marked GV constant. Loop over all users of the global, cleaning up
272/// the obvious ones. This is largely just a quick scan over the use list to
273/// clean up the easy and obvious cruft. This returns true if it made a change.
Nick Lewyckycf6aae62012-02-12 01:13:18 +0000274static bool CleanupConstantGlobalUsers(Value *V, Constant *Init,
Mehdi Amini46a43552015-03-04 18:43:29 +0000275 const DataLayout &DL,
Rafael Espindolaaeff8a92014-02-24 23:12:18 +0000276 TargetLibraryInfo *TLI) {
Chris Lattnercb9f1522004-10-10 16:43:46 +0000277 bool Changed = false;
Hal Finkelf59fd7d2013-12-12 20:45:24 +0000278 // Note that we need to use a weak value handle for the worklist items. When
279 // we delete a constant array, we may also be holding pointer to one of its
280 // elements (or an element of one of its elements if we're dealing with an
281 // array of arrays) in the worklist.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000282 SmallVector<WeakVH, 8> WorkList(V->user_begin(), V->user_end());
Bill Wendling88d06c32013-04-02 08:16:45 +0000283 while (!WorkList.empty()) {
Hal Finkelf59fd7d2013-12-12 20:45:24 +0000284 Value *UV = WorkList.pop_back_val();
285 if (!UV)
286 continue;
287
288 User *U = cast<User>(UV);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000289
Chris Lattner25db5802004-10-07 04:16:33 +0000290 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
Chris Lattner7561ca12005-02-27 18:58:52 +0000291 if (Init) {
292 // Replace the load with the initializer.
293 LI->replaceAllUsesWith(Init);
294 LI->eraseFromParent();
295 Changed = true;
296 }
Chris Lattner25db5802004-10-07 04:16:33 +0000297 } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
298 // Store must be unreachable or storing Init into the global.
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000299 SI->eraseFromParent();
Chris Lattnercb9f1522004-10-10 16:43:46 +0000300 Changed = true;
Chris Lattner25db5802004-10-07 04:16:33 +0000301 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
302 if (CE->getOpcode() == Instruction::GetElementPtr) {
Craig Topperf40110f2014-04-25 05:29:35 +0000303 Constant *SubInit = nullptr;
Chris Lattner46d9ff082005-09-26 07:34:35 +0000304 if (Init)
Dan Gohmane525d9d2009-10-05 16:36:26 +0000305 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000306 Changed |= CleanupConstantGlobalUsers(CE, SubInit, DL, TLI);
Matt Arsenault461c8e02014-01-02 20:01:43 +0000307 } else if ((CE->getOpcode() == Instruction::BitCast &&
308 CE->getType()->isPointerTy()) ||
309 CE->getOpcode() == Instruction::AddrSpaceCast) {
Chris Lattner7561ca12005-02-27 18:58:52 +0000310 // Pointer cast, delete any stores and memsets to the global.
Craig Topperf40110f2014-04-25 05:29:35 +0000311 Changed |= CleanupConstantGlobalUsers(CE, nullptr, DL, TLI);
Chris Lattner7561ca12005-02-27 18:58:52 +0000312 }
313
314 if (CE->use_empty()) {
315 CE->destroyConstant();
316 Changed = true;
Chris Lattner25db5802004-10-07 04:16:33 +0000317 }
318 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
Chris Lattnerf9c0fd72007-11-09 17:33:02 +0000319 // Do not transform "gepinst (gep constexpr (GV))" here, because forming
320 // "gepconstexpr (gep constexpr (GV))" will cause the two gep's to fold
321 // and will invalidate our notion of what Init is.
Craig Topperf40110f2014-04-25 05:29:35 +0000322 Constant *SubInit = nullptr;
Chris Lattnerf9c0fd72007-11-09 17:33:02 +0000323 if (!isa<ConstantExpr>(GEP->getOperand(0))) {
Mehdi Amini46a43552015-03-04 18:43:29 +0000324 ConstantExpr *CE = dyn_cast_or_null<ConstantExpr>(
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000325 ConstantFoldInstruction(GEP, DL, TLI));
Chris Lattnerf9c0fd72007-11-09 17:33:02 +0000326 if (Init && CE && CE->getOpcode() == Instruction::GetElementPtr)
Dan Gohmane525d9d2009-10-05 16:36:26 +0000327 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
Benjamin Krameraa9e4a52012-03-28 14:50:09 +0000328
329 // If the initializer is an all-null value and we have an inbounds GEP,
330 // we already know what the result of any load from that GEP is.
331 // TODO: Handle splats.
332 if (Init && isa<ConstantAggregateZero>(Init) && GEP->isInBounds())
333 SubInit = Constant::getNullValue(GEP->getType()->getElementType());
Chris Lattnerf9c0fd72007-11-09 17:33:02 +0000334 }
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000335 Changed |= CleanupConstantGlobalUsers(GEP, SubInit, DL, TLI);
Chris Lattnera0e769c2004-10-10 16:47:33 +0000336
Chris Lattnercb9f1522004-10-10 16:43:46 +0000337 if (GEP->use_empty()) {
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000338 GEP->eraseFromParent();
Chris Lattnercb9f1522004-10-10 16:43:46 +0000339 Changed = true;
340 }
Chris Lattner7561ca12005-02-27 18:58:52 +0000341 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U)) { // memset/cpy/mv
342 if (MI->getRawDest() == V) {
343 MI->eraseFromParent();
344 Changed = true;
345 }
346
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000347 } else if (Constant *C = dyn_cast<Constant>(U)) {
348 // If we have a chain of dead constantexprs or other things dangling from
349 // us, and if they are all dead, nuke them without remorse.
Rafael Espindola27797ba2013-10-17 18:06:32 +0000350 if (isSafeToDestroyConstant(C)) {
Devang Pateld926aaa2009-03-06 01:37:41 +0000351 C->destroyConstant();
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000352 CleanupConstantGlobalUsers(V, Init, DL, TLI);
Chris Lattnercb9f1522004-10-10 16:43:46 +0000353 return true;
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000354 }
Chris Lattner25db5802004-10-07 04:16:33 +0000355 }
356 }
Chris Lattnercb9f1522004-10-10 16:43:46 +0000357 return Changed;
Chris Lattner25db5802004-10-07 04:16:33 +0000358}
359
James Molloyea31ad32015-11-13 11:05:07 +0000360/// Return true if the specified instruction is a safe user of a derived
361/// expression from a global that we want to SROA.
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000362static bool isSafeSROAElementUse(Value *V) {
363 // We might have a dead and dangling constant hanging off of here.
364 if (Constant *C = dyn_cast<Constant>(V))
Rafael Espindola27797ba2013-10-17 18:06:32 +0000365 return isSafeToDestroyConstant(C);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000366
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000367 Instruction *I = dyn_cast<Instruction>(V);
368 if (!I) return false;
369
370 // Loads are ok.
371 if (isa<LoadInst>(I)) return true;
372
373 // Stores *to* the pointer are ok.
374 if (StoreInst *SI = dyn_cast<StoreInst>(I))
375 return SI->getOperand(0) != V;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000376
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000377 // Otherwise, it must be a GEP.
378 GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I);
Craig Topperf40110f2014-04-25 05:29:35 +0000379 if (!GEPI) return false;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000380
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000381 if (GEPI->getNumOperands() < 3 || !isa<Constant>(GEPI->getOperand(1)) ||
382 !cast<Constant>(GEPI->getOperand(1))->isNullValue())
383 return false;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000384
Chandler Carruthcdf47882014-03-09 03:16:01 +0000385 for (User *U : GEPI->users())
386 if (!isSafeSROAElementUse(U))
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000387 return false;
Chris Lattnerab053722008-01-14 01:31:05 +0000388 return true;
389}
390
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000391
James Molloyea31ad32015-11-13 11:05:07 +0000392/// U is a direct user of the specified global value. Look at it and its uses
393/// and decide whether it is safe to SROA this global.
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000394static bool IsUserOfGlobalSafeForSRA(User *U, GlobalValue *GV) {
395 // The user of the global must be a GEP Inst or a ConstantExpr GEP.
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000396 if (!isa<GetElementPtrInst>(U) &&
397 (!isa<ConstantExpr>(U) ||
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000398 cast<ConstantExpr>(U)->getOpcode() != Instruction::GetElementPtr))
399 return false;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000400
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000401 // Check to see if this ConstantExpr GEP is SRA'able. In particular, we
402 // don't like < 3 operand CE's, and we don't like non-constant integer
403 // indices. This enforces that all uses are 'gep GV, 0, C, ...' for some
404 // value of C.
405 if (U->getNumOperands() < 3 || !isa<Constant>(U->getOperand(1)) ||
406 !cast<Constant>(U->getOperand(1))->isNullValue() ||
407 !isa<ConstantInt>(U->getOperand(2)))
408 return false;
409
410 gep_type_iterator GEPI = gep_type_begin(U), E = gep_type_end(U);
411 ++GEPI; // Skip over the pointer index.
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000412
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000413 // If this is a use of an array allocation, do a bit more checking for sanity.
Chris Lattner229907c2011-07-18 04:54:35 +0000414 if (ArrayType *AT = dyn_cast<ArrayType>(*GEPI)) {
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000415 uint64_t NumElements = AT->getNumElements();
416 ConstantInt *Idx = cast<ConstantInt>(U->getOperand(2));
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000417
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000418 // Check to make sure that index falls within the array. If not,
419 // something funny is going on, so we won't do the optimization.
420 //
421 if (Idx->getZExtValue() >= NumElements)
422 return false;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000423
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000424 // We cannot scalar repl this level of the array unless any array
425 // sub-indices are in-range constants. In particular, consider:
426 // A[0][i]. We cannot know that the user isn't doing invalid things like
427 // allowing i to index an out-of-range subscript that accesses A[1].
428 //
429 // Scalar replacing *just* the outer index of the array is probably not
430 // going to be a win anyway, so just give up.
431 for (++GEPI; // Skip array index.
Dan Gohman82ac81b2009-08-18 14:58:19 +0000432 GEPI != E;
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000433 ++GEPI) {
434 uint64_t NumElements;
Chris Lattner229907c2011-07-18 04:54:35 +0000435 if (ArrayType *SubArrayTy = dyn_cast<ArrayType>(*GEPI))
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000436 NumElements = SubArrayTy->getNumElements();
Chris Lattner229907c2011-07-18 04:54:35 +0000437 else if (VectorType *SubVectorTy = dyn_cast<VectorType>(*GEPI))
Dan Gohman82ac81b2009-08-18 14:58:19 +0000438 NumElements = SubVectorTy->getNumElements();
439 else {
Duncan Sands19d0b472010-02-16 11:11:14 +0000440 assert((*GEPI)->isStructTy() &&
Dan Gohman82ac81b2009-08-18 14:58:19 +0000441 "Indexed GEP type is not array, vector, or struct!");
442 continue;
443 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000444
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000445 ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPI.getOperand());
446 if (!IdxVal || IdxVal->getZExtValue() >= NumElements)
447 return false;
448 }
449 }
450
Chandler Carruthcdf47882014-03-09 03:16:01 +0000451 for (User *UU : U->users())
452 if (!isSafeSROAElementUse(UU))
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000453 return false;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000454
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000455 return true;
456}
457
James Molloyea31ad32015-11-13 11:05:07 +0000458/// Look at all uses of the global and decide whether it is safe for us to
459/// perform this transformation.
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000460static bool GlobalUsersSafeToSRA(GlobalValue *GV) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000461 for (User *U : GV->users())
462 if (!IsUserOfGlobalSafeForSRA(U, GV))
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000463 return false;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000464
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000465 return true;
466}
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000467
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000468
James Molloyea31ad32015-11-13 11:05:07 +0000469/// Perform scalar replacement of aggregates on the specified global variable.
470/// This opens the door for other optimizations by exposing the behavior of the
471/// program in a more fine-grained way. We have determined that this
472/// transformation is safe already. We return the first global variable we
Chris Lattnerabab0712004-10-08 17:32:09 +0000473/// insert so that the caller can reprocess it.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000474static GlobalVariable *SRAGlobal(GlobalVariable *GV, const DataLayout &DL) {
Chris Lattnerab053722008-01-14 01:31:05 +0000475 // Make sure this global only has simple uses that we can SRA.
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000476 if (!GlobalUsersSafeToSRA(GV))
Craig Topperf40110f2014-04-25 05:29:35 +0000477 return nullptr;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000478
Rafael Espindola6de96a12009-01-15 20:18:42 +0000479 assert(GV->hasLocalLinkage() && !GV->isConstant());
Chris Lattnerabab0712004-10-08 17:32:09 +0000480 Constant *Init = GV->getInitializer();
Chris Lattner229907c2011-07-18 04:54:35 +0000481 Type *Ty = Init->getType();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000482
Chris Lattnerabab0712004-10-08 17:32:09 +0000483 std::vector<GlobalVariable*> NewGlobals;
484 Module::GlobalListType &Globals = GV->getParent()->getGlobalList();
485
Chris Lattner67ca6f632008-04-26 07:40:11 +0000486 // Get the alignment of the global, either explicit or target-specific.
487 unsigned StartAlignment = GV->getAlignment();
488 if (StartAlignment == 0)
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000489 StartAlignment = DL.getABITypeAlignment(GV->getType());
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000490
Chris Lattner229907c2011-07-18 04:54:35 +0000491 if (StructType *STy = dyn_cast<StructType>(Ty)) {
Chris Lattnerabab0712004-10-08 17:32:09 +0000492 NewGlobals.reserve(STy->getNumElements());
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000493 const StructLayout &Layout = *DL.getStructLayout(STy);
Chris Lattnerabab0712004-10-08 17:32:09 +0000494 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
Chris Lattner67058832012-01-25 06:48:06 +0000495 Constant *In = Init->getAggregateElement(i);
Chris Lattnerabab0712004-10-08 17:32:09 +0000496 assert(In && "Couldn't get element of initializer?");
Chris Lattner46b5c642009-11-06 04:27:31 +0000497 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(i), false,
Chris Lattnerabab0712004-10-08 17:32:09 +0000498 GlobalVariable::InternalLinkage,
Daniel Dunbar132f7832009-07-30 17:37:43 +0000499 In, GV->getName()+"."+Twine(i),
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000500 GV->getThreadLocalMode(),
Owen Anderson5948fdf2009-07-08 01:26:06 +0000501 GV->getType()->getAddressSpace());
Oliver Stannardc1103392015-11-09 16:47:16 +0000502 NGV->setExternallyInitialized(GV->isExternallyInitialized());
Duncan P. N. Exon Smith17323402015-10-13 17:51:03 +0000503 Globals.insert(GV->getIterator(), NGV);
Chris Lattnerabab0712004-10-08 17:32:09 +0000504 NewGlobals.push_back(NGV);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000505
Chris Lattner67ca6f632008-04-26 07:40:11 +0000506 // Calculate the known alignment of the field. If the original aggregate
507 // had 256 byte alignment for example, something might depend on that:
508 // propagate info to each field.
509 uint64_t FieldOffset = Layout.getElementOffset(i);
510 unsigned NewAlign = (unsigned)MinAlign(StartAlignment, FieldOffset);
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000511 if (NewAlign > DL.getABITypeAlignment(STy->getElementType(i)))
Chris Lattner67ca6f632008-04-26 07:40:11 +0000512 NGV->setAlignment(NewAlign);
Chris Lattnerabab0712004-10-08 17:32:09 +0000513 }
Chris Lattner229907c2011-07-18 04:54:35 +0000514 } else if (SequentialType *STy = dyn_cast<SequentialType>(Ty)) {
Chris Lattnerabab0712004-10-08 17:32:09 +0000515 unsigned NumElements = 0;
Chris Lattner229907c2011-07-18 04:54:35 +0000516 if (ArrayType *ATy = dyn_cast<ArrayType>(STy))
Chris Lattnerabab0712004-10-08 17:32:09 +0000517 NumElements = ATy->getNumElements();
Chris Lattnerabab0712004-10-08 17:32:09 +0000518 else
Chris Lattner67ca6f632008-04-26 07:40:11 +0000519 NumElements = cast<VectorType>(STy)->getNumElements();
Chris Lattnerabab0712004-10-08 17:32:09 +0000520
Chris Lattner25169ca2005-02-23 16:53:04 +0000521 if (NumElements > 16 && GV->hasNUsesOrMore(16))
Craig Topperf40110f2014-04-25 05:29:35 +0000522 return nullptr; // It's not worth it.
Chris Lattnerabab0712004-10-08 17:32:09 +0000523 NewGlobals.reserve(NumElements);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000524
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000525 uint64_t EltSize = DL.getTypeAllocSize(STy->getElementType());
526 unsigned EltAlign = DL.getABITypeAlignment(STy->getElementType());
Chris Lattnerabab0712004-10-08 17:32:09 +0000527 for (unsigned i = 0, e = NumElements; i != e; ++i) {
Chris Lattner67058832012-01-25 06:48:06 +0000528 Constant *In = Init->getAggregateElement(i);
Chris Lattnerabab0712004-10-08 17:32:09 +0000529 assert(In && "Couldn't get element of initializer?");
530
Chris Lattner46b5c642009-11-06 04:27:31 +0000531 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(), false,
Chris Lattnerabab0712004-10-08 17:32:09 +0000532 GlobalVariable::InternalLinkage,
Daniel Dunbar132f7832009-07-30 17:37:43 +0000533 In, GV->getName()+"."+Twine(i),
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000534 GV->getThreadLocalMode(),
Owen Andersonb17f3292009-07-08 19:03:57 +0000535 GV->getType()->getAddressSpace());
Oliver Stannardc1103392015-11-09 16:47:16 +0000536 NGV->setExternallyInitialized(GV->isExternallyInitialized());
Duncan P. N. Exon Smith17323402015-10-13 17:51:03 +0000537 Globals.insert(GV->getIterator(), NGV);
Chris Lattnerabab0712004-10-08 17:32:09 +0000538 NewGlobals.push_back(NGV);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000539
Chris Lattner67ca6f632008-04-26 07:40:11 +0000540 // Calculate the known alignment of the field. If the original aggregate
541 // had 256 byte alignment for example, something might depend on that:
542 // propagate info to each field.
543 unsigned NewAlign = (unsigned)MinAlign(StartAlignment, EltSize*i);
544 if (NewAlign > EltAlign)
545 NGV->setAlignment(NewAlign);
Chris Lattnerabab0712004-10-08 17:32:09 +0000546 }
547 }
548
549 if (NewGlobals.empty())
Craig Topperf40110f2014-04-25 05:29:35 +0000550 return nullptr;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000551
James Molloyef607a22015-10-28 14:30:53 +0000552 DEBUG(dbgs() << "PERFORMING GLOBAL SRA ON: " << *GV << "\n");
Chris Lattner004e2502004-10-11 05:54:41 +0000553
Chris Lattner46b5c642009-11-06 04:27:31 +0000554 Constant *NullInt =Constant::getNullValue(Type::getInt32Ty(GV->getContext()));
Chris Lattnerabab0712004-10-08 17:32:09 +0000555
556 // Loop over all of the uses of the global, replacing the constantexpr geps,
557 // with smaller constantexpr geps or direct references.
558 while (!GV->use_empty()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000559 User *GEP = GV->user_back();
Chris Lattner004e2502004-10-11 05:54:41 +0000560 assert(((isa<ConstantExpr>(GEP) &&
561 cast<ConstantExpr>(GEP)->getOpcode()==Instruction::GetElementPtr)||
562 isa<GetElementPtrInst>(GEP)) && "NonGEP CE's are not SRAable!");
Misha Brukmanb1c93172005-04-21 23:48:37 +0000563
Chris Lattnerabab0712004-10-08 17:32:09 +0000564 // Ignore the 1th operand, which has to be zero or else the program is quite
565 // broken (undefined). Get the 2nd operand, which is the structure or array
566 // index.
Reid Spencere0fc4df2006-10-20 07:07:24 +0000567 unsigned Val = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
Chris Lattnerabab0712004-10-08 17:32:09 +0000568 if (Val >= NewGlobals.size()) Val = 0; // Out of bound array access.
569
Chris Lattner004e2502004-10-11 05:54:41 +0000570 Value *NewPtr = NewGlobals[Val];
David Blaikied9d900c2015-05-07 17:28:58 +0000571 Type *NewTy = NewGlobals[Val]->getValueType();
Chris Lattnerabab0712004-10-08 17:32:09 +0000572
573 // Form a shorter GEP if needed.
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +0000574 if (GEP->getNumOperands() > 3) {
Chris Lattner004e2502004-10-11 05:54:41 +0000575 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEP)) {
Chris Lattnerf96f4a82007-01-31 04:40:53 +0000576 SmallVector<Constant*, 8> Idxs;
Chris Lattner004e2502004-10-11 05:54:41 +0000577 Idxs.push_back(NullInt);
578 for (unsigned i = 3, e = CE->getNumOperands(); i != e; ++i)
579 Idxs.push_back(CE->getOperand(i));
David Blaikie4a2e73b2015-04-02 18:55:32 +0000580 NewPtr =
581 ConstantExpr::getGetElementPtr(NewTy, cast<Constant>(NewPtr), Idxs);
Chris Lattner004e2502004-10-11 05:54:41 +0000582 } else {
583 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(GEP);
Chris Lattner927653f2007-01-31 19:59:55 +0000584 SmallVector<Value*, 8> Idxs;
Chris Lattner004e2502004-10-11 05:54:41 +0000585 Idxs.push_back(NullInt);
586 for (unsigned i = 3, e = GEPI->getNumOperands(); i != e; ++i)
587 Idxs.push_back(GEPI->getOperand(i));
David Blaikie741c8f82015-03-14 01:53:18 +0000588 NewPtr = GetElementPtrInst::Create(
David Blaikied9d900c2015-05-07 17:28:58 +0000589 NewTy, NewPtr, Idxs, GEPI->getName() + "." + Twine(Val), GEPI);
Chris Lattner004e2502004-10-11 05:54:41 +0000590 }
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +0000591 }
Chris Lattner004e2502004-10-11 05:54:41 +0000592 GEP->replaceAllUsesWith(NewPtr);
593
594 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(GEP))
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000595 GEPI->eraseFromParent();
Chris Lattner004e2502004-10-11 05:54:41 +0000596 else
597 cast<ConstantExpr>(GEP)->destroyConstant();
Chris Lattnerabab0712004-10-08 17:32:09 +0000598 }
599
Chris Lattner73ad73e2004-10-08 20:25:55 +0000600 // Delete the old global, now that it is dead.
601 Globals.erase(GV);
Chris Lattnerabab0712004-10-08 17:32:09 +0000602 ++NumSRA;
Chris Lattner004e2502004-10-11 05:54:41 +0000603
604 // Loop over the new globals array deleting any globals that are obviously
605 // dead. This can arise due to scalarization of a structure or an array that
606 // has elements that are dead.
607 unsigned FirstGlobal = 0;
608 for (unsigned i = 0, e = NewGlobals.size(); i != e; ++i)
609 if (NewGlobals[i]->use_empty()) {
610 Globals.erase(NewGlobals[i]);
611 if (FirstGlobal == i) ++FirstGlobal;
612 }
613
Craig Topperf40110f2014-04-25 05:29:35 +0000614 return FirstGlobal != NewGlobals.size() ? NewGlobals[FirstGlobal] : nullptr;
Chris Lattnerabab0712004-10-08 17:32:09 +0000615}
616
James Molloyea31ad32015-11-13 11:05:07 +0000617/// Return true if all users of the specified value will trap if the value is
618/// dynamically null. PHIs keeps track of any phi nodes we've seen to avoid
619/// reprocessing them.
Gabor Greif67972872010-04-06 19:24:18 +0000620static bool AllUsesOfValueWillTrapIfNull(const Value *V,
Craig Topper71b7b682014-08-21 05:55:13 +0000621 SmallPtrSetImpl<const PHINode*> &PHIs) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000622 for (const User *U : V->users())
Gabor Greif08355d62010-04-06 19:14:05 +0000623 if (isa<LoadInst>(U)) {
Chris Lattner09a52722004-10-09 21:48:45 +0000624 // Will trap.
Gabor Greif67972872010-04-06 19:24:18 +0000625 } else if (const StoreInst *SI = dyn_cast<StoreInst>(U)) {
Chris Lattner09a52722004-10-09 21:48:45 +0000626 if (SI->getOperand(0) == V) {
Gabor Greif08355d62010-04-06 19:14:05 +0000627 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner09a52722004-10-09 21:48:45 +0000628 return false; // Storing the value.
629 }
Gabor Greif67972872010-04-06 19:24:18 +0000630 } else if (const CallInst *CI = dyn_cast<CallInst>(U)) {
Gabor Greiffebf6ab2010-03-20 21:00:25 +0000631 if (CI->getCalledValue() != V) {
Gabor Greif08355d62010-04-06 19:14:05 +0000632 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner09a52722004-10-09 21:48:45 +0000633 return false; // Not calling the ptr
634 }
Gabor Greif67972872010-04-06 19:24:18 +0000635 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(U)) {
Gabor Greiffebf6ab2010-03-20 21:00:25 +0000636 if (II->getCalledValue() != V) {
Gabor Greif08355d62010-04-06 19:14:05 +0000637 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner09a52722004-10-09 21:48:45 +0000638 return false; // Not calling the ptr
639 }
Gabor Greif67972872010-04-06 19:24:18 +0000640 } else if (const BitCastInst *CI = dyn_cast<BitCastInst>(U)) {
Chris Lattner2d2892e2007-09-13 16:30:19 +0000641 if (!AllUsesOfValueWillTrapIfNull(CI, PHIs)) return false;
Gabor Greif67972872010-04-06 19:24:18 +0000642 } else if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
Chris Lattner2d2892e2007-09-13 16:30:19 +0000643 if (!AllUsesOfValueWillTrapIfNull(GEPI, PHIs)) return false;
Gabor Greif67972872010-04-06 19:24:18 +0000644 } else if (const PHINode *PN = dyn_cast<PHINode>(U)) {
Chris Lattner2d2892e2007-09-13 16:30:19 +0000645 // If we've already seen this phi node, ignore it, it has already been
646 // checked.
David Blaikie70573dc2014-11-19 07:49:26 +0000647 if (PHIs.insert(PN).second && !AllUsesOfValueWillTrapIfNull(PN, PHIs))
Jakob Stoklund Olesene27dc722010-01-29 23:54:14 +0000648 return false;
Gabor Greif08355d62010-04-06 19:14:05 +0000649 } else if (isa<ICmpInst>(U) &&
Chandler Carruthcdf47882014-03-09 03:16:01 +0000650 isa<ConstantPointerNull>(U->getOperand(1))) {
Nick Lewycky614fb942010-02-25 06:39:10 +0000651 // Ignore icmp X, null
Chris Lattner09a52722004-10-09 21:48:45 +0000652 } else {
Gabor Greif08355d62010-04-06 19:14:05 +0000653 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner09a52722004-10-09 21:48:45 +0000654 return false;
655 }
Chandler Carruthcdf47882014-03-09 03:16:01 +0000656
Chris Lattner09a52722004-10-09 21:48:45 +0000657 return true;
658}
659
James Molloyea31ad32015-11-13 11:05:07 +0000660/// Return true if all uses of any loads from GV will trap if the loaded value
661/// is null. Note that this also permits comparisons of the loaded value
662/// against null, as a special case.
Gabor Greif67972872010-04-06 19:24:18 +0000663static bool AllUsesOfLoadedValueWillTrapIfNull(const GlobalVariable *GV) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000664 for (const User *U : GV->users())
Gabor Greif67972872010-04-06 19:24:18 +0000665 if (const LoadInst *LI = dyn_cast<LoadInst>(U)) {
666 SmallPtrSet<const PHINode*, 8> PHIs;
Chris Lattner2d2892e2007-09-13 16:30:19 +0000667 if (!AllUsesOfValueWillTrapIfNull(LI, PHIs))
Chris Lattner09a52722004-10-09 21:48:45 +0000668 return false;
Gabor Greif08355d62010-04-06 19:14:05 +0000669 } else if (isa<StoreInst>(U)) {
Chris Lattner09a52722004-10-09 21:48:45 +0000670 // Ignore stores to the global.
671 } else {
672 // We don't know or understand this user, bail out.
Gabor Greif08355d62010-04-06 19:14:05 +0000673 //cerr << "UNKNOWN USER OF GLOBAL!: " << *U;
Chris Lattner09a52722004-10-09 21:48:45 +0000674 return false;
675 }
Chris Lattner09a52722004-10-09 21:48:45 +0000676 return true;
677}
678
Chris Lattner46b5c642009-11-06 04:27:31 +0000679static bool OptimizeAwayTrappingUsesOfValue(Value *V, Constant *NewV) {
Chris Lattnere42eb312004-10-10 23:14:11 +0000680 bool Changed = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000681 for (auto UI = V->user_begin(), E = V->user_end(); UI != E; ) {
Chris Lattnere42eb312004-10-10 23:14:11 +0000682 Instruction *I = cast<Instruction>(*UI++);
683 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
684 LI->setOperand(0, NewV);
685 Changed = true;
686 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
687 if (SI->getOperand(1) == V) {
688 SI->setOperand(1, NewV);
689 Changed = true;
690 }
691 } else if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
Gabor Greif04397892010-04-06 18:45:08 +0000692 CallSite CS(I);
693 if (CS.getCalledValue() == V) {
Chris Lattnere42eb312004-10-10 23:14:11 +0000694 // Calling through the pointer! Turn into a direct call, but be careful
695 // that the pointer is not also being passed as an argument.
Gabor Greif04397892010-04-06 18:45:08 +0000696 CS.setCalledFunction(NewV);
Chris Lattnere42eb312004-10-10 23:14:11 +0000697 Changed = true;
698 bool PassedAsArg = false;
Gabor Greif04397892010-04-06 18:45:08 +0000699 for (unsigned i = 0, e = CS.arg_size(); i != e; ++i)
700 if (CS.getArgument(i) == V) {
Chris Lattnere42eb312004-10-10 23:14:11 +0000701 PassedAsArg = true;
Gabor Greif04397892010-04-06 18:45:08 +0000702 CS.setArgument(i, NewV);
Chris Lattnere42eb312004-10-10 23:14:11 +0000703 }
704
705 if (PassedAsArg) {
706 // Being passed as an argument also. Be careful to not invalidate UI!
Chandler Carruthcdf47882014-03-09 03:16:01 +0000707 UI = V->user_begin();
Chris Lattnere42eb312004-10-10 23:14:11 +0000708 }
709 }
710 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
711 Changed |= OptimizeAwayTrappingUsesOfValue(CI,
Owen Anderson487375e2009-07-29 18:55:55 +0000712 ConstantExpr::getCast(CI->getOpcode(),
Chris Lattner46b5c642009-11-06 04:27:31 +0000713 NewV, CI->getType()));
Chris Lattnere42eb312004-10-10 23:14:11 +0000714 if (CI->use_empty()) {
715 Changed = true;
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000716 CI->eraseFromParent();
Chris Lattnere42eb312004-10-10 23:14:11 +0000717 }
718 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
719 // Should handle GEP here.
Chris Lattnerf96f4a82007-01-31 04:40:53 +0000720 SmallVector<Constant*, 8> Idxs;
721 Idxs.reserve(GEPI->getNumOperands()-1);
Gabor Greif3a9fba52008-05-29 01:59:18 +0000722 for (User::op_iterator i = GEPI->op_begin() + 1, e = GEPI->op_end();
723 i != e; ++i)
724 if (Constant *C = dyn_cast<Constant>(*i))
Chris Lattnerf96f4a82007-01-31 04:40:53 +0000725 Idxs.push_back(C);
Chris Lattnere42eb312004-10-10 23:14:11 +0000726 else
727 break;
Chris Lattnerf96f4a82007-01-31 04:40:53 +0000728 if (Idxs.size() == GEPI->getNumOperands()-1)
David Blaikie4a2e73b2015-04-02 18:55:32 +0000729 Changed |= OptimizeAwayTrappingUsesOfValue(
730 GEPI, ConstantExpr::getGetElementPtr(nullptr, NewV, Idxs));
Chris Lattnere42eb312004-10-10 23:14:11 +0000731 if (GEPI->use_empty()) {
732 Changed = true;
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000733 GEPI->eraseFromParent();
Chris Lattnere42eb312004-10-10 23:14:11 +0000734 }
735 }
736 }
737
738 return Changed;
739}
740
741
James Molloyea31ad32015-11-13 11:05:07 +0000742/// The specified global has only one non-null value stored into it. If there
743/// are uses of the loaded value that would trap if the loaded value is
744/// dynamically null, then we know that they cannot be reachable with a null
745/// optimize away the load.
Nick Lewyckycf6aae62012-02-12 01:13:18 +0000746static bool OptimizeAwayTrappingUsesOfLoads(GlobalVariable *GV, Constant *LV,
Mehdi Amini46a43552015-03-04 18:43:29 +0000747 const DataLayout &DL,
Nick Lewyckycf6aae62012-02-12 01:13:18 +0000748 TargetLibraryInfo *TLI) {
Chris Lattnere42eb312004-10-10 23:14:11 +0000749 bool Changed = false;
750
Chris Lattner2538eb62009-01-14 00:12:58 +0000751 // Keep track of whether we are able to remove all the uses of the global
752 // other than the store that defines it.
753 bool AllNonStoreUsesGone = true;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000754
Chris Lattnere42eb312004-10-10 23:14:11 +0000755 // Replace all uses of loads with uses of uses of the stored value.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000756 for (Value::user_iterator GUI = GV->user_begin(), E = GV->user_end(); GUI != E;){
Chris Lattner2538eb62009-01-14 00:12:58 +0000757 User *GlobalUser = *GUI++;
758 if (LoadInst *LI = dyn_cast<LoadInst>(GlobalUser)) {
Chris Lattner46b5c642009-11-06 04:27:31 +0000759 Changed |= OptimizeAwayTrappingUsesOfValue(LI, LV);
Chris Lattner2538eb62009-01-14 00:12:58 +0000760 // If we were able to delete all uses of the loads
761 if (LI->use_empty()) {
762 LI->eraseFromParent();
763 Changed = true;
764 } else {
765 AllNonStoreUsesGone = false;
766 }
767 } else if (isa<StoreInst>(GlobalUser)) {
768 // Ignore the store that stores "LV" to the global.
769 assert(GlobalUser->getOperand(1) == GV &&
770 "Must be storing *to* the global");
Chris Lattnere42eb312004-10-10 23:14:11 +0000771 } else {
Chris Lattner2538eb62009-01-14 00:12:58 +0000772 AllNonStoreUsesGone = false;
773
774 // If we get here we could have other crazy uses that are transitively
775 // loaded.
776 assert((isa<PHINode>(GlobalUser) || isa<SelectInst>(GlobalUser) ||
Benjamin Kramered843602012-09-28 10:01:27 +0000777 isa<ConstantExpr>(GlobalUser) || isa<CmpInst>(GlobalUser) ||
778 isa<BitCastInst>(GlobalUser) ||
779 isa<GetElementPtrInst>(GlobalUser)) &&
Chris Lattner1a1acc22011-05-22 07:15:13 +0000780 "Only expect load and stores!");
Chris Lattnere42eb312004-10-10 23:14:11 +0000781 }
Chris Lattner2538eb62009-01-14 00:12:58 +0000782 }
Chris Lattnere42eb312004-10-10 23:14:11 +0000783
784 if (Changed) {
James Molloyef607a22015-10-28 14:30:53 +0000785 DEBUG(dbgs() << "OPTIMIZED LOADS FROM STORED ONCE POINTER: " << *GV << "\n");
Chris Lattnere42eb312004-10-10 23:14:11 +0000786 ++NumGlobUses;
787 }
788
Chris Lattnere42eb312004-10-10 23:14:11 +0000789 // If we nuked all of the loads, then none of the stores are needed either,
790 // nor is the global.
Chris Lattner2538eb62009-01-14 00:12:58 +0000791 if (AllNonStoreUsesGone) {
Nick Lewyckyfaa9c3b02012-07-24 07:21:08 +0000792 if (isLeakCheckerRoot(GV)) {
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000793 Changed |= CleanupPointerRootUsers(GV, TLI);
Nick Lewyckyfaa9c3b02012-07-24 07:21:08 +0000794 } else {
795 Changed = true;
Craig Topperf40110f2014-04-25 05:29:35 +0000796 CleanupConstantGlobalUsers(GV, nullptr, DL, TLI);
Nick Lewyckyfaa9c3b02012-07-24 07:21:08 +0000797 }
Chris Lattnere42eb312004-10-10 23:14:11 +0000798 if (GV->use_empty()) {
Nick Lewyckyfaa9c3b02012-07-24 07:21:08 +0000799 DEBUG(dbgs() << " *** GLOBAL NOW DEAD!\n");
800 Changed = true;
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000801 GV->eraseFromParent();
Chris Lattnere42eb312004-10-10 23:14:11 +0000802 ++NumDeleted;
803 }
Chris Lattnere42eb312004-10-10 23:14:11 +0000804 }
805 return Changed;
806}
807
James Molloyea31ad32015-11-13 11:05:07 +0000808/// Walk the use list of V, constant folding all of the instructions that are
809/// foldable.
Mehdi Amini46a43552015-03-04 18:43:29 +0000810static void ConstantPropUsersOf(Value *V, const DataLayout &DL,
Rafael Espindolaaeff8a92014-02-24 23:12:18 +0000811 TargetLibraryInfo *TLI) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000812 for (Value::user_iterator UI = V->user_begin(), E = V->user_end(); UI != E; )
Chris Lattner004e2502004-10-11 05:54:41 +0000813 if (Instruction *I = dyn_cast<Instruction>(*UI++))
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000814 if (Constant *NewC = ConstantFoldInstruction(I, DL, TLI)) {
Chris Lattner004e2502004-10-11 05:54:41 +0000815 I->replaceAllUsesWith(NewC);
816
Chris Lattnerd6a44922005-02-01 01:23:31 +0000817 // Advance UI to the next non-I use to avoid invalidating it!
818 // Instructions could multiply use V.
819 while (UI != E && *UI == I)
Chris Lattner004e2502004-10-11 05:54:41 +0000820 ++UI;
Chris Lattnerd6a44922005-02-01 01:23:31 +0000821 I->eraseFromParent();
Chris Lattner004e2502004-10-11 05:54:41 +0000822 }
823}
824
James Molloyea31ad32015-11-13 11:05:07 +0000825/// This function takes the specified global variable, and transforms the
826/// program as if it always contained the result of the specified malloc.
827/// Because it is always the result of the specified malloc, there is no reason
828/// to actually DO the malloc. Instead, turn the malloc into a global, and any
829/// loads of GV as uses of the new global.
Mehdi Amini46a43552015-03-04 18:43:29 +0000830static GlobalVariable *
831OptimizeGlobalAddressOfMalloc(GlobalVariable *GV, CallInst *CI, Type *AllocTy,
832 ConstantInt *NElements, const DataLayout &DL,
833 TargetLibraryInfo *TLI) {
Chris Lattner7939f792010-02-25 22:33:52 +0000834 DEBUG(errs() << "PROMOTING GLOBAL: " << *GV << " CALL = " << *CI << '\n');
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000835
Chris Lattner229907c2011-07-18 04:54:35 +0000836 Type *GlobalType;
Chris Lattner7939f792010-02-25 22:33:52 +0000837 if (NElements->getZExtValue() == 1)
838 GlobalType = AllocTy;
839 else
840 // If we have an array allocation, the global variable is of an array.
841 GlobalType = ArrayType::get(AllocTy, NElements->getZExtValue());
Victor Hernandez5d034492009-09-18 22:35:49 +0000842
843 // Create the new global variable. The contents of the malloc'd memory is
844 // undefined, so initialize with an undef value.
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000845 GlobalVariable *NewGV = new GlobalVariable(*GV->getParent(),
Chris Lattner65d3a0a2010-02-26 23:42:13 +0000846 GlobalType, false,
Chris Lattner7939f792010-02-25 22:33:52 +0000847 GlobalValue::InternalLinkage,
Chris Lattner65d3a0a2010-02-26 23:42:13 +0000848 UndefValue::get(GlobalType),
Victor Hernandez5d034492009-09-18 22:35:49 +0000849 GV->getName()+".body",
850 GV,
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000851 GV->getThreadLocalMode());
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000852
Chris Lattner7939f792010-02-25 22:33:52 +0000853 // If there are bitcast users of the malloc (which is typical, usually we have
854 // a malloc + bitcast) then replace them with uses of the new global. Update
855 // other users to use the global as well.
Craig Topperf40110f2014-04-25 05:29:35 +0000856 BitCastInst *TheBC = nullptr;
Chris Lattner7939f792010-02-25 22:33:52 +0000857 while (!CI->use_empty()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000858 Instruction *User = cast<Instruction>(CI->user_back());
Chris Lattner7939f792010-02-25 22:33:52 +0000859 if (BitCastInst *BCI = dyn_cast<BitCastInst>(User)) {
860 if (BCI->getType() == NewGV->getType()) {
861 BCI->replaceAllUsesWith(NewGV);
862 BCI->eraseFromParent();
863 } else {
864 BCI->setOperand(0, NewGV);
865 }
866 } else {
Craig Topperf40110f2014-04-25 05:29:35 +0000867 if (!TheBC)
Chris Lattner7939f792010-02-25 22:33:52 +0000868 TheBC = new BitCastInst(NewGV, CI->getType(), "newgv", CI);
869 User->replaceUsesOfWith(CI, TheBC);
870 }
871 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000872
Victor Hernandez5d034492009-09-18 22:35:49 +0000873 Constant *RepValue = NewGV;
874 if (NewGV->getType() != GV->getType()->getElementType())
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000875 RepValue = ConstantExpr::getBitCast(RepValue,
Victor Hernandez5d034492009-09-18 22:35:49 +0000876 GV->getType()->getElementType());
877
878 // If there is a comparison against null, we will insert a global bool to
879 // keep track of whether the global was initialized yet or not.
880 GlobalVariable *InitBool =
Chris Lattner46b5c642009-11-06 04:27:31 +0000881 new GlobalVariable(Type::getInt1Ty(GV->getContext()), false,
Victor Hernandez5d034492009-09-18 22:35:49 +0000882 GlobalValue::InternalLinkage,
Chris Lattner46b5c642009-11-06 04:27:31 +0000883 ConstantInt::getFalse(GV->getContext()),
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000884 GV->getName()+".init", GV->getThreadLocalMode());
Victor Hernandez5d034492009-09-18 22:35:49 +0000885 bool InitBoolUsed = false;
886
887 // Loop over all uses of GV, processing them in turn.
Chris Lattner7939f792010-02-25 22:33:52 +0000888 while (!GV->use_empty()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000889 if (StoreInst *SI = dyn_cast<StoreInst>(GV->user_back())) {
Victor Hernandez5d034492009-09-18 22:35:49 +0000890 // The global is initialized when the store to it occurs.
Nick Lewycky52da72b2012-02-05 19:56:38 +0000891 new StoreInst(ConstantInt::getTrue(GV->getContext()), InitBool, false, 0,
892 SI->getOrdering(), SI->getSynchScope(), SI);
Victor Hernandez5d034492009-09-18 22:35:49 +0000893 SI->eraseFromParent();
Chris Lattner7939f792010-02-25 22:33:52 +0000894 continue;
Victor Hernandez5d034492009-09-18 22:35:49 +0000895 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000896
Chandler Carruthcdf47882014-03-09 03:16:01 +0000897 LoadInst *LI = cast<LoadInst>(GV->user_back());
Chris Lattner7939f792010-02-25 22:33:52 +0000898 while (!LI->use_empty()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000899 Use &LoadUse = *LI->use_begin();
900 ICmpInst *ICI = dyn_cast<ICmpInst>(LoadUse.getUser());
901 if (!ICI) {
Chris Lattner7939f792010-02-25 22:33:52 +0000902 LoadUse = RepValue;
903 continue;
904 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000905
Chris Lattner7939f792010-02-25 22:33:52 +0000906 // Replace the cmp X, 0 with a use of the bool value.
Nick Lewycky52da72b2012-02-05 19:56:38 +0000907 // Sink the load to where the compare was, if atomic rules allow us to.
908 Value *LV = new LoadInst(InitBool, InitBool->getName()+".val", false, 0,
909 LI->getOrdering(), LI->getSynchScope(),
910 LI->isUnordered() ? (Instruction*)ICI : LI);
Chris Lattner7939f792010-02-25 22:33:52 +0000911 InitBoolUsed = true;
912 switch (ICI->getPredicate()) {
913 default: llvm_unreachable("Unknown ICmp Predicate!");
914 case ICmpInst::ICMP_ULT:
915 case ICmpInst::ICMP_SLT: // X < null -> always false
916 LV = ConstantInt::getFalse(GV->getContext());
917 break;
918 case ICmpInst::ICMP_ULE:
919 case ICmpInst::ICMP_SLE:
920 case ICmpInst::ICMP_EQ:
921 LV = BinaryOperator::CreateNot(LV, "notinit", ICI);
922 break;
923 case ICmpInst::ICMP_NE:
924 case ICmpInst::ICMP_UGE:
925 case ICmpInst::ICMP_SGE:
926 case ICmpInst::ICMP_UGT:
927 case ICmpInst::ICMP_SGT:
928 break; // no change.
929 }
930 ICI->replaceAllUsesWith(LV);
931 ICI->eraseFromParent();
932 }
933 LI->eraseFromParent();
934 }
Victor Hernandez5d034492009-09-18 22:35:49 +0000935
936 // If the initialization boolean was used, insert it, otherwise delete it.
937 if (!InitBoolUsed) {
938 while (!InitBool->use_empty()) // Delete initializations
Chandler Carruthcdf47882014-03-09 03:16:01 +0000939 cast<StoreInst>(InitBool->user_back())->eraseFromParent();
Victor Hernandez5d034492009-09-18 22:35:49 +0000940 delete InitBool;
941 } else
Duncan P. N. Exon Smith17323402015-10-13 17:51:03 +0000942 GV->getParent()->getGlobalList().insert(GV->getIterator(), InitBool);
Victor Hernandez5d034492009-09-18 22:35:49 +0000943
Chris Lattner7939f792010-02-25 22:33:52 +0000944 // Now the GV is dead, nuke it and the malloc..
Victor Hernandez5d034492009-09-18 22:35:49 +0000945 GV->eraseFromParent();
Victor Hernandez5d034492009-09-18 22:35:49 +0000946 CI->eraseFromParent();
947
948 // To further other optimizations, loop over all users of NewGV and try to
949 // constant prop them. This will promote GEP instructions with constant
950 // indices into GEP constant-exprs, which will allow global-opt to hack on it.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000951 ConstantPropUsersOf(NewGV, DL, TLI);
Victor Hernandez5d034492009-09-18 22:35:49 +0000952 if (RepValue != NewGV)
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000953 ConstantPropUsersOf(RepValue, DL, TLI);
Victor Hernandez5d034492009-09-18 22:35:49 +0000954
955 return NewGV;
956}
957
James Molloyea31ad32015-11-13 11:05:07 +0000958/// Scan the use-list of V checking to make sure that there are no complex uses
959/// of V. We permit simple things like dereferencing the pointer, but not
960/// storing through the address, unless it is to the specified global.
Gabor Greifa21bc0f2010-04-06 18:58:22 +0000961static bool ValueIsOnlyUsedLocallyOrStoredToOneGlobal(const Instruction *V,
962 const GlobalVariable *GV,
Craig Topper71b7b682014-08-21 05:55:13 +0000963 SmallPtrSetImpl<const PHINode*> &PHIs) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000964 for (const User *U : V->users()) {
965 const Instruction *Inst = cast<Instruction>(U);
Gabor Greif08355d62010-04-06 19:14:05 +0000966
Chris Lattnerf0eb5682008-12-15 21:08:54 +0000967 if (isa<LoadInst>(Inst) || isa<CmpInst>(Inst)) {
968 continue; // Fine, ignore.
969 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000970
Gabor Greifa21bc0f2010-04-06 18:58:22 +0000971 if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
Chris Lattnerc0677c02004-12-02 07:11:07 +0000972 if (SI->getOperand(0) == V && SI->getOperand(1) != GV)
973 return false; // Storing the pointer itself... bad.
Chris Lattnerf0eb5682008-12-15 21:08:54 +0000974 continue; // Otherwise, storing through it, or storing into GV... fine.
975 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000976
Chris Lattnerb9801ff2010-04-10 18:19:22 +0000977 // Must index into the array and into the struct.
978 if (isa<GetElementPtrInst>(Inst) && Inst->getNumOperands() >= 3) {
Chris Lattnerf0eb5682008-12-15 21:08:54 +0000979 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(Inst, GV, PHIs))
Chris Lattnerc0677c02004-12-02 07:11:07 +0000980 return false;
Chris Lattnerf0eb5682008-12-15 21:08:54 +0000981 continue;
982 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000983
Gabor Greifa21bc0f2010-04-06 18:58:22 +0000984 if (const PHINode *PN = dyn_cast<PHINode>(Inst)) {
Chris Lattner6eed0e72007-09-13 16:37:20 +0000985 // PHIs are ok if all uses are ok. Don't infinitely recurse through PHI
986 // cycles.
David Blaikie70573dc2014-11-19 07:49:26 +0000987 if (PHIs.insert(PN).second)
Chris Lattner5d13fb532007-09-14 03:41:21 +0000988 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(PN, GV, PHIs))
989 return false;
Chris Lattnerf0eb5682008-12-15 21:08:54 +0000990 continue;
Chris Lattnerc0677c02004-12-02 07:11:07 +0000991 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000992
Gabor Greifa21bc0f2010-04-06 18:58:22 +0000993 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Inst)) {
Chris Lattnerf0eb5682008-12-15 21:08:54 +0000994 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(BCI, GV, PHIs))
995 return false;
996 continue;
997 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000998
Chris Lattnerf0eb5682008-12-15 21:08:54 +0000999 return false;
1000 }
Chris Lattnerc0677c02004-12-02 07:11:07 +00001001 return true;
Chris Lattnerc0677c02004-12-02 07:11:07 +00001002}
1003
James Molloyea31ad32015-11-13 11:05:07 +00001004/// The Alloc pointer is stored into GV somewhere. Transform all uses of the
1005/// allocation into loads from the global and uses of the resultant pointer.
1006/// Further, delete the store into GV. This assumes that these value pass the
Chris Lattner24d3d422006-09-30 23:32:09 +00001007/// 'ValueIsOnlyUsedLocallyOrStoredToOneGlobal' predicate.
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001008static void ReplaceUsesOfMallocWithGlobal(Instruction *Alloc,
Chris Lattner24d3d422006-09-30 23:32:09 +00001009 GlobalVariable *GV) {
1010 while (!Alloc->use_empty()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00001011 Instruction *U = cast<Instruction>(*Alloc->user_begin());
Chris Lattnerba98f892007-09-13 18:00:31 +00001012 Instruction *InsertPt = U;
Chris Lattner24d3d422006-09-30 23:32:09 +00001013 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
1014 // If this is the store of the allocation into the global, remove it.
1015 if (SI->getOperand(1) == GV) {
1016 SI->eraseFromParent();
1017 continue;
1018 }
Chris Lattnerba98f892007-09-13 18:00:31 +00001019 } else if (PHINode *PN = dyn_cast<PHINode>(U)) {
1020 // Insert the load in the corresponding predecessor, not right before the
1021 // PHI.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001022 InsertPt = PN->getIncomingBlock(*Alloc->use_begin())->getTerminator();
Chris Lattner49e3bdc2008-12-15 21:44:34 +00001023 } else if (isa<BitCastInst>(U)) {
1024 // Must be bitcast between the malloc and store to initialize the global.
1025 ReplaceUsesOfMallocWithGlobal(U, GV);
1026 U->eraseFromParent();
1027 continue;
1028 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
1029 // If this is a "GEP bitcast" and the user is a store to the global, then
1030 // just process it as a bitcast.
1031 if (GEPI->hasAllZeroIndices() && GEPI->hasOneUse())
Chandler Carruthcdf47882014-03-09 03:16:01 +00001032 if (StoreInst *SI = dyn_cast<StoreInst>(GEPI->user_back()))
Chris Lattner49e3bdc2008-12-15 21:44:34 +00001033 if (SI->getOperand(1) == GV) {
1034 // Must be bitcast GEP between the malloc and store to initialize
1035 // the global.
1036 ReplaceUsesOfMallocWithGlobal(GEPI, GV);
1037 GEPI->eraseFromParent();
1038 continue;
1039 }
Chris Lattner24d3d422006-09-30 23:32:09 +00001040 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001041
Chris Lattner24d3d422006-09-30 23:32:09 +00001042 // Insert a load from the global, and use it instead of the malloc.
Chris Lattnerba98f892007-09-13 18:00:31 +00001043 Value *NL = new LoadInst(GV, GV->getName()+".val", InsertPt);
Chris Lattner24d3d422006-09-30 23:32:09 +00001044 U->replaceUsesOfWith(Alloc, NL);
1045 }
1046}
1047
James Molloyea31ad32015-11-13 11:05:07 +00001048/// Verify that all uses of V (a load, or a phi of a load) are simple enough to
1049/// perform heap SRA on. This permits GEP's that index through the array and
1050/// struct field, icmps of null, and PHIs.
Gabor Greif5d5db532010-04-01 08:21:08 +00001051static bool LoadUsesSimpleEnoughForHeapSRA(const Value *V,
Craig Topper71b7b682014-08-21 05:55:13 +00001052 SmallPtrSetImpl<const PHINode*> &LoadUsingPHIs,
1053 SmallPtrSetImpl<const PHINode*> &LoadUsingPHIsPerLoad) {
Chris Lattner56b55382008-12-16 21:24:51 +00001054 // We permit two users of the load: setcc comparing against the null
1055 // pointer, and a getelementptr of a specific form.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001056 for (const User *U : V->users()) {
1057 const Instruction *UI = cast<Instruction>(U);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001058
Chris Lattner56b55382008-12-16 21:24:51 +00001059 // Comparison against null is ok.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001060 if (const ICmpInst *ICI = dyn_cast<ICmpInst>(UI)) {
Chris Lattner56b55382008-12-16 21:24:51 +00001061 if (!isa<ConstantPointerNull>(ICI->getOperand(1)))
1062 return false;
1063 continue;
1064 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001065
Chris Lattner56b55382008-12-16 21:24:51 +00001066 // getelementptr is also ok, but only a simple form.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001067 if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(UI)) {
Chris Lattner56b55382008-12-16 21:24:51 +00001068 // Must index into the array and into the struct.
1069 if (GEPI->getNumOperands() < 3)
1070 return false;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001071
Chris Lattner56b55382008-12-16 21:24:51 +00001072 // Otherwise the GEP is ok.
1073 continue;
1074 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001075
Chandler Carruthcdf47882014-03-09 03:16:01 +00001076 if (const PHINode *PN = dyn_cast<PHINode>(UI)) {
David Blaikie70573dc2014-11-19 07:49:26 +00001077 if (!LoadUsingPHIsPerLoad.insert(PN).second)
Evan Cheng83689442009-06-02 00:56:07 +00001078 // This means some phi nodes are dependent on each other.
1079 // Avoid infinite looping!
1080 return false;
David Blaikie70573dc2014-11-19 07:49:26 +00001081 if (!LoadUsingPHIs.insert(PN).second)
Evan Cheng83689442009-06-02 00:56:07 +00001082 // If we have already analyzed this PHI, then it is safe.
Chris Lattner56b55382008-12-16 21:24:51 +00001083 continue;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001084
Chris Lattner222ef4c2008-12-17 05:28:49 +00001085 // Make sure all uses of the PHI are simple enough to transform.
Evan Cheng83689442009-06-02 00:56:07 +00001086 if (!LoadUsesSimpleEnoughForHeapSRA(PN,
1087 LoadUsingPHIs, LoadUsingPHIsPerLoad))
Chris Lattner56b55382008-12-16 21:24:51 +00001088 return false;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001089
Chris Lattner56b55382008-12-16 21:24:51 +00001090 continue;
Chris Lattner24d3d422006-09-30 23:32:09 +00001091 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001092
Chris Lattner56b55382008-12-16 21:24:51 +00001093 // Otherwise we don't know what this is, not ok.
1094 return false;
1095 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001096
Chris Lattner56b55382008-12-16 21:24:51 +00001097 return true;
1098}
1099
1100
James Molloyea31ad32015-11-13 11:05:07 +00001101/// If all users of values loaded from GV are simple enough to perform HeapSRA,
1102/// return true.
Gabor Greif5d5db532010-04-01 08:21:08 +00001103static bool AllGlobalLoadUsesSimpleEnoughForHeapSRA(const GlobalVariable *GV,
Victor Hernandez5d034492009-09-18 22:35:49 +00001104 Instruction *StoredVal) {
Gabor Greif5d5db532010-04-01 08:21:08 +00001105 SmallPtrSet<const PHINode*, 32> LoadUsingPHIs;
1106 SmallPtrSet<const PHINode*, 32> LoadUsingPHIsPerLoad;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001107 for (const User *U : GV->users())
1108 if (const LoadInst *LI = dyn_cast<LoadInst>(U)) {
Evan Cheng83689442009-06-02 00:56:07 +00001109 if (!LoadUsesSimpleEnoughForHeapSRA(LI, LoadUsingPHIs,
1110 LoadUsingPHIsPerLoad))
Chris Lattner56b55382008-12-16 21:24:51 +00001111 return false;
Evan Cheng83689442009-06-02 00:56:07 +00001112 LoadUsingPHIsPerLoad.clear();
1113 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001114
Chris Lattner222ef4c2008-12-17 05:28:49 +00001115 // If we reach here, we know that all uses of the loads and transitive uses
1116 // (through PHI nodes) are simple enough to transform. However, we don't know
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001117 // that all inputs the to the PHI nodes are in the same equivalence sets.
Chris Lattner222ef4c2008-12-17 05:28:49 +00001118 // Check to verify that all operands of the PHIs are either PHIS that can be
1119 // transformed, loads from GV, or MI itself.
Craig Topper46276792014-08-24 23:23:06 +00001120 for (const PHINode *PN : LoadUsingPHIs) {
Chris Lattner222ef4c2008-12-17 05:28:49 +00001121 for (unsigned op = 0, e = PN->getNumIncomingValues(); op != e; ++op) {
1122 Value *InVal = PN->getIncomingValue(op);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001123
Chris Lattner222ef4c2008-12-17 05:28:49 +00001124 // PHI of the stored value itself is ok.
Victor Hernandez5d034492009-09-18 22:35:49 +00001125 if (InVal == StoredVal) continue;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001126
Gabor Greif5d5db532010-04-01 08:21:08 +00001127 if (const PHINode *InPN = dyn_cast<PHINode>(InVal)) {
Chris Lattner222ef4c2008-12-17 05:28:49 +00001128 // One of the PHIs in our set is (optimistically) ok.
1129 if (LoadUsingPHIs.count(InPN))
1130 continue;
1131 return false;
1132 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001133
Chris Lattner222ef4c2008-12-17 05:28:49 +00001134 // Load from GV is ok.
Gabor Greif5d5db532010-04-01 08:21:08 +00001135 if (const LoadInst *LI = dyn_cast<LoadInst>(InVal))
Chris Lattner222ef4c2008-12-17 05:28:49 +00001136 if (LI->getOperand(0) == GV)
1137 continue;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001138
Chris Lattner222ef4c2008-12-17 05:28:49 +00001139 // UNDEF? NULL?
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001140
Chris Lattner222ef4c2008-12-17 05:28:49 +00001141 // Anything else is rejected.
1142 return false;
1143 }
1144 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001145
Chris Lattner24d3d422006-09-30 23:32:09 +00001146 return true;
1147}
1148
Chris Lattner222ef4c2008-12-17 05:28:49 +00001149static Value *GetHeapSROAValue(Value *V, unsigned FieldNo,
1150 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Chris Lattner46b5c642009-11-06 04:27:31 +00001151 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
Chris Lattner222ef4c2008-12-17 05:28:49 +00001152 std::vector<Value*> &FieldVals = InsertedScalarizedValues[V];
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001153
Chris Lattner222ef4c2008-12-17 05:28:49 +00001154 if (FieldNo >= FieldVals.size())
1155 FieldVals.resize(FieldNo+1);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001156
Chris Lattner222ef4c2008-12-17 05:28:49 +00001157 // If we already have this value, just reuse the previously scalarized
1158 // version.
1159 if (Value *FieldVal = FieldVals[FieldNo])
1160 return FieldVal;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001161
Chris Lattner222ef4c2008-12-17 05:28:49 +00001162 // Depending on what instruction this is, we have several cases.
1163 Value *Result;
1164 if (LoadInst *LI = dyn_cast<LoadInst>(V)) {
1165 // This is a scalarized version of the load from the global. Just create
1166 // a new Load of the scalarized global.
1167 Result = new LoadInst(GetHeapSROAValue(LI->getOperand(0), FieldNo,
1168 InsertedScalarizedValues,
Chris Lattner46b5c642009-11-06 04:27:31 +00001169 PHIsToRewrite),
Daniel Dunbar132f7832009-07-30 17:37:43 +00001170 LI->getName()+".f"+Twine(FieldNo), LI);
David Blaikie741c8f82015-03-14 01:53:18 +00001171 } else {
1172 PHINode *PN = cast<PHINode>(V);
Chris Lattner222ef4c2008-12-17 05:28:49 +00001173 // PN's type is pointer to struct. Make a new PHI of pointer to struct
1174 // field.
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001175
Matt Arsenaultfcd74012014-04-23 20:36:10 +00001176 PointerType *PTy = cast<PointerType>(PN->getType());
1177 StructType *ST = cast<StructType>(PTy->getElementType());
1178
1179 unsigned AS = PTy->getAddressSpace();
Jay Foade0938d82011-03-30 11:19:20 +00001180 PHINode *NewPN =
Matt Arsenaultfcd74012014-04-23 20:36:10 +00001181 PHINode::Create(PointerType::get(ST->getElementType(FieldNo), AS),
Jay Foad52131342011-03-30 11:28:46 +00001182 PN->getNumIncomingValues(),
Daniel Dunbar132f7832009-07-30 17:37:43 +00001183 PN->getName()+".f"+Twine(FieldNo), PN);
Jay Foade0938d82011-03-30 11:19:20 +00001184 Result = NewPN;
Chris Lattner222ef4c2008-12-17 05:28:49 +00001185 PHIsToRewrite.push_back(std::make_pair(PN, FieldNo));
Chris Lattner222ef4c2008-12-17 05:28:49 +00001186 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001187
Chris Lattner222ef4c2008-12-17 05:28:49 +00001188 return FieldVals[FieldNo] = Result;
Chris Lattnerba98f892007-09-13 18:00:31 +00001189}
1190
James Molloyea31ad32015-11-13 11:05:07 +00001191/// Given a load instruction and a value derived from the load, rewrite the
1192/// derived value to use the HeapSRoA'd load.
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001193static void RewriteHeapSROALoadUser(Instruction *LoadUser,
Chris Lattner222ef4c2008-12-17 05:28:49 +00001194 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Chris Lattner46b5c642009-11-06 04:27:31 +00001195 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
Chris Lattnerf315d4f2007-09-13 17:29:05 +00001196 // If this is a comparison against null, handle it.
1197 if (ICmpInst *SCI = dyn_cast<ICmpInst>(LoadUser)) {
1198 assert(isa<ConstantPointerNull>(SCI->getOperand(1)));
1199 // If we have a setcc of the loaded pointer, we can use a setcc of any
1200 // field.
Chris Lattner222ef4c2008-12-17 05:28:49 +00001201 Value *NPtr = GetHeapSROAValue(SCI->getOperand(0), 0,
Chris Lattner46b5c642009-11-06 04:27:31 +00001202 InsertedScalarizedValues, PHIsToRewrite);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001203
Owen Anderson1e5f00e2009-07-09 23:48:35 +00001204 Value *New = new ICmpInst(SCI, SCI->getPredicate(), NPtr,
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001205 Constant::getNullValue(NPtr->getType()),
Owen Anderson1e5f00e2009-07-09 23:48:35 +00001206 SCI->getName());
Chris Lattnerf315d4f2007-09-13 17:29:05 +00001207 SCI->replaceAllUsesWith(New);
1208 SCI->eraseFromParent();
1209 return;
1210 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001211
Chris Lattner222ef4c2008-12-17 05:28:49 +00001212 // Handle 'getelementptr Ptr, Idx, i32 FieldNo ...'
Chris Lattnerba98f892007-09-13 18:00:31 +00001213 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(LoadUser)) {
1214 assert(GEPI->getNumOperands() >= 3 && isa<ConstantInt>(GEPI->getOperand(2))
1215 && "Unexpected GEPI!");
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001216
Chris Lattnerba98f892007-09-13 18:00:31 +00001217 // Load the pointer for this field.
1218 unsigned FieldNo = cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue();
Chris Lattner222ef4c2008-12-17 05:28:49 +00001219 Value *NewPtr = GetHeapSROAValue(GEPI->getOperand(0), FieldNo,
Chris Lattner46b5c642009-11-06 04:27:31 +00001220 InsertedScalarizedValues, PHIsToRewrite);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001221
Chris Lattnerba98f892007-09-13 18:00:31 +00001222 // Create the new GEP idx vector.
1223 SmallVector<Value*, 8> GEPIdx;
1224 GEPIdx.push_back(GEPI->getOperand(1));
1225 GEPIdx.append(GEPI->op_begin()+3, GEPI->op_end());
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001226
David Blaikie22319eb2015-03-14 19:24:04 +00001227 Value *NGEPI = GetElementPtrInst::Create(GEPI->getResultElementType(), NewPtr, GEPIdx,
Gabor Greife9ecc682008-04-06 20:25:17 +00001228 GEPI->getName(), GEPI);
Chris Lattnerba98f892007-09-13 18:00:31 +00001229 GEPI->replaceAllUsesWith(NGEPI);
1230 GEPI->eraseFromParent();
1231 return;
1232 }
Chris Lattner011f91b2007-09-13 21:31:36 +00001233
Chris Lattner222ef4c2008-12-17 05:28:49 +00001234 // Recursively transform the users of PHI nodes. This will lazily create the
1235 // PHIs that are needed for individual elements. Keep track of what PHIs we
1236 // see in InsertedScalarizedValues so that we don't get infinite loops (very
1237 // antisocial). If the PHI is already in InsertedScalarizedValues, it has
1238 // already been seen first by another load, so its uses have already been
1239 // processed.
1240 PHINode *PN = cast<PHINode>(LoadUser);
Chris Lattner5cf753c2011-07-21 06:21:31 +00001241 if (!InsertedScalarizedValues.insert(std::make_pair(PN,
1242 std::vector<Value*>())).second)
1243 return;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001244
Chris Lattner222ef4c2008-12-17 05:28:49 +00001245 // If this is the first time we've seen this PHI, recursively process all
1246 // users.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001247 for (auto UI = PN->user_begin(), E = PN->user_end(); UI != E;) {
Chris Lattner0cdf5232008-12-17 05:42:08 +00001248 Instruction *User = cast<Instruction>(*UI++);
Chris Lattner46b5c642009-11-06 04:27:31 +00001249 RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite);
Chris Lattner0cdf5232008-12-17 05:42:08 +00001250 }
Chris Lattnerf315d4f2007-09-13 17:29:05 +00001251}
1252
James Molloyea31ad32015-11-13 11:05:07 +00001253/// We are performing Heap SRoA on a global. Ptr is a value loaded from the
1254/// global. Eliminate all uses of Ptr, making them use FieldGlobals instead.
1255/// All uses of loaded values satisfy AllGlobalLoadUsesSimpleEnoughForHeapSRA.
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001256static void RewriteUsesOfLoadForHeapSRoA(LoadInst *Load,
Chris Lattner222ef4c2008-12-17 05:28:49 +00001257 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Chris Lattner46b5c642009-11-06 04:27:31 +00001258 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00001259 for (auto UI = Load->user_begin(), E = Load->user_end(); UI != E;) {
Chris Lattner0cdf5232008-12-17 05:42:08 +00001260 Instruction *User = cast<Instruction>(*UI++);
Chris Lattner46b5c642009-11-06 04:27:31 +00001261 RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite);
Chris Lattner0cdf5232008-12-17 05:42:08 +00001262 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001263
Chris Lattner222ef4c2008-12-17 05:28:49 +00001264 if (Load->use_empty()) {
1265 Load->eraseFromParent();
1266 InsertedScalarizedValues.erase(Load);
1267 }
Chris Lattner24d3d422006-09-30 23:32:09 +00001268}
1269
James Molloyea31ad32015-11-13 11:05:07 +00001270/// CI is an allocation of an array of structures. Break it up into multiple
1271/// allocations of arrays of the fields.
Victor Hernandezf3db9152009-11-07 00:16:28 +00001272static GlobalVariable *PerformHeapAllocSRoA(GlobalVariable *GV, CallInst *CI,
Mehdi Amini46a43552015-03-04 18:43:29 +00001273 Value *NElems, const DataLayout &DL,
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00001274 const TargetLibraryInfo *TLI) {
David Greene44cb8ad2010-01-05 01:28:05 +00001275 DEBUG(dbgs() << "SROA HEAP ALLOC: " << *GV << " MALLOC = " << *CI << '\n');
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00001276 Type *MAT = getMallocAllocatedType(CI, TLI);
Chris Lattner229907c2011-07-18 04:54:35 +00001277 StructType *STy = cast<StructType>(MAT);
Victor Hernandez5d034492009-09-18 22:35:49 +00001278
1279 // There is guaranteed to be at least one use of the malloc (storing
1280 // it into GV). If there are other uses, change them to be uses of
1281 // the global to simplify later code. This also deletes the store
1282 // into GV.
Victor Hernandezf3db9152009-11-07 00:16:28 +00001283 ReplaceUsesOfMallocWithGlobal(CI, GV);
1284
Victor Hernandez5d034492009-09-18 22:35:49 +00001285 // Okay, at this point, there are no users of the malloc. Insert N
1286 // new mallocs at the same place as CI, and N globals.
1287 std::vector<Value*> FieldGlobals;
1288 std::vector<Value*> FieldMallocs;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001289
Matt Arsenaultfcd74012014-04-23 20:36:10 +00001290 unsigned AS = GV->getType()->getPointerAddressSpace();
Victor Hernandez5d034492009-09-18 22:35:49 +00001291 for (unsigned FieldNo = 0, e = STy->getNumElements(); FieldNo != e;++FieldNo){
Chris Lattner229907c2011-07-18 04:54:35 +00001292 Type *FieldTy = STy->getElementType(FieldNo);
Matt Arsenaultfcd74012014-04-23 20:36:10 +00001293 PointerType *PFieldTy = PointerType::get(FieldTy, AS);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001294
Victor Hernandez5d034492009-09-18 22:35:49 +00001295 GlobalVariable *NGV =
1296 new GlobalVariable(*GV->getParent(),
1297 PFieldTy, false, GlobalValue::InternalLinkage,
1298 Constant::getNullValue(PFieldTy),
1299 GV->getName() + ".f" + Twine(FieldNo), GV,
Hans Wennborgcbe34b42012-06-23 11:37:03 +00001300 GV->getThreadLocalMode());
Victor Hernandez5d034492009-09-18 22:35:49 +00001301 FieldGlobals.push_back(NGV);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001302
Mehdi Amini46a43552015-03-04 18:43:29 +00001303 unsigned TypeSize = DL.getTypeAllocSize(FieldTy);
Chris Lattner229907c2011-07-18 04:54:35 +00001304 if (StructType *ST = dyn_cast<StructType>(FieldTy))
Mehdi Amini46a43552015-03-04 18:43:29 +00001305 TypeSize = DL.getStructLayout(ST)->getSizeInBytes();
1306 Type *IntPtrTy = DL.getIntPtrType(CI->getType());
Victor Hernandezf3db9152009-11-07 00:16:28 +00001307 Value *NMI = CallInst::CreateMalloc(CI, IntPtrTy, FieldTy,
1308 ConstantInt::get(IntPtrTy, TypeSize),
Craig Topperf40110f2014-04-25 05:29:35 +00001309 NElems, nullptr,
Victor Hernandezf3db9152009-11-07 00:16:28 +00001310 CI->getName() + ".f" + Twine(FieldNo));
Chris Lattner0521c092010-02-26 18:23:13 +00001311 FieldMallocs.push_back(NMI);
Victor Hernandezf3db9152009-11-07 00:16:28 +00001312 new StoreInst(NMI, NGV, CI);
Victor Hernandez5d034492009-09-18 22:35:49 +00001313 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001314
Victor Hernandez5d034492009-09-18 22:35:49 +00001315 // The tricky aspect of this transformation is handling the case when malloc
1316 // fails. In the original code, malloc failing would set the result pointer
1317 // of malloc to null. In this case, some mallocs could succeed and others
1318 // could fail. As such, we emit code that looks like this:
1319 // F0 = malloc(field0)
1320 // F1 = malloc(field1)
1321 // F2 = malloc(field2)
1322 // if (F0 == 0 || F1 == 0 || F2 == 0) {
1323 // if (F0) { free(F0); F0 = 0; }
1324 // if (F1) { free(F1); F1 = 0; }
1325 // if (F2) { free(F2); F2 = 0; }
1326 // }
Victor Hernandezfcc77b12009-11-10 08:32:25 +00001327 // The malloc can also fail if its argument is too large.
Gabor Greif218f5542010-06-24 14:42:01 +00001328 Constant *ConstantZero = ConstantInt::get(CI->getArgOperand(0)->getType(), 0);
1329 Value *RunningOr = new ICmpInst(CI, ICmpInst::ICMP_SLT, CI->getArgOperand(0),
Victor Hernandezfcc77b12009-11-10 08:32:25 +00001330 ConstantZero, "isneg");
Victor Hernandez5d034492009-09-18 22:35:49 +00001331 for (unsigned i = 0, e = FieldMallocs.size(); i != e; ++i) {
Victor Hernandezf3db9152009-11-07 00:16:28 +00001332 Value *Cond = new ICmpInst(CI, ICmpInst::ICMP_EQ, FieldMallocs[i],
1333 Constant::getNullValue(FieldMallocs[i]->getType()),
1334 "isnull");
Victor Hernandezfcc77b12009-11-10 08:32:25 +00001335 RunningOr = BinaryOperator::CreateOr(RunningOr, Cond, "tmp", CI);
Victor Hernandez5d034492009-09-18 22:35:49 +00001336 }
1337
1338 // Split the basic block at the old malloc.
Victor Hernandezf3db9152009-11-07 00:16:28 +00001339 BasicBlock *OrigBB = CI->getParent();
Duncan P. N. Exon Smith17323402015-10-13 17:51:03 +00001340 BasicBlock *ContBB =
1341 OrigBB->splitBasicBlock(CI->getIterator(), "malloc_cont");
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001342
Victor Hernandez5d034492009-09-18 22:35:49 +00001343 // Create the block to check the first condition. Put all these blocks at the
1344 // end of the function as they are unlikely to be executed.
Chris Lattner46b5c642009-11-06 04:27:31 +00001345 BasicBlock *NullPtrBlock = BasicBlock::Create(OrigBB->getContext(),
1346 "malloc_ret_null",
Victor Hernandez5d034492009-09-18 22:35:49 +00001347 OrigBB->getParent());
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001348
Victor Hernandez5d034492009-09-18 22:35:49 +00001349 // Remove the uncond branch from OrigBB to ContBB, turning it into a cond
1350 // branch on RunningOr.
1351 OrigBB->getTerminator()->eraseFromParent();
1352 BranchInst::Create(NullPtrBlock, ContBB, RunningOr, OrigBB);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001353
Victor Hernandez5d034492009-09-18 22:35:49 +00001354 // Within the NullPtrBlock, we need to emit a comparison and branch for each
1355 // pointer, because some may be null while others are not.
1356 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
1357 Value *GVVal = new LoadInst(FieldGlobals[i], "tmp", NullPtrBlock);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001358 Value *Cmp = new ICmpInst(*NullPtrBlock, ICmpInst::ICMP_NE, GVVal,
Benjamin Kramer547b6c52011-09-27 20:39:19 +00001359 Constant::getNullValue(GVVal->getType()));
Chris Lattner46b5c642009-11-06 04:27:31 +00001360 BasicBlock *FreeBlock = BasicBlock::Create(Cmp->getContext(), "free_it",
Victor Hernandez5d034492009-09-18 22:35:49 +00001361 OrigBB->getParent());
Chris Lattner46b5c642009-11-06 04:27:31 +00001362 BasicBlock *NextBlock = BasicBlock::Create(Cmp->getContext(), "next",
Victor Hernandez5d034492009-09-18 22:35:49 +00001363 OrigBB->getParent());
Victor Hernandeze2971492009-10-24 04:23:03 +00001364 Instruction *BI = BranchInst::Create(FreeBlock, NextBlock,
1365 Cmp, NullPtrBlock);
Victor Hernandez5d034492009-09-18 22:35:49 +00001366
1367 // Fill in FreeBlock.
Victor Hernandeze2971492009-10-24 04:23:03 +00001368 CallInst::CreateFree(GVVal, BI);
Victor Hernandez5d034492009-09-18 22:35:49 +00001369 new StoreInst(Constant::getNullValue(GVVal->getType()), FieldGlobals[i],
1370 FreeBlock);
1371 BranchInst::Create(NextBlock, FreeBlock);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001372
Victor Hernandez5d034492009-09-18 22:35:49 +00001373 NullPtrBlock = NextBlock;
1374 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001375
Victor Hernandez5d034492009-09-18 22:35:49 +00001376 BranchInst::Create(ContBB, NullPtrBlock);
Victor Hernandezf3db9152009-11-07 00:16:28 +00001377
1378 // CI is no longer needed, remove it.
Victor Hernandez5d034492009-09-18 22:35:49 +00001379 CI->eraseFromParent();
1380
James Molloyea31ad32015-11-13 11:05:07 +00001381 /// As we process loads, if we can't immediately update all uses of the load,
1382 /// keep track of what scalarized loads are inserted for a given load.
Victor Hernandez5d034492009-09-18 22:35:49 +00001383 DenseMap<Value*, std::vector<Value*> > InsertedScalarizedValues;
1384 InsertedScalarizedValues[GV] = FieldGlobals;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001385
Victor Hernandez5d034492009-09-18 22:35:49 +00001386 std::vector<std::pair<PHINode*, unsigned> > PHIsToRewrite;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001387
Victor Hernandez5d034492009-09-18 22:35:49 +00001388 // Okay, the malloc site is completely handled. All of the uses of GV are now
1389 // loads, and all uses of those loads are simple. Rewrite them to use loads
1390 // of the per-field globals instead.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001391 for (auto UI = GV->user_begin(), E = GV->user_end(); UI != E;) {
Victor Hernandez5d034492009-09-18 22:35:49 +00001392 Instruction *User = cast<Instruction>(*UI++);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001393
Victor Hernandez5d034492009-09-18 22:35:49 +00001394 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Chris Lattner46b5c642009-11-06 04:27:31 +00001395 RewriteUsesOfLoadForHeapSRoA(LI, InsertedScalarizedValues, PHIsToRewrite);
Victor Hernandez5d034492009-09-18 22:35:49 +00001396 continue;
1397 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001398
Victor Hernandez5d034492009-09-18 22:35:49 +00001399 // Must be a store of null.
1400 StoreInst *SI = cast<StoreInst>(User);
1401 assert(isa<ConstantPointerNull>(SI->getOperand(0)) &&
1402 "Unexpected heap-sra user!");
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001403
Victor Hernandez5d034492009-09-18 22:35:49 +00001404 // Insert a store of null into each global.
1405 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
Chris Lattner229907c2011-07-18 04:54:35 +00001406 PointerType *PT = cast<PointerType>(FieldGlobals[i]->getType());
Victor Hernandez5d034492009-09-18 22:35:49 +00001407 Constant *Null = Constant::getNullValue(PT->getElementType());
1408 new StoreInst(Null, FieldGlobals[i], SI);
1409 }
1410 // Erase the original store.
1411 SI->eraseFromParent();
1412 }
1413
1414 // While we have PHIs that are interesting to rewrite, do it.
1415 while (!PHIsToRewrite.empty()) {
1416 PHINode *PN = PHIsToRewrite.back().first;
1417 unsigned FieldNo = PHIsToRewrite.back().second;
1418 PHIsToRewrite.pop_back();
1419 PHINode *FieldPN = cast<PHINode>(InsertedScalarizedValues[PN][FieldNo]);
1420 assert(FieldPN->getNumIncomingValues() == 0 &&"Already processed this phi");
1421
1422 // Add all the incoming values. This can materialize more phis.
1423 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1424 Value *InVal = PN->getIncomingValue(i);
1425 InVal = GetHeapSROAValue(InVal, FieldNo, InsertedScalarizedValues,
Chris Lattner46b5c642009-11-06 04:27:31 +00001426 PHIsToRewrite);
Victor Hernandez5d034492009-09-18 22:35:49 +00001427 FieldPN->addIncoming(InVal, PN->getIncomingBlock(i));
1428 }
1429 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001430
Victor Hernandez5d034492009-09-18 22:35:49 +00001431 // Drop all inter-phi links and any loads that made it this far.
1432 for (DenseMap<Value*, std::vector<Value*> >::iterator
1433 I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
1434 I != E; ++I) {
1435 if (PHINode *PN = dyn_cast<PHINode>(I->first))
1436 PN->dropAllReferences();
1437 else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
1438 LI->dropAllReferences();
1439 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001440
Victor Hernandez5d034492009-09-18 22:35:49 +00001441 // Delete all the phis and loads now that inter-references are dead.
1442 for (DenseMap<Value*, std::vector<Value*> >::iterator
1443 I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
1444 I != E; ++I) {
1445 if (PHINode *PN = dyn_cast<PHINode>(I->first))
1446 PN->eraseFromParent();
1447 else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
1448 LI->eraseFromParent();
1449 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001450
Victor Hernandez5d034492009-09-18 22:35:49 +00001451 // The old global is now dead, remove it.
1452 GV->eraseFromParent();
1453
1454 ++NumHeapSRA;
1455 return cast<GlobalVariable>(FieldGlobals[0]);
1456}
1457
James Molloyea31ad32015-11-13 11:05:07 +00001458/// This function is called when we see a pointer global variable with a single
1459/// value stored it that is a malloc or 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) {
Duncan P. N. Exon Smith17323402015-10-13 17:51:03 +00001502 GVI = OptimizeGlobalAddressOfMalloc(GV, CI, AllocTy, NElements, DL, TLI)
1503 ->getIterator();
Evan Cheng21b588b2010-04-14 20:52:55 +00001504 return true;
Victor Hernandez5d034492009-09-18 22:35:49 +00001505 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001506
Evan Cheng21b588b2010-04-14 20:52:55 +00001507 // If the allocation is an array of structures, consider transforming this
1508 // into multiple malloc'd arrays, one for each field. This is basically
1509 // SRoA for malloc'd memory.
1510
Nick Lewycky52da72b2012-02-05 19:56:38 +00001511 if (Ordering != NotAtomic)
1512 return false;
1513
Evan Cheng21b588b2010-04-14 20:52:55 +00001514 // If this is an allocation of a fixed size array of structs, analyze as a
1515 // variable size array. malloc [100 x struct],1 -> malloc struct, 100
Gabor Greif218f5542010-06-24 14:42:01 +00001516 if (NElems == ConstantInt::get(CI->getArgOperand(0)->getType(), 1))
Chris Lattner229907c2011-07-18 04:54:35 +00001517 if (ArrayType *AT = dyn_cast<ArrayType>(AllocTy))
Evan Cheng21b588b2010-04-14 20:52:55 +00001518 AllocTy = AT->getElementType();
Gabor Greif218f5542010-06-24 14:42:01 +00001519
Chris Lattner229907c2011-07-18 04:54:35 +00001520 StructType *AllocSTy = dyn_cast<StructType>(AllocTy);
Evan Cheng21b588b2010-04-14 20:52:55 +00001521 if (!AllocSTy)
1522 return false;
1523
1524 // This the structure has an unreasonable number of fields, leave it
1525 // alone.
1526 if (AllocSTy->getNumElements() <= 16 && AllocSTy->getNumElements() != 0 &&
1527 AllGlobalLoadUsesSimpleEnoughForHeapSRA(GV, CI)) {
1528
1529 // If this is a fixed size array, transform the Malloc to be an alloc of
1530 // structs. malloc [100 x struct],1 -> malloc struct, 100
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00001531 if (ArrayType *AT = dyn_cast<ArrayType>(getMallocAllocatedType(CI, TLI))) {
Mehdi Amini46a43552015-03-04 18:43:29 +00001532 Type *IntPtrTy = DL.getIntPtrType(CI->getType());
1533 unsigned TypeSize = DL.getStructLayout(AllocSTy)->getSizeInBytes();
Evan Cheng21b588b2010-04-14 20:52:55 +00001534 Value *AllocSize = ConstantInt::get(IntPtrTy, TypeSize);
1535 Value *NumElements = ConstantInt::get(IntPtrTy, AT->getNumElements());
1536 Instruction *Malloc = CallInst::CreateMalloc(CI, IntPtrTy, AllocSTy,
1537 AllocSize, NumElements,
Craig Topperf40110f2014-04-25 05:29:35 +00001538 nullptr, CI->getName());
Evan Cheng21b588b2010-04-14 20:52:55 +00001539 Instruction *Cast = new BitCastInst(Malloc, CI->getType(), "tmp", CI);
1540 CI->replaceAllUsesWith(Cast);
1541 CI->eraseFromParent();
Nuno Lopes9792d682012-06-22 00:25:01 +00001542 if (BitCastInst *BCI = dyn_cast<BitCastInst>(Malloc))
1543 CI = cast<CallInst>(BCI->getOperand(0));
1544 else
Nuno Lopes0b60ebb2012-06-22 00:29:58 +00001545 CI = cast<CallInst>(Malloc);
Evan Cheng21b588b2010-04-14 20:52:55 +00001546 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001547
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001548 GVI = PerformHeapAllocSRoA(GV, CI, getMallocArraySize(CI, DL, TLI, true),
Duncan P. N. Exon Smith17323402015-10-13 17:51:03 +00001549 DL, TLI)
1550 ->getIterator();
Evan Cheng21b588b2010-04-14 20:52:55 +00001551 return true;
Victor Hernandez5d034492009-09-18 22:35:49 +00001552 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001553
Victor Hernandez5d034492009-09-18 22:35:49 +00001554 return false;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001555}
Victor Hernandez5d034492009-09-18 22:35:49 +00001556
Chris Lattner09a52722004-10-09 21:48:45 +00001557// OptimizeOnceStoredGlobal - Try to optimize globals based on the knowledge
1558// that only one value (besides its initializer) is ever stored to the global.
Chris Lattner004e2502004-10-11 05:54:41 +00001559static bool OptimizeOnceStoredGlobal(GlobalVariable *GV, Value *StoredOnceVal,
Nick Lewycky52da72b2012-02-05 19:56:38 +00001560 AtomicOrdering Ordering,
Chris Lattnerc2d3d312006-08-27 22:42:52 +00001561 Module::global_iterator &GVI,
Mehdi Amini46a43552015-03-04 18:43:29 +00001562 const DataLayout &DL,
Rafael Espindolaaeff8a92014-02-24 23:12:18 +00001563 TargetLibraryInfo *TLI) {
Chris Lattner1c731fa2008-12-15 21:20:32 +00001564 // Ignore no-op GEPs and bitcasts.
1565 StoredOnceVal = StoredOnceVal->stripPointerCasts();
Chris Lattner09a52722004-10-09 21:48:45 +00001566
Chris Lattnere42eb312004-10-10 23:14:11 +00001567 // If we are dealing with a pointer global that is initialized to null and
1568 // only has one (non-null) value stored into it, then we can optimize any
1569 // users of the loaded value (often calls and loads) that would trap if the
1570 // value was null.
Duncan Sands19d0b472010-02-16 11:11:14 +00001571 if (GV->getInitializer()->getType()->isPointerTy() &&
Chris Lattner09a52722004-10-09 21:48:45 +00001572 GV->getInitializer()->isNullValue()) {
Chris Lattnere42eb312004-10-10 23:14:11 +00001573 if (Constant *SOVC = dyn_cast<Constant>(StoredOnceVal)) {
1574 if (GV->getInitializer()->getType() != SOVC->getType())
Chris Lattner1a1acc22011-05-22 07:15:13 +00001575 SOVC = ConstantExpr::getBitCast(SOVC, GV->getInitializer()->getType());
Misha Brukmanb1c93172005-04-21 23:48:37 +00001576
Chris Lattnere42eb312004-10-10 23:14:11 +00001577 // Optimize away any trapping uses of the loaded value.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001578 if (OptimizeAwayTrappingUsesOfLoads(GV, SOVC, DL, TLI))
Chris Lattner604ed7a2004-10-10 17:07:12 +00001579 return true;
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00001580 } else if (CallInst *CI = extractMallocCall(StoredOnceVal, TLI)) {
1581 Type *MallocType = getMallocAllocatedType(CI, TLI);
Nick Lewyckycf6aae62012-02-12 01:13:18 +00001582 if (MallocType &&
1583 TryToOptimizeStoreOfMallocToGlobal(GV, CI, MallocType, Ordering, GVI,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001584 DL, TLI))
Victor Hernandezf3db9152009-11-07 00:16:28 +00001585 return true;
Chris Lattnere42eb312004-10-10 23:14:11 +00001586 }
Chris Lattner09a52722004-10-09 21:48:45 +00001587 }
Chris Lattner004e2502004-10-11 05:54:41 +00001588
Chris Lattner09a52722004-10-09 21:48:45 +00001589 return false;
1590}
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001591
James Molloyea31ad32015-11-13 11:05:07 +00001592/// At this point, we have learned that the only two values ever stored into GV
1593/// are its initializer and OtherVal. See if we can shrink the global into a
1594/// boolean and select between the two values whenever it is used. This exposes
1595/// the values to other scalar optimizations.
Lang Hames459b5dc2014-03-23 04:22:31 +00001596static bool TryToShrinkGlobalToBoolean(GlobalVariable *GV, Constant *OtherVal) {
Chris Lattner229907c2011-07-18 04:54:35 +00001597 Type *GVElType = GV->getType()->getElementType();
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001598
Lang Hames459b5dc2014-03-23 04:22:31 +00001599 // If GVElType is already i1, it is already shrunk. If the type of the GV is
1600 // an FP value, pointer or vector, don't do this optimization because a select
1601 // between them is very expensive and unlikely to lead to later
1602 // simplification. In these cases, we typically end up with "cond ? v1 : v2"
1603 // where v1 and v2 both require constant pool loads, a big loss.
Chris Lattner46b5c642009-11-06 04:27:31 +00001604 if (GVElType == Type::getInt1Ty(GV->getContext()) ||
Duncan Sands9dff9be2010-02-15 16:12:20 +00001605 GVElType->isFloatingPointTy() ||
Duncan Sands19d0b472010-02-16 11:11:14 +00001606 GVElType->isPointerTy() || GVElType->isVectorTy())
Chris Lattner20bbac32008-01-14 01:17:44 +00001607 return false;
Gabor Greifa75ed762010-07-12 14:13:15 +00001608
Chris Lattner20bbac32008-01-14 01:17:44 +00001609 // Walk the use list of the global seeing if all the uses are load or store.
1610 // If there is anything else, bail out.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001611 for (User *U : GV->users())
Gabor Greifa75ed762010-07-12 14:13:15 +00001612 if (!isa<LoadInst>(U) && !isa<StoreInst>(U))
Chris Lattner20bbac32008-01-14 01:17:44 +00001613 return false;
Gabor Greifa75ed762010-07-12 14:13:15 +00001614
James Molloyef607a22015-10-28 14:30:53 +00001615 DEBUG(dbgs() << " *** SHRINKING TO BOOL: " << *GV << "\n");
Lang Hames459b5dc2014-03-23 04:22:31 +00001616
1617 // Create the new global, initializing it to false.
1618 GlobalVariable *NewGV = new GlobalVariable(Type::getInt1Ty(GV->getContext()),
1619 false,
1620 GlobalValue::InternalLinkage,
1621 ConstantInt::getFalse(GV->getContext()),
1622 GV->getName()+".b",
1623 GV->getThreadLocalMode(),
1624 GV->getType()->getAddressSpace());
Duncan P. N. Exon Smith17323402015-10-13 17:51:03 +00001625 GV->getParent()->getGlobalList().insert(GV->getIterator(), NewGV);
Lang Hames459b5dc2014-03-23 04:22:31 +00001626
Chris Lattner40e4cec2004-12-12 05:53:50 +00001627 Constant *InitVal = GV->getInitializer();
Chris Lattner46b5c642009-11-06 04:27:31 +00001628 assert(InitVal->getType() != Type::getInt1Ty(GV->getContext()) &&
Lang Hames459b5dc2014-03-23 04:22:31 +00001629 "No reason to shrink to bool!");
Chris Lattner40e4cec2004-12-12 05:53:50 +00001630
Lang Hames459b5dc2014-03-23 04:22:31 +00001631 // If initialized to zero and storing one into the global, we can use a cast
1632 // instead of a select to synthesize the desired value.
1633 bool IsOneZero = false;
1634 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal))
1635 IsOneZero = InitVal->isNullValue() && CI->isOne();
Chris Lattner40e4cec2004-12-12 05:53:50 +00001636
Lang Hames459b5dc2014-03-23 04:22:31 +00001637 while (!GV->use_empty()) {
1638 Instruction *UI = cast<Instruction>(GV->user_back());
1639 if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
1640 // Change the store into a boolean store.
1641 bool StoringOther = SI->getOperand(0) == OtherVal;
1642 // Only do this if we weren't storing a loaded value.
1643 Value *StoreVal;
1644 if (StoringOther || SI->getOperand(0) == InitVal) {
1645 StoreVal = ConstantInt::get(Type::getInt1Ty(GV->getContext()),
1646 StoringOther);
Bill Wendling7297b862013-02-13 23:00:51 +00001647 } else {
Lang Hames459b5dc2014-03-23 04:22:31 +00001648 // Otherwise, we are storing a previously loaded copy. To do this,
1649 // change the copy from copying the original value to just copying the
1650 // bool.
1651 Instruction *StoredVal = cast<Instruction>(SI->getOperand(0));
1652
1653 // If we've already replaced the input, StoredVal will be a cast or
1654 // select instruction. If not, it will be a load of the original
1655 // global.
1656 if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
1657 assert(LI->getOperand(0) == GV && "Not a copy!");
1658 // Insert a new load, to preserve the saved value.
1659 StoreVal = new LoadInst(NewGV, LI->getName()+".b", false, 0,
1660 LI->getOrdering(), LI->getSynchScope(), LI);
1661 } else {
1662 assert((isa<CastInst>(StoredVal) || isa<SelectInst>(StoredVal)) &&
1663 "This is not a form that we understand!");
1664 StoreVal = StoredVal->getOperand(0);
1665 assert(isa<LoadInst>(StoreVal) && "Not a load of NewGV!");
1666 }
Chris Lattner745196a2004-12-12 19:34:41 +00001667 }
Lang Hames459b5dc2014-03-23 04:22:31 +00001668 new StoreInst(StoreVal, NewGV, false, 0,
1669 SI->getOrdering(), SI->getSynchScope(), SI);
1670 } else {
1671 // Change the load into a load of bool then a select.
1672 LoadInst *LI = cast<LoadInst>(UI);
1673 LoadInst *NLI = new LoadInst(NewGV, LI->getName()+".b", false, 0,
1674 LI->getOrdering(), LI->getSynchScope(), LI);
1675 Value *NSI;
1676 if (IsOneZero)
1677 NSI = new ZExtInst(NLI, LI->getType(), "", LI);
1678 else
1679 NSI = SelectInst::Create(NLI, OtherVal, InitVal, "", LI);
1680 NSI->takeName(LI);
1681 LI->replaceAllUsesWith(NSI);
Devang Patelfc507a12009-03-06 01:39:36 +00001682 }
Lang Hames459b5dc2014-03-23 04:22:31 +00001683 UI->eraseFromParent();
Chris Lattner40e4cec2004-12-12 05:53:50 +00001684 }
1685
Lang Hames459b5dc2014-03-23 04:22:31 +00001686 // Retain the name of the old global variable. People who are debugging their
1687 // programs may expect these variables to be named the same.
1688 NewGV->takeName(GV);
1689 GV->eraseFromParent();
Chris Lattner20bbac32008-01-14 01:17:44 +00001690 return true;
Chris Lattner40e4cec2004-12-12 05:53:50 +00001691}
1692
1693
James Molloyea31ad32015-11-13 11:05:07 +00001694/// Analyze the specified global variable and optimize it if possible. If we
1695/// make a change, return true.
Rafael Espindolafc355bc2011-01-19 16:32:21 +00001696bool GlobalOpt::ProcessGlobal(GlobalVariable *GV,
1697 Module::global_iterator &GVI) {
Rafael Espindolafc355bc2011-01-19 16:32:21 +00001698 // Do more involved optimizations if the global is internal.
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001699 GV->removeDeadConstantUsers();
1700
1701 if (GV->use_empty()) {
James Molloyef607a22015-10-28 14:30:53 +00001702 DEBUG(dbgs() << "GLOBAL DEAD: " << *GV << "\n");
Chris Lattner8e71c6a2004-10-16 18:09:00 +00001703 GV->eraseFromParent();
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001704 ++NumDeleted;
1705 return true;
1706 }
1707
Rafael Espindola1821c6c2012-06-15 18:00:24 +00001708 if (!GV->hasLocalLinkage())
1709 return false;
1710
Rafael Espindolafc355bc2011-01-19 16:32:21 +00001711 GlobalStatus GS;
1712
Rafael Espindola3d7fc252013-10-21 17:14:55 +00001713 if (GlobalStatus::analyzeGlobal(GV, GS))
Rafael Espindolaecd5b9a2011-01-18 04:36:06 +00001714 return false;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001715
Rafael Espindola045a78f2013-10-17 18:18:52 +00001716 if (!GS.IsCompared && !GV->hasUnnamedAddr()) {
Rafael Espindolafc355bc2011-01-19 16:32:21 +00001717 GV->setUnnamedAddr(true);
1718 NumUnnamed++;
1719 }
1720
1721 if (GV->isConstant() || !GV->hasInitializer())
1722 return false;
1723
Rafael Espindolad21ac192013-09-05 19:15:21 +00001724 return ProcessInternalGlobal(GV, GVI, GS);
Rafael Espindolafc355bc2011-01-19 16:32:21 +00001725}
1726
James Molloy9c7d4d82015-11-15 14:21:37 +00001727bool GlobalOpt::isPointerValueDeadOnEntryToFunction(const Function *F, GlobalValue *GV) {
1728 // Find all uses of GV. We expect them all to be in F, and if we can't
1729 // identify any of the uses we bail out.
1730 //
1731 // On each of these uses, identify if the memory that GV points to is
1732 // used/required/live at the start of the function. If it is not, for example
1733 // if the first thing the function does is store to the GV, the GV can
1734 // possibly be demoted.
1735 //
1736 // We don't do an exhaustive search for memory operations - simply look
1737 // through bitcasts as they're quite common and benign.
1738 const DataLayout &DL = GV->getParent()->getDataLayout();
1739 SmallVector<LoadInst *, 4> Loads;
1740 SmallVector<StoreInst *, 4> Stores;
1741 for (auto *U : GV->users()) {
1742 if (Operator::getOpcode(U) == Instruction::BitCast) {
1743 for (auto *UU : U->users()) {
1744 if (auto *LI = dyn_cast<LoadInst>(UU))
1745 Loads.push_back(LI);
1746 else if (auto *SI = dyn_cast<StoreInst>(UU))
1747 Stores.push_back(SI);
1748 else
1749 return false;
1750 }
1751 continue;
1752 }
1753
1754 Instruction *I = dyn_cast<Instruction>(U);
1755 if (!I)
1756 return false;
1757 assert(I->getParent()->getParent() == F);
1758
1759 if (auto *LI = dyn_cast<LoadInst>(I))
1760 Loads.push_back(LI);
1761 else if (auto *SI = dyn_cast<StoreInst>(I))
1762 Stores.push_back(SI);
1763 else
1764 return false;
1765 }
1766
1767 // We have identified all uses of GV into loads and stores. Now check if all
1768 // of them are known not to depend on the value of the global at the function
1769 // entry point. We do this by ensuring that every load is dominated by at
1770 // least one store.
1771 auto &DT = getAnalysis<DominatorTreeWrapperPass>(*const_cast<Function *>(F))
1772 .getDomTree();
1773
James Molloyd4d23572015-11-16 10:16:22 +00001774 // The below check is quadratic. Check we're not going to do too many tests.
1775 // FIXME: Even though this will always have worst-case quadratic time, we
1776 // could put effort into minimizing the average time by putting stores that
1777 // have been shown to dominate at least one load at the beginning of the
1778 // Stores array, making subsequent dominance checks more likely to succeed
1779 // early.
1780 //
1781 // The threshold here is fairly large because global->local demotion is a
1782 // very powerful optimization should it fire.
1783 const unsigned Threshold = 100;
1784 if (Loads.size() * Stores.size() > Threshold)
1785 return false;
1786
James Molloy9c7d4d82015-11-15 14:21:37 +00001787 for (auto *L : Loads) {
1788 auto *LTy = L->getType();
1789 if (!std::any_of(Stores.begin(), Stores.end(), [&](StoreInst *S) {
1790 auto *STy = S->getValueOperand()->getType();
1791 // The load is only dominated by the store if DomTree says so
1792 // and the number of bits loaded in L is less than or equal to
1793 // the number of bits stored in S.
1794 return DT.dominates(S, L) &&
1795 DL.getTypeStoreSize(LTy) <= DL.getTypeStoreSize(STy);
1796 }))
1797 return false;
1798 }
1799 // All loads have known dependences inside F, so the global can be localized.
1800 return true;
1801}
1802
James Molloy1d695a02015-11-19 18:04:33 +00001803/// C may have non-instruction users. Can all of those users be turned into
1804/// instructions?
1805static bool allNonInstructionUsersCanBeMadeInstructions(Constant *C) {
1806 // We don't do this exhaustively. The most common pattern that we really need
1807 // to care about is a constant GEP or constant bitcast - so just looking
1808 // through one single ConstantExpr.
1809 //
1810 // The set of constants that this function returns true for must be able to be
1811 // handled by makeAllConstantUsesInstructions.
1812 for (auto *U : C->users()) {
1813 if (isa<Instruction>(U))
1814 continue;
1815 if (!isa<ConstantExpr>(U))
1816 // Non instruction, non-constantexpr user; cannot convert this.
1817 return false;
1818 for (auto *UU : U->users())
1819 if (!isa<Instruction>(UU))
1820 // A constantexpr used by another constant. We don't try and recurse any
1821 // further but just bail out at this point.
1822 return false;
1823 }
1824
1825 return true;
1826}
1827
1828/// C may have non-instruction users, and
1829/// allNonInstructionUsersCanBeMadeInstructions has returned true. Convert the
1830/// non-instruction users to instructions.
1831static void makeAllConstantUsesInstructions(Constant *C) {
1832 SmallVector<ConstantExpr*,4> Users;
1833 for (auto *U : C->users()) {
1834 if (isa<ConstantExpr>(U))
1835 Users.push_back(cast<ConstantExpr>(U));
1836 else
1837 // We should never get here; allNonInstructionUsersCanBeMadeInstructions
1838 // should not have returned true for C.
1839 assert(
1840 isa<Instruction>(U) &&
1841 "Can't transform non-constantexpr non-instruction to instruction!");
1842 }
1843
1844 SmallVector<Value*,4> UUsers;
1845 for (auto *U : Users) {
1846 UUsers.clear();
1847 for (auto *UU : U->users())
1848 UUsers.push_back(UU);
1849 for (auto *UU : UUsers) {
1850 Instruction *UI = cast<Instruction>(UU);
1851 Instruction *NewU = U->getAsInstruction();
1852 NewU->insertBefore(UI);
1853 UI->replaceUsesOfWith(U, NewU);
1854 }
1855 U->dropAllReferences();
1856 }
1857}
1858
James Molloyea31ad32015-11-13 11:05:07 +00001859/// Analyze the specified global variable and optimize
Rafael Espindolafc355bc2011-01-19 16:32:21 +00001860/// it if possible. If we make a change, return true.
1861bool GlobalOpt::ProcessInternalGlobal(GlobalVariable *GV,
1862 Module::global_iterator &GVI,
Rafael Espindolafc355bc2011-01-19 16:32:21 +00001863 const GlobalStatus &GS) {
Mehdi Amini46a43552015-03-04 18:43:29 +00001864 auto &DL = GV->getParent()->getDataLayout();
James Molloy9c7d4d82015-11-15 14:21:37 +00001865 // If this is a first class global and has only one accessing function and
1866 // this function is non-recursive, we replace the global with a local alloca
1867 // in this function.
Alexey Samsonova1944e62013-10-07 19:03:24 +00001868 //
Alp Tokerf907b892013-12-05 05:44:44 +00001869 // NOTE: It doesn't make sense to promote non-single-value types since we
Alexey Samsonova1944e62013-10-07 19:03:24 +00001870 // are just replacing static memory to stack memory.
1871 //
1872 // If the global is in different address space, don't bring it to stack.
1873 if (!GS.HasMultipleAccessingFunctions &&
James Molloy1d695a02015-11-19 18:04:33 +00001874 GS.AccessingFunction &&
Alexey Samsonova1944e62013-10-07 19:03:24 +00001875 GV->getType()->getElementType()->isSingleValueType() &&
James Molloy9c7d4d82015-11-15 14:21:37 +00001876 GV->getType()->getAddressSpace() == 0 &&
1877 !GV->isExternallyInitialized() &&
James Molloy1d695a02015-11-19 18:04:33 +00001878 allNonInstructionUsersCanBeMadeInstructions(GV) &&
James Molloy9c7d4d82015-11-15 14:21:37 +00001879 GS.AccessingFunction->doesNotRecurse() &&
1880 isPointerValueDeadOnEntryToFunction(GS.AccessingFunction, GV) ) {
James Molloy33e73452015-11-13 11:05:13 +00001881 DEBUG(dbgs() << "LOCALIZING GLOBAL: " << *GV << "\n");
Alexey Samsonova1944e62013-10-07 19:03:24 +00001882 Instruction &FirstI = const_cast<Instruction&>(*GS.AccessingFunction
1883 ->getEntryBlock().begin());
1884 Type *ElemTy = GV->getType()->getElementType();
1885 // FIXME: Pass Global's alignment when globals have alignment
Craig Topperf40110f2014-04-25 05:29:35 +00001886 AllocaInst *Alloca = new AllocaInst(ElemTy, nullptr,
1887 GV->getName(), &FirstI);
Alexey Samsonova1944e62013-10-07 19:03:24 +00001888 if (!isa<UndefValue>(GV->getInitializer()))
1889 new StoreInst(GV->getInitializer(), Alloca, &FirstI);
1890
James Molloy1d695a02015-11-19 18:04:33 +00001891 makeAllConstantUsesInstructions(GV);
1892
Alexey Samsonova1944e62013-10-07 19:03:24 +00001893 GV->replaceAllUsesWith(Alloca);
1894 GV->eraseFromParent();
1895 ++NumLocalized;
1896 return true;
1897 }
1898
Rafael Espindolaecd5b9a2011-01-18 04:36:06 +00001899 // If the global is never loaded (but may be stored to), it is dead.
1900 // Delete it now.
Rafael Espindola045a78f2013-10-17 18:18:52 +00001901 if (!GS.IsLoaded) {
James Molloy33e73452015-11-13 11:05:13 +00001902 DEBUG(dbgs() << "GLOBAL NEVER LOADED: " << *GV << "\n");
Rafael Espindolaecd5b9a2011-01-18 04:36:06 +00001903
Nick Lewyckyfaa9c3b02012-07-24 07:21:08 +00001904 bool Changed;
1905 if (isLeakCheckerRoot(GV)) {
1906 // Delete any constant stores to the global.
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00001907 Changed = CleanupPointerRootUsers(GV, TLI);
Nick Lewyckyfaa9c3b02012-07-24 07:21:08 +00001908 } else {
1909 // Delete any stores we can find to the global. We may not be able to
1910 // make it completely dead though.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001911 Changed = CleanupConstantGlobalUsers(GV, GV->getInitializer(), DL, TLI);
Nick Lewyckyfaa9c3b02012-07-24 07:21:08 +00001912 }
Rafael Espindolaecd5b9a2011-01-18 04:36:06 +00001913
1914 // If the global is dead now, delete it.
1915 if (GV->use_empty()) {
1916 GV->eraseFromParent();
1917 ++NumDeleted;
1918 Changed = true;
1919 }
1920 return Changed;
1921
Rafael Espindola045a78f2013-10-17 18:18:52 +00001922 } else if (GS.StoredType <= GlobalStatus::InitializerStored) {
Michael Gottesmand1a46f22013-01-11 20:07:53 +00001923 DEBUG(dbgs() << "MARKING CONSTANT: " << *GV << "\n");
Rafael Espindolaecd5b9a2011-01-18 04:36:06 +00001924 GV->setConstant(true);
1925
1926 // Clean up any obviously simplifiable users now.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001927 CleanupConstantGlobalUsers(GV, GV->getInitializer(), DL, TLI);
Rafael Espindolaecd5b9a2011-01-18 04:36:06 +00001928
1929 // If the global is dead now, just nuke it.
1930 if (GV->use_empty()) {
1931 DEBUG(dbgs() << " *** Marking constant allowed us to simplify "
1932 << "all users and delete global!\n");
1933 GV->eraseFromParent();
1934 ++NumDeleted;
1935 }
1936
1937 ++NumMarked;
1938 return true;
1939 } else if (!GV->getInitializer()->getType()->isSingleValueType()) {
Mehdi Amini46a43552015-03-04 18:43:29 +00001940 const DataLayout &DL = GV->getParent()->getDataLayout();
1941 if (GlobalVariable *FirstNewGV = SRAGlobal(GV, DL)) {
Duncan P. N. Exon Smith17323402015-10-13 17:51:03 +00001942 GVI = FirstNewGV->getIterator(); // Don't skip the newly produced globals!
Mehdi Amini46a43552015-03-04 18:43:29 +00001943 return true;
Rafael Espindola93512512014-02-25 17:30:31 +00001944 }
Oliver Stannard939724c2015-10-12 13:20:52 +00001945 } else if (GS.StoredType == GlobalStatus::StoredOnce && GS.StoredOnceValue) {
Rafael Espindolaecd5b9a2011-01-18 04:36:06 +00001946 // If the initial value for the global was an undef value, and if only
1947 // one other value was stored into it, we can just change the
1948 // initializer to be the stored value, then delete all stores to the
1949 // global. This allows us to mark it constant.
1950 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
1951 if (isa<UndefValue>(GV->getInitializer())) {
1952 // Change the initial value here.
1953 GV->setInitializer(SOVConstant);
1954
1955 // Clean up any obviously simplifiable users now.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001956 CleanupConstantGlobalUsers(GV, GV->getInitializer(), DL, TLI);
Rafael Espindolaecd5b9a2011-01-18 04:36:06 +00001957
1958 if (GV->use_empty()) {
1959 DEBUG(dbgs() << " *** Substituting initializer allowed us to "
Nick Lewyckyfaa9c3b02012-07-24 07:21:08 +00001960 << "simplify all users and delete global!\n");
Rafael Espindolaecd5b9a2011-01-18 04:36:06 +00001961 GV->eraseFromParent();
1962 ++NumDeleted;
1963 } else {
Duncan P. N. Exon Smith17323402015-10-13 17:51:03 +00001964 GVI = GV->getIterator();
Rafael Espindolaecd5b9a2011-01-18 04:36:06 +00001965 }
1966 ++NumSubstitute;
1967 return true;
1968 }
1969
1970 // Try to optimize globals based on the knowledge that only one value
1971 // (besides its initializer) is ever stored to the global.
Nick Lewycky52da72b2012-02-05 19:56:38 +00001972 if (OptimizeOnceStoredGlobal(GV, GS.StoredOnceValue, GS.Ordering, GVI,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001973 DL, TLI))
Rafael Espindolaecd5b9a2011-01-18 04:36:06 +00001974 return true;
1975
Lang Hames459b5dc2014-03-23 04:22:31 +00001976 // Otherwise, if the global was not a boolean, we can shrink it to be a
1977 // boolean.
Eli Friedman33d37002013-09-09 22:00:13 +00001978 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue)) {
1979 if (GS.Ordering == NotAtomic) {
Lang Hames459b5dc2014-03-23 04:22:31 +00001980 if (TryToShrinkGlobalToBoolean(GV, SOVConstant)) {
Eli Friedman33d37002013-09-09 22:00:13 +00001981 ++NumShrunkToBool;
1982 return true;
1983 }
Rafael Espindolaecd5b9a2011-01-18 04:36:06 +00001984 }
Eli Friedman33d37002013-09-09 22:00:13 +00001985 }
Rafael Espindolaecd5b9a2011-01-18 04:36:06 +00001986 }
1987
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001988 return false;
1989}
1990
James Molloyea31ad32015-11-13 11:05:07 +00001991/// Walk all of the direct calls of the specified function, changing them to
1992/// FastCC.
Chris Lattnera4c80222005-05-08 22:18:06 +00001993static void ChangeCalleesToFastCall(Function *F) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00001994 for (User *U : F->users()) {
1995 if (isa<BlockAddress>(U))
Jay Foadca0c4992012-05-12 08:30:16 +00001996 continue;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001997 CallSite CS(cast<Instruction>(U));
1998 CS.setCallingConv(CallingConv::Fast);
Chris Lattnera4c80222005-05-08 22:18:06 +00001999 }
2000}
Chris Lattner1c4bddc2004-10-08 20:59:28 +00002001
Bill Wendlinge94d8432012-12-07 23:16:57 +00002002static AttributeSet StripNest(LLVMContext &C, const AttributeSet &Attrs) {
Chris Lattner8a923e72008-03-12 17:45:29 +00002003 for (unsigned i = 0, e = Attrs.getNumSlots(); i != e; ++i) {
Bill Wendling57625a42013-01-25 23:09:36 +00002004 unsigned Index = Attrs.getSlotIndex(i);
2005 if (!Attrs.getSlotAttributes(i).hasAttribute(Index, Attribute::Nest))
Duncan Sands85fab3a2008-02-18 17:32:13 +00002006 continue;
2007
Duncan Sands85fab3a2008-02-18 17:32:13 +00002008 // There can be only one.
Bill Wendling57625a42013-01-25 23:09:36 +00002009 return Attrs.removeAttribute(C, Index, Attribute::Nest);
Duncan Sands573b3f82008-02-16 20:56:04 +00002010 }
2011
2012 return Attrs;
2013}
2014
2015static void RemoveNestAttribute(Function *F) {
Bill Wendling85a64c22012-10-14 06:39:53 +00002016 F->setAttributes(StripNest(F->getContext(), F->getAttributes()));
Chandler Carruthcdf47882014-03-09 03:16:01 +00002017 for (User *U : F->users()) {
2018 if (isa<BlockAddress>(U))
Jay Foadca0c4992012-05-12 08:30:16 +00002019 continue;
Chandler Carruthcdf47882014-03-09 03:16:01 +00002020 CallSite CS(cast<Instruction>(U));
2021 CS.setAttributes(StripNest(F->getContext(), CS.getAttributes()));
Duncan Sands573b3f82008-02-16 20:56:04 +00002022 }
2023}
2024
Reid Kleckner22869372014-02-26 19:57:30 +00002025/// Return true if this is a calling convention that we'd like to change. The
2026/// idea here is that we don't want to mess with the convention if the user
2027/// explicitly requested something with performance implications like coldcc,
2028/// GHC, or anyregcc.
2029static bool isProfitableToMakeFastCC(Function *F) {
2030 CallingConv::ID CC = F->getCallingConv();
2031 // FIXME: Is it worth transforming x86_stdcallcc and x86_fastcallcc?
2032 return CC == CallingConv::C || CC == CallingConv::X86_ThisCall;
2033}
2034
Chris Lattner41b6a5a2005-09-26 01:43:45 +00002035bool GlobalOpt::OptimizeFunctions(Module &M) {
2036 bool Changed = false;
2037 // Optimize functions.
2038 for (Module::iterator FI = M.begin(), E = M.end(); FI != E; ) {
Duncan P. N. Exon Smith17323402015-10-13 17:51:03 +00002039 Function *F = &*FI++;
Duncan Sandsed722832009-03-06 10:21:56 +00002040 // Functions without names cannot be referenced outside this module.
David Majnemer5c921152014-07-01 15:26:50 +00002041 if (!F->hasName() && !F->isDeclaration() && !F->hasLocalLinkage())
Duncan Sandsed722832009-03-06 10:21:56 +00002042 F->setLinkage(GlobalValue::InternalLinkage);
David Majnemer1b3b70e2014-10-08 07:23:31 +00002043
2044 const Comdat *C = F->getComdat();
2045 bool inComdat = C && NotDiscardableComdats.count(C);
Chris Lattner41b6a5a2005-09-26 01:43:45 +00002046 F->removeDeadConstantUsers();
David Majnemer1b3b70e2014-10-08 07:23:31 +00002047 if ((!inComdat || F->hasLocalLinkage()) && F->isDefTriviallyDead()) {
Chris Lattnerb5d9c8c2009-11-01 19:03:42 +00002048 F->eraseFromParent();
Chris Lattner41b6a5a2005-09-26 01:43:45 +00002049 Changed = true;
2050 ++NumFnDeleted;
Rafael Espindola6de96a12009-01-15 20:18:42 +00002051 } else if (F->hasLocalLinkage()) {
Reid Klecknere6ff5c52014-02-28 22:50:08 +00002052 if (isProfitableToMakeFastCC(F) && !F->isVarArg() &&
2053 !F->hasAddressTaken()) {
Reid Kleckner22869372014-02-26 19:57:30 +00002054 // If this function has a calling convention worth changing, is not a
2055 // varargs function, and is only called directly, promote it to use the
2056 // Fast calling convention.
Duncan Sands573b3f82008-02-16 20:56:04 +00002057 F->setCallingConv(CallingConv::Fast);
2058 ChangeCalleesToFastCall(F);
2059 ++NumFastCallFns;
2060 Changed = true;
2061 }
2062
Bill Wendling3d7b0b82012-12-19 07:18:57 +00002063 if (F->getAttributes().hasAttrSomewhere(Attribute::Nest) &&
Jay Foad557169d2009-06-10 08:41:11 +00002064 !F->hasAddressTaken()) {
Duncan Sands573b3f82008-02-16 20:56:04 +00002065 // The function is not used by a trampoline intrinsic, so it is safe
2066 // to remove the 'nest' attribute.
2067 RemoveNestAttribute(F);
2068 ++NumNestRemoved;
2069 Changed = true;
2070 }
Chris Lattner41b6a5a2005-09-26 01:43:45 +00002071 }
2072 }
2073 return Changed;
2074}
2075
2076bool GlobalOpt::OptimizeGlobalVars(Module &M) {
2077 bool Changed = false;
David Majnemerdad0a642014-06-27 18:19:56 +00002078
Chris Lattner41b6a5a2005-09-26 01:43:45 +00002079 for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
2080 GVI != E; ) {
Duncan P. N. Exon Smith17323402015-10-13 17:51:03 +00002081 GlobalVariable *GV = &*GVI++;
Duncan Sandsed722832009-03-06 10:21:56 +00002082 // Global variables without names cannot be referenced outside this module.
David Majnemer5c921152014-07-01 15:26:50 +00002083 if (!GV->hasName() && !GV->isDeclaration() && !GV->hasLocalLinkage())
Duncan Sandsed722832009-03-06 10:21:56 +00002084 GV->setLinkage(GlobalValue::InternalLinkage);
Dan Gohman580b80d2009-11-23 16:22:21 +00002085 // Simplify the initializer.
2086 if (GV->hasInitializer())
2087 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GV->getInitializer())) {
Mehdi Amini46a43552015-03-04 18:43:29 +00002088 auto &DL = M.getDataLayout();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002089 Constant *New = ConstantFoldConstantExpression(CE, DL, TLI);
Dan Gohman580b80d2009-11-23 16:22:21 +00002090 if (New && New != CE)
2091 GV->setInitializer(New);
2092 }
Rafael Espindolafc355bc2011-01-19 16:32:21 +00002093
David Majnemerdad0a642014-06-27 18:19:56 +00002094 if (GV->isDiscardableIfUnused()) {
2095 if (const Comdat *C = GV->getComdat())
David Majnemer1b3b70e2014-10-08 07:23:31 +00002096 if (NotDiscardableComdats.count(C) && !GV->hasLocalLinkage())
David Majnemerdad0a642014-06-27 18:19:56 +00002097 continue;
2098 Changed |= ProcessGlobal(GV, GVI);
2099 }
Chris Lattner41b6a5a2005-09-26 01:43:45 +00002100 }
2101 return Changed;
2102}
2103
Jakub Staszak9525a772012-12-06 21:57:16 +00002104static inline bool
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002105isSimpleEnoughValueToCommit(Constant *C,
Mehdi Amini46a43552015-03-04 18:43:29 +00002106 SmallPtrSetImpl<Constant *> &SimpleConstants,
2107 const DataLayout &DL);
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002108
James Molloyea31ad32015-11-13 11:05:07 +00002109/// Return true if the specified constant can be handled by the code generator.
2110/// We don't want to generate something like:
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002111/// void *X = &X/42;
2112/// because the code generator doesn't have a relocation that can handle that.
2113///
2114/// This function should be called if C was not found (but just got inserted)
2115/// in SimpleConstants to avoid having to rescan the same constants all the
2116/// time.
Mehdi Amini46a43552015-03-04 18:43:29 +00002117static bool
2118isSimpleEnoughValueToCommitHelper(Constant *C,
2119 SmallPtrSetImpl<Constant *> &SimpleConstants,
2120 const DataLayout &DL) {
David Majnemer6098b2f2014-06-26 03:02:19 +00002121 // Simple global addresses are supported, do not allow dllimport or
2122 // thread-local globals.
David Majnemer23fc9af2014-06-24 06:53:45 +00002123 if (auto *GV = dyn_cast<GlobalValue>(C))
David Majnemer6098b2f2014-06-26 03:02:19 +00002124 return !GV->hasDLLImportStorageClass() && !GV->isThreadLocal();
David Majnemer23fc9af2014-06-24 06:53:45 +00002125
2126 // Simple integer, undef, constant aggregate zero, etc are all supported.
2127 if (C->getNumOperands() == 0 || isa<BlockAddress>(C))
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002128 return true;
Jakub Staszak9525a772012-12-06 21:57:16 +00002129
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002130 // Aggregate values are safe if all their elements are.
2131 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C) ||
2132 isa<ConstantVector>(C)) {
Pete Cooper125ad172015-06-25 20:51:38 +00002133 for (Value *Op : C->operands())
2134 if (!isSimpleEnoughValueToCommit(cast<Constant>(Op), SimpleConstants, DL))
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002135 return false;
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002136 return true;
2137 }
Jakub Staszak9525a772012-12-06 21:57:16 +00002138
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002139 // We don't know exactly what relocations are allowed in constant expressions,
2140 // so we allow &global+constantoffset, which is safe and uniformly supported
2141 // across targets.
2142 ConstantExpr *CE = cast<ConstantExpr>(C);
2143 switch (CE->getOpcode()) {
2144 case Instruction::BitCast:
Eli Friedman55fa49f32012-01-05 23:03:32 +00002145 // Bitcast is fine if the casted value is fine.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002146 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, DL);
Eli Friedman55fa49f32012-01-05 23:03:32 +00002147
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002148 case Instruction::IntToPtr:
2149 case Instruction::PtrToInt:
Eli Friedman55fa49f32012-01-05 23:03:32 +00002150 // int <=> ptr is fine if the int type is the same size as the
2151 // pointer type.
Mehdi Amini46a43552015-03-04 18:43:29 +00002152 if (DL.getTypeSizeInBits(CE->getType()) !=
2153 DL.getTypeSizeInBits(CE->getOperand(0)->getType()))
Eli Friedman55fa49f32012-01-05 23:03:32 +00002154 return false;
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002155 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, DL);
Jakub Staszak9525a772012-12-06 21:57:16 +00002156
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002157 // GEP is fine if it is simple + constant offset.
2158 case Instruction::GetElementPtr:
2159 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
2160 if (!isa<ConstantInt>(CE->getOperand(i)))
2161 return false;
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002162 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, DL);
Jakub Staszak9525a772012-12-06 21:57:16 +00002163
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002164 case Instruction::Add:
2165 // We allow simple+cst.
2166 if (!isa<ConstantInt>(CE->getOperand(1)))
2167 return false;
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002168 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, DL);
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002169 }
2170 return false;
2171}
2172
Jakub Staszak9525a772012-12-06 21:57:16 +00002173static inline bool
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002174isSimpleEnoughValueToCommit(Constant *C,
Mehdi Amini46a43552015-03-04 18:43:29 +00002175 SmallPtrSetImpl<Constant *> &SimpleConstants,
2176 const DataLayout &DL) {
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002177 // If we already checked this constant, we win.
David Blaikie70573dc2014-11-19 07:49:26 +00002178 if (!SimpleConstants.insert(C).second)
2179 return true;
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002180 // Check the constant.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002181 return isSimpleEnoughValueToCommitHelper(C, SimpleConstants, DL);
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002182}
2183
2184
James Molloyea31ad32015-11-13 11:05:07 +00002185/// Return true if this constant is simple enough for us to understand. In
2186/// particular, if it is a cast to anything other than from one pointer type to
2187/// another pointer type, we punt. We basically just support direct accesses to
2188/// globals and GEP's of globals. This should be kept up to date with
2189/// CommitValueTo.
Chris Lattner46b5c642009-11-06 04:27:31 +00002190static bool isSimpleEnoughPointerToCommit(Constant *C) {
Dan Gohman82e74752009-09-07 22:42:05 +00002191 // Conservatively, avoid aggregate types. This is because we don't
2192 // want to worry about them partially overlapping other stores.
2193 if (!cast<PointerType>(C->getType())->getElementType()->isSingleValueType())
2194 return false;
2195
Dan Gohmanf7f3fb12009-09-07 22:31:26 +00002196 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
David Majnemer23fc9af2014-06-24 06:53:45 +00002197 // Do not allow weak/*_odr/linkonce linkage or external globals.
Mikhail Glushenkov2072db22010-10-19 16:47:23 +00002198 return GV->hasUniqueInitializer();
Dan Gohmanf7f3fb12009-09-07 22:31:26 +00002199
Owen Anderson3e2f6cf2011-01-14 22:31:13 +00002200 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
Chris Lattner46af55e2005-09-26 06:52:44 +00002201 // Handle a constantexpr gep.
2202 if (CE->getOpcode() == Instruction::GetElementPtr &&
Dan Gohmanbeee35a2009-09-07 22:40:13 +00002203 isa<GlobalVariable>(CE->getOperand(0)) &&
2204 cast<GEPOperator>(CE)->isInBounds()) {
Chris Lattner46af55e2005-09-26 06:52:44 +00002205 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
Mikhail Glushenkov2072db22010-10-19 16:47:23 +00002206 // Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or
Dan Gohmanf7f3fb12009-09-07 22:31:26 +00002207 // external globals.
Mikhail Glushenkov2072db22010-10-19 16:47:23 +00002208 if (!GV->hasUniqueInitializer())
Dan Gohmanf7f3fb12009-09-07 22:31:26 +00002209 return false;
Dan Gohman161429f2009-09-07 22:44:55 +00002210
Dan Gohman161429f2009-09-07 22:44:55 +00002211 // The first index must be zero.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00002212 ConstantInt *CI = dyn_cast<ConstantInt>(*std::next(CE->op_begin()));
Dan Gohman161429f2009-09-07 22:44:55 +00002213 if (!CI || !CI->isZero()) return false;
Dan Gohman161429f2009-09-07 22:44:55 +00002214
2215 // The remaining indices must be compile-time known integers within the
Dan Gohman7190d482009-09-10 23:37:55 +00002216 // notional bounds of the corresponding static array types.
2217 if (!CE->isGEPWithNoNotionalOverIndexing())
2218 return false;
Dan Gohman161429f2009-09-07 22:44:55 +00002219
Dan Gohmane525d9d2009-10-05 16:36:26 +00002220 return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
Jakub Staszak9525a772012-12-06 21:57:16 +00002221
Owen Anderson9eb7cb482011-01-14 22:19:20 +00002222 // A constantexpr bitcast from a pointer to another pointer is a no-op,
2223 // and we know how to evaluate it by moving the bitcast from the pointer
2224 // operand to the value operand.
2225 } else if (CE->getOpcode() == Instruction::BitCast &&
Chris Lattner8b4952f2011-01-16 02:05:10 +00002226 isa<GlobalVariable>(CE->getOperand(0))) {
Owen Anderson9eb7cb482011-01-14 22:19:20 +00002227 // Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or
2228 // external globals.
Chris Lattner8b4952f2011-01-16 02:05:10 +00002229 return cast<GlobalVariable>(CE->getOperand(0))->hasUniqueInitializer();
Chris Lattner46af55e2005-09-26 06:52:44 +00002230 }
Owen Anderson3e2f6cf2011-01-14 22:31:13 +00002231 }
Jakub Staszak9525a772012-12-06 21:57:16 +00002232
Chris Lattner99e23fa2005-09-26 04:44:35 +00002233 return false;
2234}
2235
James Molloyea31ad32015-11-13 11:05:07 +00002236/// Evaluate a piece of a constantexpr store into a global initializer. This
2237/// returns 'Init' modified to reflect 'Val' stored into it. At this point, the
2238/// GEP operands of Addr [0, OpNo) have been stepped into.
Anthony Pesche92ae2d2015-07-22 22:26:54 +00002239static Constant *EvaluateStoreInto(Constant *Init, Constant *Val,
2240 ConstantExpr *Addr, unsigned OpNo) {
2241 // Base case of the recursion.
2242 if (OpNo == Addr->getNumOperands()) {
2243 assert(Val->getType() == Init->getType() && "Type mismatch!");
2244 return Val;
2245 }
2246
2247 SmallVector<Constant*, 32> Elts;
2248 if (StructType *STy = dyn_cast<StructType>(Init->getType())) {
2249 // Break up the constant into its elements.
2250 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
2251 Elts.push_back(Init->getAggregateElement(i));
2252
2253 // Replace the element that we are supposed to.
2254 ConstantInt *CU = cast<ConstantInt>(Addr->getOperand(OpNo));
2255 unsigned Idx = CU->getZExtValue();
2256 assert(Idx < STy->getNumElements() && "Struct index out of range!");
2257 Elts[Idx] = EvaluateStoreInto(Elts[Idx], Val, Addr, OpNo+1);
2258
2259 // Return the modified struct.
2260 return ConstantStruct::get(STy, Elts);
2261 }
2262
2263 ConstantInt *CI = cast<ConstantInt>(Addr->getOperand(OpNo));
2264 SequentialType *InitTy = cast<SequentialType>(Init->getType());
2265
2266 uint64_t NumElts;
2267 if (ArrayType *ATy = dyn_cast<ArrayType>(InitTy))
2268 NumElts = ATy->getNumElements();
2269 else
2270 NumElts = InitTy->getVectorNumElements();
2271
2272 // Break up the array into elements.
2273 for (uint64_t i = 0, e = NumElts; i != e; ++i)
2274 Elts.push_back(Init->getAggregateElement(i));
2275
2276 assert(CI->getZExtValue() < NumElts);
2277 Elts[CI->getZExtValue()] =
2278 EvaluateStoreInto(Elts[CI->getZExtValue()], Val, Addr, OpNo+1);
2279
2280 if (Init->getType()->isArrayTy())
2281 return ConstantArray::get(cast<ArrayType>(InitTy), Elts);
2282 return ConstantVector::get(Elts);
2283}
2284
James Molloyea31ad32015-11-13 11:05:07 +00002285/// We have decided that Addr (which satisfies the predicate
Anthony Pesche92ae2d2015-07-22 22:26:54 +00002286/// isSimpleEnoughPointerToCommit) should get Val as its value. Make it happen.
2287static void CommitValueTo(Constant *Val, Constant *Addr) {
2288 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Addr)) {
2289 assert(GV->hasInitializer());
2290 GV->setInitializer(Val);
2291 return;
2292 }
2293
2294 ConstantExpr *CE = cast<ConstantExpr>(Addr);
2295 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
2296 GV->setInitializer(EvaluateStoreInto(GV->getInitializer(), Val, CE, 2));
2297}
2298
Nick Lewycky60829a582012-02-20 03:25:59 +00002299namespace {
2300
James Molloyea31ad32015-11-13 11:05:07 +00002301/// This class evaluates LLVM IR, producing the Constant representing each SSA
2302/// instruction. Changes to global variables are stored in a mapping that can
2303/// be iterated over after the evaluation is complete. Once an evaluation call
2304/// fails, the evaluation object should not be reused.
Nick Lewycky60829a582012-02-20 03:25:59 +00002305class Evaluator {
Nick Lewycky73be5e32012-02-19 23:26:27 +00002306public:
Mehdi Amini46a43552015-03-04 18:43:29 +00002307 Evaluator(const DataLayout &DL, const TargetLibraryInfo *TLI)
2308 : DL(DL), TLI(TLI) {
Benjamin Kramer64425fe2014-05-03 15:50:37 +00002309 ValueStack.emplace_back();
Nick Lewycky73be5e32012-02-19 23:26:27 +00002310 }
2311
Nick Lewycky60829a582012-02-20 03:25:59 +00002312 ~Evaluator() {
David Blaikiebc442202014-04-21 20:49:36 +00002313 for (auto &Tmp : AllocaTmps)
Nick Lewycky73be5e32012-02-19 23:26:27 +00002314 // If there are still users of the alloca, the program is doing something
2315 // silly, e.g. storing the address of the alloca somewhere and using it
2316 // later. Since this is undefined, we'll just make it be null.
2317 if (!Tmp->use_empty())
2318 Tmp->replaceAllUsesWith(Constant::getNullValue(Tmp->getType()));
Nick Lewycky73be5e32012-02-19 23:26:27 +00002319 }
2320
James Molloyea31ad32015-11-13 11:05:07 +00002321 /// Evaluate a call to function F, returning true if successful, false if we
2322 /// can't evaluate it. ActualArgs contains the formal arguments for the
2323 /// function.
Nick Lewycky73be5e32012-02-19 23:26:27 +00002324 bool EvaluateFunction(Function *F, Constant *&RetVal,
2325 const SmallVectorImpl<Constant*> &ActualArgs);
2326
James Molloyea31ad32015-11-13 11:05:07 +00002327 /// Evaluate all instructions in block BB, returning true if successful, false
2328 /// if we can't evaluate it. NewBB returns the next BB that control flows
2329 /// into, or null upon return.
Nick Lewycky73be5e32012-02-19 23:26:27 +00002330 bool EvaluateBlock(BasicBlock::iterator CurInst, BasicBlock *&NextBB);
2331
2332 Constant *getVal(Value *V) {
2333 if (Constant *CV = dyn_cast<Constant>(V)) return CV;
Benjamin Kramer64425fe2014-05-03 15:50:37 +00002334 Constant *R = ValueStack.back().lookup(V);
Nick Lewycky73be5e32012-02-19 23:26:27 +00002335 assert(R && "Reference to an uncomputed value!");
2336 return R;
2337 }
2338
2339 void setVal(Value *V, Constant *C) {
Benjamin Kramer64425fe2014-05-03 15:50:37 +00002340 ValueStack.back()[V] = C;
Nick Lewycky73be5e32012-02-19 23:26:27 +00002341 }
2342
Anthony Pesche92ae2d2015-07-22 22:26:54 +00002343 const DenseMap<Constant*, Constant*> &getMutatedMemory() const {
2344 return MutatedMemory;
Nick Lewycky73be5e32012-02-19 23:26:27 +00002345 }
2346
Craig Topper71b7b682014-08-21 05:55:13 +00002347 const SmallPtrSetImpl<GlobalVariable*> &getInvariants() const {
Nick Lewycky73be5e32012-02-19 23:26:27 +00002348 return Invariants;
2349 }
2350
2351private:
2352 Constant *ComputeLoadResult(Constant *P);
2353
James Molloyea31ad32015-11-13 11:05:07 +00002354 /// As we compute SSA register values, we store their contents here. The back
2355 /// of the deque contains the current function and the stack contains the
2356 /// values in the calling frames.
Benjamin Kramer64425fe2014-05-03 15:50:37 +00002357 std::deque<DenseMap<Value*, Constant*>> ValueStack;
Nick Lewycky73be5e32012-02-19 23:26:27 +00002358
James Molloyea31ad32015-11-13 11:05:07 +00002359 /// This is used to detect recursion. In pathological situations we could hit
2360 /// exponential behavior, but at least there is nothing unbounded.
Nick Lewycky73be5e32012-02-19 23:26:27 +00002361 SmallVector<Function*, 4> CallStack;
2362
James Molloyea31ad32015-11-13 11:05:07 +00002363 /// For each store we execute, we update this map. Loads check this to get
2364 /// the most up-to-date value. If evaluation is successful, this state is
2365 /// committed to the process.
Anthony Pesche92ae2d2015-07-22 22:26:54 +00002366 DenseMap<Constant*, Constant*> MutatedMemory;
Nick Lewycky73be5e32012-02-19 23:26:27 +00002367
James Molloyea31ad32015-11-13 11:05:07 +00002368 /// To 'execute' an alloca, we create a temporary global variable to represent
2369 /// its body. This vector is needed so we can delete the temporary globals
2370 /// when we are done.
David Blaikiebc442202014-04-21 20:49:36 +00002371 SmallVector<std::unique_ptr<GlobalVariable>, 32> AllocaTmps;
Nick Lewycky73be5e32012-02-19 23:26:27 +00002372
James Molloyea31ad32015-11-13 11:05:07 +00002373 /// These global variables have been marked invariant by the static
2374 /// constructor.
Nick Lewycky73be5e32012-02-19 23:26:27 +00002375 SmallPtrSet<GlobalVariable*, 8> Invariants;
2376
James Molloyea31ad32015-11-13 11:05:07 +00002377 /// These are constants we have checked and know to be simple enough to live
2378 /// in a static initializer of a global.
Nick Lewycky73be5e32012-02-19 23:26:27 +00002379 SmallPtrSet<Constant*, 8> SimpleConstants;
2380
Mehdi Amini46a43552015-03-04 18:43:29 +00002381 const DataLayout &DL;
Nick Lewycky73be5e32012-02-19 23:26:27 +00002382 const TargetLibraryInfo *TLI;
2383};
2384
Nick Lewycky60829a582012-02-20 03:25:59 +00002385} // anonymous namespace
2386
James Molloyea31ad32015-11-13 11:05:07 +00002387/// Return the value that would be computed by a load from P after the stores
2388/// reflected by 'memory' have been performed. If we can't decide, return null.
Nick Lewycky60829a582012-02-20 03:25:59 +00002389Constant *Evaluator::ComputeLoadResult(Constant *P) {
Chris Lattner4b05c322005-09-26 05:15:37 +00002390 // If this memory location has been recently stored, use the stored value: it
2391 // is the most up-to-date.
Anthony Pesche92ae2d2015-07-22 22:26:54 +00002392 DenseMap<Constant*, Constant*>::const_iterator I = MutatedMemory.find(P);
2393 if (I != MutatedMemory.end()) return I->second;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002394
Chris Lattner4b05c322005-09-26 05:15:37 +00002395 // Access it.
2396 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(P)) {
Dan Gohman5d5bc6d2009-08-19 18:20:44 +00002397 if (GV->hasDefinitiveInitializer())
Chris Lattner4b05c322005-09-26 05:15:37 +00002398 return GV->getInitializer();
Craig Topperf40110f2014-04-25 05:29:35 +00002399 return nullptr;
Chris Lattner4b05c322005-09-26 05:15:37 +00002400 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002401
Chris Lattner46af55e2005-09-26 06:52:44 +00002402 // Handle a constantexpr getelementptr.
2403 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(P))
2404 if (CE->getOpcode() == Instruction::GetElementPtr &&
2405 isa<GlobalVariable>(CE->getOperand(0))) {
2406 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
Dan Gohman5d5bc6d2009-08-19 18:20:44 +00002407 if (GV->hasDefinitiveInitializer())
Dan Gohmane525d9d2009-10-05 16:36:26 +00002408 return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
Chris Lattner46af55e2005-09-26 06:52:44 +00002409 }
2410
Craig Topperf40110f2014-04-25 05:29:35 +00002411 return nullptr; // don't know how to evaluate.
Chris Lattner4b05c322005-09-26 05:15:37 +00002412}
2413
James Molloyea31ad32015-11-13 11:05:07 +00002414/// Evaluate all instructions in block BB, returning true if successful, false
2415/// if we can't evaluate it. NewBB returns the next BB that control flows into,
2416/// or null upon return.
Nick Lewycky60829a582012-02-20 03:25:59 +00002417bool Evaluator::EvaluateBlock(BasicBlock::iterator CurInst,
2418 BasicBlock *&NextBB) {
Chris Lattner99e23fa2005-09-26 04:44:35 +00002419 // This is the main evaluation loop.
2420 while (1) {
Craig Topperf40110f2014-04-25 05:29:35 +00002421 Constant *InstResult = nullptr;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002422
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002423 DEBUG(dbgs() << "Evaluating Instruction: " << *CurInst << "\n");
2424
Chris Lattner99e23fa2005-09-26 04:44:35 +00002425 if (StoreInst *SI = dyn_cast<StoreInst>(CurInst)) {
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002426 if (!SI->isSimple()) {
Michael Gottesman2a654272013-01-11 23:08:52 +00002427 DEBUG(dbgs() << "Store is not simple! Can not evaluate.\n");
2428 return false; // no volatile/atomic accesses.
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002429 }
Nick Lewycky73be5e32012-02-19 23:26:27 +00002430 Constant *Ptr = getVal(SI->getOperand(1));
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002431 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
Michael Gottesman2a654272013-01-11 23:08:52 +00002432 DEBUG(dbgs() << "Folding constant ptr expression: " << *Ptr);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002433 Ptr = ConstantFoldConstantExpression(CE, DL, TLI);
Michael Gottesman2a654272013-01-11 23:08:52 +00002434 DEBUG(dbgs() << "; To: " << *Ptr << "\n");
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002435 }
2436 if (!isSimpleEnoughPointerToCommit(Ptr)) {
Chris Lattner99e23fa2005-09-26 04:44:35 +00002437 // If this is too complex for us to commit, reject it.
Michael Gottesman2a654272013-01-11 23:08:52 +00002438 DEBUG(dbgs() << "Pointer is too complex for us to evaluate store.");
Chris Lattner65a3a092005-09-27 04:45:34 +00002439 return false;
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002440 }
Jakub Staszak9525a772012-12-06 21:57:16 +00002441
Nick Lewycky73be5e32012-02-19 23:26:27 +00002442 Constant *Val = getVal(SI->getOperand(0));
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002443
2444 // If this might be too difficult for the backend to handle (e.g. the addr
2445 // of one global variable divided by another) then we can't commit it.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002446 if (!isSimpleEnoughValueToCommit(Val, SimpleConstants, DL)) {
Michael Gottesman2a654272013-01-11 23:08:52 +00002447 DEBUG(dbgs() << "Store value is too complex to evaluate store. " << *Val
2448 << "\n");
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002449 return false;
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002450 }
Jakub Staszak9525a772012-12-06 21:57:16 +00002451
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002452 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
Owen Anderson9eb7cb482011-01-14 22:19:20 +00002453 if (CE->getOpcode() == Instruction::BitCast) {
Michael Gottesman2a654272013-01-11 23:08:52 +00002454 DEBUG(dbgs() << "Attempting to resolve bitcast on constant ptr.\n");
Owen Anderson9eb7cb482011-01-14 22:19:20 +00002455 // If we're evaluating a store through a bitcast, then we need
2456 // to pull the bitcast off the pointer type and push it onto the
2457 // stored value.
Chris Lattner8b4952f2011-01-16 02:05:10 +00002458 Ptr = CE->getOperand(0);
Jakub Staszak9525a772012-12-06 21:57:16 +00002459
Nick Lewycky239fdf02012-02-06 08:24:44 +00002460 Type *NewTy = cast<PointerType>(Ptr->getType())->getElementType();
Jakub Staszak9525a772012-12-06 21:57:16 +00002461
Owen Anderson4e54efd2011-01-16 04:33:33 +00002462 // In order to push the bitcast onto the stored value, a bitcast
2463 // from NewTy to Val's type must be legal. If it's not, we can try
2464 // introspecting NewTy to find a legal conversion.
2465 while (!Val->getType()->canLosslesslyBitCastTo(NewTy)) {
2466 // If NewTy is a struct, we can convert the pointer to the struct
2467 // into a pointer to its first member.
2468 // FIXME: This could be extended to support arrays as well.
Chris Lattner229907c2011-07-18 04:54:35 +00002469 if (StructType *STy = dyn_cast<StructType>(NewTy)) {
Owen Anderson4e54efd2011-01-16 04:33:33 +00002470 NewTy = STy->getTypeAtIndex(0U);
2471
Nick Lewycky239fdf02012-02-06 08:24:44 +00002472 IntegerType *IdxTy = IntegerType::get(NewTy->getContext(), 32);
Owen Anderson4e54efd2011-01-16 04:33:33 +00002473 Constant *IdxZero = ConstantInt::get(IdxTy, 0, false);
2474 Constant * const IdxList[] = {IdxZero, IdxZero};
2475
David Blaikie4a2e73b2015-04-02 18:55:32 +00002476 Ptr = ConstantExpr::getGetElementPtr(nullptr, Ptr, IdxList);
Nick Lewycky9d0da182012-02-21 22:08:06 +00002477 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002478 Ptr = ConstantFoldConstantExpression(CE, DL, TLI);
Nick Lewycky9d0da182012-02-21 22:08:06 +00002479
Owen Anderson4e54efd2011-01-16 04:33:33 +00002480 // If we can't improve the situation by introspecting NewTy,
2481 // we have to give up.
2482 } else {
Michael Gottesman2a654272013-01-11 23:08:52 +00002483 DEBUG(dbgs() << "Failed to bitcast constant ptr, can not "
2484 "evaluate.\n");
Nick Lewycky239fdf02012-02-06 08:24:44 +00002485 return false;
Owen Anderson4e54efd2011-01-16 04:33:33 +00002486 }
Owen Anderson9eb7cb482011-01-14 22:19:20 +00002487 }
Jakub Staszak9525a772012-12-06 21:57:16 +00002488
Owen Anderson4e54efd2011-01-16 04:33:33 +00002489 // If we found compatible types, go ahead and push the bitcast
2490 // onto the stored value.
Owen Anderson9eb7cb482011-01-14 22:19:20 +00002491 Val = ConstantExpr::getBitCast(Val, NewTy);
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002492
Michael Gottesman2a654272013-01-11 23:08:52 +00002493 DEBUG(dbgs() << "Evaluated bitcast: " << *Val << "\n");
Owen Anderson9eb7cb482011-01-14 22:19:20 +00002494 }
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002495 }
Jakub Staszak9525a772012-12-06 21:57:16 +00002496
Anthony Pesche92ae2d2015-07-22 22:26:54 +00002497 MutatedMemory[Ptr] = Val;
Chris Lattner99e23fa2005-09-26 04:44:35 +00002498 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CurInst)) {
Owen Anderson487375e2009-07-29 18:55:55 +00002499 InstResult = ConstantExpr::get(BO->getOpcode(),
Nick Lewycky73be5e32012-02-19 23:26:27 +00002500 getVal(BO->getOperand(0)),
2501 getVal(BO->getOperand(1)));
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002502 DEBUG(dbgs() << "Found a BinaryOperator! Simplifying: " << *InstResult
Michael Gottesman2a654272013-01-11 23:08:52 +00002503 << "\n");
Reid Spencer266e42b2006-12-23 06:05:41 +00002504 } else if (CmpInst *CI = dyn_cast<CmpInst>(CurInst)) {
Owen Anderson487375e2009-07-29 18:55:55 +00002505 InstResult = ConstantExpr::getCompare(CI->getPredicate(),
Nick Lewycky73be5e32012-02-19 23:26:27 +00002506 getVal(CI->getOperand(0)),
2507 getVal(CI->getOperand(1)));
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002508 DEBUG(dbgs() << "Found a CmpInst! Simplifying: " << *InstResult
Michael Gottesman2a654272013-01-11 23:08:52 +00002509 << "\n");
Chris Lattner99e23fa2005-09-26 04:44:35 +00002510 } else if (CastInst *CI = dyn_cast<CastInst>(CurInst)) {
Owen Anderson487375e2009-07-29 18:55:55 +00002511 InstResult = ConstantExpr::getCast(CI->getOpcode(),
Nick Lewycky73be5e32012-02-19 23:26:27 +00002512 getVal(CI->getOperand(0)),
Chris Lattner99e23fa2005-09-26 04:44:35 +00002513 CI->getType());
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002514 DEBUG(dbgs() << "Found a Cast! Simplifying: " << *InstResult
Michael Gottesman2a654272013-01-11 23:08:52 +00002515 << "\n");
Chris Lattner99e23fa2005-09-26 04:44:35 +00002516 } else if (SelectInst *SI = dyn_cast<SelectInst>(CurInst)) {
Nick Lewycky73be5e32012-02-19 23:26:27 +00002517 InstResult = ConstantExpr::getSelect(getVal(SI->getOperand(0)),
2518 getVal(SI->getOperand(1)),
2519 getVal(SI->getOperand(2)));
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002520 DEBUG(dbgs() << "Found a Select! Simplifying: " << *InstResult
Michael Gottesman2a654272013-01-11 23:08:52 +00002521 << "\n");
David Majnemerfe8c7542014-08-08 05:50:43 +00002522 } else if (auto *EVI = dyn_cast<ExtractValueInst>(CurInst)) {
2523 InstResult = ConstantExpr::getExtractValue(
2524 getVal(EVI->getAggregateOperand()), EVI->getIndices());
2525 DEBUG(dbgs() << "Found an ExtractValueInst! Simplifying: " << *InstResult
2526 << "\n");
2527 } else if (auto *IVI = dyn_cast<InsertValueInst>(CurInst)) {
2528 InstResult = ConstantExpr::getInsertValue(
2529 getVal(IVI->getAggregateOperand()),
2530 getVal(IVI->getInsertedValueOperand()), IVI->getIndices());
2531 DEBUG(dbgs() << "Found an InsertValueInst! Simplifying: " << *InstResult
2532 << "\n");
Chris Lattner4b05c322005-09-26 05:15:37 +00002533 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurInst)) {
Nick Lewycky73be5e32012-02-19 23:26:27 +00002534 Constant *P = getVal(GEP->getOperand(0));
Chris Lattnerf96f4a82007-01-31 04:40:53 +00002535 SmallVector<Constant*, 8> GEPOps;
Gabor Greif3a9fba52008-05-29 01:59:18 +00002536 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end();
2537 i != e; ++i)
Nick Lewycky73be5e32012-02-19 23:26:27 +00002538 GEPOps.push_back(getVal(*i));
Jay Foad2f5fc8c2011-07-21 15:15:37 +00002539 InstResult =
David Blaikie4a2e73b2015-04-02 18:55:32 +00002540 ConstantExpr::getGetElementPtr(GEP->getSourceElementType(), P, GEPOps,
2541 cast<GEPOperator>(GEP)->isInBounds());
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002542 DEBUG(dbgs() << "Found a GEP! Simplifying: " << *InstResult
Michael Gottesman2a654272013-01-11 23:08:52 +00002543 << "\n");
Chris Lattner4b05c322005-09-26 05:15:37 +00002544 } else if (LoadInst *LI = dyn_cast<LoadInst>(CurInst)) {
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002545
2546 if (!LI->isSimple()) {
Michael Gottesman2a654272013-01-11 23:08:52 +00002547 DEBUG(dbgs() << "Found a Load! Not a simple load, can not evaluate.\n");
2548 return false; // no volatile/atomic accesses.
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002549 }
2550
Nick Lewycky9d0da182012-02-21 22:08:06 +00002551 Constant *Ptr = getVal(LI->getOperand(0));
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002552 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002553 Ptr = ConstantFoldConstantExpression(CE, DL, TLI);
Michael Gottesman2a654272013-01-11 23:08:52 +00002554 DEBUG(dbgs() << "Found a constant pointer expression, constant "
2555 "folding: " << *Ptr << "\n");
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002556 }
Nick Lewycky9d0da182012-02-21 22:08:06 +00002557 InstResult = ComputeLoadResult(Ptr);
Craig Topperf40110f2014-04-25 05:29:35 +00002558 if (!InstResult) {
Michael Gottesman2a654272013-01-11 23:08:52 +00002559 DEBUG(dbgs() << "Failed to compute load result. Can not evaluate load."
2560 "\n");
2561 return false; // Could not evaluate load.
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002562 }
2563
2564 DEBUG(dbgs() << "Evaluated load: " << *InstResult << "\n");
Chris Lattner6bf2cd52005-09-26 17:07:09 +00002565 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(CurInst)) {
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002566 if (AI->isArrayAllocation()) {
Michael Gottesman2a654272013-01-11 23:08:52 +00002567 DEBUG(dbgs() << "Found an array alloca. Can not evaluate.\n");
2568 return false; // Cannot handle array allocs.
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002569 }
Chris Lattner229907c2011-07-18 04:54:35 +00002570 Type *Ty = AI->getType()->getElementType();
David Blaikiebc442202014-04-21 20:49:36 +00002571 AllocaTmps.push_back(
2572 make_unique<GlobalVariable>(Ty, false, GlobalValue::InternalLinkage,
2573 UndefValue::get(Ty), AI->getName()));
2574 InstResult = AllocaTmps.back().get();
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002575 DEBUG(dbgs() << "Found an alloca. Result: " << *InstResult << "\n");
Nick Lewyckyc1572e42012-02-12 05:09:35 +00002576 } else if (isa<CallInst>(CurInst) || isa<InvokeInst>(CurInst)) {
Duncan P. N. Exon Smith17323402015-10-13 17:51:03 +00002577 CallSite CS(&*CurInst);
Devang Patel04852aa2009-03-09 23:04:12 +00002578
2579 // Debug info can safely be ignored here.
Nick Lewyckyc1572e42012-02-12 05:09:35 +00002580 if (isa<DbgInfoIntrinsic>(CS.getInstruction())) {
Michael Gottesman2a654272013-01-11 23:08:52 +00002581 DEBUG(dbgs() << "Ignoring debug info.\n");
Devang Patel04852aa2009-03-09 23:04:12 +00002582 ++CurInst;
2583 continue;
2584 }
2585
Chris Lattnerfd2e13b2006-07-07 21:37:01 +00002586 // Cannot handle inline asm.
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002587 if (isa<InlineAsm>(CS.getCalledValue())) {
Michael Gottesman2a654272013-01-11 23:08:52 +00002588 DEBUG(dbgs() << "Found inline asm, can not evaluate.\n");
2589 return false;
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002590 }
Chris Lattnerfd2e13b2006-07-07 21:37:01 +00002591
Nick Lewycky68f9f9d2012-02-17 06:59:21 +00002592 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CS.getInstruction())) {
2593 if (MemSetInst *MSI = dyn_cast<MemSetInst>(II)) {
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002594 if (MSI->isVolatile()) {
Michael Gottesman2a654272013-01-11 23:08:52 +00002595 DEBUG(dbgs() << "Can not optimize a volatile memset " <<
2596 "intrinsic.\n");
2597 return false;
2598 }
Nick Lewycky73be5e32012-02-19 23:26:27 +00002599 Constant *Ptr = getVal(MSI->getDest());
2600 Constant *Val = getVal(MSI->getValue());
2601 Constant *DestVal = ComputeLoadResult(getVal(Ptr));
Nick Lewycky68f9f9d2012-02-17 06:59:21 +00002602 if (Val->isNullValue() && DestVal && DestVal->isNullValue()) {
2603 // This memset is a no-op.
Michael Gottesman2a654272013-01-11 23:08:52 +00002604 DEBUG(dbgs() << "Ignoring no-op memset.\n");
Nick Lewycky68f9f9d2012-02-17 06:59:21 +00002605 ++CurInst;
2606 continue;
2607 }
2608 }
2609
2610 if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
2611 II->getIntrinsicID() == Intrinsic::lifetime_end) {
Michael Gottesman2a654272013-01-11 23:08:52 +00002612 DEBUG(dbgs() << "Ignoring lifetime intrinsic.\n");
Nick Lewycky68f9f9d2012-02-17 06:59:21 +00002613 ++CurInst;
2614 continue;
2615 }
2616
2617 if (II->getIntrinsicID() == Intrinsic::invariant_start) {
2618 // We don't insert an entry into Values, as it doesn't have a
2619 // meaningful return value.
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002620 if (!II->use_empty()) {
Alp Tokerf907b892013-12-05 05:44:44 +00002621 DEBUG(dbgs() << "Found unused invariant_start. Can't evaluate.\n");
Nick Lewycky68f9f9d2012-02-17 06:59:21 +00002622 return false;
Michael Gottesman2a654272013-01-11 23:08:52 +00002623 }
Nick Lewycky68f9f9d2012-02-17 06:59:21 +00002624 ConstantInt *Size = cast<ConstantInt>(II->getArgOperand(0));
Nick Lewycky519561f2012-02-20 23:32:26 +00002625 Value *PtrArg = getVal(II->getArgOperand(1));
2626 Value *Ptr = PtrArg->stripPointerCasts();
2627 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr)) {
2628 Type *ElemTy = cast<PointerType>(GV->getType())->getElementType();
Mehdi Amini46a43552015-03-04 18:43:29 +00002629 if (!Size->isAllOnesValue() &&
Nick Lewycky519561f2012-02-20 23:32:26 +00002630 Size->getValue().getLimitedValue() >=
Mehdi Amini46a43552015-03-04 18:43:29 +00002631 DL.getTypeStoreSize(ElemTy)) {
Nick Lewycky68f9f9d2012-02-17 06:59:21 +00002632 Invariants.insert(GV);
Michael Gottesman2a654272013-01-11 23:08:52 +00002633 DEBUG(dbgs() << "Found a global var that is an invariant: " << *GV
2634 << "\n");
2635 } else {
2636 DEBUG(dbgs() << "Found a global var, but can not treat it as an "
2637 "invariant.\n");
2638 }
Nick Lewycky68f9f9d2012-02-17 06:59:21 +00002639 }
2640 // Continue even if we do nothing.
Nick Lewyckya3bb03e2011-05-29 18:41:56 +00002641 ++CurInst;
2642 continue;
Piotr Padlewski4e7f7522015-08-25 01:34:15 +00002643 } else if (II->getIntrinsicID() == Intrinsic::assume) {
2644 DEBUG(dbgs() << "Skipping assume intrinsic.\n");
2645 ++CurInst;
2646 continue;
Nick Lewyckya3bb03e2011-05-29 18:41:56 +00002647 }
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002648
Michael Gottesman2a654272013-01-11 23:08:52 +00002649 DEBUG(dbgs() << "Unknown intrinsic. Can not evaluate.\n");
Nick Lewyckya3bb03e2011-05-29 18:41:56 +00002650 return false;
2651 }
2652
Chris Lattner65a3a092005-09-27 04:45:34 +00002653 // Resolve function pointers.
Nick Lewycky73be5e32012-02-19 23:26:27 +00002654 Function *Callee = dyn_cast<Function>(getVal(CS.getCalledValue()));
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002655 if (!Callee || Callee->mayBeOverridden()) {
Michael Gottesman2a654272013-01-11 23:08:52 +00002656 DEBUG(dbgs() << "Can not resolve function pointer.\n");
Nick Lewyckyc1572e42012-02-12 05:09:35 +00002657 return false; // Cannot resolve.
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002658 }
Chris Lattner3d27e7f2005-09-27 05:02:43 +00002659
Duncan Sandsc4ce58d82009-08-17 14:33:27 +00002660 SmallVector<Constant*, 8> Formals;
Nick Lewyckyc1572e42012-02-12 05:09:35 +00002661 for (User::op_iterator i = CS.arg_begin(), e = CS.arg_end(); i != e; ++i)
Nick Lewycky73be5e32012-02-19 23:26:27 +00002662 Formals.push_back(getVal(*i));
Duncan Sandsc4ce58d82009-08-17 14:33:27 +00002663
Reid Spencer5301e7c2007-01-30 20:08:39 +00002664 if (Callee->isDeclaration()) {
Chris Lattner3d27e7f2005-09-27 05:02:43 +00002665 // If this is a function we can constant fold, do it.
Chad Rosiere6de63d2011-12-01 21:29:16 +00002666 if (Constant *C = ConstantFoldCall(Callee, Formals, TLI)) {
Chris Lattner3d27e7f2005-09-27 05:02:43 +00002667 InstResult = C;
Michael Gottesman2a654272013-01-11 23:08:52 +00002668 DEBUG(dbgs() << "Constant folded function call. Result: " <<
2669 *InstResult << "\n");
Chris Lattner3d27e7f2005-09-27 05:02:43 +00002670 } else {
Michael Gottesman2a654272013-01-11 23:08:52 +00002671 DEBUG(dbgs() << "Can not constant fold function call.\n");
Chris Lattner3d27e7f2005-09-27 05:02:43 +00002672 return false;
2673 }
2674 } else {
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002675 if (Callee->getFunctionType()->isVarArg()) {
Michael Gottesman2a654272013-01-11 23:08:52 +00002676 DEBUG(dbgs() << "Can not constant fold vararg function call.\n");
Chris Lattner3d27e7f2005-09-27 05:02:43 +00002677 return false;
Michael Gottesman2a654272013-01-11 23:08:52 +00002678 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002679
Craig Topperf40110f2014-04-25 05:29:35 +00002680 Constant *RetVal = nullptr;
Chris Lattner3d27e7f2005-09-27 05:02:43 +00002681 // Execute the call, if successful, use the return value.
Benjamin Kramer64425fe2014-05-03 15:50:37 +00002682 ValueStack.emplace_back();
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002683 if (!EvaluateFunction(Callee, RetVal, Formals)) {
Michael Gottesman2a654272013-01-11 23:08:52 +00002684 DEBUG(dbgs() << "Failed to evaluate function.\n");
Chris Lattner3d27e7f2005-09-27 05:02:43 +00002685 return false;
Michael Gottesman2a654272013-01-11 23:08:52 +00002686 }
David Blaikiebc442202014-04-21 20:49:36 +00002687 ValueStack.pop_back();
Chris Lattner3d27e7f2005-09-27 05:02:43 +00002688 InstResult = RetVal;
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002689
Craig Topperf40110f2014-04-25 05:29:35 +00002690 if (InstResult) {
Michael Gottesman2a654272013-01-11 23:08:52 +00002691 DEBUG(dbgs() << "Successfully evaluated function. Result: " <<
2692 InstResult << "\n\n");
2693 } else {
2694 DEBUG(dbgs() << "Successfully evaluated function. Result: 0\n\n");
2695 }
Chris Lattner3d27e7f2005-09-27 05:02:43 +00002696 }
Reid Spencerde46e482006-11-02 20:25:50 +00002697 } else if (isa<TerminatorInst>(CurInst)) {
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002698 DEBUG(dbgs() << "Found a terminator instruction.\n");
2699
Chris Lattner3e9ea5f2005-09-26 04:57:38 +00002700 if (BranchInst *BI = dyn_cast<BranchInst>(CurInst)) {
2701 if (BI->isUnconditional()) {
Nick Lewycky239fdf02012-02-06 08:24:44 +00002702 NextBB = BI->getSuccessor(0);
Chris Lattner3e9ea5f2005-09-26 04:57:38 +00002703 } else {
Zhou Sheng75b871f2007-01-11 12:24:14 +00002704 ConstantInt *Cond =
Nick Lewycky73be5e32012-02-19 23:26:27 +00002705 dyn_cast<ConstantInt>(getVal(BI->getCondition()));
Chris Lattner15649082007-01-12 18:30:11 +00002706 if (!Cond) return false; // Cannot determine.
Zhou Sheng75b871f2007-01-11 12:24:14 +00002707
Nick Lewycky239fdf02012-02-06 08:24:44 +00002708 NextBB = BI->getSuccessor(!Cond->getZExtValue());
Chris Lattner3e9ea5f2005-09-26 04:57:38 +00002709 }
2710 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(CurInst)) {
2711 ConstantInt *Val =
Nick Lewycky73be5e32012-02-19 23:26:27 +00002712 dyn_cast<ConstantInt>(getVal(SI->getCondition()));
Chris Lattner65a3a092005-09-27 04:45:34 +00002713 if (!Val) return false; // Cannot determine.
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00002714 NextBB = SI->findCaseValue(Val).getCaseSuccessor();
Chris Lattner31274882009-10-29 05:51:50 +00002715 } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(CurInst)) {
Nick Lewycky73be5e32012-02-19 23:26:27 +00002716 Value *Val = getVal(IBI->getAddress())->stripPointerCasts();
Chris Lattner31274882009-10-29 05:51:50 +00002717 if (BlockAddress *BA = dyn_cast<BlockAddress>(Val))
Nick Lewycky239fdf02012-02-06 08:24:44 +00002718 NextBB = BA->getBasicBlock();
Chris Lattneraa99c942009-11-01 01:27:45 +00002719 else
2720 return false; // Cannot determine.
Nick Lewycky239fdf02012-02-06 08:24:44 +00002721 } else if (isa<ReturnInst>(CurInst)) {
Craig Topperf40110f2014-04-25 05:29:35 +00002722 NextBB = nullptr;
Chris Lattner3e9ea5f2005-09-26 04:57:38 +00002723 } else {
Bill Wendlingf891bf82011-07-31 06:30:59 +00002724 // invoke, unwind, resume, unreachable.
Michael Gottesman2a654272013-01-11 23:08:52 +00002725 DEBUG(dbgs() << "Can not handle terminator.");
Chris Lattner65a3a092005-09-27 04:45:34 +00002726 return false; // Cannot handle this terminator.
Chris Lattner3e9ea5f2005-09-26 04:57:38 +00002727 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002728
Nick Lewycky239fdf02012-02-06 08:24:44 +00002729 // We succeeded at evaluating this block!
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002730 DEBUG(dbgs() << "Successfully evaluated block.\n");
Nick Lewycky239fdf02012-02-06 08:24:44 +00002731 return true;
Chris Lattner99e23fa2005-09-26 04:44:35 +00002732 } else {
Chris Lattner99e23fa2005-09-26 04:44:35 +00002733 // Did not know how to evaluate this!
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002734 DEBUG(dbgs() << "Failed to evaluate block due to unhandled instruction."
Michael Gottesman2a654272013-01-11 23:08:52 +00002735 "\n");
Chris Lattner65a3a092005-09-27 04:45:34 +00002736 return false;
Chris Lattner99e23fa2005-09-26 04:44:35 +00002737 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002738
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002739 if (!CurInst->use_empty()) {
2740 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(InstResult))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002741 InstResult = ConstantFoldConstantExpression(CE, DL, TLI);
Jakub Staszak9525a772012-12-06 21:57:16 +00002742
Duncan P. N. Exon Smith17323402015-10-13 17:51:03 +00002743 setVal(&*CurInst, InstResult);
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002744 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002745
Dan Gohmaneab06fa2012-03-13 18:01:37 +00002746 // If we just processed an invoke, we finished evaluating the block.
2747 if (InvokeInst *II = dyn_cast<InvokeInst>(CurInst)) {
2748 NextBB = II->getNormalDest();
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002749 DEBUG(dbgs() << "Found an invoke instruction. Finished Block.\n\n");
Dan Gohmaneab06fa2012-03-13 18:01:37 +00002750 return true;
2751 }
2752
Chris Lattner99e23fa2005-09-26 04:44:35 +00002753 // Advance program counter.
2754 ++CurInst;
2755 }
Chris Lattnerda1889b2005-09-27 04:27:01 +00002756}
2757
James Molloyea31ad32015-11-13 11:05:07 +00002758/// Evaluate a call to function F, returning true if successful, false if we
2759/// can't evaluate it. ActualArgs contains the formal arguments for the
2760/// function.
Nick Lewycky60829a582012-02-20 03:25:59 +00002761bool Evaluator::EvaluateFunction(Function *F, Constant *&RetVal,
2762 const SmallVectorImpl<Constant*> &ActualArgs) {
Nick Lewycky239fdf02012-02-06 08:24:44 +00002763 // Check to see if this function is already executing (recursion). If so,
2764 // bail out. TODO: we might want to accept limited recursion.
2765 if (std::find(CallStack.begin(), CallStack.end(), F) != CallStack.end())
2766 return false;
2767
2768 CallStack.push_back(F);
2769
Nick Lewycky239fdf02012-02-06 08:24:44 +00002770 // Initialize arguments to the incoming values specified.
2771 unsigned ArgNo = 0;
2772 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); AI != E;
2773 ++AI, ++ArgNo)
Duncan P. N. Exon Smith17323402015-10-13 17:51:03 +00002774 setVal(&*AI, ActualArgs[ArgNo]);
Nick Lewycky239fdf02012-02-06 08:24:44 +00002775
2776 // ExecutedBlocks - We only handle non-looping, non-recursive code. As such,
2777 // we can only evaluate any one basic block at most once. This set keeps
2778 // track of what we have executed so we can detect recursive cases etc.
2779 SmallPtrSet<BasicBlock*, 32> ExecutedBlocks;
2780
2781 // CurBB - The current basic block we're evaluating.
Duncan P. N. Exon Smith17323402015-10-13 17:51:03 +00002782 BasicBlock *CurBB = &F->front();
Nick Lewycky239fdf02012-02-06 08:24:44 +00002783
Nick Lewycky4231c412012-02-12 00:47:24 +00002784 BasicBlock::iterator CurInst = CurBB->begin();
2785
Nick Lewycky239fdf02012-02-06 08:24:44 +00002786 while (1) {
Craig Topperf40110f2014-04-25 05:29:35 +00002787 BasicBlock *NextBB = nullptr; // Initialized to avoid compiler warnings.
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002788 DEBUG(dbgs() << "Trying to evaluate BB: " << *CurBB << "\n");
2789
Nick Lewycky73be5e32012-02-19 23:26:27 +00002790 if (!EvaluateBlock(CurInst, NextBB))
Nick Lewycky239fdf02012-02-06 08:24:44 +00002791 return false;
2792
Craig Topperf40110f2014-04-25 05:29:35 +00002793 if (!NextBB) {
Nick Lewycky239fdf02012-02-06 08:24:44 +00002794 // Successfully running until there's no next block means that we found
2795 // the return. Fill it the return value and pop the call stack.
2796 ReturnInst *RI = cast<ReturnInst>(CurBB->getTerminator());
2797 if (RI->getNumOperands())
Nick Lewycky73be5e32012-02-19 23:26:27 +00002798 RetVal = getVal(RI->getOperand(0));
Nick Lewycky239fdf02012-02-06 08:24:44 +00002799 CallStack.pop_back();
2800 return true;
2801 }
2802
2803 // Okay, we succeeded in evaluating this control flow. See if we have
2804 // executed the new block before. If so, we have a looping function,
2805 // which we cannot evaluate in reasonable time.
David Blaikie70573dc2014-11-19 07:49:26 +00002806 if (!ExecutedBlocks.insert(NextBB).second)
Nick Lewycky239fdf02012-02-06 08:24:44 +00002807 return false; // looped!
2808
2809 // Okay, we have never been in this block before. Check to see if there
2810 // are any PHI nodes. If so, evaluate them with information about where
2811 // we came from.
Craig Topperf40110f2014-04-25 05:29:35 +00002812 PHINode *PN = nullptr;
Nick Lewycky4231c412012-02-12 00:47:24 +00002813 for (CurInst = NextBB->begin();
2814 (PN = dyn_cast<PHINode>(CurInst)); ++CurInst)
Nick Lewycky73be5e32012-02-19 23:26:27 +00002815 setVal(PN, getVal(PN->getIncomingValueForBlock(CurBB)));
Nick Lewycky239fdf02012-02-06 08:24:44 +00002816
2817 // Advance to the next block.
2818 CurBB = NextBB;
2819 }
2820}
2821
James Molloyea31ad32015-11-13 11:05:07 +00002822/// Evaluate static constructors in the function, if we can. Return true if we
2823/// can, false otherwise.
Mehdi Amini46a43552015-03-04 18:43:29 +00002824static bool EvaluateStaticConstructor(Function *F, const DataLayout &DL,
Chad Rosiere6de63d2011-12-01 21:29:16 +00002825 const TargetLibraryInfo *TLI) {
Chris Lattnerda1889b2005-09-27 04:27:01 +00002826 // Call the function.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002827 Evaluator Eval(DL, TLI);
Chris Lattner65a3a092005-09-27 04:45:34 +00002828 Constant *RetValDummy;
Nick Lewycky73be5e32012-02-19 23:26:27 +00002829 bool EvalSuccess = Eval.EvaluateFunction(F, RetValDummy,
2830 SmallVector<Constant*, 0>());
Jakub Staszak9525a772012-12-06 21:57:16 +00002831
Chris Lattnerda1889b2005-09-27 04:27:01 +00002832 if (EvalSuccess) {
Nico Weber4b2acde2014-05-02 18:35:25 +00002833 ++NumCtorsEvaluated;
2834
Chris Lattner6bf2cd52005-09-26 17:07:09 +00002835 // We succeeded at evaluation: commit the result.
David Greene44cb8ad2010-01-05 01:28:05 +00002836 DEBUG(dbgs() << "FULLY EVALUATED GLOBAL CTOR FUNCTION '"
Anthony Pesche92ae2d2015-07-22 22:26:54 +00002837 << F->getName() << "' to " << Eval.getMutatedMemory().size()
2838 << " stores.\n");
2839 for (DenseMap<Constant*, Constant*>::const_iterator I =
2840 Eval.getMutatedMemory().begin(), E = Eval.getMutatedMemory().end();
2841 I != E; ++I)
2842 CommitValueTo(I->second, I->first);
Craig Topper46276792014-08-24 23:23:06 +00002843 for (GlobalVariable *GV : Eval.getInvariants())
2844 GV->setConstant(true);
Chris Lattner6bf2cd52005-09-26 17:07:09 +00002845 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002846
Chris Lattnerda1889b2005-09-27 04:27:01 +00002847 return EvalSuccess;
Chris Lattner99e23fa2005-09-26 04:44:35 +00002848}
2849
Benjamin Krameradf1ea82014-03-07 21:52:38 +00002850static int compareNames(Constant *const *A, Constant *const *B) {
Sean Silvaace78182015-09-28 19:02:11 +00002851 return (*A)->stripPointerCasts()->getName().compare(
2852 (*B)->stripPointerCasts()->getName());
Benjamin Krameradf1ea82014-03-07 21:52:38 +00002853}
2854
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002855static void setUsedInitializer(GlobalVariable &V,
Craig Topper97ebe532014-08-19 07:44:27 +00002856 const SmallPtrSet<GlobalValue *, 8> &Init) {
Rafael Espindolac2bb73f2013-07-20 23:33:15 +00002857 if (Init.empty()) {
2858 V.eraseFromParent();
2859 return;
2860 }
2861
Matt Arsenaultda1deab2014-01-02 19:53:49 +00002862 // Type of pointer to the array of pointers.
2863 PointerType *Int8PtrTy = Type::getInt8PtrTy(V.getContext(), 0);
Rafael Espindola00752162013-05-09 17:22:59 +00002864
Matt Arsenaultda1deab2014-01-02 19:53:49 +00002865 SmallVector<llvm::Constant *, 8> UsedArray;
Craig Topper71b7b682014-08-21 05:55:13 +00002866 for (GlobalValue *GV : Init) {
Matt Arsenaultda1deab2014-01-02 19:53:49 +00002867 Constant *Cast
Craig Topper71b7b682014-08-21 05:55:13 +00002868 = ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, Int8PtrTy);
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002869 UsedArray.push_back(Cast);
Rafael Espindola00752162013-05-09 17:22:59 +00002870 }
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002871 // Sort to get deterministic order.
Benjamin Krameradf1ea82014-03-07 21:52:38 +00002872 array_pod_sort(UsedArray.begin(), UsedArray.end(), compareNames);
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002873 ArrayType *ATy = ArrayType::get(Int8PtrTy, UsedArray.size());
Rafael Espindola00752162013-05-09 17:22:59 +00002874
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002875 Module *M = V.getParent();
2876 V.removeFromParent();
2877 GlobalVariable *NV =
2878 new GlobalVariable(*M, ATy, false, llvm::GlobalValue::AppendingLinkage,
2879 llvm::ConstantArray::get(ATy, UsedArray), "");
2880 NV->takeName(&V);
2881 NV->setSection("llvm.metadata");
2882 delete &V;
Rafael Espindola00752162013-05-09 17:22:59 +00002883}
2884
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002885namespace {
James Molloyea31ad32015-11-13 11:05:07 +00002886/// An easy to access representation of llvm.used and llvm.compiler.used.
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002887class LLVMUsed {
2888 SmallPtrSet<GlobalValue *, 8> Used;
2889 SmallPtrSet<GlobalValue *, 8> CompilerUsed;
2890 GlobalVariable *UsedV;
2891 GlobalVariable *CompilerUsedV;
2892
2893public:
Rafael Espindolaec2375f2013-07-25 02:50:08 +00002894 LLVMUsed(Module &M) {
Rafael Espindola17600e22013-07-25 03:23:25 +00002895 UsedV = collectUsedGlobalVariables(M, Used, false);
2896 CompilerUsedV = collectUsedGlobalVariables(M, CompilerUsed, true);
Rafael Espindola00752162013-05-09 17:22:59 +00002897 }
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002898 typedef SmallPtrSet<GlobalValue *, 8>::iterator iterator;
Craig Topper46276792014-08-24 23:23:06 +00002899 typedef iterator_range<iterator> used_iterator_range;
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002900 iterator usedBegin() { return Used.begin(); }
2901 iterator usedEnd() { return Used.end(); }
Craig Topper46276792014-08-24 23:23:06 +00002902 used_iterator_range used() {
2903 return used_iterator_range(usedBegin(), usedEnd());
2904 }
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002905 iterator compilerUsedBegin() { return CompilerUsed.begin(); }
2906 iterator compilerUsedEnd() { return CompilerUsed.end(); }
Craig Topper46276792014-08-24 23:23:06 +00002907 used_iterator_range compilerUsed() {
2908 return used_iterator_range(compilerUsedBegin(), compilerUsedEnd());
2909 }
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002910 bool usedCount(GlobalValue *GV) const { return Used.count(GV); }
2911 bool compilerUsedCount(GlobalValue *GV) const {
2912 return CompilerUsed.count(GV);
2913 }
2914 bool usedErase(GlobalValue *GV) { return Used.erase(GV); }
2915 bool compilerUsedErase(GlobalValue *GV) { return CompilerUsed.erase(GV); }
David Blaikie70573dc2014-11-19 07:49:26 +00002916 bool usedInsert(GlobalValue *GV) { return Used.insert(GV).second; }
2917 bool compilerUsedInsert(GlobalValue *GV) {
2918 return CompilerUsed.insert(GV).second;
2919 }
Rafael Espindola00752162013-05-09 17:22:59 +00002920
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002921 void syncVariablesAndSets() {
2922 if (UsedV)
2923 setUsedInitializer(*UsedV, Used);
2924 if (CompilerUsedV)
2925 setUsedInitializer(*CompilerUsedV, CompilerUsed);
2926 }
2927};
Alexander Kornienkof00654e2015-06-23 09:49:53 +00002928}
Rafael Espindola00752162013-05-09 17:22:59 +00002929
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002930static bool hasUseOtherThanLLVMUsed(GlobalAlias &GA, const LLVMUsed &U) {
2931 if (GA.use_empty()) // No use at all.
2932 return false;
2933
2934 assert((!U.usedCount(&GA) || !U.compilerUsedCount(&GA)) &&
2935 "We should have removed the duplicated "
Rafael Espindola9aadcc42013-07-19 18:44:51 +00002936 "element from llvm.compiler.used");
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002937 if (!GA.hasOneUse())
2938 // Strictly more than one use. So at least one is not in llvm.used and
Rafael Espindola9aadcc42013-07-19 18:44:51 +00002939 // llvm.compiler.used.
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002940 return true;
2941
Rafael Espindola9aadcc42013-07-19 18:44:51 +00002942 // Exactly one use. Check if it is in llvm.used or llvm.compiler.used.
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002943 return !U.usedCount(&GA) && !U.compilerUsedCount(&GA);
Rafael Espindola00752162013-05-09 17:22:59 +00002944}
2945
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002946static bool hasMoreThanOneUseOtherThanLLVMUsed(GlobalValue &V,
2947 const LLVMUsed &U) {
2948 unsigned N = 2;
2949 assert((!U.usedCount(&V) || !U.compilerUsedCount(&V)) &&
2950 "We should have removed the duplicated "
Rafael Espindola9aadcc42013-07-19 18:44:51 +00002951 "element from llvm.compiler.used");
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002952 if (U.usedCount(&V) || U.compilerUsedCount(&V))
2953 ++N;
2954 return V.hasNUsesOrMore(N);
2955}
2956
2957static bool mayHaveOtherReferences(GlobalAlias &GA, const LLVMUsed &U) {
2958 if (!GA.hasLocalLinkage())
2959 return true;
2960
2961 return U.usedCount(&GA) || U.compilerUsedCount(&GA);
2962}
2963
Craig Topper71b7b682014-08-21 05:55:13 +00002964static bool hasUsesToReplace(GlobalAlias &GA, const LLVMUsed &U,
2965 bool &RenameTarget) {
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002966 RenameTarget = false;
Rafael Espindola00752162013-05-09 17:22:59 +00002967 bool Ret = false;
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002968 if (hasUseOtherThanLLVMUsed(GA, U))
Rafael Espindola00752162013-05-09 17:22:59 +00002969 Ret = true;
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002970
2971 // If the alias is externally visible, we may still be able to simplify it.
2972 if (!mayHaveOtherReferences(GA, U))
2973 return Ret;
2974
2975 // If the aliasee has internal linkage, give it the name and linkage
2976 // of the alias, and delete the alias. This turns:
2977 // define internal ... @f(...)
2978 // @a = alias ... @f
2979 // into:
2980 // define ... @a(...)
2981 Constant *Aliasee = GA.getAliasee();
2982 GlobalValue *Target = cast<GlobalValue>(Aliasee->stripPointerCasts());
2983 if (!Target->hasLocalLinkage())
2984 return Ret;
2985
2986 // Do not perform the transform if multiple aliases potentially target the
2987 // aliasee. This check also ensures that it is safe to replace the section
2988 // and other attributes of the aliasee with those of the alias.
2989 if (hasMoreThanOneUseOtherThanLLVMUsed(*Target, U))
2990 return Ret;
2991
2992 RenameTarget = true;
2993 return true;
Rafael Espindola00752162013-05-09 17:22:59 +00002994}
2995
Duncan Sandsed722832009-03-06 10:21:56 +00002996bool GlobalOpt::OptimizeGlobalAliases(Module &M) {
Anton Korobeynikova9b60ee2008-09-09 19:04:59 +00002997 bool Changed = false;
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002998 LLVMUsed Used(M);
2999
Craig Topper46276792014-08-24 23:23:06 +00003000 for (GlobalValue *GV : Used.used())
3001 Used.compilerUsedErase(GV);
Anton Korobeynikova9b60ee2008-09-09 19:04:59 +00003002
Duncan Sands0bcf0852009-01-07 20:01:06 +00003003 for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end();
Duncan Sandsb3f27882009-02-15 09:56:08 +00003004 I != E;) {
3005 Module::alias_iterator J = I++;
Duncan Sandsed722832009-03-06 10:21:56 +00003006 // Aliases without names cannot be referenced outside this module.
David Majnemer5c921152014-07-01 15:26:50 +00003007 if (!J->hasName() && !J->isDeclaration() && !J->hasLocalLinkage())
Duncan Sandsed722832009-03-06 10:21:56 +00003008 J->setLinkage(GlobalValue::InternalLinkage);
Duncan Sandsb3f27882009-02-15 09:56:08 +00003009 // If the aliasee may change at link time, nothing can be done - bail out.
3010 if (J->mayBeOverridden())
Anton Korobeynikova9b60ee2008-09-09 19:04:59 +00003011 continue;
3012
Duncan Sandsb3f27882009-02-15 09:56:08 +00003013 Constant *Aliasee = J->getAliasee();
David Majnemer0e2cc2a2014-07-01 00:30:56 +00003014 GlobalValue *Target = dyn_cast<GlobalValue>(Aliasee->stripPointerCasts());
3015 // We can't trivially replace the alias with the aliasee if the aliasee is
3016 // non-trivial in some way.
3017 // TODO: Try to handle non-zero GEPs of local aliasees.
3018 if (!Target)
3019 continue;
Duncan Sands7a1db332009-02-18 17:55:38 +00003020 Target->removeDeadConstantUsers();
Duncan Sandsb3f27882009-02-15 09:56:08 +00003021
3022 // Make all users of the alias use the aliasee instead.
Rafael Espindolaa82555c2013-06-11 17:48:06 +00003023 bool RenameTarget;
3024 if (!hasUsesToReplace(*J, Used, RenameTarget))
Rafael Espindola00752162013-05-09 17:22:59 +00003025 continue;
Duncan Sandsb3f27882009-02-15 09:56:08 +00003026
Rafael Espindola6b238632014-05-16 19:35:39 +00003027 J->replaceAllUsesWith(ConstantExpr::getBitCast(Aliasee, J->getType()));
Rafael Espindolaa82555c2013-06-11 17:48:06 +00003028 ++NumAliasesResolved;
3029 Changed = true;
Duncan Sandsb3f27882009-02-15 09:56:08 +00003030
Rafael Espindolaa82555c2013-06-11 17:48:06 +00003031 if (RenameTarget) {
Duncan Sands6a3df7b2009-12-08 10:10:20 +00003032 // Give the aliasee the name, linkage and other attributes of the alias.
Duncan P. N. Exon Smith17323402015-10-13 17:51:03 +00003033 Target->takeName(&*J);
Duncan Sands6a3df7b2009-12-08 10:10:20 +00003034 Target->setLinkage(J->getLinkage());
Reid Kleckner22b19da2014-02-13 02:18:36 +00003035 Target->setVisibility(J->getVisibility());
3036 Target->setDLLStorageClass(J->getDLLStorageClass());
Rafael Espindolaa82555c2013-06-11 17:48:06 +00003037
Duncan P. N. Exon Smith17323402015-10-13 17:51:03 +00003038 if (Used.usedErase(&*J))
Rafael Espindolaa82555c2013-06-11 17:48:06 +00003039 Used.usedInsert(Target);
3040
Duncan P. N. Exon Smith17323402015-10-13 17:51:03 +00003041 if (Used.compilerUsedErase(&*J))
Rafael Espindolaa82555c2013-06-11 17:48:06 +00003042 Used.compilerUsedInsert(Target);
Rafael Espindola8d304802013-06-12 16:45:47 +00003043 } else if (mayHaveOtherReferences(*J, Used))
Rafael Espindolaa82555c2013-06-11 17:48:06 +00003044 continue;
3045
Duncan Sandsb3f27882009-02-15 09:56:08 +00003046 // Delete the alias.
3047 M.getAliasList().erase(J);
3048 ++NumAliasesRemoved;
3049 Changed = true;
Anton Korobeynikova9b60ee2008-09-09 19:04:59 +00003050 }
3051
Rafael Espindolaa82555c2013-06-11 17:48:06 +00003052 Used.syncVariablesAndSets();
3053
Anton Korobeynikova9b60ee2008-09-09 19:04:59 +00003054 return Changed;
3055}
Chris Lattner41b6a5a2005-09-26 01:43:45 +00003056
Nick Lewycky4b273cb2012-02-12 02:15:20 +00003057static Function *FindCXAAtExit(Module &M, TargetLibraryInfo *TLI) {
3058 if (!TLI->has(LibFunc::cxa_atexit))
Craig Topperf40110f2014-04-25 05:29:35 +00003059 return nullptr;
Nick Lewycky4b273cb2012-02-12 02:15:20 +00003060
3061 Function *Fn = M.getFunction(TLI->getName(LibFunc::cxa_atexit));
Jakub Staszak9525a772012-12-06 21:57:16 +00003062
Anders Carlssonee6bc702011-03-20 17:59:11 +00003063 if (!Fn)
Craig Topperf40110f2014-04-25 05:29:35 +00003064 return nullptr;
Nick Lewycky4b273cb2012-02-12 02:15:20 +00003065
Chris Lattner229907c2011-07-18 04:54:35 +00003066 FunctionType *FTy = Fn->getFunctionType();
Jakub Staszak9525a772012-12-06 21:57:16 +00003067
3068 // Checking that the function has the right return type, the right number of
Anders Carlsson48a44912011-03-20 19:51:13 +00003069 // parameters and that they all have pointer types should be enough.
3070 if (!FTy->getReturnType()->isIntegerTy() ||
3071 FTy->getNumParams() != 3 ||
Anders Carlssonee6bc702011-03-20 17:59:11 +00003072 !FTy->getParamType(0)->isPointerTy() ||
3073 !FTy->getParamType(1)->isPointerTy() ||
3074 !FTy->getParamType(2)->isPointerTy())
Craig Topperf40110f2014-04-25 05:29:35 +00003075 return nullptr;
Anders Carlssonee6bc702011-03-20 17:59:11 +00003076
3077 return Fn;
3078}
3079
James Molloyea31ad32015-11-13 11:05:07 +00003080/// Returns whether the given function is an empty C++ destructor and can
3081/// therefore be eliminated.
Anders Carlssonee6bc702011-03-20 17:59:11 +00003082/// Note that we assume that other optimization passes have already simplified
3083/// the code so we only look for a function with a single basic block, where
Benjamin Kramer1a4695a2012-02-09 16:28:15 +00003084/// the only allowed instructions are 'ret', 'call' to an empty C++ dtor and
3085/// other side-effect free instructions.
Anders Carlssonfcec2f52011-03-20 20:16:43 +00003086static bool cxxDtorIsEmpty(const Function &Fn,
3087 SmallPtrSet<const Function *, 8> &CalledFunctions) {
Anders Carlsson48a44912011-03-20 19:51:13 +00003088 // FIXME: We could eliminate C++ destructors if they're readonly/readnone and
Nick Lewyckyd0781832011-03-21 02:26:01 +00003089 // nounwind, but that doesn't seem worth doing.
Anders Carlsson48a44912011-03-20 19:51:13 +00003090 if (Fn.isDeclaration())
3091 return false;
Anders Carlssonee6bc702011-03-20 17:59:11 +00003092
3093 if (++Fn.begin() != Fn.end())
3094 return false;
3095
3096 const BasicBlock &EntryBlock = Fn.getEntryBlock();
3097 for (BasicBlock::const_iterator I = EntryBlock.begin(), E = EntryBlock.end();
3098 I != E; ++I) {
3099 if (const CallInst *CI = dyn_cast<CallInst>(I)) {
Anders Carlsson4dd420f2011-03-21 14:54:40 +00003100 // Ignore debug intrinsics.
3101 if (isa<DbgInfoIntrinsic>(CI))
3102 continue;
3103
Anders Carlssonee6bc702011-03-20 17:59:11 +00003104 const Function *CalledFn = CI->getCalledFunction();
3105
3106 if (!CalledFn)
3107 return false;
3108
Anders Carlsson1cc80732011-03-22 03:21:01 +00003109 SmallPtrSet<const Function *, 8> NewCalledFunctions(CalledFunctions);
3110
Anders Carlsson48a44912011-03-20 19:51:13 +00003111 // Don't treat recursive functions as empty.
David Blaikie70573dc2014-11-19 07:49:26 +00003112 if (!NewCalledFunctions.insert(CalledFn).second)
Anders Carlsson48a44912011-03-20 19:51:13 +00003113 return false;
3114
Anders Carlsson1cc80732011-03-22 03:21:01 +00003115 if (!cxxDtorIsEmpty(*CalledFn, NewCalledFunctions))
Anders Carlssonee6bc702011-03-20 17:59:11 +00003116 return false;
3117 } else if (isa<ReturnInst>(*I))
Benjamin Kramer487a3962012-02-09 14:26:06 +00003118 return true; // We're done.
3119 else if (I->mayHaveSideEffects())
3120 return false; // Destructor with side effects, bail.
Anders Carlssonee6bc702011-03-20 17:59:11 +00003121 }
3122
3123 return false;
3124}
3125
3126bool GlobalOpt::OptimizeEmptyGlobalCXXDtors(Function *CXAAtExitFn) {
3127 /// Itanium C++ ABI p3.3.5:
3128 ///
3129 /// After constructing a global (or local static) object, that will require
3130 /// destruction on exit, a termination function is registered as follows:
3131 ///
3132 /// extern "C" int __cxa_atexit ( void (*f)(void *), void *p, void *d );
3133 ///
3134 /// This registration, e.g. __cxa_atexit(f,p,d), is intended to cause the
3135 /// call f(p) when DSO d is unloaded, before all such termination calls
3136 /// registered before this one. It returns zero if registration is
Nick Lewyckyd0781832011-03-21 02:26:01 +00003137 /// successful, nonzero on failure.
Anders Carlssonee6bc702011-03-20 17:59:11 +00003138
3139 // This pass will look for calls to __cxa_atexit where the function is trivial
3140 // and remove them.
3141 bool Changed = false;
3142
Chandler Carruthcdf47882014-03-09 03:16:01 +00003143 for (auto I = CXAAtExitFn->user_begin(), E = CXAAtExitFn->user_end();
3144 I != E;) {
Anders Carlsson336fd902011-03-20 20:21:33 +00003145 // We're only interested in calls. Theoretically, we could handle invoke
3146 // instructions as well, but neither llvm-gcc nor clang generate invokes
3147 // to __cxa_atexit.
Anders Carlsson4dd420f2011-03-21 14:54:40 +00003148 CallInst *CI = dyn_cast<CallInst>(*I++);
3149 if (!CI)
Anders Carlsson336fd902011-03-20 20:21:33 +00003150 continue;
3151
Jakub Staszak9525a772012-12-06 21:57:16 +00003152 Function *DtorFn =
Anders Carlsson4dd420f2011-03-21 14:54:40 +00003153 dyn_cast<Function>(CI->getArgOperand(0)->stripPointerCasts());
Anders Carlssonee6bc702011-03-20 17:59:11 +00003154 if (!DtorFn)
3155 continue;
3156
Anders Carlssonfcec2f52011-03-20 20:16:43 +00003157 SmallPtrSet<const Function *, 8> CalledFunctions;
3158 if (!cxxDtorIsEmpty(*DtorFn, CalledFunctions))
Anders Carlssonee6bc702011-03-20 17:59:11 +00003159 continue;
3160
3161 // Just remove the call.
Anders Carlsson4dd420f2011-03-21 14:54:40 +00003162 CI->replaceAllUsesWith(Constant::getNullValue(CI->getType()));
3163 CI->eraseFromParent();
Anders Carlsson48a44912011-03-20 19:51:13 +00003164
Anders Carlssonee6bc702011-03-20 17:59:11 +00003165 ++NumCXXDtorsRemoved;
3166
3167 Changed |= true;
3168 }
3169
3170 return Changed;
3171}
3172
Chris Lattner25db5802004-10-07 04:16:33 +00003173bool GlobalOpt::runOnModule(Module &M) {
3174 bool Changed = false;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00003175
Mehdi Amini46a43552015-03-04 18:43:29 +00003176 auto &DL = M.getDataLayout();
Chandler Carruthb98f63d2015-01-15 10:41:28 +00003177 TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Nick Lewyckycf6aae62012-02-12 01:13:18 +00003178
Chris Lattner25db5802004-10-07 04:16:33 +00003179 bool LocalChange = true;
3180 while (LocalChange) {
3181 LocalChange = false;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00003182
David Majnemer1b3b70e2014-10-08 07:23:31 +00003183 NotDiscardableComdats.clear();
3184 for (const GlobalVariable &GV : M.globals())
3185 if (const Comdat *C = GV.getComdat())
3186 if (!GV.isDiscardableIfUnused() || !GV.use_empty())
3187 NotDiscardableComdats.insert(C);
3188 for (Function &F : M)
3189 if (const Comdat *C = F.getComdat())
3190 if (!F.isDefTriviallyDead())
3191 NotDiscardableComdats.insert(C);
3192 for (GlobalAlias &GA : M.aliases())
3193 if (const Comdat *C = GA.getComdat())
3194 if (!GA.isDiscardableIfUnused() || !GA.use_empty())
3195 NotDiscardableComdats.insert(C);
3196
Chris Lattner41b6a5a2005-09-26 01:43:45 +00003197 // Delete functions that are trivially dead, ccc -> fastcc
3198 LocalChange |= OptimizeFunctions(M);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00003199
Chris Lattner41b6a5a2005-09-26 01:43:45 +00003200 // Optimize global_ctors list.
Richard Smithc167d652014-05-06 01:44:26 +00003201 LocalChange |= optimizeGlobalCtorsList(M, [&](Function *F) {
3202 return EvaluateStaticConstructor(F, DL, TLI);
3203 });
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00003204
Chris Lattner41b6a5a2005-09-26 01:43:45 +00003205 // Optimize non-address-taken globals.
3206 LocalChange |= OptimizeGlobalVars(M);
Anton Korobeynikova9b60ee2008-09-09 19:04:59 +00003207
3208 // Resolve aliases, when possible.
Duncan Sandsed722832009-03-06 10:21:56 +00003209 LocalChange |= OptimizeGlobalAliases(M);
Anders Carlssonee6bc702011-03-20 17:59:11 +00003210
Manman Renb3c52fb2013-05-14 21:52:44 +00003211 // Try to remove trivial global destructors if they are not removed
3212 // already.
3213 Function *CXAAtExitFn = FindCXAAtExit(M, TLI);
Anders Carlssonee6bc702011-03-20 17:59:11 +00003214 if (CXAAtExitFn)
3215 LocalChange |= OptimizeEmptyGlobalCXXDtors(CXAAtExitFn);
3216
Anton Korobeynikova9b60ee2008-09-09 19:04:59 +00003217 Changed |= LocalChange;
Chris Lattner25db5802004-10-07 04:16:33 +00003218 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00003219
Chris Lattner41b6a5a2005-09-26 01:43:45 +00003220 // TODO: Move all global ctors functions to the end of the module for code
3221 // layout.
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00003222
Chris Lattner25db5802004-10-07 04:16:33 +00003223 return Changed;
3224}
Anthony Pescha2d93692015-07-22 18:50:10 +00003225